下面列出了io.fabric8.kubernetes.api.model.EndpointSubset#org.onosproject.net.DeviceId 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Creates a flow rule for the L2 table mapping the given next hop MAC to
* the given output port.
* <p>
* This is called by the routing policy methods below to establish L2-based
* forwarding inside the fabric, e.g., when deviceId is a leaf switch and
* nextHopMac is the one of a spine switch.
*
* @param deviceId the device
* @param nexthopMac the next hop (destination) mac
* @param outPort the output port
*/
private FlowRule createL2NextHopRule(DeviceId deviceId, MacAddress nexthopMac,
PortNumber outPort) {
final String tableId = "IngressPipeImpl.l2_exact_table";
final PiCriterion match = PiCriterion.builder()
.matchExact(PiMatchFieldId.of("hdr.ethernet.dst_addr"),
nexthopMac.toBytes())
.build();
final PiAction action = PiAction.builder()
.withId(PiActionId.of("IngressPipeImpl.set_egress_port"))
.withParameter(new PiActionParam(
PiActionParamId.of("port_num"),
outPort.toLong()))
.build();
return Utils.buildFlowRule(
deviceId, appId, tableId, match, action);
}
/**
* Matches an obstacle constraint against a JSON representation of the
* constraint.
*
* @param obstacleConstraint constraint object to match
* @param constraintJson JSON representation of the constraint
* @return true if the constraint and JSON match, false otherwise.
*/
private boolean matchObstacleConstraint(ObstacleConstraint obstacleConstraint,
JsonNode constraintJson) {
final JsonNode obstaclesJson = constraintJson.get("obstacles");
if (obstaclesJson.size() != obstacleConstraint.obstacles().size()) {
return false;
}
for (int obstaclesIndex = 0; obstaclesIndex < obstaclesJson.size();
obstaclesIndex++) {
boolean obstacleFound = false;
final String obstacleJson = obstaclesJson.get(obstaclesIndex)
.asText();
for (DeviceId obstacle : obstacleConstraint.obstacles()) {
if (obstacle.toString().equals(obstacleJson)) {
obstacleFound = true;
}
}
if (!obstacleFound) {
return false;
}
}
return true;
}
private void handlePortStatusEvent(InternalPortStatusEvent event) {
ProviderId providerId = event.providerId();
DeviceId deviceId = event.deviceId();
Timestamped<PortDescription> portDescription = event.portDescription();
if (getDevice(deviceId) == null) {
log.debug("{} not found on this node yet, ignoring.", deviceId);
// Note: dropped information will be recovered by anti-entropy
return;
}
try {
notifyDelegateIfNotNull(updatePortStatusInternal(providerId, deviceId, portDescription));
} catch (Exception e) {
log.warn("Exception thrown handling port update", e);
}
}
@Test
public void renderExtensionInstruction() {
title("renderExtensionInstruction");
ExtensionTreatment extn = new Ofdpa3SetMplsType((short) 32);
DeviceId devid = deviceId(DEV_OF_204);
instr = Instructions.extension(extn, devid);
string = instr.toString();
render = handler.renderInstructionForDisplay(instr);
print(string);
print(render);
assertEquals("unexpected toString", EXT_FULL_STR, string);
assertEquals("unexpected short string", EXT_NO_DPID, render);
}
@Override
public void bindPort(NetworkId networkId, DeviceId deviceId,
PortNumber portNumber, ConnectPoint realizedBy) {
Set<VirtualPort> virtualPortSet = networkIdVirtualPortSetMap
.get(networkId);
Optional<VirtualPort> virtualPortOptional = virtualPortSet.stream().filter(
p -> p.element().id().equals(deviceId) &&
p.number().equals(portNumber)).findFirst();
checkState(virtualPortOptional.isPresent(), "The virtual port has not been added.");
VirtualDevice device = deviceIdVirtualDeviceMap.get(new VirtualDeviceId(networkId, deviceId));
checkNotNull(device, "The device has not been created for deviceId: "
+ deviceId);
VirtualPort vPort = virtualPortOptional.get();
virtualPortSet.remove(vPort);
vPort = new DefaultVirtualPort(networkId, device, portNumber, realizedBy);
virtualPortSet.add(vPort);
networkIdVirtualPortSetMap.put(networkId, virtualPortSet);
notifyDelegate(new VirtualNetworkEvent(VirtualNetworkEvent.Type.VIRTUAL_PORT_UPDATED,
networkId, device, vPort));
}
@Override
public MastershipRole getRole(NetworkId networkId, NodeId nodeId, DeviceId deviceId) {
Map<DeviceId, NodeId> masterMap = getMasterMap(networkId);
Map<DeviceId, List<NodeId>> backups = getBackups(networkId);
//just query
NodeId current = masterMap.get(deviceId);
MastershipRole role;
if (current != null && current.equals(nodeId)) {
return MastershipRole.MASTER;
}
if (backups.getOrDefault(deviceId, Collections.emptyList()).contains(nodeId)) {
role = MastershipRole.STANDBY;
} else {
role = MastershipRole.NONE;
}
return role;
}
@Override
protected void doExecute() {
ProxyTest proxyTest = get(ProxyTest.class);
TestProxy proxy;
if ("node".equals(type)) {
NodeId nodeId = NodeId.nodeId(arg1);
proxy = proxyTest.getProxyFor(nodeId);
} else if ("master".equals(type)) {
DeviceId deviceId = DeviceId.deviceId(arg1);
proxy = proxyTest.getProxyFor(deviceId);
} else {
throw new IllegalArgumentException("Unknown operation type " + type);
}
if ("sync".equals(operation)) {
print("%s", proxy.testSync(arg2));
} else if ("async".equals(operation)) {
try {
print("%s", proxy.testAsync(arg2).get(10, TimeUnit.SECONDS));
} catch (InterruptedException | ExecutionException | TimeoutException e) {
throw new IllegalStateException(e);
}
} else {
throw new IllegalArgumentException("Unknown operation " + operation);
}
}
@Override
public String getMergedDriver(DeviceId deviceId, PiPipeconfId pipeconfId) {
log.debug("Starting device driver merge of {} with {}...", deviceId, pipeconfId);
final BasicDeviceConfig basicDeviceConfig = cfgService.getConfig(
deviceId, BasicDeviceConfig.class);
if (basicDeviceConfig == null) {
log.warn("Unable to get basic device config for {}, " +
"aborting pipeconf driver merge", deviceId);
return null;
}
String baseDriverName = basicDeviceConfig.driver();
if (baseDriverName == null) {
log.warn("Missing driver from basic device config for {}, " +
"cannot produce merged driver", deviceId);
return null;
}
if (isMergedDriverName(baseDriverName)) {
// The config already has driver name that is a merged one. We still
// need to make sure an instance of that merged driver is present in
// this node.
log.debug("Base driver of {} ({}) is a merged one",
deviceId, baseDriverName);
baseDriverName = getBaseDriverNameFromMerged(baseDriverName);
}
return doMergeDriver(baseDriverName, pipeconfId);
}
private boolean hasBehaviour(DeviceId deviceId, Class<? extends Behaviour> type) {
Driver driver = getDriver(deviceId);
if (driver == null) {
return false;
}
return driver.hasBehaviour(type);
}
/**
* Releases allocated adjacency label of a link.
*
* @param link link
*/
public void releaseAdjacencyLabel(Link link) {
checkNotNull(link, LINK_NULL);
Device specificDevice = deviceService.getDevice(link.src().deviceId());
// Retrieve lsrId of a specific device
if (specificDevice.annotations() == null) {
log.debug("Device {} does not have annotations.", specificDevice.toString());
return;
}
String lsrId = specificDevice.annotations().value(LSRID);
if (lsrId == null) {
log.debug("Unable to retrieve lsr-id of a device {}.", specificDevice.toString());
return;
}
// Get capability config from netconfig
DeviceCapability cfg = netCfgService.getConfig(DeviceId.deviceId(lsrId), DeviceCapability.class);
if (cfg == null) {
log.error("Unable to find corresponding capabilty for a lsrd {} from NetConfig.", lsrId);
return;
}
// Check whether device has SR-TE Capability
if (cfg.labelStackCap()) {
if (!srTeHandler.releaseAdjacencyLabel(link)) {
log.error("Unable to release adjacency labels for a link {}.", link.toString());
}
}
}
/**
* Encodes a waypoint constraint.
*
* @return JSON ObjectNode representing the constraint
*/
private ObjectNode encodeWaypointConstraint() {
checkNotNull(constraint, "Waypoint constraint cannot be null");
final WaypointConstraint waypointConstraint =
(WaypointConstraint) constraint;
final ObjectNode result = context.mapper().createObjectNode();
final ArrayNode jsonWaypoints = result.putArray("waypoints");
for (DeviceId did : waypointConstraint.waypoints()) {
jsonWaypoints.add(did.toString());
}
return result;
}
/**
* Tests the instance port decoding.
*/
@Test
public void testInstancePortDecode() throws IOException {
InstancePort port = getInstancePort("InstancePort.json");
assertThat(port.networkId(), is("net-id-1"));
assertThat(port.portId(), is("port-id-1"));
assertThat(port.deviceId(), is(DeviceId.deviceId("of:000000000000000a")));
assertThat(port.portNumber(), is(PortNumber.portNumber(1, "tap-1")));
assertThat(port.ipAddress(), is(IpAddress.valueOf("10.10.10.1")));
assertThat(port.macAddress(), is(MacAddress.valueOf("11:22:33:44:55:66")));
assertThat(port.state().name(), is("ACTIVE"));
}
/**
* Retrieves device id from Resource id.
*
* @param path associated with the event
* @return the deviceId of the effected device
*/
@Beta
public DeviceId getDeviceId(ResourceId path) {
String resId = ResourceIdParser.parseResId(path);
String[] el = resId.split(ResourceIdParser.EL_CHK);
if (el.length < 3) {
throw new IllegalStateException(new NetconfException("Invalid resource id, cannot apply"));
}
if (!el[2].contains((ResourceIdParser.KEY_SEP))) {
throw new IllegalStateException(new NetconfException("Invalid device id key, cannot apply"));
}
String[] keys = el[2].split(ResourceIdParser.KEY_CHK);
if (keys.length < 2) {
throw new IllegalStateException(new NetconfException("Invalid device id key, cannot apply"));
}
String[] parts = keys[1].split(ResourceIdParser.NM_CHK);
if (parts.length < 3) {
throw new IllegalStateException(new NetconfException("Invalid device id key, cannot apply"));
}
String[] temp = parts[2].split("\\:");
String ip, port;
if (temp.length != 3) {
throw new IllegalStateException(new NetconfException("Invalid device id form, cannot apply"));
}
ip = temp[1];
port = temp[2];
try {
return DeviceId.deviceId(new URI("netconf", ip + ":" + port, (String) null));
} catch (URISyntaxException ex) {
throw new IllegalArgumentException("Unable to build deviceID for device " + ip + ":" + port, ex);
}
}
private FilteredConnectPoint getFilteredPointFromLink(Link link) {
FilteredConnectPoint filteredConnectPoint;
if (link.src().elementId() instanceof DeviceId) {
filteredConnectPoint = new FilteredConnectPoint(link.src());
} else if (link.dst().elementId() instanceof DeviceId) {
filteredConnectPoint = new FilteredConnectPoint(link.dst());
} else {
throw new IntentCompilationException(DEVICE_ID_NOT_FOUND);
}
return filteredConnectPoint;
}
@Override
public DefaultOutboundPacket read(Kryo kryo, Input input,
Class<DefaultOutboundPacket> type) {
DeviceId sendThrough = (DeviceId) kryo.readClassAndObject(input);
TrafficTreatment treatment = (TrafficTreatment) kryo.readClassAndObject(input);
byte[] data = (byte[]) kryo.readClassAndObject(input);
return new DefaultOutboundPacket(sendThrough, treatment, ByteBuffer.wrap(data));
}
/**
* Turn the current monitoring data into a data
* structure that can feed the Throughput UI memory.
*
* @param deviceId the device ID being monitored
* @param length the length of the array
* @param monStats a MonitoringStatistics object
* @return a map of throughput metrics to their values
*/
private Map<Integer, Float> populateThroughputData(
DeviceId deviceId, int length, MonitoringStatistics monStats) {
Map<Integer, Float> data = initializeMapData(MAX_COLUMNS_NB);
for (CpuStatistics stats : monStats.cpuStatisticsAll()) {
int index = stats.id();
Float value = null;
if ((stats.averageThroughput().isPresent()) && (stats.load() > MIN_CPU_LOAD)) {
value = stats.averageThroughput().get();
} else {
value = new Float(0);
}
// Unit conversion
ThroughputUnit throughputUnit = null;
if (stats.throughputUnit().isPresent()) {
throughputUnit = (ThroughputUnit) stats.throughputUnit().get();
} else {
throughputUnit = ThroughputUnit.BPS;
}
value = ThroughputUnit.toGbps(value, throughputUnit);
// Store it locally
addToCache(deviceId, length, index, value);
// And into the map
data.put(index, value);
}
return data;
}
private boolean hasEnoughBandwidth(ConnectPoint cp) {
if (cp.elementId() instanceof DeviceId) {
Device device = deviceService.getDevice(cp.deviceId());
Device.Type type = device.type();
if (isTransportLayer(type)) {
// Check if the port has enough capacity
Port port = deviceService.getPort(cp.deviceId(), cp.port());
if (port instanceof OduCltPort || port instanceof OchPort) {
// Port with capacity
return bandwidth.bps() < port.portSpeed() * 1000000.0;
} else {
// Port without valid capacity (OMS port, etc.)
return true;
}
} else {
// Check if enough amount of bandwidth resource remains
ContinuousResource resource = Resources.continuous(cp.deviceId(), cp.port(), Bandwidth.class)
.resource(bandwidth.bps());
try {
return resourceService.isAvailable(resource);
} catch (Exception e) {
log.error("Resource service failed checking availability of {}",
resource, e);
throw e;
}
}
}
return false;
}
private void discoverPorts(DeviceId deviceId) {
Device device = deviceService.getDevice(deviceId);
if (device.is(DeviceDescriptionDiscovery.class)) {
DeviceDescriptionDiscovery deviceDescriptionDiscovery = device.as(DeviceDescriptionDiscovery.class);
providerService.updatePorts(deviceId, deviceDescriptionDiscovery.discoverPortDetails());
} else {
log.warn("Device " + deviceId + " does not support behaviour DeviceDescriptionDiscovery");
}
}
/**
* Tests the result of a rest api GET for classifiers.
*/
@Test
public void testClassifiers() {
DeviceId devId1 = did("dev1");
Device device1 = device("dev1");
expect(classifierService.getClassifiers()).andReturn(ImmutableList.of(devId1)).anyTimes();
replay(classifierService);
final WebTarget wt = target();
final String response = wt.path("classifiers").request().get(String.class);
final JsonObject result = Json.parse(response).asObject();
assertThat(result, notNullValue());
}
private List<PortAuthState> reportPortsAuthState() {
List<PortAuthState> result = new ArrayList<>();
for (Map.Entry<DeviceId, Map<PortNumber, BlockState>> entry :
blockedPorts.entrySet()) {
DeviceId d = entry.getKey();
Map<PortNumber, BlockState> portMap = entry.getValue();
for (PortNumber p : portMap.keySet()) {
result.add(new PortAuthState(d, p, portMap.get(p)));
}
}
Collections.sort(result);
return result;
}
/**
* Constructs the key of multicast next objective store.
*
* @param mcastIp multicast group IP address
* @param deviceId device ID
* @param vlanId vlan id
*/
public McastStoreKey(IpAddress mcastIp, DeviceId deviceId, VlanId vlanId) {
checkNotNull(mcastIp, "mcastIp cannot be null");
checkNotNull(deviceId, "deviceId cannot be null");
checkNotNull(vlanId, "vlan id cannot be null");
checkArgument(mcastIp.isMulticast(), "mcastIp must be a multicast address");
this.mcastIp = mcastIp;
this.deviceId = deviceId;
// FIXME probably we should avoid not valid values
this.vlanId = vlanId;
}
@Override
public void emit(OutboundPacket packet) {
DeviceId devId = packet.sendThrough();
String scheme = devId.toString().split(":")[0];
if (!scheme.equals(this.id().scheme())) {
throw new IllegalArgumentException(
"Don't know how to handle Device with scheme " + scheme);
}
Dpid dpid = Dpid.dpid(devId.uri());
OpenFlowSwitch sw = controller.getSwitch(dpid);
if (sw == null) {
log.warn("Device {} isn't available?", devId);
return;
}
OFPort inPort;
if (packet.inPort() != null) {
inPort = portDesc(packet.inPort()).getPortNo();
} else {
inPort = OFPort.CONTROLLER;
}
//Ethernet eth = new Ethernet();
//eth.deserialize(packet.data().array(), 0, packet.data().array().length);
OFPortDesc p = null;
for (Instruction inst : packet.treatment().allInstructions()) {
if (inst.type().equals(Instruction.Type.OUTPUT)) {
p = portDesc(((OutputInstruction) inst).port());
OFPacketOut po = packetOut(sw, packet.data().array(), p.getPortNo(), inPort);
sw.sendMsg(po);
}
}
}
@Test
public void testEquals() {
final DefaultAlarm a = new DefaultAlarm.Builder(ALARM_ID_2,
DeviceId.NONE, "desc", Alarm.SeverityLevel.MINOR, 3).build();
final DefaultAlarm b = new DefaultAlarm.Builder(ALARM_ID,
DeviceId.NONE, "desc", Alarm.SeverityLevel.MINOR, a.timeRaised() + 1)
.withTimeUpdated(a.timeUpdated() + 1).build();
assertEquals("id or timeRaised or timeUpdated may differ", a, b);
assertNotEquals(a, new DefaultAlarm.Builder(a).withAcknowledged(!a.acknowledged()).build());
assertNotEquals(a, new DefaultAlarm.Builder(a).withManuallyClearable(!a.manuallyClearable()).build());
assertNotEquals(a, new DefaultAlarm.Builder(a).withServiceAffecting(!a.serviceAffecting()).build());
assertNotEquals(a, new DefaultAlarm.Builder(a).withAssignedUser("Changed" + a.assignedUser()).build());
}
public void validate(DeviceId expectedDeviceId,
List<GroupOperation> expectedGroupOps) {
if (expectedGroupOps == null) {
assertTrue("events generated", groupOperations.isEmpty());
return;
}
assertEquals(lastDeviceId, expectedDeviceId);
assertTrue((this.groupOperations.containsAll(expectedGroupOps) &&
expectedGroupOps.containsAll(groupOperations)));
groupOperations.clear();
lastDeviceId = null;
}
private void handleConnectionUpdate(DeviceId deviceId) {
assertConfig(deviceId);
final DeviceHandshaker handshaker = handshakerOrFail(deviceId);
if (!handshaker.hasConnection()) {
// If driver reports that a connection still exists, perhaps the
// part of the netcfg that changed does not affect the connection.
// Otherwise, remove any previous connection state from the old
// netcfg and create a new one.
log.warn("Detected change of connection endpoints for {}, will " +
"tear down existing connection and set up a new one...",
deviceId);
handleConnectionTeardown(deviceId);
handleConnectionSetup(deviceId);
}
}
/**
* Returns true if device does not accept flow rules, false otherwise.
*
* @param deviceId the device
* @return true if device does not accept flow rule, false otherwise
*/
private boolean isNoFlowRule(DeviceId deviceId) {
return NO_FLOWRULE_DEVICES.contains(
Optional.ofNullable(deviceService.getDevice(deviceId))
.map(Device::type)
.orElse(Type.OTHER));
}
@Override
public MeterId allocateMeterId(DeviceId deviceId) {
// Init steps
MeterId meterId;
long id;
// Try to reuse meter id
meterId = firstReusableMeterId(deviceId);
// We found a reusable id, return
if (meterId != null) {
return meterId;
}
// If there was no reusable MeterId we have to generate a new value
// using maxMeters as upper limit.
long maxMeters = getMaxMeters(MeterFeaturesKey.key(deviceId));
// If the device does not give us MeterFeatures
if (maxMeters == 0L) {
// MeterFeatures couldn't be retrieved, fallback to queryMeters.
maxMeters = queryMaxMeters(deviceId);
}
// If we don't know the max, cannot proceed
if (maxMeters == 0L) {
return null;
}
// Get a new value
id = meterIdGenerators.incrementAndGet(deviceId);
// Check with the max, and if the value is bigger, cannot proceed
if (id >= maxMeters) {
return null;
}
// Done, return the value
return MeterId.meterId(id);
}
@Override
public Set<DeviceId> getDevices(NodeId nodeId) {
Set<DeviceId> ids = new HashSet<>();
for (Map.Entry<DeviceId, NodeId> d : masterMap.entrySet()) {
if (Objects.equals(d.getValue(), nodeId)) {
ids.add(d.getKey());
}
}
return ids;
}
/**
* Get the ControllerId from the device .
*
* @param device Device
* @param devices Devices
* @return Controller Id
*/
public static DeviceId getControllerId(Device device,
Iterable<Device> devices) {
for (Device d : devices) {
if (d.type() == Device.Type.CONTROLLER && d.id().toString()
.contains(getControllerIpOfSwitch(device))) {
return d.id();
}
}
log.info("Can not find controller for device : {}", device.id());
return null;
}
@Override
public void deviceLabelResourcePoolDetected(DeviceId deviceId,
LabelResourceId beginLabel,
LabelResourceId endLabel) {
checkNotNull(deviceId, "deviceId is not null");
checkNotNull(beginLabel, "beginLabel is not null");
checkNotNull(endLabel, "endLabel is not null");
createDevicePool(deviceId, beginLabel, endLabel);
}