blob: 9045200e34076eee8fbe5c5aed06747c6036c8fc [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();
Ray Milkeyc7104672016-08-31 12:04:34 -0700315 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
316 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800317 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700318 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700319 // can't be master if device is not reachable
320 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700321 if (myRole == MASTER) {
322 post(store.markOffline(deviceId));
323 }
helenyrwufd296b62016-06-22 17:43:02 -0700324 //relinquish master role and ability to be backup.
325 mastershipService.relinquishMastership(deviceId).get();
326 } catch (InterruptedException e) {
327 log.warn("Interrupted while reliquishing role for {}", deviceId);
328 Thread.currentThread().interrupt();
329 } catch (ExecutionException e) {
330 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
331 }
332 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800333 continue;
334 }
335
Ray Milkeyc7104672016-08-31 12:04:34 -0700336 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800337 continue;
338 }
339
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700340 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800341
342 // isReachable but was not MASTER or STANDBY, get a role and apply
343 // Note: NONE triggers request to MastershipService
344 reassertRole(deviceId, NONE);
345 }
346 }
347
tomd3097b02014-08-26 10:40:29 -0700348 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700349 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700350 extends AbstractProviderService<DeviceProvider>
351 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700352
tomcfde0622014-09-09 11:02:42 -0700353 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700354 super(provider);
355 }
356
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700357 /**
358 * Apply role in reaction to provider event.
359 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700360 * @param deviceId device identifier
361 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700362 * @return true if the request was sent to provider
363 */
364 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
365
366 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800367 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700368 return true;
369 }
370
371 DeviceProvider provider = provider();
372 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700373 log.warn("Provider for {} was not found. Cannot apply role {}",
374 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700375 return false;
376 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700377 provider.roleChanged(deviceId, newRole);
378 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700379 return true;
380 }
381
tomd3097b02014-08-26 10:40:29 -0700382 @Override
alshabibb7b40632014-09-28 21:30:00 -0700383 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700384 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700385 checkNotNull(deviceId, DEVICE_ID_NULL);
386 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700387 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700388
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700389 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
390 if (!isAllowed(cfg)) {
391 log.warn("Device {} is not allowed", deviceId);
392 return;
393 }
394 // Generate updated description and establish my Role
395 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700396 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
397 .thenAccept(role -> {
398 log.info("Local role is {} for {}", role, deviceId);
399 applyRole(deviceId, role);
400 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700401
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700402 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
403 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700404 if (deviceDescription.isDefaultAvailable()) {
405 log.info("Device {} connected", deviceId);
406 } else {
407 log.info("Device {} registered", deviceId);
408 }
tom80c0e5e2014-09-08 18:08:58 -0700409 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700410 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700411 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700412 }
tomd3097b02014-08-26 10:40:29 -0700413 }
414
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700415 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
416 if (desc.isEnabled() != enabled) {
417 return new DefaultPortDescription(desc.portNumber(),
418 enabled,
419 desc.type(),
420 desc.portSpeed(),
421 desc.annotations());
422 }
423 return desc;
424 }
425
tomd3097b02014-08-26 10:40:29 -0700426 @Override
427 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700428 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700429 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700430
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700431 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700432
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700433 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
434 .map(desc -> ensurePortEnabledState(desc, false))
435 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300436
alshabibafc514a2014-12-01 14:44:05 -0800437 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700438 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700439 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700440 post(store.markOffline(deviceId));
441 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700442 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700443 log.warn("Failed to mark {} offline", deviceId);
444 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800445 // but if I was the last STANDBY connection, etc. and no one else
446 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700447 // temporarily request for Master Role and mark offline.
448
samuele1fa7322015-07-14 16:35:16 +0800449 //there are times when this node will correctly have mastership, BUT
450 //that isn't reflected in the ClockManager before the device disconnects.
451 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700452
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700453 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800454 // Consider revising store API to handle this scenario.
455 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700456 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800457 MastershipTerm term = termService.getMastershipTerm(deviceId);
458 // TODO: Move this type of check inside device clock manager, etc.
459 if (term != null && localNodeId.equals(term.master())) {
460 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800461 post(store.markOffline(deviceId));
462 } else {
463 log.info("Failed again marking {} offline. {}", deviceId, role);
464 }
465 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700466 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700467 try {
samuele1fa7322015-07-14 16:35:16 +0800468 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700469 mastershipService.relinquishMastership(deviceId).get();
470 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800471 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700472 Thread.currentThread().interrupt();
473 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800474 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700475 }
tom0efbb1d2014-09-09 11:54:28 -0700476 }
tomd3097b02014-08-26 10:40:29 -0700477 }
478
479 @Override
alshabibb7b40632014-09-28 21:30:00 -0700480 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700481 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700482 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700483 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700484 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700485 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700486 // Never been a master for this device
487 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800488 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700489 return;
490 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700491 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700492 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700493 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700494 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800495 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800496 if (events != null) {
497 for (DeviceEvent event : events) {
498 post(event);
499 }
tom32f66842014-08-27 19:27:47 -0700500 }
tomd3097b02014-08-26 10:40:29 -0700501 }
502
503 @Override
alshabibb7b40632014-09-28 21:30:00 -0700504 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700505 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700506 checkNotNull(deviceId, DEVICE_ID_NULL);
507 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700508 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700509
Madan Jampani565a66a2015-07-25 17:01:13 -0700510 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700511 // Never been a master for this device
512 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700513 log.trace("Ignoring {} port update on standby node. {}", deviceId,
514 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700515 return;
516 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700517 Device device = getDevice(deviceId);
518 if (device == null) {
519 log.trace("Device not found: {}", deviceId);
520 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200521 if ((Device.Type.ROADM.equals(device.type())) ||
522 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700523 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700524 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
525 deviceId,
526 portDescription.portNumber());
527 portDescription = ensurePortEnabledState(storedPortDesc,
528 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300529 }
530
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700531 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800532 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700533 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700534 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700535 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700536 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700537 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700538 }
tomd3097b02014-08-26 10:40:29 -0700539 }
tom3f2bbd72014-09-24 12:07:58 -0700540
541 @Override
samuele1fa7322015-07-14 16:35:16 +0800542 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700543 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700544 // Several things can happen here:
545 // 1. request and response match
546 // 2. request and response don't match
547 // 3. MastershipRole and requested match (and 1 or 2 are true)
548 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
549 //
550 // 2, 4, and 3 with case 2 are failure modes.
551
tom3f2bbd72014-09-24 12:07:58 -0700552 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700553
Madan Jampanif2af7712015-05-29 18:43:52 -0700554 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700555 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700556
557 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800558 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530559 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700560 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700561 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700562 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700563
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700564 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800565 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700566 return;
567 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800568 log.warn("Role mismatch on {}. set to {}, but store demands {}",
569 deviceId, response, mastershipService.getLocalRole(deviceId));
570 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700571 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800572 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800573 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700574 }
575 } else {
576 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800577 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700578 if (response == MastershipRole.MASTER) {
579 mastershipService.relinquishMastership(deviceId);
580 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800581 //final Device device = getDevice(deviceId);
582 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700583 }
584 }
tom3f2bbd72014-09-24 12:07:58 -0700585 }
sangho538108b2015-04-08 14:29:20 -0700586
587 @Override
samuele1fa7322015-07-14 16:35:16 +0800588 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700589 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700590 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700591 checkValidity();
592
samuele1fa7322015-07-14 16:35:16 +0800593 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
594 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700595 post(event);
596 }
tomd3097b02014-08-26 10:40:29 -0700597 }
tom32f66842014-08-27 19:27:47 -0700598
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700599 // by default allowed, otherwise check flag
600 private boolean isAllowed(BasicDeviceConfig cfg) {
601 return (cfg == null || cfg.isAllowed());
602 }
603
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800604 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700605
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800606 /**
607 * Apply role to device and send probe if MASTER.
608 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700609 * @param deviceId device identifier
610 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800611 * @return true if the request was sent to provider
612 */
613 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
614 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800615 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700616 return true;
617 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700618
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800619 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800620 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800621 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800622 return false;
623 }
624 provider.roleChanged(deviceId, newRole);
625
626 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800627 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800628 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800629 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800630 }
631 return true;
632 }
633
634 /**
635 * Reaasert role for specified device connected to this node.
636 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700637 * @param did device identifier
638 * @param nextRole role to apply. If NONE is specified,
639 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800640 */
samuele1fa7322015-07-14 16:35:16 +0800641 private void reassertRole(final DeviceId did,
642 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800643
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800644 MastershipRole myNextRole = nextRole;
645 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800646 try {
647 mastershipService.requestRoleFor(did).get();
648 MastershipTerm term = termService.getMastershipTerm(did);
649 if (term != null && localNodeId.equals(term.master())) {
650 myNextRole = MASTER;
651 } else {
652 myNextRole = STANDBY;
653 }
654 } catch (InterruptedException e) {
655 Thread.currentThread().interrupt();
656 log.error("Interrupted waiting for Mastership", e);
657 } catch (ExecutionException e) {
658 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800659 }
660 }
661
662 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700663 case MASTER:
664 final Device device = getDevice(did);
665 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700666 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700667 }
668 // TODO: should apply role only if there is mismatch
669 log.debug("Applying role {} to {}", myNextRole, did);
670 if (!applyRoleAndProbe(did, MASTER)) {
671 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
672 // immediately failed to apply role
673 mastershipService.relinquishMastership(did);
674 // FIXME disconnect?
675 }
676 break;
677 case STANDBY:
678 log.debug("Applying role {} to {}", myNextRole, did);
679 if (!applyRoleAndProbe(did, STANDBY)) {
680 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
681 // immediately failed to apply role
682 mastershipService.relinquishMastership(did);
683 // FIXME disconnect?
684 }
685 break;
686 case NONE:
687 default:
688 // should never reach here
689 log.error("You didn't see anything. I did not exist.");
690 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800691 }
692 }
693
Madan Jampani328371d2015-05-29 14:06:27 -0700694 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700695 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700696 // Don't care if backup list changed.
697 return;
698 }
Madan Jampani328371d2015-05-29 14:06:27 -0700699 final DeviceId did = event.subject();
700
701 // myRole suggested by MastershipService
702 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700703 if (event.type() == MastershipEvent.Type.SUSPENDED) {
704 myNextRole = NONE; // FIXME STANDBY OR NONE?
705 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700706 // confirm latest info
707 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800708 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700709 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700710 myNextRole = MASTER;
711 } else {
712 myNextRole = STANDBY;
713 }
714 } else if (event.roleInfo().backups().contains(localNodeId)) {
715 myNextRole = STANDBY;
716 } else {
717 myNextRole = NONE;
718 }
719
Madan Jampani328371d2015-05-29 14:06:27 -0700720 final boolean isReachable = isReachable(did);
721 if (!isReachable) {
722 // device is not connected to this node
723 if (myNextRole != NONE) {
724 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700725 + "but this node cannot reach the device. "
726 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800727 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700728 mastershipService.relinquishMastership(did);
729 }
730 return;
731 }
732
733 // device is connected to this node:
734 if (store.getDevice(did) != null) {
735 reassertRole(did, myNextRole);
736 } else {
737 log.debug("Device is not yet/no longer in the store: {}", did);
738 }
739 }
740
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800741 // Intercepts mastership events
742 private class InternalMastershipListener implements MastershipListener {
743
tomb41d1ac2014-09-24 01:51:24 -0700744 @Override
745 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800746 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700747 try {
748 handleMastershipEvent(event);
749 } catch (Exception e) {
750 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700751 }
Madan Jampani328371d2015-05-29 14:06:27 -0700752 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700753 }
tomb41d1ac2014-09-24 01:51:24 -0700754 }
tomf80c9722014-09-24 14:49:18 -0700755
756 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700757 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700758 @Override
759 public void notify(DeviceEvent event) {
760 post(event);
761 }
762 }
samuel738dfaf2015-07-11 11:08:57 +0800763
764 @Override
765 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900766 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800767 Set<Device> results = new HashSet<>();
768 Iterable<Device> devices = store.getDevices();
769 if (devices != null) {
770 devices.forEach(d -> {
771 if (type.equals(d.type())) {
772 results.add(d);
773 }
774 });
775 }
776 return results;
777 }
778
779 @Override
780 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900781 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800782 Set<Device> results = new HashSet<>();
783 Iterable<Device> availableDevices = store.getAvailableDevices();
784 if (availableDevices != null) {
785 availableDevices.forEach(d -> {
786 if (type.equals(d.type())) {
787 results.add(d);
788 }
789 });
790 }
791 return results;
792 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700793
794 private class InternalNetworkConfigListener implements NetworkConfigListener {
795 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700796 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700797 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
798 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
799 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700800 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700801 }
802
803 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700804 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700805 DeviceEvent de = null;
806 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800807 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700808 DeviceId did = (DeviceId) event.subject();
809 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700810
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700811 if (!isAllowed(cfg)) {
812 kickOutBadDevice(did);
813 } else {
814 Device dev = getDevice(did);
815 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
816 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800817 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700818 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
819 }
820 }
821 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700822 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700823 ConnectPoint cpt = (ConnectPoint) event.subject();
824 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700825
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700826 // Note: assuming PortOperator can modify existing port,
827 // but cannot add new port purely from Config.
828 de = Optional.ofNullable(getProvider(did))
829 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
830 .map(desc -> applyAllPortOps(cpt, desc))
831 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
832 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700833 }
834
835 if (de != null) {
836 post(de);
837 }
838 }
839
840 // checks if the specified device is allowed by the BasicDeviceConfig
841 // and if not, removes it
842 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700843 Device badDevice = getDevice(deviceId);
844 if (badDevice != null) {
845 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700846 }
847 }
848 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700849
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700850 @Override
851 @SafeVarargs
852 public final void registerPortConfigOperator(PortConfigOperator portOp,
853 Class<? extends Config<ConnectPoint>>...configs) {
854 checkNotNull(portOp);
855
856 portOp.bindService(networkConfigService);
857
858 // update both portOpsIndex and portOps
859 synchronized (portOpsIndex) {
860 for (Class<? extends Config<ConnectPoint>> config : configs) {
861 portOpsIndex.put(config, portOp);
862 }
863
864 portOps.add(portOp);
865 }
866
867 // TODO: Should we be applying to all existing Ports?
868 Tools.stream(store.getAvailableDevices())
869 .map(Device::id)
870 .filter(mastershipService::isLocalMaster)
871 // for each locally managed Device, update all port descriptions
872 .map(did -> {
873 List<PortDescription> pds
874 = store.getPortDescriptions(getProvider(did).id(), did)
875 .map(pdesc -> applyAllPortOps(did, pdesc))
876 .collect(Collectors.toList());
877 return store.updatePorts(getProvider(did).id(), did, pds);
878 })
879 // ..and port port update event if necessary
880 .forEach(evts -> evts.forEach(this::post));
881 }
882
883 @Override
884 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
885 checkNotNull(portOp);
886
887
888 // remove all portOp
889 synchronized (portOpsIndex) {
890 portOps.remove(portOp);
891
892 // had to do this since COWArrayList iterator doesn't support remove
893 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
894 }
895
896 }
897
898 /**
899 * Merges the appropriate PortConfig with the description.
900 *
901 * @param did ID of the Device where the port is attached
902 * @param desc {@link PortDescription}
903 * @return merged {@link PortDescription}
904 */
905 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
906 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
907 }
908
909 /**
910 * Merges the appropriate PortConfig with the description.
911 *
912 * @param cpt ConnectPoint where the port is attached
913 * @param desc {@link PortDescription}
914 * @return merged {@link PortDescription}
915 */
916 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
917 PortDescription work = desc;
918 for (PortConfigOperator portOp : portOps) {
919 work = portOp.combine(cpt, work);
920 }
921 return work;
922 }
923
tomd3097b02014-08-26 10:40:29 -0700924}