blob: 8dc1613c967c5c7c5908289f730fdd6a43ff55fe [file] [log] [blame]
Madan Jampani38a88212015-09-15 11:21:27 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Madan Jampani38a88212015-09-15 11:21:27 -07003 *
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 */
16package org.onosproject.store.host.impl;
17
Charles Chan35a32322017-08-14 11:42:11 -070018import com.google.common.cache.Cache;
19import com.google.common.cache.CacheBuilder;
20import com.google.common.cache.RemovalNotification;
alshabib8a4a6002015-11-25 14:31:16 -080021import com.google.common.collect.ImmutableSet;
22import com.google.common.collect.Sets;
Madan Jampanic7f49f92015-12-10 11:35:06 -080023
Madan Jampani38a88212015-09-15 11:21:27 -070024import org.apache.felix.scr.annotations.Activate;
25import org.apache.felix.scr.annotations.Component;
26import org.apache.felix.scr.annotations.Deactivate;
27import org.apache.felix.scr.annotations.Reference;
28import org.apache.felix.scr.annotations.ReferenceCardinality;
29import org.apache.felix.scr.annotations.Service;
30import org.onlab.packet.IpAddress;
31import org.onlab.packet.MacAddress;
32import org.onlab.packet.VlanId;
33import org.onlab.util.KryoNamespace;
34import org.onosproject.net.Annotations;
35import org.onosproject.net.ConnectPoint;
36import org.onosproject.net.DefaultAnnotations;
37import org.onosproject.net.DefaultHost;
38import org.onosproject.net.DeviceId;
39import org.onosproject.net.Host;
40import org.onosproject.net.HostId;
Brian O'Connorf107bd72015-09-21 15:31:03 -070041import org.onosproject.net.HostLocation;
Madan Jampani38a88212015-09-15 11:21:27 -070042import org.onosproject.net.host.HostDescription;
43import org.onosproject.net.host.HostEvent;
44import org.onosproject.net.host.HostStore;
45import org.onosproject.net.host.HostStoreDelegate;
Charles Chan47933752017-11-30 15:37:50 -080046import org.onosproject.net.host.HostLocationProbingService.ProbeMode;
Madan Jampani38a88212015-09-15 11:21:27 -070047import org.onosproject.net.provider.ProviderId;
48import org.onosproject.store.AbstractStore;
49import org.onosproject.store.serializers.KryoNamespaces;
Jordan Haltermandc49cfd2018-03-09 11:31:09 -050050import org.onosproject.store.service.AtomicCounter;
alshabib8a4a6002015-11-25 14:31:16 -080051import org.onosproject.store.service.ConsistentMap;
52import org.onosproject.store.service.MapEvent;
53import org.onosproject.store.service.MapEventListener;
54import org.onosproject.store.service.Serializer;
Madan Jampani38a88212015-09-15 11:21:27 -070055import org.onosproject.store.service.StorageService;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053056import org.onosproject.store.service.DistributedPrimitive.Status;
Charles Chan35a32322017-08-14 11:42:11 -070057import org.onosproject.store.service.Versioned;
Madan Jampani38a88212015-09-15 11:21:27 -070058import org.slf4j.Logger;
59
alshabib8a4a6002015-11-25 14:31:16 -080060import java.util.Collection;
61import java.util.HashSet;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053062import java.util.Iterator;
alshabib8a4a6002015-11-25 14:31:16 -080063import java.util.Map;
64import java.util.Objects;
Charles Chan47933752017-11-30 15:37:50 -080065import java.util.Optional;
alshabib8a4a6002015-11-25 14:31:16 -080066import java.util.Set;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053067import java.util.concurrent.ConcurrentHashMap;
Charles Chan35a32322017-08-14 11:42:11 -070068import java.util.concurrent.Executor;
69import java.util.concurrent.Executors;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053070import java.util.concurrent.ScheduledExecutorService;
Charles Chan35a32322017-08-14 11:42:11 -070071import java.util.concurrent.TimeUnit;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053072import java.util.function.Consumer;
alshabib8a4a6002015-11-25 14:31:16 -080073import java.util.function.Predicate;
74import java.util.stream.Collectors;
75
76import static com.google.common.base.Preconditions.checkNotNull;
77import static com.google.common.base.Preconditions.checkState;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +053078import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
79import static org.onlab.util.Tools.groupedThreads;
alshabib8a4a6002015-11-25 14:31:16 -080080import static org.onosproject.net.DefaultAnnotations.merge;
81import static org.onosproject.net.host.HostEvent.Type.*;
82import static org.slf4j.LoggerFactory.getLogger;
Madan Jampani38a88212015-09-15 11:21:27 -070083
84/**
85 * Manages the inventory of hosts using a {@code EventuallyConsistentMap}.
86 */
87@Component(immediate = true)
88@Service
alshabib8a4a6002015-11-25 14:31:16 -080089public class DistributedHostStore
Madan Jampani38a88212015-09-15 11:21:27 -070090 extends AbstractStore<HostEvent, HostStoreDelegate>
91 implements HostStore {
92
93 private final Logger log = getLogger(getClass());
94
95 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
96 protected StorageService storageService;
97
Jordan Haltermandc49cfd2018-03-09 11:31:09 -050098 private AtomicCounter hostProbeIndex;
Madan Jampanic6371882016-06-03 21:30:17 -070099 private ConsistentMap<HostId, DefaultHost> hostsConsistentMap;
alshabib8a4a6002015-11-25 14:31:16 -0800100 private Map<HostId, DefaultHost> hosts;
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530101 private Map<IpAddress, Set<Host>> hostsByIp;
alshabib8a4a6002015-11-25 14:31:16 -0800102 private MapEventListener<HostId, DefaultHost> hostLocationTracker =
Madan Jampani38a88212015-09-15 11:21:27 -0700103 new HostLocationTracker();
104
Charles Chan35a32322017-08-14 11:42:11 -0700105 private ConsistentMap<MacAddress, PendingHostLocation> pendingHostsConsistentMap;
106 private Map<MacAddress, PendingHostLocation> pendingHosts;
107 private MapEventListener<MacAddress, PendingHostLocation> pendingHostListener =
108 new PendingHostListener();
109
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530110 private ScheduledExecutorService executor;
111
112 private Consumer<Status> statusChangeListener;
113
Charles Chan35a32322017-08-14 11:42:11 -0700114 // TODO make this configurable
Charles Chan8277b6b2017-12-03 13:48:46 -0800115 private static final int PROBE_TIMEOUT_MS = 3000;
Charles Chan35a32322017-08-14 11:42:11 -0700116
117 private Cache<MacAddress, PendingHostLocation> pendingHostsCache = CacheBuilder.newBuilder()
118 .expireAfterWrite(PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS)
119 .removalListener((RemovalNotification<MacAddress, PendingHostLocation> notification) -> {
120 switch (notification.getCause()) {
121 case EXPIRED:
122 PendingHostLocation expired = notification.getValue();
123 if (expired != null) {
Charles Chan8e786b52017-09-12 18:57:47 -0700124 if (timeoutPendingHostLocation(notification.getKey())) {
125 log.info("Evict {} from pendingHosts due to probe timeout", notification.getValue());
126 }
Charles Chan35a32322017-08-14 11:42:11 -0700127 }
128 break;
129 case EXPLICIT:
130 break;
131 default:
132 log.warn("Remove {} from pendingHostLocations for unexpected reason {}",
133 notification.getKey(), notification.getCause());
134 }
135 }).build();
136
137 private ScheduledExecutorService cacheCleaner = Executors.newSingleThreadScheduledExecutor();
138
Madan Jampani38a88212015-09-15 11:21:27 -0700139 @Activate
140 public void activate() {
141 KryoNamespace.Builder hostSerializer = KryoNamespace.newBuilder()
Jonathan Hart38feb6e2016-08-29 22:54:16 +0000142 .register(KryoNamespaces.API);
Madan Jampanic6371882016-06-03 21:30:17 -0700143 hostsConsistentMap = storageService.<HostId, DefaultHost>consistentMapBuilder()
Madan Jampani38a88212015-09-15 11:21:27 -0700144 .withName("onos-hosts")
alshabib8a4a6002015-11-25 14:31:16 -0800145 .withRelaxedReadConsistency()
146 .withSerializer(Serializer.using(hostSerializer.build()))
Madan Jampani38a88212015-09-15 11:21:27 -0700147 .build();
Charles Chan35a32322017-08-14 11:42:11 -0700148 hostsConsistentMap.addListener(hostLocationTracker);
Madan Jampanic6371882016-06-03 21:30:17 -0700149 hosts = hostsConsistentMap.asJavaMap();
alshabib8a4a6002015-11-25 14:31:16 -0800150
Charles Chan35a32322017-08-14 11:42:11 -0700151 KryoNamespace.Builder pendingHostSerializer = KryoNamespace.newBuilder()
152 .register(KryoNamespaces.API)
Charles Chan47933752017-11-30 15:37:50 -0800153 .register(PendingHostLocation.class)
154 .register(ProbeMode.class);
Charles Chan35a32322017-08-14 11:42:11 -0700155 pendingHostsConsistentMap = storageService.<MacAddress, PendingHostLocation>consistentMapBuilder()
156 .withName("onos-hosts-pending")
157 .withRelaxedReadConsistency()
158 .withSerializer(Serializer.using(pendingHostSerializer.build()))
159 .build();
160 pendingHostsConsistentMap.addListener(pendingHostListener);
161 pendingHosts = pendingHostsConsistentMap.asJavaMap();
alshabib1400ce92015-12-16 15:05:47 -0800162
Jordan Haltermandc49cfd2018-03-09 11:31:09 -0500163 hostProbeIndex = storageService.atomicCounterBuilder()
164 .withName("onos-hosts-probe-index")
165 .build()
166 .asAtomicCounter();
167
Charles Chan35a32322017-08-14 11:42:11 -0700168 cacheCleaner.scheduleAtFixedRate(pendingHostsCache::cleanUp, 0,
169 PROBE_TIMEOUT_MS, TimeUnit.MILLISECONDS);
Madan Jampani38a88212015-09-15 11:21:27 -0700170
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530171 executor = newSingleThreadScheduledExecutor(groupedThreads("onos/hosts", "store", log));
172 statusChangeListener = status -> {
173 if (status == Status.ACTIVE) {
174 executor.execute(this::loadHostsByIp);
175 }
176 };
177 hostsConsistentMap.addStatusChangeListener(statusChangeListener);
178 loadHostsByIp();
Madan Jampani38a88212015-09-15 11:21:27 -0700179 log.info("Started");
180 }
181
182 @Deactivate
183 public void deactivate() {
Madan Jampanic6371882016-06-03 21:30:17 -0700184 hostsConsistentMap.removeListener(hostLocationTracker);
Madan Jampani38a88212015-09-15 11:21:27 -0700185
Charles Chan35a32322017-08-14 11:42:11 -0700186 cacheCleaner.shutdown();
187
Madan Jampani38a88212015-09-15 11:21:27 -0700188 log.info("Stopped");
189 }
190
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530191 private void loadHostsByIp() {
192 hostsByIp = new ConcurrentHashMap<IpAddress, Set<Host>>();
193 hostsConsistentMap.asJavaMap().values().forEach(host -> {
194 host.ipAddresses().forEach(ip -> {
195 Set<Host> existingHosts = hostsByIp.get(ip);
196 if (existingHosts == null) {
197 hostsByIp.put(ip, addHosts(host));
198 } else {
199 existingHosts.add(host);
200 }
201 });
202 });
203 }
204
Brian O'Connordab09742015-12-07 20:06:29 -0800205 private boolean shouldUpdate(DefaultHost existingHost,
206 ProviderId providerId,
Brian O'Connordab09742015-12-07 20:06:29 -0800207 HostDescription hostDescription,
208 boolean replaceIPs) {
209 if (existingHost == null) {
210 return true;
211 }
212
Charles Chan69ebcbb2017-04-27 14:33:21 -0700213 // Avoid overriding configured host with learnt host
214 if (existingHost.configured() && !hostDescription.configured()) {
Charles Chan29ecdee2017-02-22 18:46:56 -0800215 return false;
216 }
217
Brian O'Connordab09742015-12-07 20:06:29 -0800218 if (!Objects.equals(existingHost.providerId(), providerId) ||
219 !Objects.equals(existingHost.mac(), hostDescription.hwAddress()) ||
220 !Objects.equals(existingHost.vlan(), hostDescription.vlan()) ||
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700221 !Objects.equals(existingHost.innerVlan(), hostDescription.innerVlan()) ||
222 !Objects.equals(existingHost.tpid(), hostDescription.tpid()) ||
Charles Chancd06c692017-04-27 20:46:06 -0700223 !Objects.equals(existingHost.locations(), hostDescription.locations())) {
Brian O'Connordab09742015-12-07 20:06:29 -0800224 return true;
225 }
226
227 if (replaceIPs) {
228 if (!Objects.equals(hostDescription.ipAddress(),
229 existingHost.ipAddresses())) {
230 return true;
231 }
232 } else {
233 if (!existingHost.ipAddresses().containsAll(hostDescription.ipAddress())) {
234 return true;
235 }
236 }
237
238 // check to see if any of the annotations provided by hostDescription
239 // differ from those in the existing host
240 return hostDescription.annotations().keys().stream()
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530241 .anyMatch(k -> !Objects.equals(hostDescription.annotations().value(k),
242 existingHost.annotations().value(k)));
Brian O'Connordab09742015-12-07 20:06:29 -0800243
244
245 }
246
Charles Chan009c3082015-11-10 14:18:04 -0800247 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700248 @Override
249 public HostEvent createOrUpdateHost(ProviderId providerId,
Brian O'Connorf107bd72015-09-21 15:31:03 -0700250 HostId hostId,
251 HostDescription hostDescription,
252 boolean replaceIPs) {
Madan Jampanic6371882016-06-03 21:30:17 -0700253 hostsConsistentMap.computeIf(hostId,
Charles Chan69ebcbb2017-04-27 14:33:21 -0700254 existingHost -> shouldUpdate(existingHost, providerId,
Brian O'Connordab09742015-12-07 20:06:29 -0800255 hostDescription, replaceIPs),
256 (id, existingHost) -> {
Brian O'Connorf107bd72015-09-21 15:31:03 -0700257
Madan Jampanic7f49f92015-12-10 11:35:06 -0800258 final Set<IpAddress> addresses;
259 if (existingHost == null || replaceIPs) {
260 addresses = ImmutableSet.copyOf(hostDescription.ipAddress());
261 } else {
262 addresses = Sets.newHashSet(existingHost.ipAddresses());
263 addresses.addAll(hostDescription.ipAddress());
264 }
Brian O'Connorf107bd72015-09-21 15:31:03 -0700265
Madan Jampanic7f49f92015-12-10 11:35:06 -0800266 final Annotations annotations;
267 if (existingHost != null) {
268 annotations = merge((DefaultAnnotations) existingHost.annotations(),
269 hostDescription.annotations());
270 } else {
271 annotations = hostDescription.annotations();
272 }
Jonathan Hart38feb6e2016-08-29 22:54:16 +0000273
Madan Jampanic7f49f92015-12-10 11:35:06 -0800274 return new DefaultHost(providerId,
275 hostId,
276 hostDescription.hwAddress(),
277 hostDescription.vlan(),
Charles Chancd06c692017-04-27 20:46:06 -0700278 hostDescription.locations(),
Madan Jampanic7f49f92015-12-10 11:35:06 -0800279 addresses,
Jonghwan Hyun2c95acf2018-03-14 16:47:34 -0700280 hostDescription.innerVlan(),
281 hostDescription.tpid(),
Charles Chanb1e99242017-07-07 14:11:09 -0700282 hostDescription.configured(),
Madan Jampanic7f49f92015-12-10 11:35:06 -0800283 annotations);
284 });
Charles Chan009c3082015-11-10 14:18:04 -0800285 return null;
Madan Jampani38a88212015-09-15 11:21:27 -0700286 }
287
Charles Chan009c3082015-11-10 14:18:04 -0800288 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700289 @Override
290 public HostEvent removeHost(HostId hostId) {
Charles Chan009c3082015-11-10 14:18:04 -0800291 hosts.remove(hostId);
292 return null;
Madan Jampani38a88212015-09-15 11:21:27 -0700293 }
294
Charles Chan009c3082015-11-10 14:18:04 -0800295 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700296 @Override
samanwita palc40e5ed2015-09-24 11:01:51 -0700297 public HostEvent removeIp(HostId hostId, IpAddress ipAddress) {
Charles Chan009c3082015-11-10 14:18:04 -0800298 hosts.compute(hostId, (id, existingHost) -> {
samanwita palc40e5ed2015-09-24 11:01:51 -0700299 if (existingHost != null) {
300 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
301 "Existing and new MAC addresses differ.");
302 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
303 "Existing and new VLANs differ.");
304
samanwita pale7c08de2015-09-24 21:59:49 -0700305 Set<IpAddress> addresses = existingHost.ipAddresses();
samanwita palc40e5ed2015-09-24 11:01:51 -0700306 if (addresses != null && addresses.contains(ipAddress)) {
samanwita pale7c08de2015-09-24 21:59:49 -0700307 addresses = new HashSet<>(existingHost.ipAddresses());
samanwita palc40e5ed2015-09-24 11:01:51 -0700308 addresses.remove(ipAddress);
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530309 removeIpFromHostsByIp(existingHost, ipAddress);
samanwita palc40e5ed2015-09-24 11:01:51 -0700310 return new DefaultHost(existingHost.providerId(),
311 hostId,
312 existingHost.mac(),
313 existingHost.vlan(),
Charles Chancd06c692017-04-27 20:46:06 -0700314 existingHost.locations(),
samanwita palc40e5ed2015-09-24 11:01:51 -0700315 ImmutableSet.copyOf(addresses),
Charles Chancd06c692017-04-27 20:46:06 -0700316 existingHost.configured(),
samanwita palc40e5ed2015-09-24 11:01:51 -0700317 existingHost.annotations());
318 } else {
319 return existingHost;
320 }
321 }
322 return null;
323 });
Charles Chan009c3082015-11-10 14:18:04 -0800324 return null;
samanwita palc40e5ed2015-09-24 11:01:51 -0700325 }
326
327 @Override
Charles Chan47933752017-11-30 15:37:50 -0800328 public void appendLocation(HostId hostId, HostLocation location) {
329 log.debug("Appending location {} to host {}", location, hostId);
330 hosts.compute(hostId, (id, existingHost) -> {
331 if (existingHost != null) {
332 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
333 "Existing and new MAC addresses differ.");
334 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
335 "Existing and new VLANs differ.");
336
337 Set<HostLocation> locations = new HashSet<>(existingHost.locations());
338 locations.add(location);
339
340 return new DefaultHost(existingHost.providerId(),
341 hostId, existingHost.mac(), existingHost.vlan(),
342 locations, existingHost.ipAddresses(),
343 existingHost.configured(), existingHost.annotations());
344 }
345 return null;
346 });
347 }
348
349 @Override
Charles Chan888e20a2017-05-01 15:44:23 -0700350 public void removeLocation(HostId hostId, HostLocation location) {
Charles Chan47933752017-11-30 15:37:50 -0800351 log.debug("Removing location {} from host {}", location, hostId);
Charles Chan888e20a2017-05-01 15:44:23 -0700352 hosts.compute(hostId, (id, existingHost) -> {
353 if (existingHost != null) {
354 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
355 "Existing and new MAC addresses differ.");
356 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
357 "Existing and new VLANs differ.");
358
359 Set<HostLocation> locations = new HashSet<>(existingHost.locations());
360 locations.remove(location);
361
362 // Remove entire host if we are removing the last location
363 return locations.isEmpty() ? null :
364 new DefaultHost(existingHost.providerId(),
365 hostId, existingHost.mac(), existingHost.vlan(),
366 locations, existingHost.ipAddresses(),
367 existingHost.configured(), existingHost.annotations());
368 }
369 return null;
370 });
371 }
372
373 @Override
Madan Jampani38a88212015-09-15 11:21:27 -0700374 public int getHostCount() {
375 return hosts.size();
376 }
377
378 @Override
379 public Iterable<Host> getHosts() {
380 return ImmutableSet.copyOf(hosts.values());
381 }
382
383 @Override
384 public Host getHost(HostId hostId) {
385 return hosts.get(hostId);
386 }
387
388 @Override
389 public Set<Host> getHosts(VlanId vlanId) {
390 return filter(hosts.values(), host -> Objects.equals(host.vlan(), vlanId));
391 }
392
393 @Override
394 public Set<Host> getHosts(MacAddress mac) {
395 return filter(hosts.values(), host -> Objects.equals(host.mac(), mac));
396 }
397
398 @Override
399 public Set<Host> getHosts(IpAddress ip) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530400 Set<Host> hosts = hostsByIp.get(ip);
401 return hosts != null ? ImmutableSet.copyOf(hosts) : ImmutableSet.of();
Madan Jampani38a88212015-09-15 11:21:27 -0700402 }
403
404 @Override
405 public Set<Host> getConnectedHosts(ConnectPoint connectPoint) {
Charles Chan009c3082015-11-10 14:18:04 -0800406 Set<Host> filtered = hosts.entrySet().stream()
Charles Chancd06c692017-04-27 20:46:06 -0700407 .filter(entry -> entry.getValue().locations().contains(connectPoint))
Charles Chan009c3082015-11-10 14:18:04 -0800408 .map(Map.Entry::getValue)
409 .collect(Collectors.toSet());
410 return ImmutableSet.copyOf(filtered);
Madan Jampani38a88212015-09-15 11:21:27 -0700411 }
412
413 @Override
414 public Set<Host> getConnectedHosts(DeviceId deviceId) {
Charles Chan009c3082015-11-10 14:18:04 -0800415 Set<Host> filtered = hosts.entrySet().stream()
Charles Chancd06c692017-04-27 20:46:06 -0700416 .filter(entry -> entry.getValue().locations().stream()
417 .map(HostLocation::deviceId).anyMatch(dpid -> dpid.equals(deviceId)))
Charles Chan009c3082015-11-10 14:18:04 -0800418 .map(Map.Entry::getValue)
419 .collect(Collectors.toSet());
HIGUCHI Yutafe2122c2015-09-30 13:46:22 -0700420 return ImmutableSet.copyOf(filtered);
Madan Jampani38a88212015-09-15 11:21:27 -0700421 }
422
Charles Chan35a32322017-08-14 11:42:11 -0700423 @Override
Charles Chan47933752017-11-30 15:37:50 -0800424 public MacAddress addPendingHostLocation(HostId hostId, ConnectPoint connectPoint, ProbeMode probeMode) {
Charles Chan35a32322017-08-14 11:42:11 -0700425 // Use ONLab OUI (3 bytes) + atomic counter (3 bytes) as the source MAC of the probe
Jordan Haltermandc49cfd2018-03-09 11:31:09 -0500426 long nextIndex = hostProbeIndex.getAndIncrement();
Charles Chan35a32322017-08-14 11:42:11 -0700427 MacAddress probeMac = MacAddress.valueOf(MacAddress.NONE.toLong() + nextIndex);
Charles Chan47933752017-11-30 15:37:50 -0800428 PendingHostLocation phl = new PendingHostLocation(hostId, connectPoint, probeMode);
Charles Chan35a32322017-08-14 11:42:11 -0700429
430 pendingHostsCache.put(probeMac, phl);
431 pendingHosts.put(probeMac, phl);
432
433 return probeMac;
434 }
435
436 @Override
437 public void removePendingHostLocation(MacAddress probeMac) {
Charles Chan47933752017-11-30 15:37:50 -0800438 // Add the host location if probe replied in-time in DISCOVER mode
439 Optional.ofNullable(pendingHosts.get(probeMac)).ifPresent(phl -> {
440 if (phl.probeMode() == ProbeMode.DISCOVER) {
441 HostLocation newLocation = new HostLocation(phl.connectPoint(), System.currentTimeMillis());
442 appendLocation(phl.hostId(), newLocation);
443 }
444 });
445
Charles Chan35a32322017-08-14 11:42:11 -0700446 pendingHostsCache.invalidate(probeMac);
447 pendingHosts.remove(probeMac);
448 }
449
Charles Chan8e786b52017-09-12 18:57:47 -0700450 private boolean timeoutPendingHostLocation(MacAddress probeMac) {
451 PendingHostLocation phl = pendingHosts.computeIfPresent(probeMac, (k, v) -> {
Charles Chan35a32322017-08-14 11:42:11 -0700452 v.setExpired(true);
453 return v;
454 });
Charles Chan8e786b52017-09-12 18:57:47 -0700455 return phl != null;
Charles Chan35a32322017-08-14 11:42:11 -0700456 }
457
Madan Jampani38a88212015-09-15 11:21:27 -0700458 private Set<Host> filter(Collection<DefaultHost> collection, Predicate<DefaultHost> predicate) {
459 return collection.stream().filter(predicate).collect(Collectors.toSet());
460 }
461
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530462 private Set<Host> addHosts(Host host) {
463 Set<Host> hosts = Sets.newConcurrentHashSet();
464 hosts.add(host);
465 return hosts;
466 }
467
468 private Set<Host> updateHosts(Set<Host> existingHosts, Host host) {
469 Iterator<Host> iterator = existingHosts.iterator();
470 while (iterator.hasNext()) {
471 Host existingHost = iterator.next();
472 if (existingHost.id().equals(host.id())) {
473 iterator.remove();
474 }
475 }
476 existingHosts.add(host);
477 return existingHosts;
478 }
479
480 private Set<Host> removeHosts(Set<Host> existingHosts, Host host) {
481 if (existingHosts != null) {
482 Iterator<Host> iterator = existingHosts.iterator();
483 while (iterator.hasNext()) {
484 Host existingHost = iterator.next();
485 if (existingHost.id().equals(host.id())) {
486 iterator.remove();
487 }
488 }
489 }
490
Ray Milkey74e59132018-01-17 15:24:52 -0800491 if (existingHosts == null || existingHosts.isEmpty()) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530492 return null;
493 }
494 return existingHosts;
495 }
496
497 private void updateHostsByIp(DefaultHost host) {
498 host.ipAddresses().forEach(ip -> {
499 hostsByIp.compute(ip, (k, v) -> v == null ? addHosts(host)
500 : updateHosts(v, host));
501 });
502 }
503
504 private void removeHostsByIp(DefaultHost host) {
505 host.ipAddresses().forEach(ip -> {
506 hostsByIp.computeIfPresent(ip, (k, v) -> removeHosts(v, host));
507 });
508 }
509
510 private void removeIpFromHostsByIp(DefaultHost host, IpAddress ip) {
511 hostsByIp.computeIfPresent(ip, (k, v) -> removeHosts(v, host));
512 }
513
alshabib8a4a6002015-11-25 14:31:16 -0800514 private class HostLocationTracker implements MapEventListener<HostId, DefaultHost> {
Madan Jampani38a88212015-09-15 11:21:27 -0700515 @Override
alshabib8a4a6002015-11-25 14:31:16 -0800516 public void event(MapEvent<HostId, DefaultHost> event) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530517 DefaultHost host = checkNotNull(event.value().value());
alshabib1400ce92015-12-16 15:05:47 -0800518 switch (event.type()) {
519 case INSERT:
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530520 updateHostsByIp(host);
Charles Chan009c3082015-11-10 14:18:04 -0800521 notifyDelegate(new HostEvent(HOST_ADDED, host));
alshabib1400ce92015-12-16 15:05:47 -0800522 break;
523 case UPDATE:
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530524 updateHostsByIp(host);
525 DefaultHost prevHost = checkNotNull(event.oldValue().value());
Charles Chancd06c692017-04-27 20:46:06 -0700526 if (!Objects.equals(prevHost.locations(), host.locations())) {
alshabib1400ce92015-12-16 15:05:47 -0800527 notifyDelegate(new HostEvent(HOST_MOVED, host, prevHost));
528 } else if (!Objects.equals(prevHost, host)) {
529 notifyDelegate(new HostEvent(HOST_UPDATED, host, prevHost));
530 }
531 break;
532 case REMOVE:
Charles Chan21720342017-05-13 00:19:09 -0700533 removeHostsByIp(host);
Yuta HIGUCHI215a7e42016-07-20 19:54:06 -0700534 notifyDelegate(new HostEvent(HOST_REMOVED, host));
alshabib1400ce92015-12-16 15:05:47 -0800535 break;
536 default:
537 log.warn("Unknown map event type: {}", event.type());
Madan Jampani38a88212015-09-15 11:21:27 -0700538 }
539 }
540 }
Charles Chan35a32322017-08-14 11:42:11 -0700541
542 private class PendingHostListener implements MapEventListener<MacAddress, PendingHostLocation> {
543 @Override
544 public void event(MapEvent<MacAddress, PendingHostLocation> event) {
545 Versioned<PendingHostLocation> newValue = event.newValue();
546 switch (event.type()) {
547 case INSERT:
548 break;
549 case UPDATE:
Charles Chan47933752017-11-30 15:37:50 -0800550 // Remove the host location if probe timeout in VERIFY mode
551 if (newValue.value().expired() && newValue.value().probeMode() == ProbeMode.VERIFY) {
Charles Chan35a32322017-08-14 11:42:11 -0700552 Executor locationRemover = Executors.newSingleThreadScheduledExecutor();
553 locationRemover.execute(() -> {
554 pendingHosts.remove(event.key());
Charles Chan47933752017-11-30 15:37:50 -0800555 removeLocation(newValue.value().hostId(),
556 new HostLocation(newValue.value().connectPoint(), 0L));
Charles Chan35a32322017-08-14 11:42:11 -0700557 });
558 }
559 break;
560 case REMOVE:
561 break;
562 default:
563 log.warn("Unknown map event type: {}", event.type());
564 }
565 }
566 }
Madan Jampani38a88212015-09-15 11:21:27 -0700567}