blob: fdf9abbd210e55aa8c899b896e3d27f03d58aeb9 [file] [log] [blame]
Amit Ghosh47243cb2017-07-26 05:08:53 +01001/*
Deepa vaddireddy0060f532017-08-04 06:46:05 +00002 * Copyright 2017-present Open Networking Foundation
Amit Ghosh47243cb2017-07-26 05:08:53 +01003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Matteo Scandolo57af5d12019-04-29 17:11:41 -070016package org.opencord.dhcpl2relay.impl;
Amit Ghosh47243cb2017-07-26 05:08:53 +010017
Saurav Das15626a02018-09-27 18:36:45 -070018import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
19import static org.onlab.packet.MacAddress.valueOf;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030020import static org.onlab.util.Tools.get;
21import static org.onlab.util.Tools.getIntegerProperty;
Saurav Das15626a02018-09-27 18:36:45 -070022import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
23
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030024import java.io.ByteArrayOutputStream;
Saurav Das15626a02018-09-27 18:36:45 -070025import java.nio.ByteBuffer;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030026import java.util.AbstractMap;
Saurav Das15626a02018-09-27 18:36:45 -070027import java.util.ArrayList;
28import java.util.Arrays;
29import java.util.Dictionary;
30import java.util.List;
31import java.util.Map;
32import java.util.Optional;
33import java.util.Set;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030034import java.util.concurrent.Executors;
35import java.util.concurrent.atomic.AtomicLong;
Saurav Das15626a02018-09-27 18:36:45 -070036import java.util.concurrent.atomic.AtomicReference;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030037import java.util.concurrent.ScheduledExecutorService;
38import java.util.concurrent.ScheduledFuture;
39import java.util.concurrent.TimeUnit;
Saurav Das15626a02018-09-27 18:36:45 -070040import java.util.stream.Collectors;
41
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030042import org.apache.commons.io.HexDump;
Amit Ghosh47243cb2017-07-26 05:08:53 +010043import org.apache.felix.scr.annotations.Activate;
44import org.apache.felix.scr.annotations.Component;
45import org.apache.felix.scr.annotations.Deactivate;
46import org.apache.felix.scr.annotations.Modified;
47import org.apache.felix.scr.annotations.Property;
48import org.apache.felix.scr.annotations.Reference;
49import org.apache.felix.scr.annotations.ReferenceCardinality;
Jonathan Hartc36c9552018-07-31 15:07:53 -040050import org.apache.felix.scr.annotations.Service;
Amit Ghosh47243cb2017-07-26 05:08:53 +010051import org.onlab.packet.DHCP;
Amit Ghosh47243cb2017-07-26 05:08:53 +010052import org.onlab.packet.DHCPPacketType;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000053import org.onlab.packet.Ethernet;
Amit Ghosh47243cb2017-07-26 05:08:53 +010054import org.onlab.packet.IPv4;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053055import org.onlab.packet.IpAddress;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000056import org.onlab.packet.MacAddress;
Amit Ghosh47243cb2017-07-26 05:08:53 +010057import org.onlab.packet.TpPort;
58import org.onlab.packet.UDP;
59import org.onlab.packet.VlanId;
Jonathan Hartedbf6422018-05-02 17:30:05 -070060import org.onlab.packet.dhcp.DhcpOption;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -030061import org.onlab.util.SafeRecurringTask;
Amit Ghosh47243cb2017-07-26 05:08:53 +010062import org.onlab.util.Tools;
63import org.onosproject.cfg.ComponentConfigService;
64import org.onosproject.core.ApplicationId;
65import org.onosproject.core.CoreService;
Jonathan Hartc36c9552018-07-31 15:07:53 -040066import org.onosproject.event.AbstractListenerManager;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053067import org.onosproject.mastership.MastershipEvent;
68import org.onosproject.mastership.MastershipListener;
69import org.onosproject.mastership.MastershipService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010070import org.onosproject.net.AnnotationKeys;
71import org.onosproject.net.ConnectPoint;
Amit Ghosh83c8c892017-11-09 11:08:27 +000072import org.onosproject.net.Device;
73import org.onosproject.net.DeviceId;
Amit Ghosh47243cb2017-07-26 05:08:53 +010074import org.onosproject.net.Host;
75import org.onosproject.net.Port;
Amit Ghosh83c8c892017-11-09 11:08:27 +000076import org.onosproject.net.PortNumber;
Amit Ghosh47243cb2017-07-26 05:08:53 +010077import org.onosproject.net.config.ConfigFactory;
78import org.onosproject.net.config.NetworkConfigEvent;
79import org.onosproject.net.config.NetworkConfigListener;
80import org.onosproject.net.config.NetworkConfigRegistry;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053081import org.onosproject.net.device.DeviceEvent;
82import org.onosproject.net.device.DeviceListener;
Amit Ghosh47243cb2017-07-26 05:08:53 +010083import org.onosproject.net.device.DeviceService;
84import org.onosproject.net.flow.DefaultTrafficSelector;
85import org.onosproject.net.flow.DefaultTrafficTreatment;
86import org.onosproject.net.flow.TrafficSelector;
87import org.onosproject.net.flow.TrafficTreatment;
Saurav Dasb4e3e102018-10-02 15:31:17 -070088import org.onosproject.net.flowobjective.FlowObjectiveService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010089import org.onosproject.net.host.HostService;
90import org.onosproject.net.packet.DefaultOutboundPacket;
91import org.onosproject.net.packet.OutboundPacket;
92import org.onosproject.net.packet.PacketContext;
93import org.onosproject.net.packet.PacketPriority;
94import org.onosproject.net.packet.PacketProcessor;
95import org.onosproject.net.packet.PacketService;
Matteo Scandolo57af5d12019-04-29 17:11:41 -070096import org.opencord.dhcpl2relay.DhcpAllocationInfo;
97import org.opencord.dhcpl2relay.DhcpL2RelayEvent;
98import org.opencord.dhcpl2relay.DhcpL2RelayListener;
99import org.opencord.dhcpl2relay.DhcpL2RelayService;
100import org.opencord.dhcpl2relay.impl.packet.DhcpOption82;
Gamze Abakac806c6c2018-12-03 12:49:46 +0000101import org.opencord.sadis.BaseInformationService;
102import org.opencord.sadis.SadisService;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100103import org.opencord.sadis.SubscriberAndDeviceInformation;
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000104import org.opencord.sadis.UniTagInformation;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100105import org.osgi.service.component.ComponentContext;
106import org.slf4j.Logger;
107import org.slf4j.LoggerFactory;
108
Saurav Das15626a02018-09-27 18:36:45 -0700109import com.google.common.collect.ImmutableSet;
110import com.google.common.collect.Lists;
111import com.google.common.collect.Maps;
112import com.google.common.collect.Sets;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100113
114/**
115 * DHCP Relay Agent Application Component.
116 */
Jonathan Hartc36c9552018-07-31 15:07:53 -0400117@Service
Amit Ghosh47243cb2017-07-26 05:08:53 +0100118@Component(immediate = true)
Jonathan Hartc36c9552018-07-31 15:07:53 -0400119public class DhcpL2Relay
120 extends AbstractListenerManager<DhcpL2RelayEvent, DhcpL2RelayListener>
121 implements DhcpL2RelayService {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100122
123 public static final String DHCP_L2RELAY_APP = "org.opencord.dhcpl2relay";
Saurav Dasb4e3e102018-10-02 15:31:17 -0700124 private static final String HOST_LOC_PROVIDER =
125 "org.onosproject.provider.host.impl.HostLocationProvider";
Amit Ghosh47243cb2017-07-26 05:08:53 +0100126 private final Logger log = LoggerFactory.getLogger(getClass());
127 private final InternalConfigListener cfgListener =
128 new InternalConfigListener();
129
130 private final Set<ConfigFactory> factories = ImmutableSet.of(
131 new ConfigFactory<ApplicationId, DhcpL2RelayConfig>(APP_SUBJECT_FACTORY,
132 DhcpL2RelayConfig.class,
133 "dhcpl2relay") {
134 @Override
135 public DhcpL2RelayConfig createConfig() {
136 return new DhcpL2RelayConfig();
137 }
138 }
139 );
140
141 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
142 protected NetworkConfigRegistry cfgService;
143
144 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
145 protected CoreService coreService;
146
147 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
148 protected PacketService packetService;
149
150 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
151 protected HostService hostService;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
154 protected ComponentConfigService componentConfigService;
155
156 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Gamze Abakac806c6c2018-12-03 12:49:46 +0000157 protected SadisService sadisService;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100158
159 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
160 protected DeviceService deviceService;
161
Amit Ghosh8951f042017-08-10 13:48:10 +0100162 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
163 protected MastershipService mastershipService;
164
Saurav Dasb4e3e102018-10-02 15:31:17 -0700165 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
166 protected FlowObjectiveService flowObjectiveService;
167
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300168 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
169 protected DhcpL2RelayCountersStore dhcpL2RelayCounters;
170
171 protected PublishCountersToKafka publishCountersToKafka;
172
Amit Ghosh47243cb2017-07-26 05:08:53 +0100173 @Property(name = "option82", boolValue = true,
174 label = "Add option 82 to relayed packets")
175 protected boolean option82 = true;
176
Amit Ghosha17354e2017-08-23 12:56:04 +0100177 @Property(name = "enableDhcpBroadcastReplies", boolValue = false,
Amit Ghosh2095dc62017-09-25 20:56:55 +0100178 label = "Ask the DHCP Server to send back replies as L2 broadcast")
Amit Ghosha17354e2017-08-23 12:56:04 +0100179 protected boolean enableDhcpBroadcastReplies = false;
180
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300181 private static final int DEFAULT_RATE = 10;
182 @Property(name = "publishCountersRate", intValue = DEFAULT_RATE,
183 label = "The interval in seconds between calls to publish the DHCP counters to Kafka")
184 protected int publishCountersRate = 0;
185
186 ScheduledFuture<?> refreshTask;
187 ScheduledExecutorService refreshService = Executors.newSingleThreadScheduledExecutor();
188
189 private static final String DEFAULT_DHCP_COUNTERS_TOPIC = "onos_traffic.stats";
190 @Property(name = "dhcpCountersTopic", value = DEFAULT_DHCP_COUNTERS_TOPIC,
191 label = "The topic where to publish the DHCP L2 Relay counters to Kafka")
192 private String dhcpCountersTopic = DEFAULT_DHCP_COUNTERS_TOPIC;
193
Amit Ghosh47243cb2017-07-26 05:08:53 +0100194 private DhcpRelayPacketProcessor dhcpRelayPacketProcessor =
195 new DhcpRelayPacketProcessor();
196
Amit Ghosh8951f042017-08-10 13:48:10 +0100197 private InnerMastershipListener changeListener = new InnerMastershipListener();
198 private InnerDeviceListener deviceListener = new InnerDeviceListener();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100199
Amit Ghosh8951f042017-08-10 13:48:10 +0100200 // connect points to the DHCP server
201 Set<ConnectPoint> dhcpConnectPoints;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300202 protected AtomicReference<ConnectPoint> dhcpServerConnectPoint = new AtomicReference<>();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100203 private MacAddress dhcpConnectMac = MacAddress.BROADCAST;
204 private ApplicationId appId;
205
Amit Ghosha17354e2017-08-23 12:56:04 +0100206 static Map<String, DhcpAllocationInfo> allocationMap = Maps.newConcurrentMap();
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300207 protected boolean modifyClientPktsSrcDstMac = false;
Amit Ghosh83c8c892017-11-09 11:08:27 +0000208 //Whether to use the uplink port of the OLTs to send/receive messages to the DHCP server
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300209 protected boolean useOltUplink = false;
Amit Ghosha17354e2017-08-23 12:56:04 +0100210
Gamze Abakac806c6c2018-12-03 12:49:46 +0000211 private BaseInformationService<SubscriberAndDeviceInformation> subsService;
212
Amit Ghosh47243cb2017-07-26 05:08:53 +0100213 @Activate
214 protected void activate(ComponentContext context) {
215 //start the dhcp relay agent
216 appId = coreService.registerApplication(DHCP_L2RELAY_APP);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700217 // ensure that host-learning via dhcp includes IP addresses
218 componentConfigService.preSetProperty(HOST_LOC_PROVIDER,
219 "useDhcp", Boolean.TRUE.toString());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100220 componentConfigService.registerProperties(getClass());
Jonathan Hartc36c9552018-07-31 15:07:53 -0400221 eventDispatcher.addSink(DhcpL2RelayEvent.class, listenerRegistry);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100222
223 cfgService.addListener(cfgListener);
Amit Ghosh8951f042017-08-10 13:48:10 +0100224 mastershipService.addListener(changeListener);
225 deviceService.addListener(deviceListener);
226
Matteo Scandolof8da6572019-09-30 09:30:32 -0700227 subsService = sadisService.getSubscriberInfoService();
228
Amit Ghosh47243cb2017-07-26 05:08:53 +0100229 factories.forEach(cfgService::registerConfigFactory);
230 //update the dhcp server configuration.
231 updateConfig();
232 //add the packet services.
233 packetService.addProcessor(dhcpRelayPacketProcessor,
234 PacketProcessor.director(0));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000235 if (context != null) {
236 modified(context);
237 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100238
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300239 publishCountersToKafka = new PublishCountersToKafka();
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300240 restartPublishCountersTask();
Gamze Abakac806c6c2018-12-03 12:49:46 +0000241
Amit Ghosh47243cb2017-07-26 05:08:53 +0100242 log.info("DHCP-L2-RELAY Started");
243 }
244
245 @Deactivate
246 protected void deactivate() {
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300247 if (refreshTask != null) {
248 refreshTask.cancel(true);
249 }
250 if (refreshService != null) {
251 refreshService.shutdownNow();
252 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100253 cfgService.removeListener(cfgListener);
254 factories.forEach(cfgService::unregisterConfigFactory);
255 packetService.removeProcessor(dhcpRelayPacketProcessor);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700256 cancelDhcpPktsFromServer();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100257
258 componentConfigService.unregisterProperties(getClass(), false);
Deepa Vaddireddy77a6ac72017-09-20 20:36:52 +0530259 deviceService.removeListener(deviceListener);
260 mastershipService.removeListener(changeListener);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400261 eventDispatcher.removeSink(DhcpL2RelayEvent.class);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100262 log.info("DHCP-L2-RELAY Stopped");
263 }
264
265 @Modified
266 protected void modified(ComponentContext context) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000267
Amit Ghosh47243cb2017-07-26 05:08:53 +0100268 Dictionary<?, ?> properties = context.getProperties();
269
270 Boolean o = Tools.isPropertyEnabled(properties, "option82");
271 if (o != null) {
272 option82 = o;
273 }
Amit Ghosh2095dc62017-09-25 20:56:55 +0100274
275 o = Tools.isPropertyEnabled(properties, "enableDhcpBroadcastReplies");
276 if (o != null) {
277 enableDhcpBroadcastReplies = o;
278 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300279
280 Integer newPublishCountersRate = getIntegerProperty(properties, "publishCountersRate");
281 if (newPublishCountersRate != null) {
282 if (newPublishCountersRate != publishCountersRate && newPublishCountersRate >= 0) {
283 log.info("publishCountersRate modified from {} to {}", publishCountersRate, newPublishCountersRate);
284 publishCountersRate = newPublishCountersRate;
285 } else if (newPublishCountersRate < 0) {
286 log.error("Invalid newPublishCountersRate : {}, defaulting to 0", newPublishCountersRate);
287 publishCountersRate = 0;
288 }
289 restartPublishCountersTask();
290 }
291
292 String newDhcpCountersTopic = get(properties, "dhcpCountersTopic");
293 if (newDhcpCountersTopic != null && !newDhcpCountersTopic.equals(dhcpCountersTopic)) {
294 log.info("Property dhcpCountersTopic modified from {} to {}", dhcpCountersTopic, newDhcpCountersTopic);
295 dhcpCountersTopic = newDhcpCountersTopic;
296 }
297 }
298
299 /**
300 * Starts a thread to publish the counters to kafka at a certain rate time.
301 */
302 private void restartPublishCountersTask() {
303 if (refreshTask != null) {
304 refreshTask.cancel(true);
305 }
306 if (publishCountersRate > 0) {
307 log.info("Refresh Rate set to {}, publishCountersToKafka will be called every {} seconds",
308 publishCountersRate, publishCountersRate);
309 refreshTask = refreshService.scheduleWithFixedDelay(SafeRecurringTask.wrap(publishCountersToKafka),
310 publishCountersRate, publishCountersRate, TimeUnit.SECONDS);
311 } else {
312 log.info("Refresh Rate set to 0, disabling calls to publishCountersToKafka");
313 }
314 }
315
316 /**
317 * Publish the counters to kafka.
318 */
319 private class PublishCountersToKafka implements Runnable {
320 public void run() {
321 dhcpL2RelayCounters.getCountersMap().forEach((counterKey, counterValue) -> {
322 // Publish the global counters
323 if (counterKey.counterClassKey.equals(DhcpL2RelayCountersIdentifier.GLOBAL_COUNTER)) {
324 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.STATS_UPDATE, null, null,
325 new AbstractMap.SimpleEntry<String, AtomicLong>(counterKey.counterTypeKey.toString(),
326 counterValue), dhcpCountersTopic, null));
327 } else { // Publish the counters per subscriber
328 DhcpAllocationInfo info = allocationMap.get(counterKey.counterClassKey);
329 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.STATS_UPDATE, info, null,
330 new AbstractMap.SimpleEntry<String, AtomicLong>(counterKey.counterTypeKey.toString(),
331 counterValue), dhcpCountersTopic, counterKey.counterClassKey));
332 }
333 });
334 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100335 }
336
337 /**
338 * Checks if this app has been configured.
339 *
340 * @return true if all information we need have been initialized
341 */
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300342 protected boolean configured() {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000343 if (!useOltUplink) {
344 return dhcpServerConnectPoint.get() != null;
345 }
346 return true;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100347 }
348
Amit Ghosh8951f042017-08-10 13:48:10 +0100349 /**
350 * Selects a connect point through an available device for which it is the master.
351 */
352 private void selectServerConnectPoint() {
353 synchronized (this) {
354 dhcpServerConnectPoint.set(null);
355 if (dhcpConnectPoints != null) {
356 // find a connect point through a device for which we are master
357 for (ConnectPoint cp: dhcpConnectPoints) {
358 if (mastershipService.isLocalMaster(cp.deviceId())) {
359 if (deviceService.isAvailable(cp.deviceId())) {
360 dhcpServerConnectPoint.set(cp);
361 }
362 log.info("DHCP connectPoint selected is {}", cp);
363 break;
364 }
365 }
366 }
367
368 log.info("DHCP Server connectPoint is {}", dhcpServerConnectPoint.get());
369
370 if (dhcpServerConnectPoint.get() == null) {
371 log.error("Master of none, can't relay DHCP Message to server");
372 }
373 }
374 }
375
376 /**
377 * Updates the network configuration.
378 */
Amit Ghosh47243cb2017-07-26 05:08:53 +0100379 private void updateConfig() {
380 DhcpL2RelayConfig cfg = cfgService.getConfig(appId, DhcpL2RelayConfig.class);
381 if (cfg == null) {
382 log.warn("Dhcp Server info not available");
383 return;
384 }
Amit Ghosh8951f042017-08-10 13:48:10 +0100385
386 dhcpConnectPoints = Sets.newConcurrentHashSet(cfg.getDhcpServerConnectPoint());
Amit Ghosh83c8c892017-11-09 11:08:27 +0000387 modifyClientPktsSrcDstMac = cfg.getModifySrcDstMacAddresses();
Saurav Dasb4e3e102018-10-02 15:31:17 -0700388 boolean prevUseOltUplink = useOltUplink;
Amit Ghosh83c8c892017-11-09 11:08:27 +0000389 useOltUplink = cfg.getUseOltUplinkForServerPktInOut();
Amit Ghosh8951f042017-08-10 13:48:10 +0100390
Saurav Dasb4e3e102018-10-02 15:31:17 -0700391 if (useOltUplink) {
392 for (ConnectPoint cp : getUplinkPortsOfOlts()) {
393 log.debug("requestDhcpPackets: ConnectPoint: {}", cp);
Matteo Scandolof8da6572019-09-30 09:30:32 -0700394 requestDhcpPacketsFromConnectPoint(cp, Optional.ofNullable(null));
Saurav Dasb4e3e102018-10-02 15:31:17 -0700395 }
396 // check if previous config was different and so trap flows may
Saurav Dasb14f08a2019-02-22 16:34:15 -0800397 // need to be removed from other places like AGG switches
Saurav Dasb4e3e102018-10-02 15:31:17 -0700398 if (!prevUseOltUplink) {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800399 addOrRemoveDhcpTrapFromServer(false);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700400 }
Saurav Dasb4e3e102018-10-02 15:31:17 -0700401 } else {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800402 // uplink on AGG switch
403 addOrRemoveDhcpTrapFromServer(true);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700404 }
405 }
406
407 private void cancelDhcpPktsFromServer() {
408 if (useOltUplink) {
409 for (ConnectPoint cp : getUplinkPortsOfOlts()) {
410 log.debug("cancelDhcpPackets: ConnectPoint: {}", cp);
Matteo Scandolof8da6572019-09-30 09:30:32 -0700411 cancelDhcpPacketsFromConnectPoint(cp, Optional.ofNullable(null));
Saurav Dasb4e3e102018-10-02 15:31:17 -0700412 }
413 } else {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800414 // uplink on AGG switch
415 addOrRemoveDhcpTrapFromServer(false);
Amit Ghosh83c8c892017-11-09 11:08:27 +0000416 }
Saurav Dasb4e3e102018-10-02 15:31:17 -0700417 }
418
Saurav Dasb14f08a2019-02-22 16:34:15 -0800419 /**
420 * Used to add or remove DHCP trap flow for packets received from DHCP server.
421 * Typically used on a non OLT device, like an AGG switch. When adding, a
422 * new dhcp server connect point is selected from the configured options.
423 *
424 * @param add true if dhcp trap flow is to be added, false to remove the
425 * trap flow
426 */
427 private void addOrRemoveDhcpTrapFromServer(boolean add) {
428 if (add) {
429 selectServerConnectPoint();
430 log.debug("dhcp server connect point: " + dhcpServerConnectPoint);
431 }
432 if (dhcpServerConnectPoint.get() == null) {
433 log.warn("No dhcpServer connectPoint found, cannot {} dhcp trap flows",
434 (add) ? "install" : "remove");
435 return;
436 }
437 if (add) {
438 log.info("Adding trap to dhcp server connect point: "
439 + dhcpServerConnectPoint);
440 requestDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
441 Optional.of(PacketPriority.HIGH1));
442 } else {
443 log.info("Removing trap from dhcp server connect point: "
444 + dhcpServerConnectPoint);
445 cancelDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
446 Optional.of(PacketPriority.HIGH1));
447 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100448 }
449
450 /**
Amit Ghosh83c8c892017-11-09 11:08:27 +0000451 * Returns all the uplink ports of OLTs configured in SADIS.
452 * Only ports visible in ONOS and for which this instance is master
453 * are returned
454 */
455 private List<ConnectPoint> getUplinkPortsOfOlts() {
456 List<ConnectPoint> cps = new ArrayList<>();
457
458 // find all the olt devices and if their uplink ports are visible
459 Iterable<Device> devices = deviceService.getDevices();
460 for (Device d : devices) {
461 // check if this device is provisioned in Sadis
462
463 log.debug("getUplinkPortsOfOlts: Checking mastership of {}", d);
464 // do only for devices for which we are the master
465 if (!mastershipService.isLocalMaster(d.id())) {
466 continue;
467 }
468
469 String devSerialNo = d.serialNumber();
470 SubscriberAndDeviceInformation deviceInfo = subsService.get(devSerialNo);
471 log.debug("getUplinkPortsOfOlts: Found device: {}", deviceInfo);
472 if (deviceInfo != null) {
473 // check if the uplink port with that number is available on the device
474 PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
475 Port port = deviceService.getPort(d.id(), pNum);
476 log.debug("getUplinkPortsOfOlts: Found port: {}", port);
477 if (port != null) {
478 cps.add(new ConnectPoint(d.id(), pNum));
479 }
480 }
481 }
482 return cps;
483 }
484
485 /**
486 * Returns whether the passed port is the uplink port of the olt device.
487 */
488 private boolean isUplinkPortOfOlt(DeviceId dId, Port p) {
489 log.debug("isUplinkPortOfOlt: DeviceId: {} Port: {}", dId, p);
490 // do only for devices for which we are the master
491 if (!mastershipService.isLocalMaster(dId)) {
492 return false;
493 }
494
495 Device d = deviceService.getDevice(dId);
496 SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
497
498 if (deviceInfo != null) {
499 return (deviceInfo.uplinkPort() == p.number().toLong());
500 }
501
502 return false;
503 }
504
505 /**
506 * Returns the connectPoint which is the uplink port of the OLT.
507 */
508 private ConnectPoint getUplinkConnectPointOfOlt(DeviceId dId) {
509
510 Device d = deviceService.getDevice(dId);
511 SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
512 log.debug("getUplinkConnectPointOfOlt DeviceId: {} devInfo: {}", dId, deviceInfo);
513 if (deviceInfo != null) {
514 PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
515 Port port = deviceService.getPort(d.id(), pNum);
516 if (port != null) {
517 return new ConnectPoint(d.id(), pNum);
518 }
519 }
520
521 return null;
522 }
523
524 /**
525 * Request DHCP packet from particular connect point via PacketService.
Saurav Dasb14f08a2019-02-22 16:34:15 -0800526 * Optionally provide a priority for the trap flow. If no such priority is
527 * provided, the default priority will be used.
528 *
529 * @param cp the connect point to trap dhcp packets from
530 * @param priority of the trap flow, null to use default priority
Amit Ghosh83c8c892017-11-09 11:08:27 +0000531 */
Saurav Dasb14f08a2019-02-22 16:34:15 -0800532 private void requestDhcpPacketsFromConnectPoint(ConnectPoint cp,
533 Optional<PacketPriority> priority) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000534 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
535 .matchEthType(Ethernet.TYPE_IPV4)
536 .matchInPort(cp.port())
537 .matchIPProtocol(IPv4.PROTOCOL_UDP)
538 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
539 packetService.requestPackets(selectorServer.build(),
Saurav Dasb14f08a2019-02-22 16:34:15 -0800540 priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
541 appId, Optional.of(cp.deviceId()));
Amit Ghosh83c8c892017-11-09 11:08:27 +0000542 }
543
544 /**
Saurav Dasb14f08a2019-02-22 16:34:15 -0800545 * Cancel DHCP packet from particular connect point via PacketService. If
546 * the request was made with a specific packet priority, then the same
547 * priority should be used in this call.
548 *
549 * @param cp the connect point for the trap flow
550 * @param priority with which the trap flow was requested; if request
551 * priority was not specified, this param should also be null
Amit Ghosh83c8c892017-11-09 11:08:27 +0000552 */
Saurav Dasb14f08a2019-02-22 16:34:15 -0800553 private void cancelDhcpPacketsFromConnectPoint(ConnectPoint cp,
554 Optional<PacketPriority> priority) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000555 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
556 .matchEthType(Ethernet.TYPE_IPV4)
557 .matchInPort(cp.port())
558 .matchIPProtocol(IPv4.PROTOCOL_UDP)
559 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
560 packetService.cancelPackets(selectorServer.build(),
Saurav Dasb14f08a2019-02-22 16:34:15 -0800561 priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
562 appId, Optional.of(cp.deviceId()));
Amit Ghosh83c8c892017-11-09 11:08:27 +0000563 }
564
Amit Ghosha17354e2017-08-23 12:56:04 +0100565 public static Map<String, DhcpAllocationInfo> allocationMap() {
566 return allocationMap;
567 }
568
Amit Ghosh47243cb2017-07-26 05:08:53 +0100569 private SubscriberAndDeviceInformation getDevice(PacketContext context) {
570 String serialNo = deviceService.getDevice(context.inPacket().
571 receivedFrom().deviceId()).serialNumber();
572
573 return subsService.get(serialNo);
574 }
575
Amit Ghosh47243cb2017-07-26 05:08:53 +0100576 private MacAddress relayAgentMacAddress(PacketContext context) {
577
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000578 SubscriberAndDeviceInformation device = this.getDevice(context);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100579 if (device == null) {
580 log.warn("Device not found for {}", context.inPacket().
581 receivedFrom());
582 return null;
583 }
584
585 return device.hardwareIdentifier();
586 }
587
588 private String nasPortId(PacketContext context) {
Amit Ghosh8951f042017-08-10 13:48:10 +0100589 return nasPortId(context.inPacket().receivedFrom());
590 }
591
592 private String nasPortId(ConnectPoint cp) {
593 Port p = deviceService.getPort(cp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100594 return p.annotations().value(AnnotationKeys.PORT_NAME);
595 }
596
597 private SubscriberAndDeviceInformation getSubscriber(PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100598 return subsService.get(nasPortId(context));
599 }
600
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000601 private UniTagInformation getUnitagInformationFromPacketContext(PacketContext context,
602 SubscriberAndDeviceInformation sub) {
603 //If the ctag is defined in the tagList and dhcp is required, return the service info
604 List<UniTagInformation> tagList = sub.uniTagList();
605 for (UniTagInformation uniServiceInformation : tagList) {
606 if (uniServiceInformation.getPonCTag().toShort() == context.inPacket().parsed().getVlanID()) {
607 if (uniServiceInformation.getIsDhcpRequired()) {
608 return uniServiceInformation;
609 }
610 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100611 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100612
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000613 return null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100614 }
615
616 private class DhcpRelayPacketProcessor implements PacketProcessor {
617
618 @Override
619 public void process(PacketContext context) {
620 if (!configured()) {
621 log.warn("Missing DHCP relay config. Abort packet processing");
622 return;
623 }
624
625 // process the packet and get the payload
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530626 Ethernet packet = context.inPacket().parsed();
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000627
Amit Ghosh47243cb2017-07-26 05:08:53 +0100628 if (packet == null) {
629 log.warn("Packet is null");
630 return;
631 }
632
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530633 if (packet.getEtherType() == Ethernet.TYPE_IPV4) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100634 IPv4 ipv4Packet = (IPv4) packet.getPayload();
635
636 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_UDP) {
637 UDP udpPacket = (UDP) ipv4Packet.getPayload();
638 if (udpPacket.getSourcePort() == UDP.DHCP_CLIENT_PORT ||
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000639 udpPacket.getSourcePort() == UDP.DHCP_SERVER_PORT) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100640 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
641 //This packet is dhcp.
642 processDhcpPacket(context, packet, dhcpPayload);
643 }
644 }
645 }
646 }
647
648 //forward the packet to ConnectPoint where the DHCP server is attached.
Amit Ghosh83c8c892017-11-09 11:08:27 +0000649 private void forwardPacket(Ethernet packet, PacketContext context) {
650 ConnectPoint toSendTo = null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100651
Amit Ghosh83c8c892017-11-09 11:08:27 +0000652 if (!useOltUplink) {
653 toSendTo = dhcpServerConnectPoint.get();
654 } else {
655 toSendTo = getUplinkConnectPointOfOlt(context.inPacket().
656 receivedFrom().deviceId());
657 }
658
659 if (toSendTo != null) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100660 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosh83c8c892017-11-09 11:08:27 +0000661 .setOutput(toSendTo.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100662 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosh83c8c892017-11-09 11:08:27 +0000663 toSendTo.deviceId(), t,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100664 ByteBuffer.wrap(packet.serialize()));
665 if (log.isTraceEnabled()) {
Saurav Das15626a02018-09-27 18:36:45 -0700666 log.trace("Relaying packet to dhcp server at {} {}",
667 toSendTo, packet);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100668 }
669 packetService.emit(o);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300670
671 SubscriberAndDeviceInformation entry = getSubscriberInfoFromClient(context);
672 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_TO_SERVER"));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100673 } else {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000674 log.error("No connect point to send msg to DHCP Server");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100675 }
676 }
677
Amit Ghosha17354e2017-08-23 12:56:04 +0100678 // get the type of the DHCP packet
679 private DHCPPacketType getDhcpPacketType(DHCP dhcpPayload) {
680
Jonathan Hartedbf6422018-05-02 17:30:05 -0700681 for (DhcpOption option : dhcpPayload.getOptions()) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100682 if (option.getCode() == OptionCode_MessageType.getValue()) {
683 byte[] data = option.getData();
684 return DHCPPacketType.getType(data[0]);
685 }
686 }
687 return null;
688 }
689
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300690 private void updateDhcpRelayCountersStore(SubscriberAndDeviceInformation entry,
691 DhcpL2RelayCounters counterType) {
692 // Update global counter stats
693 dhcpL2RelayCounters.incrementCounter(DhcpL2RelayCountersIdentifier.GLOBAL_COUNTER, counterType);
694 if (entry == null) {
695 log.warn("Counter not updated as subscriber info not found.");
696 } else {
697 // Update subscriber counter stats
698 dhcpL2RelayCounters.incrementCounter(entry.id(), counterType);
699 }
700 }
701
702 /*
703 * Get subscriber information based on it's context packet.
704 */
705 private SubscriberAndDeviceInformation getSubscriberInfoFromClient(PacketContext context) {
706 if (context != null) {
707 return getSubscriber(context);
708 }
709 return null;
710 }
711
712 /*
713 * Get subscriber information based on it's DHCP payload.
714 */
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000715 private SubscriberAndDeviceInformation getSubscriberInfoFromServer(DHCP dhcpPayload, PacketContext context) {
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300716 if (dhcpPayload != null) {
717 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000718 ConnectPoint subsCp = getConnectPointOfClient(descMac, context);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300719
720 if (subsCp != null) {
721 String portId = nasPortId(subsCp);
722 return subsService.get(portId);
723 }
724 }
725 return null;
726 }
727
Amit Ghosh47243cb2017-07-26 05:08:53 +0100728 //process the dhcp packet before sending to server
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530729 private void processDhcpPacket(PacketContext context, Ethernet packet,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100730 DHCP dhcpPayload) {
731 if (dhcpPayload == null) {
732 log.warn("DHCP payload is null");
733 return;
734 }
735
Amit Ghosha17354e2017-08-23 12:56:04 +0100736 DHCPPacketType incomingPacketType = getDhcpPacketType(dhcpPayload);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300737 if (incomingPacketType == null) {
738 log.warn("DHCP packet type not found. Dump of ethernet pkt in hex format for troubleshooting.");
739 byte[] array = packet.serialize();
740 ByteArrayOutputStream buf = new ByteArrayOutputStream();
741 try {
742 HexDump.dump(array, 0, buf, 0);
743 log.trace(buf.toString());
744 } catch (Exception e) { }
745 return;
746 }
747
748 SubscriberAndDeviceInformation entry = null;
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000749
Saurav Das15626a02018-09-27 18:36:45 -0700750 log.info("Received DHCP Packet of type {} from {}",
751 incomingPacketType, context.inPacket().receivedFrom());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100752
753 switch (incomingPacketType) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000754 case DHCPDISCOVER:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530755 Ethernet ethernetPacketDiscover =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000756 processDhcpPacketFromClient(context, packet);
757 if (ethernetPacketDiscover != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000758 forwardPacket(ethernetPacketDiscover, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000759 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300760 entry = getSubscriberInfoFromClient(context);
761 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDISCOVER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000762 break;
763 case DHCPOFFER:
764 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700765 Ethernet ethernetPacketOffer =
766 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000767 if (ethernetPacketOffer != null) {
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000768 sendReply(ethernetPacketOffer, dhcpPayload, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000769 }
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000770 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300771 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPOFFER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000772 break;
773 case DHCPREQUEST:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530774 Ethernet ethernetPacketRequest =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000775 processDhcpPacketFromClient(context, packet);
776 if (ethernetPacketRequest != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000777 forwardPacket(ethernetPacketRequest, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000778 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300779 entry = getSubscriberInfoFromClient(context);
780 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPREQUEST"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000781 break;
782 case DHCPACK:
783 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700784 Ethernet ethernetPacketAck =
785 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000786 if (ethernetPacketAck != null) {
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000787 sendReply(ethernetPacketAck, dhcpPayload, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000788 }
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000789 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300790 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPACK"));
791 break;
792 case DHCPDECLINE:
793 entry = getSubscriberInfoFromClient(context);
794 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDECLINE"));
795 break;
796 case DHCPNAK:
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000797 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300798 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPNACK"));
799 break;
800 case DHCPRELEASE:
801 entry = getSubscriberInfoFromClient(context);
802 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPRELEASE"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000803 break;
804 default:
805 break;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100806 }
807 }
808
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530809 private Ethernet processDhcpPacketFromClient(PacketContext context,
810 Ethernet ethernetPacket) {
Saurav Das15626a02018-09-27 18:36:45 -0700811 if (log.isTraceEnabled()) {
812 log.trace("DHCP packet received from client at {} {}",
813 context.inPacket().receivedFrom(), ethernetPacket);
814 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100815
816 MacAddress relayAgentMac = relayAgentMacAddress(context);
817 if (relayAgentMac == null) {
818 log.warn("RelayAgent MAC not found ");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100819 return null;
820 }
821
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530822 Ethernet etherReply = ethernetPacket;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100823
824 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
825 UDP udpPacket = (UDP) ipv4Packet.getPayload();
826 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
827
Amit Ghosha17354e2017-08-23 12:56:04 +0100828 if (enableDhcpBroadcastReplies) {
829 // We want the reply to come back as a L2 broadcast
830 dhcpPacket.setFlags((short) 0x8000);
831 }
832
Jonathan Hartc36c9552018-07-31 15:07:53 -0400833 MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
834 IpAddress clientIp = IpAddress.valueOf(dhcpPacket.getClientIPAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100835
Jonathan Hartc36c9552018-07-31 15:07:53 -0400836 SubscriberAndDeviceInformation entry = getSubscriber(context);
837 if (entry == null) {
Saurav Das15626a02018-09-27 18:36:45 -0700838 log.warn("Dropping packet as subscriber entry is not available");
Jonathan Hartc36c9552018-07-31 15:07:53 -0400839 return null;
840 }
841
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000842 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, entry);
843 if (uniTagInformation == null) {
844 log.warn("Missing service information for connectPoint {} / cTag {}",
845 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
846 return null;
847 }
848
849
Jonathan Hartc36c9552018-07-31 15:07:53 -0400850 DhcpAllocationInfo info = new DhcpAllocationInfo(
851 context.inPacket().receivedFrom(), dhcpPacket.getPacketType(),
852 entry.nasPortId(), clientMac, clientIp);
853
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300854 allocationMap.put(entry.id(), info);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400855
Saurav Das15626a02018-09-27 18:36:45 -0700856 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info,
857 context.inPacket().receivedFrom()));
Amit Ghosha17354e2017-08-23 12:56:04 +0100858
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000859 if (option82) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000860 DHCP dhcpPacketWithOption82 = addOption82(dhcpPacket, entry);
861 udpPacket.setPayload(dhcpPacketWithOption82);
862 }
863
864 ipv4Packet.setPayload(udpPacket);
865 etherReply.setPayload(ipv4Packet);
Amit Ghosh83c8c892017-11-09 11:08:27 +0000866 if (modifyClientPktsSrcDstMac) {
867 etherReply.setSourceMACAddress(relayAgentMac);
868 etherReply.setDestinationMACAddress(dhcpConnectMac);
869 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100870
Amit Ghosh8951f042017-08-10 13:48:10 +0100871 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000872 etherReply.setVlanID(uniTagInformation.getPonCTag().toShort());
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530873 etherReply.setQinQTPID(Ethernet.TYPE_VLAN);
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000874 etherReply.setQinQVID(uniTagInformation.getPonSTag().toShort());
875 if (uniTagInformation.getUsPonSTagPriority() != -1) {
876 etherReply.setQinQPriorityCode((byte) uniTagInformation.getUsPonSTagPriority());
877 }
878 log.info("Finished processing packet.. relaying to dhcpServer {}");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100879 return etherReply;
880 }
881
882 //build the DHCP offer/ack with proper client port.
Saurav Das15626a02018-09-27 18:36:45 -0700883 private Ethernet processDhcpPacketFromServer(PacketContext context,
884 Ethernet ethernetPacket) {
885 if (log.isTraceEnabled()) {
886 log.trace("DHCP packet received from server at {} {}",
887 context.inPacket().receivedFrom(), ethernetPacket);
888 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100889 // get dhcp header.
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530890 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100891 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
892 UDP udpPacket = (UDP) ipv4Packet.getPayload();
893 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
894
Amit Ghosh47243cb2017-07-26 05:08:53 +0100895 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000896 ConnectPoint subsCp = getConnectPointOfClient(dstMac, context);
Amit Ghosh2095dc62017-09-25 20:56:55 +0100897 // If we can't find the subscriber, can't process further
898 if (subsCp == null) {
899 return null;
900 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100901 // if it's an ACK packet store the information for display purpose
902 if (getDhcpPacketType(dhcpPayload) == DHCPPacketType.DHCPACK) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100903
Amit Ghosha17354e2017-08-23 12:56:04 +0100904 String portId = nasPortId(subsCp);
905 SubscriberAndDeviceInformation sub = subsService.get(portId);
906 if (sub != null) {
Jonathan Hartedbf6422018-05-02 17:30:05 -0700907 List<DhcpOption> options = dhcpPayload.getOptions();
908 List<DhcpOption> circuitIds = options.stream()
Amit Ghosha17354e2017-08-23 12:56:04 +0100909 .filter(option -> option.getCode() == DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
910 .collect(Collectors.toList());
911
912 String circuitId = "None";
913 if (circuitIds.size() == 1) {
Amit Ghosh2095dc62017-09-25 20:56:55 +0100914 byte[] array = circuitIds.get(0).getData();
915
916 try {
917 // we leave the first two bytes as they are the id and length
918 circuitId = new String(Arrays.copyOfRange(array, 2, array.length), "UTF-8");
919 } catch (Exception e) { }
Amit Ghosha17354e2017-08-23 12:56:04 +0100920 }
921
922 IpAddress ip = IpAddress.valueOf(dhcpPayload.getYourIPAddress());
923
924 //storeDHCPAllocationInfo
Jonathan Hartc36c9552018-07-31 15:07:53 -0400925 DhcpAllocationInfo info = new DhcpAllocationInfo(subsCp,
926 dhcpPayload.getPacketType(), circuitId, dstMac, ip);
Amit Ghosha17354e2017-08-23 12:56:04 +0100927
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300928 allocationMap.put(sub.id(), info);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400929
930 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info, subsCp));
Amit Ghosha17354e2017-08-23 12:56:04 +0100931 }
932 } // end storing of info
Amit Ghosh47243cb2017-07-26 05:08:53 +0100933
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000934 SubscriberAndDeviceInformation entry = getSubscriberInfoFromServer(dhcpPayload, context);
935
936 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, entry);
937 if (uniTagInformation == null) {
938 log.warn("Missing service information for connectPoint {} / cTag {}",
939 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
940 return null;
941 }
942
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300943 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_FROM_SERVER"));
944
Amit Ghosh47243cb2017-07-26 05:08:53 +0100945 // we leave the srcMac from the original packet
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000946 etherReply.setQinQVID(VlanId.NO_VID);
947 etherReply.setQinQPriorityCode((byte) 0);
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530948 etherReply.setDestinationMACAddress(dstMac);
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000949 etherReply.setVlanID(uniTagInformation.getPonCTag().toShort());
950 if (uniTagInformation.getUsPonCTagPriority() != -1) {
951 etherReply.setPriorityCode((byte) uniTagInformation.getUsPonCTagPriority());
952 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100953
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000954 if (option82) {
955 udpPacket.setPayload(removeOption82(dhcpPayload));
956 } else {
957 udpPacket.setPayload(dhcpPayload);
958 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100959 ipv4Packet.setPayload(udpPacket);
960 etherReply.setPayload(ipv4Packet);
961
Saurav Das15626a02018-09-27 18:36:45 -0700962 log.info("Finished processing packet.. relaying to client");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100963 return etherReply;
964 }
965
Amit Ghosha17354e2017-08-23 12:56:04 +0100966 /*
967 * Get ConnectPoint of the Client based on it's MAC address
968 */
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000969 private ConnectPoint getConnectPointOfClient(MacAddress dstMac, PacketContext context) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100970 Set<Host> hosts = hostService.getHostsByMac(dstMac);
971 if (hosts == null || hosts.isEmpty()) {
972 log.warn("Cannot determine host for DHCP client: {}. Aborting "
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530973 + "relay for dhcp packet from server",
Amit Ghosha17354e2017-08-23 12:56:04 +0100974 dstMac);
975 return null;
976 }
977 for (Host h : hosts) {
978 // if more than one,
979 // find the connect point which has an valid entry in SADIS
980 ConnectPoint cp = new ConnectPoint(h.location().deviceId(),
981 h.location().port());
982
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000983 String portId = nasPortId(cp);
984 SubscriberAndDeviceInformation sub = subsService.get(portId);
985 if (sub == null) {
986 log.warn("Subscriber info not found for {}", cp);
987 return null;
Amit Ghosha17354e2017-08-23 12:56:04 +0100988 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100989
Gamze Abaka2dcd1f92020-01-31 06:51:43 +0000990 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, sub);
991 if (uniTagInformation == null) {
992 log.warn("Missing service information for connectPoint {} / cTag {}",
993 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
994 return null;
995 }
996 return cp;
997 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100998 return null;
999 }
1000
Amit Ghosh47243cb2017-07-26 05:08:53 +01001001 //send the response to the requester host.
Gamze Abaka2dcd1f92020-01-31 06:51:43 +00001002 private void sendReply(Ethernet ethPacket, DHCP dhcpPayload, PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +01001003 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abaka2dcd1f92020-01-31 06:51:43 +00001004 ConnectPoint subCp = getConnectPointOfClient(descMac, context);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001005
1006 // Send packet out to requester if the host information is available
Amit Ghosha17354e2017-08-23 12:56:04 +01001007 if (subCp != null) {
Saurav Das15626a02018-09-27 18:36:45 -07001008 log.info("Sending DHCP packet to client at {}", subCp);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001009 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosha17354e2017-08-23 12:56:04 +01001010 .setOutput(subCp.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +01001011 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosha17354e2017-08-23 12:56:04 +01001012 subCp.deviceId(), t, ByteBuffer.wrap(ethPacket.serialize()));
Amit Ghosh47243cb2017-07-26 05:08:53 +01001013 if (log.isTraceEnabled()) {
Saurav Das15626a02018-09-27 18:36:45 -07001014 log.trace("Relaying packet to dhcp client at {} {}", subCp,
1015 ethPacket);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001016 }
1017 packetService.emit(o);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001018 } else {
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001019 log.error("Dropping DHCP packet because can't find host for {}", descMac);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001020 }
1021 }
1022 }
1023
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001024 private DHCP addOption82(DHCP dhcpPacket, SubscriberAndDeviceInformation entry) {
1025 log.debug("option82data {} ", entry);
1026
Jonathan Hartedbf6422018-05-02 17:30:05 -07001027 List<DhcpOption> options = Lists.newArrayList(dhcpPacket.getOptions());
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001028 DhcpOption82 option82 = new DhcpOption82();
1029 option82.setAgentCircuitId(entry.circuitId());
1030 option82.setAgentRemoteId(entry.remoteId());
Jonathan Hartedbf6422018-05-02 17:30:05 -07001031 DhcpOption option = new DhcpOption()
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +05301032 .setCode(DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
1033 .setData(option82.toByteArray())
1034 .setLength(option82.length());
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001035
1036 options.add(options.size() - 1, option);
1037 dhcpPacket.setOptions(options);
Amit Ghosh8951f042017-08-10 13:48:10 +01001038
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001039 return dhcpPacket;
1040
1041 }
1042
1043 private DHCP removeOption82(DHCP dhcpPacket) {
Jonathan Hartedbf6422018-05-02 17:30:05 -07001044 List<DhcpOption> options = dhcpPacket.getOptions();
1045 List<DhcpOption> newoptions = options.stream()
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001046 .filter(option -> option.getCode() != DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
1047 .collect(Collectors.toList());
1048
1049 return dhcpPacket.setOptions(newoptions);
1050 }
Amit Ghosh47243cb2017-07-26 05:08:53 +01001051 /**
1052 * Listener for network config events.
1053 */
1054 private class InternalConfigListener implements NetworkConfigListener {
1055
1056 @Override
1057 public void event(NetworkConfigEvent event) {
1058
1059 if ((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
1060 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) &&
1061 event.configClass().equals(DhcpL2RelayConfig.class)) {
1062 updateConfig();
1063 log.info("Reconfigured");
1064 }
1065 }
1066 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001067
Amit Ghosh8951f042017-08-10 13:48:10 +01001068 /**
1069 * Handles Mastership changes for the devices which connect
1070 * to the DHCP server.
1071 */
1072 private class InnerMastershipListener implements MastershipListener {
1073 @Override
1074 public void event(MastershipEvent event) {
Amit Ghosh83c8c892017-11-09 11:08:27 +00001075 if (!useOltUplink) {
1076 if (dhcpServerConnectPoint.get() != null &&
1077 dhcpServerConnectPoint.get().deviceId().
1078 equals(event.subject())) {
1079 log.trace("Mastership Event recevived for {}", event.subject());
1080 // mastership of the device for our connect point has changed
1081 // reselect
1082 selectServerConnectPoint();
1083 }
Amit Ghosh8951f042017-08-10 13:48:10 +01001084 }
1085 }
1086 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001087
Amit Ghosh8951f042017-08-10 13:48:10 +01001088 /**
1089 * Handles Device status change for the devices which connect
1090 * to the DHCP server.
1091 */
1092 private class InnerDeviceListener implements DeviceListener {
1093 @Override
1094 public void event(DeviceEvent event) {
Saurav Das15626a02018-09-27 18:36:45 -07001095 if (log.isTraceEnabled() &&
1096 !event.type().equals(DeviceEvent.Type.PORT_STATS_UPDATED)) {
1097 log.trace("Device Event received for {} event {}",
1098 event.subject(), event.type());
1099 }
Amit Ghosh83c8c892017-11-09 11:08:27 +00001100 if (!useOltUplink) {
1101 if (dhcpServerConnectPoint.get() == null) {
1102 switch (event.type()) {
1103 case DEVICE_ADDED:
1104 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasb14f08a2019-02-22 16:34:15 -08001105 // some device is available check if we can get a
1106 // connect point we can use
1107 addOrRemoveDhcpTrapFromServer(true);
Amit Ghosh83c8c892017-11-09 11:08:27 +00001108 break;
1109 default:
1110 break;
1111 }
1112 return;
Amit Ghosh8951f042017-08-10 13:48:10 +01001113 }
Amit Ghosh83c8c892017-11-09 11:08:27 +00001114 if (dhcpServerConnectPoint.get().deviceId().
1115 equals(event.subject().id())) {
1116 switch (event.type()) {
1117 case DEVICE_AVAILABILITY_CHANGED:
1118 case DEVICE_REMOVED:
1119 case DEVICE_SUSPENDED:
1120 // state of our device has changed, check if we need
Saurav Dasb14f08a2019-02-22 16:34:15 -08001121 // to re-select a connectpoint
1122 addOrRemoveDhcpTrapFromServer(true);
Amit Ghosh83c8c892017-11-09 11:08:27 +00001123 break;
1124 default:
1125 break;
1126 }
1127 }
1128 } else {
Amit Ghosh8951f042017-08-10 13:48:10 +01001129 switch (event.type()) {
Amit Ghosh83c8c892017-11-09 11:08:27 +00001130 case PORT_ADDED:
Saurav Dasb4e3e102018-10-02 15:31:17 -07001131 if (useOltUplink && isUplinkPortOfOlt(event.subject().id(), event.port())) {
Saurav Dasb14f08a2019-02-22 16:34:15 -08001132 requestDhcpPacketsFromConnectPoint(
1133 new ConnectPoint(event.subject().id(), event.port().number()),
David K. Bainbridgefaf79322020-01-23 10:15:06 -08001134 Optional.ofNullable(null));
Amit Ghosh83c8c892017-11-09 11:08:27 +00001135 }
Amit Ghosh8951f042017-08-10 13:48:10 +01001136 break;
1137 default:
1138 break;
1139 }
1140 }
1141 }
1142 }
Amit Ghosh47243cb2017-07-26 05:08:53 +01001143}