blob: 7a98a5f334580b511461fecd1e8890fee80d0663 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connor5ab426f2016-04-09 01:19:45 -07002 * Copyright 2014-present Open Networking Laboratory
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
Brian O'Connorabafb502014-12-02 22:26:20 -080016package org.onosproject.net.device.impl;
tomd3097b02014-08-26 10:40:29 -070017
Yafit Hadara9a73de2015-09-06 13:52:52 +030018import java.util.Collection;
19import java.util.HashSet;
20import java.util.List;
21import java.util.Objects;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070022import java.util.Optional;
Yafit Hadara9a73de2015-09-06 13:52:52 +030023import java.util.Set;
24import java.util.concurrent.CompletableFuture;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070025import java.util.concurrent.ConcurrentHashMap;
26import java.util.concurrent.CopyOnWriteArrayList;
Yafit Hadara9a73de2015-09-06 13:52:52 +030027import java.util.concurrent.ExecutionException;
28import java.util.concurrent.ScheduledExecutorService;
29import java.util.concurrent.TimeUnit;
30import java.util.stream.Collectors;
tomd3097b02014-08-26 10:40:29 -070031import org.apache.felix.scr.annotations.Activate;
32import org.apache.felix.scr.annotations.Component;
33import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070034import org.apache.felix.scr.annotations.Reference;
35import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070036import org.apache.felix.scr.annotations.Service;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070037import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.cluster.ClusterService;
39import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.mastership.MastershipEvent;
41import org.onosproject.mastership.MastershipListener;
42import org.onosproject.mastership.MastershipService;
43import org.onosproject.mastership.MastershipTerm;
44import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070045import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080046import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080047import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.DeviceId;
49import org.onosproject.net.MastershipRole;
50import org.onosproject.net.Port;
51import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070052import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030053import org.onosproject.net.config.NetworkConfigEvent;
54import org.onosproject.net.config.NetworkConfigListener;
55import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070056import org.onosproject.net.config.PortConfigOperator;
57import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030058import org.onosproject.net.config.basics.BasicDeviceConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080059import org.onosproject.net.device.DefaultPortDescription;
60import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080061import org.onosproject.net.device.DeviceDescription;
62import org.onosproject.net.device.DeviceEvent;
63import org.onosproject.net.device.DeviceListener;
64import org.onosproject.net.device.DeviceProvider;
65import org.onosproject.net.device.DeviceProviderRegistry;
66import org.onosproject.net.device.DeviceProviderService;
67import org.onosproject.net.device.DeviceService;
68import org.onosproject.net.device.DeviceStore;
69import org.onosproject.net.device.DeviceStoreDelegate;
70import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070071import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030072import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080073import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080074import org.onosproject.net.provider.Provider;
75import org.onosproject.net.provider.ProviderId;
tomd3097b02014-08-26 10:40:29 -070076import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070077
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080078import com.google.common.collect.ImmutableList;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070079import com.google.common.collect.Multimap;
Yafit Hadara9a73de2015-09-06 13:52:52 +030080import com.google.common.util.concurrent.Futures;
Jonathan Hart2f669362015-02-11 16:19:20 -080081
Ray Milkey9ef22232016-07-14 12:42:37 -070082import static com.google.common.base.Preconditions.checkNotNull;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070083import static com.google.common.collect.Multimaps.newListMultimap;
84import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Ray Milkey9ef22232016-07-14 12:42:37 -070085import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
86import static org.onlab.util.Tools.groupedThreads;
87import static org.onosproject.net.MastershipRole.MASTER;
88import static org.onosproject.net.MastershipRole.NONE;
89import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -070090import static org.onosproject.security.AppGuard.checkPermission;
91import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
92import static org.slf4j.LoggerFactory.getLogger;
93
tomd3097b02014-08-26 10:40:29 -070094/**
tome4729872014-09-23 00:37:37 -070095 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -070096 */
97@Component(immediate = true)
98@Service
tom41a2c5f2014-09-19 09:20:35 -070099public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700100 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700101 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700102
tome5ec3fd2014-09-04 15:18:06 -0700103 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
104 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
105 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
106 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700107 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
tomd3097b02014-08-26 10:40:29 -0700108
tom5f38b3a2014-08-27 23:50:54 -0700109 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700110
alshabib339a3d92014-09-26 17:54:32 -0700111 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700112
tomc78acee2014-09-24 15:16:55 -0700113 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700114 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700115
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800116 private ScheduledExecutorService backgroundService;
117
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700118 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
119
tom41a2c5f2014-09-19 09:20:35 -0700120 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
121 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700122
tom5f38b3a2014-08-27 23:50:54 -0700123 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700124 protected ClusterService clusterService;
125
126 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700127 protected MastershipService mastershipService;
128
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800129 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700130 protected MastershipTermService termService;
131
Madan Jampani61056bc2014-09-27 09:07:26 -0700132 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700133 protected NetworkConfigService networkConfigService;
134
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700135
136 /**
137 * List of all registered PortConfigOperator.
138 */
139 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
140
141 /**
142 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
143 */
144 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
145 = synchronizedListMultimap(
146 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
147
148
tomd3097b02014-08-26 10:40:29 -0700149 @Activate
150 public void activate() {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800151 backgroundService = newSingleThreadScheduledExecutor(
152 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700153 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800154
tomf80c9722014-09-24 14:49:18 -0700155 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700156 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700157 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700158 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800159
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700160 backgroundService.scheduleWithFixedDelay(() -> {
161 try {
162 mastershipCheck();
163 } catch (Exception e) {
164 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800165 }
166 }, 1, 1, TimeUnit.MINUTES);
tomd3097b02014-08-26 10:40:29 -0700167 log.info("Started");
168 }
169
170 @Deactivate
171 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800172 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700173 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700174 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700175 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700176 eventDispatcher.removeSink(DeviceEvent.class);
tomd3097b02014-08-26 10:40:29 -0700177 log.info("Stopped");
178 }
179
180 @Override
tomad2d2092014-09-06 23:24:20 -0700181 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900182 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700183 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700184 }
185
186 @Override
tom32f66842014-08-27 19:27:47 -0700187 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900188 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700189 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700190 }
191
tom32f66842014-08-27 19:27:47 -0700192 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800193 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900194 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800195 return store.getAvailableDevices();
196 }
197
198 @Override
tom32f66842014-08-27 19:27:47 -0700199 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900200 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700201 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700202 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700203 }
204
205 @Override
tomad2d2092014-09-06 23:24:20 -0700206 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900207 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700208 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700209 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700210 }
211
212 @Override
tom32f66842014-08-27 19:27:47 -0700213 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900214 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700215 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700216 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700217 }
218
219 @Override
sangho538108b2015-04-08 14:29:20 -0700220 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900221 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700222 checkNotNull(deviceId, DEVICE_ID_NULL);
223 return store.getPortStatistics(deviceId);
224 }
225
226 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200227 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900228 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200229 checkNotNull(deviceId, DEVICE_ID_NULL);
230 return store.getPortDeltaStatistics(deviceId);
231 }
232
233 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530234 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
235 checkPermission(DEVICE_READ);
236 checkNotNull(deviceId, DEVICE_ID_NULL);
237 checkNotNull(portNumber, PORT_NUMBER_NULL);
238 return store.getStatisticsForPort(deviceId, portNumber);
239 }
240
241 @Override
242 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
243 checkPermission(DEVICE_READ);
244 checkNotNull(deviceId, DEVICE_ID_NULL);
245 checkNotNull(portNumber, PORT_NUMBER_NULL);
246 return store.getDeltaStatisticsForPort(deviceId, portNumber);
247 }
248
249 @Override
tom32f66842014-08-27 19:27:47 -0700250 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900251 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700252 checkNotNull(deviceId, DEVICE_ID_NULL);
253 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700254 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700255 }
256
257 @Override
tomff7eb7c2014-09-08 12:49:03 -0700258 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900260
tomff7eb7c2014-09-08 12:49:03 -0700261 checkNotNull(deviceId, DEVICE_ID_NULL);
262 return store.isAvailable(deviceId);
263 }
264
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700265 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700266 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800267 if (deviceId == null) {
268 return false;
269 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700270 DeviceProvider provider = getProvider(deviceId);
271 if (provider != null) {
272 return provider.isReachable(deviceId);
273 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800274 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700275 return false;
276 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700277 }
278
tome5ec3fd2014-09-04 15:18:06 -0700279 @Override
280 public void removeDevice(DeviceId deviceId) {
281 checkNotNull(deviceId, DEVICE_ID_NULL);
282 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700283 if (event != null) {
284 log.info("Device {} administratively removed", deviceId);
285 post(event);
286 }
tome5ec3fd2014-09-04 15:18:06 -0700287 }
288
tom7869ad92014-09-09 14:32:08 -0700289 @Override
Saurav Dasa2d37502016-03-25 17:50:40 -0700290 public void changePortState(DeviceId deviceId, PortNumber portNumber,
291 boolean enable) {
292 checkNotNull(deviceId, DEVICE_ID_NULL);
293 checkNotNull(deviceId, PORT_NUMBER_NULL);
294 DeviceProvider provider = getProvider(deviceId);
295 if (provider != null) {
296 log.warn("Port {} on device {} being administratively brought {}",
297 portNumber, deviceId,
298 (enable) ? "UP" : "DOWN");
299 provider.changePortState(deviceId, portNumber, enable);
300 } else {
301 log.warn("Provider not found for {}", deviceId);
302 }
303 }
304
305 @Override
samuele1fa7322015-07-14 16:35:16 +0800306 protected DeviceProviderService createProviderService(
307 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700308 return new InternalDeviceProviderService(provider);
309 }
310
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800311 /**
312 * Checks if all the reachable devices have a valid mastership role.
313 */
314 private void mastershipCheck() {
315 log.debug("Checking mastership");
316 for (Device device : getDevices()) {
317 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700318 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
319 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800320 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700321 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700322 // can't be master if device is not reachable
323 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700324 if (myRole == MASTER) {
325 post(store.markOffline(deviceId));
326 }
helenyrwufd296b62016-06-22 17:43:02 -0700327 //relinquish master role and ability to be backup.
328 mastershipService.relinquishMastership(deviceId).get();
329 } catch (InterruptedException e) {
330 log.warn("Interrupted while reliquishing role for {}", deviceId);
331 Thread.currentThread().interrupt();
332 } catch (ExecutionException e) {
333 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
334 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530335 } else {
336 // check if the device has master, if not, mark it offline
337 NodeId masterId = mastershipService.getMasterFor(deviceId);
338 // only the nodes which has mastership role can mark any device offline.
339 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
340 roleFuture.thenAccept(role -> {
341 MastershipTerm term = termService.getMastershipTerm(deviceId);
342 if (term != null && localNodeId.equals(term.master())) {
343 log.info("Marking unreachable device {} offline", deviceId);
344 post(store.markOffline(deviceId));
345 } else {
346 log.info("Failed marking {} offline. {}", deviceId, role);
347 }
348 mastershipService.relinquishMastership(deviceId);
349 });
helenyrwufd296b62016-06-22 17:43:02 -0700350 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800351 continue;
352 }
353
Ray Milkeyc7104672016-08-31 12:04:34 -0700354 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800355 continue;
356 }
357
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700358 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800359
360 // isReachable but was not MASTER or STANDBY, get a role and apply
361 // Note: NONE triggers request to MastershipService
362 reassertRole(deviceId, NONE);
363 }
364 }
365
tomd3097b02014-08-26 10:40:29 -0700366 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700367 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700368 extends AbstractProviderService<DeviceProvider>
369 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700370
tomcfde0622014-09-09 11:02:42 -0700371 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700372 super(provider);
373 }
374
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700375 /**
376 * Apply role in reaction to provider event.
377 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700378 * @param deviceId device identifier
379 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700380 * @return true if the request was sent to provider
381 */
382 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
383
384 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800385 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700386 return true;
387 }
388
389 DeviceProvider provider = provider();
390 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700391 log.warn("Provider for {} was not found. Cannot apply role {}",
392 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700393 return false;
394 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700395 provider.roleChanged(deviceId, newRole);
396 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700397 return true;
398 }
399
tomd3097b02014-08-26 10:40:29 -0700400 @Override
alshabibb7b40632014-09-28 21:30:00 -0700401 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700402 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700403 checkNotNull(deviceId, DEVICE_ID_NULL);
404 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700405 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700406
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700407 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
408 if (!isAllowed(cfg)) {
409 log.warn("Device {} is not allowed", deviceId);
410 return;
411 }
412 // Generate updated description and establish my Role
413 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700414 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
415 .thenAccept(role -> {
416 log.info("Local role is {} for {}", role, deviceId);
417 applyRole(deviceId, role);
418 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700419
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700420 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
421 deviceDescription);
helenyrwufd296b62016-06-22 17:43:02 -0700422 if (deviceDescription.isDefaultAvailable()) {
423 log.info("Device {} connected", deviceId);
424 } else {
425 log.info("Device {} registered", deviceId);
426 }
tom80c0e5e2014-09-08 18:08:58 -0700427 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700428 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700429 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700430 }
tomd3097b02014-08-26 10:40:29 -0700431 }
432
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700433 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
434 if (desc.isEnabled() != enabled) {
435 return new DefaultPortDescription(desc.portNumber(),
436 enabled,
437 desc.type(),
438 desc.portSpeed(),
439 desc.annotations());
440 }
441 return desc;
442 }
443
tomd3097b02014-08-26 10:40:29 -0700444 @Override
445 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700446 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700447 checkValidity();
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700448
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700449 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700450
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700451 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
452 .map(desc -> ensurePortEnabledState(desc, false))
453 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300454
alshabibafc514a2014-12-01 14:44:05 -0800455 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700456 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700457 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700458 post(store.markOffline(deviceId));
459 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700460 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700461 log.warn("Failed to mark {} offline", deviceId);
462 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800463 // but if I was the last STANDBY connection, etc. and no one else
464 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700465 // temporarily request for Master Role and mark offline.
466
samuele1fa7322015-07-14 16:35:16 +0800467 //there are times when this node will correctly have mastership, BUT
468 //that isn't reflected in the ClockManager before the device disconnects.
469 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700470
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700471 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800472 // Consider revising store API to handle this scenario.
473 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700474 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800475 MastershipTerm term = termService.getMastershipTerm(deviceId);
476 // TODO: Move this type of check inside device clock manager, etc.
477 if (term != null && localNodeId.equals(term.master())) {
478 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800479 post(store.markOffline(deviceId));
480 } else {
481 log.info("Failed again marking {} offline. {}", deviceId, role);
482 }
483 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700484 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700485 try {
samuele1fa7322015-07-14 16:35:16 +0800486 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700487 mastershipService.relinquishMastership(deviceId).get();
488 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800489 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700490 Thread.currentThread().interrupt();
491 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800492 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700493 }
tom0efbb1d2014-09-09 11:54:28 -0700494 }
tomd3097b02014-08-26 10:40:29 -0700495 }
496
497 @Override
alshabibb7b40632014-09-28 21:30:00 -0700498 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700499 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700500 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700501 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700502 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700503 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700504 // Never been a master for this device
505 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800506 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700507 return;
508 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700509 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700510 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700511 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700512 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800513 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800514 if (events != null) {
515 for (DeviceEvent event : events) {
516 post(event);
517 }
tom32f66842014-08-27 19:27:47 -0700518 }
tomd3097b02014-08-26 10:40:29 -0700519 }
520
521 @Override
alshabibb7b40632014-09-28 21:30:00 -0700522 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700523 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700524 checkNotNull(deviceId, DEVICE_ID_NULL);
525 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700526 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700527
Madan Jampani565a66a2015-07-25 17:01:13 -0700528 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700529 // Never been a master for this device
530 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700531 log.trace("Ignoring {} port update on standby node. {}", deviceId,
532 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700533 return;
534 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700535 Device device = getDevice(deviceId);
536 if (device == null) {
537 log.trace("Device not found: {}", deviceId);
538 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200539 if ((Device.Type.ROADM.equals(device.type())) ||
540 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700541 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700542 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
543 deviceId,
544 portDescription.portNumber());
545 portDescription = ensurePortEnabledState(storedPortDesc,
546 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300547 }
548
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700549 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800550 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700551 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700552 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700553 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700554 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700555 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700556 }
tomd3097b02014-08-26 10:40:29 -0700557 }
tom3f2bbd72014-09-24 12:07:58 -0700558
559 @Override
samuele1fa7322015-07-14 16:35:16 +0800560 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700561 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700562 // Several things can happen here:
563 // 1. request and response match
564 // 2. request and response don't match
565 // 3. MastershipRole and requested match (and 1 or 2 are true)
566 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
567 //
568 // 2, 4, and 3 with case 2 are failure modes.
569
tom3f2bbd72014-09-24 12:07:58 -0700570 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700571
Madan Jampanif2af7712015-05-29 18:43:52 -0700572 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700573 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700574
575 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800576 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530577 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700578 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700579 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700580 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700581
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700582 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800583 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700584 return;
585 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800586 log.warn("Role mismatch on {}. set to {}, but store demands {}",
587 deviceId, response, mastershipService.getLocalRole(deviceId));
588 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700589 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800590 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800591 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700592 }
593 } else {
594 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800595 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700596 if (response == MastershipRole.MASTER) {
597 mastershipService.relinquishMastership(deviceId);
598 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800599 //final Device device = getDevice(deviceId);
600 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700601 }
602 }
tom3f2bbd72014-09-24 12:07:58 -0700603 }
sangho538108b2015-04-08 14:29:20 -0700604
605 @Override
samuele1fa7322015-07-14 16:35:16 +0800606 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700607 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700608 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700609 checkValidity();
610
samuele1fa7322015-07-14 16:35:16 +0800611 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
612 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700613 post(event);
614 }
tomd3097b02014-08-26 10:40:29 -0700615 }
tom32f66842014-08-27 19:27:47 -0700616
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700617 // by default allowed, otherwise check flag
618 private boolean isAllowed(BasicDeviceConfig cfg) {
619 return (cfg == null || cfg.isAllowed());
620 }
621
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800622 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700623
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800624 /**
625 * Apply role to device and send probe if MASTER.
626 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700627 * @param deviceId device identifier
628 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800629 * @return true if the request was sent to provider
630 */
631 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
632 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800633 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700634 return true;
635 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700636
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800637 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800638 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800639 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800640 return false;
641 }
642 provider.roleChanged(deviceId, newRole);
643
644 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800645 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800646 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800647 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800648 }
649 return true;
650 }
651
652 /**
653 * Reaasert role for specified device connected to this node.
654 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700655 * @param did device identifier
656 * @param nextRole role to apply. If NONE is specified,
657 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800658 */
samuele1fa7322015-07-14 16:35:16 +0800659 private void reassertRole(final DeviceId did,
660 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800661
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800662 MastershipRole myNextRole = nextRole;
663 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800664 try {
665 mastershipService.requestRoleFor(did).get();
666 MastershipTerm term = termService.getMastershipTerm(did);
667 if (term != null && localNodeId.equals(term.master())) {
668 myNextRole = MASTER;
669 } else {
670 myNextRole = STANDBY;
671 }
672 } catch (InterruptedException e) {
673 Thread.currentThread().interrupt();
674 log.error("Interrupted waiting for Mastership", e);
675 } catch (ExecutionException e) {
676 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800677 }
678 }
679
680 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700681 case MASTER:
682 final Device device = getDevice(did);
683 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700684 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700685 }
686 // TODO: should apply role only if there is mismatch
687 log.debug("Applying role {} to {}", myNextRole, did);
688 if (!applyRoleAndProbe(did, MASTER)) {
689 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
690 // immediately failed to apply role
691 mastershipService.relinquishMastership(did);
692 // FIXME disconnect?
693 }
694 break;
695 case STANDBY:
696 log.debug("Applying role {} to {}", myNextRole, did);
697 if (!applyRoleAndProbe(did, STANDBY)) {
698 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
699 // immediately failed to apply role
700 mastershipService.relinquishMastership(did);
701 // FIXME disconnect?
702 }
703 break;
704 case NONE:
705 default:
706 // should never reach here
707 log.error("You didn't see anything. I did not exist.");
708 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800709 }
710 }
711
Madan Jampani328371d2015-05-29 14:06:27 -0700712 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700713 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700714 // Don't care if backup list changed.
715 return;
716 }
Madan Jampani328371d2015-05-29 14:06:27 -0700717 final DeviceId did = event.subject();
718
719 // myRole suggested by MastershipService
720 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700721 if (event.type() == MastershipEvent.Type.SUSPENDED) {
722 myNextRole = NONE; // FIXME STANDBY OR NONE?
723 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700724 // confirm latest info
725 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800726 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700727 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700728 myNextRole = MASTER;
729 } else {
730 myNextRole = STANDBY;
731 }
732 } else if (event.roleInfo().backups().contains(localNodeId)) {
733 myNextRole = STANDBY;
734 } else {
735 myNextRole = NONE;
736 }
737
Madan Jampani328371d2015-05-29 14:06:27 -0700738 final boolean isReachable = isReachable(did);
739 if (!isReachable) {
740 // device is not connected to this node
741 if (myNextRole != NONE) {
742 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700743 + "but this node cannot reach the device. "
744 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800745 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700746 mastershipService.relinquishMastership(did);
747 }
748 return;
749 }
750
751 // device is connected to this node:
752 if (store.getDevice(did) != null) {
753 reassertRole(did, myNextRole);
754 } else {
755 log.debug("Device is not yet/no longer in the store: {}", did);
756 }
757 }
758
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800759 // Intercepts mastership events
760 private class InternalMastershipListener implements MastershipListener {
761
tomb41d1ac2014-09-24 01:51:24 -0700762 @Override
763 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800764 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700765 try {
766 handleMastershipEvent(event);
767 } catch (Exception e) {
768 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700769 }
Madan Jampani328371d2015-05-29 14:06:27 -0700770 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700771 }
tomb41d1ac2014-09-24 01:51:24 -0700772 }
tomf80c9722014-09-24 14:49:18 -0700773
774 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700775 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700776 @Override
777 public void notify(DeviceEvent event) {
778 post(event);
779 }
780 }
samuel738dfaf2015-07-11 11:08:57 +0800781
782 @Override
783 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900784 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800785 Set<Device> results = new HashSet<>();
786 Iterable<Device> devices = store.getDevices();
787 if (devices != null) {
788 devices.forEach(d -> {
789 if (type.equals(d.type())) {
790 results.add(d);
791 }
792 });
793 }
794 return results;
795 }
796
797 @Override
798 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900799 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800800 Set<Device> results = new HashSet<>();
801 Iterable<Device> availableDevices = store.getAvailableDevices();
802 if (availableDevices != null) {
803 availableDevices.forEach(d -> {
804 if (type.equals(d.type())) {
805 results.add(d);
806 }
807 });
808 }
809 return results;
810 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700811
812 private class InternalNetworkConfigListener implements NetworkConfigListener {
813 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700814 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700815 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
816 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
817 && (event.configClass().equals(BasicDeviceConfig.class)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700818 || portOpsIndex.containsKey(event.configClass()));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700819 }
820
821 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700822 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700823 DeviceEvent de = null;
824 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800825 log.debug("Detected device network config event {}", event.type());
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700826 DeviceId did = (DeviceId) event.subject();
827 BasicDeviceConfig cfg = networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700828
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700829 if (!isAllowed(cfg)) {
830 kickOutBadDevice(did);
831 } else {
832 Device dev = getDevice(did);
833 DeviceDescription desc = (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
834 desc = BasicDeviceOperator.combine(cfg, desc);
Thomas Vachuska1627dc82015-11-13 12:22:14 -0800835 if (desc != null && getProvider(did) != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700836 de = store.createOrUpdateDevice(getProvider(did).id(), did, desc);
837 }
838 }
839 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700840 if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700841 ConnectPoint cpt = (ConnectPoint) event.subject();
842 DeviceId did = cpt.deviceId();
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700843
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700844 // Note: assuming PortOperator can modify existing port,
845 // but cannot add new port purely from Config.
846 de = Optional.ofNullable(getProvider(did))
847 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
848 .map(desc -> applyAllPortOps(cpt, desc))
849 .map(desc -> store.updatePortStatus(getProvider(did).id(), did, desc))
850 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700851 }
852
853 if (de != null) {
854 post(de);
855 }
856 }
857
858 // checks if the specified device is allowed by the BasicDeviceConfig
859 // and if not, removes it
860 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700861 Device badDevice = getDevice(deviceId);
862 if (badDevice != null) {
863 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700864 }
865 }
866 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700867
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700868 @Override
869 @SafeVarargs
870 public final void registerPortConfigOperator(PortConfigOperator portOp,
871 Class<? extends Config<ConnectPoint>>...configs) {
872 checkNotNull(portOp);
873
874 portOp.bindService(networkConfigService);
875
876 // update both portOpsIndex and portOps
877 synchronized (portOpsIndex) {
878 for (Class<? extends Config<ConnectPoint>> config : configs) {
879 portOpsIndex.put(config, portOp);
880 }
881
882 portOps.add(portOp);
883 }
884
885 // TODO: Should we be applying to all existing Ports?
886 Tools.stream(store.getAvailableDevices())
887 .map(Device::id)
888 .filter(mastershipService::isLocalMaster)
889 // for each locally managed Device, update all port descriptions
890 .map(did -> {
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800891 ProviderId pid = Optional.ofNullable(getProvider(did))
892 .map(Provider::id)
893 .orElse(null);
894 if (pid == null) {
895 log.warn("Provider not found for {}", did);
896 return ImmutableList.<DeviceEvent>of();
897 }
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700898 List<PortDescription> pds
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800899 = store.getPortDescriptions(pid, did)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700900 .map(pdesc -> applyAllPortOps(did, pdesc))
901 .collect(Collectors.toList());
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -0800902 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700903 })
904 // ..and port port update event if necessary
905 .forEach(evts -> evts.forEach(this::post));
906 }
907
908 @Override
909 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
910 checkNotNull(portOp);
911
912
913 // remove all portOp
914 synchronized (portOpsIndex) {
915 portOps.remove(portOp);
916
917 // had to do this since COWArrayList iterator doesn't support remove
918 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
919 }
920
921 }
922
923 /**
924 * Merges the appropriate PortConfig with the description.
925 *
926 * @param did ID of the Device where the port is attached
927 * @param desc {@link PortDescription}
928 * @return merged {@link PortDescription}
929 */
930 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
931 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
932 }
933
934 /**
935 * Merges the appropriate PortConfig with the description.
936 *
937 * @param cpt ConnectPoint where the port is attached
938 * @param desc {@link PortDescription}
939 * @return merged {@link PortDescription}
940 */
941 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
942 PortDescription work = desc;
943 for (PortConfigOperator portOp : portOps) {
944 work = portOp.combine(cpt, work);
945 }
946 return work;
947 }
948
tomd3097b02014-08-26 10:40:29 -0700949}