blob: a86b50dab64c41035ca55f38dfebfaec6d340677 [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;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.device.DefaultPortDescription;
62import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.device.DeviceDescription;
64import org.onosproject.net.device.DeviceEvent;
65import org.onosproject.net.device.DeviceListener;
66import org.onosproject.net.device.DeviceProvider;
67import org.onosproject.net.device.DeviceProviderRegistry;
68import org.onosproject.net.device.DeviceProviderService;
69import org.onosproject.net.device.DeviceService;
70import org.onosproject.net.device.DeviceStore;
71import org.onosproject.net.device.DeviceStoreDelegate;
72import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070073import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030074import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080075import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080076import org.onosproject.net.provider.Provider;
77import org.onosproject.net.provider.ProviderId;
tomd3097b02014-08-26 10:40:29 -070078import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070079
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080080import com.google.common.collect.ImmutableList;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080081import com.google.common.collect.Maps;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070082import com.google.common.collect.Multimap;
Yafit Hadara9a73de2015-09-06 13:52:52 +030083import com.google.common.util.concurrent.Futures;
Jonathan Hart2f669362015-02-11 16:19:20 -080084
Ray Milkey9ef22232016-07-14 12:42:37 -070085import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070086import static com.google.common.collect.Multimaps.newListMultimap;
87import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Ray Milkey9ef22232016-07-14 12:42:37 -070088import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
89import static org.onlab.util.Tools.groupedThreads;
90import static org.onosproject.net.MastershipRole.MASTER;
91import static org.onosproject.net.MastershipRole.NONE;
92import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -070093import static org.onosproject.security.AppGuard.checkPermission;
94import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
95import static org.slf4j.LoggerFactory.getLogger;
96
tomd3097b02014-08-26 10:40:29 -070097/**
tome4729872014-09-23 00:37:37 -070098 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070099 */
100@Component(immediate = true)
101@Service
tom41a2c5f2014-09-19 09:20:35 -0700102public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700103 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700104 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700105
tome5ec3fd2014-09-04 15:18:06 -0700106 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
107 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
108 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
109 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700110 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
tomd3097b02014-08-26 10:40:29 -0700111
tom5f38b3a2014-08-27 23:50:54 -0700112 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700113
alshabib339a3d92014-09-26 17:54:32 -0700114 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700115
tomc78acee2014-09-24 15:16:55 -0700116 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700117 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700118
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800119 private ScheduledExecutorService backgroundService;
120
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700121 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
122
tom41a2c5f2014-09-19 09:20:35 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
124 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700125
tom5f38b3a2014-08-27 23:50:54 -0700126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700127 protected ClusterService clusterService;
128
129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700130 protected MastershipService mastershipService;
131
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700133 protected MastershipTermService termService;
134
Madan Jampani61056bc2014-09-27 09:07:26 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700136 protected NetworkConfigService networkConfigService;
137
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700138
139 /**
140 * List of all registered PortConfigOperator.
141 */
142 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
143
144 /**
145 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
146 */
147 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
148 = synchronizedListMultimap(
149 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
150
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800151 /**
152 * Local storage for connectivity status of devices.
153 */
154 private class LocalStatus {
155 boolean connected;
156 DateTime dateTime;
157
158 public LocalStatus(boolean b, DateTime now) {
159 connected = b;
160 dateTime = now;
161 }
162 }
163 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
164 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700165
tomd3097b02014-08-26 10:40:29 -0700166 @Activate
167 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800168 backgroundService = newSingleThreadScheduledExecutor(
169 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700170 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800171
tomf80c9722014-09-24 14:49:18 -0700172 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700173 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700174 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700175 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800176
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700177 backgroundService.scheduleWithFixedDelay(() -> {
178 try {
179 mastershipCheck();
180 } catch (Exception e) {
181 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800182 }
183 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700184 log.info("Started");
185 }
186
187 @Deactivate
188 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800189 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700190 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700191 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700192 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700193 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700194 log.info("Stopped");
195 }
196
197 @Override
tomad2d2092014-09-06 23:24:20 -0700198 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900199 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700200 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700201 }
202
203 @Override
tom32f66842014-08-27 19:27:47 -0700204 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900205 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700206 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700207 }
208
tom32f66842014-08-27 19:27:47 -0700209 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800210 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900211 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800212 return store.getAvailableDevices();
213 }
214
215 @Override
tom32f66842014-08-27 19:27:47 -0700216 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900217 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700218 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700219 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700220 }
221
222 @Override
tomad2d2092014-09-06 23:24:20 -0700223 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900224 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700225 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700226 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700227 }
228
229 @Override
tom32f66842014-08-27 19:27:47 -0700230 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900231 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700232 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700233 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700234 }
235
236 @Override
sangho538108b2015-04-08 14:29:20 -0700237 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900238 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700239 checkNotNull(deviceId, DEVICE_ID_NULL);
240 return store.getPortStatistics(deviceId);
241 }
242
243 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200244 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900245 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200246 checkNotNull(deviceId, DEVICE_ID_NULL);
247 return store.getPortDeltaStatistics(deviceId);
248 }
249
250 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530251 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
252 checkPermission(DEVICE_READ);
253 checkNotNull(deviceId, DEVICE_ID_NULL);
254 checkNotNull(portNumber, PORT_NUMBER_NULL);
255 return store.getStatisticsForPort(deviceId, portNumber);
256 }
257
258 @Override
259 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
260 checkPermission(DEVICE_READ);
261 checkNotNull(deviceId, DEVICE_ID_NULL);
262 checkNotNull(portNumber, PORT_NUMBER_NULL);
263 return store.getDeltaStatisticsForPort(deviceId, portNumber);
264 }
265
266 @Override
tom32f66842014-08-27 19:27:47 -0700267 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900268 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700269 checkNotNull(deviceId, DEVICE_ID_NULL);
270 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700271 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700272 }
273
274 @Override
tomff7eb7c2014-09-08 12:49:03 -0700275 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900276 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900277
tomff7eb7c2014-09-08 12:49:03 -0700278 checkNotNull(deviceId, DEVICE_ID_NULL);
279 return store.isAvailable(deviceId);
280 }
281
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800282 @Override
283 public String localStatus(DeviceId deviceId) {
284 LocalStatus ls = deviceLocalStatus.get(deviceId);
285 if (ls == null) {
286 return "No Record";
287 }
288 String timeAgo = Tools.timeAgo(ls.dateTime.getMillis());
289 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
290 }
291
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700292 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700293 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800294 if (deviceId == null) {
295 return false;
296 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700297 DeviceProvider provider = getProvider(deviceId);
298 if (provider != null) {
299 return provider.isReachable(deviceId);
300 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800301 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700302 return false;
303 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700304 }
305
tome5ec3fd2014-09-04 15:18:06 -0700306 @Override
307 public void removeDevice(DeviceId deviceId) {
308 checkNotNull(deviceId, DEVICE_ID_NULL);
309 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700310 if (event != null) {
311 log.info("Device {} administratively removed", deviceId);
312 post(event);
313 }
tome5ec3fd2014-09-04 15:18:06 -0700314 }
315
tom7869ad92014-09-09 14:32:08 -0700316 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700317 public void changePortState(DeviceId deviceId, PortNumber portNumber,
318 boolean enable) {
319 checkNotNull(deviceId, DEVICE_ID_NULL);
320 checkNotNull(deviceId, PORT_NUMBER_NULL);
321 DeviceProvider provider = getProvider(deviceId);
322 if (provider != null) {
323 log.warn("Port {} on device {} being administratively brought {}",
324 portNumber, deviceId,
325 (enable) ? "UP" : "DOWN");
326 provider.changePortState(deviceId, portNumber, enable);
327 } else {
328 log.warn("Provider not found for {}", deviceId);
329 }
330 }
331
332 @Override
samuele1fa7322015-07-14 16:35:16 +0800333 protected DeviceProviderService createProviderService(
334 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700335 return new InternalDeviceProviderService(provider);
336 }
337
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800338 /**
339 * Checks if all the reachable devices have a valid mastership role.
340 */
341 private void mastershipCheck() {
342 log.debug("Checking mastership");
343 for (Device device : getDevices()) {
344 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700345 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
346 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800347 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700348 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700349 // can't be master if device is not reachable
350 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700351 if (myRole == MASTER) {
352 post(store.markOffline(deviceId));
353 }
helenyrwufd296b62016-06-22 17:43:02 -0700354 //relinquish master role and ability to be backup.
355 mastershipService.relinquishMastership(deviceId).get();
356 } catch (InterruptedException e) {
357 log.warn("Interrupted while reliquishing role for {}", deviceId);
358 Thread.currentThread().interrupt();
359 } catch (ExecutionException e) {
360 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
361 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530362 } else {
363 // check if the device has master, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530364 // only the nodes which has mastership role can mark any device offline.
365 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
366 roleFuture.thenAccept(role -> {
367 MastershipTerm term = termService.getMastershipTerm(deviceId);
368 if (term != null && localNodeId.equals(term.master())) {
369 log.info("Marking unreachable device {} offline", deviceId);
370 post(store.markOffline(deviceId));
371 } else {
372 log.info("Failed marking {} offline. {}", deviceId, role);
373 }
374 mastershipService.relinquishMastership(deviceId);
375 });
helenyrwufd296b62016-06-22 17:43:02 -0700376 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800377 continue;
378 }
379
Ray Milkeyc7104672016-08-31 12:04:34 -0700380 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800381 continue;
382 }
383
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700384 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800385
386 // isReachable but was not MASTER or STANDBY, get a role and apply
387 // Note: NONE triggers request to MastershipService
388 reassertRole(deviceId, NONE);
389 }
390 }
391
tomd3097b02014-08-26 10:40:29 -0700392 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700393 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700394 extends AbstractProviderService<DeviceProvider>
395 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700396
tomcfde0622014-09-09 11:02:42 -0700397 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700398 super(provider);
399 }
400
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700401 /**
402 * Apply role in reaction to provider event.
403 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700404 * @param deviceId device identifier
405 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700406 * @return true if the request was sent to provider
407 */
408 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
409
410 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800411 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700412 return true;
413 }
414
415 DeviceProvider provider = provider();
416 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700417 log.warn("Provider for {} was not found. Cannot apply role {}",
418 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700419 return false;
420 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700421 provider.roleChanged(deviceId, newRole);
422 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700423 return true;
424 }
425
tomd3097b02014-08-26 10:40:29 -0700426 @Override
alshabibb7b40632014-09-28 21:30:00 -0700427 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700428 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700429 checkNotNull(deviceId, DEVICE_ID_NULL);
430 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700431 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700432
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800433 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
434
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700435 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
436 if (!isAllowed(cfg)) {
437 log.warn("Device {} is not allowed", deviceId);
438 return;
439 }
440 // Generate updated description and establish my Role
441 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700442 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
443 .thenAccept(role -> {
444 log.info("Local role is {} for {}", role, deviceId);
445 applyRole(deviceId, role);
446 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700447
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700448 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
449 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700450 if (deviceDescription.isDefaultAvailable()) {
451 log.info("Device {} connected", deviceId);
452 } else {
453 log.info("Device {} registered", deviceId);
454 }
tom80c0e5e2014-09-08 18:08:58 -0700455 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700456 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700457 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700458 }
tomd3097b02014-08-26 10:40:29 -0700459 }
460
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700461 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
462 if (desc.isEnabled() != enabled) {
463 return new DefaultPortDescription(desc.portNumber(),
464 enabled,
465 desc.type(),
466 desc.portSpeed(),
467 desc.annotations());
468 }
469 return desc;
470 }
471
tomd3097b02014-08-26 10:40:29 -0700472 @Override
473 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700474 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700475 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800476 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700477 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700478
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700479 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
480 .map(desc -> ensurePortEnabledState(desc, false))
481 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300482
alshabibafc514a2014-12-01 14:44:05 -0800483 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700484 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700485 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700486 post(store.markOffline(deviceId));
487 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700488 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700489 log.warn("Failed to mark {} offline", deviceId);
490 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800491 // but if I was the last STANDBY connection, etc. and no one else
492 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700493 // temporarily request for Master Role and mark offline.
494
samuele1fa7322015-07-14 16:35:16 +0800495 //there are times when this node will correctly have mastership, BUT
496 //that isn't reflected in the ClockManager before the device disconnects.
497 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700498
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700499 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800500 // Consider revising store API to handle this scenario.
501 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700502 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800503 MastershipTerm term = termService.getMastershipTerm(deviceId);
504 // TODO: Move this type of check inside device clock manager, etc.
505 if (term != null && localNodeId.equals(term.master())) {
506 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800507 post(store.markOffline(deviceId));
508 } else {
509 log.info("Failed again marking {} offline. {}", deviceId, role);
510 }
511 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700512 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700513 try {
samuele1fa7322015-07-14 16:35:16 +0800514 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700515 mastershipService.relinquishMastership(deviceId).get();
516 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800517 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700518 Thread.currentThread().interrupt();
519 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800520 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700521 }
tom0efbb1d2014-09-09 11:54:28 -0700522 }
tomd3097b02014-08-26 10:40:29 -0700523 }
524
525 @Override
alshabibb7b40632014-09-28 21:30:00 -0700526 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700527 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700528 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700529 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700530 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700531 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700532 // Never been a master for this device
533 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800534 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700535 return;
536 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700537 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700538 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700539 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700540 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800541 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800542 if (events != null) {
543 for (DeviceEvent event : events) {
544 post(event);
545 }
tom32f66842014-08-27 19:27:47 -0700546 }
tomd3097b02014-08-26 10:40:29 -0700547 }
548
549 @Override
alshabibb7b40632014-09-28 21:30:00 -0700550 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700551 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700552 checkNotNull(deviceId, DEVICE_ID_NULL);
553 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700554 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700555
Madan Jampani565a66a2015-07-25 17:01:13 -0700556 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700557 // Never been a master for this device
558 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700559 log.trace("Ignoring {} port update on standby node. {}", deviceId,
560 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700561 return;
562 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700563 Device device = getDevice(deviceId);
564 if (device == null) {
565 log.trace("Device not found: {}", deviceId);
566 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200567 if ((Device.Type.ROADM.equals(device.type())) ||
568 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700569 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700570 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
571 deviceId,
572 portDescription.portNumber());
573 portDescription = ensurePortEnabledState(storedPortDesc,
574 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300575 }
576
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700577 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800578 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700579 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700580 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700581 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700582 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700583 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700584 }
tomd3097b02014-08-26 10:40:29 -0700585 }
tom3f2bbd72014-09-24 12:07:58 -0700586
587 @Override
samuele1fa7322015-07-14 16:35:16 +0800588 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700589 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700590 // Several things can happen here:
591 // 1. request and response match
592 // 2. request and response don't match
593 // 3. MastershipRole and requested match (and 1 or 2 are true)
594 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
595 //
596 // 2, 4, and 3 with case 2 are failure modes.
597
tom3f2bbd72014-09-24 12:07:58 -0700598 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700599
Madan Jampanif2af7712015-05-29 18:43:52 -0700600 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700601 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700602
603 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800604 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530605 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700606 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700607 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700608 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700609
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700610 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800611 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700612 return;
613 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800614 log.warn("Role mismatch on {}. set to {}, but store demands {}",
615 deviceId, response, mastershipService.getLocalRole(deviceId));
616 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700617 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800618 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800619 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700620 }
621 } else {
622 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800623 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700624 if (response == MastershipRole.MASTER) {
625 mastershipService.relinquishMastership(deviceId);
626 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800627 //final Device device = getDevice(deviceId);
628 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700629 }
630 }
tom3f2bbd72014-09-24 12:07:58 -0700631 }
sangho538108b2015-04-08 14:29:20 -0700632
633 @Override
samuele1fa7322015-07-14 16:35:16 +0800634 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700635 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700636 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700637 checkValidity();
638
samuele1fa7322015-07-14 16:35:16 +0800639 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
640 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700641 post(event);
642 }
tomd3097b02014-08-26 10:40:29 -0700643 }
tom32f66842014-08-27 19:27:47 -0700644
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700645 // by default allowed, otherwise check flag
646 private boolean isAllowed(BasicDeviceConfig cfg) {
647 return (cfg == null || cfg.isAllowed());
648 }
649
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800650 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700651
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800652 /**
653 * Apply role to device and send probe if MASTER.
654 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700655 * @param deviceId device identifier
656 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800657 * @return true if the request was sent to provider
658 */
659 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
660 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800661 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700662 return true;
663 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700664
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800665 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800666 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800667 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800668 return false;
669 }
670 provider.roleChanged(deviceId, newRole);
671
672 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800673 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800674 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800675 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800676 }
677 return true;
678 }
679
680 /**
681 * Reaasert role for specified device connected to this node.
682 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700683 * @param did device identifier
684 * @param nextRole role to apply. If NONE is specified,
685 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800686 */
samuele1fa7322015-07-14 16:35:16 +0800687 private void reassertRole(final DeviceId did,
688 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800689
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800690 MastershipRole myNextRole = nextRole;
691 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800692 try {
693 mastershipService.requestRoleFor(did).get();
694 MastershipTerm term = termService.getMastershipTerm(did);
695 if (term != null && localNodeId.equals(term.master())) {
696 myNextRole = MASTER;
697 } else {
698 myNextRole = STANDBY;
699 }
700 } catch (InterruptedException e) {
701 Thread.currentThread().interrupt();
702 log.error("Interrupted waiting for Mastership", e);
703 } catch (ExecutionException e) {
704 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800705 }
706 }
707
708 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700709 case MASTER:
710 final Device device = getDevice(did);
711 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700712 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700713 }
714 // TODO: should apply role only if there is mismatch
715 log.debug("Applying role {} to {}", myNextRole, did);
716 if (!applyRoleAndProbe(did, MASTER)) {
717 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
718 // immediately failed to apply role
719 mastershipService.relinquishMastership(did);
720 // FIXME disconnect?
721 }
722 break;
723 case STANDBY:
724 log.debug("Applying role {} to {}", myNextRole, did);
725 if (!applyRoleAndProbe(did, STANDBY)) {
726 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
727 // immediately failed to apply role
728 mastershipService.relinquishMastership(did);
729 // FIXME disconnect?
730 }
731 break;
732 case NONE:
733 default:
734 // should never reach here
735 log.error("You didn't see anything. I did not exist.");
736 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800737 }
738 }
739
Madan Jampani328371d2015-05-29 14:06:27 -0700740 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700741 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700742 // Don't care if backup list changed.
743 return;
744 }
Madan Jampani328371d2015-05-29 14:06:27 -0700745 final DeviceId did = event.subject();
746
747 // myRole suggested by MastershipService
748 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700749 if (event.type() == MastershipEvent.Type.SUSPENDED) {
750 myNextRole = NONE; // FIXME STANDBY OR NONE?
751 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700752 // confirm latest info
753 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800754 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700755 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700756 myNextRole = MASTER;
757 } else {
758 myNextRole = STANDBY;
759 }
760 } else if (event.roleInfo().backups().contains(localNodeId)) {
761 myNextRole = STANDBY;
762 } else {
763 myNextRole = NONE;
764 }
765
Madan Jampani328371d2015-05-29 14:06:27 -0700766 final boolean isReachable = isReachable(did);
767 if (!isReachable) {
768 // device is not connected to this node
769 if (myNextRole != NONE) {
770 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700771 + "but this node cannot reach the device. "
772 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800773 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700774 mastershipService.relinquishMastership(did);
775 }
776 return;
777 }
778
779 // device is connected to this node:
780 if (store.getDevice(did) != null) {
781 reassertRole(did, myNextRole);
782 } else {
783 log.debug("Device is not yet/no longer in the store: {}", did);
784 }
785 }
786
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800787 // Intercepts mastership events
788 private class InternalMastershipListener implements MastershipListener {
789
tomb41d1ac2014-09-24 01:51:24 -0700790 @Override
791 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800792 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700793 try {
794 handleMastershipEvent(event);
795 } catch (Exception e) {
796 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700797 }
Madan Jampani328371d2015-05-29 14:06:27 -0700798 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700799 }
tomb41d1ac2014-09-24 01:51:24 -0700800 }
tomf80c9722014-09-24 14:49:18 -0700801
802 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700803 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700804 @Override
805 public void notify(DeviceEvent event) {
806 post(event);
807 }
808 }
samuel738dfaf2015-07-11 11:08:57 +0800809
810 @Override
811 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900812 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800813 Set<Device> results = new HashSet<>();
814 Iterable<Device> devices = store.getDevices();
815 if (devices != null) {
816 devices.forEach(d -> {
817 if (type.equals(d.type())) {
818 results.add(d);
819 }
820 });
821 }
822 return results;
823 }
824
825 @Override
826 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900827 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800828 Set<Device> results = new HashSet<>();
829 Iterable<Device> availableDevices = store.getAvailableDevices();
830 if (availableDevices != null) {
831 availableDevices.forEach(d -> {
832 if (type.equals(d.type())) {
833 results.add(d);
834 }
835 });
836 }
837 return results;
838 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700839
840 private class InternalNetworkConfigListener implements NetworkConfigListener {
841 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700842 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700843 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
844 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
845 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700846 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700847 }
848
849 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700850 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700851 DeviceEvent de = null;
852 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800853 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700854 DeviceId did = (DeviceId) event.subject();
855 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700856
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700857 if (!isAllowed(cfg)) {
858 kickOutBadDevice(did);
859 } else {
860 Device dev = getDevice(did);
861 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
862 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800863 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700864 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
865 }
866 }
867 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700868 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700869 ConnectPoint cpt = (ConnectPoint) event.subject();
870 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700871
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700872 // Note: assuming PortOperator can modify existing port,
873 // but cannot add new port purely from Config.
874 de = Optional.ofNullable(getProvider(did))
875 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
876 .map(desc -> applyAllPortOps(cpt, desc))
877 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
878 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700879 }
880
881 if (de != null) {
882 post(de);
883 }
884 }
885
886 // checks if the specified device is allowed by the BasicDeviceConfig
887 // and if not, removes it
888 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700889 Device badDevice = getDevice(deviceId);
890 if (badDevice != null) {
891 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700892 }
893 }
894 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700895
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700896 @Override
897 @SafeVarargs
898 public final void registerPortConfigOperator(PortConfigOperator portOp,
899 Class<? extends Config<ConnectPoint>>...configs) {
900 checkNotNull(portOp);
901
902 portOp.bindService(networkConfigService);
903
904 // update both portOpsIndex and portOps
905 synchronized (portOpsIndex) {
906 for (Class<? extends Config<ConnectPoint>> config : configs) {
907 portOpsIndex.put(config, portOp);
908 }
909
910 portOps.add(portOp);
911 }
912
913 // TODO: Should we be applying to all existing Ports?
914 Tools.stream(store.getAvailableDevices())
915 .map(Device::id)
916 .filter(mastershipService::isLocalMaster)
917 // for each locally managed Device, update all port descriptions
918 .map(did -> {
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800919 ProviderId pid = Optional.ofNullable(getProvider(did))
920 .map(Provider::id)
921 .orElse(null);
922 if (pid == null) {
923 log.warn("Provider not found for {}", did);
924 return ImmutableList.<DeviceEvent>of();
925 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700926 List<PortDescription> pds
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800927 = store.getPortDescriptions(pid, did)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700928 .map(pdesc -> applyAllPortOps(did, pdesc))
929 .collect(Collectors.toList());
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800930 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700931 })
932 // ..and port port update event if necessary
933 .forEach(evts -> evts.forEach(this::post));
934 }
935
936 @Override
937 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
938 checkNotNull(portOp);
939
940
941 // remove all portOp
942 synchronized (portOpsIndex) {
943 portOps.remove(portOp);
944
945 // had to do this since COWArrayList iterator doesn't support remove
946 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
947 }
948
949 }
950
951 /**
952 * Merges the appropriate PortConfig with the description.
953 *
954 * @param did ID of the Device where the port is attached
955 * @param desc {@link PortDescription}
956 * @return merged {@link PortDescription}
957 */
958 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
959 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
960 }
961
962 /**
963 * Merges the appropriate PortConfig with the description.
964 *
965 * @param cpt ConnectPoint where the port is attached
966 * @param desc {@link PortDescription}
967 * @return merged {@link PortDescription}
968 */
969 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
970 PortDescription work = desc;
971 for (PortConfigOperator portOp : portOps) {
972 work = portOp.combine(cpt, work);
973 }
974 return work;
975 }
976
tomd3097b02014-08-26 10:40:29 -0700977}