Added suggest path to PointToPointIntent

Change-Id: Ie8ae3af6bd97af3628334d37482e63196d15b094
diff --git a/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/ConnectivityIntentCompiler.java b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/ConnectivityIntentCompiler.java
index a8ab9fa..6ae262c 100644
--- a/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/ConnectivityIntentCompiler.java
+++ b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/ConnectivityIntentCompiler.java
@@ -163,6 +163,28 @@
     }
 
     /**
+     * Computes all the paths between two ConnectPoints.
+     *
+     * @param intent intent on which behalf path is being computed
+     * @param one    start of the path
+     * @param two    end of the path
+     * @return Paths between the two, or null if no path can be found
+     */
+    protected List<Path> getPaths(ConnectivityIntent intent,
+                           ElementId one, ElementId two) {
+        Set<Path> paths = pathService.getPaths(one, two, weigher(intent.constraints()));
+        final List<Constraint> constraints = intent.constraints();
+        ImmutableList<Path> filtered = FluentIterable.from(paths)
+                .filter(path -> checkPath(path, constraints))
+                .toList();
+        if (filtered.isEmpty()) {
+            return null;
+        }
+
+        return filtered;
+    }
+
+    /**
      * Computes a disjoint path between two ConnectPoints.
      *
      * @param intent intent on which behalf path is being computed
diff --git a/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompiler.java b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompiler.java
index acdaddd..759202f 100644
--- a/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompiler.java
+++ b/core/net/src/main/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompiler.java
@@ -16,6 +16,7 @@
 package org.onosproject.net.intent.impl.compiler;
 
 import com.google.common.collect.ImmutableSet;
+import org.apache.commons.lang3.tuple.Pair;
 import org.apache.felix.scr.annotations.Activate;
 import org.apache.felix.scr.annotations.Component;
 import org.apache.felix.scr.annotations.Deactivate;
@@ -75,6 +76,7 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.stream.Collectors;
+import java.util.stream.IntStream;
 import java.util.stream.Stream;
 
 import static java.util.Arrays.asList;
@@ -128,6 +130,18 @@
         ConnectPoint ingressPoint = intent.filteredIngressPoint().connectPoint();
         ConnectPoint egressPoint = intent.filteredEgressPoint().connectPoint();
 
+        //TODO: handle protected path case with suggested path!!
+        //Idea: use suggested path as primary and another path from path service as protection
+        if (intent.suggestedPath() != null && intent.suggestedPath().size() > 0) {
+            Path path = new DefaultPath(PID, intent.suggestedPath(), new ScalarWeight(1));
+            //Check intent constraints against suggested path and suggested path availability
+            if (checkPath(path, intent.constraints()) && pathAvailable(intent)) {
+                allocateIntentBandwidth(intent, path);
+                return asList(createLinkCollectionIntent(ImmutableSet.copyOf(intent.suggestedPath()),
+                                                         DEFAULT_COST, intent));
+            }
+        }
+
         if (ingressPoint.deviceId().equals(egressPoint.deviceId())) {
             return createZeroHopLinkCollectionIntent(intent);
         }
@@ -147,6 +161,21 @@
         }
     }
 
+    private void allocateIntentBandwidth(PointToPointIntent intent, Path path) {
+        ConnectPoint ingressCP = intent.filteredIngressPoint().connectPoint();
+        ConnectPoint egressCP = intent.filteredEgressPoint().connectPoint();
+
+        List<ConnectPoint> pathCPs =
+                path.links().stream()
+                        .flatMap(l -> Stream.of(l.src(), l.dst()))
+                        .collect(Collectors.toList());
+
+        pathCPs.add(ingressCP);
+        pathCPs.add(egressCP);
+
+        allocateBandwidth(intent, pathCPs);
+    }
+
     private List<Intent> createZeroHopIntent(ConnectPoint ingressPoint,
                                              ConnectPoint egressPoint,
                                              PointToPointIntent intent) {
@@ -165,18 +194,7 @@
                                        intent.filteredEgressPoint().connectPoint().deviceId());
 
         // Allocate bandwidth if a bandwidth constraint is set
-        ConnectPoint ingressCP = intent.filteredIngressPoint().connectPoint();
-        ConnectPoint egressCP = intent.filteredEgressPoint().connectPoint();
-
-        List<ConnectPoint> pathCPs =
-                path.links().stream()
-                            .flatMap(l -> Stream.of(l.src(), l.dst()))
-                            .collect(Collectors.toList());
-
-        pathCPs.add(ingressCP);
-        pathCPs.add(egressCP);
-
-        allocateBandwidth(intent, pathCPs);
+        allocateIntentBandwidth(intent, path);
 
         return asList(createLinkCollectionIntent(ImmutableSet.copyOf(path.links()),
                                                  path.cost(),
@@ -295,19 +313,7 @@
             return reusableIntents;
         } else {
             // Allocate bandwidth if a bandwidth constraint is set
-            ConnectPoint ingressCP = intent.filteredIngressPoint().connectPoint();
-            ConnectPoint egressCP = intent.filteredEgressPoint().connectPoint();
-
-            List<ConnectPoint> pathCPs =
-                    onlyPath.links().stream()
-                            .flatMap(l -> Stream.of(l.src(), l.dst()))
-                            .collect(Collectors.toList());
-
-            pathCPs.add(ingressCP);
-            pathCPs.add(egressCP);
-
-            // Allocate bandwidth if a bandwidth constraint is set
-            allocateBandwidth(intent, pathCPs);
+            allocateIntentBandwidth(intent, onlyPath);
 
             links.add(createEdgeLink(ingressPoint, true));
             links.addAll(onlyPath.links());
@@ -698,4 +704,47 @@
 
         groupService.addBucketsToGroup(src.deviceId(), groupKey, addBuckets, groupKey, intent.appId());
     }
+
+    /**
+     * Checks suggested path availability.
+     * It checks:
+     * - single links availability;
+     * - that first and last device of the path are coherent with ingress and egress devices;
+     * - links contiguity.
+     *
+     * @param intent    Intent with suggested path to check
+     * @return true if the suggested path is available
+     */
+    private boolean pathAvailable(PointToPointIntent intent) {
+        // Check links availability
+        List<Link> suggestedPath = intent.suggestedPath();
+        for (Link link : suggestedPath) {
+            if (!(link instanceof EdgeLink) && !linkService.getLinks(link.src()).contains(link)) {
+                return false;
+            }
+        }
+
+        //Check that first and last device of the path are intent ingress and egress devices
+        if (!suggestedPath.get(0).src()
+                .deviceId().equals(intent.filteredIngressPoint().connectPoint().deviceId())) {
+            return false;
+        }
+        if (!suggestedPath.get(suggestedPath.size() - 1).dst()
+                .deviceId().equals(intent.filteredEgressPoint().connectPoint().deviceId())) {
+            return false;
+        }
+
+        // Check contiguity
+        List<Pair<Link, Link>> linkPairs = IntStream.
+            range(0, suggestedPath.size() - 1)
+            .mapToObj(i -> Pair.of(suggestedPath.get(i), suggestedPath.get(i + 1)))
+            .collect(Collectors.toList());
+
+        for (Pair<Link, Link> linkPair : linkPairs) {
+            if (!linkPair.getKey().dst().deviceId().equals(linkPair.getValue().src().deviceId())) {
+                return false;
+            }
+        }
+        return true;
+    }
 }
diff --git a/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompilerTest.java b/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompilerTest.java
index a811ad6..31c15ee 100644
--- a/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompilerTest.java
+++ b/core/net/src/test/java/org/onosproject/net/intent/impl/compiler/PointToPointIntentCompilerTest.java
@@ -25,6 +25,7 @@
 import org.onosproject.net.DeviceId;
 import org.onosproject.net.FilteredConnectPoint;
 import org.onosproject.net.Link;
+import org.onosproject.net.NetTestTools;
 import org.onosproject.net.PortNumber;
 import org.onosproject.net.ResourceGroup;
 import org.onosproject.net.flow.TrafficSelector;
@@ -200,6 +201,54 @@
     }
 
     /**
+     * Creates a PointToPoint intent based on ingress and egress deviceIds
+     * and a suggested path.
+     * @param ingress           the ingress connect point
+     * @param egress            the egress connect point
+     * @param suggestedPath     the suggested path
+     * @return the PointToPointIntent connecting the two connect points with
+     * the suggested path (if available)
+     */
+    private PointToPointIntent makeIntentSuggestedPath(ConnectPoint ingress,
+                                                       ConnectPoint egress,
+                                                       List<Link> suggestedPath) {
+        return PointToPointIntent.builder()
+                .appId(APPID)
+                .selector(selector)
+                .treatment(treatment)
+                .filteredIngressPoint(new FilteredConnectPoint(ingress))
+                .filteredEgressPoint(new FilteredConnectPoint(egress))
+                .suggestedPath(suggestedPath)
+                .build();
+    }
+
+    /**
+     * Creates a PointToPoint intent based on ingress and egress deviceIds and
+     * constraints with a suggested path.
+     *
+     * @param ingress         the ingress connect point
+     * @param egress          the egress connect point
+     * @param suggestedPath   the suggested path
+     * @param constraints     constraints
+     * @return the PointToPointIntent connecting the two connect points with
+     * constraints and a suggested path
+     */
+    private PointToPointIntent makeIntentSuggestedPath(ConnectPoint ingress,
+                                          ConnectPoint egress,
+                                          List<Link> suggestedPath,
+                                          List<Constraint> constraints) {
+        return PointToPointIntent.builder()
+                .appId(APPID)
+                .selector(selector)
+                .treatment(treatment)
+                .filteredIngressPoint(new FilteredConnectPoint(ingress))
+                .filteredEgressPoint(new FilteredConnectPoint(egress))
+                .constraints(constraints)
+                .suggestedPath(suggestedPath)
+                .build();
+    }
+
+    /**
      * Creates a compiler for HostToHost intents.
      *
      * @param hops string array describing the path hops to use when compiling
@@ -210,6 +259,41 @@
     }
 
     /**
+     * Creates a compiler for PointToPoint intents with suggested paths.
+     *
+     * @param paths all the possible paths in the network
+     * @return PointToPoint intent compiler
+     */
+    private PointToPointIntentCompiler makeCompilerSuggestedPath(String[][] paths) {
+        final PointToPointIntentCompiler compiler = new PointToPointIntentCompiler();
+        compiler.pathService = new IntentTestsMocks.MockMultiplePathService(paths);
+        compiler.linkService = new IntentTestsMocks.MockLinkService(paths);
+        return compiler;
+    }
+
+    /**
+     * Creates a point to point intent compiler for suggested path case.
+     *
+     * @param paths             all the possible paths in the network
+     * @param resourceService   service to use for resource allocation requests
+     * @return point to point compiler
+     */
+    private PointToPointIntentCompiler makeCompilerSuggestedPath(String[][] paths,
+                                                    ResourceService resourceService) {
+        final PointToPointIntentCompiler compiler = new PointToPointIntentCompiler();
+        compiler.pathService = new IntentTestsMocks.MockMultiplePathService(paths);
+        compiler.linkService = new IntentTestsMocks.MockLinkService(paths);
+
+        if (resourceService == null) {
+            compiler.resourceService = new MockResourceService();
+        } else {
+            compiler.resourceService = resourceService;
+        }
+
+        return compiler;
+    }
+
+    /**
      * Creates a point to point intent compiler for a three switch linear
      * topology.
      *
@@ -582,4 +666,151 @@
         assertThat(resourceAllocations, hasSize(6));
         assertEquals(expectedresourceAllocations, resourceAllocations);
     }
+
+    /**
+     * Test if a suggested path is correctly applied.
+     */
+    @Test
+    public void testSuggestedPath() {
+        String[] suggestedPathHops = {S1, S3, S4, S5, S6, S8};
+        List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
+
+        PointToPointIntent intent = makeIntentSuggestedPath(new ConnectPoint(DID_1, PORT_1),
+                                                            new ConnectPoint(DID_8, PORT_2),
+                                                            suggestedPath);
+
+        String[][] paths = {{S1, S2, S8}, suggestedPathHops};
+        PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(paths);
+
+        List<Intent> result = compiler.compile(intent, null);
+        assertThat(result, is(Matchers.notNullValue()));
+        assertThat(result, hasSize(1));
+        Intent resultIntent = result.get(0);
+        assertThat(resultIntent instanceof LinkCollectionIntent, is(true));
+
+        if (resultIntent instanceof LinkCollectionIntent) {
+            LinkCollectionIntent resultLinkIntent = (LinkCollectionIntent) resultIntent;
+            FilteredConnectPoint ingressPoint = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
+            FilteredConnectPoint egressPoint = new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_2));
+            // 5 links for the hops, plus one default link on ingress and egress
+            assertThat(resultLinkIntent.links(), hasSize(suggestedPathHops.length - 1));
+            assertThat(resultLinkIntent.links(), linksHasPath(S1, S3));
+            assertThat(resultLinkIntent.links(), linksHasPath(S3, S4));
+            assertThat(resultLinkIntent.links(), linksHasPath(S4, S5));
+            assertThat(resultLinkIntent.links(), linksHasPath(S5, S6));
+            assertThat(resultLinkIntent.links(), linksHasPath(S6, S8));
+            assertThat(resultLinkIntent.filteredIngressPoints(), is(ImmutableSet.of(ingressPoint)));
+            assertThat(resultLinkIntent.filteredEgressPoints(), is(ImmutableSet.of(egressPoint)));
+        }
+        assertThat("key is inherited", resultIntent.key(), is(intent.key()));
+    }
+
+    /**
+     * Test that if a suggested path isn't available it applies another available path.
+     */
+    @Test
+    public void testSuggestedPathNotAvailable() {
+        String[] suggestedPathHops = {S1, S3, S8};
+        String[] shortestPath = {S1, S2, S8};
+        List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
+
+        PointToPointIntent intent = makeIntentSuggestedPath(new ConnectPoint(DID_1, PORT_1),
+                                                            new ConnectPoint(DID_8, PORT_2),
+                                                            suggestedPath);
+
+        String[][] path = {shortestPath};
+        PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(path);
+
+        List<Intent> result = compiler.compile(intent, null);
+        assertThat(result, is(Matchers.notNullValue()));
+        assertThat(result, hasSize(1));
+        Intent resultIntent = result.get(0);
+        assertThat(resultIntent instanceof LinkCollectionIntent, is(true));
+
+        if (resultIntent instanceof LinkCollectionIntent) {
+            LinkCollectionIntent resultLinkIntent = (LinkCollectionIntent) resultIntent;
+            FilteredConnectPoint ingressPoint = new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1));
+            FilteredConnectPoint egressPoint = new FilteredConnectPoint(new ConnectPoint(DID_8, PORT_2));
+            // 5 links for the hops, plus one default link on ingress and egress
+            assertThat(resultLinkIntent.links(), hasSize(shortestPath.length - 1));
+            assertThat(resultLinkIntent.links(), linksHasPath(S1, S2));
+            assertThat(resultLinkIntent.links(), linksHasPath(S2, S8));
+            assertThat(resultLinkIntent.filteredIngressPoints(), is(ImmutableSet.of(ingressPoint)));
+            assertThat(resultLinkIntent.filteredEgressPoints(), is(ImmutableSet.of(egressPoint)));
+        }
+        assertThat("key is inherited", resultIntent.key(), is(intent.key()));
+    }
+
+    /**
+     * Tests that requests with suggested path
+     * and with sufficient available bandwidth succeed.
+     */
+    @Test
+    public void testSuggestedPathBandwidthConstrainedIntentSuccess() {
+        final double bpsTotal = 1000.0;
+        final double bpsToReserve = 100.0;
+
+        final ResourceService resourceService =
+                MockResourceService.makeCustomBandwidthResourceService(bpsTotal);
+        final List<Constraint> constraints =
+                Collections.singletonList(new BandwidthConstraint(Bandwidth.bps(bpsToReserve)));
+
+        String[] suggestedPathHops = {S1, S4, S5, S3};
+        List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
+
+        final PointToPointIntent intent = makeIntentSuggestedPath(
+                new ConnectPoint(DID_1, PORT_1),
+                new ConnectPoint(DID_3, PORT_2),
+                suggestedPath,
+                constraints);
+
+        String[][] hops = {{S1, S2, S3}, suggestedPathHops};
+        final PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(hops,
+                                                                 resourceService);
+
+        final List<Intent> compiledIntents = compiler.compile(intent, null);
+
+        assertThat(compiledIntents, Matchers.notNullValue());
+        assertThat(compiledIntents, hasSize(1));
+
+        assertThat("key is inherited",
+                   compiledIntents.stream().map(Intent::key).collect(Collectors.toList()),
+                   everyItem(is(intent.key())));
+
+    }
+
+    /**
+     * Tests that requests with insufficient available bandwidth fail.
+     */
+    @Test
+    public void testSuggestedPathBandwidthConstrainedIntentFailure() {
+        final double bpsTotal = 10.0;
+
+        final ResourceService resourceService =
+                MockResourceService.makeCustomBandwidthResourceService(bpsTotal);
+        final List<Constraint> constraints =
+                Collections.singletonList(new BandwidthConstraint(Bandwidth.bps(BPS_TO_RESERVE)));
+
+        String[] suggestedPathHops = {S1, S4, S5, S3};
+        List<Link> suggestedPath = NetTestTools.createPath(suggestedPathHops).links();
+
+        try {
+            final PointToPointIntent intent = makeIntentSuggestedPath(
+                    new ConnectPoint(DID_1, PORT_1),
+                    new ConnectPoint(DID_3, PORT_2),
+                    suggestedPath,
+                    constraints);
+
+            String[][] paths = {{S1, S2, S3}, suggestedPathHops};
+            final PointToPointIntentCompiler compiler = makeCompilerSuggestedPath(paths,
+                                                                     resourceService);
+
+            compiler.compile(intent, null);
+
+            fail("Point to Point compilation with insufficient bandwidth does "
+                         + "not throw exception.");
+        } catch (PathNotFoundException noPath) {
+            assertThat(noPath.getMessage(), containsString("No path"));
+        }
+    }
 }