blob: c0ee5162eb0051c68545211089b022f10024122b [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Ray Milkey34c95902015-04-15 09:47:53 -07002 * Copyright 2014-2015 Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -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 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.net.device.impl;
tomd3097b02014-08-26 10:40:29 -070017
samuel738dfaf2015-07-11 11:08:57 +080018import static com.google.common.base.Preconditions.checkNotNull;
19import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
20import static org.onlab.util.Tools.groupedThreads;
21import static org.onosproject.net.MastershipRole.MASTER;
22import static org.onosproject.net.MastershipRole.NONE;
23import static org.onosproject.net.MastershipRole.STANDBY;
24import static org.onosproject.security.AppGuard.checkPermission;
25import static org.slf4j.LoggerFactory.getLogger;
26
27import java.util.Collection;
28import java.util.HashSet;
29import java.util.List;
30import java.util.Objects;
31import java.util.Set;
32import java.util.concurrent.CompletableFuture;
33import java.util.concurrent.ExecutionException;
34import java.util.concurrent.ScheduledExecutorService;
35import java.util.concurrent.TimeUnit;
36
tomd3097b02014-08-26 10:40:29 -070037import org.apache.felix.scr.annotations.Activate;
38import org.apache.felix.scr.annotations.Component;
39import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070040import org.apache.felix.scr.annotations.Reference;
41import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070042import org.apache.felix.scr.annotations.Service;
Brian O'Connorabafb502014-12-02 22:26:20 -080043import org.onosproject.cluster.ClusterService;
44import org.onosproject.cluster.NodeId;
Changhoon Yoon541ef712015-05-23 17:18:34 +090045import org.onosproject.core.Permission;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.event.EventDeliveryService;
samuel738dfaf2015-07-11 11:08:57 +080047import org.onosproject.event.ListenerRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.mastership.MastershipEvent;
49import org.onosproject.mastership.MastershipListener;
50import org.onosproject.mastership.MastershipService;
51import org.onosproject.mastership.MastershipTerm;
52import org.onosproject.mastership.MastershipTermService;
53import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080054import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.DeviceId;
56import org.onosproject.net.MastershipRole;
57import org.onosproject.net.Port;
58import org.onosproject.net.PortNumber;
59import org.onosproject.net.device.DefaultDeviceDescription;
60import org.onosproject.net.device.DefaultPortDescription;
61import org.onosproject.net.device.DeviceAdminService;
62import org.onosproject.net.device.DeviceClockProviderService;
63import org.onosproject.net.device.DeviceDescription;
64import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceProvider;
67import org.onosproject.net.device.DeviceProviderRegistry;
68import org.onosproject.net.device.DeviceProviderService;
69import org.onosproject.net.device.DeviceService;
70import org.onosproject.net.device.DeviceStore;
71import org.onosproject.net.device.DeviceStoreDelegate;
72import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070073import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080074import org.onosproject.net.provider.AbstractProviderRegistry;
75import org.onosproject.net.provider.AbstractProviderService;
tomd3097b02014-08-26 10:40:29 -070076import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070077
samuel738dfaf2015-07-11 11:08:57 +080078import com.google.common.collect.Lists;
Jonathan Hart2f669362015-02-11 16:19:20 -080079
tomd3097b02014-08-26 10:40:29 -070080/**
tome4729872014-09-23 00:37:37 -070081 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070082 */
83@Component(immediate = true)
84@Service
tom41a2c5f2014-09-19 09:20:35 -070085public class DeviceManager
Thomas Vachuskad16ce182014-10-29 17:25:29 -070086 extends AbstractProviderRegistry<DeviceProvider, DeviceProviderService>
87 implements DeviceService, DeviceAdminService, DeviceProviderRegistry {
tom32f66842014-08-27 19:27:47 -070088
tome5ec3fd2014-09-04 15:18:06 -070089 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
90 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
91 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
92 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
tomd3097b02014-08-26 10:40:29 -070093
tom5f38b3a2014-08-27 23:50:54 -070094 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -070095
samuel738dfaf2015-07-11 11:08:57 +080096 protected final ListenerRegistry<DeviceEvent, DeviceListener> listenerRegistry = new ListenerRegistry<>();
tom32f66842014-08-27 19:27:47 -070097
alshabib339a3d92014-09-26 17:54:32 -070098 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -070099
tomc78acee2014-09-24 15:16:55 -0700100 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700101 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700102
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800103 private ScheduledExecutorService backgroundService;
104
tom41a2c5f2014-09-19 09:20:35 -0700105 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
106 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700107
tom5f38b3a2014-08-27 23:50:54 -0700108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tome5ec3fd2014-09-04 15:18:06 -0700109 protected EventDeliveryService eventDispatcher;
tom5f38b3a2014-08-27 23:50:54 -0700110
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700112 protected ClusterService clusterService;
113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700115 protected MastershipService mastershipService;
116
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700118 protected MastershipTermService termService;
119
Madan Jampani61056bc2014-09-27 09:07:26 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700121 protected DeviceClockProviderService deviceClockProviderService;
Madan Jampani61056bc2014-09-27 09:07:26 -0700122
tomd3097b02014-08-26 10:40:29 -0700123 @Activate
124 public void activate() {
samuel738dfaf2015-07-11 11:08:57 +0800125 backgroundService = newSingleThreadScheduledExecutor(groupedThreads("onos/device",
126 "manager-background"));
Madan Jampanide003d92015-05-11 17:14:20 -0700127 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800128
tomf80c9722014-09-24 14:49:18 -0700129 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700130 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700131 mastershipService.addListener(mastershipListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800132
133 backgroundService.scheduleWithFixedDelay(new Runnable() {
134
135 @Override
136 public void run() {
137 try {
138 mastershipCheck();
139 } catch (Exception e) {
140 log.error("Exception thrown during integrity check", e);
141 }
142 }
143 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700144 log.info("Started");
145 }
146
147 @Deactivate
148 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800149 backgroundService.shutdown();
150
tomf80c9722014-09-24 14:49:18 -0700151 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700152 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700153 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700154 log.info("Stopped");
155 }
156
157 @Override
tomad2d2092014-09-06 23:24:20 -0700158 public int getDeviceCount() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900159 checkPermission(Permission.DEVICE_READ);
160
tomad2d2092014-09-06 23:24:20 -0700161 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700162 }
163
164 @Override
tom32f66842014-08-27 19:27:47 -0700165 public Iterable<Device> getDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900166 checkPermission(Permission.DEVICE_READ);
167
tome5ec3fd2014-09-04 15:18:06 -0700168 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700169 }
170
tom32f66842014-08-27 19:27:47 -0700171 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800172 public Iterable<Device> getAvailableDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900173 checkPermission(Permission.DEVICE_READ);
174
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800175 return store.getAvailableDevices();
176 }
177
178 @Override
tom32f66842014-08-27 19:27:47 -0700179 public Device getDevice(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900180 checkPermission(Permission.DEVICE_READ);
181
tom32f66842014-08-27 19:27:47 -0700182 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700183 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700184 }
185
186 @Override
tomad2d2092014-09-06 23:24:20 -0700187 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900188 checkPermission(Permission.DEVICE_READ);
189
tomad2d2092014-09-06 23:24:20 -0700190 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700191 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700192 }
193
194 @Override
tom32f66842014-08-27 19:27:47 -0700195 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900196 checkPermission(Permission.DEVICE_READ);
197
tom32f66842014-08-27 19:27:47 -0700198 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700199 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700200 }
201
202 @Override
sangho538108b2015-04-08 14:29:20 -0700203 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900204 checkPermission(Permission.DEVICE_READ);
205
sangho538108b2015-04-08 14:29:20 -0700206 checkNotNull(deviceId, DEVICE_ID_NULL);
207 return store.getPortStatistics(deviceId);
208 }
209
210 @Override
tom32f66842014-08-27 19:27:47 -0700211 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900212 checkPermission(Permission.DEVICE_READ);
213
tom32f66842014-08-27 19:27:47 -0700214 checkNotNull(deviceId, DEVICE_ID_NULL);
215 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700216 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700217 }
218
219 @Override
tomff7eb7c2014-09-08 12:49:03 -0700220 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900221 checkPermission(Permission.DEVICE_READ);
222
tomff7eb7c2014-09-08 12:49:03 -0700223 checkNotNull(deviceId, DEVICE_ID_NULL);
224 return store.isAvailable(deviceId);
225 }
226
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700227 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700228 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800229 if (deviceId == null) {
230 return false;
231 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700232 DeviceProvider provider = getProvider(deviceId);
233 if (provider != null) {
234 return provider.isReachable(deviceId);
235 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800236 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700237 return false;
238 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700239 }
240
tome5ec3fd2014-09-04 15:18:06 -0700241 @Override
242 public void removeDevice(DeviceId deviceId) {
243 checkNotNull(deviceId, DEVICE_ID_NULL);
244 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700245 if (event != null) {
246 log.info("Device {} administratively removed", deviceId);
247 post(event);
248 }
tome5ec3fd2014-09-04 15:18:06 -0700249 }
250
tom7869ad92014-09-09 14:32:08 -0700251 @Override
252 public void addListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900253 checkPermission(Permission.DEVICE_EVENT);
254
tom7869ad92014-09-09 14:32:08 -0700255 listenerRegistry.addListener(listener);
256 }
257
258 @Override
259 public void removeListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900260 checkPermission(Permission.DEVICE_EVENT);
261
tom7869ad92014-09-09 14:32:08 -0700262 listenerRegistry.removeListener(listener);
263 }
264
265 @Override
samuel738dfaf2015-07-11 11:08:57 +0800266 protected DeviceProviderService createProviderService(DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700267 return new InternalDeviceProviderService(provider);
268 }
269
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800270 /**
271 * Checks if all the reachable devices have a valid mastership role.
272 */
273 private void mastershipCheck() {
274 log.debug("Checking mastership");
275 for (Device device : getDevices()) {
276 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800277 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800278
279 if (!isReachable(deviceId)) {
280 continue;
281 }
282
283 if (mastershipService.getLocalRole(deviceId) != NONE) {
284 continue;
285 }
286
samuel738dfaf2015-07-11 11:08:57 +0800287 log.info("{} is reachable but did not have a valid role, reasserting",
288 deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800289
290 // isReachable but was not MASTER or STANDBY, get a role and apply
291 // Note: NONE triggers request to MastershipService
292 reassertRole(deviceId, NONE);
293 }
294 }
295
tomd3097b02014-08-26 10:40:29 -0700296 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700297 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700298 extends AbstractProviderService<DeviceProvider>
299 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700300
tomcfde0622014-09-09 11:02:42 -0700301 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700302 super(provider);
303 }
304
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700305 /**
306 * Apply role in reaction to provider event.
307 *
samuel738dfaf2015-07-11 11:08:57 +0800308 * @param deviceId device identifier
309 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700310 * @return true if the request was sent to provider
311 */
312 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
313
314 if (newRole.equals(MastershipRole.NONE)) {
samuel738dfaf2015-07-11 11:08:57 +0800315 // no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700316 return true;
317 }
318
319 DeviceProvider provider = provider();
320 if (provider == null) {
samuel738dfaf2015-07-11 11:08:57 +0800321 log.warn("Provider for {} was not found. Cannot apply role {}",
322 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700323 return false;
324 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700325 provider.roleChanged(deviceId, newRole);
326 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700327
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700328 return true;
329 }
330
tomd3097b02014-08-26 10:40:29 -0700331 @Override
alshabibb7b40632014-09-28 21:30:00 -0700332 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700333 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700334 checkNotNull(deviceId, DEVICE_ID_NULL);
335 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700336 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700337
338 log.info("Device {} connected", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700339 // check my Role
samuel738dfaf2015-07-11 11:08:57 +0800340 CompletableFuture<MastershipRole> role = mastershipService
341 .requestRoleFor(deviceId);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700342 try {
343 // Device subsystem must wait for role assignment
344 // to avoid losing Device information.
345 // (This node could be the only Node connected to the Device.)
346 role.get();
347 } catch (InterruptedException e) {
samuel738dfaf2015-07-11 11:08:57 +0800348 log.warn("Interrupted while waiting role-assignment for {}",
349 deviceId);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700350 Thread.currentThread().interrupt();
351 } catch (ExecutionException e) {
352 log.error("Exception thrown while waiting role-assignment for {}",
353 deviceId, e);
354 }
355
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700356 final MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700357 if (term == null || !localNodeId.equals(term.master())) {
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700358 log.info("Role of this node is STANDBY for {}", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700359 applyRole(deviceId, MastershipRole.STANDBY);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800360 } else {
361 log.info("Role of this node is MASTER for {}", deviceId);
362 // tell clock provider if this instance is the master
363 deviceClockProviderService.setMastershipTerm(deviceId, term);
364 applyRole(deviceId, MastershipRole.MASTER);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700365 }
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700366
tome5ec3fd2014-09-04 15:18:06 -0700367 DeviceEvent event = store.createOrUpdateDevice(provider().id(),
samuel738dfaf2015-07-11 11:08:57 +0800368 deviceId,
369 deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700370
tom80c0e5e2014-09-08 18:08:58 -0700371 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700372 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700373 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700374 }
tomd3097b02014-08-26 10:40:29 -0700375 }
376
377 @Override
378 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700379 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700380 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700381
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700382 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700383
alshabibafc514a2014-12-01 14:44:05 -0800384 List<Port> ports = store.getPorts(deviceId);
385 List<PortDescription> descs = Lists.newArrayList();
samuel738dfaf2015-07-11 11:08:57 +0800386 ports.forEach(port -> descs.add(new DefaultPortDescription(port
387 .number(), false, port.type(), port.portSpeed())));
alshabibafc514a2014-12-01 14:44:05 -0800388 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700389 try {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700390 if (mastershipService.getLocalRole(deviceId) == MASTER) {
391 post(store.markOffline(deviceId));
392 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700393 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700394 log.warn("Failed to mark {} offline", deviceId);
395 // only the MASTER should be marking off-line in normal cases,
samuel738dfaf2015-07-11 11:08:57 +0800396 // but if I was the last STANDBY connection, etc. and no one
397 // else
398 // was there to mark the device offline, this instance may need
399 // to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700400 // temporarily request for Master Role and mark offline.
401
samuel738dfaf2015-07-11 11:08:57 +0800402 // there are times when this node will correctly have
403 // mastership, BUT
404 // that isn't reflected in the ClockManager before the device
405 // disconnects.
406 // we want to let go of the device anyways, so make sure this
407 // happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700408
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700409 // FIXME: Store semantics leaking out as IllegalStateException.
samuel738dfaf2015-07-11 11:08:57 +0800410 // Consider revising store API to handle this scenario.
411 CompletableFuture<MastershipRole> roleFuture = mastershipService
412 .requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700413 roleFuture.whenComplete((role, error) -> {
samuel738dfaf2015-07-11 11:08:57 +0800414 MastershipTerm term = termService
415 .getMastershipTerm(deviceId);
416 // TODO: Move this type of check inside device clock
417 // manager, etc.
418 if (term != null && localNodeId.equals(term.master())) {
419 log.info("Retry marking {} offline", deviceId);
420 deviceClockProviderService
421 .setMastershipTerm(deviceId, term);
422 post(store.markOffline(deviceId));
423 } else {
424 log.info("Failed again marking {} offline. {}",
425 deviceId, role);
426 }
427 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700428 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700429 try {
samuel738dfaf2015-07-11 11:08:57 +0800430 // relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700431 mastershipService.relinquishMastership(deviceId).get();
432 } catch (InterruptedException e) {
samuel738dfaf2015-07-11 11:08:57 +0800433 log.warn("Interrupted while reliquishing role for {}",
434 deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700435 Thread.currentThread().interrupt();
436 } catch (ExecutionException e) {
samuel738dfaf2015-07-11 11:08:57 +0800437 log.error("Exception thrown while relinquishing role for {}",
438 deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700439 }
tom0efbb1d2014-09-09 11:54:28 -0700440 }
tomd3097b02014-08-26 10:40:29 -0700441 }
442
443 @Override
alshabibb7b40632014-09-28 21:30:00 -0700444 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700445 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700446 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700447 checkNotNull(portDescriptions,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700448 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700449 checkValidity();
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700450 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
451 // Never been a master for this device
452 // any update will be ignored.
samuel738dfaf2015-07-11 11:08:57 +0800453 log.trace("Ignoring {} port updates on standby node. {}",
454 deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700455 return;
456 }
457
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700458 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuel738dfaf2015-07-11 11:08:57 +0800459 deviceId,
460 portDescriptions);
tom32f66842014-08-27 19:27:47 -0700461 for (DeviceEvent event : events) {
462 post(event);
463 }
tomd3097b02014-08-26 10:40:29 -0700464 }
465
466 @Override
alshabibb7b40632014-09-28 21:30:00 -0700467 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700468 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700469 checkNotNull(deviceId, DEVICE_ID_NULL);
470 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700471 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700472
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700473 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
474 // Never been a master for this device
475 // any update will be ignored.
samuel738dfaf2015-07-11 11:08:57 +0800476 log.trace("Ignoring {} port update on standby node. {}",
477 deviceId, portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700478 return;
479 }
480
samuel738dfaf2015-07-11 11:08:57 +0800481 final DeviceEvent event = store.updatePortStatus(this.provider()
482 .id(), deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700483 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700484 log.info("Device {} port {} status changed", deviceId, event
485 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700486 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700487 }
tomd3097b02014-08-26 10:40:29 -0700488 }
tom3f2bbd72014-09-24 12:07:58 -0700489
490 @Override
samuel738dfaf2015-07-11 11:08:57 +0800491 public void receivedRoleReply(DeviceId deviceId,
492 MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700493 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700494 // Several things can happen here:
495 // 1. request and response match
496 // 2. request and response don't match
497 // 3. MastershipRole and requested match (and 1 or 2 are true)
498 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
499 //
500 // 2, 4, and 3 with case 2 are failure modes.
501
tom3f2bbd72014-09-24 12:07:58 -0700502 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700503
Madan Jampanif2af7712015-05-29 18:43:52 -0700504 log.debug("got reply to a role request for {}: asked for {}, and got {}",
samuel738dfaf2015-07-11 11:08:57 +0800505 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700506
507 if (requested == null && response == null) {
samuel738dfaf2015-07-11 11:08:57 +0800508 // something was off with DeviceProvider, maybe check channel
509 // too?
510 log.warn("Failed to assert role [{}] onto Device {}",
511 requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700512 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700513 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700514 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700515
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700516 if (Objects.equals(requested, response)) {
samuel738dfaf2015-07-11 11:08:57 +0800517 if (Objects.equals(requested,
518 mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700519 return;
520 } else {
521 return;
samuel738dfaf2015-07-11 11:08:57 +0800522 // FIXME roleManager got the device to comply, but doesn't
523 // agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700524 // the store; use the store's view, then try to reassert.
525 }
526 } else {
527 // we didn't get back what we asked for. Reelect someone else.
samuel738dfaf2015-07-11 11:08:57 +0800528 log.warn("Failed to assert role [{}] onto Device {}", response,
529 deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700530 if (response == MastershipRole.MASTER) {
531 mastershipService.relinquishMastership(deviceId);
532 // TODO: Shouldn't we be triggering event?
samuel738dfaf2015-07-11 11:08:57 +0800533 // final Device device = getDevice(deviceId);
534 // post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700535 }
536 }
tom3f2bbd72014-09-24 12:07:58 -0700537 }
sangho538108b2015-04-08 14:29:20 -0700538
539 @Override
samuel738dfaf2015-07-11 11:08:57 +0800540 public void updatePortStatistics(DeviceId deviceId,
541 Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700542 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700543 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700544 checkValidity();
545
samuel738dfaf2015-07-11 11:08:57 +0800546 DeviceEvent event = store
547 .updatePortStatistics(this.provider().id(), deviceId,
548 portStatistics);
sangho538108b2015-04-08 14:29:20 -0700549 post(event);
550 }
tomd3097b02014-08-26 10:40:29 -0700551 }
tom32f66842014-08-27 19:27:47 -0700552
tomeadbb462014-09-07 16:10:19 -0700553 // Posts the specified event to the local event dispatcher.
tom32f66842014-08-27 19:27:47 -0700554 private void post(DeviceEvent event) {
555 if (event != null && eventDispatcher != null) {
556 eventDispatcher.post(event);
557 }
558 }
559
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800560 // Applies the specified role to the device; ignores NONE
561 /**
562 * Apply role to device and send probe if MASTER.
563 *
samuel738dfaf2015-07-11 11:08:57 +0800564 * @param deviceId device identifier
565 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800566 * @return true if the request was sent to provider
567 */
568 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
569 if (newRole.equals(MastershipRole.NONE)) {
samuel738dfaf2015-07-11 11:08:57 +0800570 // no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700571 return true;
572 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700573
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800574 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800575 if (provider == null) {
samuel738dfaf2015-07-11 11:08:57 +0800576 log.warn("Provider for {} was not found. Cannot apply role {}",
577 deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800578 return false;
579 }
580 provider.roleChanged(deviceId, newRole);
581
582 if (newRole.equals(MastershipRole.MASTER)) {
583 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800584 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800585 }
586 return true;
587 }
588
589 /**
590 * Reaasert role for specified device connected to this node.
591 *
samuel738dfaf2015-07-11 11:08:57 +0800592 * @param did device identifier
593 * @param nextRole role to apply. If NONE is specified, it will ask
594 * mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800595 */
samuel738dfaf2015-07-11 11:08:57 +0800596 private void reassertRole(final DeviceId did, final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800597
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800598 MastershipRole myNextRole = nextRole;
599 if (myNextRole == NONE) {
600 mastershipService.requestRoleFor(did);
601 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700602 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800603 myNextRole = MASTER;
604 } else {
605 myNextRole = STANDBY;
606 }
607 }
608
609 switch (myNextRole) {
610 case MASTER:
611 final Device device = getDevice(did);
612 if ((device != null) && !isAvailable(did)) {
samuel738dfaf2015-07-11 11:08:57 +0800613 // flag the device as online. Is there a better way to do this?
614 DefaultDeviceDescription deviceDescription = new DefaultDeviceDescription(
615 did.uri(),
616 device.type(),
617 device.manufacturer(),
618 device.hwVersion(),
619 device.swVersion(),
620 device.serialNumber(),
621 device.chassisId());
622 DeviceEvent devEvent = store.createOrUpdateDevice(device
623 .providerId(), did, deviceDescription);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800624 post(devEvent);
625 }
626 // TODO: should apply role only if there is mismatch
Madan Jampanif2af7712015-05-29 18:43:52 -0700627 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800628 if (!applyRoleAndProbe(did, MASTER)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700629 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800630 // immediately failed to apply role
631 mastershipService.relinquishMastership(did);
632 // FIXME disconnect?
633 }
634 break;
635 case STANDBY:
Madan Jampanif2af7712015-05-29 18:43:52 -0700636 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800637 if (!applyRoleAndProbe(did, STANDBY)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700638 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800639 // immediately failed to apply role
640 mastershipService.relinquishMastership(did);
641 // FIXME disconnect?
642 }
643 break;
644 case NONE:
645 default:
646 // should never reach here
647 log.error("You didn't see anything. I did not exist.");
648 break;
649 }
650 }
651
Madan Jampani328371d2015-05-29 14:06:27 -0700652 private void handleMastershipEvent(MastershipEvent event) {
653 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
654 // Don't care if backup list changed.
655 return;
656 }
657
658 final DeviceId did = event.subject();
659
660 // myRole suggested by MastershipService
661 MastershipRole myNextRole;
662 if (localNodeId.equals(event.roleInfo().master())) {
663 // confirm latest info
664 MastershipTerm term = termService.getMastershipTerm(did);
samuel738dfaf2015-07-11 11:08:57 +0800665 final boolean iHaveControl = term != null
666 && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700667 if (iHaveControl) {
668 deviceClockProviderService.setMastershipTerm(did, term);
669 myNextRole = MASTER;
670 } else {
671 myNextRole = STANDBY;
672 }
673 } else if (event.roleInfo().backups().contains(localNodeId)) {
674 myNextRole = STANDBY;
675 } else {
676 myNextRole = NONE;
677 }
678
Madan Jampani328371d2015-05-29 14:06:27 -0700679 final boolean isReachable = isReachable(did);
680 if (!isReachable) {
681 // device is not connected to this node
682 if (myNextRole != NONE) {
683 log.warn("Node was instructed to be {} role for {}, "
684 + "but this node cannot reach the device. "
samuel738dfaf2015-07-11 11:08:57 +0800685 + "Relinquishing role. ", myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700686 mastershipService.relinquishMastership(did);
687 }
688 return;
689 }
690
691 // device is connected to this node:
692 if (store.getDevice(did) != null) {
693 reassertRole(did, myNextRole);
694 } else {
695 log.debug("Device is not yet/no longer in the store: {}", did);
696 }
697 }
698
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800699 // Intercepts mastership events
700 private class InternalMastershipListener implements MastershipListener {
701
tomb41d1ac2014-09-24 01:51:24 -0700702 @Override
703 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700704 backgroundService.submit(() -> {
705 try {
706 handleMastershipEvent(event);
707 } catch (Exception e) {
708 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700709 }
Madan Jampani328371d2015-05-29 14:06:27 -0700710 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700711 }
tomb41d1ac2014-09-24 01:51:24 -0700712 }
tomf80c9722014-09-24 14:49:18 -0700713
714 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700715 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700716 @Override
717 public void notify(DeviceEvent event) {
718 post(event);
719 }
720 }
samuel738dfaf2015-07-11 11:08:57 +0800721
722 @Override
723 public Iterable<Device> getDevices(Type type) {
724 checkPermission(Permission.DEVICE_READ);
725 Set<Device> results = new HashSet<>();
726 Iterable<Device> devices = store.getDevices();
727 if (devices != null) {
728 devices.forEach(d -> {
729 if (type.equals(d.type())) {
730 results.add(d);
731 }
732 });
733 }
734 return results;
735 }
736
737 @Override
738 public Iterable<Device> getAvailableDevices(Type type) {
739 checkPermission(Permission.DEVICE_READ);
740 Set<Device> results = new HashSet<>();
741 Iterable<Device> availableDevices = store.getAvailableDevices();
742 if (availableDevices != null) {
743 availableDevices.forEach(d -> {
744 if (type.equals(d.type())) {
745 results.add(d);
746 }
747 });
748 }
749 return results;
750 }
tomd3097b02014-08-26 10:40:29 -0700751}