org.onosproject.net.flow.FlowRule Java Examples

The following examples show how to use org.onosproject.net.flow.FlowRule. 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: MainComponent.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Triggers clean up of flows and groups from this app, returns false if no
 * flows or groups were found, true otherwise.
 *
 * @return false if no flows or groups were found, true otherwise
 */
private boolean cleanUp() {
    Collection<FlowRule> flows = Lists.newArrayList(
            flowRuleService.getFlowEntriesById(appId).iterator());

    Collection<Group> groups = Lists.newArrayList();
    for (Device device : deviceService.getAvailableDevices()) {
        groupService.getGroups(device.id(), appId).forEach(groups::add);
    }

    if (flows.isEmpty() && groups.isEmpty()) {
        return false;
    }

    flows.forEach(flowRuleService::removeFlowRules);
    if (!groups.isEmpty()) {
        // Wait for flows to be removed in case those depend on groups.
        sleep(1000);
        groups.forEach(g -> groupService.removeGroup(
                g.deviceId(), g.appCookie(), g.appId()));
    }

    return true;
}
 
Example #2
Source File: Ipv6RoutingComponent.java    From ngsdn-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a flow rule for the L2 table mapping the given next hop MAC to
 * the given output port.
 * <p>
 * This is called by the routing policy methods below to establish L2-based
 * forwarding inside the fabric, e.g., when deviceId is a leaf switch and
 * nextHopMac is the one of a spine switch.
 *
 * @param deviceId   the device
 * @param nexthopMac the next hop (destination) mac
 * @param outPort    the output port
 */
private FlowRule createL2NextHopRule(DeviceId deviceId, MacAddress nexthopMac,
                                     PortNumber outPort) {

    final String tableId = "IngressPipeImpl.l2_exact_table";
    final PiCriterion match = PiCriterion.builder()
            .matchExact(PiMatchFieldId.of("hdr.ethernet.dst_addr"),
                        nexthopMac.toBytes())
            .build();


    final PiAction action = PiAction.builder()
            .withId(PiActionId.of("IngressPipeImpl.set_egress_port"))
            .withParameter(new PiActionParam(
                    PiActionParamId.of("port_num"),
                    outPort.toLong()))
            .build();

    return Utils.buildFlowRule(
            deviceId, appId, tableId, match, action);
}
 
Example #3
Source File: FlowRuleCodecTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that a rule with a SigId criterion decodes properly.
 *
 * @throws IOException if the resource cannot be processed
 */
@Test
public void codecSigIdCriteriaFlowTest() throws Exception {
    FlowRule rule = getRule("sigid-flow.json");

    checkCommonData(rule);

    assertThat(rule.selector().criteria().size(), is(1));
    Criterion criterion = rule.selector().criteria().iterator().next();
    assertThat(criterion.type(), is(Criterion.Type.OCH_SIGID));
    Lambda lambda = ((OchSignalCriterion) criterion).lambda();
    assertThat(lambda, instanceOf(OchSignal.class));
    OchSignal ochSignal = (OchSignal) lambda;
    assertThat(ochSignal.spacingMultiplier(), is(3));
    assertThat(ochSignal.slotGranularity(), is(4));
    assertThat(ochSignal.gridType(), is(GridType.CWDM));
    assertThat(ochSignal.channelSpacing(), is(ChannelSpacing.CHL_25GHZ));
}
 
Example #4
Source File: DistributedFlowStatisticStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void removeFlowStatistic(FlowRule rule) {
    ConnectPoint cp = buildConnectPoint(rule);
    if (cp == null) {
        return;
    }

    // remove this rule if present from current map
    current.computeIfPresent(cp, (c, e) -> {
        e.remove(rule);
        return e;
    });

    // remove this on if present from previous map
    previous.computeIfPresent(cp, (c, e) -> {
        e.remove(rule);
        return e;
    });
}
 
Example #5
Source File: PolatisFlowRuleProgrammable.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean editConnection(FlowRule rule, String mode) {
    CrossConnects crossConnects = PolatisOpticalUtility.fromFlowRule(this, rule);
    final StringBuilder cfg = new StringBuilder(xmlOpen(KEY_CONNS_XMLNS));
    List<Pair> pairs = crossConnects.pair();
    final String keyPairCompat = parseKeyPairCompat();
    final String keyPairMode = String.format("%s operation=\"%s\"", keyPairCompat, mode);
    pairs.forEach(p -> {
            cfg.append(xmlOpen(keyPairMode))
            .append(xmlOpen(KEY_SRC))
            .append(p.ingress())
            .append(xmlClose(KEY_SRC))
            .append(xmlOpen(KEY_DST))
            .append(p.egress())
            .append(xmlClose(KEY_DST))
            .append(xmlClose(keyPairCompat));
    });
    cfg.append(xmlClose(KEY_CONNS));
    return netconfEditConfig(handler(), null, cfg.toString());
}
 
Example #6
Source File: FlowRuleManagerTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Test
public void getFlowEntries() {
    assertTrue("store should be empty",
               Sets.newHashSet(service.getFlowEntries(DID)).isEmpty());
    FlowRule f1 = addFlowRule(1);
    FlowRule f2 = addFlowRule(2);

    FlowEntry fe1 = new DefaultFlowEntry(f1);
    FlowEntry fe2 = new DefaultFlowEntry(f2);
    assertEquals("2 rules should exist", 2, flowCount());

    providerService.pushFlowMetrics(DID, ImmutableList.of(fe1, fe2));
    validateEvents(RULE_ADD_REQUESTED, RULE_ADD_REQUESTED,
                   RULE_ADDED, RULE_ADDED);

    addFlowRule(1);
    System.err.println("events :" + listener.events);
    assertEquals("should still be 2 rules", 2, flowCount());

    providerService.pushFlowMetrics(DID, ImmutableList.of(fe1));
    validateEvents(RULE_UPDATED, RULE_UPDATED);
}
 
Example #7
Source File: CorsaPipelineV3.java    From onos with Apache License 2.0 6 votes vote down vote up
protected void processTaggedPackets(boolean install) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    selector.matchVlanId(VlanId.ANY);

    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    treatment.transition(VLAN_MAC_XLATE_TABLE);

    FlowRule rule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(CONTROLLER_PRIORITY)
            .fromApp(appId)
            .makePermanent()
            .forTable(VLAN_CHECK_TABLE).build();
    processFlowRule(install, rule, "Provisioned vlan table tagged packets");
}
 
Example #8
Source File: FlowEntryBuilder.java    From onos with Apache License 2.0 6 votes vote down vote up
private FlowEntry createFlowEntryForFlowMod(FlowEntryState...state) {
    FlowEntryState flowState = state.length > 0 ? state[0] : FlowEntryState.FAILED;
    FlowRule.Builder builder = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(buildSelector())
            .withTreatment(buildTreatment())
            .withPriority(flowMod.getPriority())
            .withIdleTimeout(flowMod.getIdleTimeout())
            .withCookie(flowMod.getCookie().getValue());
    if (flowMod.getVersion() != OFVersion.OF_10) {
        builder.forTable(flowMod.getTableId().getValue());
    }

    if (afsc != null) {
        FlowEntry.FlowLiveType liveType = FlowEntry.FlowLiveType.IMMEDIATE;
        return new DefaultFlowEntry(builder.build(), flowState, 0, liveType, 0, 0);
    } else {
        return new DefaultFlowEntry(builder.build(), flowState, 0, 0, 0);
    }
}
 
Example #9
Source File: OpenstackFlowRuleManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void connectTables(DeviceId deviceId, int fromTable, int toTable) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

    treatment.transition(toTable);

    FlowRule flowRule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(DROP_PRIORITY)
            .fromApp(appId)
            .makePermanent()
            .forTable(fromTable)
            .build();

    applyRule(flowRule, true);
}
 
Example #10
Source File: OvsOfdpaPipeline.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected List<List<FlowRule>> processEthDstOnlyFilter(EthCriterion ethCriterion,
                                                 ApplicationId applicationId) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    selector.matchEthType(Ethernet.TYPE_IPV4);
    selector.matchEthDst(ethCriterion.mac());
    treatment.transition(UNICAST_ROUTING_TABLE);
    FlowRule rule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(DEFAULT_PRIORITY)
            .fromApp(applicationId)
            .makePermanent()
            .forTable(TMAC_TABLE).build();
    return ImmutableList.of(ImmutableList.of(rule));
}
 
Example #11
Source File: PathIntentCompiler.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public List<Intent> compile(PathIntent intent, List<Intent> installable) {

    List<FlowRule> rules = new LinkedList<>();
    List<DeviceId> devices = new LinkedList<>();
    compile(this, intent, rules, devices);


    return ImmutableList.of(new FlowRuleIntent(appId,
                                               intent.key(),
                                               rules,
                                               intent.resources(),
                                               intent.type(),
                                               intent.resourceGroup()
    ));
}
 
Example #12
Source File: SpringOpenTTP.java    From onos with Apache License 2.0 6 votes vote down vote up
protected void populateTableMissEntry(int tableToAdd,
                                      boolean toControllerNow,
                                      boolean toControllerWrite,
                                      boolean toTable, int tableToSend) {
    TrafficSelector selector = DefaultTrafficSelector.builder().build();
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder();

    if (toControllerNow) {
        tBuilder.setOutput(PortNumber.CONTROLLER);
    }

    if (toControllerWrite) {
        tBuilder.deferred().setOutput(PortNumber.CONTROLLER);
    }

    if (toTable) {
        tBuilder.transition(tableToSend);
    }

    FlowRule flow = DefaultFlowRule.builder().forDevice(deviceId)
            .withSelector(selector).withTreatment(tBuilder.build())
            .withPriority(0).fromApp(appId).makePermanent()
            .forTable(tableToAdd).build();

    flowRuleService.applyFlowRules(flow);
}
 
Example #13
Source File: FlowEntryBuilder.java    From onos with Apache License 2.0 6 votes vote down vote up
private FlowEntry createFlowEntryFromLightweightStat() {
    FlowRule.Builder builder = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(buildSelector())
            .withPriority(lightWeightStat.getPriority())
            .withIdleTimeout(0)
            .withCookie(0);
    FlowStatParser flowLightweightStatParser = new FlowStatParser(lightWeightStat.getStats());
    builder.forTable(lightWeightStat.getTableId().getValue());
    if (afsc != null && flowLightweightStatParser.isDurationReceived()) {
        FlowEntry.FlowLiveType liveType = afsc.calFlowLiveType(flowLightweightStatParser.getDuration());
        return new DefaultFlowEntry(builder.build(), FlowEntryState.ADDED,
                SECONDS.toNanos(flowLightweightStatParser.getDuration())
                        + flowLightweightStatParser.getDuration(), NANOSECONDS,
                liveType,
                flowLightweightStatParser.getPacketCount(),
                flowLightweightStatParser.getByteCount());
    } else {
        return new DefaultFlowEntry(builder.build(), FlowEntryState.ADDED,
                flowLightweightStatParser.getDuration(),
                flowLightweightStatParser.getPacketCount(),
                flowLightweightStatParser.getByteCount());
    }
}
 
Example #14
Source File: Ipv6RoutingComponent.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a routing flow rule that matches on the given IPv6 prefix and
 * executes the given group ID (created before).
 *
 * @param deviceId  the device where flow rule will be installed
 * @param ip6Prefix the IPv6 prefix
 * @param groupId   the group ID
 * @return a flow rule
 */
private FlowRule createRoutingRule(DeviceId deviceId, Ip6Prefix ip6Prefix,
                                   int groupId) {

    // TODO EXERCISE 3
    // Modify P4Runtime entity names to match content of P4Info file (look
    // for the fully qualified name of tables, match fields, and actions.
    // ---- START SOLUTION ----
    final String tableId = "IngressPipeImpl.l3_table";
    final PiCriterion match = PiCriterion.builder()
            .matchLpm(
                    PiMatchFieldId.of("hdr.ipv6.dst_addr"),
                    ip6Prefix.address().toOctets(),
                    ip6Prefix.prefixLength())
            .build();

    final PiTableAction action = PiActionProfileGroupId.of(groupId);
    // ---- END SOLUTION ----

    return Utils.buildFlowRule(
            deviceId, appId, tableId, match, action);
}
 
Example #15
Source File: Ipv6RoutingComponent.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a flow rule for the L2 table mapping the given next hop MAC to
 * the given output port.
 * <p>
 * This is called by the routing policy methods below to establish L2-based
 * forwarding inside the fabric, e.g., when deviceId is a leaf switch and
 * nextHopMac is the one of a spine switch.
 *
 * @param deviceId   the device
 * @param nexthopMac the next hop (destination) mac
 * @param outPort    the output port
 */
private FlowRule createL2NextHopRule(DeviceId deviceId, MacAddress nexthopMac,
                                     PortNumber outPort) {

    // TODO EXERCISE 3
    // Modify P4Runtime entity names to match content of P4Info file (look
    // for the fully qualified name of tables, match fields, and actions.
    // ---- START SOLUTION ----
    final String tableId = "MODIFY ME";
    final PiCriterion match = PiCriterion.builder()
            .matchExact(PiMatchFieldId.of("MODIFY ME"),
                        nexthopMac.toBytes())
            .build();


    final PiAction action = PiAction.builder()
            .withId(PiActionId.of("MODIFY ME"))
            .withParameter(new PiActionParam(
                    PiActionParamId.of("MODIFY ME"),
                    outPort.toLong()))
            .build();
    // ---- END SOLUTION ----

    return Utils.buildFlowRule(
            deviceId, appId, tableId, match, action);
}
 
Example #16
Source File: CorsaPipelineV39.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void processL3IFMacDATable(boolean install) {
    int table = L3_IF_MAC_DA_TABLE;

    //Default action
    processTableMissDrop(install, table, "Provisioned l3 table drop");

    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();

    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder()
            .transition(ETHER_TABLE);

    FlowRule rule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(1)
            .fromApp(appId)
            .makePermanent()
            .forTable(table).build();
    processFlowRule(install, rule, "Provisioned l3 table");
}
 
Example #17
Source File: DefaultVirtualFlowRuleProvider.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Translate the requested physical flow rules into virtual flow rules.
 *
 * @param flowRule A virtual flow rule to be translated
 * @return A flow rule for a specific virtual network
 */
private FlowRule virtualizeFlowRule(FlowRule flowRule) {

    FlowRule storedrule = frm.getVirtualRule(flowRule);

    if (flowRule.reason() == FlowRule.FlowRemoveReason.NO_REASON) {
        return storedrule;
    } else {
        return DefaultFlowRule.builder()
                .withReason(flowRule.reason())
                .withPriority(storedrule.priority())
                .forDevice(storedrule.deviceId())
                .forTable(storedrule.tableId())
                .fromApp(new DefaultApplicationId(storedrule.appId(), null))
                .withIdleTimeout(storedrule.timeout())
                .withHardTimeout(storedrule.hardTimeout())
                .withSelector(storedrule.selector())
                .withTreatment(storedrule.treatment())
                .build();
    }
}
 
Example #18
Source File: SpringOpenTTPDell.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
//Dell switches need ETH_DST based match condition in all IP table entries.
//So while processing the ETH_DST based filtering objective, store
//the device MAC to be used locally to use it while pushing the IP rules.
protected List<FlowRule> processEthDstFilter(EthCriterion ethCriterion,
                                             VlanIdCriterion vlanIdCriterion,
                                             FilteringObjective filt,
                                             VlanId assignedVlan,
                                             ApplicationId applicationId) {
    // Store device termination Mac to be used in IP flow entries
    deviceTMac = ethCriterion.mac();

    log.debug("For now not adding any TMAC rules "
            + "into Dell switches as it is ignoring");

    return Collections.emptyList();
}
 
Example #19
Source File: SpringOpenTTP.java    From onos with Apache License 2.0 6 votes vote down vote up
protected Collection<FlowRule> processSpecific(ForwardingObjective fwd) {
    log.debug("Processing specific fwd objective:{} in dev:{} with next:{}",
              fwd.id(), deviceId, fwd.nextId());
    boolean isEthTypeObj = isSupportedEthTypeObjective(fwd);
    boolean isEthDstObj = isSupportedEthDstObjective(fwd);

    if (isEthTypeObj) {
        return processEthTypeSpecificObjective(fwd);
    } else if (isEthDstObj) {
        return processEthDstSpecificObjective(fwd);
    } else {
        log.warn("processSpecific: Unsupported "
                + "forwarding objective criteria");
        fail(fwd, ObjectiveError.UNSUPPORTED);
        return Collections.emptySet();
    }
}
 
Example #20
Source File: SimpleFlowRuleStore.java    From onos with Apache License 2.0 5 votes vote down vote up
private FlowEntry getFlowEntryInternal(DeviceId deviceId, FlowRule rule) {
    List<StoredFlowEntry> fes = getFlowEntries(deviceId, rule.id());
    for (StoredFlowEntry fe : fes) {
        if (fe.equals(rule)) {
            return fe;
        }
    }
    return null;
}
 
Example #21
Source File: IntProgrammableImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean setSourcePort(PortNumber port) {
    if (!setupBehaviour()) {
        return false;
    }

    // process_int_source_sink.tb_set_source for each host-facing port
    PiCriterion ingressCriterion = PiCriterion.builder()
            .matchExact(IntConstants.HDR_STANDARD_METADATA_INGRESS_PORT, port.toLong())
            .build();
    TrafficSelector srcSelector = DefaultTrafficSelector.builder()
            .matchPi(ingressCriterion)
            .build();
    PiAction setSourceAct = PiAction.builder()
            .withId(IntConstants.INGRESS_PROCESS_INT_SOURCE_SINK_INT_SET_SOURCE)
            .build();
    TrafficTreatment srcTreatment = DefaultTrafficTreatment.builder()
            .piTableAction(setSourceAct)
            .build();
    FlowRule srcFlowRule = DefaultFlowRule.builder()
            .withSelector(srcSelector)
            .withTreatment(srcTreatment)
            .fromApp(appId)
            .withPriority(DEFAULT_PRIORITY)
            .makePermanent()
            .forDevice(deviceId)
            .forTable(IntConstants.INGRESS_PROCESS_INT_SOURCE_SINK_TB_SET_SOURCE)
            .build();
    flowRuleService.applyFlowRules(srcFlowRule);
    return true;
}
 
Example #22
Source File: OpenVSwitchPipeline.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processSnatTable(boolean install) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

    treatment.transition(MAC_TABLE);
    treatment.add(Instructions.createOutput(PortNumber.CONTROLLER));
    FlowRule rule;
    rule = DefaultFlowRule.builder().forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(TABLE_MISS_PRIORITY).fromApp(appId)
            .makePermanent().forTable(SNAT_TABLE).build();

    applyRules(install, rule);
}
 
Example #23
Source File: DefaultVirtualFlowRuleProvider.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void applyFlowRule(NetworkId networkId, FlowRule... flowRules) {
    for (FlowRule flowRule : flowRules) {
        devirtualize(networkId, flowRule).forEach(
                r -> flowRuleService.applyFlowRules(r));
    }
}
 
Example #24
Source File: FabricFilteringPipelinerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates one rule for ingress_port_vlan table and one rule for
 * fwd_classifier table (IPv4 multicast) when the condition is ipv4
 * multicast mac address.
 */
@Test
public void testIpv4MulticastFwdClass() throws FabricPipelinerException {
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .pushVlan()
            .setVlanId(VLAN_100)
            .build();
    FilteringObjective filteringObjective = DefaultFilteringObjective.builder()
            .permit()
            .withPriority(PRIORITY)
            .withKey(Criteria.matchInPort(PORT_1))
            .addCondition(Criteria.matchEthDstMasked(MacAddress.IPV4_MULTICAST, MacAddress.IPV4_MULTICAST_MASK))
            .addCondition(Criteria.matchVlanId(VlanId.NONE))
            .withMeta(treatment)
            .fromApp(APP_ID)
            .makePermanent()
            .add();
    ObjectiveTranslation actualTranslation = translator.translate(filteringObjective);
    List<FlowRule> expectedFlowRules = Lists.newArrayList();
    // in port vlan flow rule
    expectedFlowRules.add(buildExpectedVlanInPortRule(
            PORT_1,
            VlanId.NONE,
            VlanId.NONE,
            VLAN_100,
            FabricConstants.FABRIC_INGRESS_FILTERING_INGRESS_PORT_VLAN));

    // forwarding classifier
    expectedFlowRules.addAll(buildExpectedFwdClassifierRule(
            PORT_1,
            MacAddress.IPV4_MULTICAST,
            MacAddress.IPV4_MULTICAST_MASK,
            Ethernet.TYPE_IPV4,
            FilteringObjectiveTranslator.FWD_IPV4_ROUTING));

    ObjectiveTranslation expectedTranslation = buildExpectedTranslation(expectedFlowRules);

    assertEquals(expectedTranslation, actualTranslation);
}
 
Example #25
Source File: FlowRuleManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean validateState(Map<FlowRule, FlowEntryState> expected) {
    Map<FlowRule, FlowEntryState> expectedToCheck = new HashMap<>(expected);
    Iterable<FlowEntry> rules = service.getFlowEntries(DID);
    for (FlowEntry f : rules) {
        assertTrue("Unexpected FlowRule " + f, expectedToCheck.containsKey(f));
        assertEquals("FlowEntry" + f, expectedToCheck.get(f), f.state());
        expectedToCheck.remove(f);
    }
    assertEquals(Collections.emptySet(), expectedToCheck.entrySet());
    return true;
}
 
Example #26
Source File: FlowRuleCodecTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up for each test.  Creates a context and fetches the flow rule
 * codec.
 */
@Before
public void setUp() {
    context = new MockCodecContext();
    flowRuleCodec = context.codec(FlowRule.class);
    assertThat(flowRuleCodec, notNullValue());

    expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID))
            .andReturn(APP_ID).anyTimes();
    expect(mockCoreService.getAppId(anyShort())).andReturn(APP_ID).anyTimes();
    replay(mockCoreService);
    context.registerService(CoreService.class, mockCoreService);
}
 
Example #27
Source File: NdpReplyComponent.java    From onos-p4-tutorial with Apache License 2.0 5 votes vote down vote up
private void setUpDevice(DeviceId deviceId) {
    Srv6DeviceConfig config = configService.getConfig(deviceId, Srv6DeviceConfig.class);
    if (config == null) {
        // Config not available yet
        throw new ItemNotFoundException("Missing Srv6Config for " + deviceId);
    }

    final MacAddress deviceMac = config.myStationMac();

    // Get all interface for the device
    final Collection<Interface> interfaces = interfaceService.getInterfaces()
            .stream()
            .filter(iface -> iface.connectPoint().deviceId().equals(deviceId))
            .collect(Collectors.toSet());

    if (interfaces.isEmpty()) {
        log.info("{} does not have any IPv6 interface configured",
                 deviceId);
        return;
    }

    log.info("Adding rules to {} to generate NDP NA for {} IPv6 interfaces...",
             deviceId, interfaces.size());

    final Collection<FlowRule> flowRules = interfaces.stream()
            .map(this::getIp6Addresses)
            .flatMap(Collection::stream)
            .map(iaddr -> buildNdpReplyFlowRule(deviceId, deviceMac, iaddr))
            .collect(Collectors.toSet());

    installRules(flowRules);
}
 
Example #28
Source File: FlowRuleIntentInstallerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Do both install and uninstall Intents with different flow rules.
 */
@Test
public void testUninstallAndInstall() {
    List<Intent> intentsToInstall = createAnotherFlowRuleIntents();
    List<Intent> intentsToUninstall = createFlowRuleIntents();

    IntentData toInstall = new IntentData(createP2PIntent(),
                                          IntentState.INSTALLING,
                                          new WallClockTimestamp());
    toInstall = IntentData.compiled(toInstall, intentsToInstall);
    IntentData toUninstall = new IntentData(createP2PIntent(),
                                            IntentState.INSTALLED,
                                            new WallClockTimestamp());
    toUninstall = IntentData.compiled(toUninstall, intentsToUninstall);

    IntentOperationContext<FlowRuleIntent> operationContext;
    IntentInstallationContext context = new IntentInstallationContext(toUninstall, toInstall);
    operationContext = new IntentOperationContext(intentsToUninstall, intentsToInstall, context);

    installer.apply(operationContext);

    IntentOperationContext successContext = intentInstallCoordinator.successContext;
    assertEquals(successContext, operationContext);

    Set<FlowRule> expectedFlowRules = intentsToUninstall.stream()
            .map(intent -> (FlowRuleIntent) intent)
            .map(FlowRuleIntent::flowRules)
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());

    assertEquals(expectedFlowRules, flowRuleService.flowRulesRemove);

    expectedFlowRules = intentsToInstall.stream()
            .map(intent -> (FlowRuleIntent) intent)
            .map(FlowRuleIntent::flowRules)
            .flatMap(Collection::stream)
            .collect(Collectors.toSet());

    assertEquals(expectedFlowRules, flowRuleService.flowRulesAdd);
}
 
Example #29
Source File: OvsCorsaPipeline.java    From onos with Apache License 2.0 5 votes vote down vote up
private void processEtherTable(boolean install) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder()
    .matchEthType(Ethernet.TYPE_ARP);
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment
            .builder()
            .punt();

    FlowRule rule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(CONTROLLER_PRIORITY)
            .fromApp(appId)
            .makePermanent()
            .forTable(ETHER_TABLE).build();

    processFlowRule(true, rule, "Provisioned ether table");
    selector = DefaultTrafficSelector.builder()
            .matchEthType(Ethernet.TYPE_IPV4);
    treatment = DefaultTrafficTreatment.builder()
    .transition(COS_MAP_TABLE);

    rule = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withPriority(CONTROLLER_PRIORITY)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .fromApp(appId)
            .makePermanent()
            .forTable(ETHER_TABLE).build();
    processFlowRule(true, rule, "Provisioned ether table");

    //Drop rule
    processTableMissDrop(true, VLAN_TABLE, "Provisioned ether table");

}
 
Example #30
Source File: RoadmManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public FlowId createConnection(DeviceId deviceId, int priority, boolean isPermanent,
                               int timeout, PortNumber inPort, PortNumber outPort, OchSignal ochSignal) {
    checkNotNull(deviceId);
    checkNotNull(inPort);
    checkNotNull(outPort);

    //Creation of selector.
    TrafficSelector selector = DefaultTrafficSelector.builder()
            .add(Criteria.matchInPort(inPort))
            .add(Criteria.matchOchSignalType(OchSignalType.FIXED_GRID))
            .add(Criteria.matchLambda(ochSignal))
            .build();

    //Creation of treatment
    TrafficTreatment treatment = DefaultTrafficTreatment.builder()
            .add(Instructions.modL0Lambda(ochSignal))
            .add(Instructions.createOutput(outPort))
            .build();

    FlowRule.Builder flowBuilder = DefaultFlowRule.builder()
            .forDevice(deviceId)
            .fromApp(appId)
            .withPriority(priority)
            .withSelector(selector)
            .withTreatment(treatment);
    if (isPermanent) {
        flowBuilder.makePermanent();
    } else {
        flowBuilder.makeTemporary(timeout);
    }

    FlowRule flowRule = flowBuilder.build();
    flowRuleService.applyFlowRules(flowRule);

    log.info("Created connection from input port {} to output port {}",
            inPort.toLong(), outPort.toLong());

    return flowRule.id();
}