blob: cd3c5439ff1f79a5f0d181e5bb3cae88b5a66096 [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
tom32f66842014-08-27 19:27:47 -0700231 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900232 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700233 checkNotNull(deviceId, DEVICE_ID_NULL);
234 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700235 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700236 }
237
238 @Override
tomff7eb7c2014-09-08 12:49:03 -0700239 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900240 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900241
tomff7eb7c2014-09-08 12:49:03 -0700242 checkNotNull(deviceId, DEVICE_ID_NULL);
243 return store.isAvailable(deviceId);
244 }
245
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700246 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700247 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800248 if (deviceId == null) {
249 return false;
250 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700251 DeviceProvider provider = getProvider(deviceId);
252 if (provider != null) {
253 return provider.isReachable(deviceId);
254 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800255 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700256 return false;
257 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700258 }
259
tome5ec3fd2014-09-04 15:18:06 -0700260 @Override
261 public void removeDevice(DeviceId deviceId) {
262 checkNotNull(deviceId, DEVICE_ID_NULL);
263 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700264 if (event != null) {
265 log.info("Device {} administratively removed", deviceId);
266 post(event);
267 }
tome5ec3fd2014-09-04 15:18:06 -0700268 }
269
tom7869ad92014-09-09 14:32:08 -0700270 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700271 public void changePortState(DeviceId deviceId, PortNumber portNumber,
272 boolean enable) {
273 checkNotNull(deviceId, DEVICE_ID_NULL);
274 checkNotNull(deviceId, PORT_NUMBER_NULL);
275 DeviceProvider provider = getProvider(deviceId);
276 if (provider != null) {
277 log.warn("Port {} on device {} being administratively brought {}",
278 portNumber, deviceId,
279 (enable) ? "UP" : "DOWN");
280 provider.changePortState(deviceId, portNumber, enable);
281 } else {
282 log.warn("Provider not found for {}", deviceId);
283 }
284 }
285
286 @Override
samuele1fa7322015-07-14 16:35:16 +0800287 protected DeviceProviderService createProviderService(
288 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700289 return new InternalDeviceProviderService(provider);
290 }
291
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800292 /**
293 * Checks if all the reachable devices have a valid mastership role.
294 */
295 private void mastershipCheck() {
296 log.debug("Checking mastership");
297 for (Device device : getDevices()) {
298 final DeviceId deviceId = device.id();
Jonathan Hart2f669362015-02-11 16:19:20 -0800299 log.trace("Checking device {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800300
301 if (!isReachable(deviceId)) {
helenyrwufd296b62016-06-22 17:43:02 -0700302 if (mastershipService.getLocalRole(deviceId) != NONE) {
303 // can't be master if device is not reachable
304 try {
305 post(store.markOffline(deviceId));
306 //relinquish master role and ability to be backup.
307 mastershipService.relinquishMastership(deviceId).get();
308 } catch (InterruptedException e) {
309 log.warn("Interrupted while reliquishing role for {}", deviceId);
310 Thread.currentThread().interrupt();
311 } catch (ExecutionException e) {
312 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
313 }
314 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800315 continue;
316 }
317
318 if (mastershipService.getLocalRole(deviceId) != NONE) {
319 continue;
320 }
321
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700322 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800323
324 // isReachable but was not MASTER or STANDBY, get a role and apply
325 // Note: NONE triggers request to MastershipService
326 reassertRole(deviceId, NONE);
327 }
328 }
329
tomd3097b02014-08-26 10:40:29 -0700330 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700331 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700332 extends AbstractProviderService<DeviceProvider>
333 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700334
tomcfde0622014-09-09 11:02:42 -0700335 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700336 super(provider);
337 }
338
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700339 /**
340 * Apply role in reaction to provider event.
341 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700342 * @param deviceId device identifier
343 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700344 * @return true if the request was sent to provider
345 */
346 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
347
348 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800349 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700350 return true;
351 }
352
353 DeviceProvider provider = provider();
354 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700355 log.warn("Provider for {} was not found. Cannot apply role {}",
356 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700357 return false;
358 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700359 provider.roleChanged(deviceId, newRole);
360 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700361 return true;
362 }
363
tomd3097b02014-08-26 10:40:29 -0700364 @Override
alshabibb7b40632014-09-28 21:30:00 -0700365 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700366 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700367 checkNotNull(deviceId, DEVICE_ID_NULL);
368 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700369 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700370
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700371 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
372 if (!isAllowed(cfg)) {
373 log.warn("Device {} is not allowed", deviceId);
374 return;
375 }
376 // Generate updated description and establish my Role
377 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700378 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
379 .thenAccept(role -> {
380 log.info("Local role is {} for {}", role, deviceId);
381 applyRole(deviceId, role);
382 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700383
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700384 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
385 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700386 if (deviceDescription.isDefaultAvailable()) {
387 log.info("Device {} connected", deviceId);
388 } else {
389 log.info("Device {} registered", deviceId);
390 }
tom80c0e5e2014-09-08 18:08:58 -0700391 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700392 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700393 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700394 }
tomd3097b02014-08-26 10:40:29 -0700395 }
396
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700397 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
398 if (desc.isEnabled() != enabled) {
399 return new DefaultPortDescription(desc.portNumber(),
400 enabled,
401 desc.type(),
402 desc.portSpeed(),
403 desc.annotations());
404 }
405 return desc;
406 }
407
tomd3097b02014-08-26 10:40:29 -0700408 @Override
409 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700410 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700411 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700412
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700413 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700414
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700415 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
416 .map(desc -> ensurePortEnabledState(desc, false))
417 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300418
alshabibafc514a2014-12-01 14:44:05 -0800419 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700420 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700421 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700422 post(store.markOffline(deviceId));
423 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700424 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700425 log.warn("Failed to mark {} offline", deviceId);
426 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800427 // but if I was the last STANDBY connection, etc. and no one else
428 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700429 // temporarily request for Master Role and mark offline.
430
samuele1fa7322015-07-14 16:35:16 +0800431 //there are times when this node will correctly have mastership, BUT
432 //that isn't reflected in the ClockManager before the device disconnects.
433 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700434
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700435 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800436 // Consider revising store API to handle this scenario.
437 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700438 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800439 MastershipTerm term = termService.getMastershipTerm(deviceId);
440 // TODO: Move this type of check inside device clock manager, etc.
441 if (term != null && localNodeId.equals(term.master())) {
442 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800443 post(store.markOffline(deviceId));
444 } else {
445 log.info("Failed again marking {} offline. {}", deviceId, role);
446 }
447 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700448 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700449 try {
samuele1fa7322015-07-14 16:35:16 +0800450 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700451 mastershipService.relinquishMastership(deviceId).get();
452 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800453 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700454 Thread.currentThread().interrupt();
455 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800456 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700457 }
tom0efbb1d2014-09-09 11:54:28 -0700458 }
tomd3097b02014-08-26 10:40:29 -0700459 }
460
461 @Override
alshabibb7b40632014-09-28 21:30:00 -0700462 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700463 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700464 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700465 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700466 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700467 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700468 // Never been a master for this device
469 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800470 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700471 return;
472 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700473 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700474 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700475 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700476 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800477 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800478 if (events != null) {
479 for (DeviceEvent event : events) {
480 post(event);
481 }
tom32f66842014-08-27 19:27:47 -0700482 }
tomd3097b02014-08-26 10:40:29 -0700483 }
484
485 @Override
alshabibb7b40632014-09-28 21:30:00 -0700486 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700487 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700488 checkNotNull(deviceId, DEVICE_ID_NULL);
489 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700490 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700491
Madan Jampani565a66a2015-07-25 17:01:13 -0700492 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700493 // Never been a master for this device
494 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700495 log.trace("Ignoring {} port update on standby node. {}", deviceId,
496 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700497 return;
498 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700499 Device device = getDevice(deviceId);
500 if (device == null) {
501 log.trace("Device not found: {}", deviceId);
502 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200503 if ((Device.Type.ROADM.equals(device.type())) ||
504 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700505 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700506 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
507 deviceId,
508 portDescription.portNumber());
509 portDescription = ensurePortEnabledState(storedPortDesc,
510 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300511 }
512
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700513 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800514 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700515 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700516 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700517 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700518 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700519 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700520 }
tomd3097b02014-08-26 10:40:29 -0700521 }
tom3f2bbd72014-09-24 12:07:58 -0700522
523 @Override
samuele1fa7322015-07-14 16:35:16 +0800524 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700525 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700526 // Several things can happen here:
527 // 1. request and response match
528 // 2. request and response don't match
529 // 3. MastershipRole and requested match (and 1 or 2 are true)
530 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
531 //
532 // 2, 4, and 3 with case 2 are failure modes.
533
tom3f2bbd72014-09-24 12:07:58 -0700534 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700535
Madan Jampanif2af7712015-05-29 18:43:52 -0700536 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700537 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700538
539 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800540 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530541 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700542 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700543 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700544 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700545
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700546 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800547 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700548 return;
549 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800550 log.warn("Role mismatch on {}. set to {}, but store demands {}",
551 deviceId, response, mastershipService.getLocalRole(deviceId));
552 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700553 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800554 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800555 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700556 }
557 } else {
558 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800559 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700560 if (response == MastershipRole.MASTER) {
561 mastershipService.relinquishMastership(deviceId);
562 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800563 //final Device device = getDevice(deviceId);
564 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700565 }
566 }
tom3f2bbd72014-09-24 12:07:58 -0700567 }
sangho538108b2015-04-08 14:29:20 -0700568
569 @Override
samuele1fa7322015-07-14 16:35:16 +0800570 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700571 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700572 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700573 checkValidity();
574
samuele1fa7322015-07-14 16:35:16 +0800575 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
576 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700577 post(event);
578 }
tomd3097b02014-08-26 10:40:29 -0700579 }
tom32f66842014-08-27 19:27:47 -0700580
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700581 // by default allowed, otherwise check flag
582 private boolean isAllowed(BasicDeviceConfig cfg) {
583 return (cfg == null || cfg.isAllowed());
584 }
585
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800586 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700587
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800588 /**
589 * Apply role to device and send probe if MASTER.
590 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700591 * @param deviceId device identifier
592 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800593 * @return true if the request was sent to provider
594 */
595 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
596 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800597 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700598 return true;
599 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700600
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800601 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800602 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800603 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800604 return false;
605 }
606 provider.roleChanged(deviceId, newRole);
607
608 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800609 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800610 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800611 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800612 }
613 return true;
614 }
615
616 /**
617 * Reaasert role for specified device connected to this node.
618 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700619 * @param did device identifier
620 * @param nextRole role to apply. If NONE is specified,
621 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800622 */
samuele1fa7322015-07-14 16:35:16 +0800623 private void reassertRole(final DeviceId did,
624 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800625
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800626 MastershipRole myNextRole = nextRole;
627 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800628 try {
629 mastershipService.requestRoleFor(did).get();
630 MastershipTerm term = termService.getMastershipTerm(did);
631 if (term != null && localNodeId.equals(term.master())) {
632 myNextRole = MASTER;
633 } else {
634 myNextRole = STANDBY;
635 }
636 } catch (InterruptedException e) {
637 Thread.currentThread().interrupt();
638 log.error("Interrupted waiting for Mastership", e);
639 } catch (ExecutionException e) {
640 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800641 }
642 }
643
644 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700645 case MASTER:
646 final Device device = getDevice(did);
647 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700648 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700649 }
650 // TODO: should apply role only if there is mismatch
651 log.debug("Applying role {} to {}", myNextRole, did);
652 if (!applyRoleAndProbe(did, MASTER)) {
653 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
654 // immediately failed to apply role
655 mastershipService.relinquishMastership(did);
656 // FIXME disconnect?
657 }
658 break;
659 case STANDBY:
660 log.debug("Applying role {} to {}", myNextRole, did);
661 if (!applyRoleAndProbe(did, STANDBY)) {
662 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
663 // immediately failed to apply role
664 mastershipService.relinquishMastership(did);
665 // FIXME disconnect?
666 }
667 break;
668 case NONE:
669 default:
670 // should never reach here
671 log.error("You didn't see anything. I did not exist.");
672 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800673 }
674 }
675
Madan Jampani328371d2015-05-29 14:06:27 -0700676 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700677 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700678 // Don't care if backup list changed.
679 return;
680 }
Madan Jampani328371d2015-05-29 14:06:27 -0700681 final DeviceId did = event.subject();
682
683 // myRole suggested by MastershipService
684 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700685 if (event.type() == MastershipEvent.Type.SUSPENDED) {
686 myNextRole = NONE; // FIXME STANDBY OR NONE?
687 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700688 // confirm latest info
689 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800690 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700691 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700692 myNextRole = MASTER;
693 } else {
694 myNextRole = STANDBY;
695 }
696 } else if (event.roleInfo().backups().contains(localNodeId)) {
697 myNextRole = STANDBY;
698 } else {
699 myNextRole = NONE;
700 }
701
Madan Jampani328371d2015-05-29 14:06:27 -0700702 final boolean isReachable = isReachable(did);
703 if (!isReachable) {
704 // device is not connected to this node
705 if (myNextRole != NONE) {
706 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700707 + "but this node cannot reach the device. "
708 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800709 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700710 mastershipService.relinquishMastership(did);
711 }
712 return;
713 }
714
715 // device is connected to this node:
716 if (store.getDevice(did) != null) {
717 reassertRole(did, myNextRole);
718 } else {
719 log.debug("Device is not yet/no longer in the store: {}", did);
720 }
721 }
722
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800723 // Intercepts mastership events
724 private class InternalMastershipListener implements MastershipListener {
725
tomb41d1ac2014-09-24 01:51:24 -0700726 @Override
727 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800728 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700729 try {
730 handleMastershipEvent(event);
731 } catch (Exception e) {
732 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700733 }
Madan Jampani328371d2015-05-29 14:06:27 -0700734 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700735 }
tomb41d1ac2014-09-24 01:51:24 -0700736 }
tomf80c9722014-09-24 14:49:18 -0700737
738 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700739 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700740 @Override
741 public void notify(DeviceEvent event) {
742 post(event);
743 }
744 }
samuel738dfaf2015-07-11 11:08:57 +0800745
746 @Override
747 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900748 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800749 Set<Device> results = new HashSet<>();
750 Iterable<Device> devices = store.getDevices();
751 if (devices != null) {
752 devices.forEach(d -> {
753 if (type.equals(d.type())) {
754 results.add(d);
755 }
756 });
757 }
758 return results;
759 }
760
761 @Override
762 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900763 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800764 Set<Device> results = new HashSet<>();
765 Iterable<Device> availableDevices = store.getAvailableDevices();
766 if (availableDevices != null) {
767 availableDevices.forEach(d -> {
768 if (type.equals(d.type())) {
769 results.add(d);
770 }
771 });
772 }
773 return results;
774 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700775
776 private class InternalNetworkConfigListener implements NetworkConfigListener {
777 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700778 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700779 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
780 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
781 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700782 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700783 }
784
785 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700786 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700787 DeviceEvent de = null;
788 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800789 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700790 DeviceId did = (DeviceId) event.subject();
791 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700792
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700793 if (!isAllowed(cfg)) {
794 kickOutBadDevice(did);
795 } else {
796 Device dev = getDevice(did);
797 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
798 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800799 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700800 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
801 }
802 }
803 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700804 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700805 ConnectPoint cpt = (ConnectPoint) event.subject();
806 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700807
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700808 // Note: assuming PortOperator can modify existing port,
809 // but cannot add new port purely from Config.
810 de = Optional.ofNullable(getProvider(did))
811 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
812 .map(desc -> applyAllPortOps(cpt, desc))
813 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
814 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700815 }
816
817 if (de != null) {
818 post(de);
819 }
820 }
821
822 // checks if the specified device is allowed by the BasicDeviceConfig
823 // and if not, removes it
824 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700825 Device badDevice = getDevice(deviceId);
826 if (badDevice != null) {
827 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700828 }
829 }
830 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700831
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700832 @Override
833 @SafeVarargs
834 public final void registerPortConfigOperator(PortConfigOperator portOp,
835 Class<? extends Config<ConnectPoint>>...configs) {
836 checkNotNull(portOp);
837
838 portOp.bindService(networkConfigService);
839
840 // update both portOpsIndex and portOps
841 synchronized (portOpsIndex) {
842 for (Class<? extends Config<ConnectPoint>> config : configs) {
843 portOpsIndex.put(config, portOp);
844 }
845
846 portOps.add(portOp);
847 }
848
849 // TODO: Should we be applying to all existing Ports?
850 Tools.stream(store.getAvailableDevices())
851 .map(Device::id)
852 .filter(mastershipService::isLocalMaster)
853 // for each locally managed Device, update all port descriptions
854 .map(did -> {
855 List<PortDescription> pds
856 = store.getPortDescriptions(getProvider(did).id(), did)
857 .map(pdesc -> applyAllPortOps(did, pdesc))
858 .collect(Collectors.toList());
859 return store.updatePorts(getProvider(did).id(), did, pds);
860 })
861 // ..and port port update event if necessary
862 .forEach(evts -> evts.forEach(this::post));
863 }
864
865 @Override
866 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
867 checkNotNull(portOp);
868
869
870 // remove all portOp
871 synchronized (portOpsIndex) {
872 portOps.remove(portOp);
873
874 // had to do this since COWArrayList iterator doesn't support remove
875 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
876 }
877
878 }
879
880 /**
881 * Merges the appropriate PortConfig with the description.
882 *
883 * @param did ID of the Device where the port is attached
884 * @param desc {@link PortDescription}
885 * @return merged {@link PortDescription}
886 */
887 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
888 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
889 }
890
891 /**
892 * Merges the appropriate PortConfig with the description.
893 *
894 * @param cpt ConnectPoint where the port is attached
895 * @param desc {@link PortDescription}
896 * @return merged {@link PortDescription}
897 */
898 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
899 PortDescription work = desc;
900 for (PortConfigOperator portOp : portOps) {
901 work = portOp.combine(cpt, work);
902 }
903 return work;
904 }
905
tomd3097b02014-08-26 10:40:29 -0700906}