blob: bc7f19760256205d834e48e60f8cd3f032783510 [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 Chanba90df12017-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 Halterman7138d942018-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 Chanba90df12017-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 Halterman7138d942018-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 Chanc505f1e2017-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 Chan9ff637e2017-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 Chanba90df12017-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 Halterman7138d942018-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()) ||
Charles Chancd06c692017-04-27 20:46:06 -0700221 !Objects.equals(existingHost.locations(), hostDescription.locations())) {
Brian O'Connordab09742015-12-07 20:06:29 -0800222 return true;
223 }
224
225 if (replaceIPs) {
226 if (!Objects.equals(hostDescription.ipAddress(),
227 existingHost.ipAddresses())) {
228 return true;
229 }
230 } else {
231 if (!existingHost.ipAddresses().containsAll(hostDescription.ipAddress())) {
232 return true;
233 }
234 }
235
236 // check to see if any of the annotations provided by hostDescription
237 // differ from those in the existing host
238 return hostDescription.annotations().keys().stream()
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530239 .anyMatch(k -> !Objects.equals(hostDescription.annotations().value(k),
240 existingHost.annotations().value(k)));
Brian O'Connordab09742015-12-07 20:06:29 -0800241
242
243 }
244
Charles Chan009c3082015-11-10 14:18:04 -0800245 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700246 @Override
247 public HostEvent createOrUpdateHost(ProviderId providerId,
Brian O'Connorf107bd72015-09-21 15:31:03 -0700248 HostId hostId,
249 HostDescription hostDescription,
250 boolean replaceIPs) {
Madan Jampanic6371882016-06-03 21:30:17 -0700251 hostsConsistentMap.computeIf(hostId,
Charles Chan69ebcbb2017-04-27 14:33:21 -0700252 existingHost -> shouldUpdate(existingHost, providerId,
Brian O'Connordab09742015-12-07 20:06:29 -0800253 hostDescription, replaceIPs),
254 (id, existingHost) -> {
Brian O'Connorf107bd72015-09-21 15:31:03 -0700255
Madan Jampanic7f49f92015-12-10 11:35:06 -0800256 final Set<IpAddress> addresses;
257 if (existingHost == null || replaceIPs) {
258 addresses = ImmutableSet.copyOf(hostDescription.ipAddress());
259 } else {
260 addresses = Sets.newHashSet(existingHost.ipAddresses());
261 addresses.addAll(hostDescription.ipAddress());
262 }
Brian O'Connorf107bd72015-09-21 15:31:03 -0700263
Madan Jampanic7f49f92015-12-10 11:35:06 -0800264 final Annotations annotations;
265 if (existingHost != null) {
266 annotations = merge((DefaultAnnotations) existingHost.annotations(),
267 hostDescription.annotations());
268 } else {
269 annotations = hostDescription.annotations();
270 }
Jonathan Hart38feb6e2016-08-29 22:54:16 +0000271
Madan Jampanic7f49f92015-12-10 11:35:06 -0800272 return new DefaultHost(providerId,
273 hostId,
274 hostDescription.hwAddress(),
275 hostDescription.vlan(),
Charles Chancd06c692017-04-27 20:46:06 -0700276 hostDescription.locations(),
Madan Jampanic7f49f92015-12-10 11:35:06 -0800277 addresses,
Charles Chanb1e99242017-07-07 14:11:09 -0700278 hostDescription.configured(),
Madan Jampanic7f49f92015-12-10 11:35:06 -0800279 annotations);
280 });
Charles Chan009c3082015-11-10 14:18:04 -0800281 return null;
Madan Jampani38a88212015-09-15 11:21:27 -0700282 }
283
Charles Chan009c3082015-11-10 14:18:04 -0800284 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700285 @Override
286 public HostEvent removeHost(HostId hostId) {
Charles Chan009c3082015-11-10 14:18:04 -0800287 hosts.remove(hostId);
288 return null;
Madan Jampani38a88212015-09-15 11:21:27 -0700289 }
290
Charles Chan009c3082015-11-10 14:18:04 -0800291 // TODO No longer need to return HostEvent
Madan Jampani38a88212015-09-15 11:21:27 -0700292 @Override
samanwita palc40e5ed2015-09-24 11:01:51 -0700293 public HostEvent removeIp(HostId hostId, IpAddress ipAddress) {
Charles Chan009c3082015-11-10 14:18:04 -0800294 hosts.compute(hostId, (id, existingHost) -> {
samanwita palc40e5ed2015-09-24 11:01:51 -0700295 if (existingHost != null) {
296 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
297 "Existing and new MAC addresses differ.");
298 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
299 "Existing and new VLANs differ.");
300
samanwita pale7c08de2015-09-24 21:59:49 -0700301 Set<IpAddress> addresses = existingHost.ipAddresses();
samanwita palc40e5ed2015-09-24 11:01:51 -0700302 if (addresses != null && addresses.contains(ipAddress)) {
samanwita pale7c08de2015-09-24 21:59:49 -0700303 addresses = new HashSet<>(existingHost.ipAddresses());
samanwita palc40e5ed2015-09-24 11:01:51 -0700304 addresses.remove(ipAddress);
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530305 removeIpFromHostsByIp(existingHost, ipAddress);
samanwita palc40e5ed2015-09-24 11:01:51 -0700306 return new DefaultHost(existingHost.providerId(),
307 hostId,
308 existingHost.mac(),
309 existingHost.vlan(),
Charles Chancd06c692017-04-27 20:46:06 -0700310 existingHost.locations(),
samanwita palc40e5ed2015-09-24 11:01:51 -0700311 ImmutableSet.copyOf(addresses),
Charles Chancd06c692017-04-27 20:46:06 -0700312 existingHost.configured(),
samanwita palc40e5ed2015-09-24 11:01:51 -0700313 existingHost.annotations());
314 } else {
315 return existingHost;
316 }
317 }
318 return null;
319 });
Charles Chan009c3082015-11-10 14:18:04 -0800320 return null;
samanwita palc40e5ed2015-09-24 11:01:51 -0700321 }
322
323 @Override
Charles Chanba90df12017-11-30 15:37:50 -0800324 public void appendLocation(HostId hostId, HostLocation location) {
325 log.debug("Appending location {} to host {}", location, hostId);
326 hosts.compute(hostId, (id, existingHost) -> {
327 if (existingHost != null) {
328 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
329 "Existing and new MAC addresses differ.");
330 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
331 "Existing and new VLANs differ.");
332
333 Set<HostLocation> locations = new HashSet<>(existingHost.locations());
334 locations.add(location);
335
336 return new DefaultHost(existingHost.providerId(),
337 hostId, existingHost.mac(), existingHost.vlan(),
338 locations, existingHost.ipAddresses(),
339 existingHost.configured(), existingHost.annotations());
340 }
341 return null;
342 });
343 }
344
345 @Override
Charles Chan888e20a2017-05-01 15:44:23 -0700346 public void removeLocation(HostId hostId, HostLocation location) {
Charles Chanba90df12017-11-30 15:37:50 -0800347 log.debug("Removing location {} from host {}", location, hostId);
Charles Chan888e20a2017-05-01 15:44:23 -0700348 hosts.compute(hostId, (id, existingHost) -> {
349 if (existingHost != null) {
350 checkState(Objects.equals(hostId.mac(), existingHost.mac()),
351 "Existing and new MAC addresses differ.");
352 checkState(Objects.equals(hostId.vlanId(), existingHost.vlan()),
353 "Existing and new VLANs differ.");
354
355 Set<HostLocation> locations = new HashSet<>(existingHost.locations());
356 locations.remove(location);
357
358 // Remove entire host if we are removing the last location
359 return locations.isEmpty() ? null :
360 new DefaultHost(existingHost.providerId(),
361 hostId, existingHost.mac(), existingHost.vlan(),
362 locations, existingHost.ipAddresses(),
363 existingHost.configured(), existingHost.annotations());
364 }
365 return null;
366 });
367 }
368
369 @Override
Madan Jampani38a88212015-09-15 11:21:27 -0700370 public int getHostCount() {
371 return hosts.size();
372 }
373
374 @Override
375 public Iterable<Host> getHosts() {
376 return ImmutableSet.copyOf(hosts.values());
377 }
378
379 @Override
380 public Host getHost(HostId hostId) {
381 return hosts.get(hostId);
382 }
383
384 @Override
385 public Set<Host> getHosts(VlanId vlanId) {
386 return filter(hosts.values(), host -> Objects.equals(host.vlan(), vlanId));
387 }
388
389 @Override
390 public Set<Host> getHosts(MacAddress mac) {
391 return filter(hosts.values(), host -> Objects.equals(host.mac(), mac));
392 }
393
394 @Override
395 public Set<Host> getHosts(IpAddress ip) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530396 Set<Host> hosts = hostsByIp.get(ip);
397 return hosts != null ? ImmutableSet.copyOf(hosts) : ImmutableSet.of();
Madan Jampani38a88212015-09-15 11:21:27 -0700398 }
399
400 @Override
401 public Set<Host> getConnectedHosts(ConnectPoint connectPoint) {
Charles Chan009c3082015-11-10 14:18:04 -0800402 Set<Host> filtered = hosts.entrySet().stream()
Charles Chancd06c692017-04-27 20:46:06 -0700403 .filter(entry -> entry.getValue().locations().contains(connectPoint))
Charles Chan009c3082015-11-10 14:18:04 -0800404 .map(Map.Entry::getValue)
405 .collect(Collectors.toSet());
406 return ImmutableSet.copyOf(filtered);
Madan Jampani38a88212015-09-15 11:21:27 -0700407 }
408
409 @Override
410 public Set<Host> getConnectedHosts(DeviceId deviceId) {
Charles Chan009c3082015-11-10 14:18:04 -0800411 Set<Host> filtered = hosts.entrySet().stream()
Charles Chancd06c692017-04-27 20:46:06 -0700412 .filter(entry -> entry.getValue().locations().stream()
413 .map(HostLocation::deviceId).anyMatch(dpid -> dpid.equals(deviceId)))
Charles Chan009c3082015-11-10 14:18:04 -0800414 .map(Map.Entry::getValue)
415 .collect(Collectors.toSet());
HIGUCHI Yutafe2122c2015-09-30 13:46:22 -0700416 return ImmutableSet.copyOf(filtered);
Madan Jampani38a88212015-09-15 11:21:27 -0700417 }
418
Charles Chan35a32322017-08-14 11:42:11 -0700419 @Override
Charles Chanba90df12017-11-30 15:37:50 -0800420 public MacAddress addPendingHostLocation(HostId hostId, ConnectPoint connectPoint, ProbeMode probeMode) {
Charles Chan35a32322017-08-14 11:42:11 -0700421 // Use ONLab OUI (3 bytes) + atomic counter (3 bytes) as the source MAC of the probe
Jordan Halterman7138d942018-03-09 11:31:09 -0500422 long nextIndex = hostProbeIndex.getAndIncrement();
Charles Chan35a32322017-08-14 11:42:11 -0700423 MacAddress probeMac = MacAddress.valueOf(MacAddress.NONE.toLong() + nextIndex);
Charles Chanba90df12017-11-30 15:37:50 -0800424 PendingHostLocation phl = new PendingHostLocation(hostId, connectPoint, probeMode);
Charles Chan35a32322017-08-14 11:42:11 -0700425
426 pendingHostsCache.put(probeMac, phl);
427 pendingHosts.put(probeMac, phl);
428
429 return probeMac;
430 }
431
432 @Override
433 public void removePendingHostLocation(MacAddress probeMac) {
Charles Chanba90df12017-11-30 15:37:50 -0800434 // Add the host location if probe replied in-time in DISCOVER mode
435 Optional.ofNullable(pendingHosts.get(probeMac)).ifPresent(phl -> {
436 if (phl.probeMode() == ProbeMode.DISCOVER) {
437 HostLocation newLocation = new HostLocation(phl.connectPoint(), System.currentTimeMillis());
438 appendLocation(phl.hostId(), newLocation);
439 }
440 });
441
Charles Chan35a32322017-08-14 11:42:11 -0700442 pendingHostsCache.invalidate(probeMac);
443 pendingHosts.remove(probeMac);
444 }
445
Charles Chan9ff637e2017-09-12 18:57:47 -0700446 private boolean timeoutPendingHostLocation(MacAddress probeMac) {
447 PendingHostLocation phl = pendingHosts.computeIfPresent(probeMac, (k, v) -> {
Charles Chan35a32322017-08-14 11:42:11 -0700448 v.setExpired(true);
449 return v;
450 });
Charles Chan9ff637e2017-09-12 18:57:47 -0700451 return phl != null;
Charles Chan35a32322017-08-14 11:42:11 -0700452 }
453
Madan Jampani38a88212015-09-15 11:21:27 -0700454 private Set<Host> filter(Collection<DefaultHost> collection, Predicate<DefaultHost> predicate) {
455 return collection.stream().filter(predicate).collect(Collectors.toSet());
456 }
457
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530458 private Set<Host> addHosts(Host host) {
459 Set<Host> hosts = Sets.newConcurrentHashSet();
460 hosts.add(host);
461 return hosts;
462 }
463
464 private Set<Host> updateHosts(Set<Host> existingHosts, Host host) {
465 Iterator<Host> iterator = existingHosts.iterator();
466 while (iterator.hasNext()) {
467 Host existingHost = iterator.next();
468 if (existingHost.id().equals(host.id())) {
469 iterator.remove();
470 }
471 }
472 existingHosts.add(host);
473 return existingHosts;
474 }
475
476 private Set<Host> removeHosts(Set<Host> existingHosts, Host host) {
477 if (existingHosts != null) {
478 Iterator<Host> iterator = existingHosts.iterator();
479 while (iterator.hasNext()) {
480 Host existingHost = iterator.next();
481 if (existingHost.id().equals(host.id())) {
482 iterator.remove();
483 }
484 }
485 }
486
Ray Milkeyfd4f8d32018-01-17 15:24:52 -0800487 if (existingHosts == null || existingHosts.isEmpty()) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530488 return null;
489 }
490 return existingHosts;
491 }
492
493 private void updateHostsByIp(DefaultHost host) {
494 host.ipAddresses().forEach(ip -> {
495 hostsByIp.compute(ip, (k, v) -> v == null ? addHosts(host)
496 : updateHosts(v, host));
497 });
498 }
499
500 private void removeHostsByIp(DefaultHost host) {
501 host.ipAddresses().forEach(ip -> {
502 hostsByIp.computeIfPresent(ip, (k, v) -> removeHosts(v, host));
503 });
504 }
505
506 private void removeIpFromHostsByIp(DefaultHost host, IpAddress ip) {
507 hostsByIp.computeIfPresent(ip, (k, v) -> removeHosts(v, host));
508 }
509
alshabib8a4a6002015-11-25 14:31:16 -0800510 private class HostLocationTracker implements MapEventListener<HostId, DefaultHost> {
Madan Jampani38a88212015-09-15 11:21:27 -0700511 @Override
alshabib8a4a6002015-11-25 14:31:16 -0800512 public void event(MapEvent<HostId, DefaultHost> event) {
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530513 DefaultHost host = checkNotNull(event.value().value());
alshabib1400ce92015-12-16 15:05:47 -0800514 switch (event.type()) {
515 case INSERT:
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530516 updateHostsByIp(host);
Charles Chan009c3082015-11-10 14:18:04 -0800517 notifyDelegate(new HostEvent(HOST_ADDED, host));
alshabib1400ce92015-12-16 15:05:47 -0800518 break;
519 case UPDATE:
Deepa Vaddireddy0a71c8b2017-01-19 21:20:45 +0530520 updateHostsByIp(host);
521 DefaultHost prevHost = checkNotNull(event.oldValue().value());
Charles Chancd06c692017-04-27 20:46:06 -0700522 if (!Objects.equals(prevHost.locations(), host.locations())) {
alshabib1400ce92015-12-16 15:05:47 -0800523 notifyDelegate(new HostEvent(HOST_MOVED, host, prevHost));
524 } else if (!Objects.equals(prevHost, host)) {
525 notifyDelegate(new HostEvent(HOST_UPDATED, host, prevHost));
526 }
527 break;
528 case REMOVE:
Charles Chan21720342017-05-13 00:19:09 -0700529 removeHostsByIp(host);
Yuta HIGUCHI215a7e42016-07-20 19:54:06 -0700530 notifyDelegate(new HostEvent(HOST_REMOVED, host));
alshabib1400ce92015-12-16 15:05:47 -0800531 break;
532 default:
533 log.warn("Unknown map event type: {}", event.type());
Madan Jampani38a88212015-09-15 11:21:27 -0700534 }
535 }
536 }
Charles Chan35a32322017-08-14 11:42:11 -0700537
538 private class PendingHostListener implements MapEventListener<MacAddress, PendingHostLocation> {
539 @Override
540 public void event(MapEvent<MacAddress, PendingHostLocation> event) {
541 Versioned<PendingHostLocation> newValue = event.newValue();
542 switch (event.type()) {
543 case INSERT:
544 break;
545 case UPDATE:
Charles Chanba90df12017-11-30 15:37:50 -0800546 // Remove the host location if probe timeout in VERIFY mode
547 if (newValue.value().expired() && newValue.value().probeMode() == ProbeMode.VERIFY) {
Charles Chan35a32322017-08-14 11:42:11 -0700548 Executor locationRemover = Executors.newSingleThreadScheduledExecutor();
549 locationRemover.execute(() -> {
550 pendingHosts.remove(event.key());
Charles Chanba90df12017-11-30 15:37:50 -0800551 removeLocation(newValue.value().hostId(),
552 new HostLocation(newValue.value().connectPoint(), 0L));
Charles Chan35a32322017-08-14 11:42:11 -0700553 });
554 }
555 break;
556 case REMOVE:
557 break;
558 default:
559 log.warn("Unknown map event type: {}", event.type());
560 }
561 }
562 }
Madan Jampani38a88212015-09-15 11:21:27 -0700563}