blob: ed26b41ad382ca8d987324b8461087e1107625f4 [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
Yafit Hadara9a73de2015-09-06 13:52:52 +030018import java.util.Collection;
19import java.util.HashSet;
20import java.util.List;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080021import java.util.Map;
Yafit Hadara9a73de2015-09-06 13:52:52 +030022import java.util.Objects;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070023import java.util.Optional;
Yafit Hadara9a73de2015-09-06 13:52:52 +030024import java.util.Set;
25import java.util.concurrent.CompletableFuture;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070026import java.util.concurrent.ConcurrentHashMap;
27import java.util.concurrent.CopyOnWriteArrayList;
Yafit Hadara9a73de2015-09-06 13:52:52 +030028import java.util.concurrent.ExecutionException;
29import java.util.concurrent.ScheduledExecutorService;
30import java.util.concurrent.TimeUnit;
31import java.util.stream.Collectors;
tomd3097b02014-08-26 10:40:29 -070032import org.apache.felix.scr.annotations.Activate;
33import org.apache.felix.scr.annotations.Component;
34import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070035import org.apache.felix.scr.annotations.Reference;
36import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070037import org.apache.felix.scr.annotations.Service;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080038import org.joda.time.DateTime;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070039import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.cluster.ClusterService;
41import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.mastership.MastershipEvent;
43import org.onosproject.mastership.MastershipListener;
44import org.onosproject.mastership.MastershipService;
45import org.onosproject.mastership.MastershipTerm;
46import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070047import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080049import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080050import org.onosproject.net.DeviceId;
51import org.onosproject.net.MastershipRole;
52import org.onosproject.net.Port;
53import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070054import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030055import org.onosproject.net.config.NetworkConfigEvent;
56import org.onosproject.net.config.NetworkConfigListener;
57import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070058import org.onosproject.net.config.PortConfigOperator;
59import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030060import org.onosproject.net.config.basics.BasicDeviceConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080061import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.device.DefaultPortDescription;
63import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080064import org.onosproject.net.device.DeviceDescription;
65import org.onosproject.net.device.DeviceEvent;
66import org.onosproject.net.device.DeviceListener;
67import org.onosproject.net.device.DeviceProvider;
68import org.onosproject.net.device.DeviceProviderRegistry;
69import org.onosproject.net.device.DeviceProviderService;
70import org.onosproject.net.device.DeviceService;
71import org.onosproject.net.device.DeviceStore;
72import org.onosproject.net.device.DeviceStoreDelegate;
73import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070074import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030075import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080076import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080077import org.onosproject.net.provider.Provider;
78import org.onosproject.net.provider.ProviderId;
tomd3097b02014-08-26 10:40:29 -070079import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070080
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080081import com.google.common.collect.ImmutableList;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080082import com.google.common.collect.Maps;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070083import com.google.common.collect.Multimap;
Yafit Hadara9a73de2015-09-06 13:52:52 +030084import com.google.common.util.concurrent.Futures;
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
149 = synchronizedListMultimap(
150 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
151
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 }
167 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
168 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700169
tomd3097b02014-08-26 10:40:29 -0700170 @Activate
171 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800172 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
173 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
174
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800175 backgroundService = newSingleThreadScheduledExecutor(
176 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700177 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800178
tomf80c9722014-09-24 14:49:18 -0700179 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700180 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700181 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700182 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800183
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700184 backgroundService.scheduleWithFixedDelay(() -> {
185 try {
186 mastershipCheck();
187 } catch (Exception e) {
188 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800189 }
190 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700191 log.info("Started");
192 }
193
194 @Deactivate
195 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800196 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700197 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700198 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700199 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700200 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700201 log.info("Stopped");
202 }
203
204 @Override
tomad2d2092014-09-06 23:24:20 -0700205 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900206 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700207 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700208 }
209
210 @Override
tom32f66842014-08-27 19:27:47 -0700211 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900212 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700213 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700214 }
215
tom32f66842014-08-27 19:27:47 -0700216 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800217 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900218 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800219 return store.getAvailableDevices();
220 }
221
222 @Override
tom32f66842014-08-27 19:27:47 -0700223 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900224 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700225 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700226 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700227 }
228
229 @Override
tomad2d2092014-09-06 23:24:20 -0700230 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900231 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700232 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700233 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700234 }
235
236 @Override
tom32f66842014-08-27 19:27:47 -0700237 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900238 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700239 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700240 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700241 }
242
243 @Override
sangho538108b2015-04-08 14:29:20 -0700244 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900245 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700246 checkNotNull(deviceId, DEVICE_ID_NULL);
247 return store.getPortStatistics(deviceId);
248 }
249
250 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200251 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900252 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200253 checkNotNull(deviceId, DEVICE_ID_NULL);
254 return store.getPortDeltaStatistics(deviceId);
255 }
256
257 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530258 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
259 checkPermission(DEVICE_READ);
260 checkNotNull(deviceId, DEVICE_ID_NULL);
261 checkNotNull(portNumber, PORT_NUMBER_NULL);
262 return store.getStatisticsForPort(deviceId, portNumber);
263 }
264
265 @Override
266 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
267 checkPermission(DEVICE_READ);
268 checkNotNull(deviceId, DEVICE_ID_NULL);
269 checkNotNull(portNumber, PORT_NUMBER_NULL);
270 return store.getDeltaStatisticsForPort(deviceId, portNumber);
271 }
272
273 @Override
tom32f66842014-08-27 19:27:47 -0700274 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900275 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700276 checkNotNull(deviceId, DEVICE_ID_NULL);
277 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700278 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700279 }
280
281 @Override
tomff7eb7c2014-09-08 12:49:03 -0700282 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900283 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900284
tomff7eb7c2014-09-08 12:49:03 -0700285 checkNotNull(deviceId, DEVICE_ID_NULL);
286 return store.isAvailable(deviceId);
287 }
288
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800289 @Override
290 public String localStatus(DeviceId deviceId) {
291 LocalStatus ls = deviceLocalStatus.get(deviceId);
292 if (ls == null) {
293 return "No Record";
294 }
295 String timeAgo = Tools.timeAgo(ls.dateTime.getMillis());
296 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
297 }
298
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700299 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700300 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800301 if (deviceId == null) {
302 return false;
303 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700304 DeviceProvider provider = getProvider(deviceId);
305 if (provider != null) {
306 return provider.isReachable(deviceId);
307 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800308 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700309 return false;
310 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700311 }
312
tome5ec3fd2014-09-04 15:18:06 -0700313 @Override
314 public void removeDevice(DeviceId deviceId) {
315 checkNotNull(deviceId, DEVICE_ID_NULL);
316 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700317 if (event != null) {
318 log.info("Device {} administratively removed", deviceId);
319 post(event);
320 }
tome5ec3fd2014-09-04 15:18:06 -0700321 }
322
tom7869ad92014-09-09 14:32:08 -0700323 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700324 public void changePortState(DeviceId deviceId, PortNumber portNumber,
325 boolean enable) {
326 checkNotNull(deviceId, DEVICE_ID_NULL);
327 checkNotNull(deviceId, PORT_NUMBER_NULL);
328 DeviceProvider provider = getProvider(deviceId);
329 if (provider != null) {
330 log.warn("Port {} on device {} being administratively brought {}",
331 portNumber, deviceId,
332 (enable) ? "UP" : "DOWN");
333 provider.changePortState(deviceId, portNumber, enable);
334 } else {
335 log.warn("Provider not found for {}", deviceId);
336 }
337 }
338
339 @Override
samuele1fa7322015-07-14 16:35:16 +0800340 protected DeviceProviderService createProviderService(
341 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700342 return new InternalDeviceProviderService(provider);
343 }
344
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800345 /**
346 * Checks if all the reachable devices have a valid mastership role.
347 */
348 private void mastershipCheck() {
349 log.debug("Checking mastership");
350 for (Device device : getDevices()) {
351 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700352 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
353 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800354 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700355 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700356 // can't be master if device is not reachable
357 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700358 if (myRole == MASTER) {
359 post(store.markOffline(deviceId));
360 }
helenyrwufd296b62016-06-22 17:43:02 -0700361 //relinquish master role and ability to be backup.
362 mastershipService.relinquishMastership(deviceId).get();
363 } catch (InterruptedException e) {
364 log.warn("Interrupted while reliquishing role for {}", deviceId);
365 Thread.currentThread().interrupt();
366 } catch (ExecutionException e) {
367 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
368 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530369 } else {
370 // check if the device has master, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530371 // only the nodes which has mastership role can mark any device offline.
372 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
373 roleFuture.thenAccept(role -> {
374 MastershipTerm term = termService.getMastershipTerm(deviceId);
375 if (term != null && localNodeId.equals(term.master())) {
376 log.info("Marking unreachable device {} offline", deviceId);
377 post(store.markOffline(deviceId));
378 } else {
379 log.info("Failed marking {} offline. {}", deviceId, role);
380 }
381 mastershipService.relinquishMastership(deviceId);
382 });
helenyrwufd296b62016-06-22 17:43:02 -0700383 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800384 continue;
385 }
386
Ray Milkeyc7104672016-08-31 12:04:34 -0700387 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800388 continue;
389 }
390
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700391 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800392
393 // isReachable but was not MASTER or STANDBY, get a role and apply
394 // Note: NONE triggers request to MastershipService
395 reassertRole(deviceId, NONE);
396 }
397 }
398
tomd3097b02014-08-26 10:40:29 -0700399 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700400 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700401 extends AbstractProviderService<DeviceProvider>
402 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700403
tomcfde0622014-09-09 11:02:42 -0700404 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700405 super(provider);
406 }
407
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700408 /**
409 * Apply role in reaction to provider event.
410 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700411 * @param deviceId device identifier
412 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700413 * @return true if the request was sent to provider
414 */
415 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
416
417 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800418 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700419 return true;
420 }
421
422 DeviceProvider provider = provider();
423 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700424 log.warn("Provider for {} was not found. Cannot apply role {}",
425 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700426 return false;
427 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700428 provider.roleChanged(deviceId, newRole);
429 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700430 return true;
431 }
432
tomd3097b02014-08-26 10:40:29 -0700433 @Override
alshabibb7b40632014-09-28 21:30:00 -0700434 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700435 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700436 checkNotNull(deviceId, DEVICE_ID_NULL);
437 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700438 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700439
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800440 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
441
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700442 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
443 if (!isAllowed(cfg)) {
444 log.warn("Device {} is not allowed", deviceId);
445 return;
446 }
447 // Generate updated description and establish my Role
448 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700449 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
450 .thenAccept(role -> {
451 log.info("Local role is {} for {}", role, deviceId);
452 applyRole(deviceId, role);
453 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700454
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700455 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
456 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700457 if (deviceDescription.isDefaultAvailable()) {
458 log.info("Device {} connected", deviceId);
459 } else {
460 log.info("Device {} registered", deviceId);
461 }
tom80c0e5e2014-09-08 18:08:58 -0700462 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700463 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700464 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700465 }
tomd3097b02014-08-26 10:40:29 -0700466 }
467
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700468 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
469 if (desc.isEnabled() != enabled) {
470 return new DefaultPortDescription(desc.portNumber(),
471 enabled,
472 desc.type(),
473 desc.portSpeed(),
474 desc.annotations());
475 }
476 return desc;
477 }
478
tomd3097b02014-08-26 10:40:29 -0700479 @Override
480 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700481 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700482 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800483 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700484 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700485
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700486 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
487 .map(desc -> ensurePortEnabledState(desc, false))
488 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300489
alshabibafc514a2014-12-01 14:44:05 -0800490 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700491 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700492 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700493 post(store.markOffline(deviceId));
494 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700495 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700496 log.warn("Failed to mark {} offline", deviceId);
497 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800498 // but if I was the last STANDBY connection, etc. and no one else
499 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700500 // temporarily request for Master Role and mark offline.
501
samuele1fa7322015-07-14 16:35:16 +0800502 //there are times when this node will correctly have mastership, BUT
503 //that isn't reflected in the ClockManager before the device disconnects.
504 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700505
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700506 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800507 // Consider revising store API to handle this scenario.
508 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700509 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800510 MastershipTerm term = termService.getMastershipTerm(deviceId);
511 // TODO: Move this type of check inside device clock manager, etc.
512 if (term != null && localNodeId.equals(term.master())) {
513 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800514 post(store.markOffline(deviceId));
515 } else {
516 log.info("Failed again marking {} offline. {}", deviceId, role);
517 }
518 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700519 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700520 try {
samuele1fa7322015-07-14 16:35:16 +0800521 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700522 mastershipService.relinquishMastership(deviceId).get();
523 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800524 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700525 Thread.currentThread().interrupt();
526 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800527 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700528 }
tom0efbb1d2014-09-09 11:54:28 -0700529 }
tomd3097b02014-08-26 10:40:29 -0700530 }
531
532 @Override
alshabibb7b40632014-09-28 21:30:00 -0700533 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700534 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700535 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700536 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700537 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700538 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700539 // Never been a master for this device
540 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800541 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700542 return;
543 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700544 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700545 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700546 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700547 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800548 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800549 if (events != null) {
550 for (DeviceEvent event : events) {
551 post(event);
552 }
tom32f66842014-08-27 19:27:47 -0700553 }
tomd3097b02014-08-26 10:40:29 -0700554 }
555
556 @Override
alshabibb7b40632014-09-28 21:30:00 -0700557 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700558 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700559 checkNotNull(deviceId, DEVICE_ID_NULL);
560 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700561 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700562
Madan Jampani565a66a2015-07-25 17:01:13 -0700563 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700564 // Never been a master for this device
565 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700566 log.trace("Ignoring {} port update on standby node. {}", deviceId,
567 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700568 return;
569 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700570 Device device = getDevice(deviceId);
571 if (device == null) {
572 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530573 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700574 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200575 if ((Device.Type.ROADM.equals(device.type())) ||
576 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700577 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700578 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
579 deviceId,
580 portDescription.portNumber());
581 portDescription = ensurePortEnabledState(storedPortDesc,
582 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300583 }
584
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700585 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800586 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700587 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700588 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700589 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700590 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700591 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700592 }
tomd3097b02014-08-26 10:40:29 -0700593 }
tom3f2bbd72014-09-24 12:07:58 -0700594
595 @Override
Michal Machce774332017-01-25 11:02:55 +0100596 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
597
598 checkNotNull(deviceId, DEVICE_ID_NULL);
599 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
600 checkValidity();
601
602 if (!mastershipService.isLocalMaster(deviceId)) {
603 // Never been a master for this device
604 // any update will be ignored.
605 log.trace("Ignoring {} port update on standby node. {}", deviceId,
606 basePortDescription);
607 return;
608 }
609
610 Device device = getDevice(deviceId);
611 if (device == null) {
612 log.trace("Device not found: {}", deviceId);
613 }
614
615 PortDescription newPortDescription = new DefaultPortDescription(basePortDescription.portNumber(),
616 basePortDescription.isEnabled(),
617 true,
618 basePortDescription.type(),
619 basePortDescription.portSpeed(),
620 basePortDescription.annotations());
621 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
622 deviceId,
623 newPortDescription);
624 if (event != null) {
625 log.info("Device {} port {} status changed", deviceId, event.port().number());
626 post(event);
627 }
628 }
629
630 @Override
samuele1fa7322015-07-14 16:35:16 +0800631 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700632 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700633 // Several things can happen here:
634 // 1. request and response match
635 // 2. request and response don't match
636 // 3. MastershipRole and requested match (and 1 or 2 are true)
637 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
638 //
639 // 2, 4, and 3 with case 2 are failure modes.
640
tom3f2bbd72014-09-24 12:07:58 -0700641 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700642
Madan Jampanif2af7712015-05-29 18:43:52 -0700643 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700644 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700645
646 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800647 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530648 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700649 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700650 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700651 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700652
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700653 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800654 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700655 return;
656 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800657 log.warn("Role mismatch on {}. set to {}, but store demands {}",
658 deviceId, response, mastershipService.getLocalRole(deviceId));
659 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700660 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800661 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800662 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700663 }
664 } else {
665 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800666 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700667 if (response == MastershipRole.MASTER) {
668 mastershipService.relinquishMastership(deviceId);
669 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800670 //final Device device = getDevice(deviceId);
671 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700672 }
673 }
tom3f2bbd72014-09-24 12:07:58 -0700674 }
sangho538108b2015-04-08 14:29:20 -0700675
676 @Override
samuele1fa7322015-07-14 16:35:16 +0800677 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700678 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700679 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700680 checkValidity();
681
samuele1fa7322015-07-14 16:35:16 +0800682 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
683 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700684 post(event);
685 }
tomd3097b02014-08-26 10:40:29 -0700686 }
tom32f66842014-08-27 19:27:47 -0700687
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700688 // by default allowed, otherwise check flag
689 private boolean isAllowed(BasicDeviceConfig cfg) {
690 return (cfg == null || cfg.isAllowed());
691 }
692
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800693 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700694
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800695 /**
696 * Apply role to device and send probe if MASTER.
697 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700698 * @param deviceId device identifier
699 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800700 * @return true if the request was sent to provider
701 */
702 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
703 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800704 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700705 return true;
706 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700707
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800708 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800709 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800710 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800711 return false;
712 }
713 provider.roleChanged(deviceId, newRole);
714
715 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800716 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800717 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800718 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800719 }
720 return true;
721 }
722
723 /**
724 * Reaasert role for specified device connected to this node.
725 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700726 * @param did device identifier
727 * @param nextRole role to apply. If NONE is specified,
728 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800729 */
samuele1fa7322015-07-14 16:35:16 +0800730 private void reassertRole(final DeviceId did,
731 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800732
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800733 MastershipRole myNextRole = nextRole;
734 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800735 try {
736 mastershipService.requestRoleFor(did).get();
737 MastershipTerm term = termService.getMastershipTerm(did);
738 if (term != null && localNodeId.equals(term.master())) {
739 myNextRole = MASTER;
740 } else {
741 myNextRole = STANDBY;
742 }
743 } catch (InterruptedException e) {
744 Thread.currentThread().interrupt();
745 log.error("Interrupted waiting for Mastership", e);
746 } catch (ExecutionException e) {
747 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800748 }
749 }
750
751 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700752 case MASTER:
753 final Device device = getDevice(did);
754 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700755 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700756 }
757 // TODO: should apply role only if there is mismatch
758 log.debug("Applying role {} to {}", myNextRole, did);
759 if (!applyRoleAndProbe(did, MASTER)) {
760 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
761 // immediately failed to apply role
762 mastershipService.relinquishMastership(did);
763 // FIXME disconnect?
764 }
765 break;
766 case STANDBY:
767 log.debug("Applying role {} to {}", myNextRole, did);
768 if (!applyRoleAndProbe(did, STANDBY)) {
769 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
770 // immediately failed to apply role
771 mastershipService.relinquishMastership(did);
772 // FIXME disconnect?
773 }
774 break;
775 case NONE:
776 default:
777 // should never reach here
778 log.error("You didn't see anything. I did not exist.");
779 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800780 }
781 }
782
Madan Jampani328371d2015-05-29 14:06:27 -0700783 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700784 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700785 // Don't care if backup list changed.
786 return;
787 }
Madan Jampani328371d2015-05-29 14:06:27 -0700788 final DeviceId did = event.subject();
789
790 // myRole suggested by MastershipService
791 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700792 if (event.type() == MastershipEvent.Type.SUSPENDED) {
793 myNextRole = NONE; // FIXME STANDBY OR NONE?
794 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700795 // confirm latest info
796 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800797 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700798 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700799 myNextRole = MASTER;
800 } else {
801 myNextRole = STANDBY;
802 }
803 } else if (event.roleInfo().backups().contains(localNodeId)) {
804 myNextRole = STANDBY;
805 } else {
806 myNextRole = NONE;
807 }
808
Madan Jampani328371d2015-05-29 14:06:27 -0700809 final boolean isReachable = isReachable(did);
810 if (!isReachable) {
811 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800812 if (mastershipService.getLocalRole(did) == NONE) {
813 log.debug("Node was instructed to be {} role for {}, "
814 + "but this node cannot reach the device "
815 + "and role is already None. Ignoring request.",
816 myNextRole, did);
817 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700818 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700819 + "but this node cannot reach the device. "
820 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800821 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700822 mastershipService.relinquishMastership(did);
823 }
824 return;
825 }
826
827 // device is connected to this node:
828 if (store.getDevice(did) != null) {
829 reassertRole(did, myNextRole);
830 } else {
831 log.debug("Device is not yet/no longer in the store: {}", did);
832 }
833 }
834
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800835 // Intercepts mastership events
836 private class InternalMastershipListener implements MastershipListener {
837
tomb41d1ac2014-09-24 01:51:24 -0700838 @Override
839 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800840 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700841 try {
842 handleMastershipEvent(event);
843 } catch (Exception e) {
844 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700845 }
Madan Jampani328371d2015-05-29 14:06:27 -0700846 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700847 }
tomb41d1ac2014-09-24 01:51:24 -0700848 }
tomf80c9722014-09-24 14:49:18 -0700849
850 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700851 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700852 @Override
853 public void notify(DeviceEvent event) {
854 post(event);
855 }
856 }
samuel738dfaf2015-07-11 11:08:57 +0800857
858 @Override
859 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900860 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800861 Set<Device> results = new HashSet<>();
862 Iterable<Device> devices = store.getDevices();
863 if (devices != null) {
864 devices.forEach(d -> {
865 if (type.equals(d.type())) {
866 results.add(d);
867 }
868 });
869 }
870 return results;
871 }
872
873 @Override
874 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900875 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800876 Set<Device> results = new HashSet<>();
877 Iterable<Device> availableDevices = store.getAvailableDevices();
878 if (availableDevices != null) {
879 availableDevices.forEach(d -> {
880 if (type.equals(d.type())) {
881 results.add(d);
882 }
883 });
884 }
885 return results;
886 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700887
888 private class InternalNetworkConfigListener implements NetworkConfigListener {
889 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700890 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700891 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
892 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
893 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700894 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700895 }
896
897 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700898 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700899 DeviceEvent de = null;
900 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800901 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700902 DeviceId did = (DeviceId) event.subject();
903 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700904
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700905 if (!isAllowed(cfg)) {
906 kickOutBadDevice(did);
907 } else {
908 Device dev = getDevice(did);
909 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
910 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800911 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700912 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
913 }
914 }
915 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700916 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700917 ConnectPoint cpt = (ConnectPoint) event.subject();
918 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700919
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700920 // Note: assuming PortOperator can modify existing port,
921 // but cannot add new port purely from Config.
922 de = Optional.ofNullable(getProvider(did))
923 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
924 .map(desc -> applyAllPortOps(cpt, desc))
925 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
926 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700927 }
928
929 if (de != null) {
930 post(de);
931 }
932 }
933
934 // checks if the specified device is allowed by the BasicDeviceConfig
935 // and if not, removes it
936 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700937 Device badDevice = getDevice(deviceId);
938 if (badDevice != null) {
939 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700940 }
941 }
942 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700943
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700944 @Override
945 @SafeVarargs
946 public final void registerPortConfigOperator(PortConfigOperator portOp,
947 Class<? extends Config<ConnectPoint>>...configs) {
948 checkNotNull(portOp);
949
950 portOp.bindService(networkConfigService);
951
952 // update both portOpsIndex and portOps
953 synchronized (portOpsIndex) {
954 for (Class<? extends Config<ConnectPoint>> config : configs) {
955 portOpsIndex.put(config, portOp);
956 }
957
958 portOps.add(portOp);
959 }
960
961 // TODO: Should we be applying to all existing Ports?
962 Tools.stream(store.getAvailableDevices())
963 .map(Device::id)
964 .filter(mastershipService::isLocalMaster)
965 // for each locally managed Device, update all port descriptions
966 .map(did -> {
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800967 ProviderId pid = Optional.ofNullable(getProvider(did))
968 .map(Provider::id)
969 .orElse(null);
970 if (pid == null) {
971 log.warn("Provider not found for {}", did);
972 return ImmutableList.<DeviceEvent>of();
973 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700974 List<PortDescription> pds
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800975 = store.getPortDescriptions(pid, did)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700976 .map(pdesc -> applyAllPortOps(did, pdesc))
977 .collect(Collectors.toList());
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800978 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700979 })
980 // ..and port port update event if necessary
981 .forEach(evts -> evts.forEach(this::post));
982 }
983
984 @Override
985 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
986 checkNotNull(portOp);
987
988
989 // remove all portOp
990 synchronized (portOpsIndex) {
991 portOps.remove(portOp);
992
993 // had to do this since COWArrayList iterator doesn't support remove
994 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
995 }
996
997 }
998
999 /**
1000 * Merges the appropriate PortConfig with the description.
1001 *
1002 * @param did ID of the Device where the port is attached
1003 * @param desc {@link PortDescription}
1004 * @return merged {@link PortDescription}
1005 */
1006 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1007 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1008 }
1009
1010 /**
1011 * Merges the appropriate PortConfig with the description.
1012 *
1013 * @param cpt ConnectPoint where the port is attached
1014 * @param desc {@link PortDescription}
1015 * @return merged {@link PortDescription}
1016 */
1017 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1018 PortDescription work = desc;
1019 for (PortConfigOperator portOp : portOps) {
1020 work = portOp.combine(cpt, work);
1021 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001022 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001023 }
1024
tomd3097b02014-08-26 10:40:29 -07001025}