blob: 96b7176ccaeb85be31fcc1de747445d536e5b42b [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;
tomd3097b02014-08-26 10:40:29 -070019import org.apache.felix.scr.annotations.Activate;
20import org.apache.felix.scr.annotations.Component;
21import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070022import org.apache.felix.scr.annotations.Reference;
23import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070024import org.apache.felix.scr.annotations.Service;
Brian O'Connorabafb502014-12-02 22:26:20 -080025import org.onosproject.cluster.ClusterService;
26import org.onosproject.cluster.NodeId;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070027import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Changhoon Yoon541ef712015-05-23 17:18:34 +090028import org.onosproject.core.Permission;
Sahil Lele3a0cdd52015-07-21 14:16:31 -070029import org.onosproject.incubator.net.config.NetworkConfigEvent;
30import org.onosproject.incubator.net.config.NetworkConfigListener;
31import org.onosproject.incubator.net.config.NetworkConfigService;
32import org.onosproject.incubator.net.config.basics.BasicDeviceConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.mastership.MastershipEvent;
34import org.onosproject.mastership.MastershipListener;
35import org.onosproject.mastership.MastershipService;
36import org.onosproject.mastership.MastershipTerm;
37import org.onosproject.mastership.MastershipTermService;
Sahil Lele3a0cdd52015-07-21 14:16:31 -070038import org.onosproject.net.DefaultAnnotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080039import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080040import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.DeviceId;
42import org.onosproject.net.MastershipRole;
43import org.onosproject.net.Port;
44import org.onosproject.net.PortNumber;
Sahil Lele3a0cdd52015-07-21 14:16:31 -070045import org.onosproject.net.SparseAnnotations;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.net.device.DefaultDeviceDescription;
47import org.onosproject.net.device.DefaultPortDescription;
48import org.onosproject.net.device.DeviceAdminService;
49import org.onosproject.net.device.DeviceClockProviderService;
50import org.onosproject.net.device.DeviceDescription;
51import org.onosproject.net.device.DeviceEvent;
52import org.onosproject.net.device.DeviceListener;
53import org.onosproject.net.device.DeviceProvider;
54import org.onosproject.net.device.DeviceProviderRegistry;
55import org.onosproject.net.device.DeviceProviderService;
56import org.onosproject.net.device.DeviceService;
57import org.onosproject.net.device.DeviceStore;
58import org.onosproject.net.device.DeviceStoreDelegate;
59import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070060import org.onosproject.net.device.PortStatistics;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.provider.AbstractProviderService;
tomd3097b02014-08-26 10:40:29 -070062import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070063
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070064import java.util.Collection;
65import java.util.HashSet;
66import java.util.List;
67import java.util.Objects;
68import java.util.Set;
69import java.util.concurrent.CompletableFuture;
70import java.util.concurrent.ExecutionException;
71import java.util.concurrent.ScheduledExecutorService;
72import java.util.concurrent.TimeUnit;
73
74import static com.google.common.base.Preconditions.checkNotNull;
75import static com.google.common.base.Preconditions.checkState;
76import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
77import static org.onlab.util.Tools.groupedThreads;
78import static org.onosproject.net.MastershipRole.*;
79import static org.onosproject.security.AppGuard.checkPermission;
80import static org.slf4j.LoggerFactory.getLogger;
Jonathan Hart2f669362015-02-11 16:19:20 -080081
samuele1fa7322015-07-14 16:35:16 +080082
tomd3097b02014-08-26 10:40:29 -070083/**
tome4729872014-09-23 00:37:37 -070084 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070085 */
86@Component(immediate = true)
87@Service
tom41a2c5f2014-09-19 09:20:35 -070088public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070089 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Thomas Vachuskad16ce182014-10-29 17:25:29 -070090 implements DeviceService, DeviceAdminService, DeviceProviderRegistry {
tom32f66842014-08-27 19:27:47 -070091
tome5ec3fd2014-09-04 15:18:06 -070092 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
93 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
94 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
95 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
tomd3097b02014-08-26 10:40:29 -070096
tom5f38b3a2014-08-27 23:50:54 -070097 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -070098
alshabib339a3d92014-09-26 17:54:32 -070099 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700100
tomc78acee2014-09-24 15:16:55 -0700101 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700102 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700103
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800104 private ScheduledExecutorService backgroundService;
105
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700106 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
107
tom41a2c5f2014-09-19 09:20:35 -0700108 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
109 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700110
tom5f38b3a2014-08-27 23:50:54 -0700111 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700112 protected ClusterService clusterService;
113
114 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700115 protected MastershipService mastershipService;
116
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700118 protected MastershipTermService termService;
119
Madan Jampani61056bc2014-09-27 09:07:26 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Yuta HIGUCHI093e83e2014-10-10 22:26:11 -0700121 protected DeviceClockProviderService deviceClockProviderService;
Madan Jampani61056bc2014-09-27 09:07:26 -0700122
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
124 protected NetworkConfigService networkConfigService;
125
126
tomd3097b02014-08-26 10:40:29 -0700127 @Activate
128 public void activate() {
samuele1fa7322015-07-14 16:35:16 +0800129 backgroundService = newSingleThreadScheduledExecutor(groupedThreads("onos/device", "manager-background"));
Madan Jampanide003d92015-05-11 17:14:20 -0700130 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800131
tomf80c9722014-09-24 14:49:18 -0700132 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700133 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700134 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700135 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800136
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700137 backgroundService.scheduleWithFixedDelay(() -> {
138 try {
139 mastershipCheck();
140 } catch (Exception e) {
141 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800142 }
143 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700144 log.info("Started");
145 }
146
147 @Deactivate
148 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800149 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700150 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700151 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700152 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700153 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700154 log.info("Stopped");
155 }
156
157 @Override
tomad2d2092014-09-06 23:24:20 -0700158 public int getDeviceCount() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900159 checkPermission(Permission.DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700160 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700161 }
162
163 @Override
tom32f66842014-08-27 19:27:47 -0700164 public Iterable<Device> getDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900165 checkPermission(Permission.DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700166 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700167 }
168
tom32f66842014-08-27 19:27:47 -0700169 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800170 public Iterable<Device> getAvailableDevices() {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900171 checkPermission(Permission.DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800172 return store.getAvailableDevices();
173 }
174
175 @Override
tom32f66842014-08-27 19:27:47 -0700176 public Device getDevice(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900177 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700178 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700179 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700180 }
181
182 @Override
tomad2d2092014-09-06 23:24:20 -0700183 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900184 checkPermission(Permission.DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700185 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700186 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700187 }
188
189 @Override
tom32f66842014-08-27 19:27:47 -0700190 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900191 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700192 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700193 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700194 }
195
196 @Override
sangho538108b2015-04-08 14:29:20 -0700197 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900198 checkPermission(Permission.DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700199 checkNotNull(deviceId, DEVICE_ID_NULL);
200 return store.getPortStatistics(deviceId);
201 }
202
203 @Override
tom32f66842014-08-27 19:27:47 -0700204 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900205 checkPermission(Permission.DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700206 checkNotNull(deviceId, DEVICE_ID_NULL);
207 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700208 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700209 }
210
211 @Override
tomff7eb7c2014-09-08 12:49:03 -0700212 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoon541ef712015-05-23 17:18:34 +0900213 checkPermission(Permission.DEVICE_READ);
214
tomff7eb7c2014-09-08 12:49:03 -0700215 checkNotNull(deviceId, DEVICE_ID_NULL);
216 return store.isAvailable(deviceId);
217 }
218
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700219 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700220 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800221 if (deviceId == null) {
222 return false;
223 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700224 DeviceProvider provider = getProvider(deviceId);
225 if (provider != null) {
226 return provider.isReachable(deviceId);
227 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800228 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700229 return false;
230 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700231 }
232
tome5ec3fd2014-09-04 15:18:06 -0700233 @Override
234 public void removeDevice(DeviceId deviceId) {
235 checkNotNull(deviceId, DEVICE_ID_NULL);
236 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700237 if (event != null) {
238 log.info("Device {} administratively removed", deviceId);
239 post(event);
240 }
tome5ec3fd2014-09-04 15:18:06 -0700241 }
242
tom7869ad92014-09-09 14:32:08 -0700243 @Override
samuele1fa7322015-07-14 16:35:16 +0800244 protected DeviceProviderService createProviderService(
245 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700246 return new InternalDeviceProviderService(provider);
247 }
248
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800249 /**
250 * Checks if all the reachable devices have a valid mastership role.
251 */
252 private void mastershipCheck() {
253 log.debug("Checking mastership");
254 for (Device device : getDevices()) {
255 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800256 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800257
258 if (!isReachable(deviceId)) {
259 continue;
260 }
261
262 if (mastershipService.getLocalRole(deviceId) != NONE) {
263 continue;
264 }
265
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700266 log.info("{} is reachable but did not have a valid role, reasserting",
267 deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800268
269 // isReachable but was not MASTER or STANDBY, get a role and apply
270 // Note: NONE triggers request to MastershipService
271 reassertRole(deviceId, NONE);
272 }
273 }
274
tomd3097b02014-08-26 10:40:29 -0700275 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700276 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700277 extends AbstractProviderService<DeviceProvider>
278 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700279
tomcfde0622014-09-09 11:02:42 -0700280 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700281 super(provider);
282 }
283
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700284 /**
285 * Apply role in reaction to provider event.
286 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700287 * @param deviceId device identifier
288 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700289 * @return true if the request was sent to provider
290 */
291 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
292
293 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800294 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700295 return true;
296 }
297
298 DeviceProvider provider = provider();
299 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700300 log.warn("Provider for {} was not found. Cannot apply role {}",
301 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700302 return false;
303 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700304 provider.roleChanged(deviceId, newRole);
305 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700306
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700307 return true;
308 }
309
samuele1fa7322015-07-14 16:35:16 +0800310
tomd3097b02014-08-26 10:40:29 -0700311 @Override
alshabibb7b40632014-09-28 21:30:00 -0700312 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700313 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700314 checkNotNull(deviceId, DEVICE_ID_NULL);
315 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700316 checkValidity();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700317 deviceDescription = validateDevice(deviceDescription, deviceId);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700318
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700319 // check my Role
samuele1fa7322015-07-14 16:35:16 +0800320 CompletableFuture<MastershipRole> role = mastershipService.requestRoleFor(deviceId);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700321 try {
322 // Device subsystem must wait for role assignment
323 // to avoid losing Device information.
324 // (This node could be the only Node connected to the Device.)
325 role.get();
326 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800327 log.warn("Interrupted while waiting role-assignment for {}", deviceId);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700328 Thread.currentThread().interrupt();
329 } catch (ExecutionException e) {
330 log.error("Exception thrown while waiting role-assignment for {}",
331 deviceId, e);
332 }
333
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700334 final MastershipTerm term = termService.getMastershipTerm(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700335 if (term == null || !localNodeId.equals(term.master())) {
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700336 log.info("Role of this node is STANDBY for {}", deviceId);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700337 applyRole(deviceId, MastershipRole.STANDBY);
Marc De Leenheerb473b9d2015-02-06 15:21:03 -0800338 } else {
339 log.info("Role of this node is MASTER for {}", deviceId);
340 // tell clock provider if this instance is the master
341 deviceClockProviderService.setMastershipTerm(deviceId, term);
342 applyRole(deviceId, MastershipRole.MASTER);
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700343 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700344 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
345 deviceDescription);
tom80c0e5e2014-09-08 18:08:58 -0700346 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700347 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700348 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700349 }
tomd3097b02014-08-26 10:40:29 -0700350 }
351
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700352 // returns a DeviceDescription made from the union of the BasicDeviceConfig
353 // annotations if it exists
354 private DeviceDescription validateDevice(DeviceDescription deviceDescription, DeviceId deviceId) {
355 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
356 checkState(cfg == null || cfg.isAllowed(), "Device " + deviceId + " is not allowed");
357 log.info("Device {} connected", deviceId);
358 if (cfg != null) {
359 SparseAnnotations finalSparse = processAnnotations(cfg, deviceDescription, deviceId);
360 if (cfg.type() != Type.SWITCH) {
361 deviceDescription = new DefaultDeviceDescription(deviceDescription,
362 cfg.type(), finalSparse);
363 } else {
364 deviceDescription = new DefaultDeviceDescription(deviceDescription,
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700365 deviceDescription.type(), finalSparse);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700366 }
367 }
368 return deviceDescription;
369 }
370
tomd3097b02014-08-26 10:40:29 -0700371 @Override
372 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700373 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700374 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700375
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700376 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700377
alshabibafc514a2014-12-01 14:44:05 -0800378 List<Port> ports = store.getPorts(deviceId);
379 List<PortDescription> descs = Lists.newArrayList();
samuele1fa7322015-07-14 16:35:16 +0800380 ports.forEach(port ->
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700381 descs.add(new DefaultPortDescription(port.number(),
382 false, port.type(),
383 port.portSpeed())));
alshabibafc514a2014-12-01 14:44:05 -0800384 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700385 try {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700386 if (mastershipService.getLocalRole(deviceId) == MASTER) {
387 post(store.markOffline(deviceId));
388 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700389 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700390 log.warn("Failed to mark {} offline", deviceId);
391 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800392 // but if I was the last STANDBY connection, etc. and no one else
393 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700394 // temporarily request for Master Role and mark offline.
395
samuele1fa7322015-07-14 16:35:16 +0800396 //there are times when this node will correctly have mastership, BUT
397 //that isn't reflected in the ClockManager before the device disconnects.
398 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700399
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700400 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800401 // Consider revising store API to handle this scenario.
402 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700403 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800404 MastershipTerm term = termService.getMastershipTerm(deviceId);
405 // TODO: Move this type of check inside device clock manager, etc.
406 if (term != null && localNodeId.equals(term.master())) {
407 log.info("Retry marking {} offline", deviceId);
408 deviceClockProviderService.setMastershipTerm(deviceId, term);
409 post(store.markOffline(deviceId));
410 } else {
411 log.info("Failed again marking {} offline. {}", deviceId, role);
412 }
413 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700414 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700415 try {
samuele1fa7322015-07-14 16:35:16 +0800416 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700417 mastershipService.relinquishMastership(deviceId).get();
418 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800419 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700420 Thread.currentThread().interrupt();
421 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800422 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700423 }
tom0efbb1d2014-09-09 11:54:28 -0700424 }
tomd3097b02014-08-26 10:40:29 -0700425 }
426
427 @Override
alshabibb7b40632014-09-28 21:30:00 -0700428 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700429 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700430 checkNotNull(deviceId, DEVICE_ID_NULL);
alshabibb7b40632014-09-28 21:30:00 -0700431 checkNotNull(portDescriptions,
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700432 "Port descriptions list cannot be null");
tomeadbb462014-09-07 16:10:19 -0700433 checkValidity();
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700434 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
435 // Never been a master for this device
436 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800437 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700438 return;
439 }
440
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700441 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800442 deviceId, portDescriptions);
tom32f66842014-08-27 19:27:47 -0700443 for (DeviceEvent event : events) {
444 post(event);
445 }
tomd3097b02014-08-26 10:40:29 -0700446 }
447
448 @Override
alshabibb7b40632014-09-28 21:30:00 -0700449 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700450 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700451 checkNotNull(deviceId, DEVICE_ID_NULL);
452 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700453 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700454
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700455 if (!deviceClockProviderService.isTimestampAvailable(deviceId)) {
456 // Never been a master for this device
457 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700458 log.trace("Ignoring {} port update on standby node. {}", deviceId,
459 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700460 return;
461 }
462
samuele1fa7322015-07-14 16:35:16 +0800463 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
464 deviceId, portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700465 if (event != null) {
alshabibb7b40632014-09-28 21:30:00 -0700466 log.info("Device {} port {} status changed", deviceId, event
467 .port().number());
tom0efbb1d2014-09-09 11:54:28 -0700468 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700469 }
tomd3097b02014-08-26 10:40:29 -0700470 }
tom3f2bbd72014-09-24 12:07:58 -0700471
472 @Override
samuele1fa7322015-07-14 16:35:16 +0800473 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700474 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700475 // Several things can happen here:
476 // 1. request and response match
477 // 2. request and response don't match
478 // 3. MastershipRole and requested match (and 1 or 2 are true)
479 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
480 //
481 // 2, 4, and 3 with case 2 are failure modes.
482
tom3f2bbd72014-09-24 12:07:58 -0700483 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700484
Madan Jampanif2af7712015-05-29 18:43:52 -0700485 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700486 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700487
488 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800489 // something was off with DeviceProvider, maybe check channel too?
490 log.warn("Failed to assert role [{}] onto Device {}", requested, deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700491 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700492 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700493 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700494
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700495 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800496 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700497 return;
498 } else {
499 return;
samuele1fa7322015-07-14 16:35:16 +0800500 // FIXME roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700501 // the store; use the store's view, then try to reassert.
502 }
503 } else {
504 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800505 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700506 if (response == MastershipRole.MASTER) {
507 mastershipService.relinquishMastership(deviceId);
508 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800509 //final Device device = getDevice(deviceId);
510 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700511 }
512 }
tom3f2bbd72014-09-24 12:07:58 -0700513 }
sangho538108b2015-04-08 14:29:20 -0700514
515 @Override
samuele1fa7322015-07-14 16:35:16 +0800516 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700517 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700518 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700519 checkValidity();
520
samuele1fa7322015-07-14 16:35:16 +0800521 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
522 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700523 post(event);
524 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700525
526 // supplements or replaces deviceDescription annotations with
527 // BasicDeviceConfig annotations
528 private SparseAnnotations processAnnotations(BasicDeviceConfig cfg, DeviceDescription deviceDescription,
529 DeviceId deviceId) {
530 SparseAnnotations originalAnnotations = deviceDescription.annotations();
531 DefaultAnnotations.Builder newBuilder = DefaultAnnotations.builder();
532 if (cfg.driver() != deviceId.toString()) {
533 newBuilder.set(cfg.DRIVER, cfg.driver());
534 }
535 if (cfg.type() != Type.SWITCH) {
536 newBuilder.set(cfg.TYPE, cfg.type().toString());
537 }
538 if (cfg.name() != null) {
539 newBuilder.set(cfg.NAME, cfg.name());
540 }
541 if (cfg.latitude() != -1) {
542 newBuilder.set(cfg.LATITUDE, Double.toString(cfg.latitude()));
543 }
544 if (cfg.longitude() != -1) {
545 newBuilder.set(cfg.LONGITUDE, Double.toString(cfg.longitude()));
546 }
547 if (cfg.rackAddress() != null) {
548 newBuilder.set(cfg.RACK_ADDRESS, cfg.rackAddress());
549 }
550 if (cfg.owner() != null) {
551 newBuilder.set(cfg.OWNER, cfg.owner());
552 }
553 DefaultAnnotations newAnnotations = newBuilder.build();
554 return DefaultAnnotations.union(originalAnnotations, newAnnotations);
555 }
tomd3097b02014-08-26 10:40:29 -0700556 }
tom32f66842014-08-27 19:27:47 -0700557
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800558 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700559
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800560 /**
561 * Apply role to device and send probe if MASTER.
562 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700563 * @param deviceId device identifier
564 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800565 * @return true if the request was sent to provider
566 */
567 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
568 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800569 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700570 return true;
571 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700572
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800573 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800574 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800575 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800576 return false;
577 }
578 provider.roleChanged(deviceId, newRole);
579
580 if (newRole.equals(MastershipRole.MASTER)) {
581 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800582 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800583 }
584 return true;
585 }
586
587 /**
588 * Reaasert role for specified device connected to this node.
589 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700590 * @param did device identifier
591 * @param nextRole role to apply. If NONE is specified,
592 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800593 */
samuele1fa7322015-07-14 16:35:16 +0800594 private void reassertRole(final DeviceId did,
595 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800596
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800597 MastershipRole myNextRole = nextRole;
598 if (myNextRole == NONE) {
599 mastershipService.requestRoleFor(did);
600 MastershipTerm term = termService.getMastershipTerm(did);
Madan Jampanide003d92015-05-11 17:14:20 -0700601 if (term != null && localNodeId.equals(term.master())) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800602 myNextRole = MASTER;
603 } else {
604 myNextRole = STANDBY;
605 }
606 }
607
608 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700609 case MASTER:
610 final Device device = getDevice(did);
611 if ((device != null) && !isAvailable(did)) {
612 //flag the device as online. Is there a better way to do this?
613 DefaultDeviceDescription deviceDescription
614 = new DefaultDeviceDescription(did.uri(),
615 device.type(),
616 device.manufacturer(),
617 device.hwVersion(),
618 device.swVersion(),
619 device.serialNumber(),
620 device.chassisId());
621 DeviceEvent devEvent =
622 store.createOrUpdateDevice(device.providerId(), did,
623 deviceDescription);
624 post(devEvent);
625 }
626 // TODO: should apply role only if there is mismatch
627 log.debug("Applying role {} to {}", myNextRole, did);
628 if (!applyRoleAndProbe(did, MASTER)) {
629 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
630 // immediately failed to apply role
631 mastershipService.relinquishMastership(did);
632 // FIXME disconnect?
633 }
634 break;
635 case STANDBY:
636 log.debug("Applying role {} to {}", myNextRole, did);
637 if (!applyRoleAndProbe(did, STANDBY)) {
638 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
639 // immediately failed to apply role
640 mastershipService.relinquishMastership(did);
641 // FIXME disconnect?
642 }
643 break;
644 case NONE:
645 default:
646 // should never reach here
647 log.error("You didn't see anything. I did not exist.");
648 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800649 }
650 }
651
Madan Jampani328371d2015-05-29 14:06:27 -0700652 private void handleMastershipEvent(MastershipEvent event) {
653 if (event.type() != MastershipEvent.Type.MASTER_CHANGED) {
654 // Don't care if backup list changed.
655 return;
656 }
657
658 final DeviceId did = event.subject();
659
660 // myRole suggested by MastershipService
661 MastershipRole myNextRole;
662 if (localNodeId.equals(event.roleInfo().master())) {
663 // confirm latest info
664 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800665 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700666 if (iHaveControl) {
667 deviceClockProviderService.setMastershipTerm(did, term);
668 myNextRole = MASTER;
669 } else {
670 myNextRole = STANDBY;
671 }
672 } else if (event.roleInfo().backups().contains(localNodeId)) {
673 myNextRole = STANDBY;
674 } else {
675 myNextRole = NONE;
676 }
677
samuele1fa7322015-07-14 16:35:16 +0800678
Madan Jampani328371d2015-05-29 14:06:27 -0700679 final boolean isReachable = isReachable(did);
680 if (!isReachable) {
681 // device is not connected to this node
682 if (myNextRole != NONE) {
683 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700684 + "but this node cannot reach the device. "
685 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800686 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700687 mastershipService.relinquishMastership(did);
688 }
689 return;
690 }
691
692 // device is connected to this node:
693 if (store.getDevice(did) != null) {
694 reassertRole(did, myNextRole);
695 } else {
696 log.debug("Device is not yet/no longer in the store: {}", did);
697 }
698 }
699
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800700 // Intercepts mastership events
701 private class InternalMastershipListener implements MastershipListener {
702
tomb41d1ac2014-09-24 01:51:24 -0700703 @Override
704 public void event(MastershipEvent event) {
Madan Jampani328371d2015-05-29 14:06:27 -0700705 backgroundService.submit(() -> {
706 try {
707 handleMastershipEvent(event);
708 } catch (Exception e) {
709 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700710 }
Madan Jampani328371d2015-05-29 14:06:27 -0700711 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700712 }
tomb41d1ac2014-09-24 01:51:24 -0700713 }
tomf80c9722014-09-24 14:49:18 -0700714
715 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700716 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700717 @Override
718 public void notify(DeviceEvent event) {
719 post(event);
720 }
721 }
samuel738dfaf2015-07-11 11:08:57 +0800722
723 @Override
724 public Iterable<Device> getDevices(Type type) {
725 checkPermission(Permission.DEVICE_READ);
726 Set<Device> results = new HashSet<>();
727 Iterable<Device> devices = store.getDevices();
728 if (devices != null) {
729 devices.forEach(d -> {
730 if (type.equals(d.type())) {
731 results.add(d);
732 }
733 });
734 }
735 return results;
736 }
737
738 @Override
739 public Iterable<Device> getAvailableDevices(Type type) {
740 checkPermission(Permission.DEVICE_READ);
741 Set<Device> results = new HashSet<>();
742 Iterable<Device> availableDevices = store.getAvailableDevices();
743 if (availableDevices != null) {
744 availableDevices.forEach(d -> {
745 if (type.equals(d.type())) {
746 results.add(d);
747 }
748 });
749 }
750 return results;
751 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700752
753 private class InternalNetworkConfigListener implements NetworkConfigListener {
754 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700755 public boolean isRelevant(NetworkConfigEvent event) {
756 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
757 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
758 && event.configClass().equals(BasicDeviceConfig.class);
759 }
760
761 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700762 public void event(NetworkConfigEvent event) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700763 log.info("Detected Device network config event {}", event.type());
764 kickOutBadDevice(((DeviceId) event.subject()));
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700765 }
766 }
767
768 // checks if the specified device is allowed by the BasicDeviceConfig
769 // and if not, removes it
770 private void kickOutBadDevice(DeviceId deviceId) {
771 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
772 if (!cfg.isAllowed()) {
773 Device badDevice = getDevice(deviceId);
774 if (badDevice != null) {
775 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700776 }
777 }
778 }
tomd3097b02014-08-26 10:40:29 -0700779}