blob: d71b79648d3c0d0a3530b6e8c15c4d1d99c113fc [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
samuele1fa7322015-07-14 16:35:16 +080080
tomd3097b02014-08-26 10:40:29 -070081/**
tome4729872014-09-23 00:37:37 -070082 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070083 */
84@Component(immediate = true)
85@Service
tom41a2c5f2014-09-19 09:20:35 -070086public class DeviceManager
Thomas Vachuskad16ce182014-10-29 17:25:29 -070087 extends AbstractProviderRegistry<DeviceProvider, DeviceProviderService>
88 implements DeviceService, DeviceAdminService, DeviceProviderRegistry {
tom32f66842014-08-27 19:27:47 -070089
tome5ec3fd2014-09-04 15:18:06 -070090 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
91 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
92 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
93 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
tomd3097b02014-08-26 10:40:29 -070094
tom5f38b3a2014-08-27 23:50:54 -070095 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -070096
samuele1fa7322015-07-14 16:35:16 +080097 protected final ListenerRegistry<DeviceEvent, DeviceListener> listenerRegistry =
98 new ListenerRegistry<>();
tom32f66842014-08-27 19:27:47 -070099
alshabib339a3d92014-09-26 17:54:32 -0700100 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700101
tomc78acee2014-09-24 15:16:55 -0700102 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700103 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700104
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800105 private ScheduledExecutorService backgroundService;
106
tom41a2c5f2014-09-19 09:20:35 -0700107 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
108 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700109
tom5f38b3a2014-08-27 23:50:54 -0700110 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tome5ec3fd2014-09-04 15:18:06 -0700111 protected EventDeliveryService eventDispatcher;
tom5f38b3a2014-08-27 23:50:54 -0700112
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700114 protected ClusterService clusterService;
115
116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700117 protected MastershipService mastershipService;
118
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700120 protected MastershipTermService termService;
121
Madan Jampani61056bc2014-09-27 09:07:26 -0700122 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700123 protected DeviceClockProviderService deviceClockProviderService;
Madan Jampani61056bc2014-09-27 09:07:26 -0700124
tomd3097b02014-08-26 10:40:29 -0700125 @Activate
126 public void activate() {
samuele1fa7322015-07-14 16:35:16 +0800127 backgroundService = newSingleThreadScheduledExecutor(groupedThreads("onos/device", "manager-background"));
Madan Jampanide003d92015-05-11 17:14:20 -0700128 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800129
tomf80c9722014-09-24 14:49:18 -0700130 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700131 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700132 mastershipService.addListener(mastershipListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800133
134 backgroundService.scheduleWithFixedDelay(new Runnable() {
135
136 @Override
137 public void run() {
138 try {
139 mastershipCheck();
140 } catch (Exception e) {
141 log.error("Exception thrown during integrity check", e);
142 }
143 }
144 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700145 log.info("Started");
146 }
147
148 @Deactivate
149 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800150 backgroundService.shutdown();
151
tomf80c9722014-09-24 14:49:18 -0700152 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700153 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700154 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700155 log.info("Stopped");
156 }
157
158 @Override
tomad2d2092014-09-06 23:24:20 -0700159 public int getDeviceCount() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900160 checkPermission(Permission.DEVICE_READ);
161
tomad2d2092014-09-06 23:24:20 -0700162 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700163 }
164
165 @Override
tom32f66842014-08-27 19:27:47 -0700166 public Iterable<Device> getDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900167 checkPermission(Permission.DEVICE_READ);
168
tome5ec3fd2014-09-04 15:18:06 -0700169 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700170 }
171
tom32f66842014-08-27 19:27:47 -0700172 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800173 public Iterable<Device> getAvailableDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900174 checkPermission(Permission.DEVICE_READ);
175
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800176 return store.getAvailableDevices();
177 }
178
179 @Override
tom32f66842014-08-27 19:27:47 -0700180 public Device getDevice(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900181 checkPermission(Permission.DEVICE_READ);
182
tom32f66842014-08-27 19:27:47 -0700183 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700184 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700185 }
186
187 @Override
tomad2d2092014-09-06 23:24:20 -0700188 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900189 checkPermission(Permission.DEVICE_READ);
190
tomad2d2092014-09-06 23:24:20 -0700191 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700192 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700193 }
194
195 @Override
tom32f66842014-08-27 19:27:47 -0700196 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900197 checkPermission(Permission.DEVICE_READ);
198
tom32f66842014-08-27 19:27:47 -0700199 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700200 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700201 }
202
203 @Override
sangho538108b2015-04-08 14:29:20 -0700204 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900205 checkPermission(Permission.DEVICE_READ);
206
sangho538108b2015-04-08 14:29:20 -0700207 checkNotNull(deviceId, DEVICE_ID_NULL);
208 return store.getPortStatistics(deviceId);
209 }
210
211 @Override
tom32f66842014-08-27 19:27:47 -0700212 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900213 checkPermission(Permission.DEVICE_READ);
214
tom32f66842014-08-27 19:27:47 -0700215 checkNotNull(deviceId, DEVICE_ID_NULL);
216 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700217 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700218 }
219
220 @Override
tomff7eb7c2014-09-08 12:49:03 -0700221 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900222 checkPermission(Permission.DEVICE_READ);
223
tomff7eb7c2014-09-08 12:49:03 -0700224 checkNotNull(deviceId, DEVICE_ID_NULL);
225 return store.isAvailable(deviceId);
226 }
227
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700228 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700229 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800230 if (deviceId == null) {
231 return false;
232 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700233 DeviceProvider provider = getProvider(deviceId);
234 if (provider != null) {
235 return provider.isReachable(deviceId);
236 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800237 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700238 return false;
239 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700240 }
241
tome5ec3fd2014-09-04 15:18:06 -0700242 @Override
243 public void removeDevice(DeviceId deviceId) {
244 checkNotNull(deviceId, DEVICE_ID_NULL);
245 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700246 if (event != null) {
247 log.info("Device {} administratively removed", deviceId);
248 post(event);
249 }
tome5ec3fd2014-09-04 15:18:06 -0700250 }
251
tom7869ad92014-09-09 14:32:08 -0700252 @Override
253 public void addListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900254 checkPermission(Permission.DEVICE_EVENT);
255
tom7869ad92014-09-09 14:32:08 -0700256 listenerRegistry.addListener(listener);
257 }
258
259 @Override
260 public void removeListener(DeviceListener listener) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900261 checkPermission(Permission.DEVICE_EVENT);
262
tom7869ad92014-09-09 14:32:08 -0700263 listenerRegistry.removeListener(listener);
264 }
265
266 @Override
samuele1fa7322015-07-14 16:35:16 +0800267 protected DeviceProviderService createProviderService(
268 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700269 return new InternalDeviceProviderService(provider);
270 }
271
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800272 /**
273 * Checks if all the reachable devices have a valid mastership role.
274 */
275 private void mastershipCheck() {
276 log.debug("Checking mastership");
277 for (Device device : getDevices()) {
278 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800279 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800280
281 if (!isReachable(deviceId)) {
282 continue;
283 }
284
285 if (mastershipService.getLocalRole(deviceId) != NONE) {
286 continue;
287 }
288
samuele1fa7322015-07-14 16:35:16 +0800289 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800290
291 // isReachable but was not MASTER or STANDBY, get a role and apply
292 // Note: NONE triggers request to MastershipService
293 reassertRole(deviceId, NONE);
294 }
295 }
296
tomd3097b02014-08-26 10:40:29 -0700297 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700298 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700299 extends AbstractProviderService<DeviceProvider>
300 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700301
tomcfde0622014-09-09 11:02:42 -0700302 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700303 super(provider);
304 }
305
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700306 /**
307 * Apply role in reaction to provider event.
308 *
samuele1fa7322015-07-14 16:35:16 +0800309 * @param deviceId device identifier
310 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700311 * @return true if the request was sent to provider
312 */
313 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
314
315 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800316 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700317 return true;
318 }
319
320 DeviceProvider provider = provider();
321 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800322 log.warn("Provider for {} was not found. Cannot apply role {}", 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
samuele1fa7322015-07-14 16:35:16 +0800331
tomd3097b02014-08-26 10:40:29 -0700332 @Override
alshabibb7b40632014-09-28 21:30:00 -0700333 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700334 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700335 checkNotNull(deviceId, DEVICE_ID_NULL);
336 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700337 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700338
339 log.info("Device {} connected", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700340 // check my Role
samuele1fa7322015-07-14 16:35:16 +0800341 CompletableFuture<MastershipRole> role = mastershipService.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) {
samuele1fa7322015-07-14 16:35:16 +0800348 log.warn("Interrupted while waiting role-assignment for {}", deviceId);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700349 Thread.currentThread().interrupt();
350 } catch (ExecutionException e) {
351 log.error("Exception thrown while waiting role-assignment for {}",
352 deviceId, e);
353 }
354
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700355 final MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700356 if (term == null || !localNodeId.equals(term.master())) {
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700357 log.info("Role of this node is STANDBY for {}", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700358 applyRole(deviceId, MastershipRole.STANDBY);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800359 } else {
360 log.info("Role of this node is MASTER for {}", deviceId);
361 // tell clock provider if this instance is the master
362 deviceClockProviderService.setMastershipTerm(deviceId, term);
363 applyRole(deviceId, MastershipRole.MASTER);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700364 }
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700365
tome5ec3fd2014-09-04 15:18:06 -0700366 DeviceEvent event = store.createOrUpdateDevice(provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800367 deviceId, deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700368
tom80c0e5e2014-09-08 18:08:58 -0700369 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700370 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700371 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700372 }
tomd3097b02014-08-26 10:40:29 -0700373 }
374
375 @Override
376 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700377 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700378 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700379
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700380 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700381
alshabibafc514a2014-12-01 14:44:05 -0800382 List<Port> ports = store.getPorts(deviceId);
383 List<PortDescription> descs = Lists.newArrayList();
samuele1fa7322015-07-14 16:35:16 +0800384 ports.forEach(port ->
385 descs.add(new DefaultPortDescription(port.number(),
386 false, port.type(),
387 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,
samuele1fa7322015-07-14 16:35:16 +0800396 // but if I was the last STANDBY connection, etc. and no one else
397 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700398 // temporarily request for Master Role and mark offline.
399
samuele1fa7322015-07-14 16:35:16 +0800400 //there are times when this node will correctly have mastership, BUT
401 //that isn't reflected in the ClockManager before the device disconnects.
402 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700403
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700404 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800405 // Consider revising store API to handle this scenario.
406 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700407 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800408 MastershipTerm term = termService.getMastershipTerm(deviceId);
409 // TODO: Move this type of check inside device clock manager, etc.
410 if (term != null && localNodeId.equals(term.master())) {
411 log.info("Retry marking {} offline", deviceId);
412 deviceClockProviderService.setMastershipTerm(deviceId, term);
413 post(store.markOffline(deviceId));
414 } else {
415 log.info("Failed again marking {} offline. {}", deviceId, role);
416 }
417 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700418 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700419 try {
samuele1fa7322015-07-14 16:35:16 +0800420 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700421 mastershipService.relinquishMastership(deviceId).get();
422 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800423 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700424 Thread.currentThread().interrupt();
425 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800426 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700427 }
tom0efbb1d2014-09-09 11:54:28 -0700428 }
tomd3097b02014-08-26 10:40:29 -0700429 }
430
431 @Override
alshabibb7b40632014-09-28 21:30:00 -0700432 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700433 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700434 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700435 checkNotNull(portDescriptions,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700436 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700437 checkValidity();
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700438 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
439 // Never been a master for this device
440 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800441 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700442 return;
443 }
444
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700445 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800446 deviceId, portDescriptions);
tom32f66842014-08-27 19:27:47 -0700447 for (DeviceEvent event : events) {
448 post(event);
449 }
tomd3097b02014-08-26 10:40:29 -0700450 }
451
452 @Override
alshabibb7b40632014-09-28 21:30:00 -0700453 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700454 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700455 checkNotNull(deviceId, DEVICE_ID_NULL);
456 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700457 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700458
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700459 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
460 // Never been a master for this device
461 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800462 log.trace("Ignoring {} port update on standby node. {}", deviceId, portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700463 return;
464 }
465
samuele1fa7322015-07-14 16:35:16 +0800466 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
467 deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700468 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700469 log.info("Device {} port {} status changed", deviceId, event
470 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700471 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700472 }
tomd3097b02014-08-26 10:40:29 -0700473 }
tom3f2bbd72014-09-24 12:07:58 -0700474
475 @Override
samuele1fa7322015-07-14 16:35:16 +0800476 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700477 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700478 // Several things can happen here:
479 // 1. request and response match
480 // 2. request and response don't match
481 // 3. MastershipRole and requested match (and 1 or 2 are true)
482 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
483 //
484 // 2, 4, and 3 with case 2 are failure modes.
485
tom3f2bbd72014-09-24 12:07:58 -0700486 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700487
Madan Jampanif2af7712015-05-29 18:43:52 -0700488 log.debug("got reply to a role request for {}: asked for {}, and got {}",
samuele1fa7322015-07-14 16:35:16 +0800489 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700490
491 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800492 // something was off with DeviceProvider, maybe check channel too?
493 log.warn("Failed to assert role [{}] onto Device {}", requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700494 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700495 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700496 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700497
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700498 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800499 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700500 return;
501 } else {
502 return;
samuele1fa7322015-07-14 16:35:16 +0800503 // FIXME roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700504 // the store; use the store's view, then try to reassert.
505 }
506 } else {
507 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800508 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700509 if (response == MastershipRole.MASTER) {
510 mastershipService.relinquishMastership(deviceId);
511 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800512 //final Device device = getDevice(deviceId);
513 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700514 }
515 }
tom3f2bbd72014-09-24 12:07:58 -0700516 }
sangho538108b2015-04-08 14:29:20 -0700517
518 @Override
samuele1fa7322015-07-14 16:35:16 +0800519 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700520 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700521 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700522 checkValidity();
523
samuele1fa7322015-07-14 16:35:16 +0800524 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
525 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700526 post(event);
527 }
tomd3097b02014-08-26 10:40:29 -0700528 }
tom32f66842014-08-27 19:27:47 -0700529
tomeadbb462014-09-07 16:10:19 -0700530 // Posts the specified event to the local event dispatcher.
tom32f66842014-08-27 19:27:47 -0700531 private void post(DeviceEvent event) {
532 if (event != null && eventDispatcher != null) {
533 eventDispatcher.post(event);
534 }
535 }
536
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800537 // Applies the specified role to the device; ignores NONE
538 /**
539 * Apply role to device and send probe if MASTER.
540 *
samuele1fa7322015-07-14 16:35:16 +0800541 * @param deviceId device identifier
542 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800543 * @return true if the request was sent to provider
544 */
545 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
546 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800547 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700548 return true;
549 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700550
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800551 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800552 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800553 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800554 return false;
555 }
556 provider.roleChanged(deviceId, newRole);
557
558 if (newRole.equals(MastershipRole.MASTER)) {
559 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800560 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800561 }
562 return true;
563 }
564
565 /**
566 * Reaasert role for specified device connected to this node.
567 *
samuele1fa7322015-07-14 16:35:16 +0800568 * @param did device identifier
569 * @param nextRole role to apply. If NONE is specified,
570 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800571 */
samuele1fa7322015-07-14 16:35:16 +0800572 private void reassertRole(final DeviceId did,
573 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800574
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800575 MastershipRole myNextRole = nextRole;
576 if (myNextRole == NONE) {
577 mastershipService.requestRoleFor(did);
578 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700579 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800580 myNextRole = MASTER;
581 } else {
582 myNextRole = STANDBY;
583 }
584 }
585
586 switch (myNextRole) {
587 case MASTER:
588 final Device device = getDevice(did);
589 if ((device != null) && !isAvailable(did)) {
samuele1fa7322015-07-14 16:35:16 +0800590 //flag the device as online. Is there a better way to do this?
591 DefaultDeviceDescription deviceDescription
592 = new DefaultDeviceDescription(did.uri(),
593 device.type(),
594 device.manufacturer(),
595 device.hwVersion(),
596 device.swVersion(),
597 device.serialNumber(),
598 device.chassisId());
599 DeviceEvent devEvent =
600 store.createOrUpdateDevice(device.providerId(), did,
601 deviceDescription);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800602 post(devEvent);
603 }
604 // TODO: should apply role only if there is mismatch
Madan Jampanif2af7712015-05-29 18:43:52 -0700605 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800606 if (!applyRoleAndProbe(did, MASTER)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700607 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800608 // immediately failed to apply role
609 mastershipService.relinquishMastership(did);
610 // FIXME disconnect?
611 }
612 break;
613 case STANDBY:
Madan Jampanif2af7712015-05-29 18:43:52 -0700614 log.debug("Applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800615 if (!applyRoleAndProbe(did, STANDBY)) {
Madan Jampanif2af7712015-05-29 18:43:52 -0700616 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800617 // immediately failed to apply role
618 mastershipService.relinquishMastership(did);
619 // FIXME disconnect?
620 }
621 break;
622 case NONE:
623 default:
624 // should never reach here
625 log.error("You didn't see anything. I did not exist.");
626 break;
627 }
628 }
629
Madan Jampani328371d2015-05-29 14:06:27 -0700630 private void handleMastershipEvent(MastershipEvent event) {
631 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
632 // Don't care if backup list changed.
633 return;
634 }
635
636 final DeviceId did = event.subject();
637
638 // myRole suggested by MastershipService
639 MastershipRole myNextRole;
640 if (localNodeId.equals(event.roleInfo().master())) {
641 // confirm latest info
642 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800643 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700644 if (iHaveControl) {
645 deviceClockProviderService.setMastershipTerm(did, term);
646 myNextRole = MASTER;
647 } else {
648 myNextRole = STANDBY;
649 }
650 } else if (event.roleInfo().backups().contains(localNodeId)) {
651 myNextRole = STANDBY;
652 } else {
653 myNextRole = NONE;
654 }
655
samuele1fa7322015-07-14 16:35:16 +0800656
Madan Jampani328371d2015-05-29 14:06:27 -0700657 final boolean isReachable = isReachable(did);
658 if (!isReachable) {
659 // device is not connected to this node
660 if (myNextRole != NONE) {
661 log.warn("Node was instructed to be {} role for {}, "
662 + "but this node cannot reach the device. "
samuele1fa7322015-07-14 16:35:16 +0800663 + "Relinquishing role. ",
664 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700665 mastershipService.relinquishMastership(did);
666 }
667 return;
668 }
669
670 // device is connected to this node:
671 if (store.getDevice(did) != null) {
672 reassertRole(did, myNextRole);
673 } else {
674 log.debug("Device is not yet/no longer in the store: {}", did);
675 }
676 }
677
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800678 // Intercepts mastership events
679 private class InternalMastershipListener implements MastershipListener {
680
tomb41d1ac2014-09-24 01:51:24 -0700681 @Override
682 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700683 backgroundService.submit(() -> {
684 try {
685 handleMastershipEvent(event);
686 } catch (Exception e) {
687 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700688 }
Madan Jampani328371d2015-05-29 14:06:27 -0700689 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700690 }
tomb41d1ac2014-09-24 01:51:24 -0700691 }
tomf80c9722014-09-24 14:49:18 -0700692
693 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700694 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700695 @Override
696 public void notify(DeviceEvent event) {
697 post(event);
698 }
699 }
samuel738dfaf2015-07-11 11:08:57 +0800700
701 @Override
702 public Iterable<Device> getDevices(Type type) {
703 checkPermission(Permission.DEVICE_READ);
704 Set<Device> results = new HashSet<>();
705 Iterable<Device> devices = store.getDevices();
706 if (devices != null) {
707 devices.forEach(d -> {
708 if (type.equals(d.type())) {
709 results.add(d);
710 }
711 });
712 }
713 return results;
714 }
715
716 @Override
717 public Iterable<Device> getAvailableDevices(Type type) {
718 checkPermission(Permission.DEVICE_READ);
719 Set<Device> results = new HashSet<>();
720 Iterable<Device> availableDevices = store.getAvailableDevices();
721 if (availableDevices != null) {
722 availableDevices.forEach(d -> {
723 if (type.equals(d.type())) {
724 results.add(d);
725 }
726 });
727 }
728 return results;
729 }
tomd3097b02014-08-26 10:40:29 -0700730}