blob: 0748b0c0e444eb1990a9801a0d078792c3f95498 [file] [log] [blame]
Thomas Vachuska4f1a60c2014-10-28 13:39:07 -07001/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2014-present Open Networking Foundation
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
Simon Huntffbad3b2017-05-16 15:37:51 -070018import com.google.common.collect.ImmutableList;
19import com.google.common.collect.Maps;
20import com.google.common.collect.Multimap;
21import com.google.common.util.concurrent.Futures;
tomd3097b02014-08-26 10:40:29 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070025import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070027import org.apache.felix.scr.annotations.Service;
Saurav Dasd5ec9e92017-01-17 10:40:18 -080028import org.joda.time.DateTime;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070029import org.onlab.util.KryoNamespace;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070030import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.NodeId;
Andrea Campanella75ef9f52017-07-27 20:14:32 +020033import org.onosproject.incubator.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.mastership.MastershipEvent;
35import org.onosproject.mastership.MastershipListener;
36import org.onosproject.mastership.MastershipService;
37import org.onosproject.mastership.MastershipTerm;
38import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070039import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080041import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.DeviceId;
43import org.onosproject.net.MastershipRole;
44import org.onosproject.net.Port;
45import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070046import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030047import org.onosproject.net.config.NetworkConfigEvent;
48import org.onosproject.net.config.NetworkConfigListener;
49import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070050import org.onosproject.net.config.PortConfigOperator;
51import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030052import org.onosproject.net.config.basics.BasicDeviceConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080053import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DefaultPortDescription;
55import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceListener;
59import org.onosproject.net.device.DeviceProvider;
60import org.onosproject.net.device.DeviceProviderRegistry;
61import org.onosproject.net.device.DeviceProviderService;
62import org.onosproject.net.device.DeviceService;
63import org.onosproject.net.device.DeviceStore;
64import org.onosproject.net.device.DeviceStoreDelegate;
65import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070066import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030067import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080068import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080069import org.onosproject.net.provider.Provider;
70import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070071import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
72import org.onosproject.store.cluster.messaging.MessageSubject;
73import org.onosproject.store.serializers.KryoNamespaces;
74import org.onosproject.store.service.Serializer;
tomd3097b02014-08-26 10:40:29 -070075import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070076
Simon Huntffbad3b2017-05-16 15:37:51 -070077import java.util.Collection;
78import java.util.HashSet;
79import java.util.List;
80import java.util.Map;
81import java.util.Objects;
82import java.util.Optional;
83import java.util.Set;
84import java.util.concurrent.CompletableFuture;
85import java.util.concurrent.ConcurrentHashMap;
86import java.util.concurrent.CopyOnWriteArrayList;
87import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070088import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070089import java.util.concurrent.ScheduledExecutorService;
90import java.util.concurrent.TimeUnit;
91import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080092
Ray Milkey9ef22232016-07-14 12:42:37 -070093import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070094import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070095import static com.google.common.collect.Multimaps.newListMultimap;
96import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070097import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -070098import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
99import static org.onlab.util.Tools.groupedThreads;
100import static org.onosproject.net.MastershipRole.MASTER;
101import static org.onosproject.net.MastershipRole.NONE;
102import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static org.onosproject.security.AppGuard.checkPermission;
104import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
105import static org.slf4j.LoggerFactory.getLogger;
106
tomd3097b02014-08-26 10:40:29 -0700107/**
tome4729872014-09-23 00:37:37 -0700108 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700109 */
110@Component(immediate = true)
111@Service
tom41a2c5f2014-09-19 09:20:35 -0700112public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700113 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700114 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700115
tome5ec3fd2014-09-04 15:18:06 -0700116 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
117 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
118 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
119 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700120 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700121 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700122
tom5f38b3a2014-08-27 23:50:54 -0700123 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700124
alshabib339a3d92014-09-26 17:54:32 -0700125 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700126
tomc78acee2014-09-24 15:16:55 -0700127 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700128 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700129
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800130 private ScheduledExecutorService backgroundService;
131
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700132 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
133
tom41a2c5f2014-09-19 09:20:35 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
135 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700136
tom5f38b3a2014-08-27 23:50:54 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700138 protected ClusterService clusterService;
139
140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700141 protected MastershipService mastershipService;
142
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700144 protected MastershipTermService termService;
145
Madan Jampani61056bc2014-09-27 09:07:26 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700147 protected NetworkConfigService networkConfigService;
148
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
150 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700151
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700152 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700153 /**
154 * List of all registered PortConfigOperator.
155 */
156 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
157
158 /**
159 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
160 */
161 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700162 = synchronizedListMultimap(
163 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700164
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800165 // not part of portOps. must be executed at the end
166 private PortAnnotationOperator portAnnotationOp;
167
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700168 private static final MessageSubject PORT_UPDOWN_SUBJECT =
169 new MessageSubject("port-updown-req");
170
171 private static final Serializer SERIALIZER = Serializer.using(
172 KryoNamespace.newBuilder()
173 .register(KryoNamespaces.API)
174 .register(InternalPortUpDownEvent.class)
175 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
176 .build("DeviceManager"));
177
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800178 /**
179 * Local storage for connectivity status of devices.
180 */
181 private class LocalStatus {
182 boolean connected;
183 DateTime dateTime;
184
185 public LocalStatus(boolean b, DateTime now) {
186 connected = b;
187 dateTime = now;
188 }
189 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700190
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800191 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
192 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700193
tomd3097b02014-08-26 10:40:29 -0700194 @Activate
195 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800196 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
197 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
198
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800199 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700200 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700201 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800202
tomf80c9722014-09-24 14:49:18 -0700203 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700204 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700205 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700206 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800207
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700208 backgroundService.scheduleWithFixedDelay(() -> {
209 try {
210 mastershipCheck();
211 } catch (Exception e) {
212 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800213 }
214 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700215
216 portReqeustExecutor = newSingleThreadExecutor();
217
218 communicationService.<InternalPortUpDownEvent>addSubscriber(
219 PORT_UPDOWN_SUBJECT,
220 SERIALIZER::decode,
221 this::handlePortRequest,
222 portReqeustExecutor);
223
tomd3097b02014-08-26 10:40:29 -0700224 log.info("Started");
225 }
226
227 @Deactivate
228 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800229 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700230 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700231 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700232 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700233 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700234 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
235 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700236 log.info("Stopped");
237 }
238
239 @Override
tomad2d2092014-09-06 23:24:20 -0700240 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900241 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700242 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700243 }
244
245 @Override
mskala32000d32017-07-14 16:27:06 +0200246 public int getAvailableDeviceCount() {
247 checkPermission(DEVICE_READ);
248 return store.getAvailableDeviceCount();
249 }
250
251 @Override
tom32f66842014-08-27 19:27:47 -0700252 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900253 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700254 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700255 }
256
tom32f66842014-08-27 19:27:47 -0700257 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800258 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800260 return store.getAvailableDevices();
261 }
262
263 @Override
tom32f66842014-08-27 19:27:47 -0700264 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900265 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700266 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700267 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700268 }
269
270 @Override
tomad2d2092014-09-06 23:24:20 -0700271 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900272 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700273 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700274 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700275 }
276
277 @Override
tom32f66842014-08-27 19:27:47 -0700278 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700280 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700281 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700282 }
283
284 @Override
sangho538108b2015-04-08 14:29:20 -0700285 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900286 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700287 checkNotNull(deviceId, DEVICE_ID_NULL);
288 return store.getPortStatistics(deviceId);
289 }
290
291 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200292 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900293 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200294 checkNotNull(deviceId, DEVICE_ID_NULL);
295 return store.getPortDeltaStatistics(deviceId);
296 }
297
298 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530299 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
300 checkPermission(DEVICE_READ);
301 checkNotNull(deviceId, DEVICE_ID_NULL);
302 checkNotNull(portNumber, PORT_NUMBER_NULL);
303 return store.getStatisticsForPort(deviceId, portNumber);
304 }
305
306 @Override
307 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
308 checkPermission(DEVICE_READ);
309 checkNotNull(deviceId, DEVICE_ID_NULL);
310 checkNotNull(portNumber, PORT_NUMBER_NULL);
311 return store.getDeltaStatisticsForPort(deviceId, portNumber);
312 }
313
314 @Override
tom32f66842014-08-27 19:27:47 -0700315 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900316 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700317 checkNotNull(deviceId, DEVICE_ID_NULL);
318 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700319 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700320 }
321
322 @Override
tomff7eb7c2014-09-08 12:49:03 -0700323 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900324 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900325
tomff7eb7c2014-09-08 12:49:03 -0700326 checkNotNull(deviceId, DEVICE_ID_NULL);
327 return store.isAvailable(deviceId);
328 }
329
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800330 @Override
331 public String localStatus(DeviceId deviceId) {
332 LocalStatus ls = deviceLocalStatus.get(deviceId);
333 if (ls == null) {
334 return "No Record";
335 }
336 String timeAgo = Tools.timeAgo(ls.dateTime.getMillis());
337 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
338 }
339
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700340 // Check a device for control channel connectivity.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700341 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800342 if (deviceId == null) {
343 return false;
344 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700345 DeviceProvider provider = getProvider(deviceId);
346 if (provider != null) {
347 return provider.isReachable(deviceId);
348 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800349 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700350 return false;
351 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700352 }
353
tome5ec3fd2014-09-04 15:18:06 -0700354 @Override
355 public void removeDevice(DeviceId deviceId) {
356 checkNotNull(deviceId, DEVICE_ID_NULL);
357 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700358 if (event != null) {
359 log.info("Device {} administratively removed", deviceId);
360 post(event);
361 }
tome5ec3fd2014-09-04 15:18:06 -0700362 }
363
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700364 private void handlePortRequest(InternalPortUpDownEvent event) {
365 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700366 checkNotNull(deviceId, DEVICE_ID_NULL);
367 checkNotNull(deviceId, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700368 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
369 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
370 }
371
372 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
373 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700374 DeviceProvider provider = getProvider(deviceId);
375 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700376 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700377 portNumber, deviceId,
378 (enable) ? "UP" : "DOWN");
379 provider.changePortState(deviceId, portNumber, enable);
380 } else {
381 log.warn("Provider not found for {}", deviceId);
382 }
383 }
384
385 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700386 public void changePortState(DeviceId deviceId, PortNumber portNumber,
387 boolean enable) {
388 checkNotNull(deviceId, DEVICE_ID_NULL);
389 checkNotNull(deviceId, PORT_NUMBER_NULL);
390 NodeId masterId = mastershipService.getMasterFor(deviceId);
391
392 if (!masterId.equals(localNodeId)) {
393 //Send the request to the master node for the device
394 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
395 deviceId, masterId);
396 communicationService.unicast(
397 new InternalPortUpDownEvent(deviceId, portNumber, enable),
398 PORT_UPDOWN_SUBJECT,
399 SERIALIZER::encode,
400 masterId).whenComplete((r, error) -> {
401 if (error != null) {
402 log.warn("Failed to send packet-updown-req to {}", masterId, error);
403 }
404 });
405 } else {
406 changePortStateAtMaster(deviceId, portNumber, enable);
407 }
408 }
409
410 @Override
samuele1fa7322015-07-14 16:35:16 +0800411 protected DeviceProviderService createProviderService(
412 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700413 return new InternalDeviceProviderService(provider);
414 }
415
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800416 /**
417 * Checks if all the reachable devices have a valid mastership role.
418 */
419 private void mastershipCheck() {
420 log.debug("Checking mastership");
421 for (Device device : getDevices()) {
422 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700423 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
424 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800425 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700426 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700427 // can't be master if device is not reachable
428 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700429 if (myRole == MASTER) {
430 post(store.markOffline(deviceId));
431 }
helenyrwufd296b62016-06-22 17:43:02 -0700432 //relinquish master role and ability to be backup.
433 mastershipService.relinquishMastership(deviceId).get();
434 } catch (InterruptedException e) {
435 log.warn("Interrupted while reliquishing role for {}", deviceId);
436 Thread.currentThread().interrupt();
437 } catch (ExecutionException e) {
438 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
439 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530440 } else {
441 // check if the device has master, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530442 // only the nodes which has mastership role can mark any device offline.
Jordan Halterman5fdffe02017-11-29 15:37:34 -0800443 NodeId master = mastershipService.getMasterFor(deviceId);
444 if (master == null) {
445 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
446 roleFuture.thenAccept(role -> {
447 MastershipTerm term = termService.getMastershipTerm(deviceId);
448 if (term != null && localNodeId.equals(term.master())) {
449 log.info("Marking unreachable device {} offline", deviceId);
450 post(store.markOffline(deviceId));
451 } else {
452 log.info("Failed marking {} offline. {}", deviceId, role);
453 }
454 mastershipService.relinquishMastership(deviceId);
455 });
456 }
helenyrwufd296b62016-06-22 17:43:02 -0700457 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800458 continue;
459 }
460
Ray Milkeyc7104672016-08-31 12:04:34 -0700461 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800462 continue;
463 }
464
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700465 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800466
467 // isReachable but was not MASTER or STANDBY, get a role and apply
468 // Note: NONE triggers request to MastershipService
469 reassertRole(deviceId, NONE);
470 }
471 }
472
tomd3097b02014-08-26 10:40:29 -0700473 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700474 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700475 extends AbstractProviderService<DeviceProvider>
476 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700477
tomcfde0622014-09-09 11:02:42 -0700478 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700479 super(provider);
480 }
481
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700482 /**
483 * Apply role in reaction to provider event.
484 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700485 * @param deviceId device identifier
486 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700487 * @return true if the request was sent to provider
488 */
489 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
490
491 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800492 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700493 return true;
494 }
495
496 DeviceProvider provider = provider();
497 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700498 log.warn("Provider for {} was not found. Cannot apply role {}",
499 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700500 return false;
501 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700502 provider.roleChanged(deviceId, newRole);
503 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700504 return true;
505 }
506
tomd3097b02014-08-26 10:40:29 -0700507 @Override
alshabibb7b40632014-09-28 21:30:00 -0700508 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700509 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700510 checkNotNull(deviceId, DEVICE_ID_NULL);
511 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700512 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700513
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800514 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
515
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700516 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
517 if (!isAllowed(cfg)) {
518 log.warn("Device {} is not allowed", deviceId);
519 return;
520 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200521 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700522 // Generate updated description and establish my Role
523 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700524 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700525 .thenAccept(role -> {
526 log.info("Local role is {} for {}", role, deviceId);
527 applyRole(deviceId, role);
528 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700529
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700530 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
531 deviceDescription);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200532 if (portConfig != null) {
533 //updating the ports if configration exists
534 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
535 .collect(Collectors.toList());
536 complete.addAll(portConfig.portDescriptions());
537 List<PortDescription> portDescriptions = complete.stream()
538 .map(e -> applyAllPortOps(deviceId, e))
539 .collect(Collectors.toList());
540 store.updatePorts(provider().id(), deviceId, portDescriptions);
541 }
542
helenyrwufd296b62016-06-22 17:43:02 -0700543 if (deviceDescription.isDefaultAvailable()) {
544 log.info("Device {} connected", deviceId);
545 } else {
546 log.info("Device {} registered", deviceId);
547 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200548
tom80c0e5e2014-09-08 18:08:58 -0700549 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700550 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700551 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700552 }
tomd3097b02014-08-26 10:40:29 -0700553 }
554
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700555 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
556 if (desc.isEnabled() != enabled) {
557 return new DefaultPortDescription(desc.portNumber(),
558 enabled,
559 desc.type(),
560 desc.portSpeed(),
561 desc.annotations());
562 }
563 return desc;
564 }
565
tomd3097b02014-08-26 10:40:29 -0700566 @Override
567 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700568 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700569 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800570 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700571 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700572
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700573 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
574 .map(desc -> ensurePortEnabledState(desc, false))
575 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300576
alshabibafc514a2014-12-01 14:44:05 -0800577 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700578 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700579 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700580 post(store.markOffline(deviceId));
581 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700582 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700583 log.warn("Failed to mark {} offline", deviceId);
584 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800585 // but if I was the last STANDBY connection, etc. and no one else
586 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700587 // temporarily request for Master Role and mark offline.
588
samuele1fa7322015-07-14 16:35:16 +0800589 //there are times when this node will correctly have mastership, BUT
590 //that isn't reflected in the ClockManager before the device disconnects.
591 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700592
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700593 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800594 // Consider revising store API to handle this scenario.
595 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700596 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800597 MastershipTerm term = termService.getMastershipTerm(deviceId);
598 // TODO: Move this type of check inside device clock manager, etc.
599 if (term != null && localNodeId.equals(term.master())) {
600 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800601 post(store.markOffline(deviceId));
602 } else {
603 log.info("Failed again marking {} offline. {}", deviceId, role);
604 }
605 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700606 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700607 try {
samuele1fa7322015-07-14 16:35:16 +0800608 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700609 mastershipService.relinquishMastership(deviceId).get();
610 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800611 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700612 Thread.currentThread().interrupt();
613 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800614 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700615 }
tom0efbb1d2014-09-09 11:54:28 -0700616 }
tomd3097b02014-08-26 10:40:29 -0700617 }
618
619 @Override
alshabibb7b40632014-09-28 21:30:00 -0700620 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700621 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700622 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700623 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700624 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700625 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700626 // Never been a master for this device
627 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800628 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700629 return;
630 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200631 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
632 if (portConfig != null) {
633 //updating the ports if configration exists
634 portDescriptions.addAll(portConfig.portDescriptions());
635 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700636 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700637 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700638 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700639 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800640 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800641 if (events != null) {
642 for (DeviceEvent event : events) {
643 post(event);
644 }
tom32f66842014-08-27 19:27:47 -0700645 }
tomd3097b02014-08-26 10:40:29 -0700646 }
647
648 @Override
alshabibb7b40632014-09-28 21:30:00 -0700649 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700650 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700651 checkNotNull(deviceId, DEVICE_ID_NULL);
652 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700653 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700654
Madan Jampani565a66a2015-07-25 17:01:13 -0700655 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700656 // Never been a master for this device
657 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700658 log.trace("Ignoring {} port update on standby node. {}", deviceId,
659 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700660 return;
661 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700662 Device device = getDevice(deviceId);
663 if (device == null) {
664 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530665 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700666 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200667 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700668 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700669 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700670 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700671 deviceId,
672 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700673 portDescription = ensurePortEnabledState(storedPortDesc,
674 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300675 }
676
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700677 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800678 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700679 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700680 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700681 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700682 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700683 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700684 }
tomd3097b02014-08-26 10:40:29 -0700685 }
tom3f2bbd72014-09-24 12:07:58 -0700686
687 @Override
Michal Machce774332017-01-25 11:02:55 +0100688 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
689
690 checkNotNull(deviceId, DEVICE_ID_NULL);
691 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
692 checkValidity();
693
694 if (!mastershipService.isLocalMaster(deviceId)) {
695 // Never been a master for this device
696 // any update will be ignored.
697 log.trace("Ignoring {} port update on standby node. {}", deviceId,
698 basePortDescription);
699 return;
700 }
701
702 Device device = getDevice(deviceId);
703 if (device == null) {
704 log.trace("Device not found: {}", deviceId);
705 }
706
707 PortDescription newPortDescription = new DefaultPortDescription(basePortDescription.portNumber(),
708 basePortDescription.isEnabled(),
709 true,
710 basePortDescription.type(),
711 basePortDescription.portSpeed(),
712 basePortDescription.annotations());
713 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
714 deviceId,
715 newPortDescription);
716 if (event != null) {
717 log.info("Device {} port {} status changed", deviceId, event.port().number());
718 post(event);
719 }
720 }
721
722 @Override
samuele1fa7322015-07-14 16:35:16 +0800723 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700724 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700725 // Several things can happen here:
726 // 1. request and response match
727 // 2. request and response don't match
728 // 3. MastershipRole and requested match (and 1 or 2 are true)
729 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
730 //
731 // 2, 4, and 3 with case 2 are failure modes.
732
tom3f2bbd72014-09-24 12:07:58 -0700733 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700734
Madan Jampanif2af7712015-05-29 18:43:52 -0700735 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700736 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700737
738 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800739 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530740 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700741 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700742 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700743 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700744
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700745 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800746 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700747 return;
748 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800749 log.warn("Role mismatch on {}. set to {}, but store demands {}",
750 deviceId, response, mastershipService.getLocalRole(deviceId));
751 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700752 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800753 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800754 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700755 }
756 } else {
757 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800758 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700759 if (response == MastershipRole.MASTER) {
760 mastershipService.relinquishMastership(deviceId);
761 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800762 //final Device device = getDevice(deviceId);
763 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700764 }
765 }
tom3f2bbd72014-09-24 12:07:58 -0700766 }
sangho538108b2015-04-08 14:29:20 -0700767
768 @Override
samuele1fa7322015-07-14 16:35:16 +0800769 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700770 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700771 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700772 checkValidity();
773
samuele1fa7322015-07-14 16:35:16 +0800774 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
775 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700776 post(event);
777 }
tomd3097b02014-08-26 10:40:29 -0700778 }
tom32f66842014-08-27 19:27:47 -0700779
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700780 // by default allowed, otherwise check flag
781 private boolean isAllowed(BasicDeviceConfig cfg) {
782 return (cfg == null || cfg.isAllowed());
783 }
784
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800785 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700786
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800787 /**
788 * Apply role to device and send probe if MASTER.
789 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700790 * @param deviceId device identifier
791 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800792 * @return true if the request was sent to provider
793 */
794 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
795 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800796 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700797 return true;
798 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700799
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800800 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800801 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800802 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800803 return false;
804 }
805 provider.roleChanged(deviceId, newRole);
806
807 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800808 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800809 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800810 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800811 }
812 return true;
813 }
814
815 /**
816 * Reaasert role for specified device connected to this node.
817 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700818 * @param did device identifier
819 * @param nextRole role to apply. If NONE is specified,
820 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800821 */
samuele1fa7322015-07-14 16:35:16 +0800822 private void reassertRole(final DeviceId did,
823 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800824
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800825 MastershipRole myNextRole = nextRole;
826 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800827 try {
828 mastershipService.requestRoleFor(did).get();
829 MastershipTerm term = termService.getMastershipTerm(did);
830 if (term != null && localNodeId.equals(term.master())) {
831 myNextRole = MASTER;
832 } else {
833 myNextRole = STANDBY;
834 }
835 } catch (InterruptedException e) {
836 Thread.currentThread().interrupt();
837 log.error("Interrupted waiting for Mastership", e);
838 } catch (ExecutionException e) {
839 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800840 }
841 }
842
843 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700844 case MASTER:
845 final Device device = getDevice(did);
846 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700847 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700848 }
849 // TODO: should apply role only if there is mismatch
850 log.debug("Applying role {} to {}", myNextRole, did);
851 if (!applyRoleAndProbe(did, MASTER)) {
852 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
853 // immediately failed to apply role
854 mastershipService.relinquishMastership(did);
855 // FIXME disconnect?
856 }
857 break;
858 case STANDBY:
859 log.debug("Applying role {} to {}", myNextRole, did);
860 if (!applyRoleAndProbe(did, STANDBY)) {
861 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
862 // immediately failed to apply role
863 mastershipService.relinquishMastership(did);
864 // FIXME disconnect?
865 }
866 break;
867 case NONE:
868 default:
869 // should never reach here
870 log.error("You didn't see anything. I did not exist.");
871 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800872 }
873 }
874
Madan Jampani328371d2015-05-29 14:06:27 -0700875 private void handleMastershipEvent(MastershipEvent event) {
Jordan Haltermane2546312018-02-06 10:28:08 -0800876 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED || event.type() == MastershipEvent.Type.SUSPENDED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700877 // Don't care if backup list changed.
878 return;
879 }
Madan Jampani328371d2015-05-29 14:06:27 -0700880 final DeviceId did = event.subject();
881
882 // myRole suggested by MastershipService
883 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700884 if (event.type() == MastershipEvent.Type.SUSPENDED) {
885 myNextRole = NONE; // FIXME STANDBY OR NONE?
886 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700887 // confirm latest info
888 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800889 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700890 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700891 myNextRole = MASTER;
892 } else {
893 myNextRole = STANDBY;
894 }
895 } else if (event.roleInfo().backups().contains(localNodeId)) {
896 myNextRole = STANDBY;
897 } else {
898 myNextRole = NONE;
899 }
900
Madan Jampani328371d2015-05-29 14:06:27 -0700901 final boolean isReachable = isReachable(did);
902 if (!isReachable) {
903 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800904 if (mastershipService.getLocalRole(did) == NONE) {
905 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700906 + "but this node cannot reach the device "
907 + "and role is already None. Ignoring request.",
908 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800909 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700910 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700911 + "but this node cannot reach the device. "
912 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800913 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700914 mastershipService.relinquishMastership(did);
915 }
916 return;
917 }
918
919 // device is connected to this node:
920 if (store.getDevice(did) != null) {
921 reassertRole(did, myNextRole);
922 } else {
923 log.debug("Device is not yet/no longer in the store: {}", did);
924 }
925 }
926
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800927 // Intercepts mastership events
928 private class InternalMastershipListener implements MastershipListener {
929
tomb41d1ac2014-09-24 01:51:24 -0700930 @Override
931 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800932 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700933 try {
934 handleMastershipEvent(event);
935 } catch (Exception e) {
936 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700937 }
Madan Jampani328371d2015-05-29 14:06:27 -0700938 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700939 }
tomb41d1ac2014-09-24 01:51:24 -0700940 }
tomf80c9722014-09-24 14:49:18 -0700941
942 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700943 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700944 @Override
945 public void notify(DeviceEvent event) {
946 post(event);
947 }
948 }
samuel738dfaf2015-07-11 11:08:57 +0800949
950 @Override
951 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900952 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800953 Set<Device> results = new HashSet<>();
954 Iterable<Device> devices = store.getDevices();
955 if (devices != null) {
956 devices.forEach(d -> {
957 if (type.equals(d.type())) {
958 results.add(d);
959 }
960 });
961 }
962 return results;
963 }
964
965 @Override
966 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900967 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800968 Set<Device> results = new HashSet<>();
969 Iterable<Device> availableDevices = store.getAvailableDevices();
970 if (availableDevices != null) {
971 availableDevices.forEach(d -> {
972 if (type.equals(d.type())) {
973 results.add(d);
974 }
975 });
976 }
977 return results;
978 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700979
980 private class InternalNetworkConfigListener implements NetworkConfigListener {
981 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700982 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700983 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
984 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
985 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200986 || portOpsIndex.containsKey(event.configClass())
987 || event.configClass().equals(PortDescriptionsConfig.class));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700988 }
989
990 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700991 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700992 DeviceEvent de = null;
993 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800994 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -0700995 DeviceId did = (DeviceId) event.subject();
996 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700997 BasicDeviceConfig cfg =
998 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700999
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001000 if (!isAllowed(cfg)) {
1001 kickOutBadDevice(did);
1002 } else {
1003 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001004 DeviceDescription desc =
1005 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001006 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001007 if (desc != null && dp != null) {
1008 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001009 }
1010 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001011 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1012 DeviceId did = (DeviceId) event.subject();
1013 DeviceProvider dp = getProvider(did);
1014 if (!event.config().isPresent() ||
1015 getDevice(did) == null || dp == null) {
1016 // sanity check failed, ignore
1017 return;
1018 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001019 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001020 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001021 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1022 .collect(Collectors.toList());
1023 complete.addAll(portConfig.portDescriptions());
1024 store.updatePorts(dp.id(), did, complete);
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001025 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001026 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001027 DeviceId did = cpt.deviceId();
1028 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001029
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001030 // Note: assuming PortOperator can modify existing port,
1031 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001032 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001033 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1034 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001035 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001036 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001037 }
1038
1039 if (de != null) {
1040 post(de);
1041 }
1042 }
1043
Simon Hunt8f60ff82017-04-24 17:19:30 -07001044 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001045 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001046 Device badDevice = getDevice(deviceId);
1047 if (badDevice != null) {
1048 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001049 }
1050 }
1051 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001052
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001053 @Override
1054 @SafeVarargs
1055 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001056 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001057 checkNotNull(portOp);
1058
1059 portOp.bindService(networkConfigService);
1060
1061 // update both portOpsIndex and portOps
1062 synchronized (portOpsIndex) {
1063 for (Class<? extends Config<ConnectPoint>> config : configs) {
1064 portOpsIndex.put(config, portOp);
1065 }
1066
1067 portOps.add(portOp);
1068 }
1069
1070 // TODO: Should we be applying to all existing Ports?
1071 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001072 .map(Device::id)
1073 .filter(mastershipService::isLocalMaster)
1074 // for each locally managed Device, update all port descriptions
1075 .map(did -> {
1076 ProviderId pid = Optional.ofNullable(getProvider(did))
1077 .map(Provider::id)
1078 .orElse(null);
1079 if (pid == null) {
1080 log.warn("Provider not found for {}", did);
1081 return ImmutableList.<DeviceEvent>of();
1082 }
1083 List<PortDescription> pds
1084 = store.getPortDescriptions(pid, did)
1085 .map(pdesc -> applyAllPortOps(did, pdesc))
1086 .collect(Collectors.toList());
1087 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001088 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001089 // ..and port port update event if necessary
1090 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001091 }
1092
1093 @Override
1094 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1095 checkNotNull(portOp);
1096
1097
1098 // remove all portOp
1099 synchronized (portOpsIndex) {
1100 portOps.remove(portOp);
1101
1102 // had to do this since COWArrayList iterator doesn't support remove
1103 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1104 }
1105
1106 }
1107
1108 /**
1109 * Merges the appropriate PortConfig with the description.
1110 *
1111 * @param did ID of the Device where the port is attached
1112 * @param desc {@link PortDescription}
1113 * @return merged {@link PortDescription}
1114 */
1115 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1116 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1117 }
1118
1119 /**
1120 * Merges the appropriate PortConfig with the description.
1121 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001122 * @param cpt ConnectPoint where the port is attached
1123 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001124 * @return merged {@link PortDescription}
1125 */
1126 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1127 PortDescription work = desc;
1128 for (PortConfigOperator portOp : portOps) {
1129 work = portOp.combine(cpt, work);
1130 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001131 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001132 }
1133
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001134 /**
1135 * Port Enable/Disable message sent to the device's MASTER node.
1136 */
1137 private class InternalPortUpDownEvent {
1138 private final DeviceId deviceId;
1139 private final PortNumber portNumber;
1140 private final boolean enable;
1141
1142 protected InternalPortUpDownEvent(
1143 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1144 this.deviceId = deviceId;
1145 this.portNumber = portNumber;
1146 this.enable = enable;
1147 }
1148
1149 public DeviceId deviceId() {
1150 return deviceId;
1151 }
1152 public PortNumber portNumber() {
1153 return portNumber;
1154 }
1155 public boolean isEnable() {
1156 return enable;
1157 }
1158
1159 protected InternalPortUpDownEvent() {
1160 this.deviceId = null;
1161 this.portNumber = null;
1162 this.enable = false;
1163 }
1164 }
tomd3097b02014-08-26 10:40:29 -07001165}