Java Code Examples for org.onosproject.net.PortNumber#equals()

The following examples show how to use org.onosproject.net.PortNumber#equals() . 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: OfdpaGroupHandlerUtility.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a list of all indices in the allActiveKeys list (that represents
 * a group) if the list element (a bucket or group-chain) has treatments
 * that match the given outport and label.
 *
 * @param allActiveKeys the representation of the group
 * @param groupService groups service for querying group information
 * @param deviceId the device id for the device that contains the group
 * @param portToMatch the port to match in the group buckets
 * @param labelToMatch the MPLS label-id to match in the group buckets
 * @return a list of indexes in the allActiveKeys list where the list element
 *         has treatments that match the given portToMatch and labelToMatch.
 *         Could be empty if no list elements were found to match the given
 *         port and label.
 */
public static List<Integer> existingPortAndLabel(
                                           List<Deque<GroupKey>> allActiveKeys,
                                           GroupService groupService,
                                           DeviceId deviceId,
                                           PortNumber portToMatch,
                                           int labelToMatch) {
    List<Integer> indices = new ArrayList<>();
    int index = 0;
    for (Deque<GroupKey> keyChain : allActiveKeys) {
        GroupKey ifaceGroupKey = keyChain.peekLast();
        Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
        if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
            PortNumber portNumber = readOutPortFromTreatment(
               ifaceGroup.buckets().buckets().iterator().next().treatment());
            if (portNumber != null && portNumber.equals(portToMatch)) {
                // check for label in the 2nd group of this chain
                GroupKey secondKey = (GroupKey) keyChain.toArray()[1];
                Group secondGroup = groupService.getGroup(deviceId, secondKey);
                if (secondGroup != null &&
                        !secondGroup.buckets().buckets().isEmpty()) {
                    int label = readLabelFromTreatment(
                                    secondGroup.buckets().buckets()
                                    .iterator().next().treatment());
                    if (label == labelToMatch) {
                        indices.add(index);
                    }
                }
            }
        }
        index++;
    }

    return indices;
}
 
Example 2
Source File: PipelineInterpreterImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<PiPacketOperation> mapOutboundPacket(OutboundPacket packet)
        throws PiInterpreterException {

    TrafficTreatment treatment = packet.treatment();

    // We support only packet-out with OUTPUT instructions.
    if (treatment.allInstructions().size() != 1 &&
            treatment.allInstructions().get(0).type() != OUTPUT) {
        throw new PiInterpreterException(
                "Treatment not supported: " + treatment.toString());
    }

    Instruction instruction = treatment.allInstructions().get(0);
    PortNumber port = ((OutputInstruction) instruction).port();
    List<PiPacketOperation> piPacketOps = Lists.newArrayList();

    if (!port.isLogical()) {
        piPacketOps.add(createPiPacketOp(packet.data(), port.toLong()));
    } else if (port.equals(FLOOD)) {
        // Since mytunnel.p4 does not support flooding, we create a packet
        // operation for each switch port.
        DeviceService deviceService = handler().get(DeviceService.class);
        DeviceId deviceId = packet.sendThrough();
        for (Port p : deviceService.getPorts(deviceId)) {
            piPacketOps.add(createPiPacketOp(packet.data(), p.number().toLong()));
        }
    } else {
        throw new PiInterpreterException(format(
                "Output on logical port '%s' not supported", port));
    }

    return piPacketOps;
}
 
Example 3
Source File: LinkHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if the given link should be avoided in routing calculations by
 * policy or design.
 *
 * @param link the infrastructure link being queried
 * @return true if link should be avoided
 */
boolean avoidLink(Link link) {
    // XXX currently only avoids all pair-links. In the future can be
    // extended to avoid any generic link
    DeviceId src = link.src().deviceId();
    PortNumber srcPort = link.src().port();
    DeviceConfiguration devConfig = srManager.deviceConfiguration;
    if (devConfig == null || !devConfig.isConfigured(src)) {
        log.warn("Device {} not configured..cannot avoid link {}", src,
                 link);
        return false;
    }
    DeviceId pairDev;
    PortNumber pairLocalPort, pairRemotePort = null;
    try {
        pairDev = devConfig.getPairDeviceId(src);
        pairLocalPort = devConfig.getPairLocalPort(src);
        if (pairDev != null) {
            pairRemotePort = devConfig
                    .getPairLocalPort(pairDev);
        }
    } catch (DeviceConfigNotFoundException e) {
        log.warn("Pair dev for dev {} not configured..cannot avoid link {}",
                 src, link);
        return false;
    }

    return srcPort.equals(pairLocalPort)
            && link.dst().deviceId().equals(pairDev)
            && link.dst().port().equals(pairRemotePort);
}
 
Example 4
Source File: BasicInterpreterImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
private PiAction outputPiAction(OutputInstruction outInstruction, PiActionId piActionId)
        throws PiInterpreterException {
    PortNumber port = outInstruction.port();
    if (!port.isLogical()) {
        return PiAction.builder()
                .withId(piActionId)
                .withParameter(new PiActionParam(PORT, port.toLong()))
                .build();
    } else if (port.equals(CONTROLLER)) {
        return PiAction.builder().withId(INGRESS_TABLE0_CONTROL_SEND_TO_CPU).build();
    } else {
        throw new PiInterpreterException(format(
                "Egress on logical port '%s' not supported", port));
    }
}
 
Example 5
Source File: FabricInterpreter.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Integer> mapLogicalPortNumber(PortNumber port) {
    if (!port.equals(CONTROLLER)) {
        return Optional.empty();
    }
    return capabilities.cpuPort();
}
 
Example 6
Source File: OplinkOpticalProtectionSwitchConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private int getActiveIndex(List<TransportEndpointState> pathStates, PortNumber activePort) {
    int activeIndex = 0;
    for (TransportEndpointState state : pathStates) {
        if (activePort.equals(state.description().output().connectPoint().port())) {
            return activeIndex;
        }
        ++activeIndex;
    }
    return ProtectedTransportEndpointState.ACTIVE_UNKNOWN;
}
 
Example 7
Source File: OplinkOpticalProtectionSwitchConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private TransportEndpointState buildTransportEndpointState(
        DeviceId id, PortNumber port, PortNumber activePort) {
    String status = port.equals(activePort) ? STATUS_IN_SERVICE : STATUS_OUT_SERVICE;
    Map<String, String> attributes = new HashMap<>();
    attributes.put(INPUT_PORT_STATUS, status);
    return TransportEndpointState.builder()
            .withId(TransportEndpointId.of(port.name()))
            .withDescription(buildTransportEndpointDescription(id, port))
            .addAttributes(attributes)
            .build();
}
 
Example 8
Source File: OplinkOpticalPowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean setChannelTargetPower(PortNumber port, OchSignal channel, long power) {
    log.debug("Set port{} channel{} attenuation.", port, channel.channelSpacing());
    FlowRuleService service = handler().get(FlowRuleService.class);
    Iterable<FlowEntry> entries = service.getFlowEntries(data().deviceId());
    for (FlowEntry entry : entries) {
        OplinkCrossConnect crossConnect = OplinkOpticalUtility.fromFlowRule(this, entry);
        // The channel port might be input port or output port.
        if ((port.equals(crossConnect.getInPort()) || port.equals(crossConnect.getOutPort())) &&
                channel.spacingMultiplier() == crossConnect.getChannel()) {
            log.debug("Flow is found, modify the flow with attenuation.");
            // Modify attenuation in treatment
            TrafficTreatment treatment = DefaultTrafficTreatment.builder()
                    .setOutput(crossConnect.getOutPort())
                    .extension(new OplinkAttenuation((int) power), data().deviceId())
                    .build();
            // Apply the new flow rule
            service.applyFlowRules(DefaultFlowRule.builder()
                    .forDevice(data().deviceId())
                    .makePermanent()
                    .withSelector(entry.selector())
                    .withTreatment(treatment)
                    .withPriority(entry.priority())
                    .withCookie(entry.id().value())
                    .build());
            return true;
        }
    }
    return false;
}
 
Example 9
Source File: OplinkPowerConfigUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Find matching flow on device.
 *
 * @param portNum the port number
 * @param och channel signal
 * @return flow entry
 */
private FlowEntry findFlow(PortNumber portNum, OchSignal och) {
    final DriverHandler handler = behaviour.handler();
    FlowRuleService service = handler.get(FlowRuleService.class);
    Iterable<FlowEntry> flowEntries = service.getFlowEntries(handler.data().deviceId());

    // Return first matching flow
    for (FlowEntry entry : flowEntries) {
        TrafficSelector selector = entry.selector();
        OchSignalCriterion entrySigid =
                (OchSignalCriterion) selector.getCriterion(Criterion.Type.OCH_SIGID);
        // Check channel
        if (entrySigid != null && och.equals(entrySigid.lambda())) {
            // Check input port
            PortCriterion entryPort =
                    (PortCriterion) selector.getCriterion(Criterion.Type.IN_PORT);
            if (entryPort != null && portNum.equals(entryPort.port())) {
                return entry;
            }

            // Check output port
            TrafficTreatment treatment = entry.treatment();
            for (Instruction instruction : treatment.allInstructions()) {
                if (instruction.type() == Instruction.Type.OUTPUT &&
                    ((Instructions.OutputInstruction) instruction).port().equals(portNum)) {
                    return entry;
                }
            }
        }
    }
    log.warn("No matching flow found");
    return null;
}
 
Example 10
Source File: TapiFlowRuleProgrammableTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Port getPort(DeviceId deviceId, PortNumber portNumber) {
    if (portNumber.equals(ONE)) {
        return PORT_IN;
    } else {
        return PORT_OUT;
    }
}
 
Example 11
Source File: PortQueryVlansCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
private String portName(PortNumber port) {
    return port.equals(PortNumber.LOCAL) ? "local" : port.toString();
}
 
Example 12
Source File: DefaultCheckLoop.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Process one output instruction.
 *
 * Params are passed from processOneInstruction directly,
 * and obey the same rules.
 *
 * @param instOne the instruction to be processed
 * @param currentDeviceId id of the device we are now in
 * @param initPkt the packet before being copied
 * @param matchedPkt the packet which matched the flow entry,
 *                   to which this instruction belongs
 * @param isFindLoop indicate if it is invoked by findLoop method
 * @param firstEntry the flow entry from which the packet is generated
 * @return true, if a loop is discovered;
 *         false, 1. invoked by matchDeviceFlows method, and detected no loop;
 *                2. invoked by findLoop method
 */
private boolean processOneOutputInstruction(Instruction instOne,
                                            DeviceId currentDeviceId,
                                            TsLoopPacket initPkt,
                                            TsLoopPacket matchedPkt,
                                            boolean isFindLoop,
                                            FlowEntry firstEntry) {
    OutputInstruction instOutput = (OutputInstruction) instOne;
    PortNumber instPort = instOutput.port();

    if (!instPort.isLogical()) {
        // single OUTPUT - NIC or normal port

        Set<Link> dstLink = tsGetEgressLinks(
                new ConnectPoint(currentDeviceId, instPort));
        if (!dstLink.isEmpty()) {

            // TODO - now, just deal with the first destination.
            // will there be more destinations?

            Link dstThisLink = dstLink.iterator().next();
            ConnectPoint dstPoint = dstThisLink.dst();

            // check output to devices only (output to a host is normal)
            if (isDevice(dstPoint)) {
                PortCriterion oldInPort =
                        updatePktInportPerHop(matchedPkt, dstPoint);
                matchedPkt.pushPathLink(dstThisLink);
                TsLoopPacket newNewPkt = matchedPkt.copyPacketMatch();

                boolean loopFound =
                        matchDeviceFlows(dstPoint.deviceId(), newNewPkt);
                if (isFindLoop) {
                    if (loopFound) {
                        loops.add(newNewPkt);
                        updateExcludeDeviceSet(newNewPkt);
                    }
                    matchedPkt.resetLinkFlow(firstEntry);
                } else {
                    if (loopFound) {
                        initPkt.handInLoopMatch(newNewPkt);
                        return true;
                    }
                    matchedPkt.popPathLink();
                }
                restorePktInportPerHop(matchedPkt, oldInPort);
            }
        } else {
            if (!isFindLoop) {
                //TODO - NEED
                log.warn("no link connecting at device {}, port {}",
                        currentDeviceId, instPort);
            }
        }
    } else if (instPort.equals(PortNumber.IN_PORT)) {
        //TODO - in the future,
        // we may need to resolve this condition 1
        log.warn("can not handle {} port now.", PortNumber.IN_PORT);
    } else if (instPort.equals(PortNumber.NORMAL) ||
            instPort.equals(PortNumber.FLOOD) ||
            instPort.equals(PortNumber.ALL)) {
        //TODO - in the future,
        // we may need to resolve this condition 2
        log.warn("can not handle {}/{}/{} now.",
                PortNumber.NORMAL, PortNumber.FLOOD, PortNumber.ALL);
    }
    return false;
}
 
Example 13
Source File: RoadmCrossConnectCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * This function drops XC installed on the device, which is matching parsed criteria.
 * Takes as an input "global" parameters (passed by user through the console).
 * @return - returns number of the rules that were dropped.
 */
protected FlowId dropRule() {

    // Preparing parameters
    DeviceId device = DeviceId.deviceId(deviceId);
    PortNumber inPort = PortNumber.portNumber(srcPort);
    PortNumber outPort = PortNumber.portNumber(dstPort);

    // Creating some variables
    OchSignal ochSignal = null;
    PortNumber inputPortNumber = null;
    PortNumber outputPortNumber = null;

    // Main idea: Go over all flow rules (read out from the storage) of current device and
    // filter them based on input and output port with respect to OchSignal
    FlowRuleService fr = AbstractShellCommand.get(FlowRuleService.class);
    Iterable<FlowEntry> flowRules = fr.getFlowEntries(device);
    FlowId flowId = null;
    OchSignal referenceSignal = createOchSignal(freq, sw, gridType, channelSpacing);


    for (FlowEntry flowRule : flowRules) {

        // Taken from FlowRuleParser
        for (Criterion c : flowRule.selector().criteria()) {
            if (c instanceof OchSignalCriterion) {
                ochSignal = ((OchSignalCriterion) c).lambda();
            }
            if (c instanceof PortCriterion) {
                inputPortNumber = ((PortCriterion) c).port(); // obtain input port
            }
        }
        for (Instruction i : flowRule.treatment().immediate()) {
            if (i instanceof
                    L0ModificationInstruction.ModOchSignalInstruction) {
                ochSignal =
                        ((L0ModificationInstruction.ModOchSignalInstruction) i)
                                .lambda();
            }
            if (i instanceof Instructions.OutputInstruction) {
                outputPortNumber = ((Instructions.OutputInstruction) i).port(); // obtain output port
            }
        }

        // If we found match, then let's delete this rule
        if ((ochSignal.centralFrequency().equals(referenceSignal.centralFrequency()))
                & (ochSignal.slotWidth().equals(referenceSignal.slotWidth()))
                & (inputPortNumber.equals(inPort)) & (outputPortNumber.equals(outPort))) {
            flowId = flowRule.id();

            RoadmService manager = AbstractShellCommand.get(RoadmService.class);
            manager.removeConnection(device, flowId);
            print("Dropping existing XC from the device %s", deviceId);
            return flowId;
        }
    }

    return null;
}
 
Example 14
Source File: DeviceConfiguration.java    From onos with Apache License 2.0 4 votes vote down vote up
public boolean isPairLocalPort(DeviceId devId, PortNumber pnum) {
    return pnum.equals(srManager.getPairLocalPort(devId).orElse(null));
}
 
Example 15
Source File: OfdpaGroupHandlerUtility.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get indices to remove comparing next group with next objective.
 *
 * @param allActiveKeys the representation of the group
 * @param nextObjective the next objective to verify
 * @param groupService groups service for querying group information
 * @param deviceId the device id for the device that contains the group
 * @return a list of indexes in the allActiveKeys to remove.
 */
public static List<Integer> indicesToRemoveFromNextGroup(List<Deque<GroupKey>> allActiveKeys,
                                                   NextObjective nextObjective,
                                                   GroupService groupService,
                                                   DeviceId deviceId) {
    List<Integer> indicesToRemove = Lists.newArrayList();
    int index = 0;
    // Iterate over the chain in the next data
    for (Deque<GroupKey> keyChain : allActiveKeys) {
        // Valid chain should have at least two elements
        if (keyChain.size() >= 2) {
            // Get last group (l2if) and retrieve port number
            GroupKey ifaceGroupKey = keyChain.peekLast();
            Group ifaceGroup = groupService.getGroup(deviceId, ifaceGroupKey);
            if (ifaceGroup != null && !ifaceGroup.buckets().buckets().isEmpty()) {
                PortNumber portNumber = readOutPortFromTreatment(
                        ifaceGroup.buckets().buckets().iterator().next().treatment());
                // If there is not a port number continue
                if (portNumber != null) {
                    // check for label in the 2nd group of this chain
                    GroupKey secondKey = (GroupKey) keyChain.toArray()[1];
                    Group secondGroup = groupService.getGroup(deviceId, secondKey);
                    // If there is not a second group or there are no buckets continue
                    if (secondGroup != null && !secondGroup.buckets().buckets().isEmpty()) {
                        // Get label or -1
                        int label = readLabelFromTreatment(
                                secondGroup.buckets().buckets()
                                        .iterator().next().treatment());
                        // Iterate over the next treatments looking for the port and the label
                        boolean matches = false;
                        for (TrafficTreatment t : nextObjective.next()) {
                            PortNumber tPort = readOutPortFromTreatment(t);
                            int tLabel = readLabelFromTreatment(t);
                            if (tPort != null && tPort.equals(portNumber) && tLabel == label) {
                                // We found it, exit
                                matches = true;
                                break;
                            }
                        }
                        // Not found, we have to remove it
                        if (!matches) {
                            indicesToRemove.add(index);
                        }
                    }
                }
            }
        }
        index++;
    }
    return indicesToRemove;
}
 
Example 16
Source File: PipelineInterpreterImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public PiAction mapTreatment(TrafficTreatment treatment, PiTableId piTableId)
        throws PiInterpreterException {

    if (piTableId != TABLE_L2_FWD_ID) {
        throw new PiInterpreterException(
                "Can map treatments only for 't_l2_fwd' table");
    }

    if (treatment.allInstructions().size() == 0) {
        // 0 instructions means "NoAction"
        return PiAction.builder().withId(ACT_ID_NOP).build();
    } else if (treatment.allInstructions().size() > 1) {
        // We understand treatments with only 1 instruction.
        throw new PiInterpreterException("Treatment has multiple instructions");
    }

    // Get the first and only instruction.
    Instruction instruction = treatment.allInstructions().get(0);

    if (instruction.type() != OUTPUT) {
        // We can map only instructions of type OUTPUT.
        throw new PiInterpreterException(format(
                "Instruction of type '%s' not supported", instruction.type()));
    }

    OutputInstruction outInstruction = (OutputInstruction) instruction;
    PortNumber port = outInstruction.port();
    if (!port.isLogical()) {
        return PiAction.builder()
                .withId(ACT_ID_SET_EGRESS_PORT)
                .withParameter(new PiActionParam(
                        ACT_PARAM_ID_PORT, copyFrom(port.toLong())))
                .build();
    } else if (port.equals(CONTROLLER)) {
        return PiAction.builder()
                .withId(ACT_ID_SEND_TO_CPU)
                .build();
    } else {
        throw new PiInterpreterException(format(
                "Output on logical port '%s' not supported", port));
    }
}
 
Example 17
Source File: PortCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
private String portName(PortNumber port) {
    return port.equals(PortNumber.LOCAL) ? PORT_NAME_LOCAL : port.toString();
}