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

The following examples show how to use org.onosproject.net.device.DeviceService#getDevice() . 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: Srv6InsertCommand.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    DeviceService deviceService = get(DeviceService.class);
    Srv6Component app = get(Srv6Component.class);

    Device device = deviceService.getDevice(DeviceId.deviceId(uri));
    if (device == null) {
        print("Device \"%s\" is not found", uri);
        return;
    }
    if (segments.size() == 0) {
        print("No segments listed");
        return;
    }
    List<Ip6Address> sids = segments.stream()
            .map(Ip6Address::valueOf)
            .collect(Collectors.toList());
    Ip6Address destIp = sids.get(sids.size() - 1);

    print("Installing path on device %s: %s",
            uri, sids.stream()
                     .map(IpAddress::toString)
                     .collect(Collectors.joining(", ")));
    app.insertSrv6InsertRule(device.id(), destIp, 128, sids);

}
 
Example 2
Source File: DecodeInstructionCodecHelper.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Decodes a extension instruction.
 *
 * @return extension treatment
 */
private Instruction decodeExtension() {
    ObjectNode node = (ObjectNode) json.get(InstructionCodec.EXTENSION);
    if (node != null) {
        DeviceId deviceId = getDeviceId();

        ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
        DeviceService deviceService = serviceDirectory.get(DeviceService.class);
        Device device = deviceService.getDevice(deviceId);

        if (device == null) {
            throw new IllegalArgumentException("Device not found");
        }

        if (device.is(ExtensionTreatmentCodec.class)) {
            ExtensionTreatmentCodec treatmentCodec = device.as(ExtensionTreatmentCodec.class);
            ExtensionTreatment treatment = treatmentCodec.decode(node, context);
            return Instructions.extension(treatment, deviceId);
        } else {
            throw new IllegalArgumentException(
                    "There is no codec to decode extension for device " + deviceId.toString());
        }
    }
    return null;
}
 
Example 3
Source File: OpenstackTroubleshootUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns tunnel destination extension treatment object.
 *
 * @param deviceService driver service
 * @param deviceId device id to apply this treatment
 * @param remoteIp tunnel destination ip address
 * @return extension treatment
 */
public static ExtensionTreatment buildExtension(DeviceService deviceService,
                                                DeviceId deviceId,
                                                Ip4Address remoteIp) {
    Device device = deviceService.getDevice(deviceId);
    if (device != null && !device.is(ExtensionTreatmentResolver.class)) {
        log.error("The extension treatment is not supported");
        return null;
    }

    if (device == null) {
        return null;
    }

    ExtensionTreatmentResolver resolver = device.as(ExtensionTreatmentResolver.class);
    ExtensionTreatment treatment = resolver.getExtensionInstruction(NICIRA_SET_TUNNEL_DST.type());
    try {
        treatment.setPropertyValue(TUNNEL_DST, remoteIp);
        return treatment;
    } catch (ExtensionPropertyException e) {
        log.warn("Failed to get tunnelDst extension treatment for {}", deviceId);
        return null;
    }
}
 
Example 4
Source File: EncodeInstructionCodecHelper.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Encodes a extension instruction.
 *
 * @param result json node that the instruction attributes are added to
 */
private void encodeExtension(ObjectNode result) {
    final Instructions.ExtensionInstructionWrapper extensionInstruction =
            (Instructions.ExtensionInstructionWrapper) instruction;

    DeviceId deviceId = extensionInstruction.deviceId();

    ServiceDirectory serviceDirectory = new DefaultServiceDirectory();
    DeviceService deviceService = serviceDirectory.get(DeviceService.class);
    Device device = deviceService.getDevice(deviceId);

    if (device == null) {
        throw new IllegalArgumentException("Device not found");
    }

    if (device.is(ExtensionTreatmentCodec.class)) {
        // for extension instructions, encoding device id is needed for the corresponding decoder
        result.put("deviceId", deviceId.toString());
        ExtensionTreatmentCodec treatmentCodec = device.as(ExtensionTreatmentCodec.class);
        ObjectNode node = treatmentCodec.encode(extensionInstruction.extensionInstruction(), context);
        result.set(InstructionCodec.EXTENSION, node);
    } else {
        throw new IllegalArgumentException(
                "There is no codec to encode extension for device " + deviceId.toString());
    }
}
 
Example 5
Source File: OpenstackNodeUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Adds or removes a network interface (aka port) into a given bridge of openstack node.
 *
 * @param osNode openstack node
 * @param bridgeName bridge name
 * @param intfName interface name
 * @param deviceService device service
 * @param addOrRemove add port is true, remove it otherwise
 */
public static synchronized void addOrRemoveSystemInterface(OpenstackNode osNode,
                                                           String bridgeName,
                                                           String intfName,
                                                           DeviceService deviceService,
                                                           boolean addOrRemove) {


    Device device = deviceService.getDevice(osNode.ovsdb());
    if (device == null || !device.is(BridgeConfig.class)) {
        log.info("device is null or this device if not ovsdb device");
        return;
    }
    BridgeConfig bridgeConfig =  device.as(BridgeConfig.class);

    if (addOrRemove) {
        bridgeConfig.addPort(BridgeName.bridgeName(bridgeName), intfName);
    } else {
        bridgeConfig.deletePort(BridgeName.bridgeName(bridgeName), intfName);
    }
}
 
Example 6
Source File: RulePopulatorUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Returns tunnel destination extension treatment object.
 *
 * @param deviceService driver service
 * @param deviceId device id to apply this treatment
 * @param remoteIp tunnel destination ip address
 * @return extension treatment
 */
public static ExtensionTreatment buildExtension(DeviceService deviceService,
                                                DeviceId deviceId,
                                                Ip4Address remoteIp) {
    Device device = deviceService.getDevice(deviceId);

    if (!checkTreatmentResolver(device)) {
        return null;
    }

    if (device == null) {
        return null;
    }

    ExtensionTreatmentResolver resolver = device.as(ExtensionTreatmentResolver.class);
    ExtensionTreatment treatment =
            resolver.getExtensionInstruction(NICIRA_SET_TUNNEL_DST.type());
    try {
        treatment.setPropertyValue(TUNNEL_DST, remoteIp);
        return treatment;
    } catch (ExtensionPropertyException e) {
        log.warn("Failed to get tunnelDst extension treatment for {} " +
                "because of {}", deviceId, e);
        return null;
    }
}
 
Example 7
Source File: HuaweiDeviceDescription.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Discovers device details, for huawei device by getting the system
 * information.
 *
 * @return device description
 */
@Override
public DeviceDescription discoverDeviceDetails() {
    NetconfSession session = getNetconfSession();
    String sysInfo;
    try {
        sysInfo = session.get(getVersionReq());
    } catch (NetconfException e) {
        throw new IllegalArgumentException(
                new NetconfException(DEV_INFO_FAILURE));
    }

    String[] details = parseSysInfoXml(sysInfo);
    DeviceService devSvc = checkNotNull(handler().get(DeviceService.class));
    DeviceId devId = handler().data().deviceId();
    Device dev = devSvc.getDevice(devId);
    return new DefaultDeviceDescription(dev.id().uri(), ROUTER,
                                        details[0], details[1],
                                        details[2], details[3],
                                        dev.chassisId());
}
 
Example 8
Source File: K8sNodeUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Adds or removes a network interface (aka port) into a given bridge of kubernetes node.
 *
 * @param k8sNode       kubernetes node
 * @param bridgeName    bridge name
 * @param intfName      interface name
 * @param deviceService device service
 * @param addOrRemove   add port is true, remove it otherwise
 */
public static synchronized void addOrRemoveSystemInterface(K8sNode k8sNode,
                                                           String bridgeName,
                                                           String intfName,
                                                           DeviceService deviceService,
                                                           boolean addOrRemove) {


    Device device = deviceService.getDevice(k8sNode.ovsdb());
    if (device == null || !device.is(BridgeConfig.class)) {
        log.info("device is null or this device if not ovsdb device");
        return;
    }
    BridgeConfig bridgeConfig =  device.as(BridgeConfig.class);

    if (addOrRemove) {
        bridgeConfig.addPort(BridgeName.bridgeName(bridgeName), intfName);
    } else {
        bridgeConfig.deletePort(BridgeName.bridgeName(bridgeName), intfName);
    }
}
 
Example 9
Source File: PolatisDeviceDescription.java    From onos with Apache License 2.0 6 votes vote down vote up
private DeviceDescription parseProductInformation() {
    DeviceService devsvc = checkNotNull(handler().get(DeviceService.class));
    DeviceId devid = handler().data().deviceId();
    Device dev = devsvc.getDevice(devid);
    if (dev == null) {
        return new DefaultDeviceDescription(devid.uri(), FIBER_SWITCH,
                DEFAULT_MANUFACTURER, DEFAULT_DESCRIPTION_DATA,
                DEFAULT_DESCRIPTION_DATA, DEFAULT_DESCRIPTION_DATA,
                new ChassisId());
    }
    String reply = netconfGet(handler(), getProductInformationFilter());
    subscribe(handler());
    HierarchicalConfiguration cfg = configAt(reply, KEY_DATA_PRODINF);
    return new DefaultDeviceDescription(dev.id().uri(), FIBER_SWITCH,
            cfg.getString(KEY_MANUFACTURER), cfg.getString(KEY_HWVERSION),
            cfg.getString(KEY_SWVERSION), cfg.getString(KEY_SERIALNUMBER),
            dev.chassisId());
}
 
Example 10
Source File: LumentumRoadmDiscovery.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDescription discoverDeviceDetails() {
    //TODO get device description
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    DeviceId deviceId = handler().data().deviceId();
    Device device = deviceService.getDevice(deviceId);
    return new DefaultDeviceDescription(device.id().uri(), Device.Type.ROADM,
                                        "Lumentum", "SDN ROADM", "1.0", "v1",
                                        device.chassisId(), (SparseAnnotations) device.annotations());
}
 
Example 11
Source File: LumentumNetconfRoadmDiscovery.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public List<PortDescription> discoverPortDetails() {
    DeviceId deviceId = handler().data().deviceId();
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    Device device = deviceService.getDevice(deviceId);

    //Get the configuration from the device
    if (device == null) {
        log.error("Lumentum NETCONF - device object not found for {}", deviceId);
        return ImmutableList.of();
    }

    NetconfSession session = getNetconfSession();
    if (session == null) {
        log.error("Lumentum NETCONF - session not found for {}", deviceId);
        return ImmutableList.of();
    }

    StringBuilder requestBuilder = new StringBuilder();
    requestBuilder.append("<physical-ports xmlns=\"http://www.lumentum.com/lumentum-ote-port\" ");
    requestBuilder.append("xmlns:lotep=\"http://www.lumentum.com/lumentum-ote-port\" ");
    requestBuilder.append("xmlns:lotepopt=\"http://www.lumentum.com/lumentum-ote-port-optical\" ");
    requestBuilder.append("xmlns:loteeth=\"http://www.lumentum.com/lumentum-ote-port-ethernet\">");
    requestBuilder.append("</physical-ports>");

    String reply;
    try {
        reply = session.get(requestBuilder.toString(), null);
    } catch (NetconfException e) {
        log.error("Lumentum NETCONF - " +
                "discoverPortDetails failed to retrieve port details {}", handler().data().deviceId(), e);
        return ImmutableList.of();
    }

    List<PortDescription> descriptions = parseLumentumRoadmPorts(XmlConfigParser.
                    loadXml(new ByteArrayInputStream(reply.getBytes())));

    return ImmutableList.copyOf(descriptions);
}
 
Example 12
Source File: CapabilityConstraint.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Validates the link based on capability constraint.
 *
 * @param link to validate source and destination based on capability constraint
 * @param deviceService instance of DeviceService
 * @param netCfgService instance of NetworkConfigService
 * @return true if link satisfies capability constraint otherwise false
 */
public boolean isValidLink(Link link, DeviceService deviceService, NetworkConfigService netCfgService) {
    if (deviceService == null || netCfgService == null) {
        return false;
    }

    Device srcDevice = deviceService.getDevice(link.src().deviceId());
    Device dstDevice = deviceService.getDevice(link.dst().deviceId());

    //TODO: Usage of annotations are for transient solution. In future will be replaced with the
    // network config service / Projection model.
    // L3 device
    if (srcDevice == null || dstDevice == null) {
        return false;
    }

    String srcLsrId = srcDevice.annotations().value(LSRID);
    String dstLsrId = dstDevice.annotations().value(LSRID);

    DeviceCapability srcDeviceConfig = netCfgService.getConfig(DeviceId.deviceId(srcLsrId),
                                                                   DeviceCapability.class);
    DeviceCapability dstDeviceConfig = netCfgService.getConfig(DeviceId.deviceId(dstLsrId),
                                                                   DeviceCapability.class);

    switch (capabilityType) {
    case WITH_SIGNALLING:
        return true;
    case WITHOUT_SIGNALLING_AND_WITHOUT_SR:
        return srcDeviceConfig != null && dstDeviceConfig != null
                && srcDeviceConfig.localLabelCap() && dstDeviceConfig.localLabelCap();
    case SR_WITHOUT_SIGNALLING:
        return srcDeviceConfig != null && dstDeviceConfig != null && srcDeviceConfig.srCap()
                && dstDeviceConfig.srCap() && srcDeviceConfig.labelStackCap() && dstDeviceConfig.labelStackCap();
    default:
        return false;
    }
}
 
Example 13
Source File: TapiDeviceDescriptionDiscovery.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public DeviceDescription discoverDeviceDetails() {
    log.debug("Getting device description");
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    DeviceId deviceId = handler().data().deviceId();
    Device device = deviceService.getDevice(deviceId);

    if (device == null) {
        //TODO need to obtain from the device.
        return new DefaultDeviceDescription(deviceId.uri(),
                Device.Type.OLS,
                "Tapi",
                "0",
                "2.1",
                "Unknown",
                new ChassisId(),
                DefaultAnnotations.builder().set("protocol", "REST").build());
    } else {
        return new DefaultDeviceDescription(device.id().uri(),
                Device.Type.OLS,
                device.manufacturer(),
                device.hwVersion(),
                device.swVersion(),
                device.serialNumber(),
                device.chassisId());
    }
}
 
Example 14
Source File: MeterViewMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected String noRowsMessage(ObjectNode payload) {
    String uri = string(payload, "devId");
    if (!Strings.isNullOrEmpty(uri)) {
        DeviceService ds = get(DeviceService.class);
        Device dev = ds.getDevice(DeviceId.deviceId(uri));

        if (meterNotSupported(dev)) {
            return NOT_SUPPORT_MESSAGE;
        }
    }
    return NO_ROWS_MESSAGE;
}
 
Example 15
Source File: TerminalDeviceDiscovery.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get the device instance for which the methods apply.
 *
 * @return The device instance
 */
private Device getDevice() {
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    Device device = deviceService.getDevice(did());
    return device;
}
 
Example 16
Source File: ClientLineTerminalDeviceDiscovery.java    From onos with Apache License 2.0 4 votes vote down vote up
/**
 * Get the device instance for which the methods apply.
 *
 * @return The device instance
 */
private Device getDevice() {
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    Device device = deviceService.getDevice(did());
    return device;
}
 
Example 17
Source File: PipeconfViewMessageHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void process(ObjectNode payload) {
    PiPipeconfService piPipeconfService = get(PiPipeconfService.class);
    DeviceService deviceService = get(DeviceService.class);
    ObjectNode responseData = objectNode();
    String devId = string(payload, DEVICE_ID);
    if (devId == null || devId.isEmpty()) {
        log.warn("{}: Invalid device id", PIPECONF_REQUEST);
        sendMessage(NO_PIPECONF_RESP, null);
        return;
    }
    DeviceId deviceId = DeviceId.deviceId(devId);
    Optional<PiPipeconfId> pipeconfId = piPipeconfService.ofDevice(deviceId);
    if (!pipeconfId.isPresent()) {
        log.warn("{}: Can't find pipeconf id for device {}", PIPECONF_REQUEST, deviceId);
        sendMessage(NO_PIPECONF_RESP, null);
        return;
    }

    Optional<PiPipeconf> pipeconf = piPipeconfService.getPipeconf(pipeconfId.get());
    if (!pipeconf.isPresent()) {
        log.warn("{}: Can't find pipeconf {}", PIPECONF_REQUEST, pipeconfId);
        sendMessage(NO_PIPECONF_RESP, null);
        return;
    }
    CodecContext codecContext = getJsonCodecContext();

    ObjectNode pipeconfData = codecContext.encode(pipeconf.get(), PiPipeconf.class);
    responseData.set(PIPECONF, pipeconfData);

    // Filtered out models not exists in interpreter
    // usually they generated by compiler automatically
    Device device = deviceService.getDevice(deviceId);
    if (device == null || !deviceService.isAvailable(deviceId)) {
        log.warn("{}: Device {} is not available", PIPECONF_REQUEST, deviceId);
        sendMessage(NO_PIPECONF_RESP, null);
        return;
    }
    PiPipelineModel pipelineModel = pipeconf.get().pipelineModel();

    ObjectNode pipelineModelData =
            codecContext.encode(pipelineModel, PiPipelineModel.class);
    responseData.set(PIPELINE_MODEL, pipelineModelData);

    sendMessage(PIPECONF_RESP, responseData);
}
 
Example 18
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 19
Source File: K8sNodeCheckCommand.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
protected void doExecute() {
    K8sNodeService nodeService = get(K8sNodeService.class);
    DeviceService deviceService = get(DeviceService.class);

    K8sNode node = nodeService.node(hostname);
    if (node == null) {
        print("Cannot find %s from registered nodes", hostname);
        return;
    }

    print("[Integration Bridge Status]");
    Device intgBridge = deviceService.getDevice(node.intgBridge());
    if (intgBridge != null) {
        print("%s %s=%s available=%s %s",
                deviceService.isAvailable(intgBridge.id()) ? MSG_OK : MSG_ERROR,
                INTEGRATION_BRIDGE,
                intgBridge.id(),
                deviceService.isAvailable(intgBridge.id()),
                intgBridge.annotations());
        printPortState(deviceService, node.intgBridge(), INTEGRATION_BRIDGE);
        printPortState(deviceService, node.intgBridge(), INTEGRATION_TO_EXTERNAL_BRIDGE);
        printPortState(deviceService, node.intgBridge(), INTEGRATION_TO_LOCAL_BRIDGE);
        if (node.dataIp() != null) {
            printPortState(deviceService, node.intgBridge(), VXLAN_TUNNEL);
            printPortState(deviceService, node.intgBridge(), GRE_TUNNEL);
            printPortState(deviceService, node.intgBridge(), GENEVE_TUNNEL);
        }
    } else {
        print("%s %s=%s is not available",
                MSG_ERROR,
                INTEGRATION_BRIDGE,
                node.intgBridge());
    }

    print("[External Bridge Status]");
    Device extBridge = deviceService.getDevice(node.extBridge());
    if (extBridge != null) {
        print("%s %s=%s available=%s %s",
                deviceService.isAvailable(extBridge.id()) ? MSG_OK : MSG_ERROR,
                EXTERNAL_BRIDGE,
                extBridge.id(),
                deviceService.isAvailable(extBridge.id()),
                extBridge.annotations());
        printPortState(deviceService, node.extBridge(), EXTERNAL_BRIDGE);
        printPortState(deviceService, node.extBridge(), PHYSICAL_EXTERNAL_BRIDGE);
    } else {
        print("%s %s=%s is not available",
                MSG_ERROR,
                EXTERNAL_BRIDGE,
                node.extBridge());
    }

    print("[Local Bridge Status]");
    Device localBridge = deviceService.getDevice(node.localBridge());
    if (localBridge != null) {
        print("%s %s=%s available=%s %s",
                deviceService.isAvailable(localBridge.id()) ? MSG_OK : MSG_ERROR,
                LOCAL_BRIDGE,
                localBridge.id(),
                deviceService.isAvailable(localBridge.id()),
                localBridge.annotations());
        printPortState(deviceService, node.localBridge(), LOCAL_BRIDGE);
        printPortState(deviceService, node.localBridge(), LOCAL_TO_INTEGRATION_BRIDGE);
    }
}
 
Example 20
Source File: CienaWaveserverAiDeviceDescription.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Returns the Device of the deviceId.
 *
 * @return device
 */
private Device getDevice(DeviceId deviceId) {
    DeviceService deviceService = checkNotNull(handler().get(DeviceService.class));
    return deviceService.getDevice(deviceId);
}