[SEBA-593] Splitting dhcpl2relay app in implementation and api bundles
Change-Id: Ia9c060eeac3d74dc6829d774d32d288da0df203e
diff --git a/app/app.xml b/app/app.xml
new file mode 100644
index 0000000..3bcf254
--- /dev/null
+++ b/app/app.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright 2018-present Open Networking Foundation
+ ~
+ ~ 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.
+ -->
+<app name="org.opencord.dhcpl2relay" origin="ON.Lab" version="${project.version}"
+ category="default" url="http://onosproject.org" title="DHCP L2 Relay"
+ featuresRepo="mvn:${project.groupId}/${project.artifactId}/${project.version}/xml/features"
+ features="${project.artifactId}" apps="org.opencord.sadis">
+ <description>${project.description}</description>
+ <artifact>mvn:${project.groupId}/${project.artifactId}/${project.version}</artifact>
+ <artifact>mvn:${project.groupId}/dhcpl2relay-api/${project.version}</artifact>
+</app>
diff --git a/app/features.xml b/app/features.xml
new file mode 100644
index 0000000..ba4b895
--- /dev/null
+++ b/app/features.xml
@@ -0,0 +1,24 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!--
+ ~ Copyright 2018-present Open Networking Foundation
+ ~
+ ~ 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.
+ -->
+<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="${project.artifactId}-${project.version}">
+ <feature name="${project.artifactId}" version="${project.version}"
+ description="${project.description}">
+ <feature>onos-api</feature>
+ <bundle>mvn:${project.groupId}/dhcpl2relay-api/${project.version}</bundle>
+ <bundle>mvn:${project.groupId}/${project.artifactId}/${project.version}</bundle>
+ </feature>
+</features>
diff --git a/app/pom.xml b/app/pom.xml
new file mode 100644
index 0000000..d27a579
--- /dev/null
+++ b/app/pom.xml
@@ -0,0 +1,186 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ~ Copyright 2016-present Open Networking Foundation
+ ~
+ ~ 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.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <parent>
+ <artifactId>dhcpl2relay</artifactId>
+ <groupId>org.opencord</groupId>
+ <version>1.6.0-SNAPSHOT</version>
+ </parent>
+ <modelVersion>4.0.0</modelVersion>
+
+ <artifactId>dhcpl2relay-app</artifactId>
+
+ <packaging>bundle</packaging>
+ <description>DHCP L2 Realy application for CORD</description>
+
+ <properties>
+ <onos.app.name>org.opencord.dhcpl2relay</onos.app.name>
+ <onos.version>1.13.9-rc4</onos.version>
+ <onos.app.title>DHCP Relay Agent App</onos.app.title>
+ <onos.app.category>default</onos.app.category>
+ <onos.app.url>http://opencord.org</onos.app.url>
+ <onos.app.readme>DHCP L2 Relay Agent Application.</onos.app.readme>
+ <onos.app.requires>
+ org.opencord.sadis
+ </onos.app.requires>
+ <sadis.api.version>3.0.0</sadis.api.version>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-api</artifactId>
+ <version>${onos.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.opencord</groupId>
+ <artifactId>sadis-api</artifactId>
+ <version>${sadis.api.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.opencord</groupId>
+ <artifactId>dhcpl2relay-api</artifactId>
+ <version>1.6.0-SNAPSHOT</version>
+ <scope>compile</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-incubator-api</artifactId>
+ <version>${onos.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-osgi</artifactId>
+ <version>${onos.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-junit</artifactId>
+ <version>${onos.version}</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-cli</artifactId>
+ <version>${onos.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-api</artifactId>
+ <version>${onos.version}</version>
+ <scope>test</scope>
+ <classifier>tests</classifier>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>org.apache.felix.scr.annotations</artifactId>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.compendium</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onlab-osgi</artifactId>
+ <version>${onos.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.easymock</groupId>
+ <artifactId>easymock</artifactId>
+ <scope>test</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.karaf.shell</groupId>
+ <artifactId>org.apache.karaf.shell.console</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-core-common</artifactId>
+ <version>${onos.version}</version>
+ <classifier>tests</classifier>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-scr-plugin</artifactId>
+ </plugin>
+
+ <plugin>
+ <groupId>org.onosproject</groupId>
+ <artifactId>onos-maven-plugin</artifactId>
+ <version>1.11</version>
+ </plugin>
+ </plugins>
+ </build>
+
+ <repositories>
+ <repository>
+ <id>central</id>
+ <name>Central Repository</name>
+ <url>http://repo.maven.apache.org/maven2</url>
+ <layout>default</layout>
+ <snapshots>
+ <enabled>false</enabled>
+ </snapshots>
+ <releases>
+ <enabled>true</enabled>
+ <updatePolicy>always</updatePolicy>
+ <checksumPolicy>fail</checksumPolicy>
+ </releases>
+ </repository>
+
+ <repository>
+ <id>snapshots</id>
+ <url>https://oss.sonatype.org/content/repositories/snapshots</url>
+ <snapshots>
+ <enabled>true</enabled>
+ <updatePolicy>always</updatePolicy>
+ <checksumPolicy>fail</checksumPolicy>
+ </snapshots>
+ </repository>
+ </repositories>
+
+</project>
\ No newline at end of file
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2Relay.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2Relay.java
new file mode 100755
index 0000000..cf35677
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2Relay.java
@@ -0,0 +1,972 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl;
+
+import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
+import static org.onlab.packet.MacAddress.valueOf;
+import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
+
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Dictionary;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.Set;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
+
+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.apache.felix.scr.annotations.Service;
+import org.onlab.packet.DHCP;
+import org.onlab.packet.DHCPPacketType;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.TpPort;
+import org.onlab.packet.UDP;
+import org.onlab.packet.VlanId;
+import org.onlab.packet.dhcp.DhcpOption;
+import org.onlab.util.Tools;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreService;
+import org.onosproject.event.AbstractListenerManager;
+import org.onosproject.mastership.MastershipEvent;
+import org.onosproject.mastership.MastershipListener;
+import org.onosproject.mastership.MastershipService;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Host;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.config.ConfigFactory;
+import org.onosproject.net.config.NetworkConfigEvent;
+import org.onosproject.net.config.NetworkConfigListener;
+import org.onosproject.net.config.NetworkConfigRegistry;
+import org.onosproject.net.device.DeviceEvent;
+import org.onosproject.net.device.DeviceListener;
+import org.onosproject.net.device.DeviceService;
+import org.onosproject.net.flow.DefaultTrafficSelector;
+import org.onosproject.net.flow.DefaultTrafficTreatment;
+import org.onosproject.net.flow.TrafficSelector;
+import org.onosproject.net.flow.TrafficTreatment;
+import org.onosproject.net.flowobjective.FlowObjectiveService;
+import org.onosproject.net.host.HostService;
+import org.onosproject.net.packet.DefaultOutboundPacket;
+import org.onosproject.net.packet.OutboundPacket;
+import org.onosproject.net.packet.PacketContext;
+import org.onosproject.net.packet.PacketPriority;
+import org.onosproject.net.packet.PacketProcessor;
+import org.onosproject.net.packet.PacketService;
+import org.opencord.dhcpl2relay.DhcpAllocationInfo;
+import org.opencord.dhcpl2relay.DhcpL2RelayEvent;
+import org.opencord.dhcpl2relay.DhcpL2RelayListener;
+import org.opencord.dhcpl2relay.DhcpL2RelayService;
+import org.opencord.dhcpl2relay.impl.packet.DhcpOption82;
+import org.opencord.sadis.BaseInformationService;
+import org.opencord.sadis.SadisService;
+import org.opencord.sadis.SubscriberAndDeviceInformation;
+import org.osgi.service.component.ComponentContext;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+
+/**
+ * DHCP Relay Agent Application Component.
+ */
+@Service
+@Component(immediate = true)
+public class DhcpL2Relay
+ extends AbstractListenerManager<DhcpL2RelayEvent, DhcpL2RelayListener>
+ implements DhcpL2RelayService {
+
+ public static final String DHCP_L2RELAY_APP = "org.opencord.dhcpl2relay";
+ private static final String HOST_LOC_PROVIDER =
+ "org.onosproject.provider.host.impl.HostLocationProvider";
+ private final Logger log = LoggerFactory.getLogger(getClass());
+ private final InternalConfigListener cfgListener =
+ new InternalConfigListener();
+
+ private final Set<ConfigFactory> factories = ImmutableSet.of(
+ new ConfigFactory<ApplicationId, DhcpL2RelayConfig>(APP_SUBJECT_FACTORY,
+ DhcpL2RelayConfig.class,
+ "dhcpl2relay") {
+ @Override
+ public DhcpL2RelayConfig createConfig() {
+ return new DhcpL2RelayConfig();
+ }
+ }
+ );
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected NetworkConfigRegistry cfgService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected CoreService coreService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected PacketService packetService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected HostService hostService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected ComponentConfigService componentConfigService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected SadisService sadisService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected DeviceService deviceService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected MastershipService mastershipService;
+
+ @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
+ protected FlowObjectiveService flowObjectiveService;
+
+ @Property(name = "option82", boolValue = true,
+ label = "Add option 82 to relayed packets")
+ protected boolean option82 = true;
+
+ @Property(name = "enableDhcpBroadcastReplies", boolValue = false,
+ label = "Ask the DHCP Server to send back replies as L2 broadcast")
+ protected boolean enableDhcpBroadcastReplies = false;
+
+ private DhcpRelayPacketProcessor dhcpRelayPacketProcessor =
+ new DhcpRelayPacketProcessor();
+
+ private InnerMastershipListener changeListener = new InnerMastershipListener();
+ private InnerDeviceListener deviceListener = new InnerDeviceListener();
+
+ // connect points to the DHCP server
+ Set<ConnectPoint> dhcpConnectPoints;
+ private AtomicReference<ConnectPoint> dhcpServerConnectPoint = new AtomicReference<>();
+ private MacAddress dhcpConnectMac = MacAddress.BROADCAST;
+ private ApplicationId appId;
+
+ static Map<String, DhcpAllocationInfo> allocationMap = Maps.newConcurrentMap();
+ private boolean modifyClientPktsSrcDstMac = false;
+ //Whether to use the uplink port of the OLTs to send/receive messages to the DHCP server
+ private boolean useOltUplink = false;
+
+ private BaseInformationService<SubscriberAndDeviceInformation> subsService;
+
+ @Activate
+ protected void activate(ComponentContext context) {
+ //start the dhcp relay agent
+ appId = coreService.registerApplication(DHCP_L2RELAY_APP);
+ // ensure that host-learning via dhcp includes IP addresses
+ componentConfigService.preSetProperty(HOST_LOC_PROVIDER,
+ "useDhcp", Boolean.TRUE.toString());
+ componentConfigService.registerProperties(getClass());
+ eventDispatcher.addSink(DhcpL2RelayEvent.class, listenerRegistry);
+
+ cfgService.addListener(cfgListener);
+ mastershipService.addListener(changeListener);
+ deviceService.addListener(deviceListener);
+
+ factories.forEach(cfgService::registerConfigFactory);
+ //update the dhcp server configuration.
+ updateConfig();
+ //add the packet services.
+ packetService.addProcessor(dhcpRelayPacketProcessor,
+ PacketProcessor.director(0));
+ if (context != null) {
+ modified(context);
+ }
+
+ subsService = sadisService.getSubscriberInfoService();
+
+ log.info("DHCP-L2-RELAY Started");
+ }
+
+ @Deactivate
+ protected void deactivate() {
+ cfgService.removeListener(cfgListener);
+ factories.forEach(cfgService::unregisterConfigFactory);
+ packetService.removeProcessor(dhcpRelayPacketProcessor);
+ cancelDhcpPktsFromServer();
+
+ componentConfigService.unregisterProperties(getClass(), false);
+ deviceService.removeListener(deviceListener);
+ mastershipService.removeListener(changeListener);
+ eventDispatcher.removeSink(DhcpL2RelayEvent.class);
+ log.info("DHCP-L2-RELAY Stopped");
+ }
+
+ @Modified
+ protected void modified(ComponentContext context) {
+
+ Dictionary<?, ?> properties = context.getProperties();
+
+ Boolean o = Tools.isPropertyEnabled(properties, "option82");
+ if (o != null) {
+ option82 = o;
+ }
+
+ o = Tools.isPropertyEnabled(properties, "enableDhcpBroadcastReplies");
+ if (o != null) {
+ enableDhcpBroadcastReplies = o;
+ }
+ }
+
+ /**
+ * Checks if this app has been configured.
+ *
+ * @return true if all information we need have been initialized
+ */
+ private boolean configured() {
+ if (!useOltUplink) {
+ return dhcpServerConnectPoint.get() != null;
+ }
+ return true;
+ }
+
+ /**
+ * Selects a connect point through an available device for which it is the master.
+ */
+ private void selectServerConnectPoint() {
+ synchronized (this) {
+ dhcpServerConnectPoint.set(null);
+ if (dhcpConnectPoints != null) {
+ // find a connect point through a device for which we are master
+ for (ConnectPoint cp: dhcpConnectPoints) {
+ if (mastershipService.isLocalMaster(cp.deviceId())) {
+ if (deviceService.isAvailable(cp.deviceId())) {
+ dhcpServerConnectPoint.set(cp);
+ }
+ log.info("DHCP connectPoint selected is {}", cp);
+ break;
+ }
+ }
+ }
+
+ log.info("DHCP Server connectPoint is {}", dhcpServerConnectPoint.get());
+
+ if (dhcpServerConnectPoint.get() == null) {
+ log.error("Master of none, can't relay DHCP Message to server");
+ }
+ }
+ }
+
+ /**
+ * Updates the network configuration.
+ */
+ private void updateConfig() {
+ DhcpL2RelayConfig cfg = cfgService.getConfig(appId, DhcpL2RelayConfig.class);
+ if (cfg == null) {
+ log.warn("Dhcp Server info not available");
+ return;
+ }
+
+ dhcpConnectPoints = Sets.newConcurrentHashSet(cfg.getDhcpServerConnectPoint());
+ modifyClientPktsSrcDstMac = cfg.getModifySrcDstMacAddresses();
+ boolean prevUseOltUplink = useOltUplink;
+ useOltUplink = cfg.getUseOltUplinkForServerPktInOut();
+
+ if (useOltUplink) {
+ for (ConnectPoint cp : getUplinkPortsOfOlts()) {
+ log.debug("requestDhcpPackets: ConnectPoint: {}", cp);
+ requestDhcpPacketsFromConnectPoint(cp, null);
+ }
+ // check if previous config was different and so trap flows may
+ // need to be removed from other places like AGG switches
+ if (!prevUseOltUplink) {
+ addOrRemoveDhcpTrapFromServer(false);
+ }
+ } else {
+ // uplink on AGG switch
+ addOrRemoveDhcpTrapFromServer(true);
+ }
+ }
+
+ private void cancelDhcpPktsFromServer() {
+ if (useOltUplink) {
+ for (ConnectPoint cp : getUplinkPortsOfOlts()) {
+ log.debug("cancelDhcpPackets: ConnectPoint: {}", cp);
+ cancelDhcpPacketsFromConnectPoint(cp, null);
+ }
+ } else {
+ // uplink on AGG switch
+ addOrRemoveDhcpTrapFromServer(false);
+ }
+ }
+
+ /**
+ * Used to add or remove DHCP trap flow for packets received from DHCP server.
+ * Typically used on a non OLT device, like an AGG switch. When adding, a
+ * new dhcp server connect point is selected from the configured options.
+ *
+ * @param add true if dhcp trap flow is to be added, false to remove the
+ * trap flow
+ */
+ private void addOrRemoveDhcpTrapFromServer(boolean add) {
+ if (add) {
+ selectServerConnectPoint();
+ log.debug("dhcp server connect point: " + dhcpServerConnectPoint);
+ }
+ if (dhcpServerConnectPoint.get() == null) {
+ log.warn("No dhcpServer connectPoint found, cannot {} dhcp trap flows",
+ (add) ? "install" : "remove");
+ return;
+ }
+ if (add) {
+ log.info("Adding trap to dhcp server connect point: "
+ + dhcpServerConnectPoint);
+ requestDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
+ Optional.of(PacketPriority.HIGH1));
+ } else {
+ log.info("Removing trap from dhcp server connect point: "
+ + dhcpServerConnectPoint);
+ cancelDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
+ Optional.of(PacketPriority.HIGH1));
+ }
+ }
+
+ /**
+ * Returns all the uplink ports of OLTs configured in SADIS.
+ * Only ports visible in ONOS and for which this instance is master
+ * are returned
+ */
+ private List<ConnectPoint> getUplinkPortsOfOlts() {
+ List<ConnectPoint> cps = new ArrayList<>();
+
+ // find all the olt devices and if their uplink ports are visible
+ Iterable<Device> devices = deviceService.getDevices();
+ for (Device d : devices) {
+ // check if this device is provisioned in Sadis
+
+ log.debug("getUplinkPortsOfOlts: Checking mastership of {}", d);
+ // do only for devices for which we are the master
+ if (!mastershipService.isLocalMaster(d.id())) {
+ continue;
+ }
+
+ String devSerialNo = d.serialNumber();
+ SubscriberAndDeviceInformation deviceInfo = subsService.get(devSerialNo);
+ log.debug("getUplinkPortsOfOlts: Found device: {}", deviceInfo);
+ if (deviceInfo != null) {
+ // check if the uplink port with that number is available on the device
+ PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
+ Port port = deviceService.getPort(d.id(), pNum);
+ log.debug("getUplinkPortsOfOlts: Found port: {}", port);
+ if (port != null) {
+ cps.add(new ConnectPoint(d.id(), pNum));
+ }
+ }
+ }
+ return cps;
+ }
+
+ /**
+ * Returns whether the passed port is the uplink port of the olt device.
+ */
+ private boolean isUplinkPortOfOlt(DeviceId dId, Port p) {
+ log.debug("isUplinkPortOfOlt: DeviceId: {} Port: {}", dId, p);
+ // do only for devices for which we are the master
+ if (!mastershipService.isLocalMaster(dId)) {
+ return false;
+ }
+
+ Device d = deviceService.getDevice(dId);
+ SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
+
+ if (deviceInfo != null) {
+ return (deviceInfo.uplinkPort() == p.number().toLong());
+ }
+
+ return false;
+ }
+
+ /**
+ * Returns the connectPoint which is the uplink port of the OLT.
+ */
+ private ConnectPoint getUplinkConnectPointOfOlt(DeviceId dId) {
+
+ Device d = deviceService.getDevice(dId);
+ SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
+ log.debug("getUplinkConnectPointOfOlt DeviceId: {} devInfo: {}", dId, deviceInfo);
+ if (deviceInfo != null) {
+ PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
+ Port port = deviceService.getPort(d.id(), pNum);
+ if (port != null) {
+ return new ConnectPoint(d.id(), pNum);
+ }
+ }
+
+ return null;
+ }
+
+ /**
+ * Request DHCP packet from particular connect point via PacketService.
+ * Optionally provide a priority for the trap flow. If no such priority is
+ * provided, the default priority will be used.
+ *
+ * @param cp the connect point to trap dhcp packets from
+ * @param priority of the trap flow, null to use default priority
+ */
+ private void requestDhcpPacketsFromConnectPoint(ConnectPoint cp,
+ Optional<PacketPriority> priority) {
+ TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchInPort(cp.port())
+ .matchIPProtocol(IPv4.PROTOCOL_UDP)
+ .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
+ packetService.requestPackets(selectorServer.build(),
+ priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
+ appId, Optional.of(cp.deviceId()));
+ }
+
+ /**
+ * Cancel DHCP packet from particular connect point via PacketService. If
+ * the request was made with a specific packet priority, then the same
+ * priority should be used in this call.
+ *
+ * @param cp the connect point for the trap flow
+ * @param priority with which the trap flow was requested; if request
+ * priority was not specified, this param should also be null
+ */
+ private void cancelDhcpPacketsFromConnectPoint(ConnectPoint cp,
+ Optional<PacketPriority> priority) {
+ TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
+ .matchEthType(Ethernet.TYPE_IPV4)
+ .matchInPort(cp.port())
+ .matchIPProtocol(IPv4.PROTOCOL_UDP)
+ .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
+ packetService.cancelPackets(selectorServer.build(),
+ priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
+ appId, Optional.of(cp.deviceId()));
+ }
+
+ public static Map<String, DhcpAllocationInfo> allocationMap() {
+ return allocationMap;
+ }
+
+ private SubscriberAndDeviceInformation getDevice(PacketContext context) {
+ String serialNo = deviceService.getDevice(context.inPacket().
+ receivedFrom().deviceId()).serialNumber();
+
+ return subsService.get(serialNo);
+ }
+
+ private SubscriberAndDeviceInformation getDevice(ConnectPoint cp) {
+ String serialNo = deviceService.getDevice(cp.deviceId()).
+ serialNumber();
+
+ return subsService.get(serialNo);
+ }
+
+ private MacAddress relayAgentMacAddress(PacketContext context) {
+
+ SubscriberAndDeviceInformation device = this.getDevice(context);
+ if (device == null) {
+ log.warn("Device not found for {}", context.inPacket().
+ receivedFrom());
+ return null;
+ }
+
+ return device.hardwareIdentifier();
+ }
+
+ private String nasPortId(PacketContext context) {
+ return nasPortId(context.inPacket().receivedFrom());
+ }
+
+ private String nasPortId(ConnectPoint cp) {
+ Port p = deviceService.getPort(cp);
+ return p.annotations().value(AnnotationKeys.PORT_NAME);
+ }
+
+ private SubscriberAndDeviceInformation getSubscriber(PacketContext context) {
+ return subsService.get(nasPortId(context));
+ }
+
+ private VlanId cTag(PacketContext context) {
+ SubscriberAndDeviceInformation sub = getSubscriber(context);
+ if (sub == null) {
+ log.warn("Subscriber info not found for {}", context.inPacket().
+ receivedFrom());
+ return VlanId.NONE;
+ }
+ return sub.cTag();
+ }
+
+ private VlanId cTag(ConnectPoint cp) {
+ String portId = nasPortId(cp);
+ SubscriberAndDeviceInformation sub = subsService.get(portId);
+ if (sub == null) {
+ log.warn("Subscriber info not found for {} looking for C-TAG", cp);
+ return VlanId.NONE;
+ }
+ return sub.cTag();
+ }
+
+ private VlanId sTag(ConnectPoint cp) {
+ String portId = nasPortId(cp);
+ SubscriberAndDeviceInformation sub = subsService.get(portId);
+ if (sub == null) {
+ log.warn("Subscriber info not found for {} looking for S-TAG", cp);
+ return VlanId.NONE;
+ }
+ return sub.sTag();
+ }
+
+ private VlanId sTag(PacketContext context) {
+ SubscriberAndDeviceInformation sub = getSubscriber(context);
+ if (sub == null) {
+ log.warn("Subscriber info not found for {}", context.inPacket().
+ receivedFrom());
+ return VlanId.NONE;
+ }
+ return sub.sTag();
+ }
+
+ private class DhcpRelayPacketProcessor implements PacketProcessor {
+
+ @Override
+ public void process(PacketContext context) {
+ if (!configured()) {
+ log.warn("Missing DHCP relay config. Abort packet processing");
+ return;
+ }
+
+ // process the packet and get the payload
+ Ethernet packet = context.inPacket().parsed();
+
+ if (packet == null) {
+ log.warn("Packet is null");
+ return;
+ }
+
+ if (packet.getEtherType() == Ethernet.TYPE_IPV4) {
+ IPv4 ipv4Packet = (IPv4) packet.getPayload();
+
+ if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_UDP) {
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ if (udpPacket.getSourcePort() == UDP.DHCP_CLIENT_PORT ||
+ udpPacket.getSourcePort() == UDP.DHCP_SERVER_PORT) {
+ DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
+ //This packet is dhcp.
+ processDhcpPacket(context, packet, dhcpPayload);
+ }
+ }
+ }
+ }
+
+ //forward the packet to ConnectPoint where the DHCP server is attached.
+ private void forwardPacket(Ethernet packet, PacketContext context) {
+ ConnectPoint toSendTo = null;
+
+ if (!useOltUplink) {
+ toSendTo = dhcpServerConnectPoint.get();
+ } else {
+ toSendTo = getUplinkConnectPointOfOlt(context.inPacket().
+ receivedFrom().deviceId());
+ }
+
+ if (toSendTo != null) {
+ TrafficTreatment t = DefaultTrafficTreatment.builder()
+ .setOutput(toSendTo.port()).build();
+ OutboundPacket o = new DefaultOutboundPacket(
+ toSendTo.deviceId(), t,
+ ByteBuffer.wrap(packet.serialize()));
+ if (log.isTraceEnabled()) {
+ log.trace("Relaying packet to dhcp server at {} {}",
+ toSendTo, packet);
+ }
+ packetService.emit(o);
+ } else {
+ log.error("No connect point to send msg to DHCP Server");
+ }
+ }
+
+ // get the type of the DHCP packet
+ private DHCPPacketType getDhcpPacketType(DHCP dhcpPayload) {
+
+ for (DhcpOption option : dhcpPayload.getOptions()) {
+ if (option.getCode() == OptionCode_MessageType.getValue()) {
+ byte[] data = option.getData();
+ return DHCPPacketType.getType(data[0]);
+ }
+ }
+ return null;
+ }
+
+ //process the dhcp packet before sending to server
+ private void processDhcpPacket(PacketContext context, Ethernet packet,
+ DHCP dhcpPayload) {
+ if (dhcpPayload == null) {
+ log.warn("DHCP payload is null");
+ return;
+ }
+
+ DHCPPacketType incomingPacketType = getDhcpPacketType(dhcpPayload);
+
+ log.info("Received DHCP Packet of type {} from {}",
+ incomingPacketType, context.inPacket().receivedFrom());
+
+ switch (incomingPacketType) {
+ case DHCPDISCOVER:
+ Ethernet ethernetPacketDiscover =
+ processDhcpPacketFromClient(context, packet);
+ if (ethernetPacketDiscover != null) {
+ forwardPacket(ethernetPacketDiscover, context);
+ }
+ break;
+ case DHCPOFFER:
+ //reply to dhcp client.
+ Ethernet ethernetPacketOffer =
+ processDhcpPacketFromServer(context, packet);
+ if (ethernetPacketOffer != null) {
+ sendReply(ethernetPacketOffer, dhcpPayload);
+ }
+ break;
+ case DHCPREQUEST:
+ Ethernet ethernetPacketRequest =
+ processDhcpPacketFromClient(context, packet);
+ if (ethernetPacketRequest != null) {
+ forwardPacket(ethernetPacketRequest, context);
+ }
+ break;
+ case DHCPACK:
+ //reply to dhcp client.
+ Ethernet ethernetPacketAck =
+ processDhcpPacketFromServer(context, packet);
+ if (ethernetPacketAck != null) {
+ sendReply(ethernetPacketAck, dhcpPayload);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+
+ private Ethernet processDhcpPacketFromClient(PacketContext context,
+ Ethernet ethernetPacket) {
+ if (log.isTraceEnabled()) {
+ log.trace("DHCP packet received from client at {} {}",
+ context.inPacket().receivedFrom(), ethernetPacket);
+ }
+
+ MacAddress relayAgentMac = relayAgentMacAddress(context);
+ if (relayAgentMac == null) {
+ log.warn("RelayAgent MAC not found ");
+ return null;
+ }
+
+ Ethernet etherReply = ethernetPacket;
+
+ IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ if (enableDhcpBroadcastReplies) {
+ // We want the reply to come back as a L2 broadcast
+ dhcpPacket.setFlags((short) 0x8000);
+ }
+
+ MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
+ IpAddress clientIp = IpAddress.valueOf(dhcpPacket.getClientIPAddress());
+
+ SubscriberAndDeviceInformation entry = getSubscriber(context);
+ if (entry == null) {
+ log.warn("Dropping packet as subscriber entry is not available");
+ return null;
+ }
+
+ DhcpAllocationInfo info = new DhcpAllocationInfo(
+ context.inPacket().receivedFrom(), dhcpPacket.getPacketType(),
+ entry.nasPortId(), clientMac, clientIp);
+
+ allocationMap.put(entry.nasPortId(), info);
+
+ post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info,
+ context.inPacket().receivedFrom()));
+
+ if (option82) {
+ DHCP dhcpPacketWithOption82 = addOption82(dhcpPacket, entry);
+ udpPacket.setPayload(dhcpPacketWithOption82);
+ }
+
+ ipv4Packet.setPayload(udpPacket);
+ etherReply.setPayload(ipv4Packet);
+ if (modifyClientPktsSrcDstMac) {
+ etherReply.setSourceMACAddress(relayAgentMac);
+ etherReply.setDestinationMACAddress(dhcpConnectMac);
+ }
+
+ etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
+ etherReply.setVlanID(cTag(context).toShort());
+ etherReply.setQinQTPID(Ethernet.TYPE_VLAN);
+ etherReply.setQinQVID(sTag(context).toShort());
+ log.info("Finished processing packet.. relaying to dhcpServer");
+ return etherReply;
+ }
+
+ //build the DHCP offer/ack with proper client port.
+ private Ethernet processDhcpPacketFromServer(PacketContext context,
+ Ethernet ethernetPacket) {
+ if (log.isTraceEnabled()) {
+ log.trace("DHCP packet received from server at {} {}",
+ context.inPacket().receivedFrom(), ethernetPacket);
+ }
+ // get dhcp header.
+ Ethernet etherReply = (Ethernet) ethernetPacket.clone();
+ IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
+
+ MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
+ ConnectPoint subsCp = getConnectPointOfClient(dstMac);
+ // If we can't find the subscriber, can't process further
+ if (subsCp == null) {
+ return null;
+ }
+ // if it's an ACK packet store the information for display purpose
+ if (getDhcpPacketType(dhcpPayload) == DHCPPacketType.DHCPACK) {
+
+ String portId = nasPortId(subsCp);
+ SubscriberAndDeviceInformation sub = subsService.get(portId);
+ if (sub != null) {
+ List<DhcpOption> options = dhcpPayload.getOptions();
+ List<DhcpOption> circuitIds = options.stream()
+ .filter(option -> option.getCode() == DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
+ .collect(Collectors.toList());
+
+ String circuitId = "None";
+ if (circuitIds.size() == 1) {
+ byte[] array = circuitIds.get(0).getData();
+
+ try {
+ // we leave the first two bytes as they are the id and length
+ circuitId = new String(Arrays.copyOfRange(array, 2, array.length), "UTF-8");
+ } catch (Exception e) { }
+ }
+
+ IpAddress ip = IpAddress.valueOf(dhcpPayload.getYourIPAddress());
+
+ //storeDHCPAllocationInfo
+ DhcpAllocationInfo info = new DhcpAllocationInfo(subsCp,
+ dhcpPayload.getPacketType(), circuitId, dstMac, ip);
+
+ allocationMap.put(sub.nasPortId(), info);
+
+ post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info, subsCp));
+ }
+ } // end storing of info
+
+ // we leave the srcMac from the original packet
+ etherReply.setDestinationMACAddress(dstMac);
+ etherReply.setQinQVID(sTag(subsCp).toShort());
+ etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
+ etherReply.setVlanID((cTag(subsCp).toShort()));
+
+ if (option82) {
+ udpPacket.setPayload(removeOption82(dhcpPayload));
+ } else {
+ udpPacket.setPayload(dhcpPayload);
+ }
+ ipv4Packet.setPayload(udpPacket);
+ etherReply.setPayload(ipv4Packet);
+
+ log.info("Finished processing packet.. relaying to client");
+ return etherReply;
+ }
+
+ /*
+ * Get ConnectPoint of the Client based on it's MAC address
+ */
+ private ConnectPoint getConnectPointOfClient(MacAddress dstMac) {
+ Set<Host> hosts = hostService.getHostsByMac(dstMac);
+ if (hosts == null || hosts.isEmpty()) {
+ log.warn("Cannot determine host for DHCP client: {}. Aborting "
+ + "relay for dhcp packet from server",
+ dstMac);
+ return null;
+ }
+ for (Host h : hosts) {
+ // if more than one,
+ // find the connect point which has an valid entry in SADIS
+ ConnectPoint cp = new ConnectPoint(h.location().deviceId(),
+ h.location().port());
+
+ if (sTag(cp) != VlanId.NONE) {
+ return cp;
+ }
+ }
+
+ return null;
+ }
+
+ //send the response to the requester host.
+ private void sendReply(Ethernet ethPacket, DHCP dhcpPayload) {
+ MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
+ ConnectPoint subCp = getConnectPointOfClient(descMac);
+
+ // Send packet out to requester if the host information is available
+ if (subCp != null) {
+ log.info("Sending DHCP packet to client at {}", subCp);
+ TrafficTreatment t = DefaultTrafficTreatment.builder()
+ .setOutput(subCp.port()).build();
+ OutboundPacket o = new DefaultOutboundPacket(
+ subCp.deviceId(), t, ByteBuffer.wrap(ethPacket.serialize()));
+ if (log.isTraceEnabled()) {
+ log.trace("Relaying packet to dhcp client at {} {}", subCp,
+ ethPacket);
+ }
+ packetService.emit(o);
+ } else {
+ log.error("Dropping DHCP packet because can't find host for {}", descMac);
+ }
+ }
+ }
+
+ private DHCP addOption82(DHCP dhcpPacket, SubscriberAndDeviceInformation entry) {
+ log.debug("option82data {} ", entry);
+
+ List<DhcpOption> options = Lists.newArrayList(dhcpPacket.getOptions());
+ DhcpOption82 option82 = new DhcpOption82();
+ option82.setAgentCircuitId(entry.circuitId());
+ option82.setAgentRemoteId(entry.remoteId());
+ DhcpOption option = new DhcpOption()
+ .setCode(DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
+ .setData(option82.toByteArray())
+ .setLength(option82.length());
+
+ options.add(options.size() - 1, option);
+ dhcpPacket.setOptions(options);
+
+ return dhcpPacket;
+
+ }
+
+ private DHCP removeOption82(DHCP dhcpPacket) {
+ List<DhcpOption> options = dhcpPacket.getOptions();
+ List<DhcpOption> newoptions = options.stream()
+ .filter(option -> option.getCode() != DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
+ .collect(Collectors.toList());
+
+ return dhcpPacket.setOptions(newoptions);
+ }
+ /**
+ * Listener for network config events.
+ */
+ private class InternalConfigListener implements NetworkConfigListener {
+
+ @Override
+ public void event(NetworkConfigEvent event) {
+
+ if ((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
+ event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) &&
+ event.configClass().equals(DhcpL2RelayConfig.class)) {
+ updateConfig();
+ log.info("Reconfigured");
+ }
+ }
+ }
+
+ /**
+ * Handles Mastership changes for the devices which connect
+ * to the DHCP server.
+ */
+ private class InnerMastershipListener implements MastershipListener {
+ @Override
+ public void event(MastershipEvent event) {
+ if (!useOltUplink) {
+ if (dhcpServerConnectPoint.get() != null &&
+ dhcpServerConnectPoint.get().deviceId().
+ equals(event.subject())) {
+ log.trace("Mastership Event recevived for {}", event.subject());
+ // mastership of the device for our connect point has changed
+ // reselect
+ selectServerConnectPoint();
+ }
+ }
+ }
+ }
+
+ /**
+ * Handles Device status change for the devices which connect
+ * to the DHCP server.
+ */
+ private class InnerDeviceListener implements DeviceListener {
+ @Override
+ public void event(DeviceEvent event) {
+ if (log.isTraceEnabled() &&
+ !event.type().equals(DeviceEvent.Type.PORT_STATS_UPDATED)) {
+ log.trace("Device Event received for {} event {}",
+ event.subject(), event.type());
+ }
+ if (!useOltUplink) {
+ if (dhcpServerConnectPoint.get() == null) {
+ switch (event.type()) {
+ case DEVICE_ADDED:
+ case DEVICE_AVAILABILITY_CHANGED:
+ // some device is available check if we can get a
+ // connect point we can use
+ addOrRemoveDhcpTrapFromServer(true);
+ break;
+ default:
+ break;
+ }
+ return;
+ }
+ if (dhcpServerConnectPoint.get().deviceId().
+ equals(event.subject().id())) {
+ switch (event.type()) {
+ case DEVICE_AVAILABILITY_CHANGED:
+ case DEVICE_REMOVED:
+ case DEVICE_SUSPENDED:
+ // state of our device has changed, check if we need
+ // to re-select a connectpoint
+ addOrRemoveDhcpTrapFromServer(true);
+ break;
+ default:
+ break;
+ }
+ }
+ } else {
+ switch (event.type()) {
+ case PORT_ADDED:
+ if (useOltUplink && isUplinkPortOfOlt(event.subject().id(), event.port())) {
+ requestDhcpPacketsFromConnectPoint(
+ new ConnectPoint(event.subject().id(), event.port().number()),
+ null);
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayAllocationsCommand.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayAllocationsCommand.java
new file mode 100644
index 0000000..adb0bf0
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayAllocationsCommand.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2016-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl;
+
+import org.apache.karaf.shell.commands.Command;
+import org.onosproject.cli.AbstractShellCommand;
+
+/**
+ * Shows the Successful DHCP allocations relayed by the dhcpl2relay.
+ */
+@Command(scope = "onos", name = "dhcpl2relay-allocations",
+ description = "Shows the Successful DHCP allocations relayed by the dhcpl2relay")
+public class DhcpL2RelayAllocationsCommand extends AbstractShellCommand {
+ @Override
+ protected void execute() {
+ DhcpL2Relay.allocationMap().forEach((key, value) -> {
+ print("SubscriberId=%s,ConnectPoint=%s,State=%s,MAC=%s,CircuitId=%s" +
+ ",IP Allocated=%s,Allocation Timestamp=%s",
+ key, value.location(), value.type(), value.macAddress().toString(), value.circuitId(),
+ value.ipAddress().getIp4Address().toString(), value.allocationTime().toString());
+ });
+ }
+}
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayConfig.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayConfig.java
new file mode 100755
index 0000000..9a47ab3
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayConfig.java
@@ -0,0 +1,113 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.node.ArrayNode;
+
+import com.google.common.collect.ImmutableSet;
+
+import org.onosproject.core.ApplicationId;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.config.Config;
+
+import java.util.HashSet;
+import java.util.Set;
+
+
+/**
+ * DHCP Relay Config class.
+ */
+public class DhcpL2RelayConfig extends Config<ApplicationId> {
+
+ private static final String DHCP_CONNECT_POINTS = "dhcpServerConnectPoints";
+ private static final String MODIFY_SRC_DST_MAC = "modifyUlPacketsSrcDstMacAddresses";
+ private static final String USE_OLT_ULPORT_FOR_PKT_INOUT = "useOltUplinkForServerPktInOut";
+
+ private static final Boolean DEFAULT_MODIFY_SRC_DST_MAC = false;
+ private static final Boolean DEFAULT_USE_OLT_ULPORT_FOR_PKT_INOUT = false;
+
+ @Override
+ public boolean isValid() {
+
+ return hasOnlyFields(DHCP_CONNECT_POINTS, MODIFY_SRC_DST_MAC,
+ USE_OLT_ULPORT_FOR_PKT_INOUT);
+ }
+
+ /**
+ * Returns whether the app would use the uplink port of OLT for sending/receving
+ * messages to/from the server.
+ *
+ * @return true if OLT uplink port is to be used, false otherwise
+ */
+ public boolean getUseOltUplinkForServerPktInOut() {
+ if (object == null) {
+ return DEFAULT_USE_OLT_ULPORT_FOR_PKT_INOUT;
+ }
+ if (!object.has(USE_OLT_ULPORT_FOR_PKT_INOUT)) {
+ return DEFAULT_USE_OLT_ULPORT_FOR_PKT_INOUT;
+ }
+
+ return object.path(USE_OLT_ULPORT_FOR_PKT_INOUT).asBoolean();
+ }
+
+ /**
+ * Returns whether the app would modify MAC address of uplink packets.
+ *
+ * @return whether app would modify src and dst MAC addresses or not of packets
+ * sent to the DHCP server
+ */
+ public boolean getModifySrcDstMacAddresses() {
+ if (object == null) {
+ return DEFAULT_MODIFY_SRC_DST_MAC;
+ }
+ if (!object.has(MODIFY_SRC_DST_MAC)) {
+ return DEFAULT_MODIFY_SRC_DST_MAC;
+ }
+
+ return object.path(MODIFY_SRC_DST_MAC).asBoolean();
+ }
+
+ /**
+ * Returns the dhcp server connect points.
+ *
+ * @return dhcp server connect points
+ */
+ public Set<ConnectPoint> getDhcpServerConnectPoint() {
+ if (object == null) {
+ return new HashSet<ConnectPoint>();
+ }
+
+ if (!object.has(DHCP_CONNECT_POINTS)) {
+ return ImmutableSet.of();
+ }
+
+ ImmutableSet.Builder<ConnectPoint> builder = ImmutableSet.builder();
+ ArrayNode arrayNode = (ArrayNode) object.path(DHCP_CONNECT_POINTS);
+ for (JsonNode jsonNode : arrayNode) {
+ String portName = jsonNode.asText(null);
+ if (portName == null) {
+ return null;
+ }
+ try {
+ builder.add(ConnectPoint.deviceConnectPoint(portName));
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+ return builder.build();
+ }
+}
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/package-info.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/package-info.java
new file mode 100755
index 0000000..f5617d6
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.
+ */
+
+/**
+ * DHCP-L2RELAY application.
+ */
+package org.opencord.dhcpl2relay.impl;
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/DhcpOption82.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/DhcpOption82.java
new file mode 100644
index 0000000..bad55f9
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/DhcpOption82.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl.packet;
+
+import java.io.ByteArrayOutputStream;
+import java.nio.charset.StandardCharsets;
+
+/**
+ * Represents the DHCP Option 82 information. Currently only supports
+ * sub option 1 (agent-circuit-id) and 2 (agent=-relay-id).
+ */
+public class DhcpOption82 {
+
+ private String agentCircuitId = null;
+ private String agentRemoteId = null;
+
+ public DhcpOption82() {
+
+ }
+
+ public void setAgentCircuitId(String value) {
+ this.agentCircuitId = value;
+ }
+
+ /**
+ *
+ * @return agentCircuitId
+ */
+ public String getAgentCircuitId() {
+ return this.agentCircuitId;
+ }
+
+ /**
+ * sets AgentRemoteId.
+ * @param value Value to be set
+ */
+ public void setAgentRemoteId(String value) {
+ this.agentRemoteId = value;
+ }
+
+ /**
+ *
+ * @return agentRemoteId
+ */
+ public String getAgentRemoteId() {
+ return this.agentRemoteId;
+ }
+
+ /**
+ *
+ * @return length of option 82.
+ */
+ public byte length() {
+ int length = 0;
+
+ // +2 below for sub option ID and length of sub option
+ if (agentCircuitId != null) {
+ length += agentCircuitId.length() + 2;
+ }
+ if (agentRemoteId != null) {
+ length += agentRemoteId.length() + 2;
+ }
+ return (byte) length;
+ }
+
+ /**
+ * Returns the representation of the option 82 specification as a byte
+ * array.
+ * @return returns byte array
+ */
+ public byte[] toByteArray() {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+
+ // Add sub option if set
+ if (agentCircuitId != null) {
+ buf.write((byte) 1);
+ buf.write((byte) agentCircuitId.length());
+ byte[] bytes = agentCircuitId.getBytes(StandardCharsets.UTF_8);
+ buf.write(bytes, 0, bytes.length);
+ }
+
+ // Add sub option if set
+ if (agentRemoteId != null) {
+ buf.write((byte) 2);
+ buf.write((byte) agentRemoteId.length());
+ byte[] bytes = agentRemoteId.getBytes(StandardCharsets.UTF_8);
+ buf.write(bytes, 0, bytes.length);
+ }
+
+ return buf.toByteArray();
+ }
+
+}
diff --git a/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/package-info.java b/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/package-info.java
new file mode 100644
index 0000000..19362cd
--- /dev/null
+++ b/app/src/main/java/org/opencord/dhcpl2relay/impl/packet/package-info.java
@@ -0,0 +1,20 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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 lacd ..
+ * w 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.
+ */
+/**
+ * Utilities for decoding and encoding DHCP options.
+ */
+package org.opencord.dhcpl2relay.impl.packet;
diff --git a/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTest.java b/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTest.java
new file mode 100755
index 0000000..17fb417
--- /dev/null
+++ b/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTest.java
@@ -0,0 +1,433 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl;
+
+import static org.junit.Assert.assertEquals;
+
+import java.nio.ByteBuffer;
+import java.util.List;
+import java.util.Set;
+
+import org.easymock.EasyMock;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onlab.junit.TestUtils;
+import org.onlab.osgi.ComponentContextAdapter;
+import org.onlab.packet.ChassisId;
+import org.onlab.packet.DHCP;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.IpAddress;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.UDP;
+import org.onlab.packet.VlanId;
+import org.onlab.packet.dhcp.DhcpOption;
+import org.onosproject.cfg.ComponentConfigService;
+import org.onosproject.common.event.impl.TestEventDispatcher;
+import org.onosproject.mastership.MastershipServiceAdapter;
+import org.onosproject.net.AnnotationKeys;
+import org.onosproject.net.Annotations;
+import org.onosproject.net.ConnectPoint;
+import org.onosproject.net.DefaultAnnotations;
+import org.onosproject.net.DefaultDevice;
+import org.onosproject.net.DefaultHost;
+import org.onosproject.net.Device;
+import org.onosproject.net.DeviceId;
+import org.onosproject.net.Element;
+import org.onosproject.net.Host;
+import org.onosproject.net.HostId;
+import org.onosproject.net.HostLocation;
+import org.onosproject.net.Port;
+import org.onosproject.net.PortNumber;
+import org.onosproject.net.config.Config;
+import org.onosproject.net.config.NetworkConfigRegistryAdapter;
+import org.onosproject.net.device.DeviceServiceAdapter;
+import org.onosproject.net.flowobjective.FlowObjectiveServiceAdapter;
+import org.onosproject.net.host.HostServiceAdapter;
+import org.onosproject.net.provider.ProviderId;
+import org.opencord.dhcpl2relay.impl.packet.DhcpOption82;
+import org.opencord.sadis.SubscriberAndDeviceInformation;
+import org.opencord.sadis.BandwidthProfileInformation;
+import org.opencord.sadis.BaseInformationService;
+import org.opencord.sadis.SadisService;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.ImmutableSet;
+import com.google.common.collect.Lists;
+
+public class DhcpL2RelayTest extends DhcpL2RelayTestBase {
+
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ private DhcpL2Relay dhcpL2Relay;
+
+ private static final MacAddress CLIENT_MAC = MacAddress.valueOf("00:00:00:00:00:01");
+ private static final VlanId CLIENT_C_TAG = VlanId.vlanId((short) 999);
+ private static final VlanId CLIENT_S_TAG = VlanId.vlanId((short) 111);
+ private static final String CLIENT_NAS_PORT_ID = "PON 1/1";
+ private static final String CLIENT_CIRCUIT_ID = "CIR-PON 1/1";
+
+ private static final String OLT_DEV_ID = "of:00000000000000aa";
+ private static final MacAddress OLT_MAC_ADDRESS = MacAddress.valueOf("01:02:03:04:05:06");
+ private static final DeviceId DEVICE_ID_1 = DeviceId.deviceId(OLT_DEV_ID);
+
+ private static final ConnectPoint SERVER_CONNECT_POINT =
+ ConnectPoint.deviceConnectPoint("of:0000000000000001/5");
+
+ private static final String SCHEME_NAME = "dhcpl2relay";
+ private static final DefaultAnnotations DEVICE_ANNOTATIONS = DefaultAnnotations.builder()
+ .set(AnnotationKeys.PROTOCOL, SCHEME_NAME.toUpperCase()).build();
+
+ ComponentConfigService mockConfigService =
+ EasyMock.createMock(ComponentConfigService.class);
+
+ /**
+ * Sets up the services required by the dhcpl2relay app.
+ */
+ @Before
+ public void setUp() {
+ dhcpL2Relay = new DhcpL2Relay();
+ dhcpL2Relay.cfgService = new TestNetworkConfigRegistry();
+ dhcpL2Relay.coreService = new MockCoreServiceAdapter();
+ dhcpL2Relay.flowObjectiveService = new FlowObjectiveServiceAdapter();
+ dhcpL2Relay.packetService = new MockPacketService();
+ dhcpL2Relay.componentConfigService = mockConfigService;
+ dhcpL2Relay.deviceService = new MockDeviceService();
+ dhcpL2Relay.sadisService = new MockSadisService();
+ dhcpL2Relay.hostService = new MockHostService();
+ dhcpL2Relay.mastershipService = new MockMastershipService();
+ TestUtils.setField(dhcpL2Relay, "eventDispatcher", new TestEventDispatcher());
+ dhcpL2Relay.activate(new ComponentContextAdapter());
+ }
+
+ /**
+ * Tears down the dhcpL2Relay application.
+ */
+ @After
+ public void tearDown() {
+ dhcpL2Relay.deactivate();
+ }
+
+ /**
+ * Tests the DHCP relay app by sending DHCP discovery Packet.
+ *
+ * @throws Exception when an unhandled error occurs
+ */
+ @Test
+ public void testDhcpDiscover() throws Exception {
+ // (1) Sending DHCP discover packet
+ System.out.println("Sending pakcet");
+ Ethernet discoverPacket = constructDhcpDiscoverPacket(CLIENT_MAC);
+
+ sendPacket(discoverPacket, ConnectPoint.deviceConnectPoint(OLT_DEV_ID + "/" + 1));
+
+ Ethernet discoverRelayed = (Ethernet) getPacket();
+ compareClientPackets(discoverPacket, discoverRelayed);
+ }
+
+ /**
+ * Tests the DHCP relay app by sending DHCP Request Packet.
+ *
+ * @throws Exception when an unhandled error occurs
+ */
+ @Test
+ public void testDhcpRequest() throws Exception {
+ // (1) Sending DHCP discover packet
+ System.out.println("Sending pakcet");
+ Ethernet requestPacket = constructDhcpRequestPacket(CLIENT_MAC);
+
+ sendPacket(requestPacket, ConnectPoint.deviceConnectPoint(OLT_DEV_ID + "/" + 1));
+
+ Ethernet requestRelayed = (Ethernet) getPacket();
+ compareClientPackets(requestPacket, requestRelayed);
+ }
+
+ /**
+ * Tests the DHCP relay app by sending DHCP Offer Packet.
+ *
+ * @throws Exception when an unhandled error occurs
+ */
+ @Test
+ public void testDhcpOffer() {
+ // (1) Sending DHCP discover packet
+ System.out.println("Sending pakcet");
+ Ethernet offerPacket = constructDhcpOfferPacket(MacAddress.valueOf("bb:bb:bb:bb:bb:bb"),
+ CLIENT_MAC, "1.1.1.1", "2.2.2.2");
+
+ sendPacket(offerPacket, ConnectPoint.deviceConnectPoint(OLT_DEV_ID + "/" + 1));
+
+ Ethernet offerRelayed = (Ethernet) getPacket();
+ compareServerPackets(offerPacket, offerRelayed);
+ }
+
+ /**
+ * Tests the DHCP relay app by sending DHCP Ack Packet.
+ *
+ * @throws Exception when an unhandled error occurs
+ */
+ @Test
+ public void testDhcpAck() {
+
+ Ethernet ackPacket = constructDhcpAckPacket(MacAddress.valueOf("bb:bb:bb:bb:bb:bb"),
+ CLIENT_MAC, "1.1.1.1", "2.2.2.2");
+
+ sendPacket(ackPacket, ConnectPoint.deviceConnectPoint(OLT_DEV_ID + "/" + 1));
+
+ Ethernet ackRelayed = (Ethernet) getPacket();
+ compareServerPackets(ackPacket, ackRelayed);
+ }
+
+ public void compareClientPackets(Ethernet sent, Ethernet relayed) {
+ sent.setSourceMACAddress(OLT_MAC_ADDRESS);
+ sent.setQinQVID(CLIENT_S_TAG.toShort());
+ sent.setVlanID(CLIENT_C_TAG.toShort());
+
+ IPv4 ipv4Packet = (IPv4) sent.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ List<DhcpOption> options = Lists.newArrayList(dhcpPacket.getOptions());
+ DhcpOption82 option82 = new DhcpOption82();
+ option82.setAgentCircuitId(CLIENT_CIRCUIT_ID);
+
+ DhcpOption option = new DhcpOption()
+ .setCode(DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
+ .setData(option82.toByteArray())
+ .setLength(option82.length());
+
+ options.add(options.size() - 1, option);
+ dhcpPacket.setOptions(options);
+ assertEquals(sent, relayed);
+
+ }
+
+ public void compareServerPackets(Ethernet sent, Ethernet relayed) {
+ sent.setDestinationMACAddress(CLIENT_MAC);
+ sent.setQinQVID(CLIENT_S_TAG.toShort());
+ sent.setVlanID(CLIENT_C_TAG.toShort());
+
+ final ByteBuffer byteBuffer = ByteBuffer.wrap(sent.serialize());
+ Ethernet expectedPacket = null;
+ try {
+ expectedPacket = Ethernet.deserializer().deserialize(byteBuffer.array(),
+ 0, byteBuffer.array().length);
+ } catch (Exception e) {
+ }
+ assertEquals(expectedPacket, relayed);
+
+ }
+
+ private class MockDevice extends DefaultDevice {
+
+ public MockDevice(ProviderId providerId, DeviceId id, Type type,
+ String manufacturer, String hwVersion, String swVersion,
+ String serialNumber, ChassisId chassisId, Annotations... annotations) {
+ super(providerId, id, type, manufacturer, hwVersion, swVersion, serialNumber,
+ chassisId, annotations);
+ }
+ }
+
+ private class MockDeviceService extends DeviceServiceAdapter {
+
+ private ProviderId providerId = new ProviderId("of", "foo");
+ private final Device device1 = new MockDevice(providerId, DEVICE_ID_1, Device.Type.SWITCH,
+ "foo.inc", "0", "0", OLT_DEV_ID, new ChassisId(),
+ DEVICE_ANNOTATIONS);
+
+ @Override
+ public Device getDevice(DeviceId devId) {
+ return device1;
+
+ }
+
+ @Override
+ public Port getPort(ConnectPoint cp) {
+ return new MockPort();
+ }
+
+ @Override
+ public boolean isAvailable(DeviceId d) {
+ return true;
+ }
+ }
+
+ private class MockPort implements Port {
+
+ @Override
+ public boolean isEnabled() {
+ return true;
+ }
+ @Override
+ public long portSpeed() {
+ return 1000;
+ }
+ @Override
+ public Element element() {
+ return null;
+ }
+ @Override
+ public PortNumber number() {
+ return null;
+ }
+ @Override
+ public Annotations annotations() {
+ return new MockAnnotations();
+ }
+ @Override
+ public Type type() {
+ return Port.Type.FIBER;
+ }
+
+ private class MockAnnotations implements Annotations {
+
+ @Override
+ public String value(String val) {
+ return "PON 1/1";
+ }
+ @Override
+ public Set<String> keys() {
+ return null;
+ }
+ }
+ }
+
+ private class MockSadisService implements SadisService {
+ @Override
+ public BaseInformationService<SubscriberAndDeviceInformation> getSubscriberInfoService() {
+ return new MockSubService();
+ }
+
+ @Override
+ public BaseInformationService<BandwidthProfileInformation> getBandwidthProfileService() {
+ return null;
+ }
+ }
+
+ private class MockSubService implements BaseInformationService<SubscriberAndDeviceInformation> {
+ MockSubscriberAndDeviceInformation device =
+ new MockSubscriberAndDeviceInformation(OLT_DEV_ID, VlanId.NONE, VlanId.NONE, null, null,
+ OLT_MAC_ADDRESS, Ip4Address.valueOf("10.10.10.10"));
+ MockSubscriberAndDeviceInformation sub =
+ new MockSubscriberAndDeviceInformation(CLIENT_NAS_PORT_ID, CLIENT_C_TAG,
+ CLIENT_S_TAG, CLIENT_NAS_PORT_ID, CLIENT_CIRCUIT_ID, null, null);
+ @Override
+ public SubscriberAndDeviceInformation get(String id) {
+ if (id.equals(OLT_DEV_ID)) {
+ return device;
+ } else {
+ return sub;
+ }
+ }
+
+ @Override
+ public void invalidateAll() {}
+ @Override
+ public void invalidateId(String id) {}
+ @Override
+ public SubscriberAndDeviceInformation getfromCache(String id) {
+ return null;
+ }
+ }
+
+ private class MockMastershipService extends MastershipServiceAdapter {
+ @Override
+ public boolean isLocalMaster(DeviceId d) {
+ return true;
+ }
+ }
+
+ private class MockSubscriberAndDeviceInformation extends SubscriberAndDeviceInformation {
+
+ MockSubscriberAndDeviceInformation(String id, VlanId ctag,
+ VlanId stag, String nasPortId,
+ String circuitId, MacAddress hardId,
+ Ip4Address ipAddress) {
+ this.setCTag(ctag);
+ this.setHardwareIdentifier(hardId);
+ this.setId(id);
+ this.setIPAddress(ipAddress);
+ this.setSTag(stag);
+ this.setNasPortId(nasPortId);
+ this.setCircuitId(circuitId);
+ }
+ }
+
+ private class MockHostService extends HostServiceAdapter {
+
+ @Override
+ public Set<Host> getHostsByMac(MacAddress mac) {
+
+ HostLocation loc = new HostLocation(DEVICE_ID_1, PortNumber.portNumber(22), 0);
+
+ IpAddress ip = IpAddress.valueOf("10.100.200.10");
+
+ Host h = new DefaultHost(ProviderId.NONE, HostId.hostId(mac, VlanId.NONE),
+ mac, VlanId.NONE, loc, ImmutableSet.of(ip));
+
+ return ImmutableSet.of(h);
+ }
+ }
+
+
+ /**
+ * Mocks the AAAConfig class to force usage of an unroutable address for the
+ * RADIUS server.
+ */
+ static class MockDhcpL2RealyConfig extends DhcpL2RelayConfig {
+ @Override
+ public Set<ConnectPoint> getDhcpServerConnectPoint() {
+ return ImmutableSet.of(SERVER_CONNECT_POINT);
+ }
+
+ @Override
+ public boolean getModifySrcDstMacAddresses() {
+ return true;
+ }
+ }
+
+ /**
+ * Mocks the network config registry.
+ */
+ @SuppressWarnings("unchecked")
+ private static final class TestNetworkConfigRegistry
+ extends NetworkConfigRegistryAdapter {
+ @Override
+ public <S, C extends Config<S>> C getConfig(S subject, Class<C> configClass) {
+ DhcpL2RelayConfig dhcpConfig = new MockDhcpL2RealyConfig();
+ return (C) dhcpConfig;
+ }
+ }
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTestBase.java b/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTestBase.java
new file mode 100755
index 0000000..5318adc
--- /dev/null
+++ b/app/src/test/java/org/opencord/dhcpl2relay/impl/DhcpL2RelayTestBase.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright 2017-present Open Networking Foundation
+ *
+ * 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.opencord.dhcpl2relay.impl;
+
+import static org.junit.Assert.fail;
+
+import java.nio.ByteBuffer;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.LinkedList;
+import java.util.List;
+
+import org.onlab.packet.BasePacket;
+import org.onlab.packet.DHCP;
+import org.onlab.packet.DHCPPacketType;
+import org.onlab.packet.Ethernet;
+import org.onlab.packet.IPv4;
+import org.onlab.packet.Ip4Address;
+import org.onlab.packet.MacAddress;
+import org.onlab.packet.UDP;
+import org.onlab.packet.dhcp.DhcpOption;
+import org.onosproject.core.ApplicationId;
+import org.onosproject.core.CoreServiceAdapter;
+import org.onosproject.core.DefaultApplicationId;
+import org.onosproject.net.ConnectPoint;
+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.PacketContext;
+import org.onosproject.net.packet.PacketProcessor;
+import org.onosproject.net.packet.PacketServiceAdapter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+
+/**
+ * Common methods for AAA app testing.
+ */
+public class DhcpL2RelayTestBase {
+ private final Logger log = LoggerFactory.getLogger(getClass());
+
+ private static final int TRANSACTION_ID = 1000;
+
+ private static final String EXPECTED_IP = "10.2.0.2";
+
+ List<BasePacket> savedPackets = new LinkedList<>();
+ PacketProcessor packetProcessor;
+
+
+ /**
+ * Saves the given packet onto the saved packets list.
+ *
+ * @param packet packet to save
+ */
+ void savePacket(BasePacket packet) {
+ savedPackets.add(packet);
+ }
+
+ BasePacket getPacket() {
+ return savedPackets.remove(0);
+ }
+
+ /**
+ * Mock core service adaptor that provides an appId.
+ */
+ class MockCoreServiceAdapter extends CoreServiceAdapter {
+
+ @Override
+ public ApplicationId registerApplication(String name) {
+ return new DefaultApplicationId(10, name);
+ }
+ }
+
+ /**
+ * Keeps a reference to the PacketProcessor and saves the OutboundPackets.
+ */
+ class MockPacketService extends PacketServiceAdapter {
+
+ @Override
+ public void addProcessor(PacketProcessor processor, int priority) {
+ packetProcessor = processor;
+ }
+
+ @Override
+ public void emit(OutboundPacket packet) {
+ try {
+ Ethernet eth = Ethernet.deserializer().deserialize(packet.data().array(),
+ 0, packet.data().array().length);
+ savePacket(eth);
+ } catch (Exception e) {
+ fail(e.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Mocks the DefaultPacketContext.
+ */
+ final class TestPacketContext extends DefaultPacketContext {
+
+ private TestPacketContext(long time, InboundPacket inPkt,
+ OutboundPacket outPkt, boolean block) {
+ super(time, inPkt, outPkt, block);
+ }
+
+ @Override
+ public void send() {
+ // We don't send anything out.
+ }
+ }
+
+ /**
+ * Sends an Ethernet packet to the process method of the Packet Processor.
+ *
+ * @param pkt Ethernet packet
+ */
+ void sendPacket(Ethernet pkt, ConnectPoint cp) {
+ final ByteBuffer byteBuffer = ByteBuffer.wrap(pkt.serialize());
+ InboundPacket inPacket = new DefaultInboundPacket(cp, pkt, byteBuffer);
+
+ PacketContext context = new TestPacketContext(127L, inPacket, null, false);
+ packetProcessor.process(context);
+ }
+
+ /**
+ * Constructs an Ethernet packet with IP/UDP/DHCP payload.
+ *
+ * @return Ethernet packet
+ */
+ private Ethernet construcEthernetPacket(MacAddress srcMac, MacAddress dstMac,
+ String dstIp, byte dhcpReqRsp,
+ MacAddress clientHwAddress,
+ Ip4Address dhcpClientIpAddress) {
+ // Ethernet Frame.
+ Ethernet ethPkt = new Ethernet();
+ ethPkt.setSourceMACAddress(srcMac);
+ ethPkt.setDestinationMACAddress(dstMac);
+ ethPkt.setEtherType(Ethernet.TYPE_IPV4);
+ ethPkt.setVlanID((short) 2);
+ ethPkt.setPriorityCode((byte) 6);
+
+ // IP Packet
+ IPv4 ipv4Reply = new IPv4();
+ ipv4Reply.setSourceAddress(0);
+ ipv4Reply.setDestinationAddress(dstIp);
+
+ ipv4Reply.setTtl((byte) 127);
+
+ // UDP Datagram.
+ UDP udpReply = new UDP();
+ udpReply.setSourcePort((byte) UDP.DHCP_CLIENT_PORT);
+ udpReply.setDestinationPort((byte) UDP.DHCP_SERVER_PORT);
+
+ // DHCP Payload.
+ DHCP dhcpReply = new DHCP();
+ dhcpReply.setOpCode(dhcpReqRsp);
+
+ dhcpReply.setYourIPAddress(dhcpClientIpAddress.toInt());
+ dhcpReply.setServerIPAddress(0);
+
+ final byte[] serverNameBytes = new byte[64];
+ String result = new String(serverNameBytes, StandardCharsets.US_ASCII).trim();
+ dhcpReply.setServerName(result);
+
+ final byte[] bootFileBytes = new byte[128];
+ String result1 = new String(bootFileBytes, StandardCharsets.US_ASCII).trim();
+ dhcpReply.setBootFileName(result1);
+
+ dhcpReply.setTransactionId(TRANSACTION_ID);
+ dhcpReply.setClientHardwareAddress(clientHwAddress.toBytes());
+ dhcpReply.setHardwareType(DHCP.HWTYPE_ETHERNET);
+ dhcpReply.setHardwareAddressLength((byte) 6);
+
+ udpReply.setPayload(dhcpReply);
+ ipv4Reply.setPayload(udpReply);
+ ethPkt.setPayload(ipv4Reply);
+
+ return ethPkt;
+ }
+
+ /**
+ * Constructs DHCP Discover Packet.
+ *
+ * @return Ethernet packet
+ */
+ Ethernet constructDhcpDiscoverPacket(MacAddress clientMac) {
+
+ Ethernet pkt = construcEthernetPacket(clientMac, MacAddress.BROADCAST,
+ "255.255.255.255", DHCP.OPCODE_REQUEST, MacAddress.NONE,
+ Ip4Address.valueOf("0.0.0.0"));
+
+ IPv4 ipv4Packet = (IPv4) pkt.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ dhcpPacket.setOptions(constructDhcpOptions(DHCPPacketType.DHCPDISCOVER));
+
+ return pkt;
+ }
+
+ /**
+ * Constructs DHCP Request Packet.
+ *
+ * @return Ethernet packet
+ */
+ Ethernet constructDhcpRequestPacket(MacAddress clientMac) {
+
+ Ethernet pkt = construcEthernetPacket(clientMac, MacAddress.BROADCAST,
+ "255.255.255.255", DHCP.OPCODE_REQUEST, MacAddress.NONE,
+ Ip4Address.valueOf("0.0.0.0"));
+
+ IPv4 ipv4Packet = (IPv4) pkt.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ dhcpPacket.setOptions(constructDhcpOptions(DHCPPacketType.DHCPREQUEST));
+
+ return pkt;
+ }
+
+ /**
+ * Constructs DHCP Offer Packet.
+ *
+ * @return Ethernet packet
+ */
+ Ethernet constructDhcpOfferPacket(MacAddress servMac, MacAddress clientMac,
+ String ipAddress, String dhcpClientIpAddress) {
+
+ Ethernet pkt = construcEthernetPacket(servMac, clientMac, ipAddress, DHCP.OPCODE_REPLY,
+ clientMac, Ip4Address.valueOf(dhcpClientIpAddress));
+
+ IPv4 ipv4Packet = (IPv4) pkt.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ dhcpPacket.setOptions(constructDhcpOptions(DHCPPacketType.DHCPOFFER));
+
+ return pkt;
+ }
+
+ /**
+ * Constructs DHCP Ack Packet.
+ *
+ * @return Ethernet packet
+ */
+ Ethernet constructDhcpAckPacket(MacAddress servMac, MacAddress clientMac,
+ String ipAddress, String dhcpClientIpAddress) {
+
+ Ethernet pkt = construcEthernetPacket(servMac, clientMac, ipAddress, DHCP.OPCODE_REPLY,
+ clientMac, Ip4Address.valueOf(dhcpClientIpAddress));
+
+ IPv4 ipv4Packet = (IPv4) pkt.getPayload();
+ UDP udpPacket = (UDP) ipv4Packet.getPayload();
+ DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
+
+ dhcpPacket.setOptions(constructDhcpOptions(DHCPPacketType.DHCPACK));
+
+ return pkt;
+ }
+
+ /**
+ * Constructs DHCP Discover Options.
+ *
+ * @return Ethernet packet
+ */
+ private List<DhcpOption> constructDhcpOptions(DHCPPacketType packetType) {
+
+ // DHCP Options.
+ DhcpOption option = new DhcpOption();
+ List<DhcpOption> optionList = new ArrayList<>();
+
+
+ // DHCP Message Type.
+ option.setCode(DHCP.DHCPOptionCode.OptionCode_MessageType.getValue());
+ option.setLength((byte) 1);
+ byte[] optionData = {(byte) packetType.getValue()};
+ option.setData(optionData);
+ optionList.add(option);
+
+ // DHCP Requested IP.
+ option = new DhcpOption();
+ option.setCode(DHCP.DHCPOptionCode.OptionCode_RequestedIP.getValue());
+ option.setLength((byte) 4);
+ optionData = Ip4Address.valueOf(EXPECTED_IP).toOctets();
+ option.setData(optionData);
+ optionList.add(option);
+
+ // End Option.
+ option = new DhcpOption();
+ option.setCode(DHCP.DHCPOptionCode.OptionCode_END.getValue());
+ option.setLength((byte) 1);
+ optionList.add(option);
+
+ return optionList;
+ }
+}