blob: 39e1cb3bb6c4f8e27f98d2a8bea5c3bbd1dc2a34 [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;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100104import org.osgi.service.component.ComponentContext;
105import org.slf4j.Logger;
106import org.slf4j.LoggerFactory;
107
Saurav Das15626a02018-09-27 18:36:45 -0700108import com.google.common.collect.ImmutableSet;
109import com.google.common.collect.Lists;
110import com.google.common.collect.Maps;
111import com.google.common.collect.Sets;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100112
113/**
114 * DHCP Relay Agent Application Component.
115 */
Jonathan Hartc36c9552018-07-31 15:07:53 -0400116@Service
Amit Ghosh47243cb2017-07-26 05:08:53 +0100117@Component(immediate = true)
Jonathan Hartc36c9552018-07-31 15:07:53 -0400118public class DhcpL2Relay
119 extends AbstractListenerManager<DhcpL2RelayEvent, DhcpL2RelayListener>
120 implements DhcpL2RelayService {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100121
122 public static final String DHCP_L2RELAY_APP = "org.opencord.dhcpl2relay";
Saurav Dasb4e3e102018-10-02 15:31:17 -0700123 private static final String HOST_LOC_PROVIDER =
124 "org.onosproject.provider.host.impl.HostLocationProvider";
Amit Ghosh47243cb2017-07-26 05:08:53 +0100125 private final Logger log = LoggerFactory.getLogger(getClass());
126 private final InternalConfigListener cfgListener =
127 new InternalConfigListener();
128
129 private final Set<ConfigFactory> factories = ImmutableSet.of(
130 new ConfigFactory<ApplicationId, DhcpL2RelayConfig>(APP_SUBJECT_FACTORY,
131 DhcpL2RelayConfig.class,
132 "dhcpl2relay") {
133 @Override
134 public DhcpL2RelayConfig createConfig() {
135 return new DhcpL2RelayConfig();
136 }
137 }
138 );
139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
141 protected NetworkConfigRegistry cfgService;
142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
144 protected CoreService coreService;
145
146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
147 protected PacketService packetService;
148
149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
150 protected HostService hostService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
153 protected ComponentConfigService componentConfigService;
154
155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Gamze Abakac806c6c2018-12-03 12:49:46 +0000156 protected SadisService sadisService;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100157
158 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
159 protected DeviceService deviceService;
160
Amit Ghosh8951f042017-08-10 13:48:10 +0100161 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
162 protected MastershipService mastershipService;
163
Saurav Dasb4e3e102018-10-02 15:31:17 -0700164 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
165 protected FlowObjectiveService flowObjectiveService;
166
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300167 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
168 protected DhcpL2RelayCountersStore dhcpL2RelayCounters;
169
170 protected PublishCountersToKafka publishCountersToKafka;
171
Amit Ghosh47243cb2017-07-26 05:08:53 +0100172 @Property(name = "option82", boolValue = true,
173 label = "Add option 82 to relayed packets")
174 protected boolean option82 = true;
175
Amit Ghosha17354e2017-08-23 12:56:04 +0100176 @Property(name = "enableDhcpBroadcastReplies", boolValue = false,
Amit Ghosh2095dc62017-09-25 20:56:55 +0100177 label = "Ask the DHCP Server to send back replies as L2 broadcast")
Amit Ghosha17354e2017-08-23 12:56:04 +0100178 protected boolean enableDhcpBroadcastReplies = false;
179
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300180 private static final int DEFAULT_RATE = 10;
181 @Property(name = "publishCountersRate", intValue = DEFAULT_RATE,
182 label = "The interval in seconds between calls to publish the DHCP counters to Kafka")
183 protected int publishCountersRate = 0;
184
185 ScheduledFuture<?> refreshTask;
186 ScheduledExecutorService refreshService = Executors.newSingleThreadScheduledExecutor();
187
188 private static final String DEFAULT_DHCP_COUNTERS_TOPIC = "onos_traffic.stats";
189 @Property(name = "dhcpCountersTopic", value = DEFAULT_DHCP_COUNTERS_TOPIC,
190 label = "The topic where to publish the DHCP L2 Relay counters to Kafka")
191 private String dhcpCountersTopic = DEFAULT_DHCP_COUNTERS_TOPIC;
192
Amit Ghosh47243cb2017-07-26 05:08:53 +0100193 private DhcpRelayPacketProcessor dhcpRelayPacketProcessor =
194 new DhcpRelayPacketProcessor();
195
Amit Ghosh8951f042017-08-10 13:48:10 +0100196 private InnerMastershipListener changeListener = new InnerMastershipListener();
197 private InnerDeviceListener deviceListener = new InnerDeviceListener();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100198
Amit Ghosh8951f042017-08-10 13:48:10 +0100199 // connect points to the DHCP server
200 Set<ConnectPoint> dhcpConnectPoints;
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300201 protected AtomicReference<ConnectPoint> dhcpServerConnectPoint = new AtomicReference<>();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100202 private MacAddress dhcpConnectMac = MacAddress.BROADCAST;
203 private ApplicationId appId;
204
Amit Ghosha17354e2017-08-23 12:56:04 +0100205 static Map<String, DhcpAllocationInfo> allocationMap = Maps.newConcurrentMap();
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300206 protected boolean modifyClientPktsSrcDstMac = false;
Amit Ghosh83c8c892017-11-09 11:08:27 +0000207 //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 -0300208 protected boolean useOltUplink = false;
Amit Ghosha17354e2017-08-23 12:56:04 +0100209
Gamze Abakac806c6c2018-12-03 12:49:46 +0000210 private BaseInformationService<SubscriberAndDeviceInformation> subsService;
211
Amit Ghosh47243cb2017-07-26 05:08:53 +0100212 @Activate
213 protected void activate(ComponentContext context) {
214 //start the dhcp relay agent
215 appId = coreService.registerApplication(DHCP_L2RELAY_APP);
Saurav Dasb4e3e102018-10-02 15:31:17 -0700216 // ensure that host-learning via dhcp includes IP addresses
217 componentConfigService.preSetProperty(HOST_LOC_PROVIDER,
218 "useDhcp", Boolean.TRUE.toString());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100219 componentConfigService.registerProperties(getClass());
Jonathan Hartc36c9552018-07-31 15:07:53 -0400220 eventDispatcher.addSink(DhcpL2RelayEvent.class, listenerRegistry);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100221
222 cfgService.addListener(cfgListener);
Amit Ghosh8951f042017-08-10 13:48:10 +0100223 mastershipService.addListener(changeListener);
224 deviceService.addListener(deviceListener);
225
Matteo Scandolof8da6572019-09-30 09:30:32 -0700226 subsService = sadisService.getSubscriberInfoService();
227
Amit Ghosh47243cb2017-07-26 05:08:53 +0100228 factories.forEach(cfgService::registerConfigFactory);
229 //update the dhcp server configuration.
230 updateConfig();
231 //add the packet services.
232 packetService.addProcessor(dhcpRelayPacketProcessor,
233 PacketProcessor.director(0));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000234 if (context != null) {
235 modified(context);
236 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100237
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300238 publishCountersToKafka = new PublishCountersToKafka();
239 subsService = sadisService.getSubscriberInfoService();
240 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
576 private SubscriberAndDeviceInformation getDevice(ConnectPoint cp) {
577 String serialNo = deviceService.getDevice(cp.deviceId()).
578 serialNumber();
579
580 return subsService.get(serialNo);
581 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100582
583 private MacAddress relayAgentMacAddress(PacketContext context) {
584
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000585 SubscriberAndDeviceInformation device = this.getDevice(context);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100586 if (device == null) {
587 log.warn("Device not found for {}", context.inPacket().
588 receivedFrom());
589 return null;
590 }
591
592 return device.hardwareIdentifier();
593 }
594
595 private String nasPortId(PacketContext context) {
Amit Ghosh8951f042017-08-10 13:48:10 +0100596 return nasPortId(context.inPacket().receivedFrom());
597 }
598
599 private String nasPortId(ConnectPoint cp) {
600 Port p = deviceService.getPort(cp);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100601 return p.annotations().value(AnnotationKeys.PORT_NAME);
602 }
603
604 private SubscriberAndDeviceInformation getSubscriber(PacketContext context) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100605 return subsService.get(nasPortId(context));
606 }
607
608 private VlanId cTag(PacketContext context) {
609 SubscriberAndDeviceInformation sub = getSubscriber(context);
610 if (sub == null) {
611 log.warn("Subscriber info not found for {}", context.inPacket().
612 receivedFrom());
613 return VlanId.NONE;
614 }
615 return sub.cTag();
616 }
617
Amit Ghosh8951f042017-08-10 13:48:10 +0100618 private VlanId cTag(ConnectPoint cp) {
619 String portId = nasPortId(cp);
620 SubscriberAndDeviceInformation sub = subsService.get(portId);
621 if (sub == null) {
622 log.warn("Subscriber info not found for {} looking for C-TAG", cp);
623 return VlanId.NONE;
624 }
625 return sub.cTag();
626 }
627
628 private VlanId sTag(ConnectPoint cp) {
629 String portId = nasPortId(cp);
630 SubscriberAndDeviceInformation sub = subsService.get(portId);
631 if (sub == null) {
632 log.warn("Subscriber info not found for {} looking for S-TAG", cp);
633 return VlanId.NONE;
634 }
635 return sub.sTag();
636 }
637
Amit Ghosh47243cb2017-07-26 05:08:53 +0100638 private VlanId sTag(PacketContext context) {
639 SubscriberAndDeviceInformation sub = getSubscriber(context);
640 if (sub == null) {
641 log.warn("Subscriber info not found for {}", context.inPacket().
642 receivedFrom());
643 return VlanId.NONE;
644 }
645 return sub.sTag();
646 }
647
648 private class DhcpRelayPacketProcessor implements PacketProcessor {
649
650 @Override
651 public void process(PacketContext context) {
652 if (!configured()) {
653 log.warn("Missing DHCP relay config. Abort packet processing");
654 return;
655 }
656
657 // process the packet and get the payload
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530658 Ethernet packet = context.inPacket().parsed();
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000659
Amit Ghosh47243cb2017-07-26 05:08:53 +0100660 if (packet == null) {
661 log.warn("Packet is null");
662 return;
663 }
664
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530665 if (packet.getEtherType() == Ethernet.TYPE_IPV4) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100666 IPv4 ipv4Packet = (IPv4) packet.getPayload();
667
668 if (ipv4Packet.getProtocol() == IPv4.PROTOCOL_UDP) {
669 UDP udpPacket = (UDP) ipv4Packet.getPayload();
670 if (udpPacket.getSourcePort() == UDP.DHCP_CLIENT_PORT ||
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000671 udpPacket.getSourcePort() == UDP.DHCP_SERVER_PORT) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100672 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
673 //This packet is dhcp.
674 processDhcpPacket(context, packet, dhcpPayload);
675 }
676 }
677 }
678 }
679
680 //forward the packet to ConnectPoint where the DHCP server is attached.
Amit Ghosh83c8c892017-11-09 11:08:27 +0000681 private void forwardPacket(Ethernet packet, PacketContext context) {
682 ConnectPoint toSendTo = null;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100683
Amit Ghosh83c8c892017-11-09 11:08:27 +0000684 if (!useOltUplink) {
685 toSendTo = dhcpServerConnectPoint.get();
686 } else {
687 toSendTo = getUplinkConnectPointOfOlt(context.inPacket().
688 receivedFrom().deviceId());
689 }
690
691 if (toSendTo != null) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100692 TrafficTreatment t = DefaultTrafficTreatment.builder()
Amit Ghosh83c8c892017-11-09 11:08:27 +0000693 .setOutput(toSendTo.port()).build();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100694 OutboundPacket o = new DefaultOutboundPacket(
Amit Ghosh83c8c892017-11-09 11:08:27 +0000695 toSendTo.deviceId(), t,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100696 ByteBuffer.wrap(packet.serialize()));
697 if (log.isTraceEnabled()) {
Saurav Das15626a02018-09-27 18:36:45 -0700698 log.trace("Relaying packet to dhcp server at {} {}",
699 toSendTo, packet);
Amit Ghosh47243cb2017-07-26 05:08:53 +0100700 }
701 packetService.emit(o);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300702
703 SubscriberAndDeviceInformation entry = getSubscriberInfoFromClient(context);
704 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_TO_SERVER"));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100705 } else {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000706 log.error("No connect point to send msg to DHCP Server");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100707 }
708 }
709
Amit Ghosha17354e2017-08-23 12:56:04 +0100710 // get the type of the DHCP packet
711 private DHCPPacketType getDhcpPacketType(DHCP dhcpPayload) {
712
Jonathan Hartedbf6422018-05-02 17:30:05 -0700713 for (DhcpOption option : dhcpPayload.getOptions()) {
Amit Ghosha17354e2017-08-23 12:56:04 +0100714 if (option.getCode() == OptionCode_MessageType.getValue()) {
715 byte[] data = option.getData();
716 return DHCPPacketType.getType(data[0]);
717 }
718 }
719 return null;
720 }
721
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300722 private void updateDhcpRelayCountersStore(SubscriberAndDeviceInformation entry,
723 DhcpL2RelayCounters counterType) {
724 // Update global counter stats
725 dhcpL2RelayCounters.incrementCounter(DhcpL2RelayCountersIdentifier.GLOBAL_COUNTER, counterType);
726 if (entry == null) {
727 log.warn("Counter not updated as subscriber info not found.");
728 } else {
729 // Update subscriber counter stats
730 dhcpL2RelayCounters.incrementCounter(entry.id(), counterType);
731 }
732 }
733
734 /*
735 * Get subscriber information based on it's context packet.
736 */
737 private SubscriberAndDeviceInformation getSubscriberInfoFromClient(PacketContext context) {
738 if (context != null) {
739 return getSubscriber(context);
740 }
741 return null;
742 }
743
744 /*
745 * Get subscriber information based on it's DHCP payload.
746 */
747 private SubscriberAndDeviceInformation getSubscriberInfoFromServer(DHCP dhcpPayload) {
748 if (dhcpPayload != null) {
749 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
750 ConnectPoint subsCp = getConnectPointOfClient(descMac);
751
752 if (subsCp != null) {
753 String portId = nasPortId(subsCp);
754 return subsService.get(portId);
755 }
756 }
757 return null;
758 }
759
Amit Ghosh47243cb2017-07-26 05:08:53 +0100760 //process the dhcp packet before sending to server
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530761 private void processDhcpPacket(PacketContext context, Ethernet packet,
Amit Ghosh47243cb2017-07-26 05:08:53 +0100762 DHCP dhcpPayload) {
763 if (dhcpPayload == null) {
764 log.warn("DHCP payload is null");
765 return;
766 }
767
Amit Ghosha17354e2017-08-23 12:56:04 +0100768 DHCPPacketType incomingPacketType = getDhcpPacketType(dhcpPayload);
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300769 if (incomingPacketType == null) {
770 log.warn("DHCP packet type not found. Dump of ethernet pkt in hex format for troubleshooting.");
771 byte[] array = packet.serialize();
772 ByteArrayOutputStream buf = new ByteArrayOutputStream();
773 try {
774 HexDump.dump(array, 0, buf, 0);
775 log.trace(buf.toString());
776 } catch (Exception e) { }
777 return;
778 }
779
780 SubscriberAndDeviceInformation entry = null;
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000781
Saurav Das15626a02018-09-27 18:36:45 -0700782 log.info("Received DHCP Packet of type {} from {}",
783 incomingPacketType, context.inPacket().receivedFrom());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100784
785 switch (incomingPacketType) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000786 case DHCPDISCOVER:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530787 Ethernet ethernetPacketDiscover =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000788 processDhcpPacketFromClient(context, packet);
789 if (ethernetPacketDiscover != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000790 forwardPacket(ethernetPacketDiscover, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000791 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300792 entry = getSubscriberInfoFromClient(context);
793 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDISCOVER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000794 break;
795 case DHCPOFFER:
796 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700797 Ethernet ethernetPacketOffer =
798 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000799 if (ethernetPacketOffer != null) {
800 sendReply(ethernetPacketOffer, dhcpPayload);
801 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300802 entry = getSubscriberInfoFromServer(dhcpPayload);
803 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPOFFER"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000804 break;
805 case DHCPREQUEST:
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530806 Ethernet ethernetPacketRequest =
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000807 processDhcpPacketFromClient(context, packet);
808 if (ethernetPacketRequest != null) {
Amit Ghosh83c8c892017-11-09 11:08:27 +0000809 forwardPacket(ethernetPacketRequest, context);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000810 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300811 entry = getSubscriberInfoFromClient(context);
812 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPREQUEST"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000813 break;
814 case DHCPACK:
815 //reply to dhcp client.
Saurav Das15626a02018-09-27 18:36:45 -0700816 Ethernet ethernetPacketAck =
817 processDhcpPacketFromServer(context, packet);
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000818 if (ethernetPacketAck != null) {
819 sendReply(ethernetPacketAck, dhcpPayload);
820 }
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300821 entry = getSubscriberInfoFromServer(dhcpPayload);
822 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPACK"));
823 break;
824 case DHCPDECLINE:
825 entry = getSubscriberInfoFromClient(context);
826 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPDECLINE"));
827 break;
828 case DHCPNAK:
829 entry = getSubscriberInfoFromServer(dhcpPayload);
830 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPNACK"));
831 break;
832 case DHCPRELEASE:
833 entry = getSubscriberInfoFromClient(context);
834 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("DHCPRELEASE"));
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000835 break;
836 default:
837 break;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100838 }
839 }
840
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530841 private Ethernet processDhcpPacketFromClient(PacketContext context,
842 Ethernet ethernetPacket) {
Saurav Das15626a02018-09-27 18:36:45 -0700843 if (log.isTraceEnabled()) {
844 log.trace("DHCP packet received from client at {} {}",
845 context.inPacket().receivedFrom(), ethernetPacket);
846 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100847
848 MacAddress relayAgentMac = relayAgentMacAddress(context);
849 if (relayAgentMac == null) {
850 log.warn("RelayAgent MAC not found ");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100851 return null;
852 }
853
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530854 Ethernet etherReply = ethernetPacket;
Amit Ghosh47243cb2017-07-26 05:08:53 +0100855
856 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
857 UDP udpPacket = (UDP) ipv4Packet.getPayload();
858 DHCP dhcpPacket = (DHCP) udpPacket.getPayload();
859
Amit Ghosha17354e2017-08-23 12:56:04 +0100860 if (enableDhcpBroadcastReplies) {
861 // We want the reply to come back as a L2 broadcast
862 dhcpPacket.setFlags((short) 0x8000);
863 }
864
Jonathan Hartc36c9552018-07-31 15:07:53 -0400865 MacAddress clientMac = MacAddress.valueOf(dhcpPacket.getClientHardwareAddress());
866 IpAddress clientIp = IpAddress.valueOf(dhcpPacket.getClientIPAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100867
Jonathan Hartc36c9552018-07-31 15:07:53 -0400868 SubscriberAndDeviceInformation entry = getSubscriber(context);
869 if (entry == null) {
Saurav Das15626a02018-09-27 18:36:45 -0700870 log.warn("Dropping packet as subscriber entry is not available");
Jonathan Hartc36c9552018-07-31 15:07:53 -0400871 return null;
872 }
873
874 DhcpAllocationInfo info = new DhcpAllocationInfo(
875 context.inPacket().receivedFrom(), dhcpPacket.getPacketType(),
876 entry.nasPortId(), clientMac, clientIp);
877
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300878 allocationMap.put(entry.id(), info);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400879
Saurav Das15626a02018-09-27 18:36:45 -0700880 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info,
881 context.inPacket().receivedFrom()));
Amit Ghosha17354e2017-08-23 12:56:04 +0100882
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000883 if (option82) {
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000884 DHCP dhcpPacketWithOption82 = addOption82(dhcpPacket, entry);
885 udpPacket.setPayload(dhcpPacketWithOption82);
886 }
887
888 ipv4Packet.setPayload(udpPacket);
889 etherReply.setPayload(ipv4Packet);
Amit Ghosh83c8c892017-11-09 11:08:27 +0000890 if (modifyClientPktsSrcDstMac) {
891 etherReply.setSourceMACAddress(relayAgentMac);
892 etherReply.setDestinationMACAddress(dhcpConnectMac);
893 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100894
Amit Ghosh8951f042017-08-10 13:48:10 +0100895 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
Amit Ghosh47243cb2017-07-26 05:08:53 +0100896 etherReply.setVlanID(cTag(context).toShort());
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530897 etherReply.setQinQTPID(Ethernet.TYPE_VLAN);
898 etherReply.setQinQVID(sTag(context).toShort());
Saurav Das15626a02018-09-27 18:36:45 -0700899 log.info("Finished processing packet.. relaying to dhcpServer");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100900 return etherReply;
901 }
902
903 //build the DHCP offer/ack with proper client port.
Saurav Das15626a02018-09-27 18:36:45 -0700904 private Ethernet processDhcpPacketFromServer(PacketContext context,
905 Ethernet ethernetPacket) {
906 if (log.isTraceEnabled()) {
907 log.trace("DHCP packet received from server at {} {}",
908 context.inPacket().receivedFrom(), ethernetPacket);
909 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100910 // get dhcp header.
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530911 Ethernet etherReply = (Ethernet) ethernetPacket.clone();
Amit Ghosh47243cb2017-07-26 05:08:53 +0100912 IPv4 ipv4Packet = (IPv4) etherReply.getPayload();
913 UDP udpPacket = (UDP) ipv4Packet.getPayload();
914 DHCP dhcpPayload = (DHCP) udpPacket.getPayload();
915
Amit Ghosh47243cb2017-07-26 05:08:53 +0100916 MacAddress dstMac = valueOf(dhcpPayload.getClientHardwareAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +0100917 ConnectPoint subsCp = getConnectPointOfClient(dstMac);
Amit Ghosh2095dc62017-09-25 20:56:55 +0100918 // If we can't find the subscriber, can't process further
919 if (subsCp == null) {
920 return null;
921 }
Amit Ghosha17354e2017-08-23 12:56:04 +0100922 // if it's an ACK packet store the information for display purpose
923 if (getDhcpPacketType(dhcpPayload) == DHCPPacketType.DHCPACK) {
Amit Ghosh47243cb2017-07-26 05:08:53 +0100924
Amit Ghosha17354e2017-08-23 12:56:04 +0100925 String portId = nasPortId(subsCp);
926 SubscriberAndDeviceInformation sub = subsService.get(portId);
927 if (sub != null) {
Jonathan Hartedbf6422018-05-02 17:30:05 -0700928 List<DhcpOption> options = dhcpPayload.getOptions();
929 List<DhcpOption> circuitIds = options.stream()
Amit Ghosha17354e2017-08-23 12:56:04 +0100930 .filter(option -> option.getCode() == DHCP.DHCPOptionCode.OptionCode_CircuitID.getValue())
931 .collect(Collectors.toList());
932
933 String circuitId = "None";
934 if (circuitIds.size() == 1) {
Amit Ghosh2095dc62017-09-25 20:56:55 +0100935 byte[] array = circuitIds.get(0).getData();
936
937 try {
938 // we leave the first two bytes as they are the id and length
939 circuitId = new String(Arrays.copyOfRange(array, 2, array.length), "UTF-8");
940 } catch (Exception e) { }
Amit Ghosha17354e2017-08-23 12:56:04 +0100941 }
942
943 IpAddress ip = IpAddress.valueOf(dhcpPayload.getYourIPAddress());
944
945 //storeDHCPAllocationInfo
Jonathan Hartc36c9552018-07-31 15:07:53 -0400946 DhcpAllocationInfo info = new DhcpAllocationInfo(subsCp,
947 dhcpPayload.getPacketType(), circuitId, dstMac, ip);
Amit Ghosha17354e2017-08-23 12:56:04 +0100948
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300949 allocationMap.put(sub.id(), info);
Jonathan Hartc36c9552018-07-31 15:07:53 -0400950
951 post(new DhcpL2RelayEvent(DhcpL2RelayEvent.Type.UPDATED, info, subsCp));
Amit Ghosha17354e2017-08-23 12:56:04 +0100952 }
953 } // end storing of info
Amit Ghosh47243cb2017-07-26 05:08:53 +0100954
Marcos Aurelio Carrerodadb3572019-11-25 13:34:25 -0300955 SubscriberAndDeviceInformation entry = getSubscriberInfoFromServer(dhcpPayload);
956 updateDhcpRelayCountersStore(entry, DhcpL2RelayCounters.valueOf("PACKETS_FROM_SERVER"));
957
Amit Ghosh47243cb2017-07-26 05:08:53 +0100958 // we leave the srcMac from the original packet
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530959 etherReply.setDestinationMACAddress(dstMac);
960 etherReply.setQinQVID(sTag(subsCp).toShort());
Amit Ghosh8951f042017-08-10 13:48:10 +0100961 etherReply.setPriorityCode(ethernetPacket.getPriorityCode());
962 etherReply.setVlanID((cTag(subsCp).toShort()));
Amit Ghosh47243cb2017-07-26 05:08:53 +0100963
Deepa vaddireddy0060f532017-08-04 06:46:05 +0000964 if (option82) {
965 udpPacket.setPayload(removeOption82(dhcpPayload));
966 } else {
967 udpPacket.setPayload(dhcpPayload);
968 }
Amit Ghosh47243cb2017-07-26 05:08:53 +0100969 ipv4Packet.setPayload(udpPacket);
970 etherReply.setPayload(ipv4Packet);
971
Saurav Das15626a02018-09-27 18:36:45 -0700972 log.info("Finished processing packet.. relaying to client");
Amit Ghosh47243cb2017-07-26 05:08:53 +0100973 return etherReply;
974 }
975
Amit Ghosha17354e2017-08-23 12:56:04 +0100976 /*
977 * Get ConnectPoint of the Client based on it's MAC address
978 */
979 private ConnectPoint getConnectPointOfClient(MacAddress dstMac) {
980 Set<Host> hosts = hostService.getHostsByMac(dstMac);
981 if (hosts == null || hosts.isEmpty()) {
982 log.warn("Cannot determine host for DHCP client: {}. Aborting "
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +0530983 + "relay for dhcp packet from server",
Amit Ghosha17354e2017-08-23 12:56:04 +0100984 dstMac);
985 return null;
986 }
987 for (Host h : hosts) {
988 // if more than one,
989 // find the connect point which has an valid entry in SADIS
990 ConnectPoint cp = new ConnectPoint(h.location().deviceId(),
991 h.location().port());
992
993 if (sTag(cp) != VlanId.NONE) {
994 return cp;
995 }
996 }
997
998 return null;
999 }
1000
Amit Ghosh47243cb2017-07-26 05:08:53 +01001001 //send the response to the requester host.
Deepa Vaddireddy5f278d62017-08-30 05:59:39 +05301002 private void sendReply(Ethernet ethPacket, DHCP dhcpPayload) {
Amit Ghosh47243cb2017-07-26 05:08:53 +01001003 MacAddress descMac = valueOf(dhcpPayload.getClientHardwareAddress());
Amit Ghosha17354e2017-08-23 12:56:04 +01001004 ConnectPoint subCp = getConnectPointOfClient(descMac);
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()),
1134 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}