Java Code Examples for org.onosproject.net.device.DeviceService#getPorts()

The following examples show how to use org.onosproject.net.device.DeviceService#getPorts() . 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: AddOpticalIntentCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
private ConnectPoint createConnectPoint(String devicePortString) {
    String[] splitted = devicePortString.split("/");

    checkArgument(splitted.length == 2,
            "Connect point must be in \"deviceUri/portNumber\" format");

    DeviceId deviceId = DeviceId.deviceId(splitted[0]);
    DeviceService deviceService = get(DeviceService.class);

    List<Port> ports = deviceService.getPorts(deviceId);

    for (Port port : ports) {
        if (splitted[1].equals(port.number().name())) {
            return new ConnectPoint(deviceId, port.number());
        }
    }

    return null;
}
 
Example 2
Source File: DevicePortsListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Produces JSON array containing ports of the specified device.
 *
 * @param service device service
 * @param mapper  object mapper
 * @param device  infrastructure devices
 * @return JSON array
 */
public JsonNode jsonPorts(DeviceService service, ObjectMapper mapper, Device device) {
    ObjectNode result = mapper.createObjectNode();
    ArrayNode ports = mapper.createArrayNode();
    for (Port port : service.getPorts(device.id())) {
        if (isIncluded(port)) {
            ports.add(mapper.createObjectNode()
                              .put("element", device.id().toString())
                              .put("port", port.number().toString())
                              .put("isEnabled", port.isEnabled())
                              .put("type", port.type().toString().toLowerCase())
                              .put("portSpeed", port.portSpeed())
                              .set("annotations", annotations(mapper, port.annotations())));
        }
    }
    result.set("device", jsonForEntity(device, Device.class));
    result.set("ports", ports);
    return result;
}
 
Example 3
Source File: OpticalConnectPointCompleter.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public int complete(Session session, CommandLine commandLine, List<String> candidates) {
    // Delegate string completer
    StringsCompleter delegate = new StringsCompleter();

    // Fetch our service and feed it's offerings to the string completer
    DeviceService service = AbstractShellCommand.get(DeviceService.class);

    // Generate the device ID/port number identifiers
    for (Device device : service.getDevices()) {
        SortedSet<String> strings = delegate.getStrings();
        for (Port port : service.getPorts(device.id())) {
            if (!port.number().isLogical() && (port.type().equals(Port.Type.OCH) ||
                    port.type().equals(Port.Type.OMS) || port.type().equals(Port.Type.OTU))) {
                strings.add(device.id().toString() + "/" + port.number());
            }
        }
    }

    // Now let the completer do the work for figuring out what to offer.
    return delegate.complete(session, commandLine, candidates);
}
 
Example 4
Source File: ConnectPointCompleter.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public int complete(Session session, CommandLine commandLine, List<String> candidates) {
    // Delegate string completer
    StringsCompleter delegate = new StringsCompleter();

    // Fetch our service and feed it's offerings to the string completer
    DeviceService service = AbstractShellCommand.get(DeviceService.class);

    // Generate the device ID/port number identifiers
    for (Device device : service.getDevices()) {
        SortedSet<String> strings = delegate.getStrings();
        for (Port port : service.getPorts(device.id())) {
            if (!port.number().isLogical()) {
                strings.add(device.id().toString() + "/" + port.number());
            }
        }
    }

    // Now let the completer do the work for figuring out what to offer.
    return delegate.complete(session, commandLine, candidates);
}
 
Example 5
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<FlowRule> removeFlowRules(Collection<FlowRule> rules) {
    try {
        snmp = new LumentumSnmpDevice(data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
    }

    // Line ports
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream()
            .map(p -> p.number())
            .collect(Collectors.toList());

    // Apply the valid rules on the device
    Collection<FlowRule> removed = rules.stream()
            .map(r -> new CrossConnectFlowRule(r, linePorts))
            .filter(xc -> removeCrossConnect(xc))
            .collect(Collectors.toList());

    // Remove flow rule from cache
    CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
    removed.forEach(xc -> cache.remove(
            Objects.hash(data().deviceId(), xc.selector(), xc.treatment())));

    return removed;
}
 
Example 6
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 7
Source File: VirtualNetworkDeviceManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests querying the ports of a device by null device identifier.
 */
@Test(expected = NullPointerException.class)
public void testGetPortsByNullId() {
    manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
    VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
    DeviceService deviceService = manager.get(virtualNetwork.id(), DeviceService.class);

    // test the getPorts() method using a null device identifier
    deviceService.getPorts(null);
}
 
Example 8
Source File: DevicePortsListCommand.java    From onos with Apache License 2.0 5 votes vote down vote up
protected void printPorts(DeviceService service, Device device) {
    List<Port> ports = new ArrayList<>(service.getPorts(device.id()));
    Collections.sort(ports, Comparators.PORT_COMPARATOR);
    for (Port port : ports) {
        if (!isIncluded(port)) {
            continue;
        }
        String portName = port.number().toString();
        Object portIsEnabled = port.isEnabled() ? "enabled" : "disabled";
        String portType = port.type().toString().toLowerCase();
        String annotations = annotations(port.annotations());
        print(FMT, portName, portIsEnabled, portType, port.portSpeed(), annotations);
    }
}
 
Example 9
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<FlowRule> applyFlowRules(Collection<FlowRule> rules) {
    try {
        snmp = new LumentumSnmpDevice(data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
    }

    // Line ports
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    List<PortNumber> linePorts = ports.subList(ports.size() - 2, ports.size()).stream()
            .map(p -> p.number())
            .collect(Collectors.toList());

    // Apply the valid rules on the device
    Collection<FlowRule> added = rules.stream()
            .map(r -> new CrossConnectFlowRule(r, linePorts))
            .filter(xc -> installCrossConnect(xc))
            .collect(Collectors.toList());

    // Cache the cookie/priority
    CrossConnectCache cache = this.handler().get(CrossConnectCache.class);
    added.forEach(xc -> cache.set(
            Objects.hash(data().deviceId(), xc.selector(), xc.treatment()),
            xc.id(),
            xc.priority()));

    return added;
}
 
Example 10
Source File: LumentumSdnRoadmFlowRuleProgrammable.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<FlowEntry> getFlowEntries() {
    try {
        snmp = new LumentumSnmpDevice(handler().data().deviceId());
    } catch (IOException e) {
        log.error("Failed to connect to device: ", e);
        return Collections.emptyList();
    }

    // Line in is last but one port, line out is last
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(data().deviceId());
    if (ports.size() < 2) {
        return Collections.emptyList();
    }
    PortNumber lineIn = ports.get(ports.size() - 2).number();
    PortNumber lineOut = ports.get(ports.size() - 1).number();

    Collection<FlowEntry> entries = Lists.newLinkedList();

    // Add rules
    OID addOid = new OID(CTRL_CHANNEL_STATE + "1");
    entries.addAll(
            fetchRules(addOid, true, lineOut).stream()
                    .map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
                    .collect(Collectors.toList())
    );

    // Drop rules
    OID dropOid = new OID(CTRL_CHANNEL_STATE + "2");
    entries.addAll(
            fetchRules(dropOid, false, lineIn).stream()
                    .map(fr -> new DefaultFlowEntry(fr, FlowEntry.FlowEntryState.ADDED, 0, 0, 0))
                    .collect(Collectors.toList())
    );

    return entries;
}
 
Example 11
Source File: FlowRuleJuniperImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to convert FlowRule into an abstraction of static route
 * {@link StaticRoute}.
 *
 * @param devId    the device id
 * @param criteria the IP destination criteria
 * @param output   the output instruction
 * @return optional of Static Route
 */
private Optional<StaticRoute> getStaticRoute(DeviceId devId,
                                             IPCriterion criteria,
                                             OutputInstruction output,
                                             int priority) {

    DeviceService deviceService = this.handler().get(DeviceService.class);
    Collection<Port> ports = deviceService.getPorts(devId);
    Optional<Port> port = ports.stream().filter(x -> x.number().equals(output.port())).findAny();
    if (!port.isPresent()) {
        log.error("The port {} does not exist in the device",
                output.port());
        return Optional.empty();
    }

    //Find if the route refers to a local interface.
    Optional<Port> local = deviceService.getPorts(devId).stream().filter(this::isIp)
            .filter(p -> criteria.ip().getIp4Prefix().contains(
                    Ip4Address.valueOf(p.annotations().value(JuniperUtils.AK_IP)))).findAny();

    if (local.isPresent()) {
        return Optional.of(new StaticRoute(criteria.ip().getIp4Prefix(),
                criteria.ip().getIp4Prefix().address(), true, priority));
    }

    Optional<Ip4Address> nextHop = findIpDst(devId, port.get());
    if (nextHop.isPresent()) {
        return Optional.of(
                new StaticRoute(criteria.ip().getIp4Prefix(), nextHop.get(), false, priority));
    } else {
        log.error("The destination interface has not an IP {}", port.get());
        return Optional.empty();
    }

}
 
Example 12
Source File: ZtePortStatisticsDiscovery.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<PortStatistics> discoverPortStatistics() {
    DeviceId deviceId = handler().data().deviceId();
    LOG.debug("Discovering ZTE PortStatistics for device {}", deviceId);

    NetconfController controller = handler().get(NetconfController.class);

    if (null == controller) {
        LOG.error("Cannot find NetconfController");
        return null;
    }

    NetconfSession session = controller.getDevicesMap().get(deviceId).getSession();

    if (null == session) {
        LOG.error("No session available for device {}", deviceId);
        return null;
    }

    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(deviceId);

    Collection<PortStatistics> portStatistics = Lists.newArrayList();

    ports.stream()
            .filter(Port::isEnabled)
            .filter(this::isClientPort)
            .forEach(port -> portStatistics.add(discoverSpecifiedPortStatistics(session, deviceId, port)));

    return portStatistics;
}
 
Example 13
Source File: CiscoNxosPortStatistics.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Collection<PortStatistics> discoverPortStatistics() {
    DriverHandler handler = handler();
    RestSBController controller = checkNotNull(handler.get(RestSBController.class));
    DeviceId deviceId = handler.data().deviceId();
    DeviceService deviceService = this.handler().get(DeviceService.class);
    List<Port> ports = deviceService.getPorts(deviceId);
    Collection<PortStatistics> portStatistics = Lists.newArrayList();

    ports.stream()
            .filter(Port::isEnabled)
            .forEach(port -> portStatistics.add(discoverSpecifiedPortStatistics(port, controller, deviceId)));

    return ImmutableList.copyOf(portStatistics);
}
 
Example 14
Source File: DeviceViewMessageHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    String id = string(payload, ID, ZERO_URI);

    DeviceId deviceId = deviceId(id);
    DeviceService service = get(DeviceService.class);
    MastershipService ms = get(MastershipService.class);
    Device device = service.getDevice(deviceId);
    ObjectNode data = objectNode();
    NodeId masterFor = ms.getMasterFor(deviceId);

    data.put(ID, deviceId.toString());
    data.put(NAME, deviceName(device));
    data.put(TYPE, capitalizeFully(device.type().toString()));
    data.put(TYPE_IID, getTypeIconId(device));
    data.put(MFR, device.manufacturer());
    data.put(HW, device.hwVersion());
    data.put(SW, device.swVersion());
    data.put(SERIAL, device.serialNumber());
    data.put(CHASSIS_ID, device.chassisId().toString());
    data.put(MASTER_ID, masterFor != null ? masterFor.toString() : NONE);
    data.put(PROTOCOL, deviceProtocol(device));
    data.put(PIPECONF, devicePipeconf(device));

    ArrayNode ports = arrayNode();

    List<Port> portList = new ArrayList<>(service.getPorts(deviceId));
    portList.sort((p1, p2) -> {
        long delta = p1.number().toLong() - p2.number().toLong();
        return delta == 0 ? 0 : (delta < 0 ? -1 : +1);
    });

    for (Port p : portList) {
        ports.add(portData(p, deviceId));
    }
    data.set(PORTS, ports);

    ObjectNode rootNode = objectNode();
    rootNode.set(DETAILS, data);

    // NOTE: ... an alternate way of getting all the details of an item:
    // Use the codec context to get a JSON of the device. See ONOS-5976.
    rootNode.set(DEVICE, getJsonCodecContext().encode(device, Device.class));

    sendMessage(DEV_DETAILS_RESP, rootNode);
}
 
Example 15
Source File: PortStatisticsImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public Collection<PortStatistics> discoverPortStatistics() {
    Collection<PortStatistics> portStatistics = Lists.newArrayList();
    try {
        DeviceId deviceId = handler().data().deviceId();
        DeviceService deviceService = this.handler().get(DeviceService.class);
        List<Port> ports = deviceService.getPorts(deviceId);
        Optional<JsonNode> result = AristaUtils.retrieveCommandResult(handler(), SHOW_INTERFACES);

        if (!result.isPresent()) {
            return portStatistics;
        }

        JsonNode interfaces = result.get().findValue(INTERFACES);

        if (interfaces == null) {
            return portStatistics;
        }

        Iterator<Map.Entry<String, JsonNode>> ifIterator = interfaces.fields();
        while (ifIterator.hasNext()) {
            Map.Entry<String, JsonNode> intf = ifIterator.next();
            String ifName = intf.getKey();
            JsonNode interfaceNode = intf.getValue();
            JsonNode interfaceCounters = interfaceNode.get(INTERFACE_COUNTERS);
            if (interfaceCounters == null) {
                continue;
            }
            ports.stream().filter(Port::isEnabled)
                    .filter(port -> {
                        String portName = port.annotations().value(AnnotationKeys.PORT_NAME);
                        return portName != null && portName.equals(ifName);
                    })
                    .findAny()
                    .ifPresent(port -> portStatistics.add(
                            buildStatisticsForPort(interfaceCounters, port.number(), deviceId)));
        }
    } catch (Exception e) {
        log.error("Exception occurred because of", e);
    }
    return portStatistics;
}
 
Example 16
Source File: OpticalPortsListCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void printPorts(DeviceService service, Device device) {
    List<Port> ports = new ArrayList<>(service.getPorts(device.id()));
    ports.sort((p1, p2) ->
         Long.signum(p1.number().toLong() - p2.number().toLong())
    );
    for (Port port : ports) {
        if (!isIncluded(port)) {
            continue;
        }
        String portName = port.number().toString();
        String portIsEnabled = port.isEnabled() ? "enabled" : "disabled";
        String portType = port.type().toString().toLowerCase();
        switch (port.type()) {
            case OCH:
                if (port instanceof OchPort) {
                    OchPort och = (OchPort) port;
                    print(FMT_OCH, portName, portIsEnabled, portType,
                          och.signalType().toString(),
                          och.isTunable() ? "yes" : "no",
                          annotations(och.unhandledAnnotations()));
                   break;
                }
                print("WARN: OchPort but not on OpticalDevice or ill-formed");
                print(FMT, portName, portIsEnabled, portType, port.portSpeed(), annotations(port.annotations()));
                break;
            case ODUCLT:
                if (port instanceof OduCltPort) {
                    OduCltPort oduCltPort = (OduCltPort) port;
                    print(FMT_ODUCLT_OTU, portName, portIsEnabled, portType,
                          oduCltPort.signalType().toString(),
                          annotations(oduCltPort.unhandledAnnotations()));
                    break;
                }
                print("WARN: OduCltPort but not on OpticalDevice or ill-formed");
                print(FMT, portName, portIsEnabled, portType, port.portSpeed(), annotations(port.annotations()));
                break;
            case OMS:
                if (port instanceof OmsPort) {
                    OmsPort oms = (OmsPort) port;
                    print(FMT_OMS, portName, portIsEnabled, portType,
                          oms.minFrequency().asHz() / Frequency.ofGHz(1).asHz(),
                          oms.maxFrequency().asHz() / Frequency.ofGHz(1).asHz(),
                          oms.grid().asHz() / Frequency.ofGHz(1).asHz(),
                          oms.totalChannels(),
                          annotations(oms.unhandledAnnotations()));
                    break;
                }
                print("WARN: OmsPort but not on OpticalDevice or ill-formed");
                print(FMT, portName, portIsEnabled, portType, port.portSpeed(), annotations(port.annotations()));
                break;
            case OTU:
                if (port instanceof OtuPort) {
                    OtuPort otuPort = (OtuPort) port;
                    print(FMT_ODUCLT_OTU, portName, portIsEnabled, portType,
                          otuPort.signalType().toString(),
                          annotations(otuPort.unhandledAnnotations()));
                    break;
                }
                print("WARN: OtuPort but not on OpticalDevice or ill-formed");
                print(FMT, portName, portIsEnabled, portType, port.portSpeed(), annotations(port.annotations()));
                break;
            default:
                // do not print non-optical ports
                break;
        }
    }
}
 
Example 17
Source File: LinkDiscoveryCiscoImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public Set<LinkDescription> getLinks() {
    String response = retrieveResponse(SHOW_LLDP_NEIGHBOR_DETAIL_CMD);
    DeviceId localDeviceId = this.handler().data().deviceId();
    DeviceService deviceService = this.handler().get(DeviceService.class);
    Set<LinkDescription> linkDescriptions = Sets.newHashSet();
    List<Port> ports = deviceService.getPorts(localDeviceId);

    if (ports.size() == 0 || Objects.isNull(response)) {
        return linkDescriptions;
    }
    try {
        ObjectMapper om = new ObjectMapper();
        JsonNode json = om.readTree(response);
        if (json == null) {
            return linkDescriptions;
        }

        JsonNode res = json.at("/" + JSON_RESULT);
        if (res.isMissingNode()) {
            return linkDescriptions;
        }

        JsonNode lldpNeighborsRow = res.at("/" + TABLE_NBOR_DETAIL);
        if (lldpNeighborsRow.isMissingNode()) {
            return linkDescriptions;
        }

        JsonNode lldpNeighbors = lldpNeighborsRow.at("/" + ROW_NBOR_DETAIL);
        if (lldpNeighbors.isMissingNode()) {
            return linkDescriptions;
        }

        Iterator<JsonNode> iterator = lldpNeighbors.elements();

        while (iterator.hasNext()) {
            JsonNode neighbors = iterator.next();
            String remoteChassisId = neighbors.get(CHASSIS_ID).asText();
            String remotePortName = neighbors.get(PORT_ID).asText();
            String remotePortDesc = neighbors.get(PORT_DESC).asText();
            String lldpLocalPort = neighbors.get(LOCAL_PORT_ID).asText()
                    .replaceAll("(Eth.{0,5})(.\\d{0,5}/\\d{0,5})", "Ethernet$2");

            Port localPort = findLocalPortByName(ports, lldpLocalPort);
            if (localPort == null) {
                log.warn("local port not found. LldpLocalPort value: {}", lldpLocalPort);
                continue;
            }

            Device remoteDevice = findRemoteDeviceByChassisId(deviceService, remoteChassisId);
            Port remotePort = findDestinationPortByName(remotePortName,
                                                        remotePortDesc,
                                                        deviceService,
                                                        remoteDevice);

            if (!localPort.isEnabled() || !remotePort.isEnabled()) {
                log.debug("Ports are disabled. Cannot create a link between {}/{} and {}/{}",
                          localDeviceId, localPort, remoteDevice.id(), remotePort);
                continue;
            }

            linkDescriptions.addAll(buildLinkPair(localDeviceId, localPort, remoteDevice.id(), remotePort));
        }
    } catch (IOException e) {
        log.error("Failed to get links ", e);
    }

    log.debug("Returning linkDescriptions: {}", linkDescriptions);
    return linkDescriptions;

}