blob: c7a31efa8f3c8c5b614c45b2a8cd9ded78a4ccc8 [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;
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +020019import com.google.common.collect.Lists;
Simon Huntffbad3b2017-05-16 15:37:51 -070020import com.google.common.collect.Maps;
21import com.google.common.collect.Multimap;
pier388ec252020-04-15 20:53:14 +020022import com.google.common.util.concurrent.Futures;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070023import org.onlab.util.KryoNamespace;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070024import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080025import org.onosproject.cluster.ClusterService;
26import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.mastership.MastershipEvent;
28import org.onosproject.mastership.MastershipListener;
29import org.onosproject.mastership.MastershipService;
30import org.onosproject.mastership.MastershipTerm;
31import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070032import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080034import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.net.DeviceId;
36import org.onosproject.net.MastershipRole;
37import org.onosproject.net.Port;
38import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070039import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030040import org.onosproject.net.config.NetworkConfigEvent;
41import org.onosproject.net.config.NetworkConfigListener;
42import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070043import org.onosproject.net.config.PortConfigOperator;
44import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030045import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090046import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080047import org.onosproject.net.config.basics.PortAnnotationConfig;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080048import org.onosproject.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.device.DefaultPortDescription;
50import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.device.DeviceDescription;
52import org.onosproject.net.device.DeviceEvent;
53import org.onosproject.net.device.DeviceListener;
54import org.onosproject.net.device.DeviceProvider;
55import org.onosproject.net.device.DeviceProviderRegistry;
56import org.onosproject.net.device.DeviceProviderService;
57import org.onosproject.net.device.DeviceService;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
60import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070061import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030062import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080064import org.onosproject.net.provider.Provider;
65import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070066import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
67import org.onosproject.store.cluster.messaging.MessageSubject;
68import org.onosproject.store.serializers.KryoNamespaces;
69import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080070import org.onosproject.upgrade.UpgradeService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070071import org.osgi.service.component.annotations.Activate;
72import org.osgi.service.component.annotations.Component;
73import org.osgi.service.component.annotations.Deactivate;
74import org.osgi.service.component.annotations.Reference;
75import org.osgi.service.component.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070076import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070077
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070078import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070079import java.util.Collection;
80import java.util.HashSet;
81import java.util.List;
82import java.util.Map;
83import java.util.Objects;
84import java.util.Optional;
85import java.util.Set;
86import java.util.concurrent.CompletableFuture;
87import java.util.concurrent.ConcurrentHashMap;
88import java.util.concurrent.CopyOnWriteArrayList;
89import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070090import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070091import java.util.concurrent.ScheduledExecutorService;
92import java.util.concurrent.TimeUnit;
93import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080094
Ray Milkey9ef22232016-07-14 12:42:37 -070095import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070096import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070097import static com.google.common.collect.Multimaps.newListMultimap;
98import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070099import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -0700100import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
101import static org.onlab.util.Tools.groupedThreads;
102import static org.onosproject.net.MastershipRole.MASTER;
103import static org.onosproject.net.MastershipRole.NONE;
104import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700105import static org.onosproject.security.AppGuard.checkPermission;
106import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
107import static org.slf4j.LoggerFactory.getLogger;
108
tomd3097b02014-08-26 10:40:29 -0700109/**
tome4729872014-09-23 00:37:37 -0700110 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700111 */
Ray Milkey86ad7bb2018-09-27 12:32:28 -0700112@Component(immediate = true,
113 service = {DeviceService.class, DeviceAdminService.class,
114 DeviceProviderRegistry.class, PortConfigOperatorRegistry.class })
tom41a2c5f2014-09-19 09:20:35 -0700115public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700116 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700117 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700118
tome5ec3fd2014-09-04 15:18:06 -0700119 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
120 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
121 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
122 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700123 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700124 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700125
tom5f38b3a2014-08-27 23:50:54 -0700126 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700127
alshabib339a3d92014-09-26 17:54:32 -0700128 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700129
tomc78acee2014-09-24 15:16:55 -0700130 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700131 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700132
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800133 private ScheduledExecutorService backgroundService;
134
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700135 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
136
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom41a2c5f2014-09-19 09:20:35 -0700138 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700139
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tomb41d1ac2014-09-24 01:51:24 -0700141 protected ClusterService clusterService;
142
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700143 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700144 protected MastershipService mastershipService;
145
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700146 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700147 protected MastershipTermService termService;
148
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800150 protected UpgradeService upgradeService;
151
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700152 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700153 protected NetworkConfigService networkConfigService;
154
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700156 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700157
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700158 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700159 /**
160 * List of all registered PortConfigOperator.
161 */
162 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
163
164 /**
165 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
166 */
167 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700168 = synchronizedListMultimap(
169 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700170
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800171 // not part of portOps. must be executed at the end
172 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900173 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800174
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700175 private static final MessageSubject PORT_UPDOWN_SUBJECT =
176 new MessageSubject("port-updown-req");
177
178 private static final Serializer SERIALIZER = Serializer.using(
179 KryoNamespace.newBuilder()
180 .register(KryoNamespaces.API)
181 .register(InternalPortUpDownEvent.class)
182 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
183 .build("DeviceManager"));
184
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800185 /**
186 * Local storage for connectivity status of devices.
187 */
188 private class LocalStatus {
189 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700190 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800191
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700192 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800193 connected = b;
194 dateTime = now;
195 }
196 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700197
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800198 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
199 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700200
tomd3097b02014-08-26 10:40:29 -0700201 @Activate
202 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800203 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900204 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800205 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
206
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800207 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700208 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700209 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800210
tomf80c9722014-09-24 14:49:18 -0700211 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700212 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700213 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700214 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800215
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700216 backgroundService.scheduleWithFixedDelay(() -> {
217 try {
218 mastershipCheck();
219 } catch (Exception e) {
220 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800221 }
222 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700223
224 portReqeustExecutor = newSingleThreadExecutor();
225
226 communicationService.<InternalPortUpDownEvent>addSubscriber(
227 PORT_UPDOWN_SUBJECT,
228 SERIALIZER::decode,
229 this::handlePortRequest,
230 portReqeustExecutor);
231
tomd3097b02014-08-26 10:40:29 -0700232 log.info("Started");
233 }
234
235 @Deactivate
236 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800237 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700238 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700239 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700240 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700241 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700242 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
243 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700244 log.info("Stopped");
245 }
246
247 @Override
tomad2d2092014-09-06 23:24:20 -0700248 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900249 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700250 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700251 }
252
253 @Override
mskala32000d32017-07-14 16:27:06 +0200254 public int getAvailableDeviceCount() {
255 checkPermission(DEVICE_READ);
256 return store.getAvailableDeviceCount();
257 }
258
259 @Override
tom32f66842014-08-27 19:27:47 -0700260 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900261 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700262 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700263 }
264
tom32f66842014-08-27 19:27:47 -0700265 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800266 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900267 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800268 return store.getAvailableDevices();
269 }
270
271 @Override
tom32f66842014-08-27 19:27:47 -0700272 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900273 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700274 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700275 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700276 }
277
278 @Override
tomad2d2092014-09-06 23:24:20 -0700279 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900280 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700281 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700282 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700283 }
284
285 @Override
tom32f66842014-08-27 19:27:47 -0700286 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900287 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700288 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700289 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700290 }
291
292 @Override
sangho538108b2015-04-08 14:29:20 -0700293 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900294 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700295 checkNotNull(deviceId, DEVICE_ID_NULL);
296 return store.getPortStatistics(deviceId);
297 }
298
299 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200300 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900301 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200302 checkNotNull(deviceId, DEVICE_ID_NULL);
303 return store.getPortDeltaStatistics(deviceId);
304 }
305
306 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530307 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
308 checkPermission(DEVICE_READ);
309 checkNotNull(deviceId, DEVICE_ID_NULL);
310 checkNotNull(portNumber, PORT_NUMBER_NULL);
311 return store.getStatisticsForPort(deviceId, portNumber);
312 }
313
314 @Override
315 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
316 checkPermission(DEVICE_READ);
317 checkNotNull(deviceId, DEVICE_ID_NULL);
318 checkNotNull(portNumber, PORT_NUMBER_NULL);
319 return store.getDeltaStatisticsForPort(deviceId, portNumber);
320 }
321
322 @Override
tom32f66842014-08-27 19:27:47 -0700323 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900324 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700325 checkNotNull(deviceId, DEVICE_ID_NULL);
326 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700327 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700328 }
329
330 @Override
tomff7eb7c2014-09-08 12:49:03 -0700331 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900332 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900333
tomff7eb7c2014-09-08 12:49:03 -0700334 checkNotNull(deviceId, DEVICE_ID_NULL);
335 return store.isAvailable(deviceId);
336 }
337
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800338 @Override
339 public String localStatus(DeviceId deviceId) {
340 LocalStatus ls = deviceLocalStatus.get(deviceId);
341 if (ls == null) {
342 return "No Record";
343 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700344 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800345 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
346 }
347
Palash Kala0d817b02018-03-23 18:09:45 +0900348 private boolean isLocallyConnected(DeviceId deviceId) {
349 LocalStatus ls = deviceLocalStatus.get(deviceId);
350 if (ls == null) {
351 return false;
352 }
353 return ls.connected;
354 }
355
Ray Milkey054e23d2018-03-22 13:37:11 -0700356 @Override
357 public long getLastUpdatedInstant(DeviceId deviceId) {
358 LocalStatus ls = deviceLocalStatus.get(deviceId);
359 if (ls == null) {
360 return 0;
361 }
362 return ls.dateTime.toEpochMilli();
363 }
364
Palash Kala0d817b02018-03-23 18:09:45 +0900365 // Check a device for control channel connectivity
366 // and changes local-status appropriately.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700367 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800368 if (deviceId == null) {
369 return false;
370 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700371 DeviceProvider provider = getProvider(deviceId);
372 if (provider != null) {
Palash Kala0d817b02018-03-23 18:09:45 +0900373 boolean reachable = provider.isReachable(deviceId);
374 if (reachable && !isLocallyConnected(deviceId)) {
375 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
376 } else if (!reachable && isLocallyConnected(deviceId)) {
377 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
378 }
379 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700380 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800381 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700382 return false;
383 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700384 }
385
tome5ec3fd2014-09-04 15:18:06 -0700386 @Override
387 public void removeDevice(DeviceId deviceId) {
388 checkNotNull(deviceId, DEVICE_ID_NULL);
389 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700390 if (event != null) {
391 log.info("Device {} administratively removed", deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700392 }
tome5ec3fd2014-09-04 15:18:06 -0700393 }
394
Thomas Vachuska811ea2b2020-02-11 10:20:10 -0800395 @Override
396 public void removeDevicePorts(DeviceId deviceId) {
397 checkNotNull(deviceId, DEVICE_ID_NULL);
398 if (isAvailable(deviceId)) {
399 log.debug("Cannot remove ports of device {} while it is available.", deviceId);
400 return;
401 }
402
403 List<PortDescription> portDescriptions = ImmutableList.of();
404 List<DeviceEvent> events = store.updatePorts(getProvider(deviceId).id(),
405 deviceId, portDescriptions);
406 if (events != null) {
407 for (DeviceEvent event : events) {
408 post(event);
409 }
410 }
411 }
412
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700413 private void handlePortRequest(InternalPortUpDownEvent event) {
414 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700415 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon0bd777c2021-01-01 14:23:29 +0000416 checkNotNull(event.portNumber(), PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700417 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
418 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
419 }
420
421 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
422 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700423 DeviceProvider provider = getProvider(deviceId);
424 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700425 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700426 portNumber, deviceId,
427 (enable) ? "UP" : "DOWN");
428 provider.changePortState(deviceId, portNumber, enable);
429 } else {
430 log.warn("Provider not found for {}", deviceId);
431 }
432 }
433
434 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700435 public void changePortState(DeviceId deviceId, PortNumber portNumber,
436 boolean enable) {
437 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon0bd777c2021-01-01 14:23:29 +0000438 checkNotNull(portNumber, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700439 NodeId masterId = mastershipService.getMasterFor(deviceId);
440
Ray Milkey4ef245e2018-05-10 15:41:16 -0700441 if (masterId == null) {
442 // No master found; device is offline
443 log.info("No master found for port state change for {}", deviceId);
444 return;
445 }
446
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700447 if (!masterId.equals(localNodeId)) {
448 //Send the request to the master node for the device
449 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
450 deviceId, masterId);
451 communicationService.unicast(
452 new InternalPortUpDownEvent(deviceId, portNumber, enable),
453 PORT_UPDOWN_SUBJECT,
454 SERIALIZER::encode,
455 masterId).whenComplete((r, error) -> {
456 if (error != null) {
457 log.warn("Failed to send packet-updown-req to {}", masterId, error);
458 }
459 });
460 } else {
461 changePortStateAtMaster(deviceId, portNumber, enable);
462 }
463 }
464
465 @Override
samuele1fa7322015-07-14 16:35:16 +0800466 protected DeviceProviderService createProviderService(
467 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700468 return new InternalDeviceProviderService(provider);
469 }
470
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800471 /**
472 * Checks if all the reachable devices have a valid mastership role.
473 */
474 private void mastershipCheck() {
475 log.debug("Checking mastership");
476 for (Device device : getDevices()) {
477 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700478 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
479 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800480 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700481 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700482 // can't be master if device is not reachable
483 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700484 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100485 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700486 post(store.markOffline(deviceId));
487 }
helenyrwufd296b62016-06-22 17:43:02 -0700488 //relinquish master role and ability to be backup.
489 mastershipService.relinquishMastership(deviceId).get();
490 } catch (InterruptedException e) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700491 log.warn("Interrupted while relinquishing role for {}", deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700492 Thread.currentThread().interrupt();
493 } catch (ExecutionException e) {
494 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
495 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530496 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100497 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530498 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100499 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800500 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100501 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800502 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
503 roleFuture.thenAccept(role -> {
504 MastershipTerm term = termService.getMastershipTerm(deviceId);
505 if (term != null && localNodeId.equals(term.master())) {
506 log.info("Marking unreachable device {} offline", deviceId);
507 post(store.markOffline(deviceId));
508 } else {
509 log.info("Failed marking {} offline. {}", deviceId, role);
510 }
511 mastershipService.relinquishMastership(deviceId);
512 });
513 }
helenyrwufd296b62016-06-22 17:43:02 -0700514 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800515 continue;
516 }
517
Jordan Halterman368bd3d2019-01-04 12:45:57 -0800518 // If this node is the master, ensure the device is marked online.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800519 if (myRole == MASTER && canMarkOnline(device)) {
Jordan Halterman368bd3d2019-01-04 12:45:57 -0800520 post(store.markOnline(deviceId));
521 }
522
Ray Milkeyc7104672016-08-31 12:04:34 -0700523 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800524 continue;
525 }
526
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700527 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800528
529 // isReachable but was not MASTER or STANDBY, get a role and apply
530 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800531 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800532 }
533 }
534
tomd3097b02014-08-26 10:40:29 -0700535 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700536 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700537 extends AbstractProviderService<DeviceProvider>
538 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700539
tomcfde0622014-09-09 11:02:42 -0700540 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700541 super(provider);
542 }
543
Ray Milkey33306ba2018-09-20 13:27:25 -0700544 /**
545 * Apply role in reaction to provider event.
546 *
547 * @param deviceId device identifier
548 * @param newRole new role to apply to the device
549 * @return true if the request was sent to provider
550 */
551 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
552
553 if (newRole.equals(MastershipRole.NONE)) {
554 //no-op
555 return true;
556 }
557
558 DeviceProvider provider = provider();
559 if (provider == null) {
560 log.warn("Provider for {} was not found. Cannot apply role {}",
561 deviceId, newRole);
562 return false;
563 }
564 provider.roleChanged(deviceId, newRole);
565 // not triggering probe when triggered by provider service event
566 return true;
567 }
568
tomd3097b02014-08-26 10:40:29 -0700569 @Override
alshabibb7b40632014-09-28 21:30:00 -0700570 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700571 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700572 checkNotNull(deviceId, DEVICE_ID_NULL);
573 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700574 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700575
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700576 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800577
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700578 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
579 if (!isAllowed(cfg)) {
580 log.warn("Device {} is not allowed", deviceId);
581 return;
582 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200583 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700584 // Generate updated description and establish my Role
585 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900586 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
587 if (annoConfig != null) {
588 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
589 }
590
pier388ec252020-04-15 20:53:14 +0200591 // Wait for the end of the election. sync call of requestRoleFor
592 // wait only 3s and it is not entirely safe since the leadership
593 // election timer can be higher.
594 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
jaegonkim8eabcec2018-07-27 23:40:43 +0900595 log.info("Local role is {} for {}", role, deviceId);
pier388ec252020-04-15 20:53:14 +0200596 store.createOrUpdateDevice(provider().id(), deviceId, deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700597 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700598
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200599 if (portConfig != null) {
600 //updating the ports if configration exists
601 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
602 .collect(Collectors.toList());
603 complete.addAll(portConfig.portDescriptions());
604 List<PortDescription> portDescriptions = complete.stream()
605 .map(e -> applyAllPortOps(deviceId, e))
606 .collect(Collectors.toList());
607 store.updatePorts(provider().id(), deviceId, portDescriptions);
608 }
609
helenyrwufd296b62016-06-22 17:43:02 -0700610 if (deviceDescription.isDefaultAvailable()) {
611 log.info("Device {} connected", deviceId);
612 } else {
613 log.info("Device {} registered", deviceId);
614 }
tomd3097b02014-08-26 10:40:29 -0700615 }
616
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700617 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
618 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800619 return DefaultPortDescription.builder(desc)
620 .isEnabled(enabled)
621 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700622 }
623 return desc;
624 }
625
tomd3097b02014-08-26 10:40:29 -0700626 @Override
627 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700628 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700629 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700630 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700631 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700632
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700633 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
634 .map(desc -> ensurePortEnabledState(desc, false))
635 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300636
alshabibafc514a2014-12-01 14:44:05 -0800637 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700638 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700639 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700640 post(store.markOffline(deviceId));
641 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700642 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700643 log.warn("Failed to mark {} offline", deviceId);
644 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800645 // but if I was the last STANDBY connection, etc. and no one else
646 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700647 // temporarily request for Master Role and mark offline.
648
samuele1fa7322015-07-14 16:35:16 +0800649 //there are times when this node will correctly have mastership, BUT
650 //that isn't reflected in the ClockManager before the device disconnects.
651 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700652
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700653 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800654 // Consider revising store API to handle this scenario.
655 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700656 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800657 MastershipTerm term = termService.getMastershipTerm(deviceId);
658 // TODO: Move this type of check inside device clock manager, etc.
659 if (term != null && localNodeId.equals(term.master())) {
660 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800661 post(store.markOffline(deviceId));
662 } else {
663 log.info("Failed again marking {} offline. {}", deviceId, role);
664 }
665 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700666 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700667 try {
samuele1fa7322015-07-14 16:35:16 +0800668 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700669 mastershipService.relinquishMastership(deviceId).get();
670 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800671 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700672 Thread.currentThread().interrupt();
673 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800674 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700675 }
tom0efbb1d2014-09-09 11:54:28 -0700676 }
tomd3097b02014-08-26 10:40:29 -0700677 }
678
679 @Override
alshabibb7b40632014-09-28 21:30:00 -0700680 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700681 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700682 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700683 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700684 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700685 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700686 // Never been a master for this device
687 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800688 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700689 return;
690 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200691 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
692 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200693 // Updating the ports if configuration exists (on new lists as
694 // the passed one might be immutable)
695 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200696 portDescriptions.addAll(portConfig.portDescriptions());
697 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700698 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700699 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700700 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700701 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800702 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800703 if (events != null) {
704 for (DeviceEvent event : events) {
705 post(event);
706 }
tom32f66842014-08-27 19:27:47 -0700707 }
tomd3097b02014-08-26 10:40:29 -0700708 }
709
710 @Override
alshabibb7b40632014-09-28 21:30:00 -0700711 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700712 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700713 checkNotNull(deviceId, DEVICE_ID_NULL);
714 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700715 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700716
Madan Jampani565a66a2015-07-25 17:01:13 -0700717 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700718 // Never been a master for this device
719 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700720 log.trace("Ignoring {} port update on standby node. {}", deviceId,
721 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700722 return;
723 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700724 Device device = getDevice(deviceId);
725 if (device == null) {
726 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530727 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700728 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100729 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
730 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700731 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700732 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700733 deviceId,
734 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700735 portDescription = ensurePortEnabledState(storedPortDesc,
736 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300737 }
738
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700739 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800740 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700741 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700742 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700743 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800744 log.info("Device {} port {} status changed (enabled={})",
745 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700746 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700747 }
tomd3097b02014-08-26 10:40:29 -0700748 }
tom3f2bbd72014-09-24 12:07:58 -0700749
750 @Override
Michal Machce774332017-01-25 11:02:55 +0100751 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
752
753 checkNotNull(deviceId, DEVICE_ID_NULL);
754 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
755 checkValidity();
756
757 if (!mastershipService.isLocalMaster(deviceId)) {
758 // Never been a master for this device
759 // any update will be ignored.
760 log.trace("Ignoring {} port update on standby node. {}", deviceId,
761 basePortDescription);
762 return;
763 }
764
765 Device device = getDevice(deviceId);
766 if (device == null) {
767 log.trace("Device not found: {}", deviceId);
768 }
769
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800770 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
771 .isRemoved(true)
772 .build();
773
Michal Machce774332017-01-25 11:02:55 +0100774 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
775 deviceId,
776 newPortDescription);
777 if (event != null) {
778 log.info("Device {} port {} status changed", deviceId, event.port().number());
779 post(event);
780 }
781 }
782
783 @Override
samuele1fa7322015-07-14 16:35:16 +0800784 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700785 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700786 // Several things can happen here:
787 // 1. request and response match
788 // 2. request and response don't match
789 // 3. MastershipRole and requested match (and 1 or 2 are true)
790 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
791 //
792 // 2, 4, and 3 with case 2 are failure modes.
793
tom3f2bbd72014-09-24 12:07:58 -0700794 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700795
Madan Jampanif2af7712015-05-29 18:43:52 -0700796 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700797 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700798
799 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800800 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530801 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700802 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700803 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700804 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700805
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800806 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
807
808 if (requested == null) {
809 // Provider is not able to reconcile role responses with
810 // requests. We assume what was requested is what we expect.
811 // This will work only if mastership doesn't change too often,
812 // and devices are left enough time to provide responses before
813 // a different role is requested.
814 requested = expected;
815 }
816
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700817 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800818 if (Objects.equals(requested, expected)) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700819 return;
820 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800821 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
822 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800823 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700824 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800825 backgroundService.execute(() -> reassertRole(deviceId, expected));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800826 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700827 }
828 } else {
829 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200830 log.warn("Failed to assert role onto device {}. requested={}, response={}",
831 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200832 if (requested == MastershipRole.MASTER) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700833 mastershipService.relinquishMastership(deviceId);
834 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800835 //final Device device = getDevice(deviceId);
836 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700837 }
838 }
tom3f2bbd72014-09-24 12:07:58 -0700839 }
sangho538108b2015-04-08 14:29:20 -0700840
841 @Override
samuele1fa7322015-07-14 16:35:16 +0800842 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700843 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700844 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700845 checkValidity();
846
samuele1fa7322015-07-14 16:35:16 +0800847 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
848 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700849 post(event);
850 }
tomd3097b02014-08-26 10:40:29 -0700851 }
tom32f66842014-08-27 19:27:47 -0700852
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700853 // by default allowed, otherwise check flag
854 private boolean isAllowed(BasicDeviceConfig cfg) {
855 return (cfg == null || cfg.isAllowed());
856 }
857
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700858 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800859 DeviceProvider provider = getProvider(device.id());
860 if (provider == null) {
861 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
862 return false;
863 }
864 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700865 }
866
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800867 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700868
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800869 /**
870 * Apply role to device and send probe if MASTER.
871 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700872 * @param deviceId device identifier
873 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800874 * @return true if the request was sent to provider
875 */
876 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
877 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800878 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700879 return true;
880 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700881
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800882 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800883 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800884 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800885 return false;
886 }
887 provider.roleChanged(deviceId, newRole);
888
889 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800890 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800891 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800892 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800893 }
894 return true;
895 }
896
897 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800898 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800899 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700900 * @param did device identifier
901 * @param nextRole role to apply. If NONE is specified,
902 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800903 */
samuele1fa7322015-07-14 16:35:16 +0800904 private void reassertRole(final DeviceId did,
905 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800906
Jordan Halterman9416aea2017-11-17 12:40:21 -0800907 MastershipRole myNextRole = nextRole;
908 if (myNextRole == NONE && upgradeService.isLocalActive()) {
909 try {
910 mastershipService.requestRoleFor(did).get();
911 MastershipTerm term = termService.getMastershipTerm(did);
912 if (term != null && localNodeId.equals(term.master())) {
913 myNextRole = MASTER;
914 } else {
915 myNextRole = STANDBY;
916 }
917 } catch (InterruptedException e) {
918 Thread.currentThread().interrupt();
919 log.error("Interrupted waiting for Mastership", e);
920 } catch (ExecutionException e) {
921 log.error("Encountered an error waiting for Mastership", e);
922 }
923 }
924
925 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700926 case MASTER:
927 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700928 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +0900929 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700930 }
931 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800932 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700933 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800934 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700935 // immediately failed to apply role
936 mastershipService.relinquishMastership(did);
937 // FIXME disconnect?
938 }
939 break;
940 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -0800941 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700942 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800943 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700944 // immediately failed to apply role
945 mastershipService.relinquishMastership(did);
946 // FIXME disconnect?
947 }
948 break;
949 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700950 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700951 default:
952 // should never reach here
953 log.error("You didn't see anything. I did not exist.");
954 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800955 }
956 }
957
Madan Jampani328371d2015-05-29 14:06:27 -0700958 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700959 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700960 // Don't care if backup list changed.
961 return;
962 }
Madan Jampani328371d2015-05-29 14:06:27 -0700963 final DeviceId did = event.subject();
964
965 // myRole suggested by MastershipService
966 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700967 if (event.type() == MastershipEvent.Type.SUSPENDED) {
968 myNextRole = NONE; // FIXME STANDBY OR NONE?
969 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700970 // confirm latest info
971 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800972 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700973 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700974 myNextRole = MASTER;
975 } else {
976 myNextRole = STANDBY;
977 }
978 } else if (event.roleInfo().backups().contains(localNodeId)) {
979 myNextRole = STANDBY;
980 } else {
981 myNextRole = NONE;
982 }
983
Madan Jampani328371d2015-05-29 14:06:27 -0700984 final boolean isReachable = isReachable(did);
985 if (!isReachable) {
986 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800987 if (mastershipService.getLocalRole(did) == NONE) {
988 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700989 + "but this node cannot reach the device "
990 + "and role is already None. Ignoring request.",
991 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800992 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700993 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700994 + "but this node cannot reach the device. "
995 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800996 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700997 mastershipService.relinquishMastership(did);
998 }
999 return;
1000 }
1001
1002 // device is connected to this node:
1003 if (store.getDevice(did) != null) {
1004 reassertRole(did, myNextRole);
1005 } else {
1006 log.debug("Device is not yet/no longer in the store: {}", did);
1007 }
1008 }
1009
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001010 // Intercepts mastership events
1011 private class InternalMastershipListener implements MastershipListener {
1012
tomb41d1ac2014-09-24 01:51:24 -07001013 @Override
1014 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001015 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001016 try {
1017 handleMastershipEvent(event);
1018 } catch (Exception e) {
1019 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001020 }
Madan Jampani328371d2015-05-29 14:06:27 -07001021 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001022 }
tomb41d1ac2014-09-24 01:51:24 -07001023 }
tomf80c9722014-09-24 14:49:18 -07001024
1025 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001026 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001027 @Override
1028 public void notify(DeviceEvent event) {
1029 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001030 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001031 // When device is administratively removed, force disconnect.
1032 DeviceId deviceId = event.subject().id();
1033 deviceLocalStatus.remove(deviceId);
1034
1035 DeviceProvider provider = getProvider(deviceId);
1036 if (provider != null) {
1037 log.info("Triggering disconnect for device {}", deviceId);
1038 try {
1039 provider.triggerDisconnect(deviceId);
1040 } catch (UnsupportedOperationException e) {
1041 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1042 }
1043 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001044 }
tomf80c9722014-09-24 14:49:18 -07001045 }
1046 }
samuel738dfaf2015-07-11 11:08:57 +08001047
1048 @Override
1049 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001050 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001051 Set<Device> results = new HashSet<>();
1052 Iterable<Device> devices = store.getDevices();
1053 if (devices != null) {
1054 devices.forEach(d -> {
1055 if (type.equals(d.type())) {
1056 results.add(d);
1057 }
1058 });
1059 }
1060 return results;
1061 }
1062
1063 @Override
1064 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001065 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001066 Set<Device> results = new HashSet<>();
1067 Iterable<Device> availableDevices = store.getAvailableDevices();
1068 if (availableDevices != null) {
1069 availableDevices.forEach(d -> {
1070 if (type.equals(d.type())) {
1071 results.add(d);
1072 }
1073 });
1074 }
1075 return results;
1076 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001077
1078 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001079 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1080 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301081 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001082 if (event.subject().getClass() == ConnectPoint.class) {
1083 deviceId = ((ConnectPoint) event.subject()).deviceId();
1084 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001085 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301086 deviceId = (DeviceId) event.subject();
1087 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001088 return deviceId;
1089 }
1090
1091 @Override
1092 public boolean isRelevant(NetworkConfigEvent event) {
1093 DeviceId deviceId = extractDeviceId(event);
1094
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001095 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301096 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1097 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001098 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001099 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001100 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001101 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001102 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001103 }
1104
1105 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001106 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001107 DeviceEvent de = null;
1108 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001109 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001110 DeviceId did = (DeviceId) event.subject();
1111 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001112 BasicDeviceConfig cfg =
1113 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001114
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001115 if (!isAllowed(cfg)) {
1116 kickOutBadDevice(did);
1117 } else {
1118 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001119 DeviceDescription desc =
1120 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001121 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001122 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001123 store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001124 }
1125 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001126 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1127 DeviceId did = (DeviceId) event.subject();
1128 DeviceProvider dp = getProvider(did);
1129 if (!event.config().isPresent() ||
1130 getDevice(did) == null || dp == null) {
1131 // sanity check failed, ignore
1132 return;
1133 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001134 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001135 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001136 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1137 .collect(Collectors.toList());
1138 complete.addAll(portConfig.portDescriptions());
1139 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001140 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1141 DeviceId did = (DeviceId) event.subject();
1142 DeviceProvider dp = getProvider(did);
1143 Device dev = getDevice(did);
1144 DeviceDescription desc =
1145 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1146 Optional<Config> prevConfig = event.prevConfig();
Anurag Chadha61946392020-08-28 15:18:03 +05301147 if (desc != null) { // Fix for NPE due to desc being null
1148 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1149 }
Palash Kalaa06a6162017-11-15 20:42:40 +09001150 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001151 store.createOrUpdateDevice(dp.id(), did, desc);
Palash Kalaa06a6162017-11-15 20:42:40 +09001152 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001153 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001154 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001155 DeviceId did = cpt.deviceId();
1156 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001157
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001158 // Note: assuming PortOperator can modify existing port,
1159 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001160 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001161 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301162 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001163 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001164 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001165 }
1166
1167 if (de != null) {
1168 post(de);
1169 }
1170 }
1171
Simon Hunt8f60ff82017-04-24 17:19:30 -07001172 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001173 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001174 Device badDevice = getDevice(deviceId);
1175 if (badDevice != null) {
1176 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001177 }
1178 }
1179 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001180
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001181 @Override
1182 @SafeVarargs
1183 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001184 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001185 checkNotNull(portOp);
1186
1187 portOp.bindService(networkConfigService);
1188
1189 // update both portOpsIndex and portOps
1190 synchronized (portOpsIndex) {
1191 for (Class<? extends Config<ConnectPoint>> config : configs) {
1192 portOpsIndex.put(config, portOp);
1193 }
1194
1195 portOps.add(portOp);
1196 }
1197
1198 // TODO: Should we be applying to all existing Ports?
1199 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001200 .map(Device::id)
1201 .filter(mastershipService::isLocalMaster)
1202 // for each locally managed Device, update all port descriptions
1203 .map(did -> {
1204 ProviderId pid = Optional.ofNullable(getProvider(did))
1205 .map(Provider::id)
1206 .orElse(null);
1207 if (pid == null) {
1208 log.warn("Provider not found for {}", did);
1209 return ImmutableList.<DeviceEvent>of();
1210 }
1211 List<PortDescription> pds
1212 = store.getPortDescriptions(pid, did)
1213 .map(pdesc -> applyAllPortOps(did, pdesc))
1214 .collect(Collectors.toList());
1215 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001216 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001217 // ..and port port update event if necessary
1218 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001219 }
1220
1221 @Override
1222 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1223 checkNotNull(portOp);
1224
1225
1226 // remove all portOp
1227 synchronized (portOpsIndex) {
1228 portOps.remove(portOp);
1229
1230 // had to do this since COWArrayList iterator doesn't support remove
1231 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1232 }
1233
1234 }
1235
1236 /**
1237 * Merges the appropriate PortConfig with the description.
1238 *
1239 * @param did ID of the Device where the port is attached
1240 * @param desc {@link PortDescription}
1241 * @return merged {@link PortDescription}
1242 */
1243 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1244 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1245 }
1246
1247 /**
1248 * Merges the appropriate PortConfig with the description.
1249 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001250 * @param cpt ConnectPoint where the port is attached
1251 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001252 * @return merged {@link PortDescription}
1253 */
1254 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1255 PortDescription work = desc;
1256 for (PortConfigOperator portOp : portOps) {
1257 work = portOp.combine(cpt, work);
1258 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001259 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001260 }
1261
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001262 /**
debmaiti9553ed72019-03-18 14:27:42 +05301263 * Merges the appropriate PortConfig with the description.
1264 *
1265 * @param cpt ConnectPoint where the port is attached
1266 * @param desc {@link PortDescription}
1267 * @param prevConfig previous configuration
1268 * @return merged {@link PortDescription}
1269 */
1270 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1271 Optional<Config> prevConfig) {
1272 PortDescription work = desc;
1273 for (PortConfigOperator portOp : portOps) {
1274 work = portOp.combine(cpt, work, prevConfig);
1275 }
1276 return portAnnotationOp.combine(cpt, work, prevConfig);
1277 }
1278
1279 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001280 * Port Enable/Disable message sent to the device's MASTER node.
1281 */
1282 private class InternalPortUpDownEvent {
1283 private final DeviceId deviceId;
1284 private final PortNumber portNumber;
1285 private final boolean enable;
1286
1287 protected InternalPortUpDownEvent(
1288 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1289 this.deviceId = deviceId;
1290 this.portNumber = portNumber;
1291 this.enable = enable;
1292 }
1293
1294 public DeviceId deviceId() {
1295 return deviceId;
1296 }
1297 public PortNumber portNumber() {
1298 return portNumber;
1299 }
1300 public boolean isEnable() {
1301 return enable;
1302 }
1303
1304 protected InternalPortUpDownEvent() {
1305 this.deviceId = null;
1306 this.portNumber = null;
1307 this.enable = false;
1308 }
1309 }
tomd3097b02014-08-26 10:40:29 -07001310}