blob: d2b25364ee7be208875713d6e0092accb97258be [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
466 reassertRole(deviceId, NONE);
467 }
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
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800822 MastershipRole myNextRole = nextRole;
823 if (myNextRole == NONE) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800824 try {
825 mastershipService.requestRoleFor(did).get();
826 MastershipTerm term = termService.getMastershipTerm(did);
827 if (term != null && localNodeId.equals(term.master())) {
828 myNextRole = MASTER;
829 } else {
830 myNextRole = STANDBY;
831 }
832 } catch (InterruptedException e) {
833 Thread.currentThread().interrupt();
834 log.error("Interrupted waiting for Mastership", e);
835 } catch (ExecutionException e) {
836 log.error("Encountered an error waiting for Mastership", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800837 }
838 }
839
840 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700841 case MASTER:
842 final Device device = getDevice(did);
843 if ((device != null) && !isAvailable(did)) {
helenyrwufd296b62016-06-22 17:43:02 -0700844 store.markOnline(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700845 }
846 // TODO: should apply role only if there is mismatch
847 log.debug("Applying role {} to {}", myNextRole, did);
848 if (!applyRoleAndProbe(did, MASTER)) {
849 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
850 // immediately failed to apply role
851 mastershipService.relinquishMastership(did);
852 // FIXME disconnect?
853 }
854 break;
855 case STANDBY:
856 log.debug("Applying role {} to {}", myNextRole, did);
857 if (!applyRoleAndProbe(did, STANDBY)) {
858 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
859 // immediately failed to apply role
860 mastershipService.relinquishMastership(did);
861 // FIXME disconnect?
862 }
863 break;
864 case NONE:
865 default:
866 // should never reach here
867 log.error("You didn't see anything. I did not exist.");
868 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800869 }
870 }
871
Madan Jampani328371d2015-05-29 14:06:27 -0700872 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700873 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700874 // Don't care if backup list changed.
875 return;
876 }
Madan Jampani328371d2015-05-29 14:06:27 -0700877 final DeviceId did = event.subject();
878
879 // myRole suggested by MastershipService
880 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700881 if (event.type() == MastershipEvent.Type.SUSPENDED) {
882 myNextRole = NONE; // FIXME STANDBY OR NONE?
883 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700884 // confirm latest info
885 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800886 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700887 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700888 myNextRole = MASTER;
889 } else {
890 myNextRole = STANDBY;
891 }
892 } else if (event.roleInfo().backups().contains(localNodeId)) {
893 myNextRole = STANDBY;
894 } else {
895 myNextRole = NONE;
896 }
897
Madan Jampani328371d2015-05-29 14:06:27 -0700898 final boolean isReachable = isReachable(did);
899 if (!isReachable) {
900 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800901 if (mastershipService.getLocalRole(did) == NONE) {
902 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700903 + "but this node cannot reach the device "
904 + "and role is already None. Ignoring request.",
905 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800906 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700907 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700908 + "but this node cannot reach the device. "
909 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800910 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700911 mastershipService.relinquishMastership(did);
912 }
913 return;
914 }
915
916 // device is connected to this node:
917 if (store.getDevice(did) != null) {
918 reassertRole(did, myNextRole);
919 } else {
920 log.debug("Device is not yet/no longer in the store: {}", did);
921 }
922 }
923
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800924 // Intercepts mastership events
925 private class InternalMastershipListener implements MastershipListener {
926
tomb41d1ac2014-09-24 01:51:24 -0700927 @Override
928 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800929 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700930 try {
931 handleMastershipEvent(event);
932 } catch (Exception e) {
933 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700934 }
Madan Jampani328371d2015-05-29 14:06:27 -0700935 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700936 }
tomb41d1ac2014-09-24 01:51:24 -0700937 }
tomf80c9722014-09-24 14:49:18 -0700938
939 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700940 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700941 @Override
942 public void notify(DeviceEvent event) {
943 post(event);
944 }
945 }
samuel738dfaf2015-07-11 11:08:57 +0800946
947 @Override
948 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900949 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800950 Set<Device> results = new HashSet<>();
951 Iterable<Device> devices = store.getDevices();
952 if (devices != null) {
953 devices.forEach(d -> {
954 if (type.equals(d.type())) {
955 results.add(d);
956 }
957 });
958 }
959 return results;
960 }
961
962 @Override
963 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900964 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800965 Set<Device> results = new HashSet<>();
966 Iterable<Device> availableDevices = store.getAvailableDevices();
967 if (availableDevices != null) {
968 availableDevices.forEach(d -> {
969 if (type.equals(d.type())) {
970 results.add(d);
971 }
972 });
973 }
974 return results;
975 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700976
977 private class InternalNetworkConfigListener implements NetworkConfigListener {
978 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700979 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700980 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
981 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
982 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200983 || portOpsIndex.containsKey(event.configClass())
984 || event.configClass().equals(PortDescriptionsConfig.class));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700985 }
986
987 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700988 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700989 DeviceEvent de = null;
990 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -0800991 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -0700992 DeviceId did = (DeviceId) event.subject();
993 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -0700994 BasicDeviceConfig cfg =
995 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700996
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700997 if (!isAllowed(cfg)) {
998 kickOutBadDevice(did);
999 } else {
1000 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001001 DeviceDescription desc =
1002 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001003 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001004 if (desc != null && dp != null) {
1005 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001006 }
1007 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001008 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1009 DeviceId did = (DeviceId) event.subject();
1010 DeviceProvider dp = getProvider(did);
1011 if (!event.config().isPresent() ||
1012 getDevice(did) == null || dp == null) {
1013 // sanity check failed, ignore
1014 return;
1015 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001016 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001017 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001018 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1019 .collect(Collectors.toList());
1020 complete.addAll(portConfig.portDescriptions());
1021 store.updatePorts(dp.id(), did, complete);
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001022 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001023 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001024 DeviceId did = cpt.deviceId();
1025 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001026
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001027 // Note: assuming PortOperator can modify existing port,
1028 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001029 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001030 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1031 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001032 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001033 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001034 }
1035
1036 if (de != null) {
1037 post(de);
1038 }
1039 }
1040
Simon Hunt8f60ff82017-04-24 17:19:30 -07001041 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001042 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001043 Device badDevice = getDevice(deviceId);
1044 if (badDevice != null) {
1045 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001046 }
1047 }
1048 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001049
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001050 @Override
1051 @SafeVarargs
1052 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001053 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001054 checkNotNull(portOp);
1055
1056 portOp.bindService(networkConfigService);
1057
1058 // update both portOpsIndex and portOps
1059 synchronized (portOpsIndex) {
1060 for (Class<? extends Config<ConnectPoint>> config : configs) {
1061 portOpsIndex.put(config, portOp);
1062 }
1063
1064 portOps.add(portOp);
1065 }
1066
1067 // TODO: Should we be applying to all existing Ports?
1068 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001069 .map(Device::id)
1070 .filter(mastershipService::isLocalMaster)
1071 // for each locally managed Device, update all port descriptions
1072 .map(did -> {
1073 ProviderId pid = Optional.ofNullable(getProvider(did))
1074 .map(Provider::id)
1075 .orElse(null);
1076 if (pid == null) {
1077 log.warn("Provider not found for {}", did);
1078 return ImmutableList.<DeviceEvent>of();
1079 }
1080 List<PortDescription> pds
1081 = store.getPortDescriptions(pid, did)
1082 .map(pdesc -> applyAllPortOps(did, pdesc))
1083 .collect(Collectors.toList());
1084 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001085 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001086 // ..and port port update event if necessary
1087 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001088 }
1089
1090 @Override
1091 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1092 checkNotNull(portOp);
1093
1094
1095 // remove all portOp
1096 synchronized (portOpsIndex) {
1097 portOps.remove(portOp);
1098
1099 // had to do this since COWArrayList iterator doesn't support remove
1100 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1101 }
1102
1103 }
1104
1105 /**
1106 * Merges the appropriate PortConfig with the description.
1107 *
1108 * @param did ID of the Device where the port is attached
1109 * @param desc {@link PortDescription}
1110 * @return merged {@link PortDescription}
1111 */
1112 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1113 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1114 }
1115
1116 /**
1117 * Merges the appropriate PortConfig with the description.
1118 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001119 * @param cpt ConnectPoint where the port is attached
1120 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001121 * @return merged {@link PortDescription}
1122 */
1123 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1124 PortDescription work = desc;
1125 for (PortConfigOperator portOp : portOps) {
1126 work = portOp.combine(cpt, work);
1127 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001128 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001129 }
1130
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001131 /**
1132 * Port Enable/Disable message sent to the device's MASTER node.
1133 */
1134 private class InternalPortUpDownEvent {
1135 private final DeviceId deviceId;
1136 private final PortNumber portNumber;
1137 private final boolean enable;
1138
1139 protected InternalPortUpDownEvent(
1140 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1141 this.deviceId = deviceId;
1142 this.portNumber = portNumber;
1143 this.enable = enable;
1144 }
1145
1146 public DeviceId deviceId() {
1147 return deviceId;
1148 }
1149 public PortNumber portNumber() {
1150 return portNumber;
1151 }
1152 public boolean isEnable() {
1153 return enable;
1154 }
1155
1156 protected InternalPortUpDownEvent() {
1157 this.deviceId = null;
1158 this.portNumber = null;
1159 this.enable = false;
1160 }
1161 }
tomd3097b02014-08-26 10:40:29 -07001162}