blob: 24ea9f9aa4bd18c8694671c0c52271d9d1c72460 [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;
Thomas Vachuska4998caa2015-08-26 13:28:38 -070034import org.onosproject.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
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200199 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
200 checkPermission(Permission.DEVICE_READ);
201 checkNotNull(deviceId, DEVICE_ID_NULL);
202 return store.getPortDeltaStatistics(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);
tom32f66842014-08-27 19:27:47 -0700208 checkNotNull(deviceId, DEVICE_ID_NULL);
209 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700210 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700211 }
212
213 @Override
tomff7eb7c2014-09-08 12:49:03 -0700214 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900215 checkPermission(Permission.DEVICE_READ);
216
tomff7eb7c2014-09-08 12:49:03 -0700217 checkNotNull(deviceId, DEVICE_ID_NULL);
218 return store.isAvailable(deviceId);
219 }
220
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700221 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700222 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800223 if (deviceId == null) {
224 return false;
225 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700226 DeviceProvider provider = getProvider(deviceId);
227 if (provider != null) {
228 return provider.isReachable(deviceId);
229 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800230 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700231 return false;
232 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700233 }
234
tome5ec3fd2014-09-04 15:18:06 -0700235 @Override
236 public void removeDevice(DeviceId deviceId) {
237 checkNotNull(deviceId, DEVICE_ID_NULL);
238 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700239 if (event != null) {
240 log.info("Device {} administratively removed", deviceId);
241 post(event);
242 }
tome5ec3fd2014-09-04 15:18:06 -0700243 }
244
tom7869ad92014-09-09 14:32:08 -0700245 @Override
samuele1fa7322015-07-14 16:35:16 +0800246 protected DeviceProviderService createProviderService(
247 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700248 return new InternalDeviceProviderService(provider);
249 }
250
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800251 /**
252 * Checks if all the reachable devices have a valid mastership role.
253 */
254 private void mastershipCheck() {
255 log.debug("Checking mastership");
256 for (Device device : getDevices()) {
257 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800258 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800259
260 if (!isReachable(deviceId)) {
261 continue;
262 }
263
264 if (mastershipService.getLocalRole(deviceId) != NONE) {
265 continue;
266 }
267
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700268 log.info("{} is reachable but did not have a valid role, reasserting",
269 deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800270
271 // isReachable but was not MASTER or STANDBY, get a role and apply
272 // Note: NONE triggers request to MastershipService
273 reassertRole(deviceId, NONE);
274 }
275 }
276
tomd3097b02014-08-26 10:40:29 -0700277 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700278 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700279 extends AbstractProviderService<DeviceProvider>
280 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700281
tomcfde0622014-09-09 11:02:42 -0700282 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700283 super(provider);
284 }
285
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700286 /**
287 * Apply role in reaction to provider event.
288 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700289 * @param deviceId device identifier
290 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700291 * @return true if the request was sent to provider
292 */
293 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
294
295 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800296 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700297 return true;
298 }
299
300 DeviceProvider provider = provider();
301 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700302 log.warn("Provider for {} was not found. Cannot apply role {}",
303 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700304 return false;
305 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700306 provider.roleChanged(deviceId, newRole);
307 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700308
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700309 return true;
310 }
311
samuele1fa7322015-07-14 16:35:16 +0800312
tomd3097b02014-08-26 10:40:29 -0700313 @Override
alshabibb7b40632014-09-28 21:30:00 -0700314 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700315 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700316 checkNotNull(deviceId, DEVICE_ID_NULL);
317 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700318 checkValidity();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700319 deviceDescription = validateDevice(deviceDescription, deviceId);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700320
Madan Jampani565a66a2015-07-25 17:01:13 -0700321 // Establish my Role
322 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
323 .thenAccept(role -> {
324 log.info("Local role is {} for {}", role, deviceId);
325 applyRole(deviceId, role);
326 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700327
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700328 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
329 deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700330 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700331 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700332 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700333 }
tomd3097b02014-08-26 10:40:29 -0700334 }
335
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700336 // returns a DeviceDescription made from the union of the BasicDeviceConfig
337 // annotations if it exists
338 private DeviceDescription validateDevice(DeviceDescription deviceDescription, DeviceId deviceId) {
339 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
340 checkState(cfg == null || cfg.isAllowed(), "Device " + deviceId + " is not allowed");
341 log.info("Device {} connected", deviceId);
Ayaka Koshibe5373e762015-08-06 12:31:44 -0700342
343 return BasicDeviceOperator.combine(cfg, deviceDescription);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700344 }
345
tomd3097b02014-08-26 10:40:29 -0700346 @Override
347 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700348 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700349 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700350
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700351 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700352
alshabibafc514a2014-12-01 14:44:05 -0800353 List<Port> ports = store.getPorts(deviceId);
354 List<PortDescription> descs = Lists.newArrayList();
samuele1fa7322015-07-14 16:35:16 +0800355 ports.forEach(port ->
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700356 descs.add(new DefaultPortDescription(port.number(),
357 false, port.type(),
358 port.portSpeed())));
alshabibafc514a2014-12-01 14:44:05 -0800359 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700360 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700361 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700362 post(store.markOffline(deviceId));
363 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700364 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700365 log.warn("Failed to mark {} offline", deviceId);
366 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800367 // but if I was the last STANDBY connection, etc. and no one else
368 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700369 // temporarily request for Master Role and mark offline.
370
samuele1fa7322015-07-14 16:35:16 +0800371 //there are times when this node will correctly have mastership, BUT
372 //that isn't reflected in the ClockManager before the device disconnects.
373 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700374
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700375 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800376 // Consider revising store API to handle this scenario.
377 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700378 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800379 MastershipTerm term = termService.getMastershipTerm(deviceId);
380 // TODO: Move this type of check inside device clock manager, etc.
381 if (term != null && localNodeId.equals(term.master())) {
382 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800383 post(store.markOffline(deviceId));
384 } else {
385 log.info("Failed again marking {} offline. {}", deviceId, role);
386 }
387 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700388 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700389 try {
samuele1fa7322015-07-14 16:35:16 +0800390 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700391 mastershipService.relinquishMastership(deviceId).get();
392 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800393 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700394 Thread.currentThread().interrupt();
395 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800396 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700397 }
tom0efbb1d2014-09-09 11:54:28 -0700398 }
tomd3097b02014-08-26 10:40:29 -0700399 }
400
401 @Override
alshabibb7b40632014-09-28 21:30:00 -0700402 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700403 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700404 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700405 checkNotNull(portDescriptions,
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700406 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700407 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700408 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700409 // Never been a master for this device
410 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800411 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700412 return;
413 }
414
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700415 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800416 deviceId, portDescriptions);
tom32f66842014-08-27 19:27:47 -0700417 for (DeviceEvent event : events) {
418 post(event);
419 }
tomd3097b02014-08-26 10:40:29 -0700420 }
421
422 @Override
alshabibb7b40632014-09-28 21:30:00 -0700423 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700424 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700425 checkNotNull(deviceId, DEVICE_ID_NULL);
426 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700427 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700428
Madan Jampani565a66a2015-07-25 17:01:13 -0700429 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700430 // Never been a master for this device
431 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700432 log.trace("Ignoring {} port update on standby node. {}", deviceId,
433 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700434 return;
435 }
436
samuele1fa7322015-07-14 16:35:16 +0800437 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
438 deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700439 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700440 log.info("Device {} port {} status changed", deviceId, event
441 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700442 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700443 }
tomd3097b02014-08-26 10:40:29 -0700444 }
tom3f2bbd72014-09-24 12:07:58 -0700445
446 @Override
samuele1fa7322015-07-14 16:35:16 +0800447 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700448 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700449 // Several things can happen here:
450 // 1. request and response match
451 // 2. request and response don't match
452 // 3. MastershipRole and requested match (and 1 or 2 are true)
453 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
454 //
455 // 2, 4, and 3 with case 2 are failure modes.
456
tom3f2bbd72014-09-24 12:07:58 -0700457 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700458
Madan Jampanif2af7712015-05-29 18:43:52 -0700459 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700460 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700461
462 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800463 // something was off with DeviceProvider, maybe check channel too?
464 log.warn("Failed to assert role [{}] onto Device {}", requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700465 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700466 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700467 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700468
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700469 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800470 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700471 return;
472 } else {
473 return;
samuele1fa7322015-07-14 16:35:16 +0800474 // FIXME roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700475 // the store; use the store's view, then try to reassert.
476 }
477 } else {
478 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800479 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700480 if (response == MastershipRole.MASTER) {
481 mastershipService.relinquishMastership(deviceId);
482 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800483 //final Device device = getDevice(deviceId);
484 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700485 }
486 }
tom3f2bbd72014-09-24 12:07:58 -0700487 }
sangho538108b2015-04-08 14:29:20 -0700488
489 @Override
samuele1fa7322015-07-14 16:35:16 +0800490 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700491 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700492 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700493 checkValidity();
494
samuele1fa7322015-07-14 16:35:16 +0800495 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
496 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700497 post(event);
498 }
tomd3097b02014-08-26 10:40:29 -0700499 }
tom32f66842014-08-27 19:27:47 -0700500
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800501 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700502
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800503 /**
504 * Apply role to device and send probe if MASTER.
505 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700506 * @param deviceId device identifier
507 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800508 * @return true if the request was sent to provider
509 */
510 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
511 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800512 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700513 return true;
514 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700515
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800516 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800517 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800518 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800519 return false;
520 }
521 provider.roleChanged(deviceId, newRole);
522
523 if (newRole.equals(MastershipRole.MASTER)) {
524 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800525 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800526 }
527 return true;
528 }
529
530 /**
531 * Reaasert role for specified device connected to this node.
532 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700533 * @param did device identifier
534 * @param nextRole role to apply. If NONE is specified,
535 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800536 */
samuele1fa7322015-07-14 16:35:16 +0800537 private void reassertRole(final DeviceId did,
538 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800539
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800540 MastershipRole myNextRole = nextRole;
541 if (myNextRole == NONE) {
542 mastershipService.requestRoleFor(did);
543 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700544 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800545 myNextRole = MASTER;
546 } else {
547 myNextRole = STANDBY;
548 }
549 }
550
551 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700552 case MASTER:
553 final Device device = getDevice(did);
554 if ((device != null) && !isAvailable(did)) {
555 //flag the device as online. Is there a better way to do this?
556 DefaultDeviceDescription deviceDescription
557 = new DefaultDeviceDescription(did.uri(),
558 device.type(),
559 device.manufacturer(),
560 device.hwVersion(),
561 device.swVersion(),
562 device.serialNumber(),
563 device.chassisId());
564 DeviceEvent devEvent =
565 store.createOrUpdateDevice(device.providerId(), did,
566 deviceDescription);
567 post(devEvent);
568 }
569 // TODO: should apply role only if there is mismatch
570 log.debug("Applying role {} to {}", myNextRole, did);
571 if (!applyRoleAndProbe(did, MASTER)) {
572 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
573 // immediately failed to apply role
574 mastershipService.relinquishMastership(did);
575 // FIXME disconnect?
576 }
577 break;
578 case STANDBY:
579 log.debug("Applying role {} to {}", myNextRole, did);
580 if (!applyRoleAndProbe(did, STANDBY)) {
581 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
582 // immediately failed to apply role
583 mastershipService.relinquishMastership(did);
584 // FIXME disconnect?
585 }
586 break;
587 case NONE:
588 default:
589 // should never reach here
590 log.error("You didn't see anything. I did not exist.");
591 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800592 }
593 }
594
Madan Jampani328371d2015-05-29 14:06:27 -0700595 private void handleMastershipEvent(MastershipEvent event) {
596 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
597 // Don't care if backup list changed.
598 return;
599 }
600
601 final DeviceId did = event.subject();
602
603 // myRole suggested by MastershipService
604 MastershipRole myNextRole;
605 if (localNodeId.equals(event.roleInfo().master())) {
606 // confirm latest info
607 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800608 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700609 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700610 myNextRole = MASTER;
611 } else {
612 myNextRole = STANDBY;
613 }
614 } else if (event.roleInfo().backups().contains(localNodeId)) {
615 myNextRole = STANDBY;
616 } else {
617 myNextRole = NONE;
618 }
619
samuele1fa7322015-07-14 16:35:16 +0800620
Madan Jampani328371d2015-05-29 14:06:27 -0700621 final boolean isReachable = isReachable(did);
622 if (!isReachable) {
623 // device is not connected to this node
624 if (myNextRole != NONE) {
625 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700626 + "but this node cannot reach the device. "
627 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800628 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700629 mastershipService.relinquishMastership(did);
630 }
631 return;
632 }
633
634 // device is connected to this node:
635 if (store.getDevice(did) != null) {
636 reassertRole(did, myNextRole);
637 } else {
638 log.debug("Device is not yet/no longer in the store: {}", did);
639 }
640 }
641
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800642 // Intercepts mastership events
643 private class InternalMastershipListener implements MastershipListener {
644
tomb41d1ac2014-09-24 01:51:24 -0700645 @Override
646 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700647 backgroundService.submit(() -> {
648 try {
649 handleMastershipEvent(event);
650 } catch (Exception e) {
651 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700652 }
Madan Jampani328371d2015-05-29 14:06:27 -0700653 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700654 }
tomb41d1ac2014-09-24 01:51:24 -0700655 }
tomf80c9722014-09-24 14:49:18 -0700656
657 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700658 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700659 @Override
660 public void notify(DeviceEvent event) {
661 post(event);
662 }
663 }
samuel738dfaf2015-07-11 11:08:57 +0800664
665 @Override
666 public Iterable<Device> getDevices(Type type) {
667 checkPermission(Permission.DEVICE_READ);
668 Set<Device> results = new HashSet<>();
669 Iterable<Device> devices = store.getDevices();
670 if (devices != null) {
671 devices.forEach(d -> {
672 if (type.equals(d.type())) {
673 results.add(d);
674 }
675 });
676 }
677 return results;
678 }
679
680 @Override
681 public Iterable<Device> getAvailableDevices(Type type) {
682 checkPermission(Permission.DEVICE_READ);
683 Set<Device> results = new HashSet<>();
684 Iterable<Device> availableDevices = store.getAvailableDevices();
685 if (availableDevices != null) {
686 availableDevices.forEach(d -> {
687 if (type.equals(d.type())) {
688 results.add(d);
689 }
690 });
691 }
692 return results;
693 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700694
695 private class InternalNetworkConfigListener implements NetworkConfigListener {
696 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700697 public boolean isRelevant(NetworkConfigEvent event) {
698 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
699 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
700 && event.configClass().equals(BasicDeviceConfig.class);
701 }
702
703 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700704 public void event(NetworkConfigEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700705 log.info("Detected Device network config event {}", event.type());
706 kickOutBadDevice(((DeviceId) event.subject()));
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700707 }
708 }
709
710 // checks if the specified device is allowed by the BasicDeviceConfig
711 // and if not, removes it
712 private void kickOutBadDevice(DeviceId deviceId) {
713 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
714 if (!cfg.isAllowed()) {
715 Device badDevice = getDevice(deviceId);
716 if (badDevice != null) {
717 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700718 }
719 }
720 }
tomd3097b02014-08-26 10:40:29 -0700721}