blob: 038ab60325e0af5284e6eda6c4524b54a917b9cb [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
Carmelo Casconede1e6e32019-07-15 19:39:08 -070018import com.google.common.collect.ImmutableSet;
19import com.google.common.collect.Lists;
20import com.google.common.collect.Maps;
21import com.google.common.collect.Sets;
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -030022import static org.onlab.packet.DHCP.DHCPOptionCode.OptionCode_MessageType;
23import static org.onlab.packet.MacAddress.valueOf;
24import static org.onlab.util.Tools.get;
25import static org.onlab.util.Tools.getIntegerProperty;
26import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
27
28import java.io.ByteArrayOutputStream;
29import java.nio.ByteBuffer;
30import java.util.AbstractMap;
31import java.util.ArrayList;
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -030032import java.util.Dictionary;
33import java.util.List;
34import java.util.Map;
35import java.util.Optional;
36import java.util.Set;
37import java.util.concurrent.Executors;
38import java.util.concurrent.atomic.AtomicLong;
39import java.util.concurrent.atomic.AtomicReference;
40import java.util.concurrent.ScheduledExecutorService;
41import java.util.concurrent.ScheduledFuture;
42import java.util.concurrent.TimeUnit;
43import java.util.stream.Collectors;
44
45import org.apache.commons.io.HexDump;
Amit Ghosh47243cb2017-07-26 05:08:53 +010046import org.onlab.packet.DHCP;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000047import org.onlab.packet.Ethernet;
Amit Ghosh47243cb2017-07-26 05:08:53 +010048import org.onlab.packet.IPv4;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053049import org.onlab.packet.IpAddress;
Deepa vaddireddy0060f532017-08-04 06:46:05 +000050import org.onlab.packet.MacAddress;
Amit Ghosh47243cb2017-07-26 05:08:53 +010051import org.onlab.packet.TpPort;
52import org.onlab.packet.UDP;
53import org.onlab.packet.VlanId;
Jonathan Hartedbf6422018-05-02 17:30:05 -070054import org.onlab.packet.dhcp.DhcpOption;
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -030055import org.onlab.util.SafeRecurringTask;
Amit Ghosh47243cb2017-07-26 05:08:53 +010056import org.onlab.util.Tools;
57import org.onosproject.cfg.ComponentConfigService;
58import org.onosproject.core.ApplicationId;
59import org.onosproject.core.CoreService;
Jonathan Hartc36c9552018-07-31 15:07:53 -040060import org.onosproject.event.AbstractListenerManager;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053061import org.onosproject.mastership.MastershipEvent;
62import org.onosproject.mastership.MastershipListener;
63import org.onosproject.mastership.MastershipService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010064import org.onosproject.net.AnnotationKeys;
65import org.onosproject.net.ConnectPoint;
Amit Ghosh83c8c892017-11-09 11:08:27 +000066import org.onosproject.net.Device;
67import org.onosproject.net.DeviceId;
Amit Ghosh47243cb2017-07-26 05:08:53 +010068import org.onosproject.net.Host;
69import org.onosproject.net.Port;
Amit Ghosh83c8c892017-11-09 11:08:27 +000070import org.onosproject.net.PortNumber;
Amit Ghosh47243cb2017-07-26 05:08:53 +010071import org.onosproject.net.config.ConfigFactory;
72import org.onosproject.net.config.NetworkConfigEvent;
73import org.onosproject.net.config.NetworkConfigListener;
74import org.onosproject.net.config.NetworkConfigRegistry;
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +053075import org.onosproject.net.device.DeviceEvent;
76import org.onosproject.net.device.DeviceListener;
Amit Ghosh47243cb2017-07-26 05:08:53 +010077import org.onosproject.net.device.DeviceService;
78import org.onosproject.net.flow.DefaultTrafficSelector;
79import org.onosproject.net.flow.DefaultTrafficTreatment;
80import org.onosproject.net.flow.TrafficSelector;
81import org.onosproject.net.flow.TrafficTreatment;
Saurav Dasb4e3e102018-10-02 15:31:17 -070082import org.onosproject.net.flowobjective.FlowObjectiveService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010083import org.onosproject.net.host.HostService;
84import org.onosproject.net.packet.DefaultOutboundPacket;
85import org.onosproject.net.packet.OutboundPacket;
86import org.onosproject.net.packet.PacketContext;
87import org.onosproject.net.packet.PacketPriority;
88import org.onosproject.net.packet.PacketProcessor;
89import org.onosproject.net.packet.PacketService;
Matteo Scandolo57af5d12019-04-29 17:11:41 -070090import org.opencord.dhcpl2relay.DhcpAllocationInfo;
91import org.opencord.dhcpl2relay.DhcpL2RelayEvent;
92import org.opencord.dhcpl2relay.DhcpL2RelayListener;
93import org.opencord.dhcpl2relay.DhcpL2RelayService;
94import org.opencord.dhcpl2relay.impl.packet.DhcpOption82;
Gamze Abakac806c6c2018-12-03 12:49:46 +000095import org.opencord.sadis.BaseInformationService;
96import org.opencord.sadis.SadisService;
Amit Ghosh47243cb2017-07-26 05:08:53 +010097import org.opencord.sadis.SubscriberAndDeviceInformation;
Gamze Abakaa64b3bc2020-01-31 06:51:43 +000098import org.opencord.sadis.UniTagInformation;
Amit Ghosh47243cb2017-07-26 05:08:53 +010099import org.osgi.service.component.ComponentContext;
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700100import org.osgi.service.component.annotations.Activate;
101import org.osgi.service.component.annotations.Component;
102import org.osgi.service.component.annotations.Deactivate;
103import org.osgi.service.component.annotations.Modified;
104import org.osgi.service.component.annotations.Reference;
105import org.osgi.service.component.annotations.ReferenceCardinality;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100106import org.slf4j.Logger;
107import org.slf4j.LoggerFactory;
108
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300109import static org.opencord.dhcpl2relay.impl.OsgiPropertyConstants.*;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100110
111/**
112 * DHCP Relay Agent Application Component.
113 */
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700114@Component(immediate = true,
115property = {
116 OPTION_82 + ":Boolean=" + OPTION_82_DEFAULT,
117 ENABLE_DHCP_BROADCAST_REPLIES + ":Boolean=" + ENABLE_DHCP_BROADCAST_REPLIES_DEFAULT,
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300118 PUBLISH_COUNTERS_RATE + ":Integer=" + PUBLISH_COUNTERS_RATE_DEFAULT,
119 DHCP_COUNTERS_TOPIC + ":String=" + DHCP_COUNTERS_TOPIC_DEFAULT
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700120})
Jonathan Hartc36c9552018-07-31 15:07:53 -0400121public class DhcpL2Relay
122 extends AbstractListenerManager<DhcpL2RelayEvent, DhcpL2RelayListener>
123 implements DhcpL2RelayService {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100124
125 public static final String DHCP_L2RELAY_APP = "org.opencord.dhcpl2relay";
Saurav Dasb4e3e102018-10-02 15:31:17 -0700126 private static final String HOST_LOC_PROVIDER =
127 "org.onosproject.provider.host.impl.HostLocationProvider";
Amit Ghosh47243cb2017-07-26 05:08:53 +0100128 private final Logger log = LoggerFactory.getLogger(getClass());
129 private final InternalConfigListener cfgListener =
130 new InternalConfigListener();
131
132 private final Set<ConfigFactory> factories = ImmutableSet.of(
133 new ConfigFactory<ApplicationId, DhcpL2RelayConfig>(APP_SUBJECT_FACTORY,
134 DhcpL2RelayConfig.class,
135 "dhcpl2relay") {
136 @Override
137 public DhcpL2RelayConfig createConfig() {
138 return new DhcpL2RelayConfig();
139 }
140 }
141 );
142
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100144 protected NetworkConfigRegistry cfgService;
145
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100147 protected CoreService coreService;
148
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100150 protected PacketService packetService;
151
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100153 protected HostService hostService;
154
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100156 protected ComponentConfigService componentConfigService;
157
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700158 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Gamze Abakac806c6c2018-12-03 12:49:46 +0000159 protected SadisService sadisService;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100160
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700161 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh47243cb2017-07-26 05:08:53 +0100162 protected DeviceService deviceService;
163
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Amit Ghosh8951f042017-08-10 13:48:10 +0100165 protected MastershipService mastershipService;
166
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700167 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Saurav Dasb4e3e102018-10-02 15:31:17 -0700168 protected FlowObjectiveService flowObjectiveService;
169
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300170 @Reference(cardinality = ReferenceCardinality.MANDATORY)
171 protected DhcpL2RelayCountersStore dhcpL2RelayCounters;
172
173 // OSGi Properties
Carmelo Cascone4330cf12019-11-15 21:34:02 -0800174 /** Add option 82 to relayed packets. */
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700175 protected boolean option82 = OPTION_82_DEFAULT;
Carmelo Cascone4330cf12019-11-15 21:34:02 -0800176 /** Ask the DHCP Server to send back replies as L2 broadcast. */
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700177 protected boolean enableDhcpBroadcastReplies = ENABLE_DHCP_BROADCAST_REPLIES_DEFAULT;
Amit Ghosha17354e2017-08-23 12:56:04 +0100178
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300179 protected int publishCountersRate = PUBLISH_COUNTERS_RATE_DEFAULT;
180 private String dhcpCountersTopic = DHCP_COUNTERS_TOPIC_DEFAULT;
181
182
183 protected PublishCountersToKafka publishCountersToKafka;
184
185 ScheduledFuture<?> refreshTask;
186 ScheduledExecutorService refreshService = Executors.newSingleThreadScheduledExecutor();
187
Amit Ghosh47243cb2017-07-26 05:08:53 +0100188 private DhcpRelayPacketProcessor dhcpRelayPacketProcessor =
189 new DhcpRelayPacketProcessor();
190
Amit Ghosh8951f042017-08-10 13:48:10 +0100191 private InnerMastershipListener changeListener = new InnerMastershipListener();
192 private InnerDeviceListener deviceListener = new InnerDeviceListener();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100193
Amit Ghosh8951f042017-08-10 13:48:10 +0100194 // connect points to the DHCP server
195 Set<ConnectPoint> dhcpConnectPoints;
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300196 protected AtomicReference<ConnectPoint> dhcpServerConnectPoint = new AtomicReference<>();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100197 private MacAddress dhcpConnectMac = MacAddress.BROADCAST;
198 private ApplicationId appId;
199
Amit Ghosha17354e2017-08-23 12:56:04 +0100200 static Map<String, DhcpAllocationInfo> allocationMap = Maps.newConcurrentMap();
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300201 protected boolean modifyClientPktsSrcDstMac = false;
Amit Ghosh83c8c892017-11-09 11:08:27 +0000202 //Whether to use the uplink port of the OLTs to send/receive messages to the DHCP server
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300203 protected boolean useOltUplink = false;
Amit Ghosha17354e2017-08-23 12:56:04 +0100204
Gamze Abakac806c6c2018-12-03 12:49:46 +0000205 private BaseInformationService<SubscriberAndDeviceInformation> subsService;
206
Amit Ghosh47243cb2017-07-26 05:08:53 +0100207 @Activate
208 protected void activate(ComponentContext context) {
209 //start the dhcp relay agent
210 appId = coreService.registerApplication(DHCP_L2RELAY_APP);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700211 // ensure that host-learning via dhcp includes IP addresses
212 componentConfigService.preSetProperty(HOST_LOC_PROVIDER,
213 "useDhcp", Boolean.TRUE.toString());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100214 componentConfigService.registerProperties(getClass());
Jonathan Hartc36c9552018-07-31 15:07:53 -0400215 eventDispatcher.addSink(DhcpL2RelayEvent.class, listenerRegistry);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100216
217 cfgService.addListener(cfgListener);
Amit Ghosh8951f042017-08-10 13:48:10 +0100218 mastershipService.addListener(changeListener);
219 deviceService.addListener(deviceListener);
220
Matteo Scandolo45e5a272019-09-30 09:30:32 -0700221 subsService = sadisService.getSubscriberInfoService();
222
Amit Ghosh47243cb2017-07-26 05:08:53 +0100223 factories.forEach(cfgService::registerConfigFactory);
224 //update the dhcp server configuration.
225 updateConfig();
226 //add the packet services.
227 packetService.addProcessor(dhcpRelayPacketProcessor,
228 PacketProcessor.director(0));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000229 if (context != null) {
230 modified(context);
231 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100232
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300233 publishCountersToKafka = new PublishCountersToKafka();
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300234 restartPublishCountersTask();
Gamze Abakac806c6c2018-12-03 12:49:46 +0000235
Amit Ghosh47243cb2017-07-26 05:08:53 +0100236 log.info("DHCP-L2-RELAY Started");
237 }
238
239 @Deactivate
240 protected void deactivate() {
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300241 if (refreshTask != null) {
242 refreshTask.cancel(true);
243 }
244 if (refreshService != null) {
245 refreshService.shutdownNow();
246 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100247 cfgService.removeListener(cfgListener);
248 factories.forEach(cfgService::unregisterConfigFactory);
249 packetService.removeProcessor(dhcpRelayPacketProcessor);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700250 cancelDhcpPktsFromServer();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100251
252 componentConfigService.unregisterProperties(getClass(), false);
Deepa Vaddireddy77a6ac72017-09-20 20:36:52 +0530253 deviceService.removeListener(deviceListener);
254 mastershipService.removeListener(changeListener);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400255 eventDispatcher.removeSink(DhcpL2RelayEvent.class);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100256 log.info("DHCP-L2-RELAY Stopped");
257 }
258
259 @Modified
260 protected void modified(ComponentContext context) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000261
Amit Ghosh47243cb2017-07-26 05:08:53 +0100262 Dictionary<?, ?> properties = context.getProperties();
263
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700264 Boolean o = Tools.isPropertyEnabled(properties, OPTION_82);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100265 if (o != null) {
266 option82 = o;
267 }
Amit Ghosh2095dc62017-09-25 20:56:55 +0100268
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700269 o = Tools.isPropertyEnabled(properties, ENABLE_DHCP_BROADCAST_REPLIES);
Amit Ghosh2095dc62017-09-25 20:56:55 +0100270 if (o != null) {
271 enableDhcpBroadcastReplies = o;
272 }
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300273
274 Integer newPublishCountersRate = getIntegerProperty(properties, "publishCountersRate");
275 if (newPublishCountersRate != null) {
276 if (newPublishCountersRate != publishCountersRate && newPublishCountersRate >= 0) {
277 log.info("publishCountersRate modified from {} to {}", publishCountersRate, newPublishCountersRate);
278 publishCountersRate = newPublishCountersRate;
279 } else if (newPublishCountersRate < 0) {
280 log.error("Invalid newPublishCountersRate : {}, defaulting to 0", newPublishCountersRate);
281 publishCountersRate = 0;
282 }
283 restartPublishCountersTask();
284 }
285
286 String newDhcpCountersTopic = get(properties, "dhcpCountersTopic");
287 if (newDhcpCountersTopic != null && !newDhcpCountersTopic.equals(dhcpCountersTopic)) {
288 log.info("Property dhcpCountersTopic modified from {} to {}", dhcpCountersTopic, newDhcpCountersTopic);
289 dhcpCountersTopic = newDhcpCountersTopic;
290 }
291 }
292
293 /**
294 * Starts a thread to publish the counters to kafka at a certain rate time.
295 */
296 private void restartPublishCountersTask() {
297 if (refreshTask != null) {
298 refreshTask.cancel(true);
299 }
300 if (publishCountersRate > 0) {
301 log.info("Refresh Rate set to {}, publishCountersToKafka will be called every {} seconds",
302 publishCountersRate, publishCountersRate);
303 refreshTask = refreshService.scheduleWithFixedDelay(SafeRecurringTask.wrap(publishCountersToKafka),
304 publishCountersRate, publishCountersRate, TimeUnit.SECONDS);
305 } else {
306 log.info("Refresh Rate set to 0, disabling calls to publishCountersToKafka");
307 }
308 }
309
310 /**
311 * Publish the counters to kafka.
312 */
313 private class PublishCountersToKafka implements Runnable {
314 public void run() {
315 dhcpL2RelayCounters.getCountersMap().forEach((counterKey, counterValue) -> {
316 // Publish the global counters
317 if (counterKey.counterClassKey.equals(DhcpL2RelayEvent.GLOBAL_COUNTER)) {
318 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.STATS_UPDATE, null, null,
319 new AbstractMap.SimpleEntry<String, AtomicLong>(counterKey.counterTypeKey.toString(),
320 counterValue), dhcpCountersTopic, null));
321 } else { // Publish the counters per subscriber
322 DhcpAllocationInfo info = allocationMap.get(counterKey.counterClassKey);
323 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.STATS_UPDATE, info, null,
324 new AbstractMap.SimpleEntry<String, AtomicLong>(counterKey.counterTypeKey.toString(),
325 counterValue), dhcpCountersTopic, counterKey.counterClassKey));
326 }
327 });
328 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100329 }
330
331 /**
332 * Checks if this app has been configured.
333 *
334 * @return true if all information we need have been initialized
335 */
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300336 protected boolean configured() {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000337 if (!useOltUplink) {
338 return dhcpServerConnectPoint.get() != null;
339 }
340 return true;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100341 }
342
Amit Ghosh8951f042017-08-10 13:48:10 +0100343 /**
344 * Selects a connect point through an available device for which it is the master.
345 */
346 private void selectServerConnectPoint() {
347 synchronized (this) {
348 dhcpServerConnectPoint.set(null);
349 if (dhcpConnectPoints != null) {
350 // find a connect point through a device for which we are master
351 for (ConnectPoint cp: dhcpConnectPoints) {
352 if (mastershipService.isLocalMaster(cp.deviceId())) {
353 if (deviceService.isAvailable(cp.deviceId())) {
354 dhcpServerConnectPoint.set(cp);
355 }
356 log.info("DHCP connectPoint selected is {}", cp);
357 break;
358 }
359 }
360 }
361
362 log.info("DHCP Server connectPoint is {}", dhcpServerConnectPoint.get());
363
364 if (dhcpServerConnectPoint.get() == null) {
365 log.error("Master of none, can't relay DHCP Message to server");
366 }
367 }
368 }
369
370 /**
371 * Updates the network configuration.
372 */
Amit Ghosh47243cb2017-07-26 05:08:53 +0100373 private void updateConfig() {
374 DhcpL2RelayConfig cfg = cfgService.getConfig(appId, DhcpL2RelayConfig.class);
375 if (cfg == null) {
376 log.warn("Dhcp Server info not available");
377 return;
378 }
Amit Ghosh8951f042017-08-10 13:48:10 +0100379
380 dhcpConnectPoints = Sets.newConcurrentHashSet(cfg.getDhcpServerConnectPoint());
Amit Ghosh83c8c892017-11-09 11:08:27 +0000381 modifyClientPktsSrcDstMac = cfg.getModifySrcDstMacAddresses();
Saurav Dasb4e3e102018-10-02 15:31:17 -0700382 boolean prevUseOltUplink = useOltUplink;
Amit Ghosh83c8c892017-11-09 11:08:27 +0000383 useOltUplink = cfg.getUseOltUplinkForServerPktInOut();
Amit Ghosh8951f042017-08-10 13:48:10 +0100384
Saurav Dasb4e3e102018-10-02 15:31:17 -0700385 if (useOltUplink) {
386 for (ConnectPoint cp : getUplinkPortsOfOlts()) {
387 log.debug("requestDhcpPackets: ConnectPoint: {}", cp);
Matteo Scandolo45e5a272019-09-30 09:30:32 -0700388 requestDhcpPacketsFromConnectPoint(cp, Optional.ofNullable(null));
Saurav Dasb4e3e102018-10-02 15:31:17 -0700389 }
390 // check if previous config was different and so trap flows may
Saurav Dasb14f08a2019-02-22 16:34:15 -0800391 // need to be removed from other places like AGG switches
Saurav Dasb4e3e102018-10-02 15:31:17 -0700392 if (!prevUseOltUplink) {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800393 addOrRemoveDhcpTrapFromServer(false);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700394 }
Saurav Dasb4e3e102018-10-02 15:31:17 -0700395 } else {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800396 // uplink on AGG switch
397 addOrRemoveDhcpTrapFromServer(true);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700398 }
399 }
400
401 private void cancelDhcpPktsFromServer() {
402 if (useOltUplink) {
403 for (ConnectPoint cp : getUplinkPortsOfOlts()) {
404 log.debug("cancelDhcpPackets: ConnectPoint: {}", cp);
Matteo Scandolo45e5a272019-09-30 09:30:32 -0700405 cancelDhcpPacketsFromConnectPoint(cp, Optional.ofNullable(null));
Saurav Dasb4e3e102018-10-02 15:31:17 -0700406 }
407 } else {
Saurav Dasb14f08a2019-02-22 16:34:15 -0800408 // uplink on AGG switch
409 addOrRemoveDhcpTrapFromServer(false);
Amit Ghosh83c8c892017-11-09 11:08:27 +0000410 }
Saurav Dasb4e3e102018-10-02 15:31:17 -0700411 }
412
Saurav Dasb14f08a2019-02-22 16:34:15 -0800413 /**
414 * Used to add or remove DHCP trap flow for packets received from DHCP server.
415 * Typically used on a non OLT device, like an AGG switch. When adding, a
416 * new dhcp server connect point is selected from the configured options.
417 *
418 * @param add true if dhcp trap flow is to be added, false to remove the
419 * trap flow
420 */
421 private void addOrRemoveDhcpTrapFromServer(boolean add) {
422 if (add) {
423 selectServerConnectPoint();
424 log.debug("dhcp server connect point: " + dhcpServerConnectPoint);
425 }
426 if (dhcpServerConnectPoint.get() == null) {
427 log.warn("No dhcpServer connectPoint found, cannot {} dhcp trap flows",
428 (add) ? "install" : "remove");
429 return;
430 }
431 if (add) {
432 log.info("Adding trap to dhcp server connect point: "
433 + dhcpServerConnectPoint);
434 requestDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
435 Optional.of(PacketPriority.HIGH1));
436 } else {
437 log.info("Removing trap from dhcp server connect point: "
438 + dhcpServerConnectPoint);
439 cancelDhcpPacketsFromConnectPoint(dhcpServerConnectPoint.get(),
440 Optional.of(PacketPriority.HIGH1));
441 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100442 }
443
444 /**
Amit Ghosh83c8c892017-11-09 11:08:27 +0000445 * Returns all the uplink ports of OLTs configured in SADIS.
446 * Only ports visible in ONOS and for which this instance is master
447 * are returned
448 */
449 private List<ConnectPoint> getUplinkPortsOfOlts() {
450 List<ConnectPoint> cps = new ArrayList<>();
451
452 // find all the olt devices and if their uplink ports are visible
453 Iterable<Device> devices = deviceService.getDevices();
454 for (Device d : devices) {
455 // check if this device is provisioned in Sadis
456
457 log.debug("getUplinkPortsOfOlts: Checking mastership of {}", d);
458 // do only for devices for which we are the master
459 if (!mastershipService.isLocalMaster(d.id())) {
460 continue;
461 }
462
463 String devSerialNo = d.serialNumber();
464 SubscriberAndDeviceInformation deviceInfo = subsService.get(devSerialNo);
465 log.debug("getUplinkPortsOfOlts: Found device: {}", deviceInfo);
466 if (deviceInfo != null) {
467 // check if the uplink port with that number is available on the device
468 PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
469 Port port = deviceService.getPort(d.id(), pNum);
470 log.debug("getUplinkPortsOfOlts: Found port: {}", port);
471 if (port != null) {
472 cps.add(new ConnectPoint(d.id(), pNum));
473 }
474 }
475 }
476 return cps;
477 }
478
479 /**
480 * Returns whether the passed port is the uplink port of the olt device.
481 */
482 private boolean isUplinkPortOfOlt(DeviceId dId, Port p) {
483 log.debug("isUplinkPortOfOlt: DeviceId: {} Port: {}", dId, p);
484 // do only for devices for which we are the master
485 if (!mastershipService.isLocalMaster(dId)) {
486 return false;
487 }
488
489 Device d = deviceService.getDevice(dId);
490 SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
491
492 if (deviceInfo != null) {
493 return (deviceInfo.uplinkPort() == p.number().toLong());
494 }
495
496 return false;
497 }
498
499 /**
500 * Returns the connectPoint which is the uplink port of the OLT.
501 */
502 private ConnectPoint getUplinkConnectPointOfOlt(DeviceId dId) {
503
504 Device d = deviceService.getDevice(dId);
505 SubscriberAndDeviceInformation deviceInfo = subsService.get(d.serialNumber());
506 log.debug("getUplinkConnectPointOfOlt DeviceId: {} devInfo: {}", dId, deviceInfo);
507 if (deviceInfo != null) {
508 PortNumber pNum = PortNumber.portNumber(deviceInfo.uplinkPort());
509 Port port = deviceService.getPort(d.id(), pNum);
510 if (port != null) {
511 return new ConnectPoint(d.id(), pNum);
512 }
513 }
514
515 return null;
516 }
517
518 /**
519 * Request DHCP packet from particular connect point via PacketService.
Saurav Dasb14f08a2019-02-22 16:34:15 -0800520 * Optionally provide a priority for the trap flow. If no such priority is
521 * provided, the default priority will be used.
522 *
523 * @param cp the connect point to trap dhcp packets from
524 * @param priority of the trap flow, null to use default priority
Amit Ghosh83c8c892017-11-09 11:08:27 +0000525 */
Saurav Dasb14f08a2019-02-22 16:34:15 -0800526 private void requestDhcpPacketsFromConnectPoint(ConnectPoint cp,
527 Optional<PacketPriority> priority) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000528 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
529 .matchEthType(Ethernet.TYPE_IPV4)
530 .matchInPort(cp.port())
531 .matchIPProtocol(IPv4.PROTOCOL_UDP)
532 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
533 packetService.requestPackets(selectorServer.build(),
Saurav Dasb14f08a2019-02-22 16:34:15 -0800534 priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
535 appId, Optional.of(cp.deviceId()));
Amit Ghosh83c8c892017-11-09 11:08:27 +0000536 }
537
538 /**
Saurav Dasb14f08a2019-02-22 16:34:15 -0800539 * Cancel DHCP packet from particular connect point via PacketService. If
540 * the request was made with a specific packet priority, then the same
541 * priority should be used in this call.
542 *
543 * @param cp the connect point for the trap flow
544 * @param priority with which the trap flow was requested; if request
545 * priority was not specified, this param should also be null
Amit Ghosh83c8c892017-11-09 11:08:27 +0000546 */
Saurav Dasb14f08a2019-02-22 16:34:15 -0800547 private void cancelDhcpPacketsFromConnectPoint(ConnectPoint cp,
548 Optional<PacketPriority> priority) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000549 TrafficSelector.Builder selectorServer = DefaultTrafficSelector.builder()
550 .matchEthType(Ethernet.TYPE_IPV4)
551 .matchInPort(cp.port())
552 .matchIPProtocol(IPv4.PROTOCOL_UDP)
553 .matchUdpSrc(TpPort.tpPort(UDP.DHCP_SERVER_PORT));
554 packetService.cancelPackets(selectorServer.build(),
Saurav Dasb14f08a2019-02-22 16:34:15 -0800555 priority.isPresent() ? priority.get() : PacketPriority.CONTROL,
556 appId, Optional.of(cp.deviceId()));
Amit Ghosh83c8c892017-11-09 11:08:27 +0000557 }
558
Amit Ghosha17354e2017-08-23 12:56:04 +0100559 public static Map<String, DhcpAllocationInfo> allocationMap() {
560 return allocationMap;
561 }
562
Amit Ghosh47243cb2017-07-26 05:08:53 +0100563 private SubscriberAndDeviceInformation getDevice(PacketContext context) {
564 String serialNo = deviceService.getDevice(context.inPacket().
565 receivedFrom().deviceId()).serialNumber();
566
567 return subsService.get(serialNo);
568 }
569
Amit Ghosh47243cb2017-07-26 05:08:53 +0100570 private MacAddress relayAgentMacAddress(PacketContext context) {
571
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000572 SubscriberAndDeviceInformation device = this.getDevice(context);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100573 if (device == null) {
574 log.warn("Device not found for {}", context.inPacket().
575 receivedFrom());
576 return null;
577 }
578
579 return device.hardwareIdentifier();
580 }
581
582 private String nasPortId(PacketContext context) {
Amit Ghosh8951f042017-08-10 13:48:10 +0100583 return nasPortId(context.inPacket().receivedFrom());
584 }
585
586 private String nasPortId(ConnectPoint cp) {
587 Port p = deviceService.getPort(cp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100588 return p.annotations().value(AnnotationKeys.PORT_NAME);
589 }
590
591 private SubscriberAndDeviceInformation getSubscriber(PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100592 return subsService.get(nasPortId(context));
593 }
594
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000595 private UniTagInformation getUnitagInformationFromPacketContext(PacketContext context,
596 SubscriberAndDeviceInformation sub) {
597 //If the ctag is defined in the tagList and dhcp is required, return the service info
598 List<UniTagInformation> tagList = sub.uniTagList();
599 for (UniTagInformation uniServiceInformation : tagList) {
600 if (uniServiceInformation.getPonCTag().toShort() == context.inPacket().parsed().getVlanID()) {
601 if (uniServiceInformation.getIsDhcpRequired()) {
602 return uniServiceInformation;
603 }
604 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100605 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100606
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000607 return null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100608 }
609
610 private class DhcpRelayPacketProcessor implements PacketProcessor {
611
612 @Override
613 public void process(PacketContext context) {
614 if (!configured()) {
615 log.warn("Missing DHCP relay config. Abort packet processing");
616 return;
617 }
618
619 // process the packet and get the payload
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530620 Ethernet packet = context.inPacket().parsed();
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000621
Amit Ghosh47243cb2017-07-26 05:08:53 +0100622 if (packet == null) {
623 log.warn("Packet is null");
624 return;
625 }
626
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530627 if (packet.getEtherType() == Ethernet.TYPE_IPV4) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100628 IPv4 ipv4Packet = (IPv4) packet.getPayload();
629
630 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_UDP) {
631 UDP udpPacket = (UDP) ipv4Packet.getPayload();
632 if (udpPacket.getSourcePort() == UDP.DHCP_CLIENT_PORT ||
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000633 udpPacket.getSourcePort() == UDP.DHCP_SERVER_PORT) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100634 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
635 //This packet is dhcp.
636 processDhcpPacket(context, packet, dhcpPayload);
637 }
638 }
639 }
640 }
641
642 //forward the packet to ConnectPoint where the DHCP server is attached.
Amit Ghosh83c8c892017-11-09 11:08:27 +0000643 private void forwardPacket(Ethernet packet, PacketContext context) {
644 ConnectPoint toSendTo = null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100645
Amit Ghosh83c8c892017-11-09 11:08:27 +0000646 if (!useOltUplink) {
647 toSendTo = dhcpServerConnectPoint.get();
648 } else {
649 toSendTo = getUplinkConnectPointOfOlt(context.inPacket().
650 receivedFrom().deviceId());
651 }
652
653 if (toSendTo != null) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100654 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosh83c8c892017-11-09 11:08:27 +0000655 .setOutput(toSendTo.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100656 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosh83c8c892017-11-09 11:08:27 +0000657 toSendTo.deviceId(), t,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100658 ByteBuffer.wrap(packet.serialize()));
659 if (log.isTraceEnabled()) {
Saurav Das15626a02018-09-27 18:36:45 -0700660 log.trace("Relaying packet to dhcp server at {} {}",
661 toSendTo, packet);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100662 }
663 packetService.emit(o);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300664
665 SubscriberAndDeviceInformation entry = getSubscriberInfoFromClient(context);
666 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_TO_SERVER"));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100667 } else {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000668 log.error("No connect point to send msg to DHCP Server");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100669 }
670 }
671
Amit Ghosha17354e2017-08-23 12:56:04 +0100672 // get the type of the DHCP packet
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700673 private DHCP.MsgType getDhcpPacketType(DHCP dhcpPayload) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100674
Jonathan Hartedbf6422018-05-02 17:30:05 -0700675 for (DhcpOption option : dhcpPayload.getOptions()) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100676 if (option.getCode() == OptionCode_MessageType.getValue()) {
677 byte[] data = option.getData();
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700678 return DHCP.MsgType.getType(data[0]);
Amit Ghosha17354e2017-08-23 12:56:04 +0100679 }
680 }
681 return null;
682 }
683
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300684 private void updateDhcpRelayCountersStore(SubscriberAndDeviceInformation entry,
685 DhcpL2RelayCounters counterType) {
686 // Update global counter stats
687 dhcpL2RelayCounters.incrementCounter(DhcpL2RelayEvent.GLOBAL_COUNTER, counterType);
688 if (entry == null) {
689 log.warn("Counter not updated as subscriber info not found.");
690 } else {
691 // Update subscriber counter stats
692 dhcpL2RelayCounters.incrementCounter(entry.id(), counterType);
693 }
694 }
695
696 /*
697 * Get subscriber information based on it's context packet.
698 */
699 private SubscriberAndDeviceInformation getSubscriberInfoFromClient(PacketContext context) {
700 if (context != null) {
701 return getSubscriber(context);
702 }
703 return null;
704 }
705
706 /*
707 * Get subscriber information based on it's DHCP payload.
708 */
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000709 private SubscriberAndDeviceInformation getSubscriberInfoFromServer(DHCP dhcpPayload, PacketContext context) {
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300710 if (dhcpPayload != null) {
711 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000712 ConnectPoint subsCp = getConnectPointOfClient(descMac, context);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300713
714 if (subsCp != null) {
715 String portId = nasPortId(subsCp);
716 return subsService.get(portId);
717 }
718 }
719 return null;
720 }
721
Amit Ghosh47243cb2017-07-26 05:08:53 +0100722 //process the dhcp packet before sending to server
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530723 private void processDhcpPacket(PacketContext context, Ethernet packet,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100724 DHCP dhcpPayload) {
725 if (dhcpPayload == null) {
726 log.warn("DHCP payload is null");
727 return;
728 }
729
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700730 DHCP.MsgType incomingPacketType = getDhcpPacketType(dhcpPayload);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300731 if (incomingPacketType == null) {
732 log.warn("DHCP packet type not found. Dump of ethernet pkt in hex format for troubleshooting.");
733 byte[] array = packet.serialize();
734 ByteArrayOutputStream buf = new ByteArrayOutputStream();
735 try {
736 HexDump.dump(array, 0, buf, 0);
737 log.trace(buf.toString());
738 } catch (Exception e) { }
739 return;
740 }
741
742 SubscriberAndDeviceInformation entry = null;
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000743
Saurav Das15626a02018-09-27 18:36:45 -0700744 log.info("Received DHCP Packet of type {} from {}",
745 incomingPacketType, context.inPacket().receivedFrom());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100746
747 switch (incomingPacketType) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000748 case DHCPDISCOVER:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530749 Ethernet ethernetPacketDiscover =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000750 processDhcpPacketFromClient(context, packet);
751 if (ethernetPacketDiscover != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000752 forwardPacket(ethernetPacketDiscover, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000753 }
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300754 entry = getSubscriberInfoFromClient(context);
755 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDISCOVER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000756 break;
757 case DHCPOFFER:
758 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700759 Ethernet ethernetPacketOffer =
760 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000761 if (ethernetPacketOffer != null) {
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000762 sendReply(ethernetPacketOffer, dhcpPayload, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000763 }
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000764 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300765 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPOFFER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000766 break;
767 case DHCPREQUEST:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530768 Ethernet ethernetPacketRequest =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000769 processDhcpPacketFromClient(context, packet);
770 if (ethernetPacketRequest != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000771 forwardPacket(ethernetPacketRequest, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000772 }
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300773 entry = getSubscriberInfoFromClient(context);
774 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPREQUEST"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000775 break;
776 case DHCPACK:
777 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700778 Ethernet ethernetPacketAck =
779 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000780 if (ethernetPacketAck != null) {
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000781 sendReply(ethernetPacketAck, dhcpPayload, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000782 }
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000783 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300784 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPACK"));
785 break;
786 case DHCPDECLINE:
787 entry = getSubscriberInfoFromClient(context);
788 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDECLINE"));
789 break;
790 case DHCPNAK:
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000791 entry = getSubscriberInfoFromServer(dhcpPayload, context);
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300792 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPNACK"));
793 break;
794 case DHCPRELEASE:
Thomas Lee S0dc9a3b2020-01-14 10:42:29 +0530795 Ethernet ethernetPacketRelease =
796 processDhcpPacketFromClient(context, packet);
797 if (ethernetPacketRelease != null) {
798 forwardPacket(ethernetPacketRelease, context);
799 }
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300800 entry = getSubscriberInfoFromClient(context);
801 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPRELEASE"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000802 break;
803 default:
804 break;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100805 }
806 }
807
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530808 private Ethernet processDhcpPacketFromClient(PacketContext context,
809 Ethernet ethernetPacket) {
Saurav Das15626a02018-09-27 18:36:45 -0700810 if (log.isTraceEnabled()) {
811 log.trace("DHCP packet received from client at {} {}",
812 context.inPacket().receivedFrom(), ethernetPacket);
813 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100814
815 MacAddress relayAgentMac = relayAgentMacAddress(context);
816 if (relayAgentMac == null) {
817 log.warn("RelayAgent MAC not found ");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100818 return null;
819 }
820
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530821 Ethernet etherReply = ethernetPacket;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100822
823 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
824 UDP udpPacket = (UDP) ipv4Packet.getPayload();
825 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
826
Amit Ghosha17354e2017-08-23 12:56:04 +0100827 if (enableDhcpBroadcastReplies) {
828 // We want the reply to come back as a L2 broadcast
829 dhcpPacket.setFlags((short) 0x8000);
830 }
831
Jonathan Hartc36c9552018-07-31 15:07:53 -0400832 MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
833 IpAddress clientIp = IpAddress.valueOf(dhcpPacket.getClientIPAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100834
Jonathan Hartc36c9552018-07-31 15:07:53 -0400835 SubscriberAndDeviceInformation entry = getSubscriber(context);
836 if (entry == null) {
Saurav Das15626a02018-09-27 18:36:45 -0700837 log.warn("Dropping packet as subscriber entry is not available");
Jonathan Hartc36c9552018-07-31 15:07:53 -0400838 return null;
839 }
840
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000841 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, entry);
842 if (uniTagInformation == null) {
843 log.warn("Missing service information for connectPoint {} / cTag {}",
844 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
845 return null;
846 }
847
Jonathan Hartc36c9552018-07-31 15:07:53 -0400848 DhcpAllocationInfo info = new DhcpAllocationInfo(
849 context.inPacket().receivedFrom(), dhcpPacket.getPacketType(),
Thomas Lee S0dc9a3b2020-01-14 10:42:29 +0530850 entry.circuitId(), clientMac, clientIp);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400851
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300852 allocationMap.put(entry.id(), info);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400853
Saurav Das15626a02018-09-27 18:36:45 -0700854 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info,
855 context.inPacket().receivedFrom()));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000856 if (option82) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000857 DHCP dhcpPacketWithOption82 = addOption82(dhcpPacket, entry);
858 udpPacket.setPayload(dhcpPacketWithOption82);
859 }
860
861 ipv4Packet.setPayload(udpPacket);
862 etherReply.setPayload(ipv4Packet);
Amit Ghosh83c8c892017-11-09 11:08:27 +0000863 if (modifyClientPktsSrcDstMac) {
864 etherReply.setSourceMACAddress(relayAgentMac);
865 etherReply.setDestinationMACAddress(dhcpConnectMac);
866 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100867
Amit Ghosh8951f042017-08-10 13:48:10 +0100868 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000869 etherReply.setVlanID(uniTagInformation.getPonCTag().toShort());
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530870 etherReply.setQinQTPID(Ethernet.TYPE_VLAN);
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000871 etherReply.setQinQVID(uniTagInformation.getPonSTag().toShort());
872 if (uniTagInformation.getUsPonSTagPriority() != -1) {
873 etherReply.setQinQPriorityCode((byte) uniTagInformation.getUsPonSTagPriority());
874 }
Thomas Lee S0dc9a3b2020-01-14 10:42:29 +0530875 log.info("Finished processing DHCP packet of type {} from {} and relaying to dhcpServer",
876 dhcpPacket.getPacketType(), entry.id());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100877 return etherReply;
878 }
879
880 //build the DHCP offer/ack with proper client port.
Saurav Das15626a02018-09-27 18:36:45 -0700881 private Ethernet processDhcpPacketFromServer(PacketContext context,
882 Ethernet ethernetPacket) {
883 if (log.isTraceEnabled()) {
884 log.trace("DHCP packet received from server at {} {}",
885 context.inPacket().receivedFrom(), ethernetPacket);
886 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100887 // get dhcp header.
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530888 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100889 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
890 UDP udpPacket = (UDP) ipv4Packet.getPayload();
891 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
892
Amit Ghosh47243cb2017-07-26 05:08:53 +0100893 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000894 ConnectPoint subsCp = getConnectPointOfClient(dstMac, context);
Amit Ghosh2095dc62017-09-25 20:56:55 +0100895 // If we can't find the subscriber, can't process further
896 if (subsCp == null) {
Carmelo Casconede1e6e32019-07-15 19:39:08 -0700897 log.warn("Couldn't find connection point for mac address {} DHCPOFFERs won't be delivered", dstMac);
Amit Ghosh2095dc62017-09-25 20:56:55 +0100898 return null;
899 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100900
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000901 SubscriberAndDeviceInformation entry = getSubscriberInfoFromServer(dhcpPayload, context);
902
Thomas Lee S0dc9a3b2020-01-14 10:42:29 +0530903 // if it's an ACK packet store the information for display purpose
904 if ((getDhcpPacketType(dhcpPayload) == DHCP.MsgType.DHCPACK) && (entry != null)) {
905
906 IpAddress ip = IpAddress.valueOf(dhcpPayload.getYourIPAddress());
907 //storeDHCPAllocationInfo
908 DhcpAllocationInfo info = new DhcpAllocationInfo(subsCp,
909 dhcpPayload.getPacketType(), entry.circuitId(), dstMac, ip);
910 allocationMap.put(entry.id(), info);
911 log.debug("DHCP Allocation Map {} is updated", allocationMap);
912
913 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info, subsCp));
914 } // end storing of info
915
916
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000917 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, entry);
918 if (uniTagInformation == null) {
919 log.warn("Missing service information for connectPoint {} / cTag {}",
920 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
921 return null;
922 }
923
Marcos Aurelio Carreroeaf02b82019-11-25 13:34:25 -0300924 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_FROM_SERVER"));
925
Amit Ghosh47243cb2017-07-26 05:08:53 +0100926 // we leave the srcMac from the original packet
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000927 etherReply.setQinQVID(VlanId.NO_VID);
928 etherReply.setQinQPriorityCode((byte) 0);
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530929 etherReply.setDestinationMACAddress(dstMac);
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000930 etherReply.setVlanID(uniTagInformation.getPonCTag().toShort());
931 if (uniTagInformation.getUsPonCTagPriority() != -1) {
932 etherReply.setPriorityCode((byte) uniTagInformation.getUsPonCTagPriority());
933 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100934
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000935 if (option82) {
936 udpPacket.setPayload(removeOption82(dhcpPayload));
937 } else {
938 udpPacket.setPayload(dhcpPayload);
939 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100940 ipv4Packet.setPayload(udpPacket);
941 etherReply.setPayload(ipv4Packet);
942
Saurav Das15626a02018-09-27 18:36:45 -0700943 log.info("Finished processing packet.. relaying to client");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100944 return etherReply;
945 }
946
Amit Ghosha17354e2017-08-23 12:56:04 +0100947 /*
948 * Get ConnectPoint of the Client based on it's MAC address
949 */
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000950 private ConnectPoint getConnectPointOfClient(MacAddress dstMac, PacketContext context) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100951 Set<Host> hosts = hostService.getHostsByMac(dstMac);
952 if (hosts == null || hosts.isEmpty()) {
953 log.warn("Cannot determine host for DHCP client: {}. Aborting "
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530954 + "relay for dhcp packet from server",
Amit Ghosha17354e2017-08-23 12:56:04 +0100955 dstMac);
956 return null;
957 }
958 for (Host h : hosts) {
959 // if more than one,
960 // find the connect point which has an valid entry in SADIS
961 ConnectPoint cp = new ConnectPoint(h.location().deviceId(),
962 h.location().port());
963
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000964 String portId = nasPortId(cp);
965 SubscriberAndDeviceInformation sub = subsService.get(portId);
966 if (sub == null) {
967 log.warn("Subscriber info not found for {}", cp);
968 return null;
Amit Ghosha17354e2017-08-23 12:56:04 +0100969 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100970
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000971 UniTagInformation uniTagInformation = getUnitagInformationFromPacketContext(context, sub);
972 if (uniTagInformation == null) {
973 log.warn("Missing service information for connectPoint {} / cTag {}",
974 context.inPacket().receivedFrom(), context.inPacket().parsed().getVlanID());
975 return null;
976 }
977 return cp;
978 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100979 return null;
980 }
981
Amit Ghosh47243cb2017-07-26 05:08:53 +0100982 //send the response to the requester host.
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000983 private void sendReply(Ethernet ethPacket, DHCP dhcpPayload, PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100984 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Gamze Abakaa64b3bc2020-01-31 06:51:43 +0000985 ConnectPoint subCp = getConnectPointOfClient(descMac, context);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100986
987 // Send packet out to requester if the host information is available
Amit Ghosha17354e2017-08-23 12:56:04 +0100988 if (subCp != null) {
Saurav Das15626a02018-09-27 18:36:45 -0700989 log.info("Sending DHCP packet to client at {}", subCp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100990 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosha17354e2017-08-23 12:56:04 +0100991 .setOutput(subCp.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100992 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosha17354e2017-08-23 12:56:04 +0100993 subCp.deviceId(), t, ByteBuffer.wrap(ethPacket.serialize()));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100994 if (log.isTraceEnabled()) {
Saurav Das15626a02018-09-27 18:36:45 -0700995 log.trace("Relaying packet to dhcp client at {} {}", subCp,
996 ethPacket);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100997 }
998 packetService.emit(o);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100999 } else {
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001000 log.error("Dropping DHCP packet because can't find host for {}", descMac);
Amit Ghosh47243cb2017-07-26 05:08:53 +01001001 }
1002 }
1003 }
1004
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001005 private DHCP addOption82(DHCP dhcpPacket, SubscriberAndDeviceInformation entry) {
1006 log.debug("option82data {} ", entry);
1007
Jonathan Hartedbf6422018-05-02 17:30:05 -07001008 List<DhcpOption> options = Lists.newArrayList(dhcpPacket.getOptions());
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001009 DhcpOption82 option82 = new DhcpOption82();
1010 option82.setAgentCircuitId(entry.circuitId());
1011 option82.setAgentRemoteId(entry.remoteId());
Jonathan Hartedbf6422018-05-02 17:30:05 -07001012 DhcpOption option = new DhcpOption()
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +05301013 .setCode(DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
1014 .setData(option82.toByteArray())
1015 .setLength(option82.length());
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001016
1017 options.add(options.size() - 1, option);
1018 dhcpPacket.setOptions(options);
Amit Ghosh8951f042017-08-10 13:48:10 +01001019
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001020 return dhcpPacket;
1021
1022 }
1023
1024 private DHCP removeOption82(DHCP dhcpPacket) {
Jonathan Hartedbf6422018-05-02 17:30:05 -07001025 List<DhcpOption> options = dhcpPacket.getOptions();
1026 List<DhcpOption> newoptions = options.stream()
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001027 .filter(option -> option.getCode() != DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
1028 .collect(Collectors.toList());
1029
1030 return dhcpPacket.setOptions(newoptions);
1031 }
Amit Ghosh47243cb2017-07-26 05:08:53 +01001032 /**
1033 * Listener for network config events.
1034 */
1035 private class InternalConfigListener implements NetworkConfigListener {
1036
1037 @Override
1038 public void event(NetworkConfigEvent event) {
1039
1040 if ((event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
1041 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED) &&
1042 event.configClass().equals(DhcpL2RelayConfig.class)) {
1043 updateConfig();
1044 log.info("Reconfigured");
1045 }
1046 }
1047 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001048
Amit Ghosh8951f042017-08-10 13:48:10 +01001049 /**
1050 * Handles Mastership changes for the devices which connect
1051 * to the DHCP server.
1052 */
1053 private class InnerMastershipListener implements MastershipListener {
1054 @Override
1055 public void event(MastershipEvent event) {
Amit Ghosh83c8c892017-11-09 11:08:27 +00001056 if (!useOltUplink) {
1057 if (dhcpServerConnectPoint.get() != null &&
1058 dhcpServerConnectPoint.get().deviceId().
1059 equals(event.subject())) {
1060 log.trace("Mastership Event recevived for {}", event.subject());
1061 // mastership of the device for our connect point has changed
1062 // reselect
1063 selectServerConnectPoint();
1064 }
Amit Ghosh8951f042017-08-10 13:48:10 +01001065 }
1066 }
1067 }
Deepa vaddireddy0060f532017-08-04 06:46:05 +00001068
Amit Ghosh8951f042017-08-10 13:48:10 +01001069 /**
1070 * Handles Device status change for the devices which connect
1071 * to the DHCP server.
1072 */
1073 private class InnerDeviceListener implements DeviceListener {
1074 @Override
1075 public void event(DeviceEvent event) {
Thomas Lee S9df15082019-12-23 11:31:15 +05301076 switch (event.type()) {
1077 case DEVICE_AVAILABILITY_CHANGED:
1078 log.info("Device Avail Changed {}", event.subject().id());
1079 DeviceId deviceId = event.subject().id();
1080 if (!deviceService.isAvailable(deviceId)) {
1081 log.warn("Device {} is not available ", deviceId);
1082 allocationMap.entrySet().removeIf(entry -> deviceId.equals(entry.getValue().
1083 location().deviceId()));
1084 log.info("Device {} is removed from DHCP allocationmap ", deviceId);
1085 }
1086 break;
Thomas Lee S6b77ad22020-01-10 11:27:43 +05301087 case PORT_REMOVED:
1088 Port port = event.port();
1089 deviceId = event.subject().id();
1090 log.info("Port {} is deleted on device {}", port, deviceId);
1091 allocationMap.entrySet().removeIf(entry -> port.number().equals(entry.getValue().
1092 location().port()) && deviceId.equals(entry.getValue().location().deviceId()));
1093 log.info("Port {} on device {} is removed from DHCP allocationmap", event.port(), deviceId);
1094 break;
Thomas Lee S9df15082019-12-23 11:31:15 +05301095 default:
1096 break;
1097 }
Saurav Das15626a02018-09-27 18:36:45 -07001098 if (log.isTraceEnabled() &&
1099 !event.type().equals(DeviceEvent.Type.PORT_STATS_UPDATED)) {
1100 log.trace("Device Event received for {} event {}",
1101 event.subject(), event.type());
1102 }
Amit Ghosh83c8c892017-11-09 11:08:27 +00001103 if (!useOltUplink) {
1104 if (dhcpServerConnectPoint.get() == null) {
1105 switch (event.type()) {
1106 case DEVICE_ADDED:
1107 case DEVICE_AVAILABILITY_CHANGED:
Saurav Dasb14f08a2019-02-22 16:34:15 -08001108 // some device is available check if we can get a
1109 // connect point we can use
1110 addOrRemoveDhcpTrapFromServer(true);
Amit Ghosh83c8c892017-11-09 11:08:27 +00001111 break;
1112 default:
1113 break;
1114 }
1115 return;
Amit Ghosh8951f042017-08-10 13:48:10 +01001116 }
Amit Ghosh83c8c892017-11-09 11:08:27 +00001117 if (dhcpServerConnectPoint.get().deviceId().
1118 equals(event.subject().id())) {
1119 switch (event.type()) {
1120 case DEVICE_AVAILABILITY_CHANGED:
1121 case DEVICE_REMOVED:
1122 case DEVICE_SUSPENDED:
1123 // state of our device has changed, check if we need
Saurav Dasb14f08a2019-02-22 16:34:15 -08001124 // to re-select a connectpoint
1125 addOrRemoveDhcpTrapFromServer(true);
Amit Ghosh83c8c892017-11-09 11:08:27 +00001126 break;
1127 default:
1128 break;
1129 }
1130 }
1131 } else {
Amit Ghosh8951f042017-08-10 13:48:10 +01001132 switch (event.type()) {
Amit Ghosh83c8c892017-11-09 11:08:27 +00001133 case PORT_ADDED:
Saurav Dasb4e3e102018-10-02 15:31:17 -07001134 if (useOltUplink && isUplinkPortOfOlt(event.subject().id(), event.port())) {
Saurav Dasb14f08a2019-02-22 16:34:15 -08001135 requestDhcpPacketsFromConnectPoint(
1136 new ConnectPoint(event.subject().id(), event.port().number()),
David K. Bainbridge17d0f092020-01-23 10:15:06 -08001137 Optional.ofNullable(null));
Amit Ghosh83c8c892017-11-09 11:08:27 +00001138 }
Amit Ghosh8951f042017-08-10 13:48:10 +01001139 break;
1140 default:
1141 break;
1142 }
1143 }
1144 }
1145 }
Amit Ghosh47243cb2017-07-26 05:08:53 +01001146}