blob: dfd8f298aa3ea8d9c30de3e6e245f35e0790bdbc [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
alshabibafc514a2014-12-01 14:44:05 -080018import com.google.common.collect.Lists;
tomd3097b02014-08-26 10:40:29 -070019import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070022import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070024import org.apache.felix.scr.annotations.Service;
Brian O'Connorabafb502014-12-02 22:26:20 -080025import org.onosproject.cluster.ClusterService;
26import org.onosproject.cluster.NodeId;
Changhoon Yoon541ef712015-05-23 17:18:34 +090027import org.onosproject.core.Permission;
Simon Huntff663742015-05-14 13:33:05 -070028import org.onosproject.event.ListenerRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080029import org.onosproject.event.EventDeliveryService;
30import org.onosproject.mastership.MastershipEvent;
31import org.onosproject.mastership.MastershipListener;
32import org.onosproject.mastership.MastershipService;
33import org.onosproject.mastership.MastershipTerm;
34import org.onosproject.mastership.MastershipTermService;
35import org.onosproject.net.Device;
36import org.onosproject.net.DeviceId;
37import org.onosproject.net.MastershipRole;
38import org.onosproject.net.Port;
39import org.onosproject.net.PortNumber;
40import org.onosproject.net.device.DefaultDeviceDescription;
41import org.onosproject.net.device.DefaultPortDescription;
42import org.onosproject.net.device.DeviceAdminService;
43import org.onosproject.net.device.DeviceClockProviderService;
44import org.onosproject.net.device.DeviceDescription;
45import org.onosproject.net.device.DeviceEvent;
46import org.onosproject.net.device.DeviceListener;
47import org.onosproject.net.device.DeviceProvider;
48import org.onosproject.net.device.DeviceProviderRegistry;
49import org.onosproject.net.device.DeviceProviderService;
50import org.onosproject.net.device.DeviceService;
51import org.onosproject.net.device.DeviceStore;
52import org.onosproject.net.device.DeviceStoreDelegate;
53import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070054import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.provider.AbstractProviderRegistry;
56import org.onosproject.net.provider.AbstractProviderService;
tomd3097b02014-08-26 10:40:29 -070057import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070058
sangho538108b2015-04-08 14:29:20 -070059import java.util.Collection;
Jonathan Hart2f669362015-02-11 16:19:20 -080060import java.util.List;
Thomas Vachuskab17c41f2015-05-19 11:16:05 -070061import java.util.Objects;
Madan Jampanide003d92015-05-11 17:14:20 -070062import java.util.concurrent.CompletableFuture;
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -070063import java.util.concurrent.ExecutionException;
Jonathan Hart2f669362015-02-11 16:19:20 -080064import java.util.concurrent.ScheduledExecutorService;
65import java.util.concurrent.TimeUnit;
66
67import static com.google.common.base.Preconditions.checkNotNull;
Thomas Vachuska6f94ded2015-02-21 14:02:38 -080068import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
69import static org.onlab.util.Tools.groupedThreads;
70import static org.onosproject.net.MastershipRole.*;
Jonathan Hart2f669362015-02-11 16:19:20 -080071import static org.slf4j.LoggerFactory.getLogger;
Changhoon Yoon541ef712015-05-23 17:18:34 +090072import static org.onosproject.security.AppGuard.checkPermission;
73
Jonathan Hart2f669362015-02-11 16:19:20 -080074
tomd3097b02014-08-26 10:40:29 -070075/**
tome4729872014-09-23 00:37:37 -070076 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070077 */
78@Component(immediate = true)
79@Service
tom41a2c5f2014-09-19 09:20:35 -070080public class DeviceManager
Thomas Vachuskad16ce182014-10-29 17:25:29 -070081 extends AbstractProviderRegistry<DeviceProvider, DeviceProviderService>
82 implements DeviceService, DeviceAdminService, DeviceProviderRegistry {
tom32f66842014-08-27 19:27:47 -070083
tome5ec3fd2014-09-04 15:18:06 -070084 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
85 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
86 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
87 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
tomd3097b02014-08-26 10:40:29 -070088
tom5f38b3a2014-08-27 23:50:54 -070089 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -070090
Simon Huntff663742015-05-14 13:33:05 -070091 protected final ListenerRegistry<DeviceEvent, DeviceListener> listenerRegistry =
92 new ListenerRegistry<>();
tom32f66842014-08-27 19:27:47 -070093
alshabib339a3d92014-09-26 17:54:32 -070094 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -070095
tomc78acee2014-09-24 15:16:55 -070096 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -070097 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -070098
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -080099 private ScheduledExecutorService backgroundService;
100
tom41a2c5f2014-09-19 09:20:35 -0700101 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
102 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700103
tom5f38b3a2014-08-27 23:50:54 -0700104 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tome5ec3fd2014-09-04 15:18:06 -0700105 protected EventDeliveryService eventDispatcher;
tom5f38b3a2014-08-27 23:50:54 -0700106
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700108 protected ClusterService clusterService;
109
110 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700111 protected MastershipService mastershipService;
112
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700114 protected MastershipTermService termService;
115
Madan Jampani61056bc2014-09-27 09:07:26 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700117 protected DeviceClockProviderService deviceClockProviderService;
Madan Jampani61056bc2014-09-27 09:07:26 -0700118
tomd3097b02014-08-26 10:40:29 -0700119 @Activate
120 public void activate() {
Thomas Vachuska6f94ded2015-02-21 14:02:38 -0800121 backgroundService = newSingleThreadScheduledExecutor(groupedThreads("onos/device", "manager-background"));
Madan Jampanide003d92015-05-11 17:14:20 -0700122 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800123
tomf80c9722014-09-24 14:49:18 -0700124 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700125 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700126 mastershipService.addListener(mastershipListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800127
128 backgroundService.scheduleWithFixedDelay(new Runnable() {
129
130 @Override
131 public void run() {
132 try {
133 mastershipCheck();
134 } catch (Exception e) {
135 log.error("Exception thrown during integrity check", e);
136 }
137 }
138 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700139 log.info("Started");
140 }
141
142 @Deactivate
143 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800144 backgroundService.shutdown();
145
tomf80c9722014-09-24 14:49:18 -0700146 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700147 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700148 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700149 log.info("Stopped");
150 }
151
152 @Override
tomad2d2092014-09-06 23:24:20 -0700153 public int getDeviceCount() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900154 checkPermission(Permission.DEVICE_READ);
155
tomad2d2092014-09-06 23:24:20 -0700156 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700157 }
158
159 @Override
tom32f66842014-08-27 19:27:47 -0700160 public Iterable<Device> getDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900161 checkPermission(Permission.DEVICE_READ);
162
tome5ec3fd2014-09-04 15:18:06 -0700163 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700164 }
165
tom32f66842014-08-27 19:27:47 -0700166 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800167 public Iterable<Device> getAvailableDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900168 checkPermission(Permission.DEVICE_READ);
169
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800170 return store.getAvailableDevices();
171 }
172
173 @Override
tom32f66842014-08-27 19:27:47 -0700174 public Device getDevice(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900175 checkPermission(Permission.DEVICE_READ);
176
tom32f66842014-08-27 19:27:47 -0700177 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700178 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700179 }
180
181 @Override
tomad2d2092014-09-06 23:24:20 -0700182 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900183 checkPermission(Permission.DEVICE_READ);
184
tomad2d2092014-09-06 23:24:20 -0700185 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700186 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700187 }
188
189 @Override
tom32f66842014-08-27 19:27:47 -0700190 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900191 checkPermission(Permission.DEVICE_READ);
192
tom32f66842014-08-27 19:27:47 -0700193 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700194 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700195 }
196
197 @Override
sangho538108b2015-04-08 14:29:20 -0700198 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900199 checkPermission(Permission.DEVICE_READ);
200
sangho538108b2015-04-08 14:29:20 -0700201 checkNotNull(deviceId, DEVICE_ID_NULL);
202 return store.getPortStatistics(deviceId);
203 }
204
205 @Override
tom32f66842014-08-27 19:27:47 -0700206 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900207 checkPermission(Permission.DEVICE_READ);
208
tom32f66842014-08-27 19:27:47 -0700209 checkNotNull(deviceId, DEVICE_ID_NULL);
210 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700211 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700212 }
213
214 @Override
tomff7eb7c2014-09-08 12:49:03 -0700215 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900216 checkPermission(Permission.DEVICE_READ);
217
tomff7eb7c2014-09-08 12:49:03 -0700218 checkNotNull(deviceId, DEVICE_ID_NULL);
219 return store.isAvailable(deviceId);
220 }
221
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700222 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700223 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800224 if (deviceId == null) {
225 return false;
226 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700227 DeviceProvider provider = getProvider(deviceId);
228 if (provider != null) {
229 return provider.isReachable(deviceId);
230 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800231 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700232 return false;
233 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700234 }
235
tome5ec3fd2014-09-04 15:18:06 -0700236 @Override
237 public void removeDevice(DeviceId deviceId) {
238 checkNotNull(deviceId, DEVICE_ID_NULL);
239 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700240 if (event != null) {
241 log.info("Device {} administratively removed", deviceId);
242 post(event);
243 }
tome5ec3fd2014-09-04 15:18:06 -0700244 }
245
tom7869ad92014-09-09 14:32:08 -0700246 @Override
247 public void addListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900248 checkPermission(Permission.DEVICE_EVENT);
249
tom7869ad92014-09-09 14:32:08 -0700250 listenerRegistry.addListener(listener);
251 }
252
253 @Override
254 public void removeListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900255 checkPermission(Permission.DEVICE_EVENT);
256
tom7869ad92014-09-09 14:32:08 -0700257 listenerRegistry.removeListener(listener);
258 }
259
260 @Override
alshabibb7b40632014-09-28 21:30:00 -0700261 protected DeviceProviderService createProviderService(
262 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700263 return new InternalDeviceProviderService(provider);
264 }
265
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800266 /**
267 * Checks if all the reachable devices have a valid mastership role.
268 */
269 private void mastershipCheck() {
270 log.debug("Checking mastership");
271 for (Device device : getDevices()) {
272 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800273 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800274
275 if (!isReachable(deviceId)) {
276 continue;
277 }
278
279 if (mastershipService.getLocalRole(deviceId) != NONE) {
280 continue;
281 }
282
283 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
284
285 // isReachable but was not MASTER or STANDBY, get a role and apply
286 // Note: NONE triggers request to MastershipService
287 reassertRole(deviceId, NONE);
288 }
289 }
290
tomd3097b02014-08-26 10:40:29 -0700291 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700292 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700293 extends AbstractProviderService<DeviceProvider>
294 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700295
tomcfde0622014-09-09 11:02:42 -0700296 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700297 super(provider);
298 }
299
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700300 /**
301 * Apply role in reaction to provider event.
302 *
303 * @param deviceId device identifier
304 * @param newRole new role to apply to the device
305 * @return true if the request was sent to provider
306 */
307 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
308
309 if (newRole.equals(MastershipRole.NONE)) {
310 //no-op
311 return true;
312 }
313
314 DeviceProvider provider = provider();
315 if (provider == null) {
316 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
317 return false;
318 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700319 provider.roleChanged(deviceId, newRole);
320 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700321
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700322 return true;
323 }
324
325
tomd3097b02014-08-26 10:40:29 -0700326 @Override
alshabibb7b40632014-09-28 21:30:00 -0700327 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700328 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700329 checkNotNull(deviceId, DEVICE_ID_NULL);
330 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700331 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700332
333 log.info("Device {} connected", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700334 // check my Role
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700335 CompletableFuture<MastershipRole> role = mastershipService.requestRoleFor(deviceId);
336 try {
337 // Device subsystem must wait for role assignment
338 // to avoid losing Device information.
339 // (This node could be the only Node connected to the Device.)
340 role.get();
341 } catch (InterruptedException e) {
342 log.warn("Interrupted while waiting role-assignment for {}", deviceId);
343 Thread.currentThread().interrupt();
344 } catch (ExecutionException e) {
345 log.error("Exception thrown while waiting role-assignment for {}",
346 deviceId, e);
347 }
348
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700349 final MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700350 if (term == null || !localNodeId.equals(term.master())) {
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700351 log.info("Role of this node is STANDBY for {}", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700352 applyRole(deviceId, MastershipRole.STANDBY);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800353 } else {
354 log.info("Role of this node is MASTER for {}", deviceId);
355 // tell clock provider if this instance is the master
356 deviceClockProviderService.setMastershipTerm(deviceId, term);
357 applyRole(deviceId, MastershipRole.MASTER);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700358 }
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700359
tome5ec3fd2014-09-04 15:18:06 -0700360 DeviceEvent event = store.createOrUpdateDevice(provider().id(),
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700361 deviceId, deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700362
tom80c0e5e2014-09-08 18:08:58 -0700363 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700364 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700365 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700366 }
tomd3097b02014-08-26 10:40:29 -0700367 }
368
369 @Override
370 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700371 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700372 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700373
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700374 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700375
alshabibafc514a2014-12-01 14:44:05 -0800376 List<Port> ports = store.getPorts(deviceId);
377 List<PortDescription> descs = Lists.newArrayList();
378 ports.forEach(port ->
379 descs.add(new DefaultPortDescription(port.number(),
380 false, port.type(),
381 port.portSpeed())));
382 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700383 try {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700384 if (mastershipService.getLocalRole(deviceId) == MASTER) {
385 post(store.markOffline(deviceId));
386 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700387 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700388 log.warn("Failed to mark {} offline", deviceId);
389 // only the MASTER should be marking off-line in normal cases,
390 // but if I was the last STANDBY connection, etc. and no one else
391 // was there to mark the device offline, this instance may need to
392 // temporarily request for Master Role and mark offline.
393
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700394 //there are times when this node will correctly have mastership, BUT
395 //that isn't reflected in the ClockManager before the device disconnects.
396 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700397
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700398 // FIXME: Store semantics leaking out as IllegalStateException.
399 // Consider revising store API to handle this scenario.
Madan Jampanide003d92015-05-11 17:14:20 -0700400 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
401 roleFuture.whenComplete((role, error) -> {
402 MastershipTerm term = termService.getMastershipTerm(deviceId);
403 // TODO: Move this type of check inside device clock manager, etc.
404 if (term != null && localNodeId.equals(term.master())) {
405 log.info("Retry marking {} offline", deviceId);
406 deviceClockProviderService.setMastershipTerm(deviceId, term);
407 post(store.markOffline(deviceId));
408 } else {
409 log.info("Failed again marking {} offline. {}", deviceId, role);
410 }
411 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700412 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700413 try {
414 //relinquish master role and ability to be backup.
415 mastershipService.relinquishMastership(deviceId).get();
416 } catch (InterruptedException e) {
417 log.warn("Interrupted while reliquishing role for {}", deviceId);
418 Thread.currentThread().interrupt();
419 } catch (ExecutionException e) {
420 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
421 }
tom0efbb1d2014-09-09 11:54:28 -0700422 }
tomd3097b02014-08-26 10:40:29 -0700423 }
424
425 @Override
alshabibb7b40632014-09-28 21:30:00 -0700426 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700427 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700428 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700429 checkNotNull(portDescriptions,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700430 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700431 checkValidity();
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700432 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
433 // Never been a master for this device
434 // any update will be ignored.
435 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
436 return;
437 }
438
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700439 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700440 deviceId, portDescriptions);
tom32f66842014-08-27 19:27:47 -0700441 for (DeviceEvent event : events) {
442 post(event);
443 }
tomd3097b02014-08-26 10:40:29 -0700444 }
445
446 @Override
alshabibb7b40632014-09-28 21:30:00 -0700447 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700448 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700449 checkNotNull(deviceId, DEVICE_ID_NULL);
450 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700451 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700452
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700453 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
454 // Never been a master for this device
455 // any update will be ignored.
456 log.trace("Ignoring {} port update on standby node. {}", deviceId, portDescription);
457 return;
458 }
459
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700460 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700461 deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700462 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700463 log.info("Device {} port {} status changed", deviceId, event
464 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700465 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700466 }
tomd3097b02014-08-26 10:40:29 -0700467 }
tom3f2bbd72014-09-24 12:07:58 -0700468
469 @Override
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700470 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
471 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700472 // Several things can happen here:
473 // 1. request and response match
474 // 2. request and response don't match
475 // 3. MastershipRole and requested match (and 1 or 2 are true)
476 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
477 //
478 // 2, 4, and 3 with case 2 are failure modes.
479
tom3f2bbd72014-09-24 12:07:58 -0700480 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700481
Madan Jampanif2af7712015-05-29 18:43:52 -0700482 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700483 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700484
485 if (requested == null && response == null) {
486 // something was off with DeviceProvider, maybe check channel too?
487 log.warn("Failed to assert role [{}] onto Device {}", requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700488 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700489 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700490 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700491
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700492 if (Objects.equals(requested, response)) {
493 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700494 return;
495 } else {
496 return;
497 // FIXME roleManager got the device to comply, but doesn't agree with
498 // the store; use the store's view, then try to reassert.
499 }
500 } else {
501 // we didn't get back what we asked for. Reelect someone else.
502 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
503 if (response == MastershipRole.MASTER) {
504 mastershipService.relinquishMastership(deviceId);
505 // TODO: Shouldn't we be triggering event?
506 //final Device device = getDevice(deviceId);
507 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
508 }
509 }
tom3f2bbd72014-09-24 12:07:58 -0700510 }
sangho538108b2015-04-08 14:29:20 -0700511
512 @Override
513 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
514 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700515 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700516 checkValidity();
517
518 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700519 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700520 post(event);
521 }
tomd3097b02014-08-26 10:40:29 -0700522 }
tom32f66842014-08-27 19:27:47 -0700523
tomeadbb462014-09-07 16:10:19 -0700524 // Posts the specified event to the local event dispatcher.
tom32f66842014-08-27 19:27:47 -0700525 private void post(DeviceEvent event) {
526 if (event != null && eventDispatcher != null) {
527 eventDispatcher.post(event);
528 }
529 }
530
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800531 // Applies the specified role to the device; ignores NONE
532 /**
533 * Apply role to device and send probe if MASTER.
534 *
535 * @param deviceId device identifier
536 * @param newRole new role to apply to the device
537 * @return true if the request was sent to provider
538 */
539 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
540 if (newRole.equals(MastershipRole.NONE)) {
541 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700542 return true;
543 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700544
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800545 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800546 if (provider == null) {
547 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
548 return false;
549 }
550 provider.roleChanged(deviceId, newRole);
551
552 if (newRole.equals(MastershipRole.MASTER)) {
553 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800554 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800555 }
556 return true;
557 }
558
559 /**
560 * Reaasert role for specified device connected to this node.
561 *
562 * @param did device identifier
563 * @param nextRole role to apply. If NONE is specified,
564 * it will ask mastership service for a role and apply it.
565 */
566 private void reassertRole(final DeviceId did,
567 final MastershipRole nextRole) {
568
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800569 MastershipRole myNextRole = nextRole;
570 if (myNextRole == NONE) {
571 mastershipService.requestRoleFor(did);
572 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700573 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800574 myNextRole = MASTER;
575 } else {
576 myNextRole = STANDBY;
577 }
578 }
579
580 switch (myNextRole) {
581 case MASTER:
582 final Device device = getDevice(did);
583 if ((device != null) && !isAvailable(did)) {
584 //flag the device as online. Is there a better way to do this?
585 DefaultDeviceDescription deviceDescription
586 = new DefaultDeviceDescription(did.uri(),
587 device.type(),
588 device.manufacturer(),
589 device.hwVersion(),
590 device.swVersion(),
591 device.serialNumber(),
592 device.chassisId());
593 DeviceEvent devEvent =
594 store.createOrUpdateDevice(device.providerId(), did,
595 deviceDescription);
596 post(devEvent);
597 }
598 // TODO: should apply role only if there is mismatch
Madan Jampanif2af7712015-05-29 18:43:52 -0700599 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800600 if (!applyRoleAndProbe(did, MASTER)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700601 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800602 // immediately failed to apply role
603 mastershipService.relinquishMastership(did);
604 // FIXME disconnect?
605 }
606 break;
607 case STANDBY:
Madan Jampanif2af7712015-05-29 18:43:52 -0700608 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800609 if (!applyRoleAndProbe(did, STANDBY)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700610 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800611 // immediately failed to apply role
612 mastershipService.relinquishMastership(did);
613 // FIXME disconnect?
614 }
615 break;
616 case NONE:
617 default:
618 // should never reach here
619 log.error("You didn't see anything. I did not exist.");
620 break;
621 }
622 }
623
Madan Jampani328371d2015-05-29 14:06:27 -0700624 private void handleMastershipEvent(MastershipEvent event) {
625 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
626 // Don't care if backup list changed.
627 return;
628 }
629
630 final DeviceId did = event.subject();
631
632 // myRole suggested by MastershipService
633 MastershipRole myNextRole;
634 if (localNodeId.equals(event.roleInfo().master())) {
635 // confirm latest info
636 MastershipTerm term = termService.getMastershipTerm(did);
637 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
638 if (iHaveControl) {
639 deviceClockProviderService.setMastershipTerm(did, term);
640 myNextRole = MASTER;
641 } else {
642 myNextRole = STANDBY;
643 }
644 } else if (event.roleInfo().backups().contains(localNodeId)) {
645 myNextRole = STANDBY;
646 } else {
647 myNextRole = NONE;
648 }
649
650
651 final boolean isReachable = isReachable(did);
652 if (!isReachable) {
653 // device is not connected to this node
654 if (myNextRole != NONE) {
655 log.warn("Node was instructed to be {} role for {}, "
656 + "but this node cannot reach the device. "
657 + "Relinquishing role. ",
658 myNextRole, did);
659 mastershipService.relinquishMastership(did);
660 }
661 return;
662 }
663
664 // device is connected to this node:
665 if (store.getDevice(did) != null) {
666 reassertRole(did, myNextRole);
667 } else {
668 log.debug("Device is not yet/no longer in the store: {}", did);
669 }
670 }
671
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800672 // Intercepts mastership events
673 private class InternalMastershipListener implements MastershipListener {
674
tomb41d1ac2014-09-24 01:51:24 -0700675 @Override
676 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700677 backgroundService.submit(() -> {
678 try {
679 handleMastershipEvent(event);
680 } catch (Exception e) {
681 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700682 }
Madan Jampani328371d2015-05-29 14:06:27 -0700683 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700684 }
tomb41d1ac2014-09-24 01:51:24 -0700685 }
tomf80c9722014-09-24 14:49:18 -0700686
687 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700688 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700689 @Override
690 public void notify(DeviceEvent event) {
691 post(event);
692 }
693 }
tomd3097b02014-08-26 10:40:29 -0700694}