Yuta HIGUCHI
Committed by Yuta Higuchi

Configuration to suppress LLDP discovery

Change-Id: I3b14df6682839f14694b69330a0943facd4f3a6f
......@@ -34,6 +34,11 @@
<dependencies>
<dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.compendium</artifactId>
</dependency>
<dependency>
<groupId>org.onosproject</groupId>
<artifactId>onos-api</artifactId>
<classifier>tests</classifier>
......
......@@ -18,6 +18,8 @@ package org.onosproject.provider.lldp.impl;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Deactivate;
import org.apache.felix.scr.annotations.Modified;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.ReferenceCardinality;
import org.onosproject.mastership.MastershipEvent;
......@@ -38,8 +40,16 @@ import org.onosproject.net.packet.PacketProcessor;
import org.onosproject.net.packet.PacketService;
import org.onosproject.net.provider.AbstractProvider;
import org.onosproject.net.provider.ProviderId;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.io.IOException;
import java.util.Dictionary;
import java.util.EnumSet;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
......@@ -57,6 +67,13 @@ import static org.slf4j.LoggerFactory.getLogger;
@Component(immediate = true)
public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
private static final String PROP_USE_BDDP = "useBDDP";
private static final String PROP_LLDP_SUPPRESSION = "lldpSuppression";
private static final String DEFAULT_LLDP_SUPPRESSION_CONFIG = "../config/lldp_suppression.json";
private final Logger log = getLogger(getClass());
@Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
......@@ -75,17 +92,26 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
private ScheduledExecutorService executor;
private final boolean useBDDP = true;
@Property(name = PROP_USE_BDDP, boolValue = true,
label = "use BDDP for link discovery")
private boolean useBDDP = true;
private static final long INIT_DELAY = 5;
private static final long DELAY = 5;
@Property(name = PROP_LLDP_SUPPRESSION, value = DEFAULT_LLDP_SUPPRESSION_CONFIG,
label = "Path to LLDP suppression configuration file")
private String filePath = DEFAULT_LLDP_SUPPRESSION_CONFIG;
private final InternalLinkProvider listener = new InternalLinkProvider();
private final InternalRoleListener roleListener = new InternalRoleListener();
protected final Map<DeviceId, LinkDiscovery> discoverers = new ConcurrentHashMap<>();
private SuppressionRules rules;
/**
* Creates an OpenFlow link provider.
*/
......@@ -95,6 +121,8 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
@Activate
public void activate() {
loadSuppressionRules();
providerService = providerRegistry.register(this);
deviceService.addListener(listener);
packetSevice.addProcessor(listener, 0);
......@@ -102,10 +130,19 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
LinkDiscovery ld;
for (Device device : deviceService.getAvailableDevices()) {
if (rules.isSuppressed(device)) {
log.debug("LinkDiscovery from {} disabled by configuration", device.id());
continue;
}
ld = new LinkDiscovery(device, packetSevice, masterService,
providerService, useBDDP);
discoverers.put(device.id(), ld);
for (Port p : deviceService.getPorts(device.id())) {
if (rules.isSuppressed(p)) {
log.debug("LinkDiscovery from {}@{} disabled by configuration",
p.number(), device.id());
continue;
}
if (!p.number().isLogical()) {
ld.addPort(p);
}
......@@ -134,6 +171,45 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
log.info("Stopped");
}
@Modified
public void modified(ComponentContext context) {
if (context == null) {
return;
}
@SuppressWarnings("rawtypes")
Dictionary properties = context.getProperties();
String s = (String) properties.get(PROP_USE_BDDP);
if (Strings.isNullOrEmpty(s)) {
useBDDP = true;
} else {
useBDDP = Boolean.valueOf(s);
}
s = (String) properties.get(PROP_LLDP_SUPPRESSION);
if (Strings.isNullOrEmpty(s)) {
filePath = DEFAULT_LLDP_SUPPRESSION_CONFIG;
} else {
filePath = s;
}
loadSuppressionRules();
}
private void loadSuppressionRules() {
SuppressionRulesStore store = new SuppressionRulesStore(filePath);
try {
rules = store.read();
} catch (IOException e) {
log.info("Failed to load {}, using built-in rules", filePath);
// default rule to suppress ROADM to maintain compatibility
rules = new SuppressionRules(ImmutableSet.of(),
EnumSet.of(Device.Type.ROADM),
ImmutableMap.of());
}
// should refresh discoverers when we need dynamic reconfiguration
}
private class InternalRoleListener implements MastershipListener {
@Override
......@@ -150,6 +226,9 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
log.warn("Device {} doesn't exist, or isn't there yet", deviceId);
return;
}
if (rules.isSuppressed(device)) {
return;
}
synchronized (discoverers) {
if (!discoverers.containsKey(deviceId)) {
// ideally, should never reach here
......@@ -180,20 +259,24 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
switch (event.type()) {
case DEVICE_ADDED:
case DEVICE_UPDATED:
synchronized (discoverers) {
ld = discoverers.get(deviceId);
if (ld == null) {
log.debug("Device added ({}) {}", event.type(),
deviceId);
discoverers.put(deviceId, new LinkDiscovery(device,
packetSevice, masterService, providerService,
useBDDP));
} else {
if (ld.isStopped()) {
log.debug("Device restarted ({}) {}", event.type(),
deviceId);
ld.start();
}
synchronized (discoverers) {
ld = discoverers.get(deviceId);
if (ld == null) {
if (rules.isSuppressed(device)) {
log.debug("LinkDiscovery from {} disabled by configuration", device.id());
return;
}
log.debug("Device added ({}) {}", event.type(),
deviceId);
discoverers.put(deviceId, new LinkDiscovery(device,
packetSevice, masterService, providerService,
useBDDP));
} else {
if (ld.isStopped()) {
log.debug("Device restarted ({}) {}", event.type(),
deviceId);
ld.start();
}
}
}
break;
......@@ -204,6 +287,11 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
if (ld == null) {
return;
}
if (rules.isSuppressed(port)) {
log.debug("LinkDiscovery from {}@{} disabled by configuration",
port.number(), device.id());
return;
}
if (!port.number().isLogical()) {
log.debug("Port added {}", port);
ld.addPort(port);
......@@ -280,6 +368,9 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
try {
LinkDiscovery ld = null;
for (Device dev : deviceService.getDevices()) {
if (rules.isSuppressed(dev)) {
continue;
}
DeviceId did = dev.id();
synchronized (discoverers) {
if (!discoverers.containsKey(did)) {
......@@ -287,6 +378,9 @@ public class LLDPLinkProvider extends AbstractProvider implements LinkProvider {
masterService, providerService, useBDDP);
discoverers.put(did, ld);
for (Port p : deviceService.getPorts(did)) {
if (rules.isSuppressed(p)) {
continue;
}
if (!p.number().isLogical()) {
ld.addPort(p);
}
......
......@@ -344,14 +344,12 @@ public class LinkDiscovery implements TimerTask {
}
private void sendProbes(Long portNumber) {
if (device.type() != Device.Type.ROADM) {
log.trace("Sending probes out to {}@{}", portNumber, device.id());
OutboundPacket pkt = this.createOutBoundLLDP(portNumber);
pktService.emit(pkt);
if (useBDDP) {
OutboundPacket bpkt = this.createOutBoundBDDP(portNumber);
pktService.emit(bpkt);
}
log.trace("Sending probes out to {}@{}", portNumber, device.id());
OutboundPacket pkt = this.createOutBoundLLDP(portNumber);
pktService.emit(pkt);
if (useBDDP) {
OutboundPacket bpkt = this.createOutBoundBDDP(portNumber);
pktService.emit(bpkt);
}
}
......
/*
* Copyright 2014 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.lldp.impl;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.onosproject.net.Annotations;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Element;
import org.onosproject.net.Port;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class SuppressionRules {
public static final String ANY_VALUE = "(any)";
private final Set<DeviceId> suppressedDevice;
private final Set<Device.Type> suppressedDeviceType;
private final Map<String, String> suppressedAnnotation;
public SuppressionRules(Set<DeviceId> suppressedDevice,
Set<Device.Type> suppressedType,
Map<String, String> suppressedAnnotation) {
this.suppressedDevice = ImmutableSet.copyOf(suppressedDevice);
this.suppressedDeviceType = ImmutableSet.copyOf(suppressedType);
this.suppressedAnnotation = ImmutableMap.copyOf(suppressedAnnotation);
}
public boolean isSuppressed(Device device) {
if (suppressedDevice.contains(device.id())) {
return true;
}
if (suppressedDeviceType.contains(device.type())) {
return true;
}
final Annotations annotations = device.annotations();
if (containsSuppressionAnnotation(annotations)) {
return true;
}
return false;
}
public boolean isSuppressed(Port port) {
Element parent = port.element();
if (parent instanceof Device) {
if (isSuppressed((Device) parent)) {
return true;
}
}
final Annotations annotations = port.annotations();
if (containsSuppressionAnnotation(annotations)) {
return true;
}
return false;
}
private boolean containsSuppressionAnnotation(final Annotations annotations) {
for (Entry<String, String> entry : suppressedAnnotation.entrySet()) {
final String suppValue = entry.getValue();
final String suppKey = entry.getKey();
if (suppValue == ANY_VALUE) {
if (annotations.keys().contains(suppKey)) {
return true;
}
} else {
if (suppValue.equals(annotations.value(suppKey))) {
return true;
}
}
}
return false;
}
Set<DeviceId> getSuppressedDevice() {
return suppressedDevice;
}
Set<Device.Type> getSuppressedDeviceType() {
return suppressedDeviceType;
}
Map<String, String> getSuppressedAnnotation() {
return suppressedAnnotation;
}
}
/*
* Copyright 2014 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.lldp.impl;
import static com.google.common.base.Preconditions.checkNotNull;
import static org.slf4j.LoggerFactory.getLogger;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.slf4j.Logger;
import java.io.File;
import java.io.IOException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
/*
* JSON file example
*
{
"deviceId" : [ "of:2222000000000000" ],
"deviceType" : [ "ROADM" ],
"annotation" : { "no-lldp" : null, "sendLLDP" : "false" }
}
*/
/**
* Allows for reading and writing LLDP suppression definition as a JSON file.
*/
public class SuppressionRulesStore {
private static final String DEVICE_ID = "deviceId";
private static final String DEVICE_TYPE = "deviceType";
private static final String ANNOTATION = "annotation";
private final Logger log = getLogger(getClass());
private final File file;
/**
* Creates a reader/writer of the LLDP suppression definition file.
*
* @param filePath location of the definition file
*/
public SuppressionRulesStore(String filePath) {
file = new File(filePath);
}
/**
* Creates a reader/writer of the LLDP suppression definition file.
*
* @param file definition file
*/
public SuppressionRulesStore(File file) {
this.file = checkNotNull(file);
}
/**
* Returns SuppressionRules.
*
* @return SuppressionRules
* @throws IOException
*/
public SuppressionRules read() throws IOException {
final Set<DeviceId> suppressedDevice = new HashSet<>();
final EnumSet<Device.Type> suppressedDeviceType = EnumSet.noneOf(Device.Type.class);
final Map<String, String> suppressedAnnotation = new HashMap<>();
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = (ObjectNode) mapper.readTree(file);
for (JsonNode deviceId : root.get(DEVICE_ID)) {
if (deviceId.isTextual()) {
suppressedDevice.add(DeviceId.deviceId(deviceId.asText()));
} else {
log.warn("Encountered unexpected JSONNode {} for deviceId", deviceId);
}
}
for (JsonNode deviceType : root.get(DEVICE_TYPE)) {
if (deviceType.isTextual()) {
suppressedDeviceType.add(Device.Type.valueOf(deviceType.asText()));
} else {
log.warn("Encountered unexpected JSONNode {} for deviceType", deviceType);
}
}
JsonNode annotation = root.get(ANNOTATION);
if (annotation.isObject()) {
ObjectNode obj = (ObjectNode) annotation;
Iterator<Entry<String, JsonNode>> it = obj.fields();
while (it.hasNext()) {
Entry<String, JsonNode> entry = it.next();
final String key = entry.getKey();
final JsonNode value = entry.getValue();
if (value.isValueNode()) {
if (value.isNull()) {
suppressedAnnotation.put(key, SuppressionRules.ANY_VALUE);
} else {
suppressedAnnotation.put(key, value.asText());
}
} else {
log.warn("Encountered unexpected JSON field {} for annotation", entry);
}
}
} else {
log.warn("Encountered unexpected JSONNode {} for annotation", annotation);
}
return new SuppressionRules(suppressedDevice,
suppressedDeviceType,
suppressedAnnotation);
}
/**
* Writes the given SuppressionRules.
*
* @param rules SuppressionRules
* @throws IOException
*/
public void write(SuppressionRules rules) throws IOException {
ObjectMapper mapper = new ObjectMapper();
ObjectNode root = mapper.createObjectNode();
ArrayNode deviceIds = mapper.createArrayNode();
ArrayNode deviceTypes = mapper.createArrayNode();
ObjectNode annotations = mapper.createObjectNode();
root.set(DEVICE_ID, deviceIds);
root.set(DEVICE_TYPE, deviceTypes);
root.set(ANNOTATION, annotations);
rules.getSuppressedDevice()
.forEach(deviceId -> deviceIds.add(deviceId.toString()));
rules.getSuppressedDeviceType()
.forEach(type -> deviceTypes.add(type.toString()));
rules.getSuppressedAnnotation().forEach((key, value) -> {
if (value == SuppressionRules.ANY_VALUE) {
annotations.putNull(key);
} else {
annotations.put(key, value);
}
});
mapper.writeTree(new JsonFactory().createGenerator(file, JsonEncoding.UTF8),
root);
}
}
/*
* Copyright 2014 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.lldp.impl;
import static org.junit.Assert.*;
import static org.onosproject.net.DeviceId.deviceId;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.onosproject.net.Device;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.io.Resources;
public class SuppressionRulesStoreTest {
@Rule
public TemporaryFolder tempFolder = new TemporaryFolder();
// "lldp_suppression.json"
SuppressionRules testData
= new SuppressionRules(ImmutableSet.of(deviceId("of:2222000000000000")),
ImmutableSet.of(Device.Type.ROADM),
ImmutableMap.of("no-lldp", SuppressionRules.ANY_VALUE,
"sendLLDP", "false"));
private static void assertRulesEqual(SuppressionRules expected, SuppressionRules actual) {
assertEquals(expected.getSuppressedDevice(),
actual.getSuppressedDevice());
assertEquals(expected.getSuppressedDeviceType(),
actual.getSuppressedDeviceType());
assertEquals(expected.getSuppressedAnnotation(),
actual.getSuppressedAnnotation());
}
@Test
public void testRead() throws URISyntaxException, IOException {
Path path = Paths.get(Resources.getResource("lldp_suppression.json").toURI());
SuppressionRulesStore store = new SuppressionRulesStore(path.toString());
SuppressionRules rules = store.read();
assertRulesEqual(testData, rules);
}
@Test
public void testWrite() throws IOException {
File newFile = tempFolder.newFile();
SuppressionRulesStore store = new SuppressionRulesStore(newFile);
store.write(testData);
SuppressionRulesStore reload = new SuppressionRulesStore(newFile);
SuppressionRules rules = reload.read();
assertRulesEqual(testData, rules);
}
}
package org.onosproject.provider.lldp.impl;
import static org.junit.Assert.*;
import static org.onosproject.net.DeviceId.deviceId;
import org.junit.Before;
import org.junit.Test;
import org.onlab.packet.ChassisId;
import org.onosproject.net.Annotations;
import org.onosproject.net.DefaultAnnotations;
import org.onosproject.net.DefaultDevice;
import org.onosproject.net.DefaultPort;
import org.onosproject.net.Device;
import org.onosproject.net.DeviceId;
import org.onosproject.net.Port;
import org.onosproject.net.PortNumber;
import org.onosproject.net.provider.ProviderId;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
public class SuppressionRulesTest {
private static final DeviceId NON_SUPPRESSED_DID = deviceId("of:1111000000000000");
private static final DeviceId SUPPRESSED_DID = deviceId("of:2222000000000000");
private static final ProviderId PID = new ProviderId("of", "foo");
private static final String MFR = "whitebox";
private static final String HW = "1.1.x";
private static final String SW1 = "3.8.1";
private static final String SN = "43311-12345";
private static final ChassisId CID = new ChassisId();
private static final PortNumber P1 = PortNumber.portNumber(1);
private SuppressionRules rules;
@Before
public void setUp() throws Exception {
rules = new SuppressionRules(ImmutableSet.of(SUPPRESSED_DID),
ImmutableSet.of(Device.Type.ROADM),
ImmutableMap.of("no-lldp", SuppressionRules.ANY_VALUE,
"sendLLDP", "false"));
}
@Test
public void testSuppressedDeviceId() {
Device device = new DefaultDevice(PID,
SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
assertTrue(rules.isSuppressed(device));
}
@Test
public void testSuppressedDeviceType() {
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.ROADM,
MFR, HW, SW1, SN, CID);
assertTrue(rules.isSuppressed(device));
}
@Test
public void testSuppressedDeviceAnnotation() {
Annotations annotation = DefaultAnnotations.builder()
.set("no-lldp", "random")
.build();
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID, annotation);
assertTrue(rules.isSuppressed(device));
}
@Test
public void testSuppressedDeviceAnnotationExact() {
Annotations annotation = DefaultAnnotations.builder()
.set("sendLLDP", "false")
.build();
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID, annotation);
assertTrue(rules.isSuppressed(device));
}
@Test
public void testNotSuppressedDevice() {
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
assertFalse(rules.isSuppressed(device));
}
@Test
public void testSuppressedPortOnSuppressedDevice() {
Device device = new DefaultDevice(PID,
SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
Port port = new DefaultPort(device, P1, true);
assertTrue(rules.isSuppressed(port));
}
@Test
public void testSuppressedPortAnnotation() {
Annotations annotation = DefaultAnnotations.builder()
.set("no-lldp", "random")
.build();
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
Port port = new DefaultPort(device, P1, true, annotation);
assertTrue(rules.isSuppressed(port));
}
@Test
public void testSuppressedPortAnnotationExact() {
Annotations annotation = DefaultAnnotations.builder()
.set("sendLLDP", "false")
.build();
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
Port port = new DefaultPort(device, P1, true, annotation);
assertTrue(rules.isSuppressed(port));
}
@Test
public void testNotSuppressedPort() {
Device device = new DefaultDevice(PID,
NON_SUPPRESSED_DID,
Device.Type.SWITCH,
MFR, HW, SW1, SN, CID);
Port port = new DefaultPort(device, P1, true);
assertFalse(rules.isSuppressed(port));
}
}
{
"deviceId" : [ "of:2222000000000000" ],
"deviceType" : [ "ROADM" ],
"annotation" : { "no-lldp" : null, "sendLLDP" : "false" }
}