Java Code Examples for org.onosproject.net.flow.DefaultTrafficSelector#builder()

The following examples show how to use org.onosproject.net.flow.DefaultTrafficSelector#builder() . 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: OvsCorsaPipeline.java    From onos with Apache License 2.0 6 votes vote down vote up
protected void processVlanMplsTable(boolean install) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment
            .builder();
    FlowRuleOperations.Builder ops = FlowRuleOperations.builder();
    FlowRule rule;

    selector.matchVlanId(VlanId.ANY);
    treatment.transition(VLAN_TABLE);

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

    processFlowRule(true, rule, "Provisioned vlan/mpls table");
}
 
Example 2
Source File: K8sNetworkPolicyHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
private void setAllowNamespaceRulesBase(int tunnelId, int metadata,
                                        String direction, boolean install) {
    TrafficSelector.Builder sBuilder = DefaultTrafficSelector.builder();

    if (tunnelId != 0) {
        sBuilder.matchTunnelId(tunnelId);
    }

    sBuilder.matchMetadata(metadata);
    TrafficTreatment.Builder tBuilder = DefaultTrafficTreatment.builder()
            .setTunnelId(DEFAULT_SEGMENT_ID)
            .transition(ROUTING_TABLE);

    if (DIRECTION_INGRESS.equals(direction)) {
        setPolicyRulesBase(sBuilder, tBuilder, ACL_INGRESS_WHITE_TABLE, install);
    }
}
 
Example 3
Source File: K8sFlowRuleManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void setUpTableMissEntry(DeviceId deviceId, int table) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();

    treatment.drop();

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

    applyRule(flowRule, true);
}
 
Example 4
Source File: CorsaPipelineV3.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected Builder processVlanFiler(FilteringObjective filt, VlanIdCriterion vlan, PortCriterion port) {
    log.debug("adding rule for VLAN: {}", vlan.vlanId());
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    selector.matchVlanId(vlan.vlanId());
    selector.matchInPort(port.port());
            /* Static treatment for VLAN_CIRCUIT_TABLE */
    treatment.setVlanPcp(MAX_VLAN_PCP);
    treatment.setQueue(0);
    treatment.meter(MeterId.meterId(defaultMeterId.id())); /* use default meter (Green) */
    treatment.transition(L3_IF_MAC_DA_TABLE);
    return DefaultFlowRule.builder()
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(CONTROLLER_PRIORITY)
            .makePermanent()
            .forTable(VLAN_CIRCUIT_TABLE);
}
 
Example 5
Source File: HostLocationProvider.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Withdraw packet intercepts.
 */
private void withdrawIntercepts() {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    selector.matchEthType(Ethernet.TYPE_ARP);
    packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);

    // IPv6 Neighbor Solicitation packet.
    selector.matchEthType(Ethernet.TYPE_IPV6);
    selector.matchIPProtocol(IPv6.PROTOCOL_ICMP6);
    selector.matchIcmpv6Type(ICMP6.NEIGHBOR_SOLICITATION);
    packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);

    // IPv6 Neighbor Advertisement packet.
    selector.matchIcmpv6Type(ICMP6.NEIGHBOR_ADVERTISEMENT);
    packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
}
 
Example 6
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 7
Source File: TrafficSelectorCodec.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public TrafficSelector decode(ObjectNode json, CodecContext context) {
    final JsonCodec<Criterion> criterionCodec =
            context.codec(Criterion.class);

    JsonNode criteriaJson = json.get(CRITERIA);
    TrafficSelector.Builder builder = DefaultTrafficSelector.builder();
    if (criteriaJson != null) {
        IntStream.range(0, criteriaJson.size())
                .forEach(i -> builder.add(
                        criterionCodec.decode(get(criteriaJson, i),
                                context)));
    }
    return builder.build();
}
 
Example 8
Source File: DefaultL2TunnelHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates the forwarding objective for the termination.
 *
 * @param pwLabel    the pseudo wire label
 * @param tunnelId   the tunnel id
 * @param egressPort the egress port
 * @param nextId     the next step
 * @return the forwarding objective to support the termination
 */
private ForwardingObjective.Builder createTermFwdObjective(MplsLabel pwLabel, long tunnelId,
                                                           PortNumber egressPort, int nextId) {

    log.debug("Creating forwarding objective for termination for tunnel {} : pwLabel {}, egressPort {}, nextId {}",
             tunnelId, pwLabel, egressPort, nextId);
    TrafficSelector.Builder trafficSelector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder trafficTreatment = DefaultTrafficTreatment.builder();
    // The flow has to match on the pw label and bos
    trafficSelector.matchEthType(Ethernet.MPLS_UNICAST);
    trafficSelector.matchMplsLabel(pwLabel);
    trafficSelector.matchMplsBos(true);
    // The flow has to decrement ttl, restore ttl in
    // pop mpls, set tunnel id and port.
    trafficTreatment.decMplsTtl();
    trafficTreatment.copyTtlIn();
    trafficTreatment.popMpls();
    trafficTreatment.setTunnelId(tunnelId);
    trafficTreatment.setOutput(egressPort);

    return DefaultForwardingObjective
            .builder()
            .fromApp(srManager.appId())
            .makePermanent()
            .nextStep(nextId)
            .withPriority(SegmentRoutingService.DEFAULT_PRIORITY)
            .withSelector(trafficSelector.build())
            .withTreatment(trafficTreatment.build())
            .withFlag(VERSATILE);
}
 
Example 9
Source File: Ofdpa2Pipeline.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds TMAC rule for MPLS packets.
 *
 * @param ethCriterion dst mac matching
 * @param vidCriterion vlan id assigned to the port
 * @param ofdpaMatchVlanVid OFDPA vlan id matching
 * @param applicationId application id
 * @param pnum port number
 * @return TMAC rule for MPLS packets
 */
private FlowRule buildTmacRuleForMpls(EthCriterion ethCriterion,
                                      VlanIdCriterion vidCriterion,
                                      OfdpaMatchVlanVid ofdpaMatchVlanVid,
                                      ApplicationId applicationId,
                                      PortNumber pnum) {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    if (pnum != null) {
        if (matchInPortTmacTable()) {
            selector.matchInPort(pnum);
        } else {
            log.debug("Pipeline does not support IN_PORT matching in TMAC table, " +
                    "ignoring the IN_PORT criteria");
        }
    }
    if (vidCriterion != null) {
        if (requireVlanExtensions()) {
            selector.extension(ofdpaMatchVlanVid, deviceId);
        } else {
            selector.matchVlanId(vidCriterion.vlanId());
        }
    }
    selector.matchEthType(Ethernet.MPLS_UNICAST);
    selector.matchEthDst(ethCriterion.mac());
    treatment.transition(MPLS_TABLE_0);
    return DefaultFlowRule.builder()
            .forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(DEFAULT_PRIORITY)
            .fromApp(applicationId)
            .makePermanent()
            .forTable(TMAC_TABLE).build();
}
 
Example 10
Source File: ReactiveForwarding.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Request packet in via packet service.
 */
private void requestIntercepts() {
    TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
    selector.matchEthType(Ethernet.TYPE_IPV4);
    packetService.requestPackets(selector.build(), PacketPriority.REACTIVE, appId);

    selector.matchEthType(Ethernet.TYPE_IPV6);
    if (ipv6Forwarding) {
        packetService.requestPackets(selector.build(), PacketPriority.REACTIVE, appId);
    } else {
        packetService.cancelPackets(selector.build(), PacketPriority.REACTIVE, appId);
    }
}
 
Example 11
Source File: RoutingRulePopulator.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Populate or revoke a bridging rule on given deviceId that matches given vlanId,
 * and hostMAC connected to given port, and output to given port only when
 * vlan information is valid.
 *
 * @param deviceId device ID that host attaches to
 * @param portNum port number that host attaches to
 * @param hostMac mac address of the host connected to the switch port
 * @param vlanId Vlan ID configured on the switch port
 * @param popVlan true to pop Vlan tag at TrafficTreatment, false otherwise
 * @param install true to populate the objective, false to revoke
 */
// TODO Refactor. There are a lot of duplications between this method, populateBridging,
//      revokeBridging and bridgingFwdObjBuilder.
void updateBridging(DeviceId deviceId, PortNumber portNum, MacAddress hostMac,
                    VlanId vlanId, boolean popVlan, boolean install) {
    // Create host selector
    TrafficSelector.Builder sbuilder = DefaultTrafficSelector.builder();
    sbuilder.matchEthDst(hostMac);

    // Create host meta
    TrafficSelector.Builder mbuilder = DefaultTrafficSelector.builder();

    sbuilder.matchVlanId(vlanId);
    mbuilder.matchVlanId(vlanId);

    // Create host treatment
    TrafficTreatment.Builder tbuilder = DefaultTrafficTreatment.builder();
    tbuilder.immediate().setOutput(portNum);

    if (popVlan) {
        tbuilder.immediate().popVlan();
    }

    int portNextObjId = srManager.getPortNextObjectiveId(deviceId, portNum,
            tbuilder.build(), mbuilder.build(), install);
    if (portNextObjId != -1) {
        ForwardingObjective.Builder fob = DefaultForwardingObjective.builder()
                .withFlag(ForwardingObjective.Flag.SPECIFIC)
                .withSelector(sbuilder.build())
                .nextStep(portNextObjId)
                .withPriority(100)
                .fromApp(srManager.appId)
                .makePermanent();

        ObjectiveContext context = new DefaultObjectiveContext(
                (objective) -> log.debug("Brigding rule for {}/{} {}", hostMac, vlanId,
                        install ? "populated" : "revoked"),
                (objective, error) -> log.warn("Failed to {} bridging rule for {}/{}: {}",
                        install ? "populate" : "revoke", hostMac, vlanId, error));
        srManager.flowObjectiveService.forward(deviceId, install ? fob.add(context) : fob.remove(context));
    } else {
        log.warn("Failed to retrieve next objective for {}/{}", hostMac, vlanId);
    }
}
 
Example 12
Source File: OpticalOduIntentCompilerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Tests compile of OpticalOduIntent with allocation of TributarySlots.
 * Compile two ODUCLT ports (with CLT_10GBE), over OTU ports (with OTU2):
 *   - All TributarySlots are used
 */
@Test
public void test10GbeMultiplexOverOdu2() {

    intent = OpticalOduIntent.builder()
            .appId(APP_ID)
            .key(KEY1)
            .src(d1p3)
            .dst(d3p3)
            .signalType(D1P3.signalType())
            .bidirectional(false)
            .build();

    sut.activate();

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

    assertThat("key is inherited",
               compiled.stream().map(Intent::key).collect(Collectors.toList()),
               everyItem(is(intent.key())));

    Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();

    // 1st Device
    FlowRule rule1 = rules.stream()
            .filter(x -> x.deviceId().equals(device1.id()))
            .findFirst()
            .get();
    // validate SRC selector
    TrafficSelector.Builder selectorBuilder1 = DefaultTrafficSelector.builder();
    selectorBuilder1.matchInPort(d1p3.port());
    selectorBuilder1.add(Criteria.matchOduSignalType(OduSignalType.ODU2));
    assertThat(rule1.selector(), is(selectorBuilder1.build()));

    // validate SRC treatment  (without OduSignalId - all TributarySlots are used)
    TrafficTreatment.Builder treatmentBuilder1 = DefaultTrafficTreatment.builder();
    treatmentBuilder1.setOutput(d1p2.port());
    assertThat(rule1.treatment(), is(treatmentBuilder1.build()));

    // 2nd Device
    FlowRule rule2 = rules.stream()
            .filter(x -> x.deviceId().equals(device2.id()))
            .findFirst()
            .get();
    // validate SRC selector
    TrafficSelector.Builder selectorBuilder2 = DefaultTrafficSelector.builder();
    selectorBuilder2.matchInPort(d2p1.port());
    selectorBuilder2.add(Criteria.matchOduSignalType(OduSignalType.ODU2));
    assertThat(rule2.selector(), is(selectorBuilder2.build()));

    // validate SRC treatment  (without OduSignalId - all TributarySlots are used)
    TrafficTreatment.Builder treatmentBuilder2 = DefaultTrafficTreatment.builder();
    treatmentBuilder2.setOutput(d2p2.port());
    assertThat(rule2.treatment(), is(treatmentBuilder2.build()));


    // 3rd Device
    FlowRule rule3 = rules.stream()
            .filter(x -> x.deviceId().equals(device3.id()))
            .findFirst()
            .get();
    // validate DST selector (without OduSignalId - all TributarySlots are used)
    TrafficSelector.Builder selectorBuilder3 = DefaultTrafficSelector.builder();
    selectorBuilder3.matchInPort(d3p1.port());
    selectorBuilder3.add(Criteria.matchOduSignalType(OduSignalType.ODU2));
    assertThat(rule3.selector(), is(selectorBuilder3.build()));

    // validate DST treatment
    assertThat(rule3.treatment(), is(
            DefaultTrafficTreatment.builder().setOutput(d3p3.port()).build()
            ));

    rules.forEach(rule -> assertEquals("FlowRule priority is incorrect",
            intent.priority(), rule.priority()));

    sut.deactivate();
}
 
Example 13
Source File: Ofdpa2Pipeline.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * In the OF-DPA 2.0 pipeline, egress forwarding objectives go to the
 * egress tables.
 * @param fwd  the forwarding objective of type 'egress'
 * @return     a collection of flow rules to be sent to the switch. An empty
 *             collection may be returned if there is a problem in processing
 *             the flow rule
 */
protected Collection<FlowRule> processEgress(ForwardingObjective fwd) {
    log.debug("Processing egress forwarding objective:{} in dev:{}",
             fwd, deviceId);

    List<FlowRule> rules = new ArrayList<>();

    // Build selector
    TrafficSelector.Builder sb = DefaultTrafficSelector.builder();
    VlanIdCriterion vlanIdCriterion = (VlanIdCriterion) fwd.selector().getCriterion(Criterion.Type.VLAN_VID);
    if (vlanIdCriterion == null) {
        log.error("Egress forwarding objective:{} must include vlanId", fwd.id());
        fail(fwd, ObjectiveError.BADPARAMS);
        return rules;
    }

    Optional<Instruction> outInstr = fwd.treatment().allInstructions().stream()
                       .filter(instruction -> instruction instanceof OutputInstruction).findFirst();
    if (!outInstr.isPresent()) {
        log.error("Egress forwarding objective:{} must include output port", fwd.id());
        fail(fwd, ObjectiveError.BADPARAMS);
        return rules;
    }

    PortNumber portNumber = ((OutputInstruction) outInstr.get()).port();

    sb.matchVlanId(vlanIdCriterion.vlanId());
    OfdpaMatchActsetOutput actsetOutput = new OfdpaMatchActsetOutput(portNumber);
    sb.extension(actsetOutput, deviceId);

    sb.extension(new OfdpaMatchAllowVlanTranslation(ALLOW_VLAN_TRANSLATION), deviceId);

    // Build a flow rule for Egress VLAN Flow table
    TrafficTreatment.Builder tb = DefaultTrafficTreatment.builder();
    tb.transition(EGRESS_DSCP_PCP_REMARK_FLOW_TABLE);
    if (fwd.treatment() != null) {
        for (Instruction instr : fwd.treatment().allInstructions()) {
            if (instr instanceof L2ModificationInstruction &&
                    ((L2ModificationInstruction) instr).subtype() == L2SubType.VLAN_ID) {
                tb.immediate().add(instr);
            }
            if (instr instanceof L2ModificationInstruction &&
                    ((L2ModificationInstruction) instr).subtype() == L2SubType.VLAN_PUSH) {
                tb.immediate().pushVlan();
                EthType ethType = ((L2ModificationInstruction.ModVlanHeaderInstruction) instr).ethernetType();
                if (ethType.equals(EtherType.QINQ.ethType())) {
                    // Build a flow rule for Egress TPID Flow table
                    TrafficSelector tpidSelector = DefaultTrafficSelector.builder()
                            .extension(actsetOutput, deviceId)
                            .matchVlanId(VlanId.ANY).build();

                    TrafficTreatment tpidTreatment = DefaultTrafficTreatment.builder()
                            .extension(new Ofdpa3CopyField(COPY_FIELD_NBITS, COPY_FIELD_OFFSET,
                                                           COPY_FIELD_OFFSET, OXM_ID_VLAN_VID,
                                                           OXM_ID_PACKET_REG_1),
                                       deviceId)
                            .popVlan()
                            .pushVlan(EtherType.QINQ.ethType())
                            .extension(new Ofdpa3CopyField(COPY_FIELD_NBITS, COPY_FIELD_OFFSET,
                                                           COPY_FIELD_OFFSET, OXM_ID_PACKET_REG_1,
                                                           OXM_ID_VLAN_VID),
                                       deviceId)
                            .build();

                    FlowRule.Builder tpidRuleBuilder = DefaultFlowRule.builder()
                            .fromApp(fwd.appId())
                            .withPriority(fwd.priority())
                            .forDevice(deviceId)
                            .withSelector(tpidSelector)
                            .withTreatment(tpidTreatment)
                            .makePermanent()
                            .forTable(EGRESS_TPID_FLOW_TABLE);
                    rules.add(tpidRuleBuilder.build());
                }
            }
        }
    }

    FlowRule.Builder ruleBuilder = DefaultFlowRule.builder()
            .fromApp(fwd.appId())
            .withPriority(fwd.priority())
            .forDevice(deviceId)
            .withSelector(sb.build())
            .withTreatment(tb.build())
            .makePermanent()
            .forTable(EGRESS_VLAN_FLOW_TABLE);
    rules.add(ruleBuilder.build());
    return rules;
}
 
Example 14
Source File: DefaultGroupHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Returns the next objective of type simple associated with the mac/vlan on the
 * device, given the treatment. Different treatments to the same mac/vlan result
 * in different next objectives. If no such objective exists, this method
 * creates one (if requested) and returns the id. Optionally metadata can be passed in for
 * the creation of the objective. Typically this is used for L2 and L3 forwarding
 * to compute nodes and containers/VMs on the compute nodes directly attached
 * to the switch.
 *
 * @param macAddr the mac addr for the simple next objective
 * @param vlanId the vlan for the simple next objective
 * @param port port with which to create the Next Obj.
 * @param createIfMissing true if a next object should be created if not found
 * @return int if found or created, -1 if there are errors during the
 *          creation of the next objective.
 */
public int getMacVlanNextObjectiveId(MacAddress macAddr, VlanId vlanId, PortNumber port,
                                  boolean createIfMissing) {

    Integer nextId = macVlanNextObjStore
            .get(new MacVlanNextObjectiveStoreKey(deviceId, macAddr, vlanId));

    if (nextId != null) {
        return nextId;
    }

    log.debug("getMacVlanNextObjectiveId in device {}: Next objective id "
            + "not found for host : {}/{} .. {}", deviceId, macAddr, vlanId,
            (createIfMissing) ? "creating" : "aborting");

    if (!createIfMissing) {
        return -1;
    }

    MacAddress deviceMac;
    try {
        deviceMac = deviceConfig.getDeviceMac(deviceId);
    } catch (DeviceConfigNotFoundException e) {
        log.warn(e.getMessage() + " in getMacVlanNextObjectiveId");
        return -1;
    }

    // since we are creating now, port cannot be null
    if (port == null) {
       log.debug("getMacVlanNextObjectiveId : port information cannot be null "
                      + "for device {}, host {}/{}", deviceId, macAddr, vlanId);
       return -1;
    }

    TrafficSelector.Builder meta = DefaultTrafficSelector.builder();

    TrafficTreatment.Builder treatment = DefaultTrafficTreatment.builder();
    treatment.deferred()
            .setEthDst(macAddr)
            .setEthSrc(deviceMac)
            .setOutput(port);

    ConnectPoint connectPoint = new ConnectPoint(deviceId, port);
    VlanId untaggedVlan = srManager.interfaceService.getUntaggedVlanId(connectPoint);
    Set<VlanId> taggedVlans = srManager.interfaceService.getTaggedVlanId(connectPoint);
    VlanId nativeVlan = srManager.interfaceService.getNativeVlanId(connectPoint);

    // Adjust the meta according to VLAN configuration
    if (taggedVlans.contains(vlanId)) {
        treatment.setVlanId(vlanId);
    } else if (vlanId.equals(VlanId.NONE)) {
        if (untaggedVlan != null) {
            meta.matchVlanId(untaggedVlan);
        } else if (nativeVlan != null) {
            meta.matchVlanId(nativeVlan);
        } else {
            log.warn("Untagged nexthop {}/{} is not allowed on {} without untagged or native vlan",
                    macAddr, vlanId, connectPoint);
            return -1;
        }
    } else {
        log.warn("Tagged nexthop {}/{} is not allowed on {} without VLAN listed"
                + " in tagged vlan", macAddr, vlanId, connectPoint);
        return -1;
    }

    /* create missing next objective */
    nextId = createGroupFromMacVlan(macAddr, vlanId, treatment.build(), meta.build());
    if (nextId == null) {
        log.warn("getMacVlanNextObjectiveId: unable to create next obj"
                + "for dev:{} host:{}/{}", deviceId, macAddr, vlanId);
        return -1;
    }
    return nextId;
}
 
Example 15
Source File: OpticalOduIntentCompilerTest.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Tests compile of OpticalOduIntent with allocation of TributarySlots.
 * Compile two ODUCLT ports (with CLT_1GBE), over OTU ports (with OTU2):
 *   - only one TributarySlot is used
 */
@Test
public void test1GbeMultiplexOverOdu2() {

    intent = OpticalOduIntent.builder()
            .appId(APP_ID)
            .key(KEY1)
            .src(d1p1)
            .dst(d3p2)
            .signalType(D1P1.signalType())
            .bidirectional(false)
            .build();

    sut.activate();

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

    assertThat("key is inherited",
               compiled.stream().map(Intent::key).collect(Collectors.toList()),
               everyItem(is(intent.key())));

    Collection<FlowRule> rules = ((FlowRuleIntent) compiled.get(0)).flowRules();

    // 1st Device
    FlowRule rule1 = rules.stream()
            .filter(x -> x.deviceId().equals(device1.id()))
            .findFirst()
            .get();
    // validate SRC selector
    TrafficSelector.Builder selectorBuilder1 = DefaultTrafficSelector.builder();
    selectorBuilder1.matchInPort(d1p1.port());
    selectorBuilder1.add(Criteria.matchOduSignalType(OduSignalType.ODU0));
    assertThat(rule1.selector(), is(selectorBuilder1.build()));

    // validate SRC treatment  (with OduSignalId, where 1 TributarySlot is used)
    TrafficTreatment.Builder treatmentBuilder1 = DefaultTrafficTreatment.builder();
    Set<TributarySlot> slots = new HashSet<>();
    slots.add(TributarySlot.of(1));
    OduSignalId oduSignalId = OduSignalUtils.buildOduSignalId(OduSignalType.ODU2, slots);
    treatmentBuilder1.add(Instructions.modL1OduSignalId(oduSignalId));
    treatmentBuilder1.setOutput(d1p2.port());
    assertThat(rule1.treatment(), is(treatmentBuilder1.build()));

    // 2nd Device
    FlowRule rule2 = rules.stream()
            .filter(x -> x.deviceId().equals(device2.id()))
            .findFirst()
            .get();
    // validate SRC selector
    TrafficSelector.Builder selectorBuilder2 = DefaultTrafficSelector.builder();
    selectorBuilder2.matchInPort(d2p1.port());
    selectorBuilder2.add(Criteria.matchOduSignalType(OduSignalType.ODU0));
    selectorBuilder2.add(Criteria.matchOduSignalId(oduSignalId));
    assertThat(rule2.selector(), is(selectorBuilder2.build()));

    // validate SRC treatment  (with OduSignalId, where 1 TributarySlot is used)
    TrafficTreatment.Builder treatmentBuilder2 = DefaultTrafficTreatment.builder();
    treatmentBuilder2.add(Instructions.modL1OduSignalId(oduSignalId));
    treatmentBuilder2.setOutput(d2p2.port());
    assertThat(rule2.treatment(), is(treatmentBuilder2.build()));


    // 3rd Device
    FlowRule rule3 = rules.stream()
            .filter(x -> x.deviceId().equals(device3.id()))
            .findFirst()
            .get();
    // validate DST selector (with OduSignalId, where the same TributarySlot is used)
    TrafficSelector.Builder selectorBuilder3 = DefaultTrafficSelector.builder();
    selectorBuilder3.matchInPort(d3p1.port());
    selectorBuilder3.add(Criteria.matchOduSignalType(OduSignalType.ODU0));
    selectorBuilder3.add(Criteria.matchOduSignalId(oduSignalId));
    assertThat(rule3.selector(), is(selectorBuilder3.build()));

    // validate DST treatment
    assertThat(rule3.treatment(), is(
            DefaultTrafficTreatment.builder().setOutput(d3p2.port()).build()
            ));

    rules.forEach(rule -> assertEquals("FlowRule priority is incorrect",
            intent.priority(), rule.priority()));

    sut.deactivate();
}
 
Example 16
Source File: RoutingRulePopulator.java    From onos with Apache License 2.0 4 votes vote down vote up
private TrafficSelector.Builder buildIpv6Selector() {
    TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
    selectorBuilder.matchEthType(Ethernet.TYPE_IPV6);
    return selectorBuilder;
}
 
Example 17
Source File: XconnectManager.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Cleans up VLAN L2 multicast group on given deviceId. ACL rules for the group will also be deleted.
 * Normally multicast group is not removed if it contains access ports; which can be forced
 * by "force" flag
 *
 * @param deviceId Device ID
 * @param pairPort Pair port number
 * @param vlanId   VLAN ID
 * @param force    Forceful removal
 */
private void cleanupL2MulticastRule(DeviceId deviceId, PortNumber pairPort, VlanId vlanId, boolean force) {

    // Ensure enough rights to program pair device
    if (!srService.shouldProgram(deviceId)) {
        log.debug("Abort cleanup L2Multicast {}-{}: {}", deviceId, vlanId, ERROR_NOT_LEADER);
        return;
    }

    VlanNextObjectiveStoreKey key = new VlanNextObjectiveStoreKey(deviceId, vlanId);

    // Ensure L2 multicast group doesn't contain access ports
    if (hasAccessPortInMulticastGroup(key, pairPort) && !force) {
        return;
    }

    // Load L2 multicast group details
    int vlanMulticastNextId = getMulticastGroupNextObjectiveId(key);
    if (vlanMulticastNextId == -1) {
        return;
    }

    // Step 1 : Clear ACL rule; selector = vlan + pair-port, output = vlan L2 multicast group
    TrafficSelector.Builder l2MulticastSelector = DefaultTrafficSelector.builder();
    l2MulticastSelector.matchEthType(Ethernet.TYPE_VLAN);
    l2MulticastSelector.matchInPort(pairPort);
    l2MulticastSelector.matchVlanId(vlanId);
    ForwardingObjective.Builder vlanMulticastForwardingObj = DefaultForwardingObjective.builder()
            .withFlag(ForwardingObjective.Flag.VERSATILE)
            .nextStep(vlanMulticastNextId)
            .withSelector(l2MulticastSelector.build())
            .withPriority(100)
            .fromApp(srService.appId())
            .makePermanent();
    ObjectiveContext context = new DefaultObjectiveContext(
            (objective) -> log.debug("L2 multicasting rule for device {}, port/vlan {}/{} deleted", deviceId,
                                     pairPort, vlanId),
            (objective, error) -> log.warn("Failed to delete L2 multicasting rule for device {}, " +
                                                   "ports/vlan {}/{}: {}", deviceId, pairPort, vlanId, error));
    flowObjectiveService.forward(deviceId, vlanMulticastForwardingObj.remove(context));

    // Step 2 : Clear L2 multicast group associated with vlan
    NextObjective.Builder l2MulticastGroupBuilder = DefaultNextObjective
            .builder()
            .withId(vlanMulticastNextId)
            .withType(NextObjective.Type.BROADCAST)
            .fromApp(srService.appId())
        .withMeta(DefaultTrafficSelector.builder()
                      .matchVlanId(vlanId)
                      .matchEthDst(MacAddress.IPV4_MULTICAST).build())
            .addTreatment(DefaultTrafficTreatment.builder().popVlan().setOutput(pairPort).build());
    context = new DefaultObjectiveContext(
            (objective) ->
                    log.debug("L2 multicast group with NextObject Id {} deleted on {} for subnet {} ",
                              vlanMulticastNextId, deviceId, vlanId),
            (objective, error) ->
                    log.warn("L2 multicast group with NextObject Id {} failed to delete on {} for subnet {} : {}",
                             vlanMulticastNextId, deviceId, vlanId, error)
    );
    flowObjectiveService.next(deviceId, l2MulticastGroupBuilder.remove(context));

    // Finally clear store.
    removeMulticastGroup(key);
}
 
Example 18
Source File: TroubleshootManager.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Applies an instruction to the packet in the form of a selector.
 *
 * @param newSelector the packet selector
 * @param instruction the instruction to be translated
 * @return the new selector with the applied instruction
 */
private Builder translateInstruction(Builder newSelector, Instruction instruction) {
    log.debug("Translating instruction {}", instruction);
    log.debug("New Selector {}", newSelector.build());
    //TODO add as required
    Criterion criterion = null;
    switch (instruction.type()) {
        case L2MODIFICATION:
            L2ModificationInstruction l2Instruction = (L2ModificationInstruction) instruction;
            switch (l2Instruction.subtype()) {
                case VLAN_ID:
                    ModVlanIdInstruction vlanIdInstruction =
                            (ModVlanIdInstruction) instruction;
                    VlanId id = vlanIdInstruction.vlanId();
                    criterion = Criteria.matchVlanId(id);
                    break;
                case VLAN_POP:
                    criterion = Criteria.matchVlanId(VlanId.NONE);
                    break;
                case MPLS_PUSH:
                    ModMplsHeaderInstruction mplsEthInstruction =
                            (ModMplsHeaderInstruction) instruction;
                    criterion = Criteria.matchEthType(mplsEthInstruction.ethernetType().toShort());
                    break;
                case MPLS_POP:
                    ModMplsHeaderInstruction mplsPopInstruction =
                            (ModMplsHeaderInstruction) instruction;
                    criterion = Criteria.matchEthType(mplsPopInstruction.ethernetType().toShort());

                    //When popping MPLS we remove label and BOS
                    TrafficSelector temporaryPacket = newSelector.build();
                    if (temporaryPacket.getCriterion(Criterion.Type.MPLS_LABEL) != null) {
                        Builder noMplsSelector = DefaultTrafficSelector.builder();
                        temporaryPacket.criteria().stream().filter(c -> {
                            return !c.type().equals(Criterion.Type.MPLS_LABEL) &&
                                    !c.type().equals(Criterion.Type.MPLS_BOS);
                        }).forEach(noMplsSelector::add);
                        newSelector = noMplsSelector;
                    }

                    break;
                case MPLS_LABEL:
                    ModMplsLabelInstruction mplsLabelInstruction =
                            (ModMplsLabelInstruction) instruction;
                    criterion = Criteria.matchMplsLabel(mplsLabelInstruction.label());
                    newSelector.matchMplsBos(true);
                    break;
                case ETH_DST:
                    ModEtherInstruction modEtherDstInstruction =
                            (ModEtherInstruction) instruction;
                    criterion = Criteria.matchEthDst(modEtherDstInstruction.mac());
                    break;
                case ETH_SRC:
                    ModEtherInstruction modEtherSrcInstruction =
                            (ModEtherInstruction) instruction;
                    criterion = Criteria.matchEthSrc(modEtherSrcInstruction.mac());
                    break;
                default:
                    log.debug("Unsupported L2 Instruction");
                    break;
            }
            break;
        default:
            log.debug("Unsupported Instruction");
            break;
    }
    if (criterion != null) {
        log.debug("Adding criterion {}", criterion);
        newSelector.add(criterion);
    }
    return newSelector;
}
 
Example 19
Source File: RoutingRulePopulator.java    From onos with Apache License 2.0 4 votes vote down vote up
private TrafficSelector.Builder buildIpv4Selector() {
    TrafficSelector.Builder selectorBuilder = DefaultTrafficSelector.builder();
    selectorBuilder.matchEthType(Ethernet.TYPE_IPV4);
    return selectorBuilder;
}
 
Example 20
Source File: SpringOpenTTP.java    From onos with Apache License 2.0 4 votes vote down vote up
protected List<FlowRule> processVlanIdFilter(VlanIdCriterion vlanIdCriterion,
                                             FilteringObjective filt,
                                             VlanId assignedVlan, VlanId explicitlyAssignedVlan, VlanId pushedVlan,
                                             boolean pushVlan, boolean popVlan,
                                             ApplicationId applicationId) {
    List<FlowRule> rules = new ArrayList<>();
    log.debug("adding rule for VLAN: {}", vlanIdCriterion.vlanId());
    TrafficSelector.Builder selector = DefaultTrafficSelector
            .builder();
    TrafficTreatment.Builder treatment = DefaultTrafficTreatment
            .builder();
    PortCriterion p = (PortCriterion) filt.key();
    if (vlanIdCriterion.vlanId() != VlanId.NONE) {
        selector.matchVlanId(vlanIdCriterion.vlanId());
        selector.matchInPort(p.port());
        if (popVlan) {
            // Pop outer tag
            treatment.immediate().popVlan();
        }
        if (explicitlyAssignedVlan != null && (!popVlan || !vlanIdCriterion.vlanId().equals(assignedVlan))) {
            // Modify VLAN ID on single tagged packet or modify remaining tag after popping
            // In the first case, do not set VLAN ID again to the already existing value
            treatment.immediate().setVlanId(explicitlyAssignedVlan);
        }
        if (pushVlan) {
            // Push new tag
            treatment.immediate().pushVlan().setVlanId(pushedVlan);
        }
    } else {
        selector.matchInPort(p.port());
        treatment.immediate().pushVlan().setVlanId(assignedVlan);
    }
    treatment.transition(tmacTableId);
    FlowRule rule = DefaultFlowRule.builder().forDevice(deviceId)
            .withSelector(selector.build())
            .withTreatment(treatment.build())
            .withPriority(filt.priority()).fromApp(applicationId)
            .makePermanent().forTable(vlanTableId).build();
    rules.add(rule);

    return rules;
}