ONOS-2184 - Initial implementation of Virtual network Intent service.

Change-Id: I03103b4eca797cd32480fbd0e3b4cf0385b50ef2
diff --git a/core/net/BUCK b/core/net/BUCK
index 7070fb7..fa93865 100644
--- a/core/net/BUCK
+++ b/core/net/BUCK
@@ -1,9 +1,13 @@
 COMPILE_DEPS = [
     '//lib:CORE_DEPS',
     '//incubator/api:onos-incubator-api',
+    '//utils/rest:onlab-rest',
+    '//incubator/net:onos-incubator-net',
+    '//incubator/store:onos-incubator-store',
 ]
 
 TEST_DEPS = [
+    '//lib:TEST_REST',
     '//lib:TEST_ADAPTERS',
     '//core/common:onos-core-common',
     '//core/store/dist:onos-core-dist',
diff --git a/core/net/pom.xml b/core/net/pom.xml
index eb6f1b7..1d3650b 100644
--- a/core/net/pom.xml
+++ b/core/net/pom.xml
@@ -93,6 +93,14 @@
 
         <dependency>
             <groupId>org.onosproject</groupId>
+            <artifactId>onlab-osgi</artifactId>
+            <version>${project.version}</version>
+            <classifier>tests</classifier>
+            <scope>test</scope>
+        </dependency>
+
+        <dependency>
+            <groupId>org.onosproject</groupId>
             <artifactId>onos-incubator-api</artifactId>
         </dependency>
 
@@ -110,6 +118,17 @@
             <groupId>org.apache.felix</groupId>
             <artifactId>org.apache.felix.scr</artifactId>
         </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-incubator-store</artifactId>
+            <version>${project.version}</version>
+            <scope>test</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.onosproject</groupId>
+            <artifactId>onos-incubator-net</artifactId>
+            <version>${project.version}</version>
+        </dependency>
     </dependencies>
 
 </project>
diff --git a/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompiler.java b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompiler.java
new file mode 100644
index 0000000..04f42e5
--- /dev/null
+++ b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompiler.java
@@ -0,0 +1,189 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.net.intent.impl.compiler;
+
+import org.apache.felix.scr.annotations.Activate;
+import org.apache.felix.scr.annotations.Component;
+import org.apache.felix.scr.annotations.Deactivate;
+import org.apache.felix.scr.annotations.Reference;
+import org.apache.felix.scr.annotations.ReferenceCardinality;
+import org.onlab.osgi.DefaultServiceDirectory;
+import org.onlab.osgi.ServiceDirectory;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.incubator.net.tunnel.TunnelId;
+import org.onosproject.incubator.net.virtual.NetworkId;
+import org.onosproject.incubator.net.virtual.VirtualNetworkIntent;
+import org.onosproject.incubator.net.virtual.VirtualNetworkService;
+import org.onosproject.incubator.net.virtual.VirtualNetworkStore;
+import org.onosproject.incubator.net.virtual.VirtualPort;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.EncapsulationType;
+import org.onosproject.net.Link;
+import org.onosproject.net.Path;
+import org.onosproject.net.intent.Constraint;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentService;
+import org.onosproject.net.intent.Key;
+import org.onosproject.net.intent.PointToPointIntent;
+import org.onosproject.net.intent.constraint.EncapsulationConstraint;
+import org.onosproject.net.intent.impl.IntentCompilationException;
+import org.onosproject.net.topology.TopologyService;
+import org.slf4j.Logger;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+import java.util.Set;
+
+import static org.slf4j.LoggerFactory.getLogger;
+
+/**
+ * An intent compiler for {@link org.onosproject.incubator.net.virtual.VirtualNetworkIntent}.
+ */
+@Component(immediate = true)
+public class VirtualNetworkIntentCompiler
+        extends ConnectivityIntentCompiler<VirtualNetworkIntent> {
+
+    private final Logger log = getLogger(getClass());
+
+    private static final String NETWORK_ID = "networkId=";
+    protected static final String KEY_FORMAT = "{" + NETWORK_ID + "%s, src=%s, dst=%s}";
+
+    protected ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected VirtualNetworkService manager;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected IntentService intentService;
+
+    @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+    protected VirtualNetworkStore store;
+
+
+    @Activate
+    public void activate() {
+        intentManager.registerCompiler(VirtualNetworkIntent.class, this);
+    }
+
+    @Deactivate
+    public void deactivate() {
+        intentManager.unregisterCompiler(VirtualNetworkIntent.class);
+    }
+
+    @Override
+    public List<Intent> compile(VirtualNetworkIntent intent, List<Intent> installable) {
+
+        log.debug("Compiling intent: " + intent);
+        List<Intent> intents = new ArrayList<>();
+        Optional<Path> path = getPaths(intent).stream()
+                .findFirst();
+        if (path != null && path.isPresent()) {
+            path.get().links().forEach(link -> {
+                Intent physicalIntent = createPtPtIntent(intent, link);
+                intents.add(physicalIntent);
+
+                // store the virtual intent to physical intent tunnelId mapping
+                store.addTunnelId(intent, TunnelId.valueOf(physicalIntent.key().toString()));
+            });
+        } else {
+            throw new IntentCompilationException("Unable to find a path for intent " + intent);
+        }
+
+        return intents;
+    }
+
+    /**
+     * Returns the paths for the virtual network intent.
+     *
+     * @param intent virtual network intent
+     * @return set of paths
+     */
+    private Set<Path> getPaths(VirtualNetworkIntent intent) {
+
+        TopologyService topologyService = manager.get(intent.networkId(), TopologyService.class);
+        if (topologyService == null) {
+            throw new IntentCompilationException("topologyService is null");
+        }
+        return topologyService.getPaths(topologyService.currentTopology(),
+                                        intent.ingressPoint().deviceId(), intent.egressPoint().deviceId());
+    }
+
+    /**
+     * Encodes the key using the network identifier, application identifer, source and destination
+     * connect points.
+     *
+     * @param networkId     virtual network identifier
+     * @param applicationId application identifier
+     * @param src           source connect point
+     * @param dst           destination connect point
+     * @return encoded key
+     */
+    private static Key encodeKey(NetworkId networkId, ApplicationId applicationId, ConnectPoint src, ConnectPoint dst) {
+        String key = String.format(KEY_FORMAT, networkId, src, dst);
+        return Key.of(key, applicationId);
+    }
+
+    /**
+     * Creates a point-to-point intent from the virtual network intent and virtual link.
+     *
+     * @param intent virtual network intent
+     * @param link   virtual link
+     * @return point to point intent
+     */
+    private Intent createPtPtIntent(VirtualNetworkIntent intent, Link link) {
+        ConnectPoint ingressPoint = mapVirtualToPhysicalPort(intent.networkId(), link.src());
+        ConnectPoint egressPoint = mapVirtualToPhysicalPort(intent.networkId(), link.dst());
+        Key intentKey = encodeKey(intent.networkId(), intent.appId(), ingressPoint, egressPoint);
+
+        List<Constraint> constraints = new ArrayList<>();
+        constraints.add(new EncapsulationConstraint(EncapsulationType.VLAN));
+
+        // TODO Currently there can only be one intent between the ingress and egress across
+        // all virtual networks. We may want to support multiple intents between the same src/dst pairs.
+        PointToPointIntent physicalIntent = PointToPointIntent.builder()
+                .key(intentKey)
+                .appId(intent.appId())
+                .ingressPoint(ingressPoint)
+                .egressPoint(egressPoint)
+                .constraints(constraints)
+                .build();
+        log.debug("Submitting physical intent: " + physicalIntent);
+        intentService.submit(physicalIntent);
+
+        return physicalIntent;
+    }
+
+    /**
+     * Maps the virtual connect point to a physical connect point.
+     *
+     * @param networkId virtual network identifier
+     * @param virtualCp virtual connect point
+     * @return physical connect point
+     */
+    private ConnectPoint mapVirtualToPhysicalPort(NetworkId networkId, ConnectPoint virtualCp) {
+        Set<VirtualPort> ports = manager.getVirtualPorts(networkId, virtualCp.deviceId());
+        for (VirtualPort port : ports) {
+            if (port.element().id().equals(virtualCp.elementId()) &&
+                    port.number().equals(virtualCp.port())) {
+                return new ConnectPoint(port.realizedBy().element().id(), port.realizedBy().number());
+            }
+        }
+        return null;
+    }
+}
+
diff --git a/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompilerTest.java b/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompilerTest.java
new file mode 100644
index 0000000..137d2e0
--- /dev/null
+++ b/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/VirtualNetworkIntentCompilerTest.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright 2016-present Open Networking Laboratory
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.onosproject.net.intent.impl.compiler;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.osgi.ServiceDirectory;
+import org.onlab.osgi.TestServiceDirectory;
+import org.onlab.rest.BaseResource;
+import org.onosproject.TestApplicationId;
+import org.onosproject.common.event.impl.TestEventDispatcher;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.IdGenerator;
+import org.onosproject.incubator.net.virtual.TenantId;
+import org.onosproject.incubator.net.virtual.VirtualDevice;
+import org.onosproject.incubator.net.virtual.VirtualLink;
+import org.onosproject.incubator.net.virtual.VirtualNetwork;
+import org.onosproject.incubator.net.virtual.VirtualNetworkIntent;
+import org.onosproject.incubator.net.virtual.VirtualNetworkService;
+import org.onosproject.incubator.net.virtual.VirtualNetworkStore;
+import org.onosproject.incubator.net.virtual.impl.VirtualNetworkManager;
+import org.onosproject.incubator.store.virtual.impl.DistributedVirtualNetworkStore;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DefaultPort;
+import org.onosproject.net.EncapsulationType;
+import org.onosproject.net.Link;
+import org.onosproject.net.NetTestTools;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.TestDeviceParams;
+import org.onosproject.net.intent.Constraint;
+import org.onosproject.net.intent.FakeIntentManager;
+import org.onosproject.net.intent.Intent;
+import org.onosproject.net.intent.IntentExtensionService;
+import org.onosproject.net.intent.IntentService;
+import org.onosproject.net.intent.Key;
+import org.onosproject.net.intent.MockIdGenerator;
+import org.onosproject.net.intent.TestableIntentService;
+import org.onosproject.net.intent.constraint.EncapsulationConstraint;
+import org.onosproject.store.service.TestStorageService;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.atomic.AtomicLong;
+
+import static org.junit.Assert.assertEquals;
+import static org.onlab.junit.TestUtils.TestUtilsException;
+import static org.onlab.junit.TestUtils.setField;
+
+/**
+ * Junit tests for virtual network intent compiler.
+ */
+public class VirtualNetworkIntentCompilerTest extends TestDeviceParams {
+
+    private CoreService coreService;
+    private TestableIntentService intentService = new FakeIntentManager();
+    private IntentExtensionService intentExtensionService;
+    private final IdGenerator idGenerator = new MockIdGenerator();
+    private VirtualNetworkIntentCompiler compiler;
+    private VirtualNetworkManager manager;
+    private DistributedVirtualNetworkStore virtualNetworkManagerStore;
+    private ServiceDirectory testDirectory;
+
+    private final String tenantIdValue1 = "TENANT_ID1";
+    private static final ApplicationId APP_ID =
+            new TestApplicationId("test");
+
+    private ConnectPoint cp1;
+    private ConnectPoint cp2;
+    private ConnectPoint cp3;
+    private ConnectPoint cp4;
+    private ConnectPoint cp5;
+    private ConnectPoint cp6;
+    private VirtualLink link1;
+    private VirtualLink link2;
+    private VirtualLink link3;
+    private VirtualLink link4;
+    private VirtualLink link5;
+    private VirtualLink link6;
+
+    @Before
+    public void setUp() throws TestUtilsException {
+        virtualNetworkManagerStore = new DistributedVirtualNetworkStore();
+
+        coreService = new TestCoreService();
+
+        Intent.unbindIdGenerator(idGenerator);
+        Intent.bindIdGenerator(idGenerator);
+
+        virtualNetworkManagerStore.setCoreService(coreService);
+        setField(coreService, "coreService", new TestCoreService());
+        setField(virtualNetworkManagerStore, "storageService", new TestStorageService());
+        virtualNetworkManagerStore.activate();
+
+        manager = new VirtualNetworkManager();
+        manager.setStore(virtualNetworkManagerStore);
+        manager.setIntentService(intentService);
+        NetTestTools.injectEventDispatcher(manager, new TestEventDispatcher());
+        manager.activate();
+
+        // Register a compiler and an installer both setup for success.
+        intentExtensionService = intentService;
+
+        testDirectory = new TestServiceDirectory()
+                .add(VirtualNetworkService.class, manager)
+                .add(VirtualNetworkStore.class, virtualNetworkManagerStore)
+                .add(IntentService.class, intentService);
+        BaseResource.setServiceDirectory(testDirectory);
+
+        compiler = new VirtualNetworkIntentCompiler();
+        compiler.manager = manager;
+        compiler.intentService = intentService;
+        compiler.store = virtualNetworkManagerStore;
+        compiler.intentManager = intentExtensionService;
+        compiler.serviceDirectory = testDirectory;
+    }
+
+    @After
+    public void tearDown() {
+        Intent.unbindIdGenerator(idGenerator);
+        manager.deactivate();
+    }
+
+    /**
+     * Method to create the virtual network for further testing.
+     *
+     * @return virtual network
+     */
+    private VirtualNetwork setupVirtualNetworkTopology() {
+        manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
+        VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
+        VirtualDevice virtualDevice1 =
+                manager.createVirtualDevice(virtualNetwork.id(), DID1);
+        VirtualDevice virtualDevice2 =
+                manager.createVirtualDevice(virtualNetwork.id(), DID2);
+        VirtualDevice virtualDevice3 =
+                manager.createVirtualDevice(virtualNetwork.id(), DID3);
+        VirtualDevice virtualDevice4 =
+                manager.createVirtualDevice(virtualNetwork.id(), DID4);
+
+        Port port1 = new DefaultPort(virtualDevice1, PortNumber.portNumber(1), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice1.id(), port1.number(), port1);
+        cp1 = new ConnectPoint(virtualDevice1.id(), port1.number());
+
+        Port port2 = new DefaultPort(virtualDevice1, PortNumber.portNumber(2), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice1.id(), port2.number(), port2);
+        cp2 = new ConnectPoint(virtualDevice1.id(), port2.number());
+
+        Port port3 = new DefaultPort(virtualDevice2, PortNumber.portNumber(3), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice2.id(), port3.number(), port3);
+        cp3 = new ConnectPoint(virtualDevice2.id(), port3.number());
+
+        Port port4 = new DefaultPort(virtualDevice2, PortNumber.portNumber(4), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice2.id(), port4.number(), port4);
+        cp4 = new ConnectPoint(virtualDevice2.id(), port4.number());
+
+        Port port5 = new DefaultPort(virtualDevice3, PortNumber.portNumber(5), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice3.id(), port5.number(), port5);
+        cp5 = new ConnectPoint(virtualDevice3.id(), port5.number());
+
+        Port port6 = new DefaultPort(virtualDevice3, PortNumber.portNumber(6), true);
+        manager.createVirtualPort(virtualNetwork.id(), virtualDevice3.id(), port6.number(), port6);
+        cp6 = new ConnectPoint(virtualDevice3.id(), port6.number());
+
+        link1 = manager.createVirtualLink(virtualNetwork.id(), cp1, cp3);
+        virtualNetworkManagerStore.updateLink(link1, link1.tunnelId(), Link.State.ACTIVE);
+        link2 = manager.createVirtualLink(virtualNetwork.id(), cp3, cp1);
+        virtualNetworkManagerStore.updateLink(link2, link2.tunnelId(), Link.State.ACTIVE);
+        link3 = manager.createVirtualLink(virtualNetwork.id(), cp4, cp5);
+        virtualNetworkManagerStore.updateLink(link3, link3.tunnelId(), Link.State.ACTIVE);
+        link4 = manager.createVirtualLink(virtualNetwork.id(), cp5, cp4);
+        virtualNetworkManagerStore.updateLink(link4, link4.tunnelId(), Link.State.ACTIVE);
+
+        return virtualNetwork;
+    }
+
+    @Test
+    public void testCompiler() {
+        compiler.activate();
+        VirtualNetwork virtualNetwork = setupVirtualNetworkTopology();
+
+        Key intentKey = Key.of("test", APP_ID);
+
+        List<Constraint> constraints = new ArrayList<>();
+        constraints.add(new EncapsulationConstraint(EncapsulationType.VLAN));
+
+        VirtualNetworkIntent virtualIntent = VirtualNetworkIntent.builder()
+                .networkId(virtualNetwork.id())
+                .key(intentKey)
+                .appId(APP_ID)
+                .ingressPoint(cp1)
+                .egressPoint(cp5)
+                .constraints(constraints)
+                .build();
+
+        List<Intent> compiled = compiler.compile(virtualIntent, Collections.emptyList());
+        assertEquals("The virtual intents size is not as expected.", 2, compiled.size());
+
+        compiler.deactivate();
+    }
+
+
+    /**
+     * Core service test class.
+     */
+    private class TestCoreService extends CoreServiceAdapter {
+
+        @Override
+        public IdGenerator getIdGenerator(String topic) {
+            return new IdGenerator() {
+                private AtomicLong counter = new AtomicLong(0);
+
+                @Override
+                public long getNewId() {
+                    return counter.getAndIncrement();
+                }
+            };
+        }
+    }
+
+}