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

The following examples show how to use org.onosproject.net.PortNumber#toLong() . 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: OpenFlowLambdaQuery.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Set<OchSignal> queryLambdas(PortNumber port) {
    Set<OchSignal> signals = new LinkedHashSet<>();
    for (OFPortDesc pd : getPortDescs()) {
        if (pd.getPortNo().getPortNumber() == port.toLong()) {
            for (OFPortDescProp prop : pd.getProperties()) {
                if (prop instanceof OFPortDescPropOptical) {
                    OFPortDescPropOptical oprop = (OFPortDescPropOptical) prop;
                    long txMin = oprop.getTxMinFreqLmda();
                    long txMax = oprop.getTxMaxFreqLmda();
                    long txGrid = oprop.getTxGridFreqLmda();
                    signals.addAll(signals(txMin, txMax, txGrid));
                    long rxMin = oprop.getRxMinFreqLmda();
                    long rxMax = oprop.getRxMaxFreqLmda();
                    long rxGrid = oprop.getRxGridFreqLmda();
                    signals.addAll(signals(rxMin, rxMax, rxGrid));
                }
            }
        }
    }
    return signals;

}
 
Example 2
Source File: OpenFlowPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public Optional<Range<Double>> getTargetPowerRange(PortNumber port, T component) {
    for (OFPortDesc pd : getPortDescs()) {
        if (pd.getPortNo().getPortNumber() == port.toLong()) {
            for (OFPortDescProp prop : pd.getProperties()) {
                if (prop instanceof OFPortDescPropOptical) {
                    OFPortDescPropOptical oprop = (OFPortDescPropOptical) prop;
                    double txMin = oprop.getTxPwrMin();
                    double txMax = oprop.getTxPwrMax();
                    return Optional.of(Range.closed(txMin, txMax));
                }
            }
        }
    }
    return Optional.empty();
}
 
Example 3
Source File: PolatisOpticalUtility.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Transforms a flow FlowRule object to a variable binding.
 * @param rule FlowRule object
 * @param delete whether it is a delete or edit request
 * @return variable binding
 */
public static VariableBinding fromFlowRule(FlowRule rule, boolean delete) {
    Set<Criterion> criterions = rule.selector().criteria();
    PortNumber inPort = criterions.stream()
            .filter(c -> c instanceof PortCriterion)
            .map(c -> ((PortCriterion) c).port())
            .findAny()
            .orElse(null);
    long input = inPort.toLong();
    List<Instruction> instructions = rule.treatment().immediate();
    PortNumber outPort = instructions.stream()
            .filter(c -> c instanceof Instructions.OutputInstruction)
            .map(c -> ((Instructions.OutputInstruction) c).port())
            .findAny()
            .orElse(null);
    long output = outPort.toLong();
    OID oid = new OID(PORT_PATCH_OID + "." + input);
    Variable var = new UnsignedInteger32(delete ? 0 : output);
    return new VariableBinding(oid, var);
}
 
Example 4
Source File: PolatisPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean setPortTargetPower(PortNumber port, long power) {
    log.debug("Set port{} target power...", port);
    List<VariableBinding> vbs = new ArrayList<>();

    OID voaStateOid = new OID(VOA_STATE_OID + "." + port.toLong());
    Variable voaStateVar = new UnsignedInteger32(VOA_STATE_ABSOLUTE);
    VariableBinding voaStateVb = new VariableBinding(voaStateOid, voaStateVar);
    vbs.add(voaStateVb);

    OID voaLevelOid = new OID(VOA_LEVEL_OID + "." + port.toLong());
    Variable voaLevelVar = new UnsignedInteger32(power);
    VariableBinding voaLevelVb = new VariableBinding(voaLevelOid, voaLevelVar);
    vbs.add(voaLevelVb);

    DeviceId deviceId = handler().data().deviceId();
    try {
        set(handler(), vbs);
    } catch (IOException e) {
        log.error("Error writing ports table for device {} exception {}", deviceId, e);
        return false;
    }
    return true;
}
 
Example 5
Source File: ServerPortAdmin.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public CompletableFuture<Boolean> isEnabled(PortNumber number) {
    // Retrieve the device ID
    DeviceId deviceId = super.getDeviceId();
    checkNotNull(deviceId, MSG_DEVICE_ID_NULL);

    // ...and the device itself
    RestServerSBDevice device = null;
    try {
        device = (RestServerSBDevice) getDevice(deviceId);
    } catch (ClassCastException ccEx) {
        log.error("Failed to discover ports for device {}", deviceId);
        return completedFuture(false);
    }

    // Iterate server's NICs to find the correct port
    for (NicDevice nic : device.nics()) {
        if (nic.portNumber() == number.toLong()) {
            return completedFuture(nic.status());
        }
    }

    return completedFuture(false);
}
 
Example 6
Source File: VirtualNetworkWebResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests removing a virtual port with DELETE request.
 */
@Test
public void testDeleteVirtualPort() {
    NetworkId networkId = networkId3;
    DeviceId deviceId = devId2;
    PortNumber portNum = portNumber(2);
    mockVnetAdminService.removeVirtualPort(networkId, deviceId, portNum);
    expectLastCall();
    replay(mockVnetAdminService);

    WebTarget wt = target()
            .property(ClientProperties.SUPPRESS_HTTP_COMPLIANCE_VALIDATION, true);
    String reqLocation = "vnets/" + networkId.toString()
            + "/devices/" + deviceId.toString() + "/ports/" + portNum.toLong();
    Response response = wt.path(reqLocation)
            .request(MediaType.APPLICATION_JSON_TYPE)
            .delete();

    assertThat(response.getStatus(), is(HttpURLConnection.HTTP_NO_CONTENT));

    verify(mockVnetAdminService);
}
 
Example 7
Source File: IsisTopologyProvider.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void addLink(IsisLink isisLink) {
    log.debug("Addlink {}", isisLink.localSystemId());

    LinkDescription linkDes = buildLinkDes(isisLink);
    //Updating ports of the link
    //If already link exists, return
    if (linkService.getLink(linkDes.src(), linkDes.dst()) != null || linkProviderService == null) {
        return;
    }
    ConnectPoint destconnectPoint = linkDes.dst();
    PortNumber destport = destconnectPoint.port();
    if (destport.toLong() != 0) {
        deviceProviderService.updatePorts(linkDes.src().deviceId(),
                                          buildPortDescriptions(linkDes.src().deviceId(),
                                          linkDes.src().port()));
        deviceProviderService.updatePorts(linkDes.dst().deviceId(),
                                          buildPortDescriptions(linkDes.dst().deviceId(),
                                          linkDes.dst().port()));
        registerBandwidth(linkDes, isisLink);
        linkProviderService.linkDetected(linkDes);
        System.out.println("link desc " + linkDes.toString());
    }
}
 
Example 8
Source File: OpenFlowPowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean setPortTargetPower(PortNumber port, double power) {
    DeviceId deviceId = handler().data().deviceId();
    final Dpid dpid = dpid(deviceId.uri());
    OpenFlowSwitch sw = handler().get(OpenFlowController.class).getSwitch(dpid);
    if (sw == null || !sw.isConnected()) {
        log.error("Failed to change port on device {}", deviceId);
        return false;
    }
    boolean enable = false;
    for (OFPortDesc pd : getPortDescs()) {
        if (pd.getPortNo().getPortNumber() == port.toLong()) {
            enable = pd.getConfig().contains(OFPortConfig.PORT_DOWN);
            break;
        }
    }
    OFPortMod.Builder pmb = makePortMod(sw, port, enable);
    double configure = OFOpticalPortFeaturesSerializerVer14.TX_PWR_VAL;
    OFPortModPropOptical.Builder property = sw.factory().buildPortModPropOptical();
    property.setTxPwr((long) power);

    List<OFPortModProp> properties = new ArrayList<>();
    properties.add(property.build());
    pmb.setProperties(properties);

    sw.sendMsg(Collections.singletonList(pmb.build()));
    // TODO: We would need to report false in case of port mod failure.
    return true;
}
 
Example 9
Source File: OplinkPowerConfigUtil.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Find oplink port description type from optical ports.
 *
 * @param opsw switch
 * @param portNum the port number
 * @return port oplink port description type
 */
private PortDescType getPortDescType(OpenFlowOpticalSwitch opsw, PortNumber portNum) {
    for (PortDescPropertyType type : opsw.getPortTypes()) {
        List<? extends OFObject> portsOf = opsw.getPortsOf(type);
        for (OFObject op : portsOf) {
            if (op instanceof OFPortOptical) {
                OFPortOptical opticalPort = (OFPortOptical) op;
                if ((long) opticalPort.getPortNo().getPortNumber() == portNum.toLong()) {
                    return PortDescType.values()[opticalPort.getDesc().get(0).getPortType()];
                }
            }
        }
    }
    return PortDescType.NONE;
}
 
Example 10
Source File: Bmv2PreGroupTranslatorImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Builds a port map string composing of 1 and 0s.
 * BMv2 API reads a port map from most significant to least significant char.
 * Index of 1s indicates port numbers.
 * For example, if port numbers are 4,3 and 1, the generated port map string looks like 11010.
 *
 * @param outPorts set of output port numbers
 * @return port map string
 */
private static String buildPortMap(Set<PortNumber> outPorts) {
    //Sorts port numbers in descending order
    SortedSet<PortNumber> outPortsSorted = new TreeSet<>((o1, o2) -> (int) (o2.toLong() - o1.toLong()));
    outPortsSorted.addAll(outPorts);
    PortNumber biggestPort = outPortsSorted.iterator().next();
    int portMapSize = (int) biggestPort.toLong() + 1;
    //init and fill port map with zero characters
    char[] portMap = new char[portMapSize];
    Arrays.fill(portMap, '0');
    //fill in the ports with 1
    outPortsSorted.forEach(portNumber -> portMap[portMapSize - (int) portNumber.toLong() - 1] = '1');
    return String.valueOf(portMap);
}
 
Example 11
Source File: PortNumberCodec.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public int encode(PortNumber resource) {
    return (int) resource.toLong();
}
 
Example 12
Source File: AbstractTerminalDeviceFlowRuleProgrammable.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get the OpenConfig component name for the OpticalChannel component
 * associated to the passed port number (typically a line side port, already
 * mapped to ONOS port).
 *
 * @param session    The netconf session to the device.
 * @param portNumber ONOS port number of the Line port ().
 * @return the channel component name or null
 */
protected String getOpticalChannel(NetconfSession session,
                                   PortNumber portNumber) {
    try {
        checkNotNull(session);
        checkNotNull(portNumber);
        XPath xp = XPathFactory.newInstance().newXPath();
        xp.setNamespaceContext(NS_CONTEXT);

        // Get the port name for a given port number
        // We could iterate the port annotations too, no need to
        // interact with device.
        String xpGetPortName =
                "/rpc-reply/data/components/"
                        +
                        "component[./properties/property[name='onos-index']/config/value ='" +
                        portNumber.toLong() + "']/"
                        + "name/text()";

        // Get all the components and their properties
        String compReply = session.rpc(getComponents()).get();
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document =
                builder.parse(new InputSource(new StringReader(compReply)));
        String portName = xp.evaluate(xpGetPortName, document);
        String xpGetOptChannelName =
                "/rpc-reply/data/components/"
                        + "component[./optical-channel/config/line-port='" + portName +
                        "']/name/text()";

        String optChannelReply = session.rpc(getOpticalChannels()).get();
        document =
                builder.parse(new InputSource(new StringReader(optChannelReply)));
        return xp.evaluate(xpGetOptChannelName, document);
    } catch (Exception e) {
        openConfigError("Exception {}", e);
        return null;
    }
}
 
Example 13
Source File: MyTunnelApp.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Generates and insert a flow rule to perform the tunnel FORWARD/EGRESS
 * function for the given switch, output port address and tunnel ID.
 *
 * @param switchId switch ID
 * @param outPort  output port where to forward tunneled packets
 * @param tunId    tunnel ID
 * @param isEgress if true, perform tunnel egress action, otherwise forward
 *                 packet as is to port
 */
private void insertTunnelForwardRule(DeviceId switchId,
                                     PortNumber outPort,
                                     int tunId,
                                     boolean isEgress) {

    PiTableId tunnelForwardTableId = PiTableId.of("c_ingress.t_tunnel_fwd");

    // Exact match on tun_id
    PiMatchFieldId tunIdMatchFieldId = PiMatchFieldId.of("hdr.my_tunnel.tun_id");
    PiCriterion match = PiCriterion.builder()
            .matchExact(tunIdMatchFieldId, tunId)
            .build();

    // Action depend on isEgress parameter.
    // if true, perform tunnel egress action on the given outPort, otherwise
    // simply forward packet as is (set_out_port action).
    PiActionParamId portParamId = PiActionParamId.of("port");
    PiActionParam portParam = new PiActionParam(portParamId, (short) outPort.toLong());

    final PiAction action;
    if (isEgress) {
        // Tunnel egress action.
        // Remove MyTunnel header and forward to outPort.
        PiActionId egressActionId = PiActionId.of("c_ingress.my_tunnel_egress");
        action = PiAction.builder()
                .withId(egressActionId)
                .withParameter(portParam)
                .build();
    } else {
        // Tunnel transit action.
        // Forward the packet as is to outPort.
        /*
         * TODO EXERCISE: create action object for the transit case.
         * Look at the t_tunnel_fwd table in the P4 program. Which of the 3
         * actions can be used to simply set the output port? Get the full
         * action name from the P4Info file, and use that when creating the
         * PiActionId object. When creating the PiAction object, remember to
         * add all action parameters as defined in the P4 program.
         *
         * Hint: the code will be similar to the case when isEgress is true.
         */
        action = null; // Replace null with your solution.
    }

    log.info("Inserting {} rule on switch {}: table={}, match={}, action={}",
             isEgress ? "EGRESS" : "TRANSIT",
             switchId, tunnelForwardTableId, match, action);

    insertPiFlowRule(switchId, tunnelForwardTableId, match, action);
}
 
Example 14
Source File: CzechLightPowerConfig.java    From onos with Apache License 2.0 4 votes vote down vote up
private String inlineAmpStageNameFor(final PortNumber port) {
    return port.toLong() == CzechLightDiscovery.PORT_INLINE_WEST ? "west-to-east" : "east-to-west";
}
 
Example 15
Source File: CzechLightPowerConfig.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void setTargetPower(PortNumber port, T component, double power) {
    switch (deviceType()) {
        case LINE_DEGREE:
        case ADD_DROP_FLEX:
            if (!(component instanceof OchSignal)) {
                log.error("Cannot set target power on anything but a Media Channel");
                return;
            }
            HierarchicalConfiguration xml;
            try {
                xml = doGetSubtree(CzechLightDiscovery.CHANNEL_DEFS_FILTER + CzechLightDiscovery.MC_ROUTING_FILTER);
            } catch (NetconfException e) {
                log.error("Cannot read data from NETCONF: {}", e);
                return;
            }
            final var allChannels = MediaChannelDefinition.parseChannelDefinitions(xml);
            final var och = ((OchSignal) component);
            final var channel = allChannels.entrySet().stream()
                    .filter(entry -> MediaChannelDefinition.mcMatches(entry, och))
                    .findAny()
                    .orElse(null);
            if (channel == null) {
                log.error("Cannot map OCh definition {} to a channel from the channel plan", och);
                return;
            }
            final String element = port.toLong() == CzechLightDiscovery.PORT_COMMON ? "add" : "drop";
            log.debug("{}: setting power for MC {} to {}",
                    data().deviceId(), channel.getKey().toUpperCase(), power);
            var sb = new StringBuilder();
            sb.append(CzechLightDiscovery.XML_MC_OPEN);
            sb.append("<channel>");
            sb.append(channel.getKey());
            sb.append("</channel>");
            sb.append("<");
            sb.append(element);
            sb.append("><power>");
            sb.append(power);
            sb.append("</power></");
            sb.append(element);
            sb.append(">");
            sb.append(CzechLightDiscovery.XML_MC_CLOSE);
            doEditConfig("merge", sb.toString());
            return;
        default:
            log.error("Target power is only supported on WSS-based devices");
            return;
    }
}
 
Example 16
Source File: ClientLineTerminalDeviceFlowRuleProgrammable.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get the OpenConfig component name for the OpticalChannel component
 * associated to the passed port number (typically a line side port, already
 * mapped to ONOS port).
 *
 * @param session    The netconf session to the device.
 * @param portNumber ONOS port number of the Line port ().
 * @return the channel component name or null
 */
private String getOpticalChannel(NetconfSession session,
                                 PortNumber portNumber) {
    try {
        checkNotNull(session);
        checkNotNull(portNumber);
        XPath xp = XPathFactory.newInstance().newXPath();
        xp.setNamespaceContext(NS_CONTEXT);

        // Get the port name for a given port number
        // We could iterate the port annotations too, no need to
        // interact with device.
        String xpGetPortName =
                "/rpc-reply/data/components/"
                        +
                        "component[./properties/property[name='onos-index']/config/value ='" +
                        portNumber.toLong() + "']/"
                        + "name/text()";

        // Get all the components and their properties
        String compReply = session.rpc(getComponents()).get();
        DocumentBuilderFactory builderFactory =
                DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = builderFactory.newDocumentBuilder();
        Document document =
                builder.parse(new InputSource(new StringReader(compReply)));
        String portName = xp.evaluate(xpGetPortName, document);
        String xpGetOptChannelName =
                "/rpc-reply/data/components/"
                        + "component[./optical-channel/config/line-port='" + portName +
                        "']/name/text()";

        String optChannelReply = session.rpc(getOpticalChannels()).get();
        document =
                builder.parse(new InputSource(new StringReader(optChannelReply)));
        return xp.evaluate(xpGetOptChannelName, document);
    } catch (Exception e) {
        openConfigError("Exception {}", e);
        return null;
    }
}
 
Example 17
Source File: Bmv2PreGroupTranslatorImpl.java    From onos with Apache License 2.0 3 votes vote down vote up
/**
 * Checks whether a port number is a valid physical BMv2 port or not.
 * If not, throws RuntimeException; does nothing otherwise.
 *
 * @param portNumber port number
 * @throws RuntimeException iff the port number can not be validated
 */
private static void validatePort(PortNumber portNumber) {
    if (portNumber.toLong() < 0 || portNumber.toLong() >= BMV2_PORT_MAP_SIZE) {
        throw new IllegalStateException(String.format("Port number %d is not a valid BMv2 physical port number." +
                                                         "Valid port range is [0,255]", portNumber.toLong()));
    }
}