org.onosproject.net.intent.Intent Java Examples

The following examples show how to use org.onosproject.net.intent.Intent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: IntentManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
public void verifyState() {
        // verify that all intents are parked and the batch operation is unblocked
        Set<IntentState> parked = Sets.newHashSet(INSTALLED, WITHDRAWN, FAILED, CORRUPT);
        for (Intent i : service.getIntents()) {
            IntentState state = service.getIntentState(i.key());
            assertTrue("Intent " + i.id() + " is in invalid state " + state,
                       parked.contains(state));
        }
        //the batch has not yet been removed when we receive the last event
        // FIXME: this doesn't guarantee to avoid the race

        //FIXME
//        for (int tries = 0; tries < 10; tries++) {
//            if (manager.batchService.getPendingOperations().isEmpty()) {
//                break;
//            }
//            delay(10);
//        }
//        assertTrue("There are still pending batch operations.",
//                   manager.batchService.getPendingOperations().isEmpty());

    }
 
Example #2
Source File: CompilerRegistry.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an intent compiler of the specified intent if an intent compiler
 * for the intent is not registered. This method traverses the class hierarchy of
 * the intent. Once an intent compiler for a parent type is found, this method
 * registers the found intent compiler.
 *
 * @param intent intent
 */
private void registerSubclassCompilerIfNeeded(Intent intent) {
    if (!compilers.containsKey(intent.getClass())) {
        Class<?> cls = intent.getClass();
        while (cls != Object.class) {
            // As long as we're within the Intent class descendants
            if (Intent.class.isAssignableFrom(cls)) {
                IntentCompiler<?> compiler = compilers.get(cls);
                if (compiler != null) {
                    compilers.put(intent.getClass(), compiler);
                    return;
                }
            }
            cls = cls.getSuperclass();
        }
    }
}
 
Example #3
Source File: PointToPointIntentCompiler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a link collection intent from the specified path and original
 * point to point intent.
 *
 * @param links the links of the packets
 * @param cost the cost associated to the links
 * @param intent the point to point intent we are compiling
 * @return the link collection intent
 */
private Intent createLinkCollectionIntent(Set<Link> links,
                                          double cost,
                                          PointToPointIntent intent) {

    return LinkCollectionIntent.builder()
            .key(intent.key())
            .appId(intent.appId())
            .selector(intent.selector())
            .treatment(intent.treatment())
            .links(ImmutableSet.copyOf(links))
            .filteredIngressPoints(ImmutableSet.of(
                    intent.filteredIngressPoint()
            ))
            .filteredEgressPoints(ImmutableSet.of(
                    intent.filteredEgressPoint()
            ))
            .applyTreatmentOnEgress(true)
            .constraints(intent.constraints())
            .priority(intent.priority())
            .cost(cost)
            .resourceGroup(intent.resourceGroup())
            .build();
}
 
Example #4
Source File: VplsIntentTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if the number of intents submitted to the intent framework is equal
 * to the number of intents expected and if all intents are equivalent.
 *
 * @param intents the list of intents expected
 */
private void checkIntents(List<Intent> intents) {
    assertEquals("The number of intents submitted differs from the number" +
                         " of intents expected. ",
                 intents.size(), intentService.getIntentCount());
    for (Intent intentOne : intents) {
        boolean found = false;
        for (Intent intentTwo : intentService.getIntents()) {
            if (intentOne.key().equals(intentTwo.key())) {
                found = true;
                assertTrue(format("The intent submitted is different from" +
                                          " the intent expected. %s %s",
                                  intentOne, intentTwo),
                           IntentUtils.intentsAreEqual(intentOne, intentTwo));
                break;
            }
        }
        assertTrue("The intent submitted is not equal to any of the expected" +
                           " intents. ", found);
    }
}
 
Example #5
Source File: MultiPointToSinglePointIntentCompilerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests if compiling an intent without partial failure constraints set and
 * with a missing ingress connect point generates an exception and no other
 * results.
 */
@Test
public void testPartialFailureConstraintFailure() {
    Set<FilteredConnectPoint> ingress = ImmutableSet.of(
            new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)),
            new FilteredConnectPoint(new ConnectPoint(DID_5, PORT_1)));

    FilteredConnectPoint egress =
            new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_2));

    MultiPointToSinglePointIntent intent =
            makeIntent(ingress, egress);

    String[] hops = {S3};

    MultiPointToSinglePointIntentCompiler compiler =
            makeCompiler(null,
                         new IntentTestsMocks.FixedMP2MPMockPathService(hops),
                         null);
    assertThat(compiler, is(notNullValue()));

    intentException.expect(IntentException.class);

    List<Intent> result = compiler.compile(intent, null);
    assertThat(result, null);
}
 
Example #6
Source File: OpticalIntentsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Submits a new optical intent.
 * Creates and submits optical intents from the JSON request.
 *
 * @param stream input JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel CreateIntent
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createIntent(InputStream stream) {
    try {
        IntentService service = get(IntentService.class);
        ObjectNode root = readTreeFromStream(mapper(), stream);
        Intent intent = decode(root);
        service.submit(intent);
        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("intents")
                .path(intent.appId().name())
                .path(Long.toString(intent.id().fingerprint()));
        return Response
                .created(locationBuilder.build())
                .build();
    } catch (IOException ioe) {
        throw new IllegalArgumentException(ioe);
    }
}
 
Example #7
Source File: InstallCoordinatorTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Installs test Intents.
 */
@Test
public void testInstallIntent() {
    IntentData toInstall = new IntentData(createTestIntent(),
                                          IntentState.INSTALLING,
                                          new WallClockTimestamp());
    List<Intent> intents = Lists.newArrayList();
    IntStream.range(0, 10).forEach(val -> {
        intents.add(new TestInstallableIntent(val));
    });
    toInstall = IntentData.compiled(toInstall, intents);
    installCoordinator.installIntents(Optional.empty(), Optional.of(toInstall));
    Intent toInstallIntent = toInstall.intent();
    TestTools.assertAfter(INSTALL_DELAY, INSTALL_DURATION, () -> {
        IntentData newData = intentStore.newData;
        assertEquals(toInstallIntent, newData.intent());
        assertEquals(IntentState.INSTALLED, newData.state());
        assertEquals(intents, newData.installables());
    });
}
 
Example #8
Source File: IntentMonitorAndRerouteManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public boolean isRelevant(FlowRuleEvent event) {
    /*
    *  Check if the rule event is relevant and it needs to be managed
     * A Rule event is relevant if the flow rule it refers to is
     * part of one of the monitored intents
     */
    FlowRule rule = event.subject();
    for (Map.Entry<ApplicationId, Map<Key, ConnectivityIntent>> entry : monitoredIntents.entrySet()) {
        for (Key key : entry.getValue().keySet()) {
            List<Intent> ints =  intentService.getInstallableIntents(key);
            for (Intent i : ints) {
                if (i instanceof FlowRuleIntent
                        && ((FlowRuleIntent) i).flowRules().contains(rule)) {
                    return true;
                }
            }
        }
    }
    return false;
}
 
Example #9
Source File: PathIntentCompilerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the compilation behavior of the path intent compiler in case of
 * VLAN {@link EncapsulationType} encapsulation constraint {@link EncapsulationConstraint}
 * and single-hop-indirect-link scenario. Ingress VLAN. No egress VLAN.
 */
@Test
public void testVlanEncapCompileSingleHopIndirectIngressVlan() {
    sut.activate();

    List<Intent> compiled = sut.compile(singleHopIndirectIntentIngressVlan, Collections.emptyList());
    assertThat(compiled, hasSize(1));

    Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();
    assertThat(rules, hasSize(1));


    FlowRule rule = rules.stream()
            .filter(x -> x.deviceId().equals(d2p2.deviceId()))
            .findFirst()
            .get();
    verifyIdAndPriority(rule, d2p2.deviceId());

    assertThat(rule.selector(), is(DefaultTrafficSelector.builder().matchInPort(d2p2.port())
                                           .matchVlanId(ingressVlan).build()));
    assertThat(rule.treatment(),
               is(DefaultTrafficTreatment.builder().setOutput(d2p3.port()).build()));

    sut.deactivate();
}
 
Example #10
Source File: PointToPointIntentCompiler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a path intent from the specified path and original
 * connectivity intent.
 *
 * @param path   path to create an intent for
 * @param intent original intent
 * @param type   primary or backup
 */
private Intent createPathIntent(Path path,
                                PointToPointIntent intent,
                                PathIntent.ProtectionType type) {
    return PathIntent.builder()
            .appId(intent.appId())
            .key(intent.key())
            .selector(intent.selector())
            .treatment(intent.treatment())
            .path(path)
            .constraints(intent.constraints())
            .priority(intent.priority())
            .setType(type)
            .resourceGroup(intent.resourceGroup())
            .build();
}
 
Example #11
Source File: DomainIntentInstallerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Test if domain Intent installation operations failed.
 */
@Test
public void testInstallFailed() {
    domainIntentService = new TestFailedDomainIntentService();
    installer.domainIntentService = domainIntentService;
    List<Intent> intentsToUninstall = Lists.newArrayList();
    List<Intent> intentsToInstall = createDomainIntents();
    IntentData toUninstall = null;
    IntentData toInstall = new IntentData(createP2PIntent(),
                                          IntentState.INSTALLING,
                                          new WallClockTimestamp());
    toInstall = IntentData.compiled(toInstall, intentsToInstall);
    IntentOperationContext<DomainIntent> operationContext;
    IntentInstallationContext context = new IntentInstallationContext(toUninstall, toInstall);
    operationContext = new IntentOperationContext(intentsToUninstall, intentsToInstall, context);
    installer.apply(operationContext);
    assertEquals(intentInstallCoordinator.failedContext, operationContext);
}
 
Example #12
Source File: IntentsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets intent installables by application ID and key.
 * @param appId application identifier
 * @param key   intent key
 *
 * @return 200 OK with array of the intent installables
 * @onos.rsModel Intents
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("installables/{appId}/{key}")
public Response getIntentWithInstallable(@PathParam("appId") String appId,
                                         @PathParam("key") String key) {
    final IntentService intentService = get(IntentService.class);
    final ApplicationId app = get(CoreService.class).getAppId(appId);
    nullIsNotFound(app, APP_ID_NOT_FOUND);

    Intent intent = intentService.getIntent(Key.of(key, app));
    if (intent == null) {
        long numericalKey = Long.decode(key);
        intent = intentService.getIntent(Key.of(numericalKey, app));
    }
    nullIsNotFound(intent, INTENT_NOT_FOUND);

    final Iterable<Intent> installables = intentService.getInstallableIntents(intent.key());
    final ObjectNode root = encodeArray(Intent.class, "installables", installables);
    return ok(root).build();
}
 
Example #13
Source File: PathIntentCompilerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests the compilation behavior of the path intent compiler in case of
 * VLAN {@link EncapsulationType} encapsulation constraint {@link EncapsulationConstraint}
 * and single-hop-direct-link scenario. No ingress VLAN. No egress VLAN.
 */
@Test
public void testVlanEncapCompileSingleHopDirectNoVlan() {
    sut.activate();

    List<Intent> compiled = sut.compile(singleHopDirectIntentNoVlan, Collections.emptyList());
    assertThat(compiled, hasSize(1));

    Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();
    assertThat(rules, hasSize(1));


    FlowRule rule = rules.stream()
            .filter(x -> x.deviceId().equals(d2p4.deviceId()))
            .findFirst()
            .get();
    verifyIdAndPriority(rule, d2p4.deviceId());

    assertThat(rule.selector(), is(DefaultTrafficSelector.builder().matchInPort(d2p4.port())
                                           .build()));
    assertThat(rule.treatment(),
               is(DefaultTrafficTreatment.builder().setOutput(d2p5.port()).build()));

    sut.deactivate();
}
 
Example #14
Source File: IntentManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void withdrawIntent() {
    flowRuleService.setFuture(true);

    listener.setLatch(1, Type.INSTALLED);
    Intent intent = new MockIntent(MockIntent.nextId());
    service.submit(intent);
    listener.await(Type.INSTALLED);
    assertEquals(1L, service.getIntentCount());
    assertEquals(1L, flowRuleService.getFlowRuleCount());

    listener.setLatch(1, Type.WITHDRAWN);
    service.withdraw(intent);
    listener.await(Type.WITHDRAWN);
    assertEquals(0L, flowRuleService.getFlowRuleCount());
    verifyState();
}
 
Example #15
Source File: NetworkManagerTest.java    From onos-byon with Apache License 2.0 6 votes vote down vote up
@Test
public void testMatches() {
    Intent intent = HostToHostIntent.builder()
            .key(manager.generateKey(NETWORK, HOST_1, HOST_2))
            .appId(manager.appId)
            .one(HOST_1)
            .two(HOST_2)
            .build();

    assertTrue(manager.matches(NETWORK, Optional.of(HOST_1), intent));
    assertTrue(manager.matches(NETWORK, Optional.of(HOST_2), intent));
    assertTrue(manager.matches(NETWORK, Optional.empty(), intent));

    assertFalse(manager.matches(NETWORK, Optional.of(HOST_3), intent));
    assertFalse(manager.matches(NETWORK_2, Optional.of(HOST_1), intent));
    assertFalse(manager.matches(NETWORK_2, Optional.of(HOST_3), intent));
}
 
Example #16
Source File: VirtualIntentCompilerRegistry.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Registers an intent compiler of the specified intent if an intent compiler
 * for the intent is not registered. This method traverses the class hierarchy of
 * the intent. Once an intent compiler for a parent type is found, this method
 * registers the found intent compiler.
 *
 * @param intent intent
 */
private void registerSubclassCompilerIfNeeded(Intent intent) {
    if (!compilers.containsKey(intent.getClass())) {
        Class<?> cls = intent.getClass();
        while (cls != Object.class) {
            // As long as we're within the Intent class descendants
            if (Intent.class.isAssignableFrom(cls)) {
                VirtualIntentCompiler<?> compiler = compilers.get(cls);
                if (compiler != null) {
                    compilers.put(intent.getClass(), compiler);
                    return;
                }
            }
            cls = cls.getSuperclass();
        }
    }
}
 
Example #17
Source File: AddOpticalIntentCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    IntentService service = get(IntentService.class);
    DeviceService deviceService = get(DeviceService.class);
    ConnectPoint ingress = createConnectPoint(ingressString);
    ConnectPoint egress = createConnectPoint(egressString);

    Intent intent = createOpticalIntent(ingress, egress, deviceService,
            key(), appId(), bidirectional, createOchSignal(), null);

    service.submit(intent);
    print("Optical intent submitted:\n%s", intent.toString());
}
 
Example #18
Source File: IntentCleanupTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Only submit one of two intents because one is too new.
 */
@Test
public void skipPoll() {
    IntentStoreDelegate mockDelegate = new IntentStoreDelegate() {
        @Override
        public void process(IntentData intentData) {
            intentData.setState(CORRUPT);
            store.write(intentData);
        }

        @Override
        public void notify(IntentEvent event) {}
    };
    store.setDelegate(mockDelegate);

    Intent intent = new MockIntent(1L);
    IntentData data = new IntentData(intent, INSTALL_REQ, null);
    store.addPending(data);

    Intent intent2 = new MockIntent(2L);
    Timestamp version = new SystemClockTimestamp(1L);
    data = new IntentData(intent2, INSTALL_REQ, version);
    store.addPending(data);

    cleanup.run();
    assertEquals("Expect number of submits incorrect",
                 1, service.submitCounter());
}
 
Example #19
Source File: FlowRuleIntentInstallerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Generates FlowRuleIntents for test. Flow rules in Intent should have same
 * match as we created by createFlowRuleIntents method, but action will be
 * different.
 *
 * @return the FlowRuleIntents for test
 */
public List<Intent> createFlowRuleIntentsWithSameMatch() {
    TrafficSelector selector = DefaultTrafficSelector.builder()
            .matchInPhyPort(CP1.port())
            .build();
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .punt()
            .build();

    FlowRule flowRule = DefaultFlowRule.builder()
            .forDevice(CP1.deviceId())
            .withSelector(selector)
            .withTreatment(treatment)
            .fromApp(APP_ID)
            .withPriority(DEFAULT_PRIORITY)
            .makePermanent()
            .build();

    List<NetworkResource> resources = ImmutableList.of(CP1.deviceId());

    FlowRuleIntent intent = new FlowRuleIntent(APP_ID,
                                               KEY1,
                                               ImmutableList.of(flowRule),
                                               resources,
                                               PathIntent.ProtectionType.PRIMARY,
                                               RG1);

    List<Intent> flowRuleIntents = Lists.newArrayList();
    flowRuleIntents.add(intent);

    return flowRuleIntents;
}
 
Example #20
Source File: McastForwarding.java    From onos with Apache License 2.0 5 votes vote down vote up
public void withdrawIntent(Key key) {
    if (key == null) {
        // nothing to withdraw
        return;
    }
    Intent intent = intentService.getIntent(key);
    intentService.withdraw(intent);
}
 
Example #21
Source File: MultiPointToSinglePointIntentCompilerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests a simple topology where two ingress points share some path segments
 * and some path segments are not shared.
 */
@Test
public void testTwoIngressCompilation() {
    Set<FilteredConnectPoint> ingress =
            Sets.newHashSet(new FilteredConnectPoint(new ConnectPoint(DID_1, PORT_1)),
                            new FilteredConnectPoint(new ConnectPoint(DID_2, PORT_1)));
    FilteredConnectPoint egress =
            new FilteredConnectPoint(new ConnectPoint(DID_4, PORT_1));

    MultiPointToSinglePointIntent intent = makeIntent(ingress, egress);
    assertThat(intent, is(notNullValue()));

    final String[] hops = {S3};
    MultiPointToSinglePointIntentCompiler compiler = makeCompiler(hops);
    assertThat(compiler, is(notNullValue()));

    List<Intent> result = compiler.compile(intent, null);
    assertThat(result, is(notNullValue()));
    assertThat(result, hasSize(1));
    Intent resultIntent = result.get(0);
    assertThat(resultIntent instanceof LinkCollectionIntent, is(true));

    if (resultIntent instanceof LinkCollectionIntent) {
        LinkCollectionIntent linkIntent = (LinkCollectionIntent) resultIntent;
        assertThat(linkIntent.links(), hasSize(3));
        assertThat(linkIntent.links(), linksHasPath(S1, S3));
        assertThat(linkIntent.links(), linksHasPath(S2, S3));
        assertThat(linkIntent.links(), linksHasPath(S3, S4));
    }
    assertThat("key is inherited", resultIntent.key(), is(intent.key()));
}
 
Example #22
Source File: IntentSelection.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Marks and returns the previous intent in this group. Note that the
 * selection wraps around to the end again, if necessary.
 *
 * @return the previous intent in the group
 */
public Intent prev() {
    index -= 1;
    if (index < 0) {
        index = intents.size() - 1;
    }
    return intents.get(index);
}
 
Example #23
Source File: AddPointToPointIntentCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    IntentService service = get(IntentService.class);

    ConnectPoint ingress = ConnectPoint.deviceConnectPoint(ingressDeviceString);

    ConnectPoint egress = ConnectPoint.deviceConnectPoint(egressDeviceString);

    TrafficSelector selector = buildTrafficSelector();
    TrafficTreatment treatment = buildTrafficTreatment();

    List<Constraint> constraints = buildConstraints();
    if (backup) {
        constraints.add(protection());
    }

    if (useProtected) {
        constraints.add(ProtectedConstraint.useProtectedLink());
    }

    Intent intent = PointToPointIntent.builder()
            .appId(appId())
            .key(key())
            .selector(selector)
            .treatment(treatment)
            .filteredIngressPoint(new FilteredConnectPoint(ingress))
            .filteredEgressPoint(new FilteredConnectPoint(egress))
            .constraints(constraints)
            .priority(priority())
            .resourceGroup(resourceGroup())
            .build();
    service.submit(intent);
    print("Point to point intent submitted:\n%s", intent.toString());
}
 
Example #24
Source File: PointToPointIntentCompilerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * 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())));

}
 
Example #25
Source File: IntentSynchronizer.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void submit(Intent intent) {
    synchronized (this) {
        intents.put(intent.key(), intent);
        if (isElectedLeader && isActivatedLeader) {
            log.trace("Submitting intent: {}", intent);
            intentService.submit(intent);
        }
    }
}
 
Example #26
Source File: ProtectedTransportIntentCompiler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Allocate resource for each {@link Path}s.
 *
 * @param intent to allocate resource to
 * @param primary path
 * @param secondary path
 * @param klass label resource class
 * @return Pair of chosen resource (primary, secondary)
 * @param <T> label resource type
 * @throws IntentCompilationException when there is no resource available
 */
<T> Pair<T, T> allocateEach(Intent intent, Path primary, Path secondary, Class<T> klass) {
    log.trace("allocateEach({}, {}, {}, {})", intent, primary, secondary, klass);
    Pair<T, T> vlans = null;
    do {
        Set<T> primaryVlans = commonLabelResource(primary, klass);
        Set<T> secondaryVlans = commonLabelResource(secondary, klass);
        Pair<T, T> candidates = pickEach(primaryVlans, secondaryVlans);
        T primaryT = candidates.getLeft();
        T secondaryT = candidates.getRight();

        // try to allocate candidates along each path
        Stream<Resource> primaryResources = primary.links().stream()
                .flatMap(link -> Stream.of(link.src(), link.dst()))
                .distinct()
                .map(cp -> Resources.discrete(resourceId(cp), primaryT).resource());
        Stream<Resource> secondaryResources = secondary.links().stream()
                .flatMap(link -> Stream.of(link.src(), link.dst()))
                .distinct()
                .map(cp -> Resources.discrete(resourceId(cp), secondaryT).resource());

        List<Resource> resources = concat(primaryResources, secondaryResources)
                                    .collect(Collectors.toList());
        log.trace("Calling allocate({},{})", intent.key(), resources);
        if (resourceService.allocate(intent.key(), resources).isEmpty()) {
            log.warn("Allocation failed, retrying");
            continue;
        }
        vlans = candidates;
    } while (false);
    log.trace("allocation done.");
    return vlans;
}
 
Example #27
Source File: VplsOperationManager.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Retrieves installed Intents from IntentService which related to
 * specific VPLS.
 *
 * @return the Intents which related to the VPLS
 */
private Set<Intent> getCurrentIntents() {
    VplsData vplsData = vplsOperation.vpls();
    String vplsName = vplsData.name();
    return Tools.stream(intentService.getIntents())
            .filter(intent -> intent.key().toString().startsWith(vplsName))
            .collect(Collectors.toSet());
}
 
Example #28
Source File: TrafficMonitorBase.java    From onos with Apache License 2.0 5 votes vote down vote up
protected Highlights intentGroup() {
    Highlights highlights = new Highlights();

    if (selectedIntents != null && !selectedIntents.none()) {
        // If 'all' intents are selected, they will all have primary
        // highlighting; otherwise, the specifically selected intent will
        // have primary highlighting, and the remainder will have secondary
        // highlighting.
        Set<Intent> primary;
        Set<Intent> secondary;
        int count = selectedIntents.size();

        Set<Intent> allBut = new HashSet<>(selectedIntents.intents());
        Intent current;

        if (selectedIntents.all()) {
            primary = allBut;
            secondary = Collections.emptySet();
            log.debug("Highlight all intents ({})", count);
        } else {
            current = selectedIntents.current();
            primary = new HashSet<>();
            primary.add(current);
            allBut.remove(current);
            secondary = allBut;
            log.debug("Highlight intent: {} ([{}] of {})",
                                     current.id(), selectedIntents.index(), count);
        }

        highlightIntentLinks(highlights, primary, secondary);
    }
    return highlights;
}
 
Example #29
Source File: TrafficMonitorBase.java    From onos with Apache License 2.0 5 votes vote down vote up
protected Iterable<Link> addEdgeLinksIfNeeded(Intent parentIntent,
                                              Collection<Link> links) {
    if (parentIntent instanceof HostToHostIntent) {
        links = new HashSet<>(links);
        HostToHostIntent h2h = (HostToHostIntent) parentIntent;
        Host h1 = services.host().getHost(h2h.one());
        Host h2 = services.host().getHost(h2h.two());
        links.add(createEdgeLink(h1, true));
        links.add(createEdgeLink(h2, true));
    }
    return links;
}
 
Example #30
Source File: NetworkManagerTest.java    From onos-byon with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() {
    manager = new NetworkManager();
    manager.appId = new TestApplicationId("network-test");
    Intent.bindIdGenerator(idGenerator);

}