blob: b804c6d5df7f05514e0585256f9b1bab8e1c90d4 [file] [log] [blame]
Thomas Vachuska781d18b2014-10-27 10:31:25 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
Thomas Vachuska781d18b2014-10-27 10:31:25 -07003 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07004 * 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
Thomas Vachuska781d18b2014-10-27 10:31:25 -07007 *
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07008 * 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.
Thomas Vachuska781d18b2014-10-27 10:31:25 -070015 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.provider.host.impl;
alshabibe1cf87d2014-10-17 09:23:50 -070017
Charles Chan35a32322017-08-14 11:42:11 -070018import com.google.common.collect.Sets;
Jonathan Harte8600eb2015-01-12 10:30:45 -080019import org.onlab.packet.ARP;
Yi Tsengfcf5dce2017-07-26 14:30:41 -070020import org.onlab.packet.BasePacket;
Charles Chane6067892016-11-17 10:23:46 -080021import org.onlab.packet.DHCP;
Yi Tsengfcf5dce2017-07-26 14:30:41 -070022import org.onlab.packet.DHCP6;
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -070023import org.onlab.packet.EthType;
Jonathan Harte8600eb2015-01-12 10:30:45 -080024import org.onlab.packet.Ethernet;
Pavlin Radoslavovd6612f92015-02-23 13:53:32 -080025import org.onlab.packet.ICMP6;
Thomas Vachuskaf845cf62015-03-24 10:13:09 -070026import org.onlab.packet.IPacket;
Charles Chane6067892016-11-17 10:23:46 -080027import org.onlab.packet.IPv4;
Jonathan Harte8600eb2015-01-12 10:30:45 -080028import org.onlab.packet.IPv6;
Charles Chan35a32322017-08-14 11:42:11 -070029import org.onlab.packet.Ip4Address;
Yi Tsengfcf5dce2017-07-26 14:30:41 -070030import org.onlab.packet.Ip6Address;
Jonathan Harte8600eb2015-01-12 10:30:45 -080031import org.onlab.packet.IpAddress;
Charles M.C. Chan956cb692015-04-26 18:49:39 +080032import org.onlab.packet.MacAddress;
Charles Chane6067892016-11-17 10:23:46 -080033import org.onlab.packet.UDP;
Jonathan Harte8600eb2015-01-12 10:30:45 -080034import org.onlab.packet.VlanId;
Yi Tsengfcf5dce2017-07-26 14:30:41 -070035import org.onlab.packet.dhcp.Dhcp6ClientIdOption;
36import org.onlab.packet.dhcp.Dhcp6IaAddressOption;
37import org.onlab.packet.dhcp.Dhcp6IaNaOption;
38import org.onlab.packet.dhcp.Dhcp6IaTaOption;
39import org.onlab.packet.dhcp.Dhcp6RelayOption;
Charles M.C. Chan956cb692015-04-26 18:49:39 +080040import org.onlab.packet.ipv6.IExtensionHeader;
Jonathan Harte8600eb2015-01-12 10:30:45 -080041import org.onlab.packet.ndp.NeighborAdvertisement;
42import org.onlab.packet.ndp.NeighborSolicitation;
Charles M.C. Chan441d7da2015-03-17 21:03:39 +080043import org.onlab.packet.ndp.RouterAdvertisement;
44import org.onlab.packet.ndp.RouterSolicitation;
Jian Lid9b5f552016-03-11 18:15:31 -080045import org.onlab.util.Tools;
Thomas Vachuska6519e6f2015-03-11 02:29:31 -070046import org.onosproject.cfg.ComponentConfigService;
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -080047import org.onosproject.core.ApplicationId;
48import org.onosproject.core.CoreService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070049import org.onosproject.net.ConnectPoint;
50import org.onosproject.net.Device;
51import org.onosproject.net.DeviceId;
52import org.onosproject.net.Host;
53import org.onosproject.net.HostId;
54import org.onosproject.net.HostLocation;
Andreas Pantelopoulos19416412018-06-12 13:19:52 -070055import org.onosproject.net.config.ConfigFactory;
56import org.onosproject.net.config.NetworkConfigEvent;
57import org.onosproject.net.config.NetworkConfigListener;
58import org.onosproject.net.config.NetworkConfigRegistry;
59import org.onosproject.net.config.NetworkConfigService;
60import org.onosproject.net.config.basics.BasicHostConfig;
61import org.onosproject.net.config.basics.HostLearningConfig;
62import org.onosproject.net.config.basics.SubjectFactories;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.device.DeviceEvent;
64import org.onosproject.net.device.DeviceListener;
65import org.onosproject.net.device.DeviceService;
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -080066import org.onosproject.net.flow.DefaultTrafficSelector;
sdn94b00152016-08-30 02:12:32 -070067import org.onosproject.net.flow.DefaultTrafficTreatment;
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -080068import org.onosproject.net.flow.TrafficSelector;
sdn94b00152016-08-30 02:12:32 -070069import org.onosproject.net.flow.TrafficTreatment;
Brian O'Connorabafb502014-12-02 22:26:20 -080070import org.onosproject.net.host.DefaultHostDescription;
71import org.onosproject.net.host.HostDescription;
72import org.onosproject.net.host.HostProvider;
73import org.onosproject.net.host.HostProviderRegistry;
74import org.onosproject.net.host.HostProviderService;
75import org.onosproject.net.host.HostService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070076import org.onosproject.net.intf.InterfaceService;
sdn94b00152016-08-30 02:12:32 -070077import org.onosproject.net.packet.DefaultOutboundPacket;
78import org.onosproject.net.packet.OutboundPacket;
Brian O'Connorabafb502014-12-02 22:26:20 -080079import org.onosproject.net.packet.PacketContext;
Jonathan Hart3cfce8e2015-01-14 16:43:27 -080080import org.onosproject.net.packet.PacketPriority;
Brian O'Connorabafb502014-12-02 22:26:20 -080081import org.onosproject.net.packet.PacketProcessor;
82import org.onosproject.net.packet.PacketService;
83import org.onosproject.net.provider.AbstractProvider;
84import org.onosproject.net.provider.ProviderId;
85import org.onosproject.net.topology.Topology;
86import org.onosproject.net.topology.TopologyService;
Thomas Vachuska33601602014-11-19 03:32:15 -080087import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070088import org.osgi.service.component.annotations.Activate;
89import org.osgi.service.component.annotations.Component;
90import org.osgi.service.component.annotations.Deactivate;
91import org.osgi.service.component.annotations.Modified;
92import org.osgi.service.component.annotations.Reference;
93import org.osgi.service.component.annotations.ReferenceCardinality;
alshabibe1cf87d2014-10-17 09:23:50 -070094import org.slf4j.Logger;
95
sdn94b00152016-08-30 02:12:32 -070096import java.nio.ByteBuffer;
Thomas Vachuskaf845cf62015-03-24 10:13:09 -070097import java.util.Dictionary;
Yi Tseng7a38f9a2017-06-09 14:36:40 -070098import java.util.Objects;
99import java.util.Optional;
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700100import java.util.Set;
Madan Jampania3770c32015-12-11 12:07:41 -0800101import java.util.concurrent.ExecutorService;
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700102import java.util.stream.Stream;
Thomas Vachuskaf845cf62015-03-24 10:13:09 -0700103
Madan Jampania3770c32015-12-11 12:07:41 -0800104import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
105import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuskaf845cf62015-03-24 10:13:09 -0700106import static org.slf4j.LoggerFactory.getLogger;
107
alshabibe1cf87d2014-10-17 09:23:50 -0700108/**
Thomas Vachuskaec9c7dd2015-09-03 18:30:04 -0700109 * Provider which uses an OpenFlow controller to detect network end-station
110 * hosts.
alshabibe1cf87d2014-10-17 09:23:50 -0700111 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700112@Component(immediate = true, service = HostProvider.class,
113 property = {
114 "hostRemovalEnabled:Boolean=true",
115 "requestArp:Boolean=true",
116 "requestIpv6ND:Boolean=false",
117 "useDhcp:Boolean=false",
118 "useDhcp6:Boolean=false",
119 "requestInterceptsEnabled:Boolean=true",
120 "multihomingEnabled:Boolean=false",
121 })
Charles Chanff79dd92018-06-01 16:33:48 -0700122public class HostLocationProvider extends AbstractProvider implements HostProvider {
alshabibe1cf87d2014-10-17 09:23:50 -0700123 private final Logger log = getLogger(getClass());
124
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700125 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -0800126 protected CoreService coreService;
127
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabibe1cf87d2014-10-17 09:23:50 -0700129 protected HostProviderRegistry providerRegistry;
130
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Pavlin Radoslavovd6612f92015-02-23 13:53:32 -0800132 protected PacketService packetService;
alshabibe1cf87d2014-10-17 09:23:50 -0700133
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
alshabibe1cf87d2014-10-17 09:23:50 -0700135 protected TopologyService topologyService;
136
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska33601602014-11-19 03:32:15 -0800138 protected HostService hostService;
139
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska33601602014-11-19 03:32:15 -0800141 protected DeviceService deviceService;
142
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700144 protected ComponentConfigService cfgService;
145
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700147 protected NetworkConfigRegistry registry;
148
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700150 protected InterfaceService interfaceService;
151
alshabibe1cf87d2014-10-17 09:23:50 -0700152 private final InternalHostProvider processor = new InternalHostProvider();
Thomas Vachuska33601602014-11-19 03:32:15 -0800153 private final DeviceListener deviceListener = new InternalDeviceListener();
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700154 private final InternalConfigListener cfgListener = new InternalConfigListener();
Thomas Vachuska33601602014-11-19 03:32:15 -0800155
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -0800156 private ApplicationId appId;
157
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700158 //@Property(name = "hostRemovalEnabled", boolValue = true,
159 // label = "Enable host removal on port/device down events")
Thomas Vachuska33601602014-11-19 03:32:15 -0800160 private boolean hostRemovalEnabled = true;
alshabibe1cf87d2014-10-17 09:23:50 -0700161
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700162 //@Property(name = "requestArp", boolValue = true,
163 // label = "Request ARP packets for neighbor discovery by the " +
164 // "Host Location Provider; default is true")
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700165 private boolean requestArp = true;
Charles Chane6067892016-11-17 10:23:46 -0800166
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700167 //@Property(name = "requestIpv6ND", boolValue = false,
168 // label = "Requests IPv6 Neighbor Discovery by the " +
169 // "Host Location Provider; default is false")
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700170 private boolean requestIpv6ND = false;
Charles Chane6067892016-11-17 10:23:46 -0800171
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700172 //@Property(name = "useDhcp", boolValue = false,
173 // label = "Use DHCP to update IP address of the host; default is false")
Charles Chane6067892016-11-17 10:23:46 -0800174 private boolean useDhcp = false;
alshabibe1cf87d2014-10-17 09:23:50 -0700175
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700176 //@Property(name = "useDhcp6", boolValue = false,
177 // label = "Use DHCPv6 to update IP address of the host; default is false")
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700178 private boolean useDhcp6 = false;
179
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700180 //@Property(name = "requestInterceptsEnabled", boolValue = true,
181 // label = "Enable requesting packet intercepts")
Jonathan Hart9af322d2016-01-06 17:42:04 -0800182 private boolean requestInterceptsEnabled = true;
183
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700184 //@Property(name = "multihomingEnabled", boolValue = false,
185 // label = "Allow hosts to be multihomed")
Charles Chan35a32322017-08-14 11:42:11 -0700186 private boolean multihomingEnabled = false;
Madan Jampania3770c32015-12-11 12:07:41 -0800187
Charles Chanff79dd92018-06-01 16:33:48 -0700188 private HostProviderService providerService;
Charles Chan47933752017-11-30 15:37:50 -0800189
Charles Chanff79dd92018-06-01 16:33:48 -0700190 ExecutorService deviceEventHandler;
191 private ExecutorService probeEventHandler;
Charles Chan07f15f22018-05-08 21:35:50 -0700192 private ExecutorService packetHandler;
Charles Chan8277b6b2017-12-03 13:48:46 -0800193
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700194 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700195 protected NetworkConfigService netcfgService;
196
197 private ConfigFactory<ConnectPoint, HostLearningConfig> hostLearningConfig =
198 new ConfigFactory<ConnectPoint, HostLearningConfig>(
199 SubjectFactories.CONNECT_POINT_SUBJECT_FACTORY,
200 HostLearningConfig.class, "hostLearning") {
201 @Override
202 public HostLearningConfig createConfig() {
203 return new HostLearningConfig();
204 }
205 };
206
alshabibe1cf87d2014-10-17 09:23:50 -0700207 /**
208 * Creates an OpenFlow host provider.
209 */
210 public HostLocationProvider() {
Brian O'Connorabafb502014-12-02 22:26:20 -0800211 super(new ProviderId("of", "org.onosproject.provider.host"));
alshabibe1cf87d2014-10-17 09:23:50 -0700212 }
213
214 @Activate
Thomas Vachuska33601602014-11-19 03:32:15 -0800215 public void activate(ComponentContext context) {
Thomas Vachuska6519e6f2015-03-11 02:29:31 -0700216 cfgService.registerProperties(getClass());
217 appId = coreService.registerApplication("org.onosproject.provider.host");
Charles Chanff79dd92018-06-01 16:33:48 -0700218 deviceEventHandler = newSingleThreadScheduledExecutor(groupedThreads("onos/host-loc-provider",
219 "device-event-handler", log));
220 probeEventHandler = newSingleThreadScheduledExecutor(groupedThreads("onos/host-loc-provider",
221 "probe-event-handler", log));
Charles Chan07f15f22018-05-08 21:35:50 -0700222 packetHandler = newSingleThreadScheduledExecutor(groupedThreads("onos/host-loc-provider",
223 "packet-handler", log));
alshabibe1cf87d2014-10-17 09:23:50 -0700224 providerService = providerRegistry.register(this);
Brian O'Connor3b783262015-07-29 17:49:24 -0700225 packetService.addProcessor(processor, PacketProcessor.advisor(1));
Thomas Vachuska33601602014-11-19 03:32:15 -0800226 deviceService.addListener(deviceListener);
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700227 registry.registerConfigFactory(hostLearningConfig);
Jonathan Hart9af322d2016-01-06 17:42:04 -0800228 modified(context);
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700229 netcfgService.addListener(cfgListener);
Jonathan Hart3cfce8e2015-01-14 16:43:27 -0800230
Charles M.C. Chane148de82015-05-06 12:38:21 +0800231 log.info("Started with Application ID {}", appId.id());
232 }
233
234 @Deactivate
235 public void deactivate() {
Charles M.C. Chane148de82015-05-06 12:38:21 +0800236 cfgService.unregisterProperties(getClass(), false);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700237
238 withdrawIntercepts();
239
Charles M.C. Chane148de82015-05-06 12:38:21 +0800240 providerRegistry.unregister(this);
241 packetService.removeProcessor(processor);
242 deviceService.removeListener(deviceListener);
Charles Chanff79dd92018-06-01 16:33:48 -0700243 deviceEventHandler.shutdown();
244 probeEventHandler.shutdown();
Charles Chan07f15f22018-05-08 21:35:50 -0700245 packetHandler.shutdown();
Charles M.C. Chane148de82015-05-06 12:38:21 +0800246 providerService = null;
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700247 registry.unregisterConfigFactory(hostLearningConfig);
248 netcfgService.removeListener(cfgListener);
Charles M.C. Chane148de82015-05-06 12:38:21 +0800249 log.info("Stopped");
250 }
251
252 @Modified
253 public void modified(ComponentContext context) {
Charles M.C. Chane148de82015-05-06 12:38:21 +0800254 readComponentConfiguration(context);
Jonathan Hart9af322d2016-01-06 17:42:04 -0800255
256 if (requestInterceptsEnabled) {
257 requestIntercepts();
258 } else {
259 withdrawIntercepts();
260 }
Charles M.C. Chane148de82015-05-06 12:38:21 +0800261 }
262
263 /**
Thomas Vachuska27bee092015-06-23 19:03:10 -0700264 * Request packet intercepts.
Charles M.C. Chane148de82015-05-06 12:38:21 +0800265 */
Thomas Vachuska27bee092015-06-23 19:03:10 -0700266 private void requestIntercepts() {
Charles Chane6067892016-11-17 10:23:46 -0800267 // Use ARP
268 TrafficSelector arpSelector = DefaultTrafficSelector.builder()
269 .matchEthType(Ethernet.TYPE_ARP)
270 .build();
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700271 if (requestArp) {
Charles Chane6067892016-11-17 10:23:46 -0800272 packetService.requestPackets(arpSelector, PacketPriority.CONTROL, appId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700273 } else {
Charles Chane6067892016-11-17 10:23:46 -0800274 packetService.cancelPackets(arpSelector, PacketPriority.CONTROL, appId);
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800275 }
Thomas Vachuska27bee092015-06-23 19:03:10 -0700276
Charles Chane6067892016-11-17 10:23:46 -0800277 // Use IPv6 Neighbor Discovery
278 TrafficSelector ipv6NsSelector = DefaultTrafficSelector.builder()
279 .matchEthType(Ethernet.TYPE_IPV6)
280 .matchIPProtocol(IPv6.PROTOCOL_ICMP6)
281 .matchIcmpv6Type(ICMP6.NEIGHBOR_SOLICITATION)
282 .build();
283 TrafficSelector ipv6NaSelector = DefaultTrafficSelector.builder()
284 .matchEthType(Ethernet.TYPE_IPV6)
285 .matchIPProtocol(IPv6.PROTOCOL_ICMP6)
286 .matchIcmpv6Type(ICMP6.NEIGHBOR_ADVERTISEMENT)
287 .build();
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700288 if (requestIpv6ND) {
Charles Chane6067892016-11-17 10:23:46 -0800289 packetService.requestPackets(ipv6NsSelector, PacketPriority.CONTROL, appId);
290 packetService.requestPackets(ipv6NaSelector, PacketPriority.CONTROL, appId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700291 } else {
Charles Chane6067892016-11-17 10:23:46 -0800292 packetService.cancelPackets(ipv6NsSelector, PacketPriority.CONTROL, appId);
293 packetService.cancelPackets(ipv6NaSelector, PacketPriority.CONTROL, appId);
294 }
Thomas Vachuska27bee092015-06-23 19:03:10 -0700295 }
296
297 /**
298 * Withdraw packet intercepts.
299 */
300 private void withdrawIntercepts() {
301 TrafficSelector.Builder selector = DefaultTrafficSelector.builder();
302 selector.matchEthType(Ethernet.TYPE_ARP);
Aaron Kruglikov07a923d2015-07-03 13:30:57 -0700303 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
Thomas Vachuska27bee092015-06-23 19:03:10 -0700304
305 // IPv6 Neighbor Solicitation packet.
306 selector.matchEthType(Ethernet.TYPE_IPV6);
307 selector.matchIPProtocol(IPv6.PROTOCOL_ICMP6);
308 selector.matchIcmpv6Type(ICMP6.NEIGHBOR_SOLICITATION);
309 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
310
311 // IPv6 Neighbor Advertisement packet.
312 selector.matchIcmpv6Type(ICMP6.NEIGHBOR_ADVERTISEMENT);
313 packetService.cancelPackets(selector.build(), PacketPriority.CONTROL, appId);
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800314 }
315
316 /**
317 * Extracts properties from the component configuration context.
318 *
319 * @param context the component context
320 */
321 private void readComponentConfiguration(ComponentContext context) {
322 Dictionary<?, ?> properties = context.getProperties();
323 Boolean flag;
324
Jian Lid9b5f552016-03-11 18:15:31 -0800325 flag = Tools.isPropertyEnabled(properties, "hostRemovalEnabled");
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800326 if (flag == null) {
327 log.info("Host removal on port/device down events is not configured, " +
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700328 "using current value of {}", hostRemovalEnabled);
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800329 } else {
330 hostRemovalEnabled = flag;
331 log.info("Configured. Host removal on port/device down events is {}",
332 hostRemovalEnabled ? "enabled" : "disabled");
Thomas Vachuska33601602014-11-19 03:32:15 -0800333 }
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800334
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700335 flag = Tools.isPropertyEnabled(properties, "requestArp");
Charles Chane6067892016-11-17 10:23:46 -0800336 if (flag == null) {
337 log.info("Using ARP is not configured, " +
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700338 "using current value of {}", requestArp);
Charles Chane6067892016-11-17 10:23:46 -0800339 } else {
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700340 requestArp = flag;
Charles Chane6067892016-11-17 10:23:46 -0800341 log.info("Configured. Using ARP is {}",
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700342 requestArp ? "enabled" : "disabled");
Charles Chane6067892016-11-17 10:23:46 -0800343 }
344
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700345 flag = Tools.isPropertyEnabled(properties, "requestIpv6ND");
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800346 if (flag == null) {
347 log.info("Using IPv6 Neighbor Discovery is not configured, " +
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700348 "using current value of {}", requestIpv6ND);
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800349 } else {
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700350 requestIpv6ND = flag;
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800351 log.info("Configured. Using IPv6 Neighbor Discovery is {}",
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700352 requestIpv6ND ? "enabled" : "disabled");
Charles Chane6067892016-11-17 10:23:46 -0800353 }
354
355 flag = Tools.isPropertyEnabled(properties, "useDhcp");
356 if (flag == null) {
357 log.info("Using DHCP is not configured, " +
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700358 "using current value of {}", useDhcp);
Charles Chane6067892016-11-17 10:23:46 -0800359 } else {
360 useDhcp = flag;
361 log.info("Configured. Using DHCP is {}",
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700362 useDhcp ? "enabled" : "disabled");
Pavlin Radoslavov93b606b2015-02-25 17:28:39 -0800363 }
Jonathan Hart9af322d2016-01-06 17:42:04 -0800364
Jian Lid9b5f552016-03-11 18:15:31 -0800365 flag = Tools.isPropertyEnabled(properties, "requestInterceptsEnabled");
Jonathan Hart9af322d2016-01-06 17:42:04 -0800366 if (flag == null) {
367 log.info("Request intercepts is not configured, " +
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700368 "using current value of {}", requestInterceptsEnabled);
Jonathan Hart9af322d2016-01-06 17:42:04 -0800369 } else {
370 requestInterceptsEnabled = flag;
371 log.info("Configured. Request intercepts is {}",
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700372 requestInterceptsEnabled ? "enabled" : "disabled");
Jonathan Hart9af322d2016-01-06 17:42:04 -0800373 }
Charles Chan35a32322017-08-14 11:42:11 -0700374
375 flag = Tools.isPropertyEnabled(properties, "multihomingEnabled");
376 if (flag == null) {
377 log.info("Multihoming is not configured, " +
378 "using current value of {}", multihomingEnabled);
379 } else {
380 multihomingEnabled = flag;
381 log.info("Configured. Multihoming is {}",
382 multihomingEnabled ? "enabled" : "disabled");
383 }
Charles Chan47933752017-11-30 15:37:50 -0800384 }
Charles Chan35a32322017-08-14 11:42:11 -0700385
Charles Chan47933752017-11-30 15:37:50 -0800386 @Override
alshabibe1cf87d2014-10-17 09:23:50 -0700387 public void triggerProbe(Host host) {
Saurav Dasb0ae6ee2017-03-04 16:08:47 -0800388 //log.info("Triggering probe on device {} ", host);
Jonathan Hartf353e402016-09-23 09:27:36 -0700389
390 // FIXME Disabling host probing for now, because sending packets from a
391 // broadcast MAC address caused problems when two ONOS networks were
392 // interconnected. Host probing should take into account the interface
393 // configuration when determining which source address to use.
394
395 //MastershipRole role = deviceService.getRole(host.location().deviceId());
396 //if (role.equals(MastershipRole.MASTER)) {
397 // host.ipAddresses().forEach(ip -> {
398 // sendProbe(host, ip);
399 // });
400 //} else {
401 // log.info("not the master, master will probe {}");
402 //}
sdn94b00152016-08-30 02:12:32 -0700403 }
404
405 private void sendProbe(Host host, IpAddress targetIp) {
406 Ethernet probePacket = null;
407 if (targetIp.isIp4()) {
408 // IPv4: Use ARP
409 probePacket = buildArpRequest(targetIp, host);
410 } else {
411 // IPv6: Use Neighbor Discovery
Jonathan Hartf353e402016-09-23 09:27:36 -0700412 //TODO need to implement ndp probe
sdn94b00152016-08-30 02:12:32 -0700413 log.info("Triggering probe on device {} ", host);
Ray Milkey74e59132018-01-17 15:24:52 -0800414 return;
sdn94b00152016-08-30 02:12:32 -0700415 }
416
417 TrafficTreatment treatment = DefaultTrafficTreatment.builder().setOutput(host.location().port()).build();
418
419 OutboundPacket outboundPacket = new DefaultOutboundPacket(host.location().deviceId(), treatment,
420 ByteBuffer.wrap(probePacket.serialize()));
421
422 packetService.emit(outboundPacket);
423 }
424
Charles Chan888e20a2017-05-01 15:44:23 -0700425 // This method is using source ip as 0.0.0.0 , to receive the reply even from the sub net hosts.
sdn94b00152016-08-30 02:12:32 -0700426 private Ethernet buildArpRequest(IpAddress targetIp, Host host) {
Charles Chan35a32322017-08-14 11:42:11 -0700427 return ARP.buildArpRequest(MacAddress.BROADCAST.toBytes(), Ip4Address.ZERO.toOctets(),
428 MacAddress.BROADCAST.toBytes(), targetIp.toOctets(),
429 MacAddress.BROADCAST.toBytes(), VlanId.NONE.toShort());
alshabibe1cf87d2014-10-17 09:23:50 -0700430 }
431
432 private class InternalHostProvider implements PacketProcessor {
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800433 /**
Charles Chan888e20a2017-05-01 15:44:23 -0700434 * Create or update host information.
435 * Will not update IP if IP is null, all zero or self-assigned.
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800436 *
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700437 * @param hid host ID
438 * @param mac source Mac address
439 * @param vlan VLAN ID
440 * @param innerVlan inner VLAN ID
441 * @param outerTpid outer TPID
442 * @param hloc host location
443 * @param ip source IP address or null if not updating
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800444 */
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700445 private void createOrUpdateHost(HostId hid, MacAddress mac, VlanId vlan,
446 VlanId innerVlan, EthType outerTpid,
447 HostLocation hloc, IpAddress ip) {
Charles Chan35a32322017-08-14 11:42:11 -0700448 Set<HostLocation> newLocations = Sets.newHashSet(hloc);
449
450 if (multihomingEnabled) {
451 Host existingHost = hostService.getHost(hid);
452 if (existingHost != null) {
453 Set<HostLocation> prevLocations = existingHost.locations();
Charles Chan35a32322017-08-14 11:42:11 -0700454
Charles Chan653e2ac2017-11-22 14:49:55 -0800455 if (prevLocations.stream().noneMatch(loc -> loc.deviceId().equals(hloc.deviceId()))) {
456 // New location is on a device that we haven't seen before
Charles Chanff79dd92018-06-01 16:33:48 -0700457 // Could be a dual-home host.
Charles Chan653e2ac2017-11-22 14:49:55 -0800458 newLocations.addAll(prevLocations);
Charles Chan653e2ac2017-11-22 14:49:55 -0800459 } else {
460 // Move within the same switch
461 // Simply replace old location that is on the same device
462 prevLocations.stream().filter(loc -> !loc.deviceId().equals(hloc.deviceId()))
463 .forEach(newLocations::add);
Charles Chan35a32322017-08-14 11:42:11 -0700464 }
465 }
466 }
467
Charles Chan888e20a2017-05-01 15:44:23 -0700468 HostDescription desc = ip == null || ip.isZero() || ip.isSelfAssigned() ?
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700469 new DefaultHostDescription(mac, vlan, newLocations, Sets.newHashSet(),
470 innerVlan, outerTpid, false) :
471 new DefaultHostDescription(mac, vlan, newLocations, Sets.newHashSet(ip),
472 innerVlan, outerTpid, false);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700473 try {
Ray Milkeydc083442016-02-22 11:27:57 -0800474 providerService.hostDetected(hid, desc, false);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700475 } catch (IllegalStateException e) {
476 log.debug("Host {} suppressed", hid);
477 }
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800478 }
alshabibe1cf87d2014-10-17 09:23:50 -0700479
Charles Chane6067892016-11-17 10:23:46 -0800480 /**
Charles Chan888e20a2017-05-01 15:44:23 -0700481 * Updates IP address for an existing host.
Charles Chane6067892016-11-17 10:23:46 -0800482 *
483 * @param hid host ID
484 * @param ip IP address
485 */
Charles Chan888e20a2017-05-01 15:44:23 -0700486 private void updateHostIp(HostId hid, IpAddress ip) {
Charles Chane6067892016-11-17 10:23:46 -0800487 Host host = hostService.getHost(hid);
488 if (host == null) {
Charles Chan35a32322017-08-14 11:42:11 -0700489 log.warn("Fail to update IP for {}. Host does not exist", hid);
Charles Chane6067892016-11-17 10:23:46 -0800490 return;
491 }
492
Charles Chan888e20a2017-05-01 15:44:23 -0700493 HostDescription desc = new DefaultHostDescription(hid.mac(), hid.vlanId(),
Charles Chan35a32322017-08-14 11:42:11 -0700494 host.locations(), Sets.newHashSet(ip), false);
Charles Chane6067892016-11-17 10:23:46 -0800495 try {
496 providerService.hostDetected(hid, desc, false);
497 } catch (IllegalStateException e) {
498 log.debug("Host {} suppressed", hid);
499 }
500 }
501
alshabibe1cf87d2014-10-17 09:23:50 -0700502 @Override
503 public void process(PacketContext context) {
Charles Chan07f15f22018-05-08 21:35:50 -0700504 packetHandler.execute(() -> processPacketInternal(context));
505 }
506
507 private void processPacketInternal(PacketContext context) {
alshabib4a179dc2014-10-17 17:17:01 -0700508 if (context == null) {
509 return;
510 }
alshabibe1cf87d2014-10-17 09:23:50 -0700511
Thomas Vachuskaf845cf62015-03-24 10:13:09 -0700512 Ethernet eth = context.inPacket().parsed();
Jonathan Harte8600eb2015-01-12 10:30:45 -0800513 if (eth == null) {
514 return;
515 }
Jonathan Hartf353e402016-09-23 09:27:36 -0700516
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800517 MacAddress srcMac = eth.getSourceMAC();
Jonathan Hartf353e402016-09-23 09:27:36 -0700518 if (srcMac.isBroadcast() || srcMac.isMulticast()) {
519 return;
520 }
Jonathan Harte8600eb2015-01-12 10:30:45 -0800521
alshabibe1cf87d2014-10-17 09:23:50 -0700522 VlanId vlan = VlanId.vlanId(eth.getVlanID());
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700523 VlanId outerVlan = VlanId.vlanId(eth.getQinQVID());
524 VlanId innerVlan = VlanId.NONE;
525 EthType outerTpid = EthType.EtherType.UNKNOWN.ethType();
526 // Set up values for double-tagged hosts
527 if (outerVlan.toShort() != Ethernet.VLAN_UNTAGGED) {
528 innerVlan = vlan;
529 vlan = outerVlan;
530 outerTpid = EthType.EtherType.lookup(eth.getQinQTPID()).ethType();
531 }
alshabibe1cf87d2014-10-17 09:23:50 -0700532 ConnectPoint heardOn = context.inPacket().receivedFrom();
533
Thomas Vachuskaf845cf62015-03-24 10:13:09 -0700534 // If this arrived on control port, bail out.
535 if (heardOn.port().isLogical()) {
536 return;
537 }
538
alshabibe1cf87d2014-10-17 09:23:50 -0700539 // If this is not an edge port, bail out.
540 Topology topology = topologyService.currentTopology();
541 if (topologyService.isInfrastructure(topology, heardOn)) {
542 return;
543 }
544
Thomas Vachuskaec9c7dd2015-09-03 18:30:04 -0700545 HostLocation hloc = new HostLocation(heardOn, System.currentTimeMillis());
alshabibe1cf87d2014-10-17 09:23:50 -0700546 HostId hid = HostId.hostId(eth.getSourceMAC(), vlan);
Charles Chan35a32322017-08-14 11:42:11 -0700547 MacAddress destMac = eth.getDestinationMAC();
548
Charles Chanff79dd92018-06-01 16:33:48 -0700549 // Ignore location probes
Charles Chan35a32322017-08-14 11:42:11 -0700550 if (multihomingEnabled && destMac.isOnos() && !MacAddress.NONE.equals(destMac)) {
Charles Chan35a32322017-08-14 11:42:11 -0700551 return;
552 }
alshabibe1cf87d2014-10-17 09:23:50 -0700553
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700554 HostLearningConfig cfg = netcfgService.getConfig(heardOn, HostLearningConfig.class);
555 // if learning is disabled bail out.
556 if ((cfg != null) && (!cfg.hostLearningEnabled())) {
557 log.debug("Learning disabled for {}, abort.", heardOn);
558 return;
559 }
560
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800561 // ARP: possible new hosts, update both location and IP
alshabibe1cf87d2014-10-17 09:23:50 -0700562 if (eth.getEtherType() == Ethernet.TYPE_ARP) {
563 ARP arp = (ARP) eth.getPayload();
Pavlin Radoslavovd6612f92015-02-23 13:53:32 -0800564 IpAddress ip = IpAddress.valueOf(IpAddress.Version.INET,
565 arp.getSenderProtocolAddress());
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700566 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, ip);
alshabibe1cf87d2014-10-17 09:23:50 -0700567
Charles Chan5d5e0622015-09-25 13:00:06 -0700568 // IPv4: update location only
alshabibe1cf87d2014-10-17 09:23:50 -0700569 } else if (eth.getEtherType() == Ethernet.TYPE_IPV4) {
Yi Tsengaa417a62017-09-08 17:22:51 -0700570 // Update host location
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700571 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, null);
Yi Tsengaa417a62017-09-08 17:22:51 -0700572 if (useDhcp) {
573 DHCP dhcp = findDhcp(eth).orElse(null);
574 // DHCP ACK: additionally update IP of DHCP client
575 if (dhcp != null && dhcp.getPacketType().equals(DHCP.MsgType.DHCPACK)) {
576 MacAddress hostMac = MacAddress.valueOf(dhcp.getClientHardwareAddress());
577 VlanId hostVlan = VlanId.vlanId(eth.getVlanID());
578 HostId hostId = HostId.hostId(hostMac, hostVlan);
579 updateHostIp(hostId, IpAddress.valueOf(dhcp.getYourIPAddress()));
Yi Tsengcfa637a2017-07-26 17:24:10 -0700580 }
Charles Chane6067892016-11-17 10:23:46 -0800581 }
Charles Chan5d5e0622015-09-25 13:00:06 -0700582 // NeighborAdvertisement and NeighborSolicitation: possible
583 // new hosts, update both location and IP.
584 //
585 // IPv6: update location only
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800586 } else if (eth.getEtherType() == Ethernet.TYPE_IPV6) {
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800587 IPv6 ipv6 = (IPv6) eth.getPayload();
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800588 IpAddress ip = IpAddress.valueOf(IpAddress.Version.INET6,
Thomas Vachuska27bee092015-06-23 19:03:10 -0700589 ipv6.getSourceAddress());
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800590
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800591 // skip extension headers
592 IPacket pkt = ipv6;
593 while (pkt.getPayload() != null &&
594 pkt.getPayload() instanceof IExtensionHeader) {
595 pkt = pkt.getPayload();
596 }
Charles M.C. Chan9148d2d2015-04-27 03:36:39 +0800597 pkt = pkt.getPayload();
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700598
599 // DHCPv6 protocol
600 DHCP6 dhcp6 = findDhcp6(pkt).orElse(null);
601 if (dhcp6 != null && useDhcp6) {
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700602 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, null);
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700603 handleDhcp6(dhcp6, vlan);
604 return;
605 }
606
Charles M.C. Chan9148d2d2015-04-27 03:36:39 +0800607 if (pkt != null && pkt instanceof ICMP6) {
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700608 // Neighbor Discovery Protocol
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800609 pkt = pkt.getPayload();
Charles Chan178b0f52017-10-08 23:51:22 -0400610 if (pkt != null) {
611 // RouterSolicitation, RouterAdvertisement
612 if (pkt instanceof RouterAdvertisement || pkt instanceof RouterSolicitation) {
Charles M.C. Chan441d7da2015-03-17 21:03:39 +0800613 return;
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800614 }
Charles Chan178b0f52017-10-08 23:51:22 -0400615 if (pkt instanceof NeighborSolicitation || pkt instanceof NeighborAdvertisement) {
616 // Duplicate Address Detection
617 if (ip.isZero()) {
618 return;
619 }
620 // NeighborSolicitation, NeighborAdvertisement
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700621 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, ip);
Charles Chan178b0f52017-10-08 23:51:22 -0400622
623 // Also learn from the target address of NeighborAdvertisement
624 if (pkt instanceof NeighborAdvertisement) {
625 NeighborAdvertisement na = (NeighborAdvertisement) pkt;
626 Ip6Address targetAddr = Ip6Address.valueOf(na.getTargetAddress());
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700627 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, targetAddr);
Charles Chan178b0f52017-10-08 23:51:22 -0400628 }
629 return;
630 }
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800631 }
Charles M.C. Chan7fee36a2014-12-31 00:19:59 +0800632 }
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800633
Yi Tsengaa417a62017-09-08 17:22:51 -0700634 // multicast, exclude DHCPv6
635 if (eth.isMulticast() && dhcp6 == null) {
Charles M.C. Chan956cb692015-04-26 18:49:39 +0800636 return;
637 }
638
639 // normal IPv6 packets
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700640 createOrUpdateHost(hid, srcMac, vlan, innerVlan, outerTpid, hloc, null);
alshabibe1cf87d2014-10-17 09:23:50 -0700641 }
642 }
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700643
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700644 /**
645 * Handles DHCPv6 packet, if message type is ACK, update IP address
646 * according to DHCPv6 payload (IA Address option).
647 *
648 * @param dhcp6 the DHCPv6 payload
649 * @param vlanId the vlan of this packet
650 */
651 private void handleDhcp6(DHCP6 dhcp6, VlanId vlanId) {
652 // extract the relay message if exist
653 while (dhcp6 != null && DHCP6.RELAY_MSG_TYPES.contains(dhcp6.getMsgType())) {
654 dhcp6 = dhcp6.getOptions().stream()
655 .filter(opt -> opt instanceof Dhcp6RelayOption)
656 .map(BasePacket::getPayload)
657 .map(pld -> (DHCP6) pld)
658 .findFirst()
659 .orElse(null);
660 }
661
662 if (dhcp6 == null) {
663 // Can't find dhcp payload
664 log.warn("Can't find dhcp payload from relay message");
665 return;
666 }
667
668 if (dhcp6.getMsgType() != DHCP6.MsgType.REPLY.value()) {
669 // Update IP address only when we received REPLY message
670 return;
671 }
672 Optional<Dhcp6ClientIdOption> clientIdOption = dhcp6.getOptions()
673 .stream()
674 .filter(opt -> opt instanceof Dhcp6ClientIdOption)
675 .map(opt -> (Dhcp6ClientIdOption) opt)
676 .findFirst();
677
678 if (!clientIdOption.isPresent()) {
679 // invalid DHCPv6 option
680 log.warn("Can't find client ID from DHCPv6 {}", dhcp6);
681 return;
682 }
683
684 byte[] linkLayerAddr = clientIdOption.get().getDuid().getLinkLayerAddress();
685 if (linkLayerAddr == null || linkLayerAddr.length != 6) {
686 // No any mac address found
687 log.warn("Can't find client mac from option {}", clientIdOption);
688 return;
689 }
690 MacAddress clientMac = MacAddress.valueOf(linkLayerAddr);
691
692 // Extract IPv6 address from IA NA ot IA TA option
693 Optional<Dhcp6IaNaOption> iaNaOption = dhcp6.getOptions()
694 .stream()
695 .filter(opt -> opt instanceof Dhcp6IaNaOption)
696 .map(opt -> (Dhcp6IaNaOption) opt)
697 .findFirst();
698 Optional<Dhcp6IaTaOption> iaTaOption = dhcp6.getOptions()
699 .stream()
700 .filter(opt -> opt instanceof Dhcp6IaTaOption)
701 .map(opt -> (Dhcp6IaTaOption) opt)
702 .findFirst();
703 Optional<Dhcp6IaAddressOption> iaAddressOption;
704 if (iaNaOption.isPresent()) {
705 iaAddressOption = iaNaOption.get().getOptions().stream()
706 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
707 .map(opt -> (Dhcp6IaAddressOption) opt)
708 .findFirst();
709 } else if (iaTaOption.isPresent()) {
710 iaAddressOption = iaTaOption.get().getOptions().stream()
711 .filter(opt -> opt instanceof Dhcp6IaAddressOption)
712 .map(opt -> (Dhcp6IaAddressOption) opt)
713 .findFirst();
714 } else {
715 iaAddressOption = Optional.empty();
716 }
717 if (iaAddressOption.isPresent()) {
718 Ip6Address ip = iaAddressOption.get().getIp6Address();
719 HostId hostId = HostId.hostId(clientMac, vlanId);
720 updateHostIp(hostId, ip);
721 } else {
722 log.warn("Can't find IPv6 address from DHCPv6 {}", dhcp6);
723 }
724 }
725
Yi Tseng7a38f9a2017-06-09 14:36:40 -0700726 private Optional<DHCP> findDhcp(Ethernet eth) {
727 IPacket pkt = eth.getPayload();
728 return Stream.of(pkt)
729 .filter(Objects::nonNull)
730 .filter(p -> p instanceof IPv4)
731 .map(IPacket::getPayload)
732 .filter(Objects::nonNull)
733 .filter(p -> p instanceof UDP)
734 .map(IPacket::getPayload)
735 .filter(Objects::nonNull)
736 .filter(p -> p instanceof DHCP)
737 .map(p -> (DHCP) p)
738 .findFirst();
739 }
Yi Tsengfcf5dce2017-07-26 14:30:41 -0700740
741 private Optional<DHCP6> findDhcp6(IPacket pkt) {
742 return Stream.of(pkt)
743 .filter(Objects::nonNull)
744 .filter(p -> p instanceof UDP)
745 .map(IPacket::getPayload)
746 .filter(Objects::nonNull)
747 .filter(p -> p instanceof DHCP6)
748 .map(p -> (DHCP6) p)
749 .findFirst();
750 }
alshabibe1cf87d2014-10-17 09:23:50 -0700751 }
Thomas Vachuska33601602014-11-19 03:32:15 -0800752
753 // Auxiliary listener to device events.
754 private class InternalDeviceListener implements DeviceListener {
755 @Override
756 public void event(DeviceEvent event) {
Charles Chanff79dd92018-06-01 16:33:48 -0700757 deviceEventHandler.execute(() -> handleEvent(event));
Madan Jampania3770c32015-12-11 12:07:41 -0800758 }
759
760 private void handleEvent(DeviceEvent event) {
Pavlin Radoslavovd36a74b2015-01-09 11:59:07 -0800761 Device device = event.subject();
762 switch (event.type()) {
Thomas Vachuska27bee092015-06-23 19:03:10 -0700763 case DEVICE_ADDED:
764 break;
765 case DEVICE_AVAILABILITY_CHANGED:
Charles Chan888e20a2017-05-01 15:44:23 -0700766 if (hostRemovalEnabled && !deviceService.isAvailable(device.id())) {
767 processDeviceDown(device.id());
Thomas Vachuska27bee092015-06-23 19:03:10 -0700768 }
769 break;
770 case DEVICE_SUSPENDED:
771 case DEVICE_UPDATED:
772 // Nothing to do?
773 break;
774 case DEVICE_REMOVED:
775 if (hostRemovalEnabled) {
Charles Chan888e20a2017-05-01 15:44:23 -0700776 processDeviceDown(device.id());
Thomas Vachuska27bee092015-06-23 19:03:10 -0700777 }
778 break;
779 case PORT_ADDED:
780 break;
781 case PORT_UPDATED:
Charles Chan888e20a2017-05-01 15:44:23 -0700782 if (hostRemovalEnabled && !event.port().isEnabled()) {
783 processPortDown(new ConnectPoint(device.id(), event.port().number()));
Thomas Vachuska27bee092015-06-23 19:03:10 -0700784 }
785 break;
786 case PORT_REMOVED:
enen923305efe2018-07-03 23:16:53 +0100787 if (hostRemovalEnabled) {
788 processPortDown(new ConnectPoint(device.id(), event.port().number()));
789 }
Thomas Vachuska27bee092015-06-23 19:03:10 -0700790 break;
791 default:
792 break;
Thomas Vachuska33601602014-11-19 03:32:15 -0800793 }
794 }
795 }
796
Charles Chan888e20a2017-05-01 15:44:23 -0700797 /**
798 * When a device goes down, update the location of affected hosts.
799 *
800 * @param deviceId the device that goes down
801 */
802 private void processDeviceDown(DeviceId deviceId) {
803 hostService.getConnectedHosts(deviceId).forEach(affectedHost -> affectedHost.locations().stream()
804 .filter(hostLocation -> hostLocation.deviceId().equals(deviceId))
805 .forEach(affectedLocation ->
806 providerService.removeLocationFromHost(affectedHost.id(), affectedLocation))
807 );
808 }
809
810 /**
811 * When a port goes down, update the location of affected hosts.
812 *
813 * @param connectPoint the port that goes down
814 */
815 private void processPortDown(ConnectPoint connectPoint) {
816 hostService.getConnectedHosts(connectPoint).forEach(affectedHost ->
817 providerService.removeLocationFromHost(affectedHost.id(), new HostLocation(connectPoint, 0L))
818 );
Thomas Vachuska33601602014-11-19 03:32:15 -0800819 }
820
Andreas Pantelopoulos19416412018-06-12 13:19:52 -0700821
822 private class InternalConfigListener implements NetworkConfigListener {
823
824 @Override
825 public void event(NetworkConfigEvent event) {
826 switch (event.type()) {
827 case CONFIG_ADDED:
828 case CONFIG_UPDATED:
829 log.debug("HostLearningConfig event of type {}", event.type());
830 // if learning enabled do nothing
831 HostLearningConfig learningConfig = (HostLearningConfig) event.config().get();
832 if (learningConfig.hostLearningEnabled()) {
833 return;
834 }
835
836 // if host learning is disable remove this location from existing, learnt hosts
837 ConnectPoint connectPoint = learningConfig.subject();
838 Set<Host> connectedHosts = hostService.getConnectedHosts(connectPoint);
839 for (Host host : connectedHosts) {
840 BasicHostConfig hostConfig = netcfgService.getConfig(host.id(), BasicHostConfig.class);
841
842 if ((hostConfig == null) || (!hostConfig.locations().contains(connectPoint))) {
843 // timestamp shoud not matter for comparing HostLocation and ConnectPoint
844 providerService.removeLocationFromHost(host.id(), new HostLocation(connectPoint, 1));
845 }
846 }
847 break;
848 case CONFIG_REMOVED:
849 default:
850 break;
851 }
852 }
853
854 @Override
855 public boolean isRelevant(NetworkConfigEvent event) {
856 if (!event.configClass().equals(HostLearningConfig.class)) {
857 return false;
858 }
859 return true;
860 }
861 }
alshabibe1cf87d2014-10-17 09:23:50 -0700862}