blob: 5b92489127c1330cf8d467b65dfcb41411fc9b23 [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;
tomd3097b02014-08-26 10:40:29 -070074import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070075
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070076import com.google.common.collect.Multimap;
Yafit Hadara9a73de2015-09-06 13:52:52 +030077import com.google.common.util.concurrent.Futures;
Jonathan Hart2f669362015-02-11 16:19:20 -080078
Ray Milkey9ef22232016-07-14 12:42:37 -070079import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070080import static com.google.common.collect.Multimaps.newListMultimap;
81import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Ray Milkey9ef22232016-07-14 12:42:37 -070082import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
83import static org.onlab.util.Tools.groupedThreads;
84import static org.onosproject.net.MastershipRole.MASTER;
85import static org.onosproject.net.MastershipRole.NONE;
86import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -070087import static org.onosproject.security.AppGuard.checkPermission;
88import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
89import static org.slf4j.LoggerFactory.getLogger;
90
tomd3097b02014-08-26 10:40:29 -070091/**
tome4729872014-09-23 00:37:37 -070092 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070093 */
94@Component(immediate = true)
95@Service
tom41a2c5f2014-09-19 09:20:35 -070096public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -070097 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070098 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -070099
tome5ec3fd2014-09-04 15:18:06 -0700100 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
101 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
102 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
103 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700104 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
tomd3097b02014-08-26 10:40:29 -0700105
tom5f38b3a2014-08-27 23:50:54 -0700106 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700107
alshabib339a3d92014-09-26 17:54:32 -0700108 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700109
tomc78acee2014-09-24 15:16:55 -0700110 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700111 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700112
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800113 private ScheduledExecutorService backgroundService;
114
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700115 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
116
tom41a2c5f2014-09-19 09:20:35 -0700117 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
118 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700119
tom5f38b3a2014-08-27 23:50:54 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700121 protected ClusterService clusterService;
122
123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700124 protected MastershipService mastershipService;
125
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700127 protected MastershipTermService termService;
128
Madan Jampani61056bc2014-09-27 09:07:26 -0700129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700130 protected NetworkConfigService networkConfigService;
131
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700132
133 /**
134 * List of all registered PortConfigOperator.
135 */
136 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
137
138 /**
139 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
140 */
141 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
142 = synchronizedListMultimap(
143 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
144
145
tomd3097b02014-08-26 10:40:29 -0700146 @Activate
147 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800148 backgroundService = newSingleThreadScheduledExecutor(
149 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700150 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800151
tomf80c9722014-09-24 14:49:18 -0700152 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700153 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700154 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700155 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800156
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700157 backgroundService.scheduleWithFixedDelay(() -> {
158 try {
159 mastershipCheck();
160 } catch (Exception e) {
161 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800162 }
163 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700164 log.info("Started");
165 }
166
167 @Deactivate
168 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800169 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700170 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700171 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700172 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700173 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700174 log.info("Stopped");
175 }
176
177 @Override
tomad2d2092014-09-06 23:24:20 -0700178 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900179 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700180 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700181 }
182
183 @Override
tom32f66842014-08-27 19:27:47 -0700184 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900185 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700186 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700187 }
188
tom32f66842014-08-27 19:27:47 -0700189 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800190 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900191 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800192 return store.getAvailableDevices();
193 }
194
195 @Override
tom32f66842014-08-27 19:27:47 -0700196 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900197 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700198 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700199 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700200 }
201
202 @Override
tomad2d2092014-09-06 23:24:20 -0700203 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900204 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700205 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700206 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700207 }
208
209 @Override
tom32f66842014-08-27 19:27:47 -0700210 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900211 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700212 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700213 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700214 }
215
216 @Override
sangho538108b2015-04-08 14:29:20 -0700217 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900218 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700219 checkNotNull(deviceId, DEVICE_ID_NULL);
220 return store.getPortStatistics(deviceId);
221 }
222
223 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200224 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900225 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200226 checkNotNull(deviceId, DEVICE_ID_NULL);
227 return store.getPortDeltaStatistics(deviceId);
228 }
229
230 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530231 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
232 checkPermission(DEVICE_READ);
233 checkNotNull(deviceId, DEVICE_ID_NULL);
234 checkNotNull(portNumber, PORT_NUMBER_NULL);
235 return store.getStatisticsForPort(deviceId, portNumber);
236 }
237
238 @Override
239 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
240 checkPermission(DEVICE_READ);
241 checkNotNull(deviceId, DEVICE_ID_NULL);
242 checkNotNull(portNumber, PORT_NUMBER_NULL);
243 return store.getDeltaStatisticsForPort(deviceId, portNumber);
244 }
245
246 @Override
tom32f66842014-08-27 19:27:47 -0700247 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900248 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700249 checkNotNull(deviceId, DEVICE_ID_NULL);
250 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700251 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700252 }
253
254 @Override
tomff7eb7c2014-09-08 12:49:03 -0700255 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900256 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900257
tomff7eb7c2014-09-08 12:49:03 -0700258 checkNotNull(deviceId, DEVICE_ID_NULL);
259 return store.isAvailable(deviceId);
260 }
261
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700262 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700263 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800264 if (deviceId == null) {
265 return false;
266 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700267 DeviceProvider provider = getProvider(deviceId);
268 if (provider != null) {
269 return provider.isReachable(deviceId);
270 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800271 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700272 return false;
273 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700274 }
275
tome5ec3fd2014-09-04 15:18:06 -0700276 @Override
277 public void removeDevice(DeviceId deviceId) {
278 checkNotNull(deviceId, DEVICE_ID_NULL);
279 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700280 if (event != null) {
281 log.info("Device {} administratively removed", deviceId);
282 post(event);
283 }
tome5ec3fd2014-09-04 15:18:06 -0700284 }
285
tom7869ad92014-09-09 14:32:08 -0700286 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700287 public void changePortState(DeviceId deviceId, PortNumber portNumber,
288 boolean enable) {
289 checkNotNull(deviceId, DEVICE_ID_NULL);
290 checkNotNull(deviceId, PORT_NUMBER_NULL);
291 DeviceProvider provider = getProvider(deviceId);
292 if (provider != null) {
293 log.warn("Port {} on device {} being administratively brought {}",
294 portNumber, deviceId,
295 (enable) ? "UP" : "DOWN");
296 provider.changePortState(deviceId, portNumber, enable);
297 } else {
298 log.warn("Provider not found for {}", deviceId);
299 }
300 }
301
302 @Override
samuele1fa7322015-07-14 16:35:16 +0800303 protected DeviceProviderService createProviderService(
304 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700305 return new InternalDeviceProviderService(provider);
306 }
307
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800308 /**
309 * Checks if all the reachable devices have a valid mastership role.
310 */
311 private void mastershipCheck() {
312 log.debug("Checking mastership");
313 for (Device device : getDevices()) {
314 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800315 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800316
317 if (!isReachable(deviceId)) {
helenyrwufd296b62016-06-22 17:43:02 -0700318 if (mastershipService.getLocalRole(deviceId) != NONE) {
319 // can't be master if device is not reachable
320 try {
321 post(store.markOffline(deviceId));
322 //relinquish master role and ability to be backup.
323 mastershipService.relinquishMastership(deviceId).get();
324 } catch (InterruptedException e) {
325 log.warn("Interrupted while reliquishing role for {}", deviceId);
326 Thread.currentThread().interrupt();
327 } catch (ExecutionException e) {
328 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
329 }
330 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800331 continue;
332 }
333
334 if (mastershipService.getLocalRole(deviceId) != NONE) {
335 continue;
336 }
337
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700338 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800339
340 // isReachable but was not MASTER or STANDBY, get a role and apply
341 // Note: NONE triggers request to MastershipService
342 reassertRole(deviceId, NONE);
343 }
344 }
345
tomd3097b02014-08-26 10:40:29 -0700346 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700347 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700348 extends AbstractProviderService<DeviceProvider>
349 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700350
tomcfde0622014-09-09 11:02:42 -0700351 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700352 super(provider);
353 }
354
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700355 /**
356 * Apply role in reaction to provider event.
357 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700358 * @param deviceId device identifier
359 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700360 * @return true if the request was sent to provider
361 */
362 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
363
364 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800365 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700366 return true;
367 }
368
369 DeviceProvider provider = provider();
370 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700371 log.warn("Provider for {} was not found. Cannot apply role {}",
372 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700373 return false;
374 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700375 provider.roleChanged(deviceId, newRole);
376 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700377 return true;
378 }
379
tomd3097b02014-08-26 10:40:29 -0700380 @Override
alshabibb7b40632014-09-28 21:30:00 -0700381 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700382 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700383 checkNotNull(deviceId, DEVICE_ID_NULL);
384 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700385 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700386
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700387 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
388 if (!isAllowed(cfg)) {
389 log.warn("Device {} is not allowed", deviceId);
390 return;
391 }
392 // Generate updated description and establish my Role
393 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700394 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
395 .thenAccept(role -> {
396 log.info("Local role is {} for {}", role, deviceId);
397 applyRole(deviceId, role);
398 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700399
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700400 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
401 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700402 if (deviceDescription.isDefaultAvailable()) {
403 log.info("Device {} connected", deviceId);
404 } else {
405 log.info("Device {} registered", deviceId);
406 }
tom80c0e5e2014-09-08 18:08:58 -0700407 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700408 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700409 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700410 }
tomd3097b02014-08-26 10:40:29 -0700411 }
412
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700413 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
414 if (desc.isEnabled() != enabled) {
415 return new DefaultPortDescription(desc.portNumber(),
416 enabled,
417 desc.type(),
418 desc.portSpeed(),
419 desc.annotations());
420 }
421 return desc;
422 }
423
tomd3097b02014-08-26 10:40:29 -0700424 @Override
425 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700426 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700427 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700428
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700429 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700430
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700431 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
432 .map(desc -> ensurePortEnabledState(desc, false))
433 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300434
alshabibafc514a2014-12-01 14:44:05 -0800435 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700436 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700437 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700438 post(store.markOffline(deviceId));
439 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700440 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700441 log.warn("Failed to mark {} offline", deviceId);
442 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800443 // but if I was the last STANDBY connection, etc. and no one else
444 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700445 // temporarily request for Master Role and mark offline.
446
samuele1fa7322015-07-14 16:35:16 +0800447 //there are times when this node will correctly have mastership, BUT
448 //that isn't reflected in the ClockManager before the device disconnects.
449 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700450
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700451 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800452 // Consider revising store API to handle this scenario.
453 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700454 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800455 MastershipTerm term = termService.getMastershipTerm(deviceId);
456 // TODO: Move this type of check inside device clock manager, etc.
457 if (term != null && localNodeId.equals(term.master())) {
458 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800459 post(store.markOffline(deviceId));
460 } else {
461 log.info("Failed again marking {} offline. {}", deviceId, role);
462 }
463 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700464 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700465 try {
samuele1fa7322015-07-14 16:35:16 +0800466 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700467 mastershipService.relinquishMastership(deviceId).get();
468 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800469 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700470 Thread.currentThread().interrupt();
471 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800472 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700473 }
tom0efbb1d2014-09-09 11:54:28 -0700474 }
tomd3097b02014-08-26 10:40:29 -0700475 }
476
477 @Override
alshabibb7b40632014-09-28 21:30:00 -0700478 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700479 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700480 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700481 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700482 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700483 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700484 // Never been a master for this device
485 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800486 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700487 return;
488 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700489 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700490 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700491 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700492 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800493 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800494 if (events != null) {
495 for (DeviceEvent event : events) {
496 post(event);
497 }
tom32f66842014-08-27 19:27:47 -0700498 }
tomd3097b02014-08-26 10:40:29 -0700499 }
500
501 @Override
alshabibb7b40632014-09-28 21:30:00 -0700502 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700503 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700504 checkNotNull(deviceId, DEVICE_ID_NULL);
505 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700506 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700507
Madan Jampani565a66a2015-07-25 17:01:13 -0700508 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700509 // Never been a master for this device
510 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700511 log.trace("Ignoring {} port update on standby node. {}", deviceId,
512 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700513 return;
514 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700515 Device device = getDevice(deviceId);
516 if (device == null) {
517 log.trace("Device not found: {}", deviceId);
518 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200519 if ((Device.Type.ROADM.equals(device.type())) ||
520 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700521 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700522 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
523 deviceId,
524 portDescription.portNumber());
525 portDescription = ensurePortEnabledState(storedPortDesc,
526 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300527 }
528
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700529 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800530 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700531 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700532 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700533 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700534 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700535 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700536 }
tomd3097b02014-08-26 10:40:29 -0700537 }
tom3f2bbd72014-09-24 12:07:58 -0700538
539 @Override
samuele1fa7322015-07-14 16:35:16 +0800540 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700541 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700542 // Several things can happen here:
543 // 1. request and response match
544 // 2. request and response don't match
545 // 3. MastershipRole and requested match (and 1 or 2 are true)
546 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
547 //
548 // 2, 4, and 3 with case 2 are failure modes.
549
tom3f2bbd72014-09-24 12:07:58 -0700550 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700551
Madan Jampanif2af7712015-05-29 18:43:52 -0700552 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700553 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700554
555 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800556 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530557 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700558 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700559 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700560 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700561
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700562 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800563 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700564 return;
565 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800566 log.warn("Role mismatch on {}. set to {}, but store demands {}",
567 deviceId, response, mastershipService.getLocalRole(deviceId));
568 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700569 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800570 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800571 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700572 }
573 } else {
574 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800575 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700576 if (response == MastershipRole.MASTER) {
577 mastershipService.relinquishMastership(deviceId);
578 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800579 //final Device device = getDevice(deviceId);
580 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700581 }
582 }
tom3f2bbd72014-09-24 12:07:58 -0700583 }
sangho538108b2015-04-08 14:29:20 -0700584
585 @Override
samuele1fa7322015-07-14 16:35:16 +0800586 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700587 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700588 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700589 checkValidity();
590
samuele1fa7322015-07-14 16:35:16 +0800591 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
592 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700593 post(event);
594 }
tomd3097b02014-08-26 10:40:29 -0700595 }
tom32f66842014-08-27 19:27:47 -0700596
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700597 // by default allowed, otherwise check flag
598 private boolean isAllowed(BasicDeviceConfig cfg) {
599 return (cfg == null || cfg.isAllowed());
600 }
601
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800602 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700603
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800604 /**
605 * Apply role to device and send probe if MASTER.
606 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700607 * @param deviceId device identifier
608 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800609 * @return true if the request was sent to provider
610 */
611 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
612 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800613 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700614 return true;
615 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700616
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800617 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800618 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800619 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800620 return false;
621 }
622 provider.roleChanged(deviceId, newRole);
623
624 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800625 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800626 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800627 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800628 }
629 return true;
630 }
631
632 /**
633 * Reaasert role for specified device connected to this node.
634 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700635 * @param did device identifier
636 * @param nextRole role to apply. If NONE is specified,
637 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800638 */
samuele1fa7322015-07-14 16:35:16 +0800639 private void reassertRole(final DeviceId did,
640 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800641
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800642 MastershipRole myNextRole = nextRole;
643 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800644 try {
645 mastershipService.requestRoleFor(did).get();
646 MastershipTerm term = termService.getMastershipTerm(did);
647 if (term != null && localNodeId.equals(term.master())) {
648 myNextRole = MASTER;
649 } else {
650 myNextRole = STANDBY;
651 }
652 } catch (InterruptedException e) {
653 Thread.currentThread().interrupt();
654 log.error("Interrupted waiting for Mastership", e);
655 } catch (ExecutionException e) {
656 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800657 }
658 }
659
660 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700661 case MASTER:
662 final Device device = getDevice(did);
663 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700664 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700665 }
666 // TODO: should apply role only if there is mismatch
667 log.debug("Applying role {} to {}", myNextRole, did);
668 if (!applyRoleAndProbe(did, MASTER)) {
669 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
670 // immediately failed to apply role
671 mastershipService.relinquishMastership(did);
672 // FIXME disconnect?
673 }
674 break;
675 case STANDBY:
676 log.debug("Applying role {} to {}", myNextRole, did);
677 if (!applyRoleAndProbe(did, STANDBY)) {
678 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
679 // immediately failed to apply role
680 mastershipService.relinquishMastership(did);
681 // FIXME disconnect?
682 }
683 break;
684 case NONE:
685 default:
686 // should never reach here
687 log.error("You didn't see anything. I did not exist.");
688 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800689 }
690 }
691
Madan Jampani328371d2015-05-29 14:06:27 -0700692 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700693 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700694 // Don't care if backup list changed.
695 return;
696 }
Madan Jampani328371d2015-05-29 14:06:27 -0700697 final DeviceId did = event.subject();
698
699 // myRole suggested by MastershipService
700 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700701 if (event.type() == MastershipEvent.Type.SUSPENDED) {
702 myNextRole = NONE; // FIXME STANDBY OR NONE?
703 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700704 // confirm latest info
705 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800706 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700707 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700708 myNextRole = MASTER;
709 } else {
710 myNextRole = STANDBY;
711 }
712 } else if (event.roleInfo().backups().contains(localNodeId)) {
713 myNextRole = STANDBY;
714 } else {
715 myNextRole = NONE;
716 }
717
Madan Jampani328371d2015-05-29 14:06:27 -0700718 final boolean isReachable = isReachable(did);
719 if (!isReachable) {
720 // device is not connected to this node
721 if (myNextRole != NONE) {
722 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700723 + "but this node cannot reach the device. "
724 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800725 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700726 mastershipService.relinquishMastership(did);
727 }
728 return;
729 }
730
731 // device is connected to this node:
732 if (store.getDevice(did) != null) {
733 reassertRole(did, myNextRole);
734 } else {
735 log.debug("Device is not yet/no longer in the store: {}", did);
736 }
737 }
738
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800739 // Intercepts mastership events
740 private class InternalMastershipListener implements MastershipListener {
741
tomb41d1ac2014-09-24 01:51:24 -0700742 @Override
743 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800744 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700745 try {
746 handleMastershipEvent(event);
747 } catch (Exception e) {
748 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700749 }
Madan Jampani328371d2015-05-29 14:06:27 -0700750 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700751 }
tomb41d1ac2014-09-24 01:51:24 -0700752 }
tomf80c9722014-09-24 14:49:18 -0700753
754 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700755 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700756 @Override
757 public void notify(DeviceEvent event) {
758 post(event);
759 }
760 }
samuel738dfaf2015-07-11 11:08:57 +0800761
762 @Override
763 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900764 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800765 Set<Device> results = new HashSet<>();
766 Iterable<Device> devices = store.getDevices();
767 if (devices != null) {
768 devices.forEach(d -> {
769 if (type.equals(d.type())) {
770 results.add(d);
771 }
772 });
773 }
774 return results;
775 }
776
777 @Override
778 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900779 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800780 Set<Device> results = new HashSet<>();
781 Iterable<Device> availableDevices = store.getAvailableDevices();
782 if (availableDevices != null) {
783 availableDevices.forEach(d -> {
784 if (type.equals(d.type())) {
785 results.add(d);
786 }
787 });
788 }
789 return results;
790 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700791
792 private class InternalNetworkConfigListener implements NetworkConfigListener {
793 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700794 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700795 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
796 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
797 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700798 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700799 }
800
801 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700802 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700803 DeviceEvent de = null;
804 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800805 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700806 DeviceId did = (DeviceId) event.subject();
807 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700808
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700809 if (!isAllowed(cfg)) {
810 kickOutBadDevice(did);
811 } else {
812 Device dev = getDevice(did);
813 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
814 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800815 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700816 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
817 }
818 }
819 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700820 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700821 ConnectPoint cpt = (ConnectPoint) event.subject();
822 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700823
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700824 // Note: assuming PortOperator can modify existing port,
825 // but cannot add new port purely from Config.
826 de = Optional.ofNullable(getProvider(did))
827 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
828 .map(desc -> applyAllPortOps(cpt, desc))
829 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
830 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700831 }
832
833 if (de != null) {
834 post(de);
835 }
836 }
837
838 // checks if the specified device is allowed by the BasicDeviceConfig
839 // and if not, removes it
840 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700841 Device badDevice = getDevice(deviceId);
842 if (badDevice != null) {
843 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700844 }
845 }
846 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700847
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700848 @Override
849 @SafeVarargs
850 public final void registerPortConfigOperator(PortConfigOperator portOp,
851 Class<? extends Config<ConnectPoint>>...configs) {
852 checkNotNull(portOp);
853
854 portOp.bindService(networkConfigService);
855
856 // update both portOpsIndex and portOps
857 synchronized (portOpsIndex) {
858 for (Class<? extends Config<ConnectPoint>> config : configs) {
859 portOpsIndex.put(config, portOp);
860 }
861
862 portOps.add(portOp);
863 }
864
865 // TODO: Should we be applying to all existing Ports?
866 Tools.stream(store.getAvailableDevices())
867 .map(Device::id)
868 .filter(mastershipService::isLocalMaster)
869 // for each locally managed Device, update all port descriptions
870 .map(did -> {
871 List<PortDescription> pds
872 = store.getPortDescriptions(getProvider(did).id(), did)
873 .map(pdesc -> applyAllPortOps(did, pdesc))
874 .collect(Collectors.toList());
875 return store.updatePorts(getProvider(did).id(), did, pds);
876 })
877 // ..and port port update event if necessary
878 .forEach(evts -> evts.forEach(this::post));
879 }
880
881 @Override
882 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
883 checkNotNull(portOp);
884
885
886 // remove all portOp
887 synchronized (portOpsIndex) {
888 portOps.remove(portOp);
889
890 // had to do this since COWArrayList iterator doesn't support remove
891 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
892 }
893
894 }
895
896 /**
897 * Merges the appropriate PortConfig with the description.
898 *
899 * @param did ID of the Device where the port is attached
900 * @param desc {@link PortDescription}
901 * @return merged {@link PortDescription}
902 */
903 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
904 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
905 }
906
907 /**
908 * Merges the appropriate PortConfig with the description.
909 *
910 * @param cpt ConnectPoint where the port is attached
911 * @param desc {@link PortDescription}
912 * @return merged {@link PortDescription}
913 */
914 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
915 PortDescription work = desc;
916 for (PortConfigOperator portOp : portOps) {
917 work = portOp.combine(cpt, work);
918 }
919 return work;
920 }
921
tomd3097b02014-08-26 10:40:29 -0700922}