blob: 6fe1ca6139c7941ef4d53d44ec174bfe7be048e0 [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;
21import java.util.Objects;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070022import java.util.Optional;
Yafit Hadara9a73de2015-09-06 13:52:52 +030023import java.util.Set;
24import java.util.concurrent.CompletableFuture;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070025import java.util.concurrent.ConcurrentHashMap;
26import java.util.concurrent.CopyOnWriteArrayList;
Yafit Hadara9a73de2015-09-06 13:52:52 +030027import java.util.concurrent.ExecutionException;
28import java.util.concurrent.ScheduledExecutorService;
29import java.util.concurrent.TimeUnit;
30import java.util.stream.Collectors;
tomd3097b02014-08-26 10:40:29 -070031import org.apache.felix.scr.annotations.Activate;
32import org.apache.felix.scr.annotations.Component;
33import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070034import org.apache.felix.scr.annotations.Reference;
35import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070036import org.apache.felix.scr.annotations.Service;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070037import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.cluster.ClusterService;
39import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.mastership.MastershipEvent;
41import org.onosproject.mastership.MastershipListener;
42import org.onosproject.mastership.MastershipService;
43import org.onosproject.mastership.MastershipTerm;
44import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070045import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080047import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.DeviceId;
49import org.onosproject.net.MastershipRole;
50import org.onosproject.net.Port;
51import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070052import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030053import org.onosproject.net.config.NetworkConfigEvent;
54import org.onosproject.net.config.NetworkConfigListener;
55import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070056import org.onosproject.net.config.PortConfigOperator;
57import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030058import org.onosproject.net.config.basics.BasicDeviceConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080059import org.onosproject.net.device.DefaultPortDescription;
60import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.device.DeviceDescription;
62import org.onosproject.net.device.DeviceEvent;
63import org.onosproject.net.device.DeviceListener;
64import org.onosproject.net.device.DeviceProvider;
65import org.onosproject.net.device.DeviceProviderRegistry;
66import org.onosproject.net.device.DeviceProviderService;
67import org.onosproject.net.device.DeviceService;
68import org.onosproject.net.device.DeviceStore;
69import org.onosproject.net.device.DeviceStoreDelegate;
70import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070071import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030072import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080074import org.onosproject.net.provider.Provider;
75import org.onosproject.net.provider.ProviderId;
tomd3097b02014-08-26 10:40:29 -070076import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070077
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080078import com.google.common.collect.ImmutableList;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070079import com.google.common.collect.Multimap;
Yafit Hadara9a73de2015-09-06 13:52:52 +030080import com.google.common.util.concurrent.Futures;
Jonathan Hart2f669362015-02-11 16:19:20 -080081
Ray Milkey9ef22232016-07-14 12:42:37 -070082import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070083import static com.google.common.collect.Multimaps.newListMultimap;
84import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Ray Milkey9ef22232016-07-14 12:42:37 -070085import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
86import static org.onlab.util.Tools.groupedThreads;
87import static org.onosproject.net.MastershipRole.MASTER;
88import static org.onosproject.net.MastershipRole.NONE;
89import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -070090import static org.onosproject.security.AppGuard.checkPermission;
91import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
92import static org.slf4j.LoggerFactory.getLogger;
93
tomd3097b02014-08-26 10:40:29 -070094/**
tome4729872014-09-23 00:37:37 -070095 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070096 */
97@Component(immediate = true)
98@Service
tom41a2c5f2014-09-19 09:20:35 -070099public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700100 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700101 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700102
tome5ec3fd2014-09-04 15:18:06 -0700103 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
104 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
105 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
106 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700107 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
tomd3097b02014-08-26 10:40:29 -0700108
tom5f38b3a2014-08-27 23:50:54 -0700109 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700110
alshabib339a3d92014-09-26 17:54:32 -0700111 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700112
tomc78acee2014-09-24 15:16:55 -0700113 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700114 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700115
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800116 private ScheduledExecutorService backgroundService;
117
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700118 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
119
tom41a2c5f2014-09-19 09:20:35 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
121 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700122
tom5f38b3a2014-08-27 23:50:54 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700124 protected ClusterService clusterService;
125
126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700127 protected MastershipService mastershipService;
128
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700130 protected MastershipTermService termService;
131
Madan Jampani61056bc2014-09-27 09:07:26 -0700132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700133 protected NetworkConfigService networkConfigService;
134
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700135
136 /**
137 * List of all registered PortConfigOperator.
138 */
139 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
140
141 /**
142 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
143 */
144 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
145 = synchronizedListMultimap(
146 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
147
148
tomd3097b02014-08-26 10:40:29 -0700149 @Activate
150 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800151 backgroundService = newSingleThreadScheduledExecutor(
152 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700153 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800154
tomf80c9722014-09-24 14:49:18 -0700155 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700156 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700157 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700158 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800159
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700160 backgroundService.scheduleWithFixedDelay(() -> {
161 try {
162 mastershipCheck();
163 } catch (Exception e) {
164 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800165 }
166 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700167 log.info("Started");
168 }
169
170 @Deactivate
171 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800172 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700173 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700174 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700175 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700176 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700177 log.info("Stopped");
178 }
179
180 @Override
tomad2d2092014-09-06 23:24:20 -0700181 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900182 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700183 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700184 }
185
186 @Override
tom32f66842014-08-27 19:27:47 -0700187 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900188 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700189 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700190 }
191
tom32f66842014-08-27 19:27:47 -0700192 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800193 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900194 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800195 return store.getAvailableDevices();
196 }
197
198 @Override
tom32f66842014-08-27 19:27:47 -0700199 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900200 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700201 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700202 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700203 }
204
205 @Override
tomad2d2092014-09-06 23:24:20 -0700206 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900207 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700208 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700209 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700210 }
211
212 @Override
tom32f66842014-08-27 19:27:47 -0700213 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900214 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700215 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700216 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700217 }
218
219 @Override
sangho538108b2015-04-08 14:29:20 -0700220 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900221 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700222 checkNotNull(deviceId, DEVICE_ID_NULL);
223 return store.getPortStatistics(deviceId);
224 }
225
226 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200227 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900228 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200229 checkNotNull(deviceId, DEVICE_ID_NULL);
230 return store.getPortDeltaStatistics(deviceId);
231 }
232
233 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530234 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
235 checkPermission(DEVICE_READ);
236 checkNotNull(deviceId, DEVICE_ID_NULL);
237 checkNotNull(portNumber, PORT_NUMBER_NULL);
238 return store.getStatisticsForPort(deviceId, portNumber);
239 }
240
241 @Override
242 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
243 checkPermission(DEVICE_READ);
244 checkNotNull(deviceId, DEVICE_ID_NULL);
245 checkNotNull(portNumber, PORT_NUMBER_NULL);
246 return store.getDeltaStatisticsForPort(deviceId, portNumber);
247 }
248
249 @Override
tom32f66842014-08-27 19:27:47 -0700250 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900251 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700252 checkNotNull(deviceId, DEVICE_ID_NULL);
253 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700254 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700255 }
256
257 @Override
tomff7eb7c2014-09-08 12:49:03 -0700258 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900260
tomff7eb7c2014-09-08 12:49:03 -0700261 checkNotNull(deviceId, DEVICE_ID_NULL);
262 return store.isAvailable(deviceId);
263 }
264
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700265 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700266 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800267 if (deviceId == null) {
268 return false;
269 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700270 DeviceProvider provider = getProvider(deviceId);
271 if (provider != null) {
272 return provider.isReachable(deviceId);
273 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800274 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700275 return false;
276 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700277 }
278
tome5ec3fd2014-09-04 15:18:06 -0700279 @Override
280 public void removeDevice(DeviceId deviceId) {
281 checkNotNull(deviceId, DEVICE_ID_NULL);
282 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700283 if (event != null) {
284 log.info("Device {} administratively removed", deviceId);
285 post(event);
286 }
tome5ec3fd2014-09-04 15:18:06 -0700287 }
288
tom7869ad92014-09-09 14:32:08 -0700289 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700290 public void changePortState(DeviceId deviceId, PortNumber portNumber,
291 boolean enable) {
292 checkNotNull(deviceId, DEVICE_ID_NULL);
293 checkNotNull(deviceId, PORT_NUMBER_NULL);
294 DeviceProvider provider = getProvider(deviceId);
295 if (provider != null) {
296 log.warn("Port {} on device {} being administratively brought {}",
297 portNumber, deviceId,
298 (enable) ? "UP" : "DOWN");
299 provider.changePortState(deviceId, portNumber, enable);
300 } else {
301 log.warn("Provider not found for {}", deviceId);
302 }
303 }
304
305 @Override
samuele1fa7322015-07-14 16:35:16 +0800306 protected DeviceProviderService createProviderService(
307 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700308 return new InternalDeviceProviderService(provider);
309 }
310
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800311 /**
312 * Checks if all the reachable devices have a valid mastership role.
313 */
314 private void mastershipCheck() {
315 log.debug("Checking mastership");
316 for (Device device : getDevices()) {
317 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700318 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
319 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800320 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700321 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700322 // can't be master if device is not reachable
323 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700324 if (myRole == MASTER) {
325 post(store.markOffline(deviceId));
326 }
helenyrwufd296b62016-06-22 17:43:02 -0700327 //relinquish master role and ability to be backup.
328 mastershipService.relinquishMastership(deviceId).get();
329 } catch (InterruptedException e) {
330 log.warn("Interrupted while reliquishing role for {}", deviceId);
331 Thread.currentThread().interrupt();
332 } catch (ExecutionException e) {
333 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
334 }
335 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800336 continue;
337 }
338
Ray Milkeyc7104672016-08-31 12:04:34 -0700339 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800340 continue;
341 }
342
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700343 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800344
345 // isReachable but was not MASTER or STANDBY, get a role and apply
346 // Note: NONE triggers request to MastershipService
347 reassertRole(deviceId, NONE);
348 }
349 }
350
tomd3097b02014-08-26 10:40:29 -0700351 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700352 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700353 extends AbstractProviderService<DeviceProvider>
354 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700355
tomcfde0622014-09-09 11:02:42 -0700356 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700357 super(provider);
358 }
359
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700360 /**
361 * Apply role in reaction to provider event.
362 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700363 * @param deviceId device identifier
364 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700365 * @return true if the request was sent to provider
366 */
367 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
368
369 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800370 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700371 return true;
372 }
373
374 DeviceProvider provider = provider();
375 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700376 log.warn("Provider for {} was not found. Cannot apply role {}",
377 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700378 return false;
379 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700380 provider.roleChanged(deviceId, newRole);
381 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700382 return true;
383 }
384
tomd3097b02014-08-26 10:40:29 -0700385 @Override
alshabibb7b40632014-09-28 21:30:00 -0700386 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700387 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700388 checkNotNull(deviceId, DEVICE_ID_NULL);
389 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700390 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700391
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700392 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
393 if (!isAllowed(cfg)) {
394 log.warn("Device {} is not allowed", deviceId);
395 return;
396 }
397 // Generate updated description and establish my Role
398 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700399 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
400 .thenAccept(role -> {
401 log.info("Local role is {} for {}", role, deviceId);
402 applyRole(deviceId, role);
403 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700404
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700405 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
406 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700407 if (deviceDescription.isDefaultAvailable()) {
408 log.info("Device {} connected", deviceId);
409 } else {
410 log.info("Device {} registered", deviceId);
411 }
tom80c0e5e2014-09-08 18:08:58 -0700412 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700413 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700414 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700415 }
tomd3097b02014-08-26 10:40:29 -0700416 }
417
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700418 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
419 if (desc.isEnabled() != enabled) {
420 return new DefaultPortDescription(desc.portNumber(),
421 enabled,
422 desc.type(),
423 desc.portSpeed(),
424 desc.annotations());
425 }
426 return desc;
427 }
428
tomd3097b02014-08-26 10:40:29 -0700429 @Override
430 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700431 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700432 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700433
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700434 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700435
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700436 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
437 .map(desc -> ensurePortEnabledState(desc, false))
438 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300439
alshabibafc514a2014-12-01 14:44:05 -0800440 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700441 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700442 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700443 post(store.markOffline(deviceId));
444 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700445 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700446 log.warn("Failed to mark {} offline", deviceId);
447 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800448 // but if I was the last STANDBY connection, etc. and no one else
449 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700450 // temporarily request for Master Role and mark offline.
451
samuele1fa7322015-07-14 16:35:16 +0800452 //there are times when this node will correctly have mastership, BUT
453 //that isn't reflected in the ClockManager before the device disconnects.
454 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700455
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700456 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800457 // Consider revising store API to handle this scenario.
458 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700459 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800460 MastershipTerm term = termService.getMastershipTerm(deviceId);
461 // TODO: Move this type of check inside device clock manager, etc.
462 if (term != null && localNodeId.equals(term.master())) {
463 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800464 post(store.markOffline(deviceId));
465 } else {
466 log.info("Failed again marking {} offline. {}", deviceId, role);
467 }
468 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700469 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700470 try {
samuele1fa7322015-07-14 16:35:16 +0800471 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700472 mastershipService.relinquishMastership(deviceId).get();
473 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800474 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700475 Thread.currentThread().interrupt();
476 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800477 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700478 }
tom0efbb1d2014-09-09 11:54:28 -0700479 }
tomd3097b02014-08-26 10:40:29 -0700480 }
481
482 @Override
alshabibb7b40632014-09-28 21:30:00 -0700483 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700484 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700485 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700486 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700487 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700488 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700489 // Never been a master for this device
490 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800491 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700492 return;
493 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700494 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700495 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700496 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700497 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800498 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800499 if (events != null) {
500 for (DeviceEvent event : events) {
501 post(event);
502 }
tom32f66842014-08-27 19:27:47 -0700503 }
tomd3097b02014-08-26 10:40:29 -0700504 }
505
506 @Override
alshabibb7b40632014-09-28 21:30:00 -0700507 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700508 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700509 checkNotNull(deviceId, DEVICE_ID_NULL);
510 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700511 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700512
Madan Jampani565a66a2015-07-25 17:01:13 -0700513 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700514 // Never been a master for this device
515 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700516 log.trace("Ignoring {} port update on standby node. {}", deviceId,
517 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700518 return;
519 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700520 Device device = getDevice(deviceId);
521 if (device == null) {
522 log.trace("Device not found: {}", deviceId);
523 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200524 if ((Device.Type.ROADM.equals(device.type())) ||
525 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700526 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700527 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
528 deviceId,
529 portDescription.portNumber());
530 portDescription = ensurePortEnabledState(storedPortDesc,
531 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300532 }
533
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700534 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800535 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700536 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700537 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700538 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700539 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700540 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700541 }
tomd3097b02014-08-26 10:40:29 -0700542 }
tom3f2bbd72014-09-24 12:07:58 -0700543
544 @Override
samuele1fa7322015-07-14 16:35:16 +0800545 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700546 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700547 // Several things can happen here:
548 // 1. request and response match
549 // 2. request and response don't match
550 // 3. MastershipRole and requested match (and 1 or 2 are true)
551 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
552 //
553 // 2, 4, and 3 with case 2 are failure modes.
554
tom3f2bbd72014-09-24 12:07:58 -0700555 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700556
Madan Jampanif2af7712015-05-29 18:43:52 -0700557 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700558 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700559
560 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800561 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530562 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700563 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700564 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700565 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700566
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700567 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800568 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700569 return;
570 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800571 log.warn("Role mismatch on {}. set to {}, but store demands {}",
572 deviceId, response, mastershipService.getLocalRole(deviceId));
573 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700574 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800575 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800576 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700577 }
578 } else {
579 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800580 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700581 if (response == MastershipRole.MASTER) {
582 mastershipService.relinquishMastership(deviceId);
583 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800584 //final Device device = getDevice(deviceId);
585 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700586 }
587 }
tom3f2bbd72014-09-24 12:07:58 -0700588 }
sangho538108b2015-04-08 14:29:20 -0700589
590 @Override
samuele1fa7322015-07-14 16:35:16 +0800591 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700592 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700593 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700594 checkValidity();
595
samuele1fa7322015-07-14 16:35:16 +0800596 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
597 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700598 post(event);
599 }
tomd3097b02014-08-26 10:40:29 -0700600 }
tom32f66842014-08-27 19:27:47 -0700601
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700602 // by default allowed, otherwise check flag
603 private boolean isAllowed(BasicDeviceConfig cfg) {
604 return (cfg == null || cfg.isAllowed());
605 }
606
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800607 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700608
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800609 /**
610 * Apply role to device and send probe if MASTER.
611 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700612 * @param deviceId device identifier
613 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800614 * @return true if the request was sent to provider
615 */
616 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
617 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800618 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700619 return true;
620 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700621
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800622 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800623 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800624 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800625 return false;
626 }
627 provider.roleChanged(deviceId, newRole);
628
629 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800630 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800631 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800632 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800633 }
634 return true;
635 }
636
637 /**
638 * Reaasert role for specified device connected to this node.
639 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700640 * @param did device identifier
641 * @param nextRole role to apply. If NONE is specified,
642 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800643 */
samuele1fa7322015-07-14 16:35:16 +0800644 private void reassertRole(final DeviceId did,
645 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800646
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800647 MastershipRole myNextRole = nextRole;
648 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800649 try {
650 mastershipService.requestRoleFor(did).get();
651 MastershipTerm term = termService.getMastershipTerm(did);
652 if (term != null && localNodeId.equals(term.master())) {
653 myNextRole = MASTER;
654 } else {
655 myNextRole = STANDBY;
656 }
657 } catch (InterruptedException e) {
658 Thread.currentThread().interrupt();
659 log.error("Interrupted waiting for Mastership", e);
660 } catch (ExecutionException e) {
661 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800662 }
663 }
664
665 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700666 case MASTER:
667 final Device device = getDevice(did);
668 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700669 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700670 }
671 // TODO: should apply role only if there is mismatch
672 log.debug("Applying role {} to {}", myNextRole, did);
673 if (!applyRoleAndProbe(did, MASTER)) {
674 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
675 // immediately failed to apply role
676 mastershipService.relinquishMastership(did);
677 // FIXME disconnect?
678 }
679 break;
680 case STANDBY:
681 log.debug("Applying role {} to {}", myNextRole, did);
682 if (!applyRoleAndProbe(did, STANDBY)) {
683 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
684 // immediately failed to apply role
685 mastershipService.relinquishMastership(did);
686 // FIXME disconnect?
687 }
688 break;
689 case NONE:
690 default:
691 // should never reach here
692 log.error("You didn't see anything. I did not exist.");
693 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800694 }
695 }
696
Madan Jampani328371d2015-05-29 14:06:27 -0700697 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700698 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700699 // Don't care if backup list changed.
700 return;
701 }
Madan Jampani328371d2015-05-29 14:06:27 -0700702 final DeviceId did = event.subject();
703
704 // myRole suggested by MastershipService
705 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700706 if (event.type() == MastershipEvent.Type.SUSPENDED) {
707 myNextRole = NONE; // FIXME STANDBY OR NONE?
708 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700709 // confirm latest info
710 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800711 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700712 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700713 myNextRole = MASTER;
714 } else {
715 myNextRole = STANDBY;
716 }
717 } else if (event.roleInfo().backups().contains(localNodeId)) {
718 myNextRole = STANDBY;
719 } else {
720 myNextRole = NONE;
721 }
722
Madan Jampani328371d2015-05-29 14:06:27 -0700723 final boolean isReachable = isReachable(did);
724 if (!isReachable) {
725 // device is not connected to this node
726 if (myNextRole != NONE) {
727 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700728 + "but this node cannot reach the device. "
729 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800730 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700731 mastershipService.relinquishMastership(did);
732 }
733 return;
734 }
735
736 // device is connected to this node:
737 if (store.getDevice(did) != null) {
738 reassertRole(did, myNextRole);
739 } else {
740 log.debug("Device is not yet/no longer in the store: {}", did);
741 }
742 }
743
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800744 // Intercepts mastership events
745 private class InternalMastershipListener implements MastershipListener {
746
tomb41d1ac2014-09-24 01:51:24 -0700747 @Override
748 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800749 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700750 try {
751 handleMastershipEvent(event);
752 } catch (Exception e) {
753 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700754 }
Madan Jampani328371d2015-05-29 14:06:27 -0700755 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700756 }
tomb41d1ac2014-09-24 01:51:24 -0700757 }
tomf80c9722014-09-24 14:49:18 -0700758
759 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700760 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700761 @Override
762 public void notify(DeviceEvent event) {
763 post(event);
764 }
765 }
samuel738dfaf2015-07-11 11:08:57 +0800766
767 @Override
768 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900769 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800770 Set<Device> results = new HashSet<>();
771 Iterable<Device> devices = store.getDevices();
772 if (devices != null) {
773 devices.forEach(d -> {
774 if (type.equals(d.type())) {
775 results.add(d);
776 }
777 });
778 }
779 return results;
780 }
781
782 @Override
783 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900784 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800785 Set<Device> results = new HashSet<>();
786 Iterable<Device> availableDevices = store.getAvailableDevices();
787 if (availableDevices != null) {
788 availableDevices.forEach(d -> {
789 if (type.equals(d.type())) {
790 results.add(d);
791 }
792 });
793 }
794 return results;
795 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700796
797 private class InternalNetworkConfigListener implements NetworkConfigListener {
798 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700799 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700800 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
801 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
802 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700803 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700804 }
805
806 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700807 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700808 DeviceEvent de = null;
809 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800810 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700811 DeviceId did = (DeviceId) event.subject();
812 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700813
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700814 if (!isAllowed(cfg)) {
815 kickOutBadDevice(did);
816 } else {
817 Device dev = getDevice(did);
818 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
819 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800820 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700821 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
822 }
823 }
824 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700825 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700826 ConnectPoint cpt = (ConnectPoint) event.subject();
827 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700828
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700829 // Note: assuming PortOperator can modify existing port,
830 // but cannot add new port purely from Config.
831 de = Optional.ofNullable(getProvider(did))
832 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
833 .map(desc -> applyAllPortOps(cpt, desc))
834 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
835 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700836 }
837
838 if (de != null) {
839 post(de);
840 }
841 }
842
843 // checks if the specified device is allowed by the BasicDeviceConfig
844 // and if not, removes it
845 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700846 Device badDevice = getDevice(deviceId);
847 if (badDevice != null) {
848 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700849 }
850 }
851 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700852
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700853 @Override
854 @SafeVarargs
855 public final void registerPortConfigOperator(PortConfigOperator portOp,
856 Class<? extends Config<ConnectPoint>>...configs) {
857 checkNotNull(portOp);
858
859 portOp.bindService(networkConfigService);
860
861 // update both portOpsIndex and portOps
862 synchronized (portOpsIndex) {
863 for (Class<? extends Config<ConnectPoint>> config : configs) {
864 portOpsIndex.put(config, portOp);
865 }
866
867 portOps.add(portOp);
868 }
869
870 // TODO: Should we be applying to all existing Ports?
871 Tools.stream(store.getAvailableDevices())
872 .map(Device::id)
873 .filter(mastershipService::isLocalMaster)
874 // for each locally managed Device, update all port descriptions
875 .map(did -> {
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800876 ProviderId pid = Optional.ofNullable(getProvider(did))
877 .map(Provider::id)
878 .orElse(null);
879 if (pid == null) {
880 log.warn("Provider not found for {}", did);
881 return ImmutableList.<DeviceEvent>of();
882 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700883 List<PortDescription> pds
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800884 = store.getPortDescriptions(pid, did)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700885 .map(pdesc -> applyAllPortOps(did, pdesc))
886 .collect(Collectors.toList());
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800887 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700888 })
889 // ..and port port update event if necessary
890 .forEach(evts -> evts.forEach(this::post));
891 }
892
893 @Override
894 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
895 checkNotNull(portOp);
896
897
898 // remove all portOp
899 synchronized (portOpsIndex) {
900 portOps.remove(portOp);
901
902 // had to do this since COWArrayList iterator doesn't support remove
903 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
904 }
905
906 }
907
908 /**
909 * Merges the appropriate PortConfig with the description.
910 *
911 * @param did ID of the Device where the port is attached
912 * @param desc {@link PortDescription}
913 * @return merged {@link PortDescription}
914 */
915 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
916 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
917 }
918
919 /**
920 * Merges the appropriate PortConfig with the description.
921 *
922 * @param cpt ConnectPoint where the port is attached
923 * @param desc {@link PortDescription}
924 * @return merged {@link PortDescription}
925 */
926 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
927 PortDescription work = desc;
928 for (PortConfigOperator portOp : portOps) {
929 work = portOp.combine(cpt, work);
930 }
931 return work;
932 }
933
tomd3097b02014-08-26 10:40:29 -0700934}