blob: c0bf128788f1333d8c3fb5a0491cd25392c08900 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present 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
Simon Huntffbad3b2017-05-16 15:37:51 -070018import com.google.common.collect.ImmutableList;
19import com.google.common.collect.Maps;
20import com.google.common.collect.Multimap;
21import com.google.common.util.concurrent.Futures;
tomd3097b02014-08-26 10:40:29 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070025import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070027import org.apache.felix.scr.annotations.Service;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080028import org.joda.time.DateTime;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070029import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.cluster.ClusterService;
31import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.mastership.MastershipEvent;
33import org.onosproject.mastership.MastershipListener;
34import org.onosproject.mastership.MastershipService;
35import org.onosproject.mastership.MastershipTerm;
36import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070037import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080039import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.DeviceId;
41import org.onosproject.net.MastershipRole;
42import org.onosproject.net.Port;
43import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070044import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030045import org.onosproject.net.config.NetworkConfigEvent;
46import org.onosproject.net.config.NetworkConfigListener;
47import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070048import org.onosproject.net.config.PortConfigOperator;
49import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030050import org.onosproject.net.config.basics.BasicDeviceConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080051import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.device.DefaultPortDescription;
53import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DeviceDescription;
55import org.onosproject.net.device.DeviceEvent;
56import org.onosproject.net.device.DeviceListener;
57import org.onosproject.net.device.DeviceProvider;
58import org.onosproject.net.device.DeviceProviderRegistry;
59import org.onosproject.net.device.DeviceProviderService;
60import org.onosproject.net.device.DeviceService;
61import org.onosproject.net.device.DeviceStore;
62import org.onosproject.net.device.DeviceStoreDelegate;
63import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070064import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030065import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080067import org.onosproject.net.provider.Provider;
68import org.onosproject.net.provider.ProviderId;
tomd3097b02014-08-26 10:40:29 -070069import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070070
Simon Huntffbad3b2017-05-16 15:37:51 -070071import java.util.Collection;
72import java.util.HashSet;
73import java.util.List;
74import java.util.Map;
75import java.util.Objects;
76import java.util.Optional;
77import java.util.Set;
78import java.util.concurrent.CompletableFuture;
79import java.util.concurrent.ConcurrentHashMap;
80import java.util.concurrent.CopyOnWriteArrayList;
81import java.util.concurrent.ExecutionException;
82import java.util.concurrent.ScheduledExecutorService;
83import java.util.concurrent.TimeUnit;
84import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080085
Ray Milkey9ef22232016-07-14 12:42:37 -070086import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070087import static com.google.common.collect.Multimaps.newListMultimap;
88import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Ray Milkey9ef22232016-07-14 12:42:37 -070089import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
90import static org.onlab.util.Tools.groupedThreads;
91import static org.onosproject.net.MastershipRole.MASTER;
92import static org.onosproject.net.MastershipRole.NONE;
93import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -070094import static org.onosproject.security.AppGuard.checkPermission;
95import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
96import static org.slf4j.LoggerFactory.getLogger;
97
tomd3097b02014-08-26 10:40:29 -070098/**
tome4729872014-09-23 00:37:37 -070099 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700100 */
101@Component(immediate = true)
102@Service
tom41a2c5f2014-09-19 09:20:35 -0700103public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700104 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700105 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700106
tome5ec3fd2014-09-04 15:18:06 -0700107 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
108 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
109 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
110 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700111 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
tomd3097b02014-08-26 10:40:29 -0700112
tom5f38b3a2014-08-27 23:50:54 -0700113 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700114
alshabib339a3d92014-09-26 17:54:32 -0700115 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700116
tomc78acee2014-09-24 15:16:55 -0700117 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700118 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700119
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800120 private ScheduledExecutorService backgroundService;
121
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700122 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
123
tom41a2c5f2014-09-19 09:20:35 -0700124 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
125 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700126
tom5f38b3a2014-08-27 23:50:54 -0700127 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700128 protected ClusterService clusterService;
129
130 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700131 protected MastershipService mastershipService;
132
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800133 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700134 protected MastershipTermService termService;
135
Madan Jampani61056bc2014-09-27 09:07:26 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700137 protected NetworkConfigService networkConfigService;
138
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700139
140 /**
141 * List of all registered PortConfigOperator.
142 */
143 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
144
145 /**
146 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
147 */
148 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700149 = synchronizedListMultimap(
150 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700151
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800152 // not part of portOps. must be executed at the end
153 private PortAnnotationOperator portAnnotationOp;
154
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800155 /**
156 * Local storage for connectivity status of devices.
157 */
158 private class LocalStatus {
159 boolean connected;
160 DateTime dateTime;
161
162 public LocalStatus(boolean b, DateTime now) {
163 connected = b;
164 dateTime = now;
165 }
166 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700167
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800168 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
169 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700170
tomd3097b02014-08-26 10:40:29 -0700171 @Activate
172 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800173 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
174 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
175
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800176 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700177 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700178 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800179
tomf80c9722014-09-24 14:49:18 -0700180 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700181 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700182 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700183 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800184
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700185 backgroundService.scheduleWithFixedDelay(() -> {
186 try {
187 mastershipCheck();
188 } catch (Exception e) {
189 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800190 }
191 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700192 log.info("Started");
193 }
194
195 @Deactivate
196 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800197 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700198 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700199 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700200 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700201 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700202 log.info("Stopped");
203 }
204
205 @Override
tomad2d2092014-09-06 23:24:20 -0700206 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900207 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700208 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700209 }
210
211 @Override
mskala32000d32017-07-14 16:27:06 +0200212 public int getAvailableDeviceCount() {
213 checkPermission(DEVICE_READ);
214 return store.getAvailableDeviceCount();
215 }
216
217 @Override
tom32f66842014-08-27 19:27:47 -0700218 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900219 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700220 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700221 }
222
tom32f66842014-08-27 19:27:47 -0700223 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800224 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900225 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800226 return store.getAvailableDevices();
227 }
228
229 @Override
tom32f66842014-08-27 19:27:47 -0700230 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900231 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700232 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700233 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700234 }
235
236 @Override
tomad2d2092014-09-06 23:24:20 -0700237 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900238 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700239 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700240 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700241 }
242
243 @Override
tom32f66842014-08-27 19:27:47 -0700244 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900245 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700246 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700247 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700248 }
249
250 @Override
sangho538108b2015-04-08 14:29:20 -0700251 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900252 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700253 checkNotNull(deviceId, DEVICE_ID_NULL);
254 return store.getPortStatistics(deviceId);
255 }
256
257 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200258 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200260 checkNotNull(deviceId, DEVICE_ID_NULL);
261 return store.getPortDeltaStatistics(deviceId);
262 }
263
264 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530265 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
266 checkPermission(DEVICE_READ);
267 checkNotNull(deviceId, DEVICE_ID_NULL);
268 checkNotNull(portNumber, PORT_NUMBER_NULL);
269 return store.getStatisticsForPort(deviceId, portNumber);
270 }
271
272 @Override
273 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
274 checkPermission(DEVICE_READ);
275 checkNotNull(deviceId, DEVICE_ID_NULL);
276 checkNotNull(portNumber, PORT_NUMBER_NULL);
277 return store.getDeltaStatisticsForPort(deviceId, portNumber);
278 }
279
280 @Override
tom32f66842014-08-27 19:27:47 -0700281 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900282 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700283 checkNotNull(deviceId, DEVICE_ID_NULL);
284 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700285 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700286 }
287
288 @Override
tomff7eb7c2014-09-08 12:49:03 -0700289 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900290 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900291
tomff7eb7c2014-09-08 12:49:03 -0700292 checkNotNull(deviceId, DEVICE_ID_NULL);
293 return store.isAvailable(deviceId);
294 }
295
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800296 @Override
297 public String localStatus(DeviceId deviceId) {
298 LocalStatus ls = deviceLocalStatus.get(deviceId);
299 if (ls == null) {
300 return "No Record";
301 }
302 String timeAgo = Tools.timeAgo(ls.dateTime.getMillis());
303 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
304 }
305
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700306 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700307 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800308 if (deviceId == null) {
309 return false;
310 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700311 DeviceProvider provider = getProvider(deviceId);
312 if (provider != null) {
313 return provider.isReachable(deviceId);
314 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800315 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700316 return false;
317 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700318 }
319
tome5ec3fd2014-09-04 15:18:06 -0700320 @Override
321 public void removeDevice(DeviceId deviceId) {
322 checkNotNull(deviceId, DEVICE_ID_NULL);
323 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700324 if (event != null) {
325 log.info("Device {} administratively removed", deviceId);
326 post(event);
327 }
tome5ec3fd2014-09-04 15:18:06 -0700328 }
329
tom7869ad92014-09-09 14:32:08 -0700330 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700331 public void changePortState(DeviceId deviceId, PortNumber portNumber,
332 boolean enable) {
333 checkNotNull(deviceId, DEVICE_ID_NULL);
334 checkNotNull(deviceId, PORT_NUMBER_NULL);
335 DeviceProvider provider = getProvider(deviceId);
336 if (provider != null) {
337 log.warn("Port {} on device {} being administratively brought {}",
338 portNumber, deviceId,
339 (enable) ? "UP" : "DOWN");
340 provider.changePortState(deviceId, portNumber, enable);
341 } else {
342 log.warn("Provider not found for {}", deviceId);
343 }
344 }
345
346 @Override
samuele1fa7322015-07-14 16:35:16 +0800347 protected DeviceProviderService createProviderService(
348 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700349 return new InternalDeviceProviderService(provider);
350 }
351
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800352 /**
353 * Checks if all the reachable devices have a valid mastership role.
354 */
355 private void mastershipCheck() {
356 log.debug("Checking mastership");
357 for (Device device : getDevices()) {
358 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700359 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
360 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800361 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700362 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700363 // can't be master if device is not reachable
364 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700365 if (myRole == MASTER) {
366 post(store.markOffline(deviceId));
367 }
helenyrwufd296b62016-06-22 17:43:02 -0700368 //relinquish master role and ability to be backup.
369 mastershipService.relinquishMastership(deviceId).get();
370 } catch (InterruptedException e) {
371 log.warn("Interrupted while reliquishing role for {}", deviceId);
372 Thread.currentThread().interrupt();
373 } catch (ExecutionException e) {
374 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
375 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530376 } else {
377 // check if the device has master, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530378 // only the nodes which has mastership role can mark any device offline.
379 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
380 roleFuture.thenAccept(role -> {
381 MastershipTerm term = termService.getMastershipTerm(deviceId);
382 if (term != null && localNodeId.equals(term.master())) {
383 log.info("Marking unreachable device {} offline", deviceId);
384 post(store.markOffline(deviceId));
385 } else {
386 log.info("Failed marking {} offline. {}", deviceId, role);
387 }
388 mastershipService.relinquishMastership(deviceId);
389 });
helenyrwufd296b62016-06-22 17:43:02 -0700390 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800391 continue;
392 }
393
Ray Milkeyc7104672016-08-31 12:04:34 -0700394 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800395 continue;
396 }
397
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700398 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800399
400 // isReachable but was not MASTER or STANDBY, get a role and apply
401 // Note: NONE triggers request to MastershipService
402 reassertRole(deviceId, NONE);
403 }
404 }
405
tomd3097b02014-08-26 10:40:29 -0700406 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700407 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700408 extends AbstractProviderService<DeviceProvider>
409 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700410
tomcfde0622014-09-09 11:02:42 -0700411 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700412 super(provider);
413 }
414
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700415 /**
416 * Apply role in reaction to provider event.
417 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700418 * @param deviceId device identifier
419 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700420 * @return true if the request was sent to provider
421 */
422 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
423
424 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800425 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700426 return true;
427 }
428
429 DeviceProvider provider = provider();
430 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700431 log.warn("Provider for {} was not found. Cannot apply role {}",
432 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700433 return false;
434 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700435 provider.roleChanged(deviceId, newRole);
436 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700437 return true;
438 }
439
tomd3097b02014-08-26 10:40:29 -0700440 @Override
alshabibb7b40632014-09-28 21:30:00 -0700441 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700442 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700443 checkNotNull(deviceId, DEVICE_ID_NULL);
444 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700445 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700446
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800447 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
448
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700449 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
450 if (!isAllowed(cfg)) {
451 log.warn("Device {} is not allowed", deviceId);
452 return;
453 }
454 // Generate updated description and establish my Role
455 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700456 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700457 .thenAccept(role -> {
458 log.info("Local role is {} for {}", role, deviceId);
459 applyRole(deviceId, role);
460 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700461
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700462 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
463 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700464 if (deviceDescription.isDefaultAvailable()) {
465 log.info("Device {} connected", deviceId);
466 } else {
467 log.info("Device {} registered", deviceId);
468 }
tom80c0e5e2014-09-08 18:08:58 -0700469 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700470 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700471 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700472 }
tomd3097b02014-08-26 10:40:29 -0700473 }
474
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700475 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
476 if (desc.isEnabled() != enabled) {
477 return new DefaultPortDescription(desc.portNumber(),
478 enabled,
479 desc.type(),
480 desc.portSpeed(),
481 desc.annotations());
482 }
483 return desc;
484 }
485
tomd3097b02014-08-26 10:40:29 -0700486 @Override
487 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700488 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700489 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800490 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700491 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700492
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700493 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
494 .map(desc -> ensurePortEnabledState(desc, false))
495 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300496
alshabibafc514a2014-12-01 14:44:05 -0800497 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700498 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700499 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700500 post(store.markOffline(deviceId));
501 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700502 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700503 log.warn("Failed to mark {} offline", deviceId);
504 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800505 // but if I was the last STANDBY connection, etc. and no one else
506 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700507 // temporarily request for Master Role and mark offline.
508
samuele1fa7322015-07-14 16:35:16 +0800509 //there are times when this node will correctly have mastership, BUT
510 //that isn't reflected in the ClockManager before the device disconnects.
511 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700512
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700513 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800514 // Consider revising store API to handle this scenario.
515 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700516 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800517 MastershipTerm term = termService.getMastershipTerm(deviceId);
518 // TODO: Move this type of check inside device clock manager, etc.
519 if (term != null && localNodeId.equals(term.master())) {
520 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800521 post(store.markOffline(deviceId));
522 } else {
523 log.info("Failed again marking {} offline. {}", deviceId, role);
524 }
525 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700526 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700527 try {
samuele1fa7322015-07-14 16:35:16 +0800528 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700529 mastershipService.relinquishMastership(deviceId).get();
530 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800531 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700532 Thread.currentThread().interrupt();
533 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800534 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700535 }
tom0efbb1d2014-09-09 11:54:28 -0700536 }
tomd3097b02014-08-26 10:40:29 -0700537 }
538
539 @Override
alshabibb7b40632014-09-28 21:30:00 -0700540 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700541 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700542 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700543 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700544 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700545 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700546 // Never been a master for this device
547 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800548 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700549 return;
550 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700551 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700552 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700553 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700554 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800555 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800556 if (events != null) {
557 for (DeviceEvent event : events) {
558 post(event);
559 }
tom32f66842014-08-27 19:27:47 -0700560 }
tomd3097b02014-08-26 10:40:29 -0700561 }
562
563 @Override
alshabibb7b40632014-09-28 21:30:00 -0700564 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700565 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700566 checkNotNull(deviceId, DEVICE_ID_NULL);
567 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700568 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700569
Madan Jampani565a66a2015-07-25 17:01:13 -0700570 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700571 // Never been a master for this device
572 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700573 log.trace("Ignoring {} port update on standby node. {}", deviceId,
574 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700575 return;
576 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700577 Device device = getDevice(deviceId);
578 if (device == null) {
579 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530580 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700581 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200582 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700583 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700584 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700585 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700586 deviceId,
587 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700588 portDescription = ensurePortEnabledState(storedPortDesc,
589 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300590 }
591
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700592 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800593 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700594 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700595 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700596 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700597 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700598 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700599 }
tomd3097b02014-08-26 10:40:29 -0700600 }
tom3f2bbd72014-09-24 12:07:58 -0700601
602 @Override
Michal Machce774332017-01-25 11:02:55 +0100603 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
604
605 checkNotNull(deviceId, DEVICE_ID_NULL);
606 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
607 checkValidity();
608
609 if (!mastershipService.isLocalMaster(deviceId)) {
610 // Never been a master for this device
611 // any update will be ignored.
612 log.trace("Ignoring {} port update on standby node. {}", deviceId,
613 basePortDescription);
614 return;
615 }
616
617 Device device = getDevice(deviceId);
618 if (device == null) {
619 log.trace("Device not found: {}", deviceId);
620 }
621
622 PortDescription newPortDescription = new DefaultPortDescription(basePortDescription.portNumber(),
623 basePortDescription.isEnabled(),
624 true,
625 basePortDescription.type(),
626 basePortDescription.portSpeed(),
627 basePortDescription.annotations());
628 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
629 deviceId,
630 newPortDescription);
631 if (event != null) {
632 log.info("Device {} port {} status changed", deviceId, event.port().number());
633 post(event);
634 }
635 }
636
637 @Override
samuele1fa7322015-07-14 16:35:16 +0800638 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700639 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700640 // Several things can happen here:
641 // 1. request and response match
642 // 2. request and response don't match
643 // 3. MastershipRole and requested match (and 1 or 2 are true)
644 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
645 //
646 // 2, 4, and 3 with case 2 are failure modes.
647
tom3f2bbd72014-09-24 12:07:58 -0700648 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700649
Madan Jampanif2af7712015-05-29 18:43:52 -0700650 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700651 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700652
653 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800654 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530655 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700656 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700657 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700658 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700659
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700660 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800661 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700662 return;
663 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800664 log.warn("Role mismatch on {}. set to {}, but store demands {}",
665 deviceId, response, mastershipService.getLocalRole(deviceId));
666 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700667 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800668 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800669 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700670 }
671 } else {
672 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800673 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700674 if (response == MastershipRole.MASTER) {
675 mastershipService.relinquishMastership(deviceId);
676 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800677 //final Device device = getDevice(deviceId);
678 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700679 }
680 }
tom3f2bbd72014-09-24 12:07:58 -0700681 }
sangho538108b2015-04-08 14:29:20 -0700682
683 @Override
samuele1fa7322015-07-14 16:35:16 +0800684 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700685 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700686 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700687 checkValidity();
688
samuele1fa7322015-07-14 16:35:16 +0800689 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
690 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700691 post(event);
692 }
tomd3097b02014-08-26 10:40:29 -0700693 }
tom32f66842014-08-27 19:27:47 -0700694
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700695 // by default allowed, otherwise check flag
696 private boolean isAllowed(BasicDeviceConfig cfg) {
697 return (cfg == null || cfg.isAllowed());
698 }
699
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800700 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700701
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800702 /**
703 * Apply role to device and send probe if MASTER.
704 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700705 * @param deviceId device identifier
706 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800707 * @return true if the request was sent to provider
708 */
709 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
710 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800711 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700712 return true;
713 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700714
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800715 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800716 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800717 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800718 return false;
719 }
720 provider.roleChanged(deviceId, newRole);
721
722 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800723 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800724 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800725 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800726 }
727 return true;
728 }
729
730 /**
731 * Reaasert role for specified device connected to this node.
732 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700733 * @param did device identifier
734 * @param nextRole role to apply. If NONE is specified,
735 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800736 */
samuele1fa7322015-07-14 16:35:16 +0800737 private void reassertRole(final DeviceId did,
738 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800739
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800740 MastershipRole myNextRole = nextRole;
741 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800742 try {
743 mastershipService.requestRoleFor(did).get();
744 MastershipTerm term = termService.getMastershipTerm(did);
745 if (term != null && localNodeId.equals(term.master())) {
746 myNextRole = MASTER;
747 } else {
748 myNextRole = STANDBY;
749 }
750 } catch (InterruptedException e) {
751 Thread.currentThread().interrupt();
752 log.error("Interrupted waiting for Mastership", e);
753 } catch (ExecutionException e) {
754 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800755 }
756 }
757
758 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700759 case MASTER:
760 final Device device = getDevice(did);
761 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700762 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700763 }
764 // TODO: should apply role only if there is mismatch
765 log.debug("Applying role {} to {}", myNextRole, did);
766 if (!applyRoleAndProbe(did, MASTER)) {
767 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
768 // immediately failed to apply role
769 mastershipService.relinquishMastership(did);
770 // FIXME disconnect?
771 }
772 break;
773 case STANDBY:
774 log.debug("Applying role {} to {}", myNextRole, did);
775 if (!applyRoleAndProbe(did, STANDBY)) {
776 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
777 // immediately failed to apply role
778 mastershipService.relinquishMastership(did);
779 // FIXME disconnect?
780 }
781 break;
782 case NONE:
783 default:
784 // should never reach here
785 log.error("You didn't see anything. I did not exist.");
786 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800787 }
788 }
789
Madan Jampani328371d2015-05-29 14:06:27 -0700790 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700791 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700792 // Don't care if backup list changed.
793 return;
794 }
Madan Jampani328371d2015-05-29 14:06:27 -0700795 final DeviceId did = event.subject();
796
797 // myRole suggested by MastershipService
798 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700799 if (event.type() == MastershipEvent.Type.SUSPENDED) {
800 myNextRole = NONE; // FIXME STANDBY OR NONE?
801 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700802 // confirm latest info
803 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800804 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700805 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700806 myNextRole = MASTER;
807 } else {
808 myNextRole = STANDBY;
809 }
810 } else if (event.roleInfo().backups().contains(localNodeId)) {
811 myNextRole = STANDBY;
812 } else {
813 myNextRole = NONE;
814 }
815
Madan Jampani328371d2015-05-29 14:06:27 -0700816 final boolean isReachable = isReachable(did);
817 if (!isReachable) {
818 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800819 if (mastershipService.getLocalRole(did) == NONE) {
820 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700821 + "but this node cannot reach the device "
822 + "and role is already None. Ignoring request.",
823 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800824 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700825 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700826 + "but this node cannot reach the device. "
827 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800828 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700829 mastershipService.relinquishMastership(did);
830 }
831 return;
832 }
833
834 // device is connected to this node:
835 if (store.getDevice(did) != null) {
836 reassertRole(did, myNextRole);
837 } else {
838 log.debug("Device is not yet/no longer in the store: {}", did);
839 }
840 }
841
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800842 // Intercepts mastership events
843 private class InternalMastershipListener implements MastershipListener {
844
tomb41d1ac2014-09-24 01:51:24 -0700845 @Override
846 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800847 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700848 try {
849 handleMastershipEvent(event);
850 } catch (Exception e) {
851 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700852 }
Madan Jampani328371d2015-05-29 14:06:27 -0700853 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700854 }
tomb41d1ac2014-09-24 01:51:24 -0700855 }
tomf80c9722014-09-24 14:49:18 -0700856
857 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700858 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700859 @Override
860 public void notify(DeviceEvent event) {
861 post(event);
862 }
863 }
samuel738dfaf2015-07-11 11:08:57 +0800864
865 @Override
866 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900867 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800868 Set<Device> results = new HashSet<>();
869 Iterable<Device> devices = store.getDevices();
870 if (devices != null) {
871 devices.forEach(d -> {
872 if (type.equals(d.type())) {
873 results.add(d);
874 }
875 });
876 }
877 return results;
878 }
879
880 @Override
881 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900882 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800883 Set<Device> results = new HashSet<>();
884 Iterable<Device> availableDevices = store.getAvailableDevices();
885 if (availableDevices != null) {
886 availableDevices.forEach(d -> {
887 if (type.equals(d.type())) {
888 results.add(d);
889 }
890 });
891 }
892 return results;
893 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700894
895 private class InternalNetworkConfigListener implements NetworkConfigListener {
896 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700897 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700898 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
899 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
900 && (event.configClass().equals(BasicDeviceConfig.class)
Simon Huntffbad3b2017-05-16 15:37:51 -0700901 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700902 }
903
904 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700905 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700906 DeviceEvent de = null;
907 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800908 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700909 DeviceId did = (DeviceId) event.subject();
Simon Huntffbad3b2017-05-16 15:37:51 -0700910 DeviceProvider dp = getProvider(did);
911 BasicDeviceConfig cfg =
912 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700913
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700914 if (!isAllowed(cfg)) {
915 kickOutBadDevice(did);
916 } else {
917 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700918 DeviceDescription desc =
919 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700920 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -0700921 if (desc != null && dp != null) {
922 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700923 }
924 }
925 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700926 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700927 ConnectPoint cpt = (ConnectPoint) event.subject();
928 DeviceId did = cpt.deviceId();
Simon Huntffbad3b2017-05-16 15:37:51 -0700929 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700930
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700931 // Note: assuming PortOperator can modify existing port,
932 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -0700933 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700934 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
935 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -0700936 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700937 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700938 }
939
940 if (de != null) {
941 post(de);
942 }
943 }
944
Simon Hunt8f60ff82017-04-24 17:19:30 -0700945 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700946 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700947 Device badDevice = getDevice(deviceId);
948 if (badDevice != null) {
949 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700950 }
951 }
952 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700953
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700954 @Override
955 @SafeVarargs
956 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -0700957 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700958 checkNotNull(portOp);
959
960 portOp.bindService(networkConfigService);
961
962 // update both portOpsIndex and portOps
963 synchronized (portOpsIndex) {
964 for (Class<? extends Config<ConnectPoint>> config : configs) {
965 portOpsIndex.put(config, portOp);
966 }
967
968 portOps.add(portOp);
969 }
970
971 // TODO: Should we be applying to all existing Ports?
972 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -0700973 .map(Device::id)
974 .filter(mastershipService::isLocalMaster)
975 // for each locally managed Device, update all port descriptions
976 .map(did -> {
977 ProviderId pid = Optional.ofNullable(getProvider(did))
978 .map(Provider::id)
979 .orElse(null);
980 if (pid == null) {
981 log.warn("Provider not found for {}", did);
982 return ImmutableList.<DeviceEvent>of();
983 }
984 List<PortDescription> pds
985 = store.getPortDescriptions(pid, did)
986 .map(pdesc -> applyAllPortOps(did, pdesc))
987 .collect(Collectors.toList());
988 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700989 })
Simon Huntffbad3b2017-05-16 15:37:51 -0700990 // ..and port port update event if necessary
991 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700992 }
993
994 @Override
995 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
996 checkNotNull(portOp);
997
998
999 // remove all portOp
1000 synchronized (portOpsIndex) {
1001 portOps.remove(portOp);
1002
1003 // had to do this since COWArrayList iterator doesn't support remove
1004 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1005 }
1006
1007 }
1008
1009 /**
1010 * Merges the appropriate PortConfig with the description.
1011 *
1012 * @param did ID of the Device where the port is attached
1013 * @param desc {@link PortDescription}
1014 * @return merged {@link PortDescription}
1015 */
1016 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1017 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1018 }
1019
1020 /**
1021 * Merges the appropriate PortConfig with the description.
1022 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001023 * @param cpt ConnectPoint where the port is attached
1024 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001025 * @return merged {@link PortDescription}
1026 */
1027 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1028 PortDescription work = desc;
1029 for (PortConfigOperator portOp : portOps) {
1030 work = portOp.combine(cpt, work);
1031 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001032 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001033 }
1034
tomd3097b02014-08-26 10:40:29 -07001035}