blob: cc8050233417244dd62bd8a14bd56297fe0fbe2a [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
tom32f66842014-08-27 19:27:47 -0700212 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900213 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700214 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700215 }
216
tom32f66842014-08-27 19:27:47 -0700217 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800218 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900219 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800220 return store.getAvailableDevices();
221 }
222
223 @Override
tom32f66842014-08-27 19:27:47 -0700224 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900225 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700226 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700227 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700228 }
229
230 @Override
tomad2d2092014-09-06 23:24:20 -0700231 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900232 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700233 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700234 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700235 }
236
237 @Override
tom32f66842014-08-27 19:27:47 -0700238 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900239 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700240 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700241 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700242 }
243
244 @Override
sangho538108b2015-04-08 14:29:20 -0700245 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900246 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700247 checkNotNull(deviceId, DEVICE_ID_NULL);
248 return store.getPortStatistics(deviceId);
249 }
250
251 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200252 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900253 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200254 checkNotNull(deviceId, DEVICE_ID_NULL);
255 return store.getPortDeltaStatistics(deviceId);
256 }
257
258 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530259 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
260 checkPermission(DEVICE_READ);
261 checkNotNull(deviceId, DEVICE_ID_NULL);
262 checkNotNull(portNumber, PORT_NUMBER_NULL);
263 return store.getStatisticsForPort(deviceId, portNumber);
264 }
265
266 @Override
267 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
268 checkPermission(DEVICE_READ);
269 checkNotNull(deviceId, DEVICE_ID_NULL);
270 checkNotNull(portNumber, PORT_NUMBER_NULL);
271 return store.getDeltaStatisticsForPort(deviceId, portNumber);
272 }
273
274 @Override
tom32f66842014-08-27 19:27:47 -0700275 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900276 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700277 checkNotNull(deviceId, DEVICE_ID_NULL);
278 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700279 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700280 }
281
282 @Override
tomff7eb7c2014-09-08 12:49:03 -0700283 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900284 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900285
tomff7eb7c2014-09-08 12:49:03 -0700286 checkNotNull(deviceId, DEVICE_ID_NULL);
287 return store.isAvailable(deviceId);
288 }
289
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800290 @Override
291 public String localStatus(DeviceId deviceId) {
292 LocalStatus ls = deviceLocalStatus.get(deviceId);
293 if (ls == null) {
294 return "No Record";
295 }
296 String timeAgo = Tools.timeAgo(ls.dateTime.getMillis());
297 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
298 }
299
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700300 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700301 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800302 if (deviceId == null) {
303 return false;
304 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700305 DeviceProvider provider = getProvider(deviceId);
306 if (provider != null) {
307 return provider.isReachable(deviceId);
308 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800309 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700310 return false;
311 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700312 }
313
tome5ec3fd2014-09-04 15:18:06 -0700314 @Override
315 public void removeDevice(DeviceId deviceId) {
316 checkNotNull(deviceId, DEVICE_ID_NULL);
317 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700318 if (event != null) {
319 log.info("Device {} administratively removed", deviceId);
320 post(event);
321 }
tome5ec3fd2014-09-04 15:18:06 -0700322 }
323
tom7869ad92014-09-09 14:32:08 -0700324 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700325 public void changePortState(DeviceId deviceId, PortNumber portNumber,
326 boolean enable) {
327 checkNotNull(deviceId, DEVICE_ID_NULL);
328 checkNotNull(deviceId, PORT_NUMBER_NULL);
329 DeviceProvider provider = getProvider(deviceId);
330 if (provider != null) {
331 log.warn("Port {} on device {} being administratively brought {}",
332 portNumber, deviceId,
333 (enable) ? "UP" : "DOWN");
334 provider.changePortState(deviceId, portNumber, enable);
335 } else {
336 log.warn("Provider not found for {}", deviceId);
337 }
338 }
339
340 @Override
samuele1fa7322015-07-14 16:35:16 +0800341 protected DeviceProviderService createProviderService(
342 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700343 return new InternalDeviceProviderService(provider);
344 }
345
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800346 /**
347 * Checks if all the reachable devices have a valid mastership role.
348 */
349 private void mastershipCheck() {
350 log.debug("Checking mastership");
351 for (Device device : getDevices()) {
352 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700353 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
354 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800355 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700356 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700357 // can't be master if device is not reachable
358 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700359 if (myRole == MASTER) {
360 post(store.markOffline(deviceId));
361 }
helenyrwufd296b62016-06-22 17:43:02 -0700362 //relinquish master role and ability to be backup.
363 mastershipService.relinquishMastership(deviceId).get();
364 } catch (InterruptedException e) {
365 log.warn("Interrupted while reliquishing role for {}", deviceId);
366 Thread.currentThread().interrupt();
367 } catch (ExecutionException e) {
368 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
369 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530370 } else {
371 // check if the device has master, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530372 // only the nodes which has mastership role can mark any device offline.
373 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
374 roleFuture.thenAccept(role -> {
375 MastershipTerm term = termService.getMastershipTerm(deviceId);
376 if (term != null && localNodeId.equals(term.master())) {
377 log.info("Marking unreachable device {} offline", deviceId);
378 post(store.markOffline(deviceId));
379 } else {
380 log.info("Failed marking {} offline. {}", deviceId, role);
381 }
382 mastershipService.relinquishMastership(deviceId);
383 });
helenyrwufd296b62016-06-22 17:43:02 -0700384 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800385 continue;
386 }
387
Ray Milkeyc7104672016-08-31 12:04:34 -0700388 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800389 continue;
390 }
391
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700392 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800393
394 // isReachable but was not MASTER or STANDBY, get a role and apply
395 // Note: NONE triggers request to MastershipService
396 reassertRole(deviceId, NONE);
397 }
398 }
399
tomd3097b02014-08-26 10:40:29 -0700400 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700401 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700402 extends AbstractProviderService<DeviceProvider>
403 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700404
tomcfde0622014-09-09 11:02:42 -0700405 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700406 super(provider);
407 }
408
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700409 /**
410 * Apply role in reaction to provider event.
411 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700412 * @param deviceId device identifier
413 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700414 * @return true if the request was sent to provider
415 */
416 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
417
418 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800419 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700420 return true;
421 }
422
423 DeviceProvider provider = provider();
424 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700425 log.warn("Provider for {} was not found. Cannot apply role {}",
426 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700427 return false;
428 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700429 provider.roleChanged(deviceId, newRole);
430 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700431 return true;
432 }
433
tomd3097b02014-08-26 10:40:29 -0700434 @Override
alshabibb7b40632014-09-28 21:30:00 -0700435 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700436 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700437 checkNotNull(deviceId, DEVICE_ID_NULL);
438 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700439 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700440
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800441 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
442
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700443 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
444 if (!isAllowed(cfg)) {
445 log.warn("Device {} is not allowed", deviceId);
446 return;
447 }
448 // Generate updated description and establish my Role
449 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700450 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700451 .thenAccept(role -> {
452 log.info("Local role is {} for {}", role, deviceId);
453 applyRole(deviceId, role);
454 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700455
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700456 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
457 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700458 if (deviceDescription.isDefaultAvailable()) {
459 log.info("Device {} connected", deviceId);
460 } else {
461 log.info("Device {} registered", deviceId);
462 }
tom80c0e5e2014-09-08 18:08:58 -0700463 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700464 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700465 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700466 }
tomd3097b02014-08-26 10:40:29 -0700467 }
468
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700469 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
470 if (desc.isEnabled() != enabled) {
471 return new DefaultPortDescription(desc.portNumber(),
472 enabled,
473 desc.type(),
474 desc.portSpeed(),
475 desc.annotations());
476 }
477 return desc;
478 }
479
tomd3097b02014-08-26 10:40:29 -0700480 @Override
481 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700482 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700483 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800484 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700485 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700486
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700487 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
488 .map(desc -> ensurePortEnabledState(desc, false))
489 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300490
alshabibafc514a2014-12-01 14:44:05 -0800491 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700492 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700493 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700494 post(store.markOffline(deviceId));
495 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700496 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700497 log.warn("Failed to mark {} offline", deviceId);
498 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800499 // but if I was the last STANDBY connection, etc. and no one else
500 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700501 // temporarily request for Master Role and mark offline.
502
samuele1fa7322015-07-14 16:35:16 +0800503 //there are times when this node will correctly have mastership, BUT
504 //that isn't reflected in the ClockManager before the device disconnects.
505 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700506
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700507 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800508 // Consider revising store API to handle this scenario.
509 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700510 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800511 MastershipTerm term = termService.getMastershipTerm(deviceId);
512 // TODO: Move this type of check inside device clock manager, etc.
513 if (term != null && localNodeId.equals(term.master())) {
514 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800515 post(store.markOffline(deviceId));
516 } else {
517 log.info("Failed again marking {} offline. {}", deviceId, role);
518 }
519 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700520 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700521 try {
samuele1fa7322015-07-14 16:35:16 +0800522 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700523 mastershipService.relinquishMastership(deviceId).get();
524 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800525 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700526 Thread.currentThread().interrupt();
527 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800528 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700529 }
tom0efbb1d2014-09-09 11:54:28 -0700530 }
tomd3097b02014-08-26 10:40:29 -0700531 }
532
533 @Override
alshabibb7b40632014-09-28 21:30:00 -0700534 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700535 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700536 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700537 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700538 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700539 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700540 // Never been a master for this device
541 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800542 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700543 return;
544 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700545 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700546 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700547 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700548 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800549 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800550 if (events != null) {
551 for (DeviceEvent event : events) {
552 post(event);
553 }
tom32f66842014-08-27 19:27:47 -0700554 }
tomd3097b02014-08-26 10:40:29 -0700555 }
556
557 @Override
alshabibb7b40632014-09-28 21:30:00 -0700558 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700559 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700560 checkNotNull(deviceId, DEVICE_ID_NULL);
561 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700562 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700563
Madan Jampani565a66a2015-07-25 17:01:13 -0700564 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700565 // Never been a master for this device
566 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700567 log.trace("Ignoring {} port update on standby node. {}", deviceId,
568 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700569 return;
570 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700571 Device device = getDevice(deviceId);
572 if (device == null) {
573 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530574 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700575 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200576 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700577 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700578 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700579 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700580 deviceId,
581 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700582 portDescription = ensurePortEnabledState(storedPortDesc,
583 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300584 }
585
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700586 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800587 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700588 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700589 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700590 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700591 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700592 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700593 }
tomd3097b02014-08-26 10:40:29 -0700594 }
tom3f2bbd72014-09-24 12:07:58 -0700595
596 @Override
Michal Machce774332017-01-25 11:02:55 +0100597 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
598
599 checkNotNull(deviceId, DEVICE_ID_NULL);
600 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
601 checkValidity();
602
603 if (!mastershipService.isLocalMaster(deviceId)) {
604 // Never been a master for this device
605 // any update will be ignored.
606 log.trace("Ignoring {} port update on standby node. {}", deviceId,
607 basePortDescription);
608 return;
609 }
610
611 Device device = getDevice(deviceId);
612 if (device == null) {
613 log.trace("Device not found: {}", deviceId);
614 }
615
616 PortDescription newPortDescription = new DefaultPortDescription(basePortDescription.portNumber(),
617 basePortDescription.isEnabled(),
618 true,
619 basePortDescription.type(),
620 basePortDescription.portSpeed(),
621 basePortDescription.annotations());
622 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
623 deviceId,
624 newPortDescription);
625 if (event != null) {
626 log.info("Device {} port {} status changed", deviceId, event.port().number());
627 post(event);
628 }
629 }
630
631 @Override
samuele1fa7322015-07-14 16:35:16 +0800632 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700633 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700634 // Several things can happen here:
635 // 1. request and response match
636 // 2. request and response don't match
637 // 3. MastershipRole and requested match (and 1 or 2 are true)
638 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
639 //
640 // 2, 4, and 3 with case 2 are failure modes.
641
tom3f2bbd72014-09-24 12:07:58 -0700642 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700643
Madan Jampanif2af7712015-05-29 18:43:52 -0700644 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700645 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700646
647 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800648 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530649 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700650 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700651 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700652 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700653
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700654 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800655 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700656 return;
657 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800658 log.warn("Role mismatch on {}. set to {}, but store demands {}",
659 deviceId, response, mastershipService.getLocalRole(deviceId));
660 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700661 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800662 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800663 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700664 }
665 } else {
666 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800667 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700668 if (response == MastershipRole.MASTER) {
669 mastershipService.relinquishMastership(deviceId);
670 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800671 //final Device device = getDevice(deviceId);
672 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700673 }
674 }
tom3f2bbd72014-09-24 12:07:58 -0700675 }
sangho538108b2015-04-08 14:29:20 -0700676
677 @Override
samuele1fa7322015-07-14 16:35:16 +0800678 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700679 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700680 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700681 checkValidity();
682
samuele1fa7322015-07-14 16:35:16 +0800683 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
684 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700685 post(event);
686 }
tomd3097b02014-08-26 10:40:29 -0700687 }
tom32f66842014-08-27 19:27:47 -0700688
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700689 // by default allowed, otherwise check flag
690 private boolean isAllowed(BasicDeviceConfig cfg) {
691 return (cfg == null || cfg.isAllowed());
692 }
693
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800694 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700695
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800696 /**
697 * Apply role to device and send probe if MASTER.
698 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700699 * @param deviceId device identifier
700 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800701 * @return true if the request was sent to provider
702 */
703 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
704 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800705 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700706 return true;
707 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700708
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800709 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800710 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800711 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800712 return false;
713 }
714 provider.roleChanged(deviceId, newRole);
715
716 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800717 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800718 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800719 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800720 }
721 return true;
722 }
723
724 /**
725 * Reaasert role for specified device connected to this node.
726 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700727 * @param did device identifier
728 * @param nextRole role to apply. If NONE is specified,
729 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800730 */
samuele1fa7322015-07-14 16:35:16 +0800731 private void reassertRole(final DeviceId did,
732 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800733
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800734 MastershipRole myNextRole = nextRole;
735 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800736 try {
737 mastershipService.requestRoleFor(did).get();
738 MastershipTerm term = termService.getMastershipTerm(did);
739 if (term != null && localNodeId.equals(term.master())) {
740 myNextRole = MASTER;
741 } else {
742 myNextRole = STANDBY;
743 }
744 } catch (InterruptedException e) {
745 Thread.currentThread().interrupt();
746 log.error("Interrupted waiting for Mastership", e);
747 } catch (ExecutionException e) {
748 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800749 }
750 }
751
752 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700753 case MASTER:
754 final Device device = getDevice(did);
755 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700756 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700757 }
758 // TODO: should apply role only if there is mismatch
759 log.debug("Applying role {} to {}", myNextRole, did);
760 if (!applyRoleAndProbe(did, MASTER)) {
761 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
762 // immediately failed to apply role
763 mastershipService.relinquishMastership(did);
764 // FIXME disconnect?
765 }
766 break;
767 case STANDBY:
768 log.debug("Applying role {} to {}", myNextRole, did);
769 if (!applyRoleAndProbe(did, STANDBY)) {
770 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
771 // immediately failed to apply role
772 mastershipService.relinquishMastership(did);
773 // FIXME disconnect?
774 }
775 break;
776 case NONE:
777 default:
778 // should never reach here
779 log.error("You didn't see anything. I did not exist.");
780 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800781 }
782 }
783
Madan Jampani328371d2015-05-29 14:06:27 -0700784 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700785 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700786 // Don't care if backup list changed.
787 return;
788 }
Madan Jampani328371d2015-05-29 14:06:27 -0700789 final DeviceId did = event.subject();
790
791 // myRole suggested by MastershipService
792 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700793 if (event.type() == MastershipEvent.Type.SUSPENDED) {
794 myNextRole = NONE; // FIXME STANDBY OR NONE?
795 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700796 // confirm latest info
797 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800798 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700799 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700800 myNextRole = MASTER;
801 } else {
802 myNextRole = STANDBY;
803 }
804 } else if (event.roleInfo().backups().contains(localNodeId)) {
805 myNextRole = STANDBY;
806 } else {
807 myNextRole = NONE;
808 }
809
Madan Jampani328371d2015-05-29 14:06:27 -0700810 final boolean isReachable = isReachable(did);
811 if (!isReachable) {
812 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800813 if (mastershipService.getLocalRole(did) == NONE) {
814 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700815 + "but this node cannot reach the device "
816 + "and role is already None. Ignoring request.",
817 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800818 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700819 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700820 + "but this node cannot reach the device. "
821 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800822 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700823 mastershipService.relinquishMastership(did);
824 }
825 return;
826 }
827
828 // device is connected to this node:
829 if (store.getDevice(did) != null) {
830 reassertRole(did, myNextRole);
831 } else {
832 log.debug("Device is not yet/no longer in the store: {}", did);
833 }
834 }
835
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800836 // Intercepts mastership events
837 private class InternalMastershipListener implements MastershipListener {
838
tomb41d1ac2014-09-24 01:51:24 -0700839 @Override
840 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800841 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700842 try {
843 handleMastershipEvent(event);
844 } catch (Exception e) {
845 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700846 }
Madan Jampani328371d2015-05-29 14:06:27 -0700847 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700848 }
tomb41d1ac2014-09-24 01:51:24 -0700849 }
tomf80c9722014-09-24 14:49:18 -0700850
851 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700852 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700853 @Override
854 public void notify(DeviceEvent event) {
855 post(event);
856 }
857 }
samuel738dfaf2015-07-11 11:08:57 +0800858
859 @Override
860 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900861 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800862 Set<Device> results = new HashSet<>();
863 Iterable<Device> devices = store.getDevices();
864 if (devices != null) {
865 devices.forEach(d -> {
866 if (type.equals(d.type())) {
867 results.add(d);
868 }
869 });
870 }
871 return results;
872 }
873
874 @Override
875 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900876 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800877 Set<Device> results = new HashSet<>();
878 Iterable<Device> availableDevices = store.getAvailableDevices();
879 if (availableDevices != null) {
880 availableDevices.forEach(d -> {
881 if (type.equals(d.type())) {
882 results.add(d);
883 }
884 });
885 }
886 return results;
887 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700888
889 private class InternalNetworkConfigListener implements NetworkConfigListener {
890 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700891 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700892 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
893 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
894 && (event.configClass().equals(BasicDeviceConfig.class)
Simon Huntffbad3b2017-05-16 15:37:51 -0700895 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700896 }
897
898 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700899 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700900 DeviceEvent de = null;
901 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800902 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700903 DeviceId did = (DeviceId) event.subject();
Simon Huntffbad3b2017-05-16 15:37:51 -0700904 DeviceProvider dp = getProvider(did);
905 BasicDeviceConfig cfg =
906 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700907
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700908 if (!isAllowed(cfg)) {
909 kickOutBadDevice(did);
910 } else {
911 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700912 DeviceDescription desc =
913 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700914 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -0700915 if (desc != null && dp != null) {
916 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700917 }
918 }
919 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700920 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700921 ConnectPoint cpt = (ConnectPoint) event.subject();
922 DeviceId did = cpt.deviceId();
Simon Huntffbad3b2017-05-16 15:37:51 -0700923 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700924
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700925 // Note: assuming PortOperator can modify existing port,
926 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -0700927 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700928 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
929 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -0700930 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700931 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700932 }
933
934 if (de != null) {
935 post(de);
936 }
937 }
938
Simon Hunt8f60ff82017-04-24 17:19:30 -0700939 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700940 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700941 Device badDevice = getDevice(deviceId);
942 if (badDevice != null) {
943 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700944 }
945 }
946 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700947
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700948 @Override
949 @SafeVarargs
950 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -0700951 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700952 checkNotNull(portOp);
953
954 portOp.bindService(networkConfigService);
955
956 // update both portOpsIndex and portOps
957 synchronized (portOpsIndex) {
958 for (Class<? extends Config<ConnectPoint>> config : configs) {
959 portOpsIndex.put(config, portOp);
960 }
961
962 portOps.add(portOp);
963 }
964
965 // TODO: Should we be applying to all existing Ports?
966 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -0700967 .map(Device::id)
968 .filter(mastershipService::isLocalMaster)
969 // for each locally managed Device, update all port descriptions
970 .map(did -> {
971 ProviderId pid = Optional.ofNullable(getProvider(did))
972 .map(Provider::id)
973 .orElse(null);
974 if (pid == null) {
975 log.warn("Provider not found for {}", did);
976 return ImmutableList.<DeviceEvent>of();
977 }
978 List<PortDescription> pds
979 = store.getPortDescriptions(pid, did)
980 .map(pdesc -> applyAllPortOps(did, pdesc))
981 .collect(Collectors.toList());
982 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700983 })
Simon Huntffbad3b2017-05-16 15:37:51 -0700984 // ..and port port update event if necessary
985 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700986 }
987
988 @Override
989 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
990 checkNotNull(portOp);
991
992
993 // remove all portOp
994 synchronized (portOpsIndex) {
995 portOps.remove(portOp);
996
997 // had to do this since COWArrayList iterator doesn't support remove
998 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
999 }
1000
1001 }
1002
1003 /**
1004 * Merges the appropriate PortConfig with the description.
1005 *
1006 * @param did ID of the Device where the port is attached
1007 * @param desc {@link PortDescription}
1008 * @return merged {@link PortDescription}
1009 */
1010 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1011 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1012 }
1013
1014 /**
1015 * Merges the appropriate PortConfig with the description.
1016 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001017 * @param cpt ConnectPoint where the port is attached
1018 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001019 * @return merged {@link PortDescription}
1020 */
1021 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1022 PortDescription work = desc;
1023 for (PortConfigOperator portOp : portOps) {
1024 work = portOp.combine(cpt, work);
1025 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001026 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001027 }
1028
tomd3097b02014-08-26 10:40:29 -07001029}