blob: 6a1724da2e5b90b393be9e09d5b28b88aa713c8c [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
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070018import com.google.common.collect.Lists;
Madan Jampani565a66a2015-07-25 17:01:13 -070019import com.google.common.util.concurrent.Futures;
20
tomd3097b02014-08-26 10:40:29 -070021import org.apache.felix.scr.annotations.Activate;
22import org.apache.felix.scr.annotations.Component;
23import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070024import org.apache.felix.scr.annotations.Reference;
25import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070026import org.apache.felix.scr.annotations.Service;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.cluster.ClusterService;
28import org.onosproject.cluster.NodeId;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070029import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Changhoon Yoon541ef712015-05-23 17:18:34 +090030import org.onosproject.core.Permission;
Ray Milkeya4122362015-08-18 15:19:08 -070031import org.onosproject.net.config.NetworkConfigEvent;
32import org.onosproject.net.config.NetworkConfigListener;
33import org.onosproject.net.config.NetworkConfigService;
Sahil Lele3a0cdd52015-07-21 14:16:31 -070034import org.onosproject.incubator.net.config.basics.BasicDeviceConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.mastership.MastershipEvent;
36import org.onosproject.mastership.MastershipListener;
37import org.onosproject.mastership.MastershipService;
38import org.onosproject.mastership.MastershipTerm;
39import org.onosproject.mastership.MastershipTermService;
40import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080041import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.DeviceId;
43import org.onosproject.net.MastershipRole;
44import org.onosproject.net.Port;
45import org.onosproject.net.PortNumber;
46import org.onosproject.net.device.DefaultDeviceDescription;
47import org.onosproject.net.device.DefaultPortDescription;
48import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.device.DeviceDescription;
50import org.onosproject.net.device.DeviceEvent;
51import org.onosproject.net.device.DeviceListener;
52import org.onosproject.net.device.DeviceProvider;
53import org.onosproject.net.device.DeviceProviderRegistry;
54import org.onosproject.net.device.DeviceProviderService;
55import org.onosproject.net.device.DeviceService;
56import org.onosproject.net.device.DeviceStore;
57import org.onosproject.net.device.DeviceStoreDelegate;
58import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070059import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080060import org.onosproject.net.provider.AbstractProviderService;
tomd3097b02014-08-26 10:40:29 -070061import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070062
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070063import java.util.Collection;
64import java.util.HashSet;
65import java.util.List;
66import java.util.Objects;
67import java.util.Set;
68import java.util.concurrent.CompletableFuture;
69import java.util.concurrent.ExecutionException;
70import java.util.concurrent.ScheduledExecutorService;
71import java.util.concurrent.TimeUnit;
72
73import static com.google.common.base.Preconditions.checkNotNull;
74import static com.google.common.base.Preconditions.checkState;
75import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
76import static org.onlab.util.Tools.groupedThreads;
77import static org.onosproject.net.MastershipRole.*;
78import static org.onosproject.security.AppGuard.checkPermission;
79import static org.slf4j.LoggerFactory.getLogger;
Jonathan Hart2f669362015-02-11 16:19:20 -080080
samuele1fa7322015-07-14 16:35:16 +080081
tomd3097b02014-08-26 10:40:29 -070082/**
tome4729872014-09-23 00:37:37 -070083 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070084 */
85@Component(immediate = true)
86@Service
tom41a2c5f2014-09-19 09:20:35 -070087public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070088 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Thomas Vachuskad16ce182014-10-29 17:25:29 -070089 implements DeviceService, DeviceAdminService, DeviceProviderRegistry {
tom32f66842014-08-27 19:27:47 -070090
tome5ec3fd2014-09-04 15:18:06 -070091 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
92 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
93 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
94 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
tomd3097b02014-08-26 10:40:29 -070095
tom5f38b3a2014-08-27 23:50:54 -070096 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -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
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700105 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
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)
tomb41d1ac2014-09-24 01:51:24 -0700111 protected ClusterService clusterService;
112
113 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700114 protected MastershipService mastershipService;
115
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800116 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700117 protected MastershipTermService termService;
118
Madan Jampani61056bc2014-09-27 09:07:26 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700120 protected NetworkConfigService networkConfigService;
121
tomd3097b02014-08-26 10:40:29 -0700122 @Activate
123 public void activate() {
samuele1fa7322015-07-14 16:35:16 +0800124 backgroundService = newSingleThreadScheduledExecutor(groupedThreads("onos/device", "manager-background"));
Madan Jampanide003d92015-05-11 17:14:20 -0700125 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800126
tomf80c9722014-09-24 14:49:18 -0700127 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700128 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700129 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700130 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800131
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700132 backgroundService.scheduleWithFixedDelay(() -> {
133 try {
134 mastershipCheck();
135 } catch (Exception e) {
136 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800137 }
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();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700145 networkConfigService.removeListener(networkConfigListener);
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);
tomad2d2092014-09-06 23:24:20 -0700155 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700156 }
157
158 @Override
tom32f66842014-08-27 19:27:47 -0700159 public Iterable<Device> getDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900160 checkPermission(Permission.DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700161 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700162 }
163
tom32f66842014-08-27 19:27:47 -0700164 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800165 public Iterable<Device> getAvailableDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900166 checkPermission(Permission.DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800167 return store.getAvailableDevices();
168 }
169
170 @Override
tom32f66842014-08-27 19:27:47 -0700171 public Device getDevice(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900172 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700173 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700174 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700175 }
176
177 @Override
tomad2d2092014-09-06 23:24:20 -0700178 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900179 checkPermission(Permission.DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700180 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700181 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700182 }
183
184 @Override
tom32f66842014-08-27 19:27:47 -0700185 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900186 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700187 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700188 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700189 }
190
191 @Override
sangho538108b2015-04-08 14:29:20 -0700192 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900193 checkPermission(Permission.DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700194 checkNotNull(deviceId, DEVICE_ID_NULL);
195 return store.getPortStatistics(deviceId);
196 }
197
198 @Override
tom32f66842014-08-27 19:27:47 -0700199 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900200 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700201 checkNotNull(deviceId, DEVICE_ID_NULL);
202 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700203 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700204 }
205
206 @Override
tomff7eb7c2014-09-08 12:49:03 -0700207 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900208 checkPermission(Permission.DEVICE_READ);
209
tomff7eb7c2014-09-08 12:49:03 -0700210 checkNotNull(deviceId, DEVICE_ID_NULL);
211 return store.isAvailable(deviceId);
212 }
213
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700214 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700215 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800216 if (deviceId == null) {
217 return false;
218 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700219 DeviceProvider provider = getProvider(deviceId);
220 if (provider != null) {
221 return provider.isReachable(deviceId);
222 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800223 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700224 return false;
225 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700226 }
227
tome5ec3fd2014-09-04 15:18:06 -0700228 @Override
229 public void removeDevice(DeviceId deviceId) {
230 checkNotNull(deviceId, DEVICE_ID_NULL);
231 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700232 if (event != null) {
233 log.info("Device {} administratively removed", deviceId);
234 post(event);
235 }
tome5ec3fd2014-09-04 15:18:06 -0700236 }
237
tom7869ad92014-09-09 14:32:08 -0700238 @Override
samuele1fa7322015-07-14 16:35:16 +0800239 protected DeviceProviderService createProviderService(
240 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700241 return new InternalDeviceProviderService(provider);
242 }
243
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800244 /**
245 * Checks if all the reachable devices have a valid mastership role.
246 */
247 private void mastershipCheck() {
248 log.debug("Checking mastership");
249 for (Device device : getDevices()) {
250 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800251 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800252
253 if (!isReachable(deviceId)) {
254 continue;
255 }
256
257 if (mastershipService.getLocalRole(deviceId) != NONE) {
258 continue;
259 }
260
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700261 log.info("{} is reachable but did not have a valid role, reasserting",
262 deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800263
264 // isReachable but was not MASTER or STANDBY, get a role and apply
265 // Note: NONE triggers request to MastershipService
266 reassertRole(deviceId, NONE);
267 }
268 }
269
tomd3097b02014-08-26 10:40:29 -0700270 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700271 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700272 extends AbstractProviderService<DeviceProvider>
273 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700274
tomcfde0622014-09-09 11:02:42 -0700275 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700276 super(provider);
277 }
278
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700279 /**
280 * Apply role in reaction to provider event.
281 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700282 * @param deviceId device identifier
283 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700284 * @return true if the request was sent to provider
285 */
286 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
287
288 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800289 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700290 return true;
291 }
292
293 DeviceProvider provider = provider();
294 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700295 log.warn("Provider for {} was not found. Cannot apply role {}",
296 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700297 return false;
298 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700299 provider.roleChanged(deviceId, newRole);
300 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700301
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700302 return true;
303 }
304
samuele1fa7322015-07-14 16:35:16 +0800305
tomd3097b02014-08-26 10:40:29 -0700306 @Override
alshabibb7b40632014-09-28 21:30:00 -0700307 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700308 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700309 checkNotNull(deviceId, DEVICE_ID_NULL);
310 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700311 checkValidity();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700312 deviceDescription = validateDevice(deviceDescription, deviceId);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700313
Madan Jampani565a66a2015-07-25 17:01:13 -0700314 // Establish my Role
315 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
316 .thenAccept(role -> {
317 log.info("Local role is {} for {}", role, deviceId);
318 applyRole(deviceId, role);
319 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700320
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700321 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
322 deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700323 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700324 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700325 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700326 }
tomd3097b02014-08-26 10:40:29 -0700327 }
328
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700329 // returns a DeviceDescription made from the union of the BasicDeviceConfig
330 // annotations if it exists
331 private DeviceDescription validateDevice(DeviceDescription deviceDescription, DeviceId deviceId) {
332 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
333 checkState(cfg == null || cfg.isAllowed(), "Device " + deviceId + " is not allowed");
334 log.info("Device {} connected", deviceId);
Ayaka Koshibe5373e762015-08-06 12:31:44 -0700335
336 return BasicDeviceOperator.combine(cfg, deviceDescription);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700337 }
338
tomd3097b02014-08-26 10:40:29 -0700339 @Override
340 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700341 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700342 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700343
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700344 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700345
alshabibafc514a2014-12-01 14:44:05 -0800346 List<Port> ports = store.getPorts(deviceId);
347 List<PortDescription> descs = Lists.newArrayList();
samuele1fa7322015-07-14 16:35:16 +0800348 ports.forEach(port ->
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700349 descs.add(new DefaultPortDescription(port.number(),
350 false, port.type(),
351 port.portSpeed())));
alshabibafc514a2014-12-01 14:44:05 -0800352 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700353 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700354 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700355 post(store.markOffline(deviceId));
356 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700357 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700358 log.warn("Failed to mark {} offline", deviceId);
359 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800360 // but if I was the last STANDBY connection, etc. and no one else
361 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700362 // temporarily request for Master Role and mark offline.
363
samuele1fa7322015-07-14 16:35:16 +0800364 //there are times when this node will correctly have mastership, BUT
365 //that isn't reflected in the ClockManager before the device disconnects.
366 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700367
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700368 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800369 // Consider revising store API to handle this scenario.
370 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700371 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800372 MastershipTerm term = termService.getMastershipTerm(deviceId);
373 // TODO: Move this type of check inside device clock manager, etc.
374 if (term != null && localNodeId.equals(term.master())) {
375 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800376 post(store.markOffline(deviceId));
377 } else {
378 log.info("Failed again marking {} offline. {}", deviceId, role);
379 }
380 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700381 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700382 try {
samuele1fa7322015-07-14 16:35:16 +0800383 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700384 mastershipService.relinquishMastership(deviceId).get();
385 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800386 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700387 Thread.currentThread().interrupt();
388 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800389 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700390 }
tom0efbb1d2014-09-09 11:54:28 -0700391 }
tomd3097b02014-08-26 10:40:29 -0700392 }
393
394 @Override
alshabibb7b40632014-09-28 21:30:00 -0700395 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700396 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700397 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700398 checkNotNull(portDescriptions,
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700399 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700400 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700401 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700402 // Never been a master for this device
403 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800404 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700405 return;
406 }
407
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700408 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800409 deviceId, portDescriptions);
tom32f66842014-08-27 19:27:47 -0700410 for (DeviceEvent event : events) {
411 post(event);
412 }
tomd3097b02014-08-26 10:40:29 -0700413 }
414
415 @Override
alshabibb7b40632014-09-28 21:30:00 -0700416 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700417 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700418 checkNotNull(deviceId, DEVICE_ID_NULL);
419 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700420 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700421
Madan Jampani565a66a2015-07-25 17:01:13 -0700422 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700423 // Never been a master for this device
424 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700425 log.trace("Ignoring {} port update on standby node. {}", deviceId,
426 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700427 return;
428 }
429
samuele1fa7322015-07-14 16:35:16 +0800430 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
431 deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700432 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700433 log.info("Device {} port {} status changed", deviceId, event
434 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700435 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700436 }
tomd3097b02014-08-26 10:40:29 -0700437 }
tom3f2bbd72014-09-24 12:07:58 -0700438
439 @Override
samuele1fa7322015-07-14 16:35:16 +0800440 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700441 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700442 // Several things can happen here:
443 // 1. request and response match
444 // 2. request and response don't match
445 // 3. MastershipRole and requested match (and 1 or 2 are true)
446 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
447 //
448 // 2, 4, and 3 with case 2 are failure modes.
449
tom3f2bbd72014-09-24 12:07:58 -0700450 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700451
Madan Jampanif2af7712015-05-29 18:43:52 -0700452 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700453 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700454
455 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800456 // something was off with DeviceProvider, maybe check channel too?
457 log.warn("Failed to assert role [{}] onto Device {}", requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700458 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700459 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700460 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700461
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700462 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800463 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700464 return;
465 } else {
466 return;
samuele1fa7322015-07-14 16:35:16 +0800467 // FIXME roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700468 // the store; use the store's view, then try to reassert.
469 }
470 } else {
471 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800472 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700473 if (response == MastershipRole.MASTER) {
474 mastershipService.relinquishMastership(deviceId);
475 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800476 //final Device device = getDevice(deviceId);
477 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700478 }
479 }
tom3f2bbd72014-09-24 12:07:58 -0700480 }
sangho538108b2015-04-08 14:29:20 -0700481
482 @Override
samuele1fa7322015-07-14 16:35:16 +0800483 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700484 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700485 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700486 checkValidity();
487
samuele1fa7322015-07-14 16:35:16 +0800488 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
489 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700490 post(event);
491 }
tomd3097b02014-08-26 10:40:29 -0700492 }
tom32f66842014-08-27 19:27:47 -0700493
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800494 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700495
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800496 /**
497 * Apply role to device and send probe if MASTER.
498 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700499 * @param deviceId device identifier
500 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800501 * @return true if the request was sent to provider
502 */
503 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
504 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800505 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700506 return true;
507 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700508
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800509 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800510 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800511 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800512 return false;
513 }
514 provider.roleChanged(deviceId, newRole);
515
516 if (newRole.equals(MastershipRole.MASTER)) {
517 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800518 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800519 }
520 return true;
521 }
522
523 /**
524 * Reaasert role for specified device connected to this node.
525 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700526 * @param did device identifier
527 * @param nextRole role to apply. If NONE is specified,
528 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800529 */
samuele1fa7322015-07-14 16:35:16 +0800530 private void reassertRole(final DeviceId did,
531 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800532
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800533 MastershipRole myNextRole = nextRole;
534 if (myNextRole == NONE) {
535 mastershipService.requestRoleFor(did);
536 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700537 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800538 myNextRole = MASTER;
539 } else {
540 myNextRole = STANDBY;
541 }
542 }
543
544 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700545 case MASTER:
546 final Device device = getDevice(did);
547 if ((device != null) && !isAvailable(did)) {
548 //flag the device as online. Is there a better way to do this?
549 DefaultDeviceDescription deviceDescription
550 = new DefaultDeviceDescription(did.uri(),
551 device.type(),
552 device.manufacturer(),
553 device.hwVersion(),
554 device.swVersion(),
555 device.serialNumber(),
556 device.chassisId());
557 DeviceEvent devEvent =
558 store.createOrUpdateDevice(device.providerId(), did,
559 deviceDescription);
560 post(devEvent);
561 }
562 // TODO: should apply role only if there is mismatch
563 log.debug("Applying role {} to {}", myNextRole, did);
564 if (!applyRoleAndProbe(did, MASTER)) {
565 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
566 // immediately failed to apply role
567 mastershipService.relinquishMastership(did);
568 // FIXME disconnect?
569 }
570 break;
571 case STANDBY:
572 log.debug("Applying role {} to {}", myNextRole, did);
573 if (!applyRoleAndProbe(did, STANDBY)) {
574 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
575 // immediately failed to apply role
576 mastershipService.relinquishMastership(did);
577 // FIXME disconnect?
578 }
579 break;
580 case NONE:
581 default:
582 // should never reach here
583 log.error("You didn't see anything. I did not exist.");
584 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800585 }
586 }
587
Madan Jampani328371d2015-05-29 14:06:27 -0700588 private void handleMastershipEvent(MastershipEvent event) {
589 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
590 // Don't care if backup list changed.
591 return;
592 }
593
594 final DeviceId did = event.subject();
595
596 // myRole suggested by MastershipService
597 MastershipRole myNextRole;
598 if (localNodeId.equals(event.roleInfo().master())) {
599 // confirm latest info
600 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800601 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700602 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700603 myNextRole = MASTER;
604 } else {
605 myNextRole = STANDBY;
606 }
607 } else if (event.roleInfo().backups().contains(localNodeId)) {
608 myNextRole = STANDBY;
609 } else {
610 myNextRole = NONE;
611 }
612
samuele1fa7322015-07-14 16:35:16 +0800613
Madan Jampani328371d2015-05-29 14:06:27 -0700614 final boolean isReachable = isReachable(did);
615 if (!isReachable) {
616 // device is not connected to this node
617 if (myNextRole != NONE) {
618 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700619 + "but this node cannot reach the device. "
620 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800621 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700622 mastershipService.relinquishMastership(did);
623 }
624 return;
625 }
626
627 // device is connected to this node:
628 if (store.getDevice(did) != null) {
629 reassertRole(did, myNextRole);
630 } else {
631 log.debug("Device is not yet/no longer in the store: {}", did);
632 }
633 }
634
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800635 // Intercepts mastership events
636 private class InternalMastershipListener implements MastershipListener {
637
tomb41d1ac2014-09-24 01:51:24 -0700638 @Override
639 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700640 backgroundService.submit(() -> {
641 try {
642 handleMastershipEvent(event);
643 } catch (Exception e) {
644 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700645 }
Madan Jampani328371d2015-05-29 14:06:27 -0700646 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700647 }
tomb41d1ac2014-09-24 01:51:24 -0700648 }
tomf80c9722014-09-24 14:49:18 -0700649
650 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700651 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700652 @Override
653 public void notify(DeviceEvent event) {
654 post(event);
655 }
656 }
samuel738dfaf2015-07-11 11:08:57 +0800657
658 @Override
659 public Iterable<Device> getDevices(Type type) {
660 checkPermission(Permission.DEVICE_READ);
661 Set<Device> results = new HashSet<>();
662 Iterable<Device> devices = store.getDevices();
663 if (devices != null) {
664 devices.forEach(d -> {
665 if (type.equals(d.type())) {
666 results.add(d);
667 }
668 });
669 }
670 return results;
671 }
672
673 @Override
674 public Iterable<Device> getAvailableDevices(Type type) {
675 checkPermission(Permission.DEVICE_READ);
676 Set<Device> results = new HashSet<>();
677 Iterable<Device> availableDevices = store.getAvailableDevices();
678 if (availableDevices != null) {
679 availableDevices.forEach(d -> {
680 if (type.equals(d.type())) {
681 results.add(d);
682 }
683 });
684 }
685 return results;
686 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700687
688 private class InternalNetworkConfigListener implements NetworkConfigListener {
689 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700690 public boolean isRelevant(NetworkConfigEvent event) {
691 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
692 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
693 && event.configClass().equals(BasicDeviceConfig.class);
694 }
695
696 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700697 public void event(NetworkConfigEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700698 log.info("Detected Device network config event {}", event.type());
699 kickOutBadDevice(((DeviceId) event.subject()));
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700700 }
701 }
702
703 // checks if the specified device is allowed by the BasicDeviceConfig
704 // and if not, removes it
705 private void kickOutBadDevice(DeviceId deviceId) {
706 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
707 if (!cfg.isAllowed()) {
708 Device badDevice = getDevice(deviceId);
709 if (badDevice != null) {
710 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700711 }
712 }
713 }
tomd3097b02014-08-26 10:40:29 -0700714}