Thomas Vachuska

Consolidating null providers and making them fully configurable and integrated w…

…ith the ConfigProvider to allow arbitrary topologies.

Change-Id: I899e27a9771af4013a3ce6da7f683a4927ffb438
Showing 40 changed files with 1393 additions and 47 deletions
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import java.util.List;
import java.util.SortedSet;
/**
* Abstraction of a completer with preset choices.
*/
public abstract class AbstractChoicesCompleter extends AbstractCompleter {
protected abstract List<String> choices();
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
StringsCompleter delegate = new StringsCompleter();
SortedSet<String> strings = delegate.getStrings();
choices().forEach(strings::add);
return delegate.complete(buffer, cursor, candidates);
}
}
......@@ -13,7 +13,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli.net;
package org.onosproject.cli;
import org.apache.felix.service.command.CommandSession;
import org.apache.karaf.shell.console.CommandSessionHolder;
......
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli;
import com.google.common.collect.ImmutableList;
import java.util.List;
/**
* Start/stop command completer.
*/
public class StartStopCompleter extends AbstractChoicesCompleter {
public static final String START = "start";
public static final String STOP = "stop";
@Override
public List<String> choices() {
return ImmutableList.of(START, STOP);
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli;
import com.google.common.collect.ImmutableList;
import java.util.List;
/**
* Up/down command completer.
*/
public class UpDownCompleter extends AbstractChoicesCompleter {
public static final String UP = "up";
public static final String DOWN = "down";
@Override
public List<String> choices() {
return ImmutableList.of(UP, DOWN);
}
}
......@@ -15,30 +15,20 @@
*/
package org.onosproject.cli.app;
import org.apache.karaf.shell.console.Completer;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import com.google.common.collect.ImmutableList;
import org.onosproject.cli.AbstractChoicesCompleter;
import java.util.List;
import java.util.SortedSet;
import static org.onosproject.cli.app.ApplicationCommand.*;
/**
* Application name completer.
* Application command completer.
*/
public class ApplicationCommandCompleter implements Completer {
public class ApplicationCommandCompleter extends AbstractChoicesCompleter {
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
// Delegate string completer
StringsCompleter delegate = new StringsCompleter();
SortedSet<String> strings = delegate.getStrings();
strings.add(INSTALL);
strings.add(UNINSTALL);
strings.add(ACTIVATE);
strings.add(DEACTIVATE);
// Now let the completer do the work for figuring out what to offer.
return delegate.complete(buffer, cursor, candidates);
public List<String> choices() {
return ImmutableList.of(INSTALL, UNINSTALL, ACTIVATE, DEACTIVATE);
}
}
......
......@@ -19,7 +19,7 @@ import org.apache.karaf.shell.console.completer.ArgumentCompleter;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.app.ApplicationService;
import org.onosproject.app.ApplicationState;
import org.onosproject.cli.net.AbstractCompleter;
import org.onosproject.cli.AbstractCompleter;
import org.onosproject.core.Application;
import java.util.Iterator;
......
......@@ -19,7 +19,7 @@ import org.apache.karaf.shell.console.completer.ArgumentCompleter;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cfg.ConfigProperty;
import org.onosproject.cli.net.AbstractCompleter;
import org.onosproject.cli.AbstractCompleter;
import java.util.List;
import java.util.Set;
......
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli.net;
import org.apache.karaf.shell.console.completer.ArgumentCompleter;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.cli.AbstractCompleter;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.link.LinkService;
import java.util.List;
import java.util.SortedSet;
import static org.onosproject.cli.net.AddPointToPointIntentCommand.getDeviceId;
import static org.onosproject.cli.net.AddPointToPointIntentCommand.getPortNumber;
import static org.onosproject.net.DeviceId.deviceId;
import static org.onosproject.net.PortNumber.portNumber;
/**
* Link end-point completer.
*/
public class LinkDstCompleter extends AbstractCompleter {
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
// Delegate string completer
StringsCompleter delegate = new StringsCompleter();
// Fetch our service and feed it's offerings to the string completer
LinkService service = AbstractShellCommand.get(LinkService.class);
// Link source the previous argument.
ArgumentCompleter.ArgumentList list = getArgumentList();
String srcArg = list.getArguments()[list.getCursorArgumentIndex() - 1];
// Generate the device ID/port number identifiers
SortedSet<String> strings = delegate.getStrings();
try {
ConnectPoint src = new ConnectPoint(deviceId(getDeviceId(srcArg)),
portNumber(getPortNumber(srcArg)));
service.getEgressLinks(src)
.forEach(link -> strings.add(link.dst().elementId().toString() +
"/" + link.dst().port()));
} catch (NumberFormatException e) {
System.err.println("Invalid connect-point");
}
// Now let the completer do the work for figuring out what to offer.
return delegate.complete(buffer, cursor, candidates);
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.cli.net;
import org.apache.karaf.shell.console.completer.StringsCompleter;
import org.onosproject.cli.AbstractCompleter;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.link.LinkService;
import java.util.List;
import java.util.SortedSet;
/**
* Link end-point completer.
*/
public class LinkSrcCompleter extends AbstractCompleter {
@Override
public int complete(String buffer, int cursor, List<String> candidates) {
// Delegate string completer
StringsCompleter delegate = new StringsCompleter();
// Fetch our service and feed it's offerings to the string completer
LinkService service = AbstractShellCommand.get(LinkService.class);
// Generate the device ID/port number identifiers
SortedSet<String> strings = delegate.getStrings();
service.getLinks()
.forEach(link -> strings.add(link.src().elementId().toString() +
"/" + link.src().port()));
// Now let the completer do the work for figuring out what to offer.
return delegate.complete(buffer, cursor, candidates);
}
}
......@@ -332,4 +332,7 @@
<bean id="ipProtocolCompleter" class="org.onosproject.cli.net.IpProtocolCompleter"/>
<bean id="driverNameCompleter" class="org.onosproject.cli.net.DriverNameCompleter"/>
<bean id="startStopCompleter" class="org.onosproject.cli.StartStopCompleter"/>
<bean id="upDownCompleter" class="org.onosproject.cli.UpDownCompleter"/>
</blueprint>
......
......@@ -20,7 +20,7 @@ import org.onosproject.net.DeviceId;
/**
* Service for administering the inventory of infrastructure devices.
*/
public interface DeviceAdminService {
public interface DeviceAdminService extends DeviceService {
/**
* Removes the device with the specified identifier.
......
......@@ -21,7 +21,7 @@ import org.onosproject.net.HostId;
/**
* Service for administering the inventory of end-station hosts.
*/
public interface HostAdminService {
public interface HostAdminService extends HostService {
/**
* Removes the end-station host with the specified identifier.
......
......@@ -21,7 +21,7 @@ import org.onosproject.net.DeviceId;
/**
* Service for administering the inventory of infrastructure links.
*/
public interface LinkAdminService {
public interface LinkAdminService extends LinkService {
/**
* Removes all infrastructure links leading to and from the
......
......@@ -705,7 +705,8 @@ public class DistributedGroupStore
remove(new GroupStoreKeyMapKey(deviceId, group.appCookie()));
}
} else {
if (deviceAuditStatus.get(deviceId)) {
Boolean audited = deviceAuditStatus.get(deviceId);
if (audited != null && audited) {
log.debug("deviceInitialAuditCompleted: Clearing AUDIT "
+ "status for device {}", deviceId);
deviceAuditStatus.put(deviceId, false);
......@@ -717,8 +718,8 @@ public class DistributedGroupStore
@Override
public boolean deviceInitialAuditStatus(DeviceId deviceId) {
synchronized (deviceAuditStatus) {
return (deviceAuditStatus.get(deviceId) != null)
? deviceAuditStatus.get(deviceId) : false;
Boolean audited = deviceAuditStatus.get(deviceId);
return audited != null && audited;
}
}
......
......@@ -79,7 +79,7 @@
<group>
<title>Null Providers</title>
<packages>
org.onosproject.provider.nil.*
org.onosproject.provider.nil:org.onosproject.provider.nil.*
</packages>
</group>
<group>
......
......@@ -131,13 +131,7 @@
<feature name="onos-null" version="@FEATURE-VERSION"
description="ONOS Null providers">
<feature>onos-api</feature>
<bundle>mvn:org.onosproject/onos-null-provider-device/@ONOS-VERSION</bundle>
<bundle>mvn:org.onosproject/onos-null-provider-link/@ONOS-VERSION</bundle>
<bundle>mvn:org.onosproject/onos-null-provider-host/@ONOS-VERSION</bundle>
<bundle>mvn:org.onosproject/onos-null-provider-packet/@ONOS-VERSION</bundle>
<bundle>mvn:org.onosproject/onos-null-provider-flow/@ONOS-VERSION</bundle>
<bundle>mvn:org.onosproject/onos-null-provider/@ONOS-VERSION</bundle>
</feature>
<feature name="onos-openflow" version="@FEATURE-VERSION"
......
......@@ -26,20 +26,25 @@
<relativePath>../pom.xml</relativePath>
</parent>
<artifactId>onos-null-providers</artifactId>
<packaging>pom</packaging>
<artifactId>onos-null-provider</artifactId>
<packaging>bundle</packaging>
<description>ONOS null protocol adapters</description>
<modules>
<module>device</module>
<module>link</module>
<module>host</module>
<module>packet</module>
<module>flow</module>
</modules>
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.console</artifactId>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-cli</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
......
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
/**
* Linear topology with hosts on every device.
*/
public class CentipedeTopologySimulator extends LinearTopologySimulator {
/**
* Creates simulated hosts.
*/
protected void createHosts() {
deviceIds.forEach(id -> createHosts(id, infrastructurePorts));
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
/**
* Topology simulator which operates on topology configured via the REST API
* config service.
*/
public class ConfiguredTopologySimulator extends TopologySimulator {
@Override
protected void createDevices() {
deviceService.getDevices()
.forEach(device -> deviceProviderService
.deviceConnected(device.id(), description(device)));
}
@Override
protected void createLinks() {
linkService.getLinks()
.forEach(link -> linkProviderService
.linkDetected(description(link)));
}
@Override
protected void createHosts() {
hostService.getHosts()
.forEach(host -> hostProviderService
.hostDetected(host.id(), description(host)));
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Linear topology simulator.
*/
public class LinearTopologySimulator extends TopologySimulator {
@Override
protected void processTopoShape(String shape) {
super.processTopoShape(shape);
deviceCount = (topoShape.length == 1) ? deviceCount : Integer.parseInt(topoShape[1]);
}
@Override
public void setUpTopology() {
checkArgument(deviceCount > 1, "There must be at least 2 devices");
prepareForDeviceEvents(deviceCount);
createDevices();
waitForDeviceEvents();
createLinks();
createHosts();
}
@Override
protected void createLinks() {
for (int i = 0, n = deviceCount - 1; i < n; i++) {
createLink(i, i + 1);
}
}
@Override
protected void createHosts() {
createHosts(deviceIds.get(0), infrastructurePorts);
createHosts(deviceIds.get(deviceCount - 1), infrastructurePorts);
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
/**
* Full mesh topology with hosts at each device.
*/
public class MeshTopologySimulator extends TopologySimulator {
@Override
protected void processTopoShape(String shape) {
super.processTopoShape(shape);
// FIXME: implement this
}
@Override
public void setUpTopology() {
// FIXME: implement this
// checkArgument(FIXME, "There must be at least ...");
super.setUpTopology();
}
@Override
protected void createLinks() {
}
@Override
protected void createHosts() {
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import com.google.common.collect.Sets;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.onlab.util.Timer;
import org.onosproject.core.ApplicationId;
import org.onosproject.net.DeviceId;
import org.onosproject.net.flow.CompletedBatchOperation;
import org.onosproject.net.flow.DefaultFlowEntry;
import org.onosproject.net.flow.FlowEntry;
import org.onosproject.net.flow.FlowRule;
import org.onosproject.net.flow.FlowRuleBatchEntry;
import org.onosproject.net.flow.FlowRuleBatchOperation;
import org.onosproject.net.flow.FlowRuleProvider;
import org.onosproject.net.flow.FlowRuleProviderService;
import org.slf4j.Logger;
import java.util.Collections;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Null provider to accept any flow and report them.
*/
class NullFlowRuleProvider extends NullProviders.AbstractNullProvider
implements FlowRuleProvider {
private final Logger log = getLogger(getClass());
private ConcurrentMap<DeviceId, Set<FlowEntry>> flowTable = new ConcurrentHashMap<>();
private FlowRuleProviderService providerService;
private HashedWheelTimer timer = Timer.getTimer();
private Timeout timeout;
/**
* Starts the flow rule provider simulation.
*
* @param providerService flow rule provider service
*/
void start(FlowRuleProviderService providerService) {
this.providerService = providerService;
timeout = timer.newTimeout(new StatisticTask(), 5, TimeUnit.SECONDS);
}
/**
* Stops the flow rule provider simulation.
*/
void stop() {
timeout.cancel();
}
@Override
public void applyFlowRule(FlowRule... flowRules) {
// FIXME: invoke executeBatch
}
@Override
public void removeFlowRule(FlowRule... flowRules) {
// FIXME: invoke executeBatch
}
@Override
public void removeRulesById(ApplicationId id, FlowRule... flowRules) {
throw new UnsupportedOperationException("Cannot remove by appId from null provider");
}
@Override
public void executeBatch(FlowRuleBatchOperation batch) {
// TODO: consider checking mastership
Set<FlowEntry> entries =
flowTable.getOrDefault(batch.deviceId(),
Sets.newConcurrentHashSet());
for (FlowRuleBatchEntry fbe : batch.getOperations()) {
switch (fbe.operator()) {
case ADD:
entries.add(new DefaultFlowEntry(fbe.target()));
break;
case REMOVE:
entries.remove(new DefaultFlowEntry(fbe.target()));
break;
case MODIFY:
FlowEntry entry = new DefaultFlowEntry(fbe.target());
entries.remove(entry);
entries.add(entry);
break;
default:
log.error("Unknown flow operation: {}", fbe);
}
}
flowTable.put(batch.deviceId(), entries);
CompletedBatchOperation op =
new CompletedBatchOperation(true, Collections.emptySet(),
batch.deviceId());
providerService.batchOperationCompleted(batch.id(), op);
}
// Periodically reports flow rule statistics.
private class StatisticTask implements TimerTask {
@Override
public void run(Timeout to) throws Exception {
for (DeviceId devId : flowTable.keySet()) {
Set<FlowEntry> entries =
flowTable.getOrDefault(devId, Collections.emptySet());
providerService.pushFlowMetrics(devId, entries);
}
timeout = timer.newTimeout(to.getTask(), 5, TimeUnit.SECONDS);
}
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import org.jboss.netty.util.HashedWheelTimer;
import org.jboss.netty.util.Timeout;
import org.jboss.netty.util.TimerTask;
import org.onlab.packet.Ethernet;
import org.onlab.packet.ICMP;
import org.onlab.util.Timer;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.Device;
import org.onosproject.net.PortNumber;
import org.onosproject.net.device.DeviceAdminService;
import org.onosproject.net.host.HostService;
import org.onosproject.net.packet.DefaultInboundPacket;
import org.onosproject.net.packet.DefaultPacketContext;
import org.onosproject.net.packet.InboundPacket;
import org.onosproject.net.packet.OutboundPacket;
import org.onosproject.net.packet.PacketProvider;
import org.onosproject.net.packet.PacketProviderService;
import org.slf4j.Logger;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import static com.google.common.collect.ImmutableList.copyOf;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.onosproject.net.MastershipRole.MASTER;
import static org.slf4j.LoggerFactory.getLogger;
/**
* Provider which generates simulated packets and acts as a sink for outbound
* packets. To be used for benchmarking only.
*/
class NullPacketProvider extends NullProviders.AbstractNullProvider
implements PacketProvider {
private static final int INITIAL_DELAY = 5;
private final Logger log = getLogger(getClass());
// Arbitrary host src/dst
private static final int SRC_HOST = 2;
private static final int DST_HOST = 5;
// Time between event firing, in milliseconds
private int delay;
// TODO: use host service to pick legitimate hosts connected to devices
private HostService hostService;
private PacketProviderService providerService;
private List<Device> devices;
private int currentDevice = 0;
private HashedWheelTimer timer = Timer.getTimer();
private Timeout timeout;
/**
* Starts the packet generation process.
*
* @param packetRate packets per second
* @param hostService host service
* @param deviceService device service
* @param providerService packet provider service
*/
void start(int packetRate, HostService hostService,
DeviceAdminService deviceService,
PacketProviderService providerService) {
this.hostService = hostService;
this.providerService = providerService;
this.devices = copyOf(deviceService.getDevices()).stream()
.filter(d -> deviceService.getRole(d.id()) == MASTER)
.collect(Collectors.toList());
adjustRate(packetRate);
timeout = timer.newTimeout(new PacketDriverTask(), INITIAL_DELAY, SECONDS);
}
/**
* Adjusts packet rate.
*
* @param packetRate new packet rate
*/
void adjustRate(int packetRate) {
delay = 1000 / packetRate;
log.info("Settings: packetRate={}, delay={}", packetRate, delay);
}
/**
* Stops the packet generation process.
*/
void stop() {
if (timeout != null) {
timeout.cancel();
}
}
@Override
public void emit(OutboundPacket packet) {
// We don't have a network to emit to. Keep a counter here, maybe?
}
/**
* Generates packet events at a given rate.
*/
private class PacketDriverTask implements TimerTask {
// Filler echo request
ICMP icmp;
Ethernet eth;
public PacketDriverTask() {
icmp = new ICMP();
icmp.setIcmpType((byte) 8).setIcmpCode((byte) 0).setChecksum((short) 0);
eth = new Ethernet();
eth.setEtherType(Ethernet.TYPE_IPV4);
eth.setPayload(icmp);
}
@Override
public void run(Timeout to) {
if (!devices.isEmpty()) {
sendEvent(devices.get(currentDevice));
currentDevice = (currentDevice + 1) % devices.size();
timeout = timer.newTimeout(to.getTask(), delay, TimeUnit.MILLISECONDS);
}
}
private void sendEvent(Device device) {
// Make it look like things came from ports attached to hosts
eth.setSourceMACAddress("00:00:10:00:00:0" + SRC_HOST)
.setDestinationMACAddress("00:00:10:00:00:0" + DST_HOST);
InboundPacket inPkt = new DefaultInboundPacket(
new ConnectPoint(device.id(), PortNumber.portNumber(SRC_HOST)),
eth, ByteBuffer.wrap(eth.serialize()));
providerService.processPacket(new NullPacketContext(inPkt, null));
}
}
// Minimal PacketContext to make core and applications happy.
private final class NullPacketContext extends DefaultPacketContext {
private NullPacketContext(InboundPacket inPkt, OutboundPacket outPkt) {
super(System.currentTimeMillis(), inPkt, outPkt, false);
}
@Override
public void send() {
// We don't send anything out.
}
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Re-routable linear topology simulator with an alternate path in the middle.
*/
public class RerouteTopologySimulator extends LinearTopologySimulator {
@Override
protected void processTopoShape(String shape) {
super.processTopoShape(shape);
infrastructurePorts = 3;
deviceCount = (topoShape.length == 1) ? deviceCount : Integer.parseInt(topoShape[1]);
}
@Override
public void setUpTopology() {
checkArgument(deviceCount > 2, "There must be at least 3 devices");
super.setUpTopology();
}
@Override
protected void createLinks() {
for (int i = 0, n = deviceCount - 2; i < n; i++) {
createLink(i, i + 1);
}
int middle = (deviceCount - 1) / 2;
int alternate = deviceCount - 1;
createLink(middle - 1, alternate);
createLink(middle, alternate);
}
@Override
protected void createHosts() {
createHosts(deviceIds.get(0), infrastructurePorts);
createHosts(deviceIds.get(deviceCount - 2), infrastructurePorts);
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
/**
* Spine-leaf topology with hosts at the leaf devices.
*/
public class SpineLeafTopologySimulator extends TopologySimulator {
@Override
protected void processTopoShape(String shape) {
super.processTopoShape(shape);
// FIXME: implement this
}
@Override
public void setUpTopology() {
// checkArgument(FIXME, "There must be at least one spine tier");
super.setUpTopology();
}
@Override
protected void createLinks() {
}
@Override
protected void createHosts() {
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import com.google.common.collect.Lists;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.link.DefaultLinkDescription;
import org.onosproject.net.link.LinkDescription;
import org.onosproject.net.link.LinkProviderService;
import org.onosproject.net.link.LinkService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.List;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;
import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
import static org.onlab.util.Tools.delay;
import static org.onlab.util.Tools.groupedThreads;
import static org.onosproject.net.Link.Type.DIRECT;
import static org.onosproject.net.MastershipRole.MASTER;
import static org.onosproject.provider.nil.TopologySimulator.description;
/**
* Drives topology mutations at a specified rate of events per second.
*/
class TopologyMutationDriver implements Runnable {
private final Logger log = LoggerFactory.getLogger(getClass());
private static final int WAIT_DELAY = 2_000;
private static final int MAX_DOWN_LINKS = 5;
private final Random random = new Random();
private volatile boolean stopped = true;
private double mutationRate;
private int millis, nanos;
private LinkService linkService;
private DeviceService deviceService;
private LinkProviderService linkProviderService;
private List<LinkDescription> activeLinks;
private List<LinkDescription> inactiveLinks;
private final ExecutorService executor =
newSingleThreadScheduledExecutor(groupedThreads("onos/null", "topo-mutator"));
/**
* Starts the mutation process.
*
* @param mutationRate link events per second
* @param linkService link service
* @param deviceService device service
* @param linkProviderService link provider service
*/
void start(double mutationRate,
LinkService linkService, DeviceService deviceService,
LinkProviderService linkProviderService) {
stopped = false;
this.linkService = linkService;
this.deviceService = deviceService;
this.linkProviderService = linkProviderService;
activeLinks = reduceLinks();
inactiveLinks = Lists.newArrayList();
adjustRate(mutationRate);
executor.submit(this);
}
/**
* Adjusts the topology mutation rate.
*
* @param mutationRate new topology mutation rate
*/
void adjustRate(double mutationRate) {
this.mutationRate = mutationRate;
if (mutationRate > 0) {
this.millis = (int) (1_000 / mutationRate / 2);
this.nanos = (int) (1_000_000 / mutationRate / 2) % 1_000_000;
} else {
this.millis = 0;
this.nanos = 0;
}
log.info("Settings: millis={}, nanos={}", millis, nanos);
}
/**
* Stops the mutation process.
*/
void stop() {
stopped = true;
}
/**
* Severs the link between the specified end-points in both directions.
*
* @param one link endpoint
* @param two link endpoint
*/
void severLink(ConnectPoint one, ConnectPoint two) {
LinkDescription link = new DefaultLinkDescription(one, two, DIRECT);
linkProviderService.linkVanished(link);
linkProviderService.linkVanished(reverse(link));
}
/**
* Repairs the link between the specified end-points in both directions.
*
* @param one link endpoint
* @param two link endpoint
*/
void repairLink(ConnectPoint one, ConnectPoint two) {
LinkDescription link = new DefaultLinkDescription(one, two, DIRECT);
linkProviderService.linkDetected(link);
linkProviderService.linkDetected(reverse(link));
}
@Override
public void run() {
delay(WAIT_DELAY);
while (!stopped) {
if (mutationRate > 0 && inactiveLinks.isEmpty()) {
primeInactiveLinks();
} else if (mutationRate <= 0 && !inactiveLinks.isEmpty()) {
repairInactiveLinks();
} else if (inactiveLinks.isEmpty()) {
delay(WAIT_DELAY);
} else {
activeLinks.add(repairLink());
pause();
inactiveLinks.add(severLink());
pause();
}
}
}
// Primes the inactive links with a few random links.
private void primeInactiveLinks() {
for (int i = 0, n = Math.min(MAX_DOWN_LINKS, activeLinks.size()); i < n; i++) {
inactiveLinks.add(severLink());
}
}
// Repairs all inactive links.
private void repairInactiveLinks() {
while (!inactiveLinks.isEmpty()) {
repairLink();
}
}
// Picks a random active link and severs it.
private LinkDescription severLink() {
LinkDescription link = getRandomLink(activeLinks);
linkProviderService.linkVanished(link);
linkProviderService.linkVanished(reverse(link));
return link;
}
// Picks a random inactive link and repairs it.
private LinkDescription repairLink() {
LinkDescription link = getRandomLink(inactiveLinks);
linkProviderService.linkDetected(link);
linkProviderService.linkDetected(reverse(link));
return link;
}
// Produces a reverse of the specified link.
private LinkDescription reverse(LinkDescription link) {
return new DefaultLinkDescription(link.dst(), link.src(), link.type());
}
// Returns a random link from the specified list of links.
private LinkDescription getRandomLink(List<LinkDescription> links) {
return links.remove(random.nextInt(links.size()));
}
// Reduces the given list of links to just a single link in each original pair.
private List<LinkDescription> reduceLinks() {
List<LinkDescription> links = Lists.newArrayList();
linkService.getLinks().forEach(link -> links.add(description(link)));
return links.stream()
.filter(this::isOurLink)
.filter(this::isRightDirection)
.collect(Collectors.toList());
}
// Returns true if the specified link is ours.
private boolean isOurLink(LinkDescription linkDescription) {
return deviceService.getRole(linkDescription.src().deviceId()) == MASTER;
}
// Returns true if the link source is greater than the link destination.
private boolean isRightDirection(LinkDescription link) {
return link.src().deviceId().toString().compareTo(link.dst().deviceId().toString()) > 0;
}
// Pauses the current thread for the pre-computed time of millis & nanos.
private void pause() {
delay(millis, nanos);
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil;
import static com.google.common.base.Preconditions.checkArgument;
/**
* Tree topology with hosts at the leaf devices.
*/
public class TreeTopologySimulator extends TopologySimulator {
private int[] tierMultiplier;
private int[] tierDeviceCount;
private int[] tierOffset;
@Override
protected void processTopoShape(String shape) {
super.processTopoShape(shape);
tierOffset = new int[topoShape.length];
tierMultiplier = new int[topoShape.length];
tierDeviceCount = new int[topoShape.length];
deviceCount = 1;
tierOffset[0] = 0;
tierMultiplier[0] = 1;
tierDeviceCount[0] = deviceCount;
for (int i = 1; i < topoShape.length; i++) {
tierOffset[i] = deviceCount;
tierMultiplier[i] = Integer.parseInt(topoShape[i]);
tierDeviceCount[i] = tierDeviceCount[i - 1] * tierMultiplier[i];
deviceCount = deviceCount + tierDeviceCount[i];
}
}
@Override
public void setUpTopology() {
checkArgument(tierDeviceCount.length > 0, "There must be at least one tree tier");
super.setUpTopology();
}
@Override
protected void createLinks() {
for (int t = 1; t < tierOffset.length; t++) {
int child = tierOffset[t];
for (int parent = tierOffset[t - 1]; parent < tierOffset[t]; parent++) {
for (int i = 0; i < tierMultiplier[t]; i++) {
createLink(parent, child);
child++;
}
}
}
}
@Override
protected void createHosts() {
for (int i = tierOffset[tierOffset.length - 1]; i < deviceCount; i++) {
createHosts(deviceIds.get(i), hostCount);
}
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil.cli;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cfg.ComponentConfigService;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.provider.nil.NullProviders;
import static org.onosproject.cli.StartStopCompleter.START;
/**
* Starts or stops topology simulation.
*/
@Command(scope = "onos", name = "null-simulation",
description = "Starts or stops topology simulation")
public class NullControlCommand extends AbstractShellCommand {
@Argument(index = 0, name = "cmd", description = "Control command: start/stop",
required = true, multiValued = false)
String cmd = null;
@Argument(index = 1, name = "topoShape",
description = "Topology shape: e.g. configured, linear, reroute, centipede, tree, spineleaf, mesh",
required = false, multiValued = false)
String topoShape = null;
@Override
protected void execute() {
ComponentConfigService service = get(ComponentConfigService.class);
if (topoShape != null) {
service.setProperty(NullProviders.class.getName(), "topoShape", topoShape);
}
service.setProperty(NullProviders.class.getName(), "enabled",
cmd.equals(START) ? "true" : "false");
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil.cli;
import org.apache.karaf.shell.commands.Argument;
import org.apache.karaf.shell.commands.Command;
import org.onosproject.cli.AbstractShellCommand;
import org.onosproject.net.ConnectPoint;
import org.onosproject.net.DeviceId;
import org.onosproject.net.PortNumber;
import org.onosproject.provider.nil.NullProviders;
import static org.onosproject.cli.UpDownCompleter.DOWN;
import static org.onosproject.cli.UpDownCompleter.UP;
import static org.onosproject.cli.net.AddPointToPointIntentCommand.getDeviceId;
import static org.onosproject.cli.net.AddPointToPointIntentCommand.getPortNumber;
import static org.onosproject.net.DeviceId.deviceId;
import static org.onosproject.net.PortNumber.portNumber;
/**
* Servers or repairs a simulated link.
*/
@Command(scope = "onos", name = "null-link",
description = "Severs or repairs a simulated link")
public class NullLinkCommand extends AbstractShellCommand {
@Argument(index = 0, name = "one", description = "One link end-point as device/port",
required = true, multiValued = false)
String one = null;
@Argument(index = 1, name = "two", description = "Another link end-point as device/port",
required = true, multiValued = false)
String two = null;
@Argument(index = 2, name = "cmd", description = "up/down",
required = true, multiValued = false)
String cmd = null;
@Override
protected void execute() {
NullProviders service = get(NullProviders.class);
try {
DeviceId oneId = deviceId(getDeviceId(one));
PortNumber onePort = portNumber(getPortNumber(one));
ConnectPoint onePoint = new ConnectPoint(oneId, onePort);
DeviceId twoId = deviceId(getDeviceId(two));
PortNumber twoPort = portNumber(getPortNumber(two));
ConnectPoint twoPoint = new ConnectPoint(twoId, twoPort);
if (cmd.equals(UP)) {
service.repairLink(onePoint, twoPoint);
} else if (cmd.equals(DOWN)) {
service.severLink(onePoint, twoPoint);
} else {
error("Illegal command %s; must be up or down", cmd);
}
} catch (NumberFormatException e) {
error("Invalid port number specified", e);
}
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.onosproject.provider.nil.cli;
import com.google.common.collect.ImmutableList;
import org.onosproject.cli.AbstractChoicesCompleter;
import java.util.List;
/**
* Topology shape completer.
*/
public class TopologyShapeCompleter extends AbstractChoicesCompleter {
@Override
public List<String> choices() {
return ImmutableList.of("configured", "linear", "reroute", "centipede",
"tree", "spineleaf", "mesh");
}
}
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Null provider CLI commands and completers.
*/
package org.onosproject.provider.nil.cli;
/*
* Copyright 2015 Open Networking Laboratory
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Set of null south-bound providers which permit simulating a network
* topology using fake devices, links, hosts, etc.
*/
package org.onosproject.provider.nil;
<!--
~ Copyright 2015 Open Networking Laboratory
~
~ Licensed under the Apache License, Version 2.0 (the "License");
~ you may not use this file except in compliance with the License.
~ You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing, software
~ distributed under the License is distributed on an "AS IS" BASIS,
~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0">
<command-bundle xmlns="http://karaf.apache.org/xmlns/shell/v1.1.0">
<command>
<action class="org.onosproject.provider.nil.cli.NullControlCommand"/>
<completers>
<ref component-id="startStopCompleter"/>
<ref component-id="topoShapeCompleter"/>
<null/>
</completers>
</command>
<command>
<action class="org.onosproject.provider.nil.cli.NullLinkCommand"/>
<completers>
<ref component-id="linkSrcCompleter"/>
<ref component-id="linkDstCompleter"/>
<ref component-id="upDownCompleter"/>
<null/>
</completers>
</command>
</command-bundle>
<bean id="startStopCompleter" class="org.onosproject.cli.StartStopCompleter"/>
<bean id="upDownCompleter" class="org.onosproject.cli.UpDownCompleter"/>
<bean id="topoShapeCompleter" class="org.onosproject.provider.nil.cli.TopologyShapeCompleter"/>
<bean id="linkSrcCompleter" class="org.onosproject.cli.net.LinkSrcCompleter"/>
<bean id="linkDstCompleter" class="org.onosproject.cli.net.LinkDstCompleter"/>
</blueprint>
This diff is collapsed. Click to expand it.
......@@ -192,6 +192,20 @@ public abstract class Tools {
}
/**
* Suspends the current thread for a specified number of millis and nanos.
*
* @param ms number of millis
* @param nanos number of nanos
*/
public static void delay(int ms, int nanos) {
try {
Thread.sleep(ms, nanos);
} catch (InterruptedException e) {
throw new RuntimeException("Interrupted", e);
}
}
/**
* Slurps the contents of a file into a list of strings, one per line.
*
* @param path file path
......
......@@ -18,6 +18,7 @@ package org.onosproject.rest;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.onosproject.net.device.DeviceProviderRegistry;
import org.onosproject.net.device.DeviceService;
import org.onosproject.net.host.HostProviderRegistry;
import org.onosproject.net.link.LinkProviderRegistry;
import org.onlab.rest.BaseResource;
......@@ -40,9 +41,9 @@ import static javax.ws.rs.core.Response.Status.INTERNAL_SERVER_ERROR;
* devices, ports and links.
*/
@Path("config")
public class ConfigResource extends BaseResource {
public class ConfigWebResource extends BaseResource {
private static Logger log = LoggerFactory.getLogger(ConfigResource.class);
private static Logger log = LoggerFactory.getLogger(ConfigWebResource.class);
@POST
@Path("topology")
......@@ -52,7 +53,8 @@ public class ConfigResource extends BaseResource {
try {
ObjectMapper mapper = new ObjectMapper();
JsonNode cfg = mapper.readTree(input);
new ConfigProvider(cfg, get(DeviceProviderRegistry.class),
new ConfigProvider(cfg, get(DeviceService.class),
get(DeviceProviderRegistry.class),
get(LinkProviderRegistry.class),
get(HostProviderRegistry.class)).parse();
return Response.ok().build();
......
......@@ -72,7 +72,7 @@
org.onosproject.rest.IntentsWebResource,
org.onosproject.rest.FlowsWebResource,
org.onosproject.rest.TopologyWebResource,
org.onosproject.rest.ConfigResource,
org.onosproject.rest.ConfigWebResource,
org.onosproject.rest.PathsWebResource
</param-value>
</init-param>
......