org.onosproject.net.HostId Java Examples

The following examples show how to use org.onosproject.net.HostId. 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: HostManager.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void hostVanished(HostId hostId) {
    checkNotNull(hostId, HOST_ID_NULL);
    checkValidity();
    Host host = store.getHost(hostId);

    if (!allowedToChange(hostId)) {
        log.info("Request to remove {} is ignored due to provider mismatch", hostId);
        return;
    }

    if (monitorHosts) {
        host.ipAddresses().forEach(ip -> {
            monitor.stopMonitoring(ip);
        });
    }
    store.removeHost(hostId);
}
 
Example #2
Source File: OpenstackSwitchingHostProviderTest.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void hostDetected(HostId hostId, HostDescription hostDescription,
                         boolean replaceIps) {
    Host host = new DefaultHost(PROVIDER_ID,
            hostId,
            hostDescription.hwAddress(),
            hostDescription.vlan(),
            hostDescription.locations(),
            ImmutableSet.copyOf(hostDescription.ipAddress()),
            hostDescription.innerVlan(),
            hostDescription.tpid(),
            hostDescription.configured(),
            hostDescription.annotations());

    hostMap.put(hostId, host);
}
 
Example #3
Source File: DhcpRelayCommand.java    From onos with Apache License 2.0 6 votes vote down vote up
private String findNextHopIp6(Predicate<IpAddress> ipFilter, MacAddress nextHopMac, VlanId vlanId) {
    if (ipFilter == null || nextHopMac == null || vlanId == null) {
        return NA;
    }

    Host host = HOST_SERVICE.getHost(HostId.hostId(nextHopMac, vlanId));
    if (host == null) {
        return NA;
    }
    return host.ipAddresses().stream()
            .filter(ipFilter)
            .filter(ip -> ip.isLinkLocal())
            .map(Object::toString)
            .findFirst()
            .orElse(NA);
}
 
Example #4
Source File: ConnectPointCodec.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public ConnectPoint decode(ObjectNode json, CodecContext context) {
    if (json == null || !json.isObject()) {
        return null;
    }

    ElementId elementId;
    if (json.has(ELEMENT_DEVICE)) {
        elementId = DeviceId.deviceId(json.get(ELEMENT_DEVICE).asText());
    } else if (json.has(ELEMENT_HOST)) {
        elementId = HostId.hostId(json.get(ELEMENT_HOST).asText());
    } else {
        // invalid JSON
        return null;
    }
    PortNumber portNumber = portNumber(json.get(PORT).asText());
    return new ConnectPoint(elementId, portNumber);
}
 
Example #5
Source File: DistributedHostStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@Override
public void appendLocation(HostId hostId, HostLocation location) {
    log.debug("Appending location {} to host {}", location, hostId);
    hosts.compute(hostId, (id, existingHost) -> {
        if (existingHost != null) {
            checkState(Objects.equals(hostId.mac(), existingHost.mac()),
                    "Existing and new MAC addresses differ.");
            checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
                    "Existing and new VLANs differ.");

            // Move within the same switch
            // Simply replace old location that is on the same device
            Set<HostLocation> newLocations = Sets.newHashSet(location);
            existingHost.locations().stream().filter(loc -> !loc.deviceId().equals(location.deviceId()))
                    .forEach(newLocations::add);

            return new DefaultHost(existingHost.providerId(),
                    hostId, existingHost.mac(), existingHost.vlan(),
                    newLocations, existingHost.auxLocations(), existingHost.ipAddresses(),
                    existingHost.innerVlan(), existingHost.tpid(),
                    existingHost.configured(), existingHost.suspended(), existingHost.annotations());
        }
        return null;
    });
}
 
Example #6
Source File: HostResourceTest.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that a fetch of a non-existent object throws an exception.
 */
@Test
public void testBadGet() {

        expect(mockHostService.getHost(HostId.hostId("00:00:11:00:00:01/1")))
                .andReturn(null)
                .anyTimes();
        replay(mockHostService);

    WebTarget wt = target();
    try {
        wt.path("hosts/00:00:11:00:00:01/1").request().get(String.class);
        fail("Fetch of non-existent host did not throw an exception");
    } catch (NotFoundException ex) {
        assertThat(ex.getMessage(),
                containsString("HTTP 404 Not Found"));
    }
}
 
Example #7
Source File: TopologySimulator.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates simularted hosts for the specified device.
 *
 * @param deviceId   device identifier
 * @param portOffset port offset where to start attaching hosts
 */
public void createHosts(DeviceId deviceId, int portOffset) {
    String s = deviceId.toString();
    byte dByte = Byte.parseByte(s.substring(s.length() - 2), 16);
    // TODO: this limits the simulation to 256 devices & 256 hosts/device.
    byte[] macBytes = new byte[]{0, 0, 0, 0, dByte, 0};
    byte[] ipBytes = new byte[]{(byte) 192, (byte) 168, dByte, 0};

    for (int i = 0; i < hostCount; i++) {
        int port = portOffset + i + 1;
        macBytes[5] = (byte) (i + 1);
        ipBytes[3] = (byte) (i + 1);
        HostId id = hostId(MacAddress.valueOf(macBytes), VlanId.NONE);
        IpAddress ip = IpAddress.valueOf(IpAddress.Version.INET, ipBytes);
        hostProviderService.hostDetected(id, description(id, ip, deviceId, port), false);
    }
}
 
Example #8
Source File: DistributedDhcpRelayStore.java    From onos with Apache License 2.0 6 votes vote down vote up
@Activate
protected void activated() {
    dhcpRecords = storageService.<HostId, DhcpRecord>eventuallyConsistentMapBuilder()
            .withName("DHCP-Relay-Records")
            .withTimestampProvider((hostId, record) -> {
                if (record != null) {
                    return new WallClockTimestamp(record.lastSeen());
                } else {
                    return new WallClockTimestamp();
                }
            })
            .withSerializer(APP_KRYO)
            .build();
    listener = new InternalMapListener();
    dhcpRecords.addListener(listener);
}
 
Example #9
Source File: ModelCache.java    From onos with Apache License 2.0 5 votes vote down vote up
private void updateRegion(UiRegion region) {
    RegionId rid = region.id();
    Set<DeviceId> deviceIds = services.region().getRegionDevices(rid);
    Set<HostId> hostIds = services.region().getRegionHosts(rid);

    // Make sure device objects refer to their region
    deviceIds.forEach(d -> {
        UiDevice dev = uiTopology.findDevice(d);
        if (dev != null) {
            dev.setRegionId(rid);
        } else {
            // if we don't have the UiDevice in the topology, what can we do?
            log.warn("Region device {}, but we don't have UiDevice in topology", d);
        }
    });

    hostIds.forEach(d -> {
        UiHost host = uiTopology.findHost(d);
        if (host != null) {
            host.setRegionId(rid);
        } else {
            // if we don't have the UiDevice in the topology, what can we do?
            log.warn("Region host {}, but we don't have UiHost in topology", d);
        }
    });

    // Make sure the region object refers to the devices
    region.reconcileDevices(deviceIds);
    region.reconcileHosts(hostIds);

    fixupContainmentHierarchy(region);
}
 
Example #10
Source File: HostsWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new host based on JSON input and adds it to the current
 * host inventory.
 *
 * @param stream input JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel HostPut
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createAndAddHost(InputStream stream) {
    URI location;
    HostProviderRegistry hostProviderRegistry = get(HostProviderRegistry.class);
    InternalHostProvider hostProvider = new InternalHostProvider();
    try {
        // Parse the input stream
        ObjectNode root = readTreeFromStream(mapper(), stream);

        HostProviderService hostProviderService = hostProviderRegistry.register(hostProvider);
        hostProvider.setHostProviderService(hostProviderService);
        HostId hostId = hostProvider.parseHost(root);

        UriBuilder locationBuilder = uriInfo.getBaseUriBuilder()
                .path("hosts")
                .path(hostId.mac().toString())
                .path(hostId.vlanId().toString());
        location = locationBuilder.build();
    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    } finally {
        hostProviderRegistry.unregister(hostProvider);
    }

    return Response
            .created(location)
            .build();
}
 
Example #11
Source File: DistributedHostStoreTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testHostMoved() {
    // Host is updated with a second location
    MapEvent<HostId, DefaultHost> event = new MapEvent<>("event", HOSTID,
            new Versioned<>(HOST3, 1), new Versioned<>(HOST2, 0));
    // Expect: HOST_MOVED
    ecXHostStore.hostLocationTracker.event(event);
    assertEquals(HostEvent.Type.HOST_MOVED, delegate.lastEvent.type());
    assertEquals(HOST3, delegate.lastEvent.subject());
    assertEquals(HOST2, delegate.lastEvent.prevSubject());
}
 
Example #12
Source File: DistributedMcastRoutesStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void removeSource(McastRoute route, HostId source) {
    mcastRoutes.compute(route, (k, v) -> {
        v.removeSource(source);
        // Since there are no sources, we should remove the route
        return v.sources().isEmpty() ? null : v;
    });
}
 
Example #13
Source File: TopologyViewMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private Set<HostId> getHostIds(ArrayNode ids) {
    Set<HostId> hostIds = new HashSet<>();
    for (JsonNode id : ids) {
        hostIds.add(hostId(id.asText()));
    }
    return hostIds;
}
 
Example #14
Source File: DistributedMcastRoutesStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void removeSink(McastRoute route, HostId hostId) {
    mcastRoutes.compute(route, (k, v) -> {
        v.removeSinks(hostId);
        return v;
    });
}
 
Example #15
Source File: McastRouteWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Create new multicast route.
 *
 * @param stream multicast route JSON
 * @return status of the request - CREATED if the JSON is correct,
 * BAD_REQUEST if the JSON is invalid
 * @onos.rsModel McastRoute
 */
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response createRoute(InputStream stream) {
    MulticastRouteService service = get(MulticastRouteService.class);
    try {
        ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
        McastRoute route = codec(McastRoute.class).decode(jsonTree, this);
        service.add(route);

        Set<HostId> sources = new HashSet<>();
        jsonTree.path(SOURCES).elements().forEachRemaining(src -> {
            sources.add(HostId.hostId(src.asText()));
        });
        Set<HostId> sinks = new HashSet<>();
        jsonTree.path(SINKS).elements().forEachRemaining(sink -> {
            sinks.add(HostId.hostId(sink.asText()));
        });

        if (!sources.isEmpty()) {
            sources.forEach(source -> {
                service.addSource(route, source);
            });
        }
        if (!sinks.isEmpty()) {
            sinks.forEach(sink -> {
                service.addSink(route, sink);
            });
        }

    } catch (IOException ex) {
        throw new IllegalArgumentException(ex);
    }

    return Response
            .created(URI.create(""))
            .build();
}
 
Example #16
Source File: DistributedMcastRoutesStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void removeSinks(McastRoute route, Set<ConnectPoint> sinks) {
    mcastRoutes.compute(route, (k, v) -> {
        v.removeSinks(HostId.NONE, sinks);
        return v;
    });
}
 
Example #17
Source File: McastUtils.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Gets sinks of given multicast group.
 *
 * @param mcastIp multicast IP
 * @return map of sinks or empty map if not found
 */
Map<HostId, Set<ConnectPoint>> getSinks(IpAddress mcastIp) {
    // TODO we should support different types of routes
    McastRoute mcastRoute = srManager.multicastRouteService.getRoutes().stream()
            .filter(mcastRouteInternal -> mcastRouteInternal.group().equals(mcastIp))
            .findFirst().orElse(null);
    return mcastRoute == null ?
            ImmutableMap.of() :
            srManager.multicastRouteService.routeData(mcastRoute).sinks();
}
 
Example #18
Source File: McastRouteWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Deletes a sink connect points for a given host for a specific route.
 *
 * @param group  group IP address
 * @param srcIp  source IP address
 * @param hostId sink host
 * @return 204 NO CONTENT
 */
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Path("sinks/{group}/{srcIp}/{hostId}")
public Response deleteHostSinks(@PathParam("group") String group,
                                @PathParam("srcIp") String srcIp,
                                @PathParam("hostId") String hostId) {
    Optional<McastRoute> route = getMcastRoute(group, srcIp);
    route.ifPresent(mcastRoute -> get(MulticastRouteService.class)
            .removeSink(mcastRoute, HostId.hostId(hostId)));
    return Response.noContent().build();
}
 
Example #19
Source File: TopoIntentFilter.java    From onos with Apache License 2.0 5 votes vote down vote up
private boolean isIntentRelevantToHosts(HostToHostIntent intent, Iterable<Host> hosts) {
    for (Host host : hosts) {
        HostId id = host.id();
        // Bail if intent does not involve this host.
        if (!id.equals(intent.one()) && !id.equals(intent.two())) {
            return false;
        }
    }
    return true;
}
 
Example #20
Source File: TopologyViewMessageHandlerBase.java    From onos with Apache License 2.0 5 votes vote down vote up
protected PropertyPanel edgeLinkDetails(HostId hid, ConnectPoint cp) {
    log.debug("generate prop panel data for edgelink {} {}", hid, cp);
    LionBundle lion = getLionBundle(LION_TOPO);
    String title = lion.getSafe("title_edge_link");

    PropertyPanel pp = new PropertyPanel(title, LINK_GLYPH);
    addLinkHostProps(pp, hid, lion);
    addLinkCpBProps(pp, cp, lion);
    return pp;
}
 
Example #21
Source File: DhcpListAllMappings.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {

    DhcpService dhcpService = AbstractShellCommand.get(DhcpService.class);
    Map<HostId, IpAssignment> allocationMap = dhcpService.listMapping();

    for (Map.Entry<HostId, IpAssignment> entry : allocationMap.entrySet()) {
        print(DHCP_MAPPING_FORMAT, entry.getKey().toString(), entry.getValue().ipAddress().toString());
    }
}
 
Example #22
Source File: DhcpWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Post a new static MAC/IP binding.
 * Registers a static binding to the DHCP server, and displays the current set of bindings.
 *
 * @onos.rsModel DhcpConfigPut
 * @param stream JSON stream
 * @return 200 OK
 */
@POST
@Path("mappings")
@Consumes(MediaType.APPLICATION_JSON)
public Response setMapping(InputStream stream) {
    ObjectNode root = mapper().createObjectNode();
    try {
        ObjectNode jsonTree = readTreeFromStream(mapper(), stream);
        JsonNode macID = jsonTree.get("mac");
        JsonNode ip = jsonTree.get("ip");
        if (macID != null && ip != null) {
            IpAssignment ipAssignment = IpAssignment.builder()
                    .ipAddress(Ip4Address.valueOf(ip.asText()))
                    .leasePeriod(service.getLeaseTime())
                    .timestamp(new Date())
                    .assignmentStatus(Option_Requested)
                    .build();

            if (!service.setStaticMapping(MacAddress.valueOf(macID.asText()),
                                          ipAssignment)) {
                throw new IllegalArgumentException("Static Mapping Failed. " +
                                                           "The IP maybe unavailable.");
            }
        }

        final Map<HostId, IpAssignment> intents = service.listMapping();
        ArrayNode arrayNode = root.putArray("mappings");
        intents.entrySet().forEach(i -> arrayNode.add(mapper().createObjectNode()
                                                              .put("host", i.getKey().toString())
                                                              .put("ip", i.getValue().ipAddress().toString())));
    } catch (IOException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
    return ok(root).build();
}
 
Example #23
Source File: MulticastRouteManager.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public void removeSource(McastRoute route, HostId source) {
    checkNotNull(route, "Route cannot be null");
    checkNotNull(source, "Source cannot be null");
    if (checkRoute(route)) {
        store.removeSource(route, source);
    }
}
 
Example #24
Source File: DistributedHostStoreTest.java    From onos with Apache License 2.0 5 votes vote down vote up
@Test
public void testHostUpdated() {
    // Host is updated with an IP
    MapEvent<HostId, DefaultHost> event = new MapEvent<>("event", HOSTID,
            new Versioned<>(HOST2, 1), new Versioned<>(HOST1, 0));
    // Expect: HOST_UPDATED
    ecXHostStore.hostLocationTracker.event(event);
    assertEquals(HostEvent.Type.HOST_UPDATED, delegate.lastEvent.type());
    assertEquals(HOST2, delegate.lastEvent.subject());
    assertEquals(HOST1, delegate.lastEvent.prevSubject());
}
 
Example #25
Source File: DistributedVirtualNetworkStore.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
public Set<VirtualHost> getHosts(NetworkId networkId) {
    checkState(networkExists(networkId), "The network has not been added.");
    Set<HostId> hostIdSet = networkIdHostIdSetMap.get(networkId);
    Set<VirtualHost> virtualHostSet = new HashSet<>();
    if (hostIdSet != null) {
        hostIdSet.forEach(hostId -> virtualHostSet.add(hostIdVirtualHostMap.get(hostId)));
    }
    return ImmutableSet.copyOf(virtualHostSet);
}
 
Example #26
Source File: CreateNullHost.java    From onos with Apache License 2.0 5 votes vote down vote up
@Override
protected void doExecute() {
    NullProviders service = get(NullProviders.class);
    NetworkConfigService cfgService = get(NetworkConfigService.class);

    TopologySimulator simulator = service.currentSimulator();
    if (!validateSimulator(simulator) || !validateLocType(locType)) {
        return;
    }

    CustomTopologySimulator sim = (CustomTopologySimulator) simulator;
    HostId id = sim.nextHostId();
    Set<HostLocation> locations;
    try {
        locations = getLocations(sim, deviceNames);
    } catch (NoLocationException e) {
        error("\u001B[1;31mHost not created - no location (free port) available on %s\u001B[0m", e.getMessage());
        return;
    }
    Set<IpAddress> ips = getIps(hostIps);

    BasicHostConfig cfg = cfgService.addConfig(id, BasicHostConfig.class);
    setUiCoordinates(cfg, locType, latOrY, longOrX);

    Tools.delay(10);
    sim.createHost(id, locations, ips);
}
 
Example #27
Source File: Dhcp6HandlerImpl.java    From onos with Apache License 2.0 5 votes vote down vote up
public Ip6Address findNextHopIp6FromRelayStore(Ip6Address clientAddress) {

        DhcpRecord dr = getDhcpRelayRecordFor(clientAddress);
        if (dr != null) {
            Optional<MacAddress> nextHopMac = dr.nextHop();
            if (nextHopMac.isPresent()) {
                // find the local ip6 from the host store
                HostId gwHostId = HostId.hostId(nextHopMac.get(), dr.vlanId());
                Host gwHost = hostService.getHost(gwHostId);
                if (gwHost == null) {
                    log.warn("Can't find next hop host ID {}", gwHostId);
                    return null;
                }
                Ip6Address nextHopIp = gwHost.ipAddresses()
                        .stream()
                        .filter(IpAddress::isIp6)
                        .filter(IpAddress::isLinkLocal)
                        .map(IpAddress::getIp6Address)
                        .findFirst()
                        .orElse(null);

                log.info("findNextHopIp6FromRelayStore " + clientAddress + " got mac " +
                                 nextHopMac.toString() + " ip6 " + nextHopIp);
                return nextHopIp;
            }
        } else {
            log.warn("findNextHopIp6FromRelayStore could NOT find next hop for " + clientAddress);
            return null;
        }
        return null;
    }
 
Example #28
Source File: DhcpWebResource.java    From onos with Apache License 2.0 5 votes vote down vote up
/**
 * Get all MAC/IP mappings.
 * Shows all MAC/IP mappings held by the DHCP server.
 *
 * @onos.rsModel DhcpConfigGetMappings
 * @return 200 OK
 */
@GET
@Path("mappings")
public Response listMappings() {
    ObjectNode root = mapper().createObjectNode();

    Map<HostId, IpAssignment> intents = service.listMapping();
    ArrayNode arrayNode = root.putArray("mappings");
    intents.entrySet().forEach(i -> arrayNode.add(mapper().createObjectNode()
                                                          .put("host", i.getKey().toString())
                                                          .put("ip", i.getValue().ipAddress().toString())));

    return ok(root).build();
}
 
Example #29
Source File: AppUiTopovMessageHandler.java    From onos with Apache License 2.0 5 votes vote down vote up
private void updateForMode(String id) {
    log.debug("host service: {}", hostService);
    log.debug("device service: {}", deviceService);

    try {
        HostId hid = HostId.hostId(id);
        log.debug("host id {}", hid);
        elementOfNote = hostService.getHost(hid);
        log.debug("host element {}", elementOfNote);

    } catch (Exception e) {
        try {
            DeviceId did = DeviceId.deviceId(id);
            log.debug("device id {}", did);
            elementOfNote = deviceService.getDevice(did);
            log.debug("device element {}", elementOfNote);

        } catch (Exception e2) {
            log.debug("Unable to process ID [{}]", id);
            elementOfNote = null;
        }
    }

    switch (currentMode) {
        case MOUSE:
            sendMouseData();
            break;

        case LINK:
            sendLinkData();
            break;

        default:
            break;
    }

}
 
Example #30
Source File: MulticastRouteManager.java    From onos with Apache License 2.0 5 votes vote down vote up
private void eventRemoveSources(HostId hostId, Set<HostLocation> removedSources, Set<McastRoute> routesForSource) {
    Set<ConnectPoint> sources = new HashSet<>();
    // Build sink using host location
    sources.addAll(removedSources);
    // Remove from each route the provided sinks
    routesForSource.forEach(route -> store.removeSources(route, hostId, sources));
}