org.onosproject.net.device.DeviceService Java Examples

The following examples show how to use org.onosproject.net.device.DeviceService. 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: LinkDiscovery.java    From onos with Apache License 2.0 6 votes vote down vote up
private Optional<Device> findSourceDeviceByChassisId(DeviceService deviceService, MacAddress srcChassisId) {
    Supplier<Stream<Device>> deviceStream = () ->
            StreamSupport.stream(deviceService.getAvailableDevices().spliterator(), false);
    Optional<Device> remoteDeviceOptional = deviceStream.get()
            .filter(device -> device.chassisId() != null
                    && MacAddress.valueOf(device.chassisId().value()).equals(srcChassisId))
            .findAny();

    if (remoteDeviceOptional.isPresent()) {
        log.debug("sourceDevice found by chassis id: {}", srcChassisId);
        return remoteDeviceOptional;
    } else {
        remoteDeviceOptional = deviceStream.get().filter(device ->
                Tools.stream(deviceService.getPorts(device.id()))
                        .anyMatch(port -> port.annotations().keys().contains(AnnotationKeys.PORT_MAC)
                                && MacAddress.valueOf(port.annotations().value(AnnotationKeys.PORT_MAC))
                                .equals(srcChassisId)))
                .findAny();
        if (remoteDeviceOptional.isPresent()) {
            log.debug("sourceDevice found by port mac: {}", srcChassisId);
            return remoteDeviceOptional;
        } else {
            return Optional.empty();
        }
    }
}
 
Example #2
Source File: DeviceInterfacesListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
private void printDevice(DeviceService deviceService,
                         DriverService driverService,
                         Device device) {
    super.printDevice(deviceService, device);
    if (!device.is(InterfaceConfig.class)) {
        // The relevant behavior is not supported by the device.
        print(ERROR_RESULT);
        return;
    }
    DriverHandler h = driverService.createHandler(device.id());
    InterfaceConfig interfaceConfig = h.behaviour(InterfaceConfig.class);

    List<DeviceInterfaceDescription> interfaces =
            interfaceConfig.getInterfaces();
    if (interfaces == null) {
        print(ERROR_RESULT);
    } else if (interfaces.isEmpty()) {
        print(NO_INTERFACES);
    } else {
        interfaces.forEach(this::printInterface);
    }
}
 
Example #3
Source File: OplinkPowerConfigUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Find specified port power from port description.
 *
 * @param portNum the port number
 * @param annotation annotation in port description
 * @return power value in 0.01 dBm
 */
private Long getPortPower(PortNumber portNum, String annotation) {
    // Check if switch is connected, otherwise do not return value in store, which is obsolete.
    if (getOpenFlowDevice() == null) {
        // Warning already exists in method getOpenFlowDevice()
        return null;
    }
    final DriverHandler handler = behaviour.handler();
    DeviceService deviceService = handler.get(DeviceService.class);
    Port port = deviceService.getPort(handler.data().deviceId(), portNum);
    if (port == null) {
        log.warn("Unexpected port: {}", portNum);
        return null;
    }
    String power = port.annotations().value(annotation);
    if (power == null) {
        // Do not need warning here for port polling.
        log.debug("Cannot get {} from port {}.", annotation, portNum);
        return null;
    }
    return Long.valueOf(power);
}
 
Example #4
Source File: StatisticsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets port statistics of a specified device and port.
 * @onos.rsModel StatisticsPorts
 * @param deviceId device ID
 * @param port port
 * @return 200 OK with JSON encoded array of port statistics for the specified port
 */
@GET
@Path("ports/{deviceId}/{port}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortStatisticsByDeviceIdAndPort(@PathParam("deviceId") String deviceId,
                                                   @PathParam("port") String port) {
    final DeviceService service = get(DeviceService.class);
    final PortNumber portNumber = portNumber(port);
    final PortStatistics portStatsEntry =
            service.getStatisticsForPort(DeviceId.deviceId(deviceId), portNumber);
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
    if (portStatsEntry != null) {
        statisticsNode.add(codec(PortStatistics.class).encode(portStatsEntry, this));
    }
    rootArrayNode.add(deviceStatsNode);

    return ok(root).build();
}
 
Example #5
Source File: VirtualNetworkGroupManager.java    From onos with Apache License 2.0 6 votes vote down vote up
public VirtualNetworkGroupManager(VirtualNetworkService manager, NetworkId networkId) {
    super(manager, networkId, GroupEvent.class);

    store = serviceDirectory.get(VirtualNetworkGroupStore.class);
    deviceService = manager.get(networkId, DeviceService.class);

    providerRegistryService =
            serviceDirectory.get(VirtualProviderRegistryService.class);
    innerProviderService = new InternalGroupProviderService();
    providerRegistryService.registerProviderService(networkId(), innerProviderService);

    this.storeDelegate = new InternalStoreDelegate();
    store.setDelegate(networkId, this.storeDelegate);

    log.info("Started");
}
 
Example #6
Source File: StatisticsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets port delta statistics of a specified devices.
 * @onos.rsModel StatisticsPorts
 * @param deviceId device ID
 * @return 200 OK with JSON encoded array of port delta statistics
 */
@GET
@Path("delta/ports/{deviceId}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortDeltaStatisticsByDeviceId(@PathParam("deviceId") String deviceId) {
    final DeviceService service = get(DeviceService.class);
    final Iterable<PortStatistics> portStatsEntries =
            service.getPortDeltaStatistics(DeviceId.deviceId(deviceId));
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
    if (portStatsEntries != null) {
        for (final PortStatistics entry : portStatsEntries) {
            statisticsNode.add(codec(PortStatistics.class).encode(entry, this));
        }
    }
    rootArrayNode.add(deviceStatsNode);

    return ok(root).build();
}
 
Example #7
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 #8
Source File: StatisticsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets port delta statistics of a specified device and port.
 * @onos.rsModel StatisticsPorts
 * @param deviceId device ID
 * @param port port
 * @return 200 OK with JSON encoded array of port delta statistics for the specified port
 */
@GET
@Path("delta/ports/{deviceId}/{port}")
@Produces(MediaType.APPLICATION_JSON)
public Response getPortDeltaStatisticsByDeviceIdAndPort(@PathParam("deviceId") String deviceId,
                                                   @PathParam("port") String port) {
    final DeviceService service = get(DeviceService.class);
    final PortNumber portNumber = portNumber(port);
    final PortStatistics portStatsEntry =
            service.getDeltaStatisticsForPort(DeviceId.deviceId(deviceId), portNumber);
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    final ObjectNode deviceStatsNode = mapper().createObjectNode();
    deviceStatsNode.put("device", deviceId);
    final ArrayNode statisticsNode = deviceStatsNode.putArray("ports");
    if (portStatsEntry != null) {
        statisticsNode.add(codec(PortStatistics.class).encode(portStatsEntry, this));
    }
    rootArrayNode.add(deviceStatsNode);

    return ok(root).build();
}
 
Example #9
Source File: StatisticsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets sum of active entries in all tables for all devices.
 *
 * @onos.rsModel StatisticsFlowsActiveEntries
 * @return 200 OK with JSON encoded array of active entry count per device
 */
@GET
@Path("flows/activeentries")
@Produces(MediaType.APPLICATION_JSON)
public Response getActiveEntriesCountPerDevice() {
    final FlowRuleService service = get(FlowRuleService.class);
    final Iterable<Device> devices = get(DeviceService.class).getDevices();
    final ObjectNode root = mapper().createObjectNode();
    final ArrayNode rootArrayNode = root.putArray("statistics");
    for (final Device device : devices) {
        int activeEntries = service.getFlowRuleCount(device.id(), FlowEntry.FlowEntryState.ADDED);
        final ObjectNode entry = mapper().createObjectNode();
        entry.put("device", device.id().toString());
        entry.put("activeEntries", activeEntries);
        rootArrayNode.add(entry);
    }

    return ok(root).build();
}
 
Example #10
Source File: MastersListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    ClusterService service = get(ClusterService.class);
    MastershipService mastershipService = get(MastershipService.class);
    DeviceService deviceService = get(DeviceService.class);
    List<ControllerNode> nodes = newArrayList(service.getNodes());
    Collections.sort(nodes, Comparators.NODE_COMPARATOR);

    if (outputJson()) {
        print("%s", json(service, mastershipService, nodes));
    } else {
        for (ControllerNode node : nodes) {
            List<DeviceId> ids = Lists.newArrayList(mastershipService.getDevicesOf(node.id()));
            ids.removeIf(did -> deviceService.getDevice(did) == null);
            Collections.sort(ids, Comparators.ELEMENT_ID_COMPARATOR);
            print("%s: %d devices", node.id(), ids.size());
            for (DeviceId deviceId : ids) {
                print("  %s", deviceId);
            }
        }
    }
}
 
Example #11
Source File: Ofdpa2Pipeline.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void init(DeviceId deviceId, PipelinerContext context) {
    this.deviceId = deviceId;

    serviceDirectory = context.directory();
    coreService = serviceDirectory.get(CoreService.class);
    flowRuleService = serviceDirectory.get(FlowRuleService.class);
    groupService = serviceDirectory.get(GroupService.class);
    flowObjectiveStore = context.store();
    deviceService = serviceDirectory.get(DeviceService.class);
    // Init the accumulator, if enabled
    if (isAccumulatorEnabled(this)) {
        accumulator = new ForwardingObjectiveAccumulator(context.accumulatorMaxObjectives(),
                context.accumulatorMaxBatchMillis(),
                context.accumulatorMaxIdleMillis());
    }

    initDriverId();
    initGroupHander(context);

    initializePipeline();
}
 
Example #12
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 #13
Source File: Topo2Jsonifier.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates an instance with a reference to the services directory, so that
 * additional information about network elements may be looked up on
 * on the fly.
 *
 * @param directory service directory
 * @param userName  logged in user name
 */
public Topo2Jsonifier(ServiceDirectory directory, String userName) {
    this.directory = checkNotNull(directory, "Directory cannot be null");
    this.userName = checkNotNull(userName, "User name cannot be null");

    clusterService = directory.get(ClusterService.class);
    deviceService = directory.get(DeviceService.class);
    linkService = directory.get(LinkService.class);
    hostService = directory.get(HostService.class);
    mastershipService = directory.get(MastershipService.class);
    intentService = directory.get(IntentService.class);
    flowService = directory.get(FlowRuleService.class);
    flowStatsService = directory.get(StatisticService.class);
    portStatsService = directory.get(PortStatisticsService.class);
    topologyService = directory.get(TopologyService.class);
    uiextService = directory.get(UiExtensionService.class);
    prefService = directory.get(UiPreferencesService.class);
}
 
Example #14
Source File: GroupDriverProvider.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Initializes the provider with the necessary device service, group provider service,
 * mastership service and poll frequency.
 *
 * @param deviceService        device service
 * @param groupProviderService group provider service
 * @param mastershipService    mastership service
 * @param pollFrequency        group entry poll frequency
 */
void init(DeviceService deviceService, GroupProviderService groupProviderService,
          MastershipService mastershipService, int pollFrequency) {
    this.deviceService = deviceService;
    this.groupProviderService = groupProviderService;
    this.mastershipService = mastershipService;

    deviceService.addListener(deviceListener);

    if (poller != null && !poller.isCancelled()) {
        poller.cancel(false);
    }

    poller = executor.scheduleAtFixedRate(this::pollGroups, pollFrequency,
            pollFrequency, TimeUnit.SECONDS);

}
 
Example #15
Source File: GroupsListCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute() {
    DeviceService deviceService = get(DeviceService.class);
    GroupService groupService = get(GroupService.class);
    SortedMap<Device, List<Group>> sortedGroups =
            getSortedGroups(deviceService, groupService);

    if (referencedOnly && unreferencedOnly) {
        print("Options -r and -u cannot be used at the same time");
        return;
    }

    if (outputJson()) {
        print("%s", json(sortedGroups));
    } else {
        sortedGroups.forEach((device, groups) -> printGroups(device.id(), groups));
    }
}
 
Example #16
Source File: FlowsWebResource.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all flow entries for a table. Returns array of all flow rules for a table.
 * @param tableId table identifier
 * @return 200 OK with a collection of flows
 * @onos.rsModel FlowEntries
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("table/{tableId}")
public Response getTableFlows(@PathParam("tableId") int tableId) {
    ObjectNode root = mapper().createObjectNode();
    ArrayNode flowsNode = root.putArray(FLOWS);
    FlowRuleService service = get(FlowRuleService.class);
    Iterable<Device> devices = get(DeviceService.class).getDevices();
    for (Device device : devices) {
        Iterable<FlowEntry> flowEntries = service.getFlowEntries(device.id());
        if (flowEntries != null) {
            for (FlowEntry entry : flowEntries) {
                if (((IndexTableId) entry.table()).id() == tableId) {
                   flowsNode.add(codec(FlowEntry.class).encode(entry, this));
                }
            }
        }
    }

    return ok(root).build();
}
 
Example #17
Source File: CienaWaveserverDeviceDescription.java    From onos with Apache License 2.0 6 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) {
        return new DefaultDeviceDescription(deviceId.uri(),
                                            Device.Type.OTN,
                                            "Ciena",
                                            "WaveServer",
                                            "Unknown",
                                            "Unknown",
                                            new ChassisId());
    } else {
        return new DefaultDeviceDescription(device.id().uri(),
                                            Device.Type.OTN,
                                            device.manufacturer(),
                                            device.hwVersion(),
                                            device.swVersion(),
                                            device.serialNumber(),
                                            device.chassisId());
    }
}
 
Example #18
Source File: OFSwitchManager.java    From onos with Apache License 2.0 6 votes vote down vote up
private void processOFAgentStarted(OFAgent ofAgent) {
    devices(ofAgent.networkId()).forEach(deviceId -> {
        OFSwitch ofSwitch = ofSwitchMap.get(deviceId);
        if (ofSwitch != null) {
            connectController(ofSwitch, ofAgent.controllers());
        }
    });

    DeviceService deviceService = virtualNetService.get(
            ofAgent.networkId(),
            DeviceService.class);
    deviceService.addListener(deviceListener);

    PacketService packetService = virtualNetService.get(
            ofAgent.networkId(),
            PacketService.class);
    packetService.addProcessor(packetProcessor, PacketProcessor.director(0));

    FlowRuleService flowRuleService = virtualNetService.get(
            ofAgent.networkId(),
            FlowRuleService.class);
    flowRuleService.addListener(flowRuleListener);
}
 
Example #19
Source File: OplinkHandshakerUtil.java    From onos with Apache License 2.0 6 votes vote down vote up
private boolean linkValidation(DeviceService deviceService, OplinkPortAdjacency neighbor) {
    // check neighbor object
    if (neighbor == null) {
        return false;
    }
    // check src device is validate or not
    if (!deviceService.isAvailable(neighbor.getDeviceId())) {
        log.debug("Invalid adjacency device. devId = {}", neighbor.getDeviceId());
        return false;
    }
    // check src port is validate or not
    if (deviceService.getPort(neighbor.getDeviceId(), neighbor.getPort()) == null) {
        log.debug("Invalid adjacency port. devId = {}, port = {}",
                  neighbor.getDeviceId(), neighbor.getPort());
        return false;
    }
    // validate link
    return true;
}
 
Example #20
Source File: OplinkOpticalPowerConfig.java    From onos with Apache License 2.0 6 votes vote down vote up
private Range<Long> getPowerRange(PortNumber port, String directionKey, String minKey, String maxKey) {
    // TODO
    // Optical protection switch does not support power range configuration, it'll reply error.
    // To prevent replying error log flooding from netconf session when polling all ports information,
    // use general power range of [-60, 60] instead.
    if (handler().get(DeviceService.class).getDevice(data().deviceId()).type()
            == Device.Type.FIBER_SWITCH) {
        return RANGE_GENERAL;
    }
    String reply = netconfGet(handler(), getPowerRangeFilter(port, directionKey));
    HierarchicalConfiguration info = configAt(reply, KEY_PORTS_PORT_PROPERTY);
    if (info == null) {
        return null;
    }
    long minPower = (long) (info.getDouble(minKey) * POWER_MULTIPLIER);
    long maxPower = (long) (info.getDouble(maxKey) * POWER_MULTIPLIER);
    return Range.closed(minPower, maxPower);
}
 
Example #21
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 #22
Source File: Srv6SidCompleter.java    From onos-p4-tutorial with Apache License 2.0 6 votes vote down vote up
@Override
public int complete(Session session, CommandLine commandLine, List<String> candidates) {
    DeviceService deviceService = AbstractShellCommand.get(DeviceService.class);
    NetworkConfigService netCfgService = AbstractShellCommand.get(NetworkConfigService.class);

    // Delegate string completer
    StringsCompleter delegate = new StringsCompleter();
    SortedSet<String> strings = delegate.getStrings();

    stream(deviceService.getDevices())
            .map(d -> netCfgService.getConfig(d.id(), Srv6DeviceConfig.class))
            .filter(Objects::nonNull)
            .map(Srv6DeviceConfig::mySid)
            .filter(Objects::nonNull)
            .forEach(sid -> strings.add(sid.toString()));

    // Now let the completer do the work for figuring out what to offer.
    return delegate.complete(session, commandLine, candidates);
}
 
Example #23
Source File: DeviceViewMessageHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
private void populateRow(TableModel.Row row, Device dev,
                         DeviceService ds, MastershipService ms) {
    DeviceId id = dev.id();
    boolean available = ds.isAvailable(id);
    String iconId = available ? ICON_ID_ONLINE : ICON_ID_OFFLINE;

    row.cell(ID, id)
        .cell(NAME, deviceName(dev))
        .cell(AVAILABLE, available)
        .cell(AVAILABLE_IID, iconId)
        .cell(TYPE_IID, getTypeIconId(dev))
        .cell(MFR, dev.manufacturer())
        .cell(HW, dev.hwVersion())
        .cell(SW, dev.swVersion())
        .cell(PROTOCOL, deviceProtocol(dev))
        .cell(NUM_PORTS, ds.getPorts(id).size())
        .cell(MASTER_ID, ms.getMasterFor(id));
}
 
Example #24
Source File: GrooveOpenConfigDevicePowerConfig.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Range<Double>> getTargetPowerRange(PortNumber port, Object component) {
    // Only line ports have power
    DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
    DeviceId deviceId = did();
    if (deviceService.getPort(deviceId, port).type() == Port.Type.OCH) {
        return Optional.of(Range.open(-20., 6.));
    }
    return Optional.empty();
}
 
Example #25
Source File: VirtualNetworkDeviceManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests querying the port delta statistics of a device by null device identifier.
 */
@Test(expected = NullPointerException.class)
public void testGetPortsDeltaStatisticsByNullId() {
    manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
    VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
    DeviceService deviceService = manager.get(virtualNetwork.id(), DeviceService.class);

    // test the getPortDeltaStatistics() method using a null device identifier
    deviceService.getPortDeltaStatistics(null);
}
 
Example #26
Source File: ResourceDeviceListener.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an instance with the specified ResourceAdminService and ExecutorService.
 *
 * @param adminService instance invoked to register resources
 * @param resourceService {@link ResourceQueryService} to be used
 * @param deviceService {@link DeviceService} to be used
 * @param mastershipService {@link MastershipService} to be used
 * @param driverService {@link DriverService} to be used
 * @param netcfgService {@link NetworkConfigService} to be used.
 * @param executor executor used for processing resource registration
 */
ResourceDeviceListener(ResourceAdminService adminService, ResourceQueryService resourceService,
                       DeviceService deviceService, MastershipService mastershipService,
                       DriverService driverService, NetworkConfigService netcfgService,
                       ExecutorService executor) {
    this.adminService = checkNotNull(adminService);
    this.resourceService = checkNotNull(resourceService);
    this.deviceService = checkNotNull(deviceService);
    this.mastershipService = checkNotNull(mastershipService);
    this.driverService = checkNotNull(driverService);
    this.netcfgService = checkNotNull(netcfgService);
    this.executor = checkNotNull(executor);
}
 
Example #27
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 #28
Source File: VirtualNetworkDeviceManagerTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Tests querying the port statistics of a device by device identifier.
 */
@Test
public void testGetPortStatistics() {
    manager.registerTenantId(TenantId.tenantId(tenantIdValue1));
    VirtualNetwork virtualNetwork = manager.createVirtualNetwork(TenantId.tenantId(tenantIdValue1));
    VirtualDevice virtualDevice = manager.createVirtualDevice(virtualNetwork.id(), DID1);
    manager.createVirtualDevice(virtualNetwork.id(), DID2);

    DeviceService deviceService = manager.get(virtualNetwork.id(), DeviceService.class);

    // test the getPortStatistics() method
    assertEquals("The port statistics set size did not match.", 0,
                 deviceService.getPortStatistics(DID1).size());
}
 
Example #29
Source File: FlowsResourceTest.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Sets up the global values for all the tests.
 */
@Before
public void setUpTest() {
    // Mock device service
    expect(mockDeviceService.getDevice(deviceId1))
            .andReturn(device1);
    expect(mockDeviceService.getDevice(deviceId2))
            .andReturn(device2);
    expect(mockDeviceService.getDevices())
            .andReturn(ImmutableSet.of(device1, device2));

    // Mock Core Service
    expect(mockCoreService.getAppId(anyShort()))
            .andReturn(NetTestTools.APP_ID).anyTimes();
    expect(mockCoreService.getAppId(anyString()))
            .andReturn(NetTestTools.APP_ID).anyTimes();
    expect(mockCoreService.registerApplication(FlowRuleCodec.REST_APP_ID))
            .andReturn(APP_ID).anyTimes();
    replay(mockCoreService);

    // Register the services needed for the test
    final CodecManager codecService =  new CodecManager();
    codecService.activate();
    ServiceDirectory testDirectory =
            new TestServiceDirectory()
                    .add(FlowRuleService.class, mockFlowService)
                    .add(DeviceService.class, mockDeviceService)
                    .add(CodecService.class, codecService)
                    .add(CoreService.class, mockCoreService)
                    .add(ApplicationService.class, mockApplicationService);

    setServiceDirectory(testDirectory);
}
 
Example #30
Source File: Ovs.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isNext(WorkflowContext context) throws WorkflowException {

    DeviceId devId = OvsUtil.buildOfDeviceId(IpAddress.valueOf(strMgmtIp), DEVID_IDX_BRIDGE_OVERLAY);

    Device dev = context.getService(DeviceService.class).getDevice(devId);
    return dev != null;
}