blob: bbf6d394a32503ef08b2bc56fcc7c117b9c28049 [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.
443 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
444 roleFuture.thenAccept(role -> {
445 MastershipTerm term = termService.getMastershipTerm(deviceId);
446 if (term != null && localNodeId.equals(term.master())) {
447 log.info("Marking unreachable device {} offline", deviceId);
448 post(store.markOffline(deviceId));
449 } else {
450 log.info("Failed marking {} offline. {}", deviceId, role);
451 }
452 mastershipService.relinquishMastership(deviceId);
453 });
helenyrwufd296b62016-06-22 17:43:02 -0700454 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800455 continue;
456 }
457
Ray Milkeyc7104672016-08-31 12:04:34 -0700458 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800459 continue;
460 }
461
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700462 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800463
464 // isReachable but was not MASTER or STANDBY, get a role and apply
465 // Note: NONE triggers request to MastershipService
Jordan Halterman980a8c12017-09-22 18:01:19 -0700466 reassertRole(deviceId, mastershipService.getLocalRole(deviceId));
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800467 }
468 }
469
tomd3097b02014-08-26 10:40:29 -0700470 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700471 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700472 extends AbstractProviderService<DeviceProvider>
473 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700474
tomcfde0622014-09-09 11:02:42 -0700475 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700476 super(provider);
477 }
478
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700479 /**
480 * Apply role in reaction to provider event.
481 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700482 * @param deviceId device identifier
483 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700484 * @return true if the request was sent to provider
485 */
486 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
487
488 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800489 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700490 return true;
491 }
492
493 DeviceProvider provider = provider();
494 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700495 log.warn("Provider for {} was not found. Cannot apply role {}",
496 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700497 return false;
498 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700499 provider.roleChanged(deviceId, newRole);
500 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700501 return true;
502 }
503
tomd3097b02014-08-26 10:40:29 -0700504 @Override
alshabibb7b40632014-09-28 21:30:00 -0700505 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700506 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700507 checkNotNull(deviceId, DEVICE_ID_NULL);
508 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700509 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700510
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800511 deviceLocalStatus.put(deviceId, new LocalStatus(true, DateTime.now()));
512
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700513 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
514 if (!isAllowed(cfg)) {
515 log.warn("Device {} is not allowed", deviceId);
516 return;
517 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200518 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700519 // Generate updated description and establish my Role
520 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700521 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700522 .thenAccept(role -> {
523 log.info("Local role is {} for {}", role, deviceId);
524 applyRole(deviceId, role);
525 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700526
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700527 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
528 deviceDescription);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200529 if (portConfig != null) {
530 //updating the ports if configration exists
531 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
532 .collect(Collectors.toList());
533 complete.addAll(portConfig.portDescriptions());
534 List<PortDescription> portDescriptions = complete.stream()
535 .map(e -> applyAllPortOps(deviceId, e))
536 .collect(Collectors.toList());
537 store.updatePorts(provider().id(), deviceId, portDescriptions);
538 }
539
helenyrwufd296b62016-06-22 17:43:02 -0700540 if (deviceDescription.isDefaultAvailable()) {
541 log.info("Device {} connected", deviceId);
542 } else {
543 log.info("Device {} registered", deviceId);
544 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200545
tom80c0e5e2014-09-08 18:08:58 -0700546 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700547 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700548 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700549 }
tomd3097b02014-08-26 10:40:29 -0700550 }
551
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700552 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
553 if (desc.isEnabled() != enabled) {
554 return new DefaultPortDescription(desc.portNumber(),
555 enabled,
556 desc.type(),
557 desc.portSpeed(),
558 desc.annotations());
559 }
560 return desc;
561 }
562
tomd3097b02014-08-26 10:40:29 -0700563 @Override
564 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700565 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700566 checkValidity();
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800567 deviceLocalStatus.put(deviceId, new LocalStatus(false, DateTime.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700568 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700569
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700570 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
571 .map(desc -> ensurePortEnabledState(desc, false))
572 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300573
alshabibafc514a2014-12-01 14:44:05 -0800574 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700575 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700576 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700577 post(store.markOffline(deviceId));
578 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700579 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700580 log.warn("Failed to mark {} offline", deviceId);
581 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800582 // but if I was the last STANDBY connection, etc. and no one else
583 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700584 // temporarily request for Master Role and mark offline.
585
samuele1fa7322015-07-14 16:35:16 +0800586 //there are times when this node will correctly have mastership, BUT
587 //that isn't reflected in the ClockManager before the device disconnects.
588 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700589
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700590 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800591 // Consider revising store API to handle this scenario.
592 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700593 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800594 MastershipTerm term = termService.getMastershipTerm(deviceId);
595 // TODO: Move this type of check inside device clock manager, etc.
596 if (term != null && localNodeId.equals(term.master())) {
597 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800598 post(store.markOffline(deviceId));
599 } else {
600 log.info("Failed again marking {} offline. {}", deviceId, role);
601 }
602 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700603 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700604 try {
samuele1fa7322015-07-14 16:35:16 +0800605 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700606 mastershipService.relinquishMastership(deviceId).get();
607 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800608 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700609 Thread.currentThread().interrupt();
610 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800611 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700612 }
tom0efbb1d2014-09-09 11:54:28 -0700613 }
tomd3097b02014-08-26 10:40:29 -0700614 }
615
616 @Override
alshabibb7b40632014-09-28 21:30:00 -0700617 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700618 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700619 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700620 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700621 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700622 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700623 // Never been a master for this device
624 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800625 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700626 return;
627 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200628 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
629 if (portConfig != null) {
630 //updating the ports if configration exists
631 portDescriptions.addAll(portConfig.portDescriptions());
632 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700633 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700634 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700635 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700636 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800637 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800638 if (events != null) {
639 for (DeviceEvent event : events) {
640 post(event);
641 }
tom32f66842014-08-27 19:27:47 -0700642 }
tomd3097b02014-08-26 10:40:29 -0700643 }
644
645 @Override
alshabibb7b40632014-09-28 21:30:00 -0700646 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700647 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700648 checkNotNull(deviceId, DEVICE_ID_NULL);
649 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700650 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700651
Madan Jampani565a66a2015-07-25 17:01:13 -0700652 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700653 // Never been a master for this device
654 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700655 log.trace("Ignoring {} port update on standby node. {}", deviceId,
656 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700657 return;
658 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700659 Device device = getDevice(deviceId);
660 if (device == null) {
661 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530662 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700663 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200664 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700665 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700666 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700667 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700668 deviceId,
669 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700670 portDescription = ensurePortEnabledState(storedPortDesc,
671 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300672 }
673
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700674 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800675 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700676 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700677 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700678 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700679 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700680 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700681 }
tomd3097b02014-08-26 10:40:29 -0700682 }
tom3f2bbd72014-09-24 12:07:58 -0700683
684 @Override
Michal Machce774332017-01-25 11:02:55 +0100685 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
686
687 checkNotNull(deviceId, DEVICE_ID_NULL);
688 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
689 checkValidity();
690
691 if (!mastershipService.isLocalMaster(deviceId)) {
692 // Never been a master for this device
693 // any update will be ignored.
694 log.trace("Ignoring {} port update on standby node. {}", deviceId,
695 basePortDescription);
696 return;
697 }
698
699 Device device = getDevice(deviceId);
700 if (device == null) {
701 log.trace("Device not found: {}", deviceId);
702 }
703
704 PortDescription newPortDescription = new DefaultPortDescription(basePortDescription.portNumber(),
705 basePortDescription.isEnabled(),
706 true,
707 basePortDescription.type(),
708 basePortDescription.portSpeed(),
709 basePortDescription.annotations());
710 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
711 deviceId,
712 newPortDescription);
713 if (event != null) {
714 log.info("Device {} port {} status changed", deviceId, event.port().number());
715 post(event);
716 }
717 }
718
719 @Override
samuele1fa7322015-07-14 16:35:16 +0800720 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700721 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700722 // Several things can happen here:
723 // 1. request and response match
724 // 2. request and response don't match
725 // 3. MastershipRole and requested match (and 1 or 2 are true)
726 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
727 //
728 // 2, 4, and 3 with case 2 are failure modes.
729
tom3f2bbd72014-09-24 12:07:58 -0700730 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700731
Madan Jampanif2af7712015-05-29 18:43:52 -0700732 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700733 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700734
735 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800736 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530737 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700738 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700739 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700740 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700741
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700742 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800743 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700744 return;
745 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800746 log.warn("Role mismatch on {}. set to {}, but store demands {}",
747 deviceId, response, mastershipService.getLocalRole(deviceId));
748 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700749 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800750 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800751 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700752 }
753 } else {
754 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800755 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700756 if (response == MastershipRole.MASTER) {
757 mastershipService.relinquishMastership(deviceId);
758 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800759 //final Device device = getDevice(deviceId);
760 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700761 }
762 }
tom3f2bbd72014-09-24 12:07:58 -0700763 }
sangho538108b2015-04-08 14:29:20 -0700764
765 @Override
samuele1fa7322015-07-14 16:35:16 +0800766 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700767 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700768 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700769 checkValidity();
770
samuele1fa7322015-07-14 16:35:16 +0800771 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
772 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700773 post(event);
774 }
tomd3097b02014-08-26 10:40:29 -0700775 }
tom32f66842014-08-27 19:27:47 -0700776
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700777 // by default allowed, otherwise check flag
778 private boolean isAllowed(BasicDeviceConfig cfg) {
779 return (cfg == null || cfg.isAllowed());
780 }
781
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800782 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700783
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800784 /**
785 * Apply role to device and send probe if MASTER.
786 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700787 * @param deviceId device identifier
788 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800789 * @return true if the request was sent to provider
790 */
791 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
792 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800793 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700794 return true;
795 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700796
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800797 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800798 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800799 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800800 return false;
801 }
802 provider.roleChanged(deviceId, newRole);
803
804 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800805 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800806 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800807 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800808 }
809 return true;
810 }
811
812 /**
813 * Reaasert role for specified device connected to this node.
814 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700815 * @param did device identifier
816 * @param nextRole role to apply. If NONE is specified,
817 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800818 */
samuele1fa7322015-07-14 16:35:16 +0800819 private void reassertRole(final DeviceId did,
820 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800821
Jordan Halterman980a8c12017-09-22 18:01:19 -0700822 switch (nextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700823 case MASTER:
824 final Device device = getDevice(did);
825 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700826 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700827 }
828 // TODO: should apply role only if there is mismatch
Jordan Halterman980a8c12017-09-22 18:01:19 -0700829 log.debug("Applying role {} to {}", nextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700830 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman980a8c12017-09-22 18:01:19 -0700831 log.warn("Unsuccessful applying role {} to {}", nextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700832 // immediately failed to apply role
833 mastershipService.relinquishMastership(did);
834 // FIXME disconnect?
835 }
836 break;
837 case STANDBY:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700838 log.debug("Applying role {} to {}", nextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700839 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman980a8c12017-09-22 18:01:19 -0700840 log.warn("Unsuccessful applying role {} to {}", nextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700841 // immediately failed to apply role
842 mastershipService.relinquishMastership(did);
843 // FIXME disconnect?
844 }
845 break;
846 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700847 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700848 default:
849 // should never reach here
850 log.error("You didn't see anything. I did not exist.");
851 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800852 }
853 }
854
Madan Jampani328371d2015-05-29 14:06:27 -0700855 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700856 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700857 // Don't care if backup list changed.
858 return;
859 }
Madan Jampani328371d2015-05-29 14:06:27 -0700860 final DeviceId did = event.subject();
861
862 // myRole suggested by MastershipService
863 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700864 if (event.type() == MastershipEvent.Type.SUSPENDED) {
865 myNextRole = NONE; // FIXME STANDBY OR NONE?
866 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700867 // confirm latest info
868 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800869 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700870 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700871 myNextRole = MASTER;
872 } else {
873 myNextRole = STANDBY;
874 }
875 } else if (event.roleInfo().backups().contains(localNodeId)) {
876 myNextRole = STANDBY;
877 } else {
878 myNextRole = NONE;
879 }
880
Madan Jampani328371d2015-05-29 14:06:27 -0700881 final boolean isReachable = isReachable(did);
882 if (!isReachable) {
883 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800884 if (mastershipService.getLocalRole(did) == NONE) {
885 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700886 + "but this node cannot reach the device "
887 + "and role is already None. Ignoring request.",
888 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800889 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700890 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700891 + "but this node cannot reach the device. "
892 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800893 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700894 mastershipService.relinquishMastership(did);
895 }
896 return;
897 }
898
899 // device is connected to this node:
900 if (store.getDevice(did) != null) {
901 reassertRole(did, myNextRole);
902 } else {
903 log.debug("Device is not yet/no longer in the store: {}", did);
904 }
905 }
906
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800907 // Intercepts mastership events
908 private class InternalMastershipListener implements MastershipListener {
909
tomb41d1ac2014-09-24 01:51:24 -0700910 @Override
911 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800912 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700913 try {
914 handleMastershipEvent(event);
915 } catch (Exception e) {
916 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700917 }
Madan Jampani328371d2015-05-29 14:06:27 -0700918 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700919 }
tomb41d1ac2014-09-24 01:51:24 -0700920 }
tomf80c9722014-09-24 14:49:18 -0700921
922 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700923 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700924 @Override
925 public void notify(DeviceEvent event) {
926 post(event);
927 }
928 }
samuel738dfaf2015-07-11 11:08:57 +0800929
930 @Override
931 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900932 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800933 Set<Device> results = new HashSet<>();
934 Iterable<Device> devices = store.getDevices();
935 if (devices != null) {
936 devices.forEach(d -> {
937 if (type.equals(d.type())) {
938 results.add(d);
939 }
940 });
941 }
942 return results;
943 }
944
945 @Override
946 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900947 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800948 Set<Device> results = new HashSet<>();
949 Iterable<Device> availableDevices = store.getAvailableDevices();
950 if (availableDevices != null) {
951 availableDevices.forEach(d -> {
952 if (type.equals(d.type())) {
953 results.add(d);
954 }
955 });
956 }
957 return results;
958 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700959
960 private class InternalNetworkConfigListener implements NetworkConfigListener {
961 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700962 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700963 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
964 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
965 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200966 || portOpsIndex.containsKey(event.configClass())
967 || event.configClass().equals(PortDescriptionsConfig.class));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700968 }
969
970 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700971 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700972 DeviceEvent de = null;
973 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800974 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -0700975 DeviceId did = (DeviceId) event.subject();
976 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700977 BasicDeviceConfig cfg =
978 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700979
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700980 if (!isAllowed(cfg)) {
981 kickOutBadDevice(did);
982 } else {
983 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700984 DeviceDescription desc =
985 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700986 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -0700987 if (desc != null && dp != null) {
988 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700989 }
990 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -0700991 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
992 DeviceId did = (DeviceId) event.subject();
993 DeviceProvider dp = getProvider(did);
994 if (!event.config().isPresent() ||
995 getDevice(did) == null || dp == null) {
996 // sanity check failed, ignore
997 return;
998 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200999 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001000 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001001 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1002 .collect(Collectors.toList());
1003 complete.addAll(portConfig.portDescriptions());
1004 store.updatePorts(dp.id(), did, complete);
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001005 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001006 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001007 DeviceId did = cpt.deviceId();
1008 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001009
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001010 // Note: assuming PortOperator can modify existing port,
1011 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001012 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001013 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1014 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001015 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001016 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001017 }
1018
1019 if (de != null) {
1020 post(de);
1021 }
1022 }
1023
Simon Hunt8f60ff82017-04-24 17:19:30 -07001024 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001025 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001026 Device badDevice = getDevice(deviceId);
1027 if (badDevice != null) {
1028 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001029 }
1030 }
1031 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001032
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001033 @Override
1034 @SafeVarargs
1035 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001036 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001037 checkNotNull(portOp);
1038
1039 portOp.bindService(networkConfigService);
1040
1041 // update both portOpsIndex and portOps
1042 synchronized (portOpsIndex) {
1043 for (Class<? extends Config<ConnectPoint>> config : configs) {
1044 portOpsIndex.put(config, portOp);
1045 }
1046
1047 portOps.add(portOp);
1048 }
1049
1050 // TODO: Should we be applying to all existing Ports?
1051 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001052 .map(Device::id)
1053 .filter(mastershipService::isLocalMaster)
1054 // for each locally managed Device, update all port descriptions
1055 .map(did -> {
1056 ProviderId pid = Optional.ofNullable(getProvider(did))
1057 .map(Provider::id)
1058 .orElse(null);
1059 if (pid == null) {
1060 log.warn("Provider not found for {}", did);
1061 return ImmutableList.<DeviceEvent>of();
1062 }
1063 List<PortDescription> pds
1064 = store.getPortDescriptions(pid, did)
1065 .map(pdesc -> applyAllPortOps(did, pdesc))
1066 .collect(Collectors.toList());
1067 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001068 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001069 // ..and port port update event if necessary
1070 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001071 }
1072
1073 @Override
1074 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1075 checkNotNull(portOp);
1076
1077
1078 // remove all portOp
1079 synchronized (portOpsIndex) {
1080 portOps.remove(portOp);
1081
1082 // had to do this since COWArrayList iterator doesn't support remove
1083 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1084 }
1085
1086 }
1087
1088 /**
1089 * Merges the appropriate PortConfig with the description.
1090 *
1091 * @param did ID of the Device where the port is attached
1092 * @param desc {@link PortDescription}
1093 * @return merged {@link PortDescription}
1094 */
1095 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1096 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1097 }
1098
1099 /**
1100 * Merges the appropriate PortConfig with the description.
1101 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001102 * @param cpt ConnectPoint where the port is attached
1103 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001104 * @return merged {@link PortDescription}
1105 */
1106 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1107 PortDescription work = desc;
1108 for (PortConfigOperator portOp : portOps) {
1109 work = portOp.combine(cpt, work);
1110 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001111 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001112 }
1113
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001114 /**
1115 * Port Enable/Disable message sent to the device's MASTER node.
1116 */
1117 private class InternalPortUpDownEvent {
1118 private final DeviceId deviceId;
1119 private final PortNumber portNumber;
1120 private final boolean enable;
1121
1122 protected InternalPortUpDownEvent(
1123 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1124 this.deviceId = deviceId;
1125 this.portNumber = portNumber;
1126 this.enable = enable;
1127 }
1128
1129 public DeviceId deviceId() {
1130 return deviceId;
1131 }
1132 public PortNumber portNumber() {
1133 return portNumber;
1134 }
1135 public boolean isEnable() {
1136 return enable;
1137 }
1138
1139 protected InternalPortUpDownEvent() {
1140 this.deviceId = null;
1141 this.portNumber = null;
1142 this.enable = false;
1143 }
1144 }
tomd3097b02014-08-26 10:40:29 -07001145}