blob: fbbb15db9ce1386ac707ac2735fdc765c9157b1c [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;
pierventre2bb50162022-01-03 17:19:24 +010026import org.onosproject.cluster.ControllerNode;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.cluster.NodeId;
pierventre2bb50162022-01-03 17:19:24 +010028import org.onosproject.mastership.MastershipAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080029import org.onosproject.mastership.MastershipEvent;
30import org.onosproject.mastership.MastershipListener;
31import org.onosproject.mastership.MastershipService;
32import org.onosproject.mastership.MastershipTerm;
33import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070034import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080035import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080036import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080037import org.onosproject.net.DeviceId;
38import org.onosproject.net.MastershipRole;
39import org.onosproject.net.Port;
40import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070041import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030042import org.onosproject.net.config.NetworkConfigEvent;
43import org.onosproject.net.config.NetworkConfigListener;
44import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070045import org.onosproject.net.config.PortConfigOperator;
46import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030047import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090048import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080049import org.onosproject.net.config.basics.PortAnnotationConfig;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080050import org.onosproject.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.device.DefaultPortDescription;
52import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080053import org.onosproject.net.device.DeviceDescription;
54import org.onosproject.net.device.DeviceEvent;
55import org.onosproject.net.device.DeviceListener;
56import org.onosproject.net.device.DeviceProvider;
57import org.onosproject.net.device.DeviceProviderRegistry;
58import org.onosproject.net.device.DeviceProviderService;
59import org.onosproject.net.device.DeviceService;
60import org.onosproject.net.device.DeviceStore;
61import org.onosproject.net.device.DeviceStoreDelegate;
62import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070063import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030064import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080065import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080066import org.onosproject.net.provider.Provider;
67import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070068import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
69import org.onosproject.store.cluster.messaging.MessageSubject;
70import org.onosproject.store.serializers.KryoNamespaces;
71import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080072import org.onosproject.upgrade.UpgradeService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070073import org.osgi.service.component.annotations.Activate;
74import org.osgi.service.component.annotations.Component;
75import org.osgi.service.component.annotations.Deactivate;
76import org.osgi.service.component.annotations.Reference;
77import org.osgi.service.component.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070078import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070079
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070080import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070081import java.util.Collection;
82import java.util.HashSet;
83import java.util.List;
84import java.util.Map;
85import java.util.Objects;
86import java.util.Optional;
87import java.util.Set;
88import java.util.concurrent.CompletableFuture;
89import java.util.concurrent.ConcurrentHashMap;
90import java.util.concurrent.CopyOnWriteArrayList;
91import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070092import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070093import java.util.concurrent.ScheduledExecutorService;
94import java.util.concurrent.TimeUnit;
pierventre4af48792021-12-02 09:42:28 +010095import java.util.concurrent.atomic.AtomicBoolean;
Simon Huntffbad3b2017-05-16 15:37:51 -070096import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080097
Ray Milkey9ef22232016-07-14 12:42:37 -070098import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070099import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700100import static com.google.common.collect.Multimaps.newListMultimap;
101import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700102import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
pierventre4af48792021-12-02 09:42:28 +0100104import static java.lang.System.currentTimeMillis;
Ray Milkey9ef22232016-07-14 12:42:37 -0700105import static org.onlab.util.Tools.groupedThreads;
106import static org.onosproject.net.MastershipRole.MASTER;
107import static org.onosproject.net.MastershipRole.NONE;
108import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700109import static org.onosproject.security.AppGuard.checkPermission;
110import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
111import static org.slf4j.LoggerFactory.getLogger;
112
tomd3097b02014-08-26 10:40:29 -0700113/**
tome4729872014-09-23 00:37:37 -0700114 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700115 */
Ray Milkey86ad7bb2018-09-27 12:32:28 -0700116@Component(immediate = true,
117 service = {DeviceService.class, DeviceAdminService.class,
118 DeviceProviderRegistry.class, PortConfigOperatorRegistry.class })
tom41a2c5f2014-09-19 09:20:35 -0700119public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700120 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700121 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700122
tome5ec3fd2014-09-04 15:18:06 -0700123 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
124 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
125 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
126 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700127 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700128 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700129
tom5f38b3a2014-08-27 23:50:54 -0700130 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700131
alshabib339a3d92014-09-26 17:54:32 -0700132 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700133
tomc78acee2014-09-24 15:16:55 -0700134 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700135 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700136
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800137 private ScheduledExecutorService backgroundService;
138
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700139 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
140
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700141 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom41a2c5f2014-09-19 09:20:35 -0700142 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700143
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700144 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tomb41d1ac2014-09-24 01:51:24 -0700145 protected ClusterService clusterService;
146
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700147 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700148 protected MastershipService mastershipService;
149
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700150 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pierventre2bb50162022-01-03 17:19:24 +0100151 protected MastershipAdminService mastershipAdminService;
152
153 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700154 protected MastershipTermService termService;
155
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800157 protected UpgradeService upgradeService;
158
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700160 protected NetworkConfigService networkConfigService;
161
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700163 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700164
pierventre2bb50162022-01-03 17:19:24 +0100165 private ExecutorService clusterRequestExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700166 /**
167 * List of all registered PortConfigOperator.
168 */
169 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
170
171 /**
172 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
173 */
174 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700175 = synchronizedListMultimap(
176 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700177
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800178 // not part of portOps. must be executed at the end
179 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900180 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800181
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700182 private static final MessageSubject PORT_UPDOWN_SUBJECT =
183 new MessageSubject("port-updown-req");
184
pierventre2bb50162022-01-03 17:19:24 +0100185 private static final MessageSubject PROBE_SUBJECT =
186 new MessageSubject("probe-req");
187 private static final long PROBE_TIMEOUT_MILLIS = 5000;
188 private static final int PROBE_ATTEMPTS = 3;
189
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700190 private static final Serializer SERIALIZER = Serializer.using(
191 KryoNamespace.newBuilder()
192 .register(KryoNamespaces.API)
193 .register(InternalPortUpDownEvent.class)
194 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
195 .build("DeviceManager"));
196
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800197 /**
198 * Local storage for connectivity status of devices.
199 */
200 private class LocalStatus {
201 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700202 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800203
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700204 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800205 connected = b;
206 dateTime = now;
207 }
208 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700209
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800210 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
211 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700212
pierventre4af48792021-12-02 09:42:28 +0100213 // To remember whether or not the role was acknowledged by the device
214 private final Map<DeviceId, Long> roleToAcknowledge =
215 Maps.newConcurrentMap();
216 private ScheduledExecutorService backgroundRoleChecker;
217 private static final int ROLE_TIMEOUT_SECONDS = 10;
218
pierventre14a76e72022-02-28 20:34:42 -0800219 // FIXME join this map with roleToAcknowledge and fix the back to back event issue here
220 private final Map<DeviceId, MastershipRole> lastAcknowledgedRole =
221 Maps.newConcurrentMap();
222
tomd3097b02014-08-26 10:40:29 -0700223 @Activate
224 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800225 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900226 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800227 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
228
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800229 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700230 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700231 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800232
tomf80c9722014-09-24 14:49:18 -0700233 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700234 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700235 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700236 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800237
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700238 backgroundService.scheduleWithFixedDelay(() -> {
239 try {
240 mastershipCheck();
241 } catch (Exception e) {
pierventre4af48792021-12-02 09:42:28 +0100242 log.error("Exception thrown during mastership integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800243 }
244 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700245
pierventre2bb50162022-01-03 17:19:24 +0100246 clusterRequestExecutor = newSingleThreadExecutor();
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700247
pierventre2bb50162022-01-03 17:19:24 +0100248 communicationService.addSubscriber(
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700249 PORT_UPDOWN_SUBJECT,
250 SERIALIZER::decode,
251 this::handlePortRequest,
pierventre2bb50162022-01-03 17:19:24 +0100252 clusterRequestExecutor);
253
254 communicationService.addSubscriber(
255 PROBE_SUBJECT,
256 SERIALIZER::decode,
257 this::handleProbeRequest,
258 SERIALIZER::encode,
259 clusterRequestExecutor);
pierventre4af48792021-12-02 09:42:28 +0100260
261 backgroundRoleChecker = newSingleThreadScheduledExecutor(
262 groupedThreads("onos/device", "manager-role", log));
263 backgroundRoleChecker.scheduleAtFixedRate(() -> {
264 try {
265 roleCheck();
266 } catch (Exception e) {
267 log.error("Exception thrown while verifying role acknowledgement from all devices", e);
268 }
269 }, 0, 10, TimeUnit.SECONDS);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700270
tomd3097b02014-08-26 10:40:29 -0700271 log.info("Started");
272 }
273
274 @Deactivate
275 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800276 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700277 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700278 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700279 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700280 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700281 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
pierventre2bb50162022-01-03 17:19:24 +0100282 clusterRequestExecutor.shutdown();
pierventre4af48792021-12-02 09:42:28 +0100283 backgroundRoleChecker.shutdown();
tomd3097b02014-08-26 10:40:29 -0700284 log.info("Stopped");
285 }
286
287 @Override
tomad2d2092014-09-06 23:24:20 -0700288 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900289 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700290 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700291 }
292
293 @Override
mskala32000d32017-07-14 16:27:06 +0200294 public int getAvailableDeviceCount() {
295 checkPermission(DEVICE_READ);
296 return store.getAvailableDeviceCount();
297 }
298
299 @Override
tom32f66842014-08-27 19:27:47 -0700300 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900301 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700302 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700303 }
304
tom32f66842014-08-27 19:27:47 -0700305 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800306 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900307 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800308 return store.getAvailableDevices();
309 }
310
311 @Override
tom32f66842014-08-27 19:27:47 -0700312 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900313 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700314 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700315 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700316 }
317
318 @Override
tomad2d2092014-09-06 23:24:20 -0700319 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900320 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700321 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700322 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700323 }
324
325 @Override
tom32f66842014-08-27 19:27:47 -0700326 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900327 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700328 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700329 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700330 }
331
332 @Override
sangho538108b2015-04-08 14:29:20 -0700333 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900334 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700335 checkNotNull(deviceId, DEVICE_ID_NULL);
336 return store.getPortStatistics(deviceId);
337 }
338
339 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200340 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900341 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200342 checkNotNull(deviceId, DEVICE_ID_NULL);
343 return store.getPortDeltaStatistics(deviceId);
344 }
345
346 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530347 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
348 checkPermission(DEVICE_READ);
349 checkNotNull(deviceId, DEVICE_ID_NULL);
350 checkNotNull(portNumber, PORT_NUMBER_NULL);
351 return store.getStatisticsForPort(deviceId, portNumber);
352 }
353
354 @Override
355 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
356 checkPermission(DEVICE_READ);
357 checkNotNull(deviceId, DEVICE_ID_NULL);
358 checkNotNull(portNumber, PORT_NUMBER_NULL);
359 return store.getDeltaStatisticsForPort(deviceId, portNumber);
360 }
361
362 @Override
tom32f66842014-08-27 19:27:47 -0700363 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900364 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700365 checkNotNull(deviceId, DEVICE_ID_NULL);
366 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700367 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700368 }
369
370 @Override
tomff7eb7c2014-09-08 12:49:03 -0700371 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900372 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900373
tomff7eb7c2014-09-08 12:49:03 -0700374 checkNotNull(deviceId, DEVICE_ID_NULL);
375 return store.isAvailable(deviceId);
376 }
377
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800378 @Override
379 public String localStatus(DeviceId deviceId) {
380 LocalStatus ls = deviceLocalStatus.get(deviceId);
381 if (ls == null) {
382 return "No Record";
383 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700384 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800385 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
386 }
387
Palash Kala0d817b02018-03-23 18:09:45 +0900388 private boolean isLocallyConnected(DeviceId deviceId) {
389 LocalStatus ls = deviceLocalStatus.get(deviceId);
390 if (ls == null) {
391 return false;
392 }
393 return ls.connected;
394 }
395
Ray Milkey054e23d2018-03-22 13:37:11 -0700396 @Override
397 public long getLastUpdatedInstant(DeviceId deviceId) {
398 LocalStatus ls = deviceLocalStatus.get(deviceId);
399 if (ls == null) {
400 return 0;
401 }
402 return ls.dateTime.toEpochMilli();
403 }
404
pierventrebc91cea2022-02-18 05:16:48 -0800405 // Returns true if the grace period is still on
406 private boolean inGracePeriod(DeviceId deviceId) {
407 LocalStatus ls = deviceLocalStatus.get(deviceId);
408 if (ls == null) {
409 // This should not be possible, unless the device is removed
410 log.warn("Not found a recent local status for {}", deviceId);
411 return true;
412 }
413 DeviceProvider provider = getProvider(deviceId);
414 return ls.connected &&
415 (Instant.now().toEpochMilli() - ls.dateTime.toEpochMilli()) < provider.gracePeriod();
416 }
417
Palash Kala0d817b02018-03-23 18:09:45 +0900418 // Check a device for control channel connectivity
419 // and changes local-status appropriately.
pierventrebc91cea2022-02-18 05:16:48 -0800420 private boolean isReachable(DeviceId deviceId, boolean inGracePeriod) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800421 if (deviceId == null) {
422 return false;
423 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700424 DeviceProvider provider = getProvider(deviceId);
425 if (provider != null) {
pierventre2bb50162022-01-03 17:19:24 +0100426 boolean reachable = probeReachability(deviceId);
Palash Kala0d817b02018-03-23 18:09:45 +0900427 if (reachable && !isLocallyConnected(deviceId)) {
428 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
pierventrebc91cea2022-02-18 05:16:48 -0800429 } else if (!reachable && isLocallyConnected(deviceId) && !inGracePeriod) {
430 // Do not update if the grace period is still on
Palash Kala0d817b02018-03-23 18:09:45 +0900431 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
432 }
433 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700434 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800435 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700436 return false;
437 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700438 }
439
tome5ec3fd2014-09-04 15:18:06 -0700440 @Override
441 public void removeDevice(DeviceId deviceId) {
442 checkNotNull(deviceId, DEVICE_ID_NULL);
443 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700444 if (event != null) {
445 log.info("Device {} administratively removed", deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700446 }
tome5ec3fd2014-09-04 15:18:06 -0700447 }
448
Thomas Vachuska811ea2b2020-02-11 10:20:10 -0800449 @Override
450 public void removeDevicePorts(DeviceId deviceId) {
451 checkNotNull(deviceId, DEVICE_ID_NULL);
452 if (isAvailable(deviceId)) {
453 log.debug("Cannot remove ports of device {} while it is available.", deviceId);
454 return;
455 }
456
457 List<PortDescription> portDescriptions = ImmutableList.of();
458 List<DeviceEvent> events = store.updatePorts(getProvider(deviceId).id(),
459 deviceId, portDescriptions);
460 if (events != null) {
461 for (DeviceEvent event : events) {
462 post(event);
463 }
464 }
465 }
466
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700467 private void handlePortRequest(InternalPortUpDownEvent event) {
468 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700469 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon436c60a2021-01-01 14:23:29 +0000470 checkNotNull(event.portNumber(), PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700471 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
472 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
473 }
474
475 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
476 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700477 DeviceProvider provider = getProvider(deviceId);
478 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700479 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700480 portNumber, deviceId,
481 (enable) ? "UP" : "DOWN");
482 provider.changePortState(deviceId, portNumber, enable);
483 } else {
484 log.warn("Provider not found for {}", deviceId);
485 }
486 }
487
488 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700489 public void changePortState(DeviceId deviceId, PortNumber portNumber,
490 boolean enable) {
491 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon436c60a2021-01-01 14:23:29 +0000492 checkNotNull(portNumber, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700493 NodeId masterId = mastershipService.getMasterFor(deviceId);
494
Ray Milkey4ef245e2018-05-10 15:41:16 -0700495 if (masterId == null) {
496 // No master found; device is offline
497 log.info("No master found for port state change for {}", deviceId);
498 return;
499 }
500
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700501 if (!masterId.equals(localNodeId)) {
502 //Send the request to the master node for the device
503 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
504 deviceId, masterId);
505 communicationService.unicast(
506 new InternalPortUpDownEvent(deviceId, portNumber, enable),
507 PORT_UPDOWN_SUBJECT,
508 SERIALIZER::encode,
509 masterId).whenComplete((r, error) -> {
510 if (error != null) {
511 log.warn("Failed to send packet-updown-req to {}", masterId, error);
512 }
513 });
514 } else {
515 changePortStateAtMaster(deviceId, portNumber, enable);
516 }
517 }
518
519 @Override
samuele1fa7322015-07-14 16:35:16 +0800520 protected DeviceProviderService createProviderService(
521 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700522 return new InternalDeviceProviderService(provider);
523 }
524
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800525 /**
526 * Checks if all the reachable devices have a valid mastership role.
527 */
528 private void mastershipCheck() {
529 log.debug("Checking mastership");
530 for (Device device : getDevices()) {
531 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700532 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
533 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
pierventrebc91cea2022-02-18 05:16:48 -0800534
535 log.debug("Device {} local status is {}", deviceId, localStatus(deviceId));
536 final boolean isGracePeriodOn = inGracePeriod(deviceId);
537 final boolean isReachable = isReachable(deviceId, isGracePeriodOn);
538 // Passed the grace period and it is still not reachable
539 if (!isGracePeriodOn && !isReachable) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700540 if (myRole != NONE) {
pierventre2bb50162022-01-03 17:19:24 +0100541 // Verify if the device is fully disconnected from the cluster
542 if (updateMastershipFor(deviceId) == null
543 && myRole == MASTER && isAvailable(deviceId)) {
544 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Andrea Campanella3971df82022-04-27 13:24:34 +0200545 // Following the deviceDisconnected method logic (line 734) we are marking also all the
546 // ports as disabled.
547 List<PortDescription> descs = store.getPortDescriptions(getProvider(deviceId).id(), deviceId)
548 .map(desc -> ensurePortEnabledState(desc, false))
549 .collect(Collectors.toList());
550 store.updatePorts(getProvider(deviceId).id(), deviceId, descs);
pierventre2bb50162022-01-03 17:19:24 +0100551 post(store.markOffline(deviceId));
helenyrwufd296b62016-06-22 17:43:02 -0700552 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530553 } else {
pierventrebc91cea2022-02-18 05:16:48 -0800554 // Firstly get a role and then check if the device is available in the store.
555 // if it is, if this node is the master and the device is fully disconnected
556 // from the cluster mark the device offline. In principle, this condition should
557 // never be hit unless in a device removed phase for NONE mastership roles.
pierventre2bb50162022-01-03 17:19:24 +0100558 try {
559 mastershipService.requestRoleFor(deviceId).get();
560 } catch (InterruptedException e) {
561 Thread.currentThread().interrupt();
562 log.error("Interrupted waiting for Mastership", e);
563 } catch (ExecutionException e) {
564 log.error("Encountered an error waiting for Mastership", e);
565 }
566
567 MastershipTerm term = termService.getMastershipTerm(deviceId);
568 if (updateMastershipFor(deviceId) == null &&
569 term != null && localNodeId.equals(term.master()) &&
570 isAvailable(deviceId)) {
571 log.info("Marking unreachable device {} offline", deviceId);
Andrea Campanella3971df82022-04-27 13:24:34 +0200572 // Following the deviceDisconnected method logic (line 734) we are marking also all the
573 // ports as disabled.
574 List<PortDescription> descs = store.getPortDescriptions(getProvider(deviceId).id(), deviceId)
575 .map(desc -> ensurePortEnabledState(desc, false))
576 .collect(Collectors.toList());
577 store.updatePorts(getProvider(deviceId).id(), deviceId, descs);
pierventre2bb50162022-01-03 17:19:24 +0100578 post(store.markOffline(deviceId));
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800579 }
helenyrwufd296b62016-06-22 17:43:02 -0700580 }
pierventre2bb50162022-01-03 17:19:24 +0100581 roleToAcknowledge.remove(deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800582 } else if (isReachable) {
583 // If this node is the master, ensure the device is marked online.
584 if (myRole == MASTER && canMarkOnline(device)) {
pierventre14a76e72022-02-28 20:34:42 -0800585 log.debug("Can mark online {}", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800586 post(store.markOnline(deviceId));
587 }
588
pierventre14a76e72022-02-28 20:34:42 -0800589 log.debug("{} is reachable - reasserting the role", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800590
591 // Device is still reachable. It is useful for some protocols
592 // to reassert the role. Note: NONE triggers request to MastershipService
593 reassertRole(deviceId, myRole);
594 } else {
595 // Do not proceed furthermore if the grace period is still on
596 log.debug("Skipping mastership check for {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800597 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800598 }
599 }
600
pierventre4af48792021-12-02 09:42:28 +0100601 /**
602 * Checks if all the devices have acknowledged the mastership role.
603 */
604 private void roleCheck() {
605 log.debug("Checking role");
606 for (Device device : getDevices()) {
607 final DeviceId deviceId = device.id();
608 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
609 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
610 final AtomicBoolean exists = new AtomicBoolean(false);
611 final Long ts = roleToAcknowledge.compute(deviceId, (key, value) -> {
612 if (value == null) {
613 return null;
614 }
615 exists.set(true);
616 if (currentTimeMillis() - value < (ROLE_TIMEOUT_SECONDS * 1000)) {
617 return value;
618 }
619 return null;
620 });
621 // Nobody applied the role recently
622 if (!exists.get()) {
623 log.trace("Role was not applied or it has been acknowledged for device {}", deviceId);
624 continue;
625 }
626 // Timeout still on
627 if (ts != null) {
628 log.debug("Timeout expires in {} ms", ((ROLE_TIMEOUT_SECONDS * 1000) - currentTimeMillis() + ts));
629 continue;
630 }
631 if (myRole != MASTER) {
632 log.debug("Timeout is expired but current role is not MASTER ({}), nothing to do", myRole);
633 continue;
634 }
pierventrebc91cea2022-02-18 05:16:48 -0800635 // Switch failed to acknowledge master role we asked for.
636 // Yield mastership to other instance
pierventre4af48792021-12-02 09:42:28 +0100637 log.warn("Failed to assert role onto device {}. requested={}, no response",
638 deviceId, myRole);
pierventre2bb50162022-01-03 17:19:24 +0100639 updateMastershipFor(deviceId);
pierventre4af48792021-12-02 09:42:28 +0100640 }
641 }
642
Andrea Campanella3971df82022-04-27 13:24:34 +0200643 PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
644 if (desc.isEnabled() != enabled) {
645 return DefaultPortDescription.builder(desc)
646 .isEnabled(enabled)
647 .build();
648 }
649 return desc;
650 }
651
tomd3097b02014-08-26 10:40:29 -0700652 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700653 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700654 extends AbstractProviderService<DeviceProvider>
655 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700656
tomcfde0622014-09-09 11:02:42 -0700657 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700658 super(provider);
659 }
660
Ray Milkey33306ba2018-09-20 13:27:25 -0700661 /**
662 * Apply role in reaction to provider event.
663 *
664 * @param deviceId device identifier
665 * @param newRole new role to apply to the device
666 * @return true if the request was sent to provider
667 */
668 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
669
670 if (newRole.equals(MastershipRole.NONE)) {
671 //no-op
672 return true;
673 }
674
675 DeviceProvider provider = provider();
676 if (provider == null) {
677 log.warn("Provider for {} was not found. Cannot apply role {}",
678 deviceId, newRole);
679 return false;
680 }
pierventre4af48792021-12-02 09:42:28 +0100681 // Start the timer
682 roleToAcknowledge.put(deviceId, currentTimeMillis());
Ray Milkey33306ba2018-09-20 13:27:25 -0700683 provider.roleChanged(deviceId, newRole);
684 // not triggering probe when triggered by provider service event
685 return true;
686 }
687
tomd3097b02014-08-26 10:40:29 -0700688 @Override
alshabibb7b40632014-09-28 21:30:00 -0700689 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700690 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700691 checkNotNull(deviceId, DEVICE_ID_NULL);
692 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700693 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700694
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700695 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800696
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700697 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
698 if (!isAllowed(cfg)) {
699 log.warn("Device {} is not allowed", deviceId);
700 return;
701 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200702 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700703 // Generate updated description and establish my Role
704 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900705 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
706 if (annoConfig != null) {
707 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
708 }
709
pier388ec252020-04-15 20:53:14 +0200710 // Wait for the end of the election. sync call of requestRoleFor
711 // wait only 3s and it is not entirely safe since the leadership
712 // election timer can be higher.
713 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
jaegonkim8eabcec2018-07-27 23:40:43 +0900714 log.info("Local role is {} for {}", role, deviceId);
pier388ec252020-04-15 20:53:14 +0200715 store.createOrUpdateDevice(provider().id(), deviceId, deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700716 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700717
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200718 if (portConfig != null) {
719 //updating the ports if configration exists
720 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
721 .collect(Collectors.toList());
722 complete.addAll(portConfig.portDescriptions());
723 List<PortDescription> portDescriptions = complete.stream()
724 .map(e -> applyAllPortOps(deviceId, e))
725 .collect(Collectors.toList());
726 store.updatePorts(provider().id(), deviceId, portDescriptions);
727 }
728
helenyrwufd296b62016-06-22 17:43:02 -0700729 if (deviceDescription.isDefaultAvailable()) {
730 log.info("Device {} connected", deviceId);
731 } else {
732 log.info("Device {} registered", deviceId);
733 }
tomd3097b02014-08-26 10:40:29 -0700734 }
735
736 @Override
737 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700738 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700739 checkValidity();
pierventre2bb50162022-01-03 17:19:24 +0100740 // Update the local status
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700741 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Andrea Campanella18fdda82021-09-13 12:37:36 +0200742 log.info("Device {} disconnected from this node: {}", deviceId,
743 clusterService.getLocalNode().id());
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700744
pierventrebc91cea2022-02-18 05:16:48 -0800745 // If none can reach the device, we will continue with the disconnection logic.
746 // If there is one instance that reported device is still reachable, we hand over
747 // the mastership to it if we are the current master, otherwise if we are a backup
748 // we demote ourselves to the bottom of the backups list
pierventre2bb50162022-01-03 17:19:24 +0100749 if (updateMastershipFor(deviceId) == null) {
750 log.info("Device {} is fully disconnected from the cluster", deviceId);
751 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
752 .map(desc -> ensurePortEnabledState(desc, false))
753 .collect(Collectors.toList());
754 store.updatePorts(this.provider().id(), deviceId, descs);
Yafit Hadara9a73de2015-09-06 13:52:52 +0300755
Madan Jampanic6e574f2015-05-29 13:41:52 -0700756 try {
pierventre2bb50162022-01-03 17:19:24 +0100757 if (mastershipService.isLocalMaster(deviceId)) {
758 post(store.markOffline(deviceId));
759 }
760 } catch (IllegalStateException e) {
761 log.warn("Failed to mark {} offline", deviceId);
762 // only the MASTER should be marking off-line in normal cases,
763 // but if I was the last STANDBY connection, etc. and no one else
764 // was there to mark the device offline, this instance may need to
765 // temporarily request for Master Role and mark offline.
766
767 //there are times when this node will correctly have mastership, BUT
768 //that isn't reflected in the ClockManager before the device disconnects.
769 //we want to let go of the device anyways, so make sure this happens.
770
771 // FIXME: Store semantics leaking out as IllegalStateException.
772 // Consider revising store API to handle this scenario.
773 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
774 roleFuture.whenComplete((role, error) -> {
775 MastershipTerm term = termService.getMastershipTerm(deviceId);
776 // TODO: Move this type of check inside device clock manager, etc.
777 if (term != null && localNodeId.equals(term.master())) {
778 log.info("Retry marking {} offline", deviceId);
779 post(store.markOffline(deviceId));
780 } else {
781 log.info("Failed again marking {} offline. {}", deviceId, role);
782 }
783 });
784 } finally {
pierventre4af48792021-12-02 09:42:28 +0100785 roleToAcknowledge.remove(deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700786 }
tom0efbb1d2014-09-09 11:54:28 -0700787 }
pierventre2bb50162022-01-03 17:19:24 +0100788
tomd3097b02014-08-26 10:40:29 -0700789 }
790
791 @Override
alshabibb7b40632014-09-28 21:30:00 -0700792 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700793 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700794 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700795 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700796 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700797 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700798 // Never been a master for this device
799 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800800 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700801 return;
802 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200803 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
804 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200805 // Updating the ports if configuration exists (on new lists as
806 // the passed one might be immutable)
807 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200808 portDescriptions.addAll(portConfig.portDescriptions());
809 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700810 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700811 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700812 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700813 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800814 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800815 if (events != null) {
816 for (DeviceEvent event : events) {
817 post(event);
818 }
tom32f66842014-08-27 19:27:47 -0700819 }
tomd3097b02014-08-26 10:40:29 -0700820 }
821
822 @Override
alshabibb7b40632014-09-28 21:30:00 -0700823 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700824 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700825 checkNotNull(deviceId, DEVICE_ID_NULL);
826 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700827 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700828
Madan Jampani565a66a2015-07-25 17:01:13 -0700829 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700830 // Never been a master for this device
831 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700832 log.trace("Ignoring {} port update on standby node. {}", deviceId,
833 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700834 return;
835 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700836 Device device = getDevice(deviceId);
837 if (device == null) {
838 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530839 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700840 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100841 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
842 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700843 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700844 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700845 deviceId,
846 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700847 portDescription = ensurePortEnabledState(storedPortDesc,
848 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300849 }
850
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700851 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800852 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700853 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700854 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700855 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800856 log.info("Device {} port {} status changed (enabled={})",
857 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700858 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700859 }
tomd3097b02014-08-26 10:40:29 -0700860 }
tom3f2bbd72014-09-24 12:07:58 -0700861
862 @Override
Michal Machce774332017-01-25 11:02:55 +0100863 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
864
865 checkNotNull(deviceId, DEVICE_ID_NULL);
866 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
867 checkValidity();
868
869 if (!mastershipService.isLocalMaster(deviceId)) {
870 // Never been a master for this device
871 // any update will be ignored.
872 log.trace("Ignoring {} port update on standby node. {}", deviceId,
873 basePortDescription);
874 return;
875 }
876
877 Device device = getDevice(deviceId);
878 if (device == null) {
879 log.trace("Device not found: {}", deviceId);
880 }
881
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800882 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
883 .isRemoved(true)
884 .build();
885
Michal Machce774332017-01-25 11:02:55 +0100886 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
887 deviceId,
888 newPortDescription);
889 if (event != null) {
890 log.info("Device {} port {} status changed", deviceId, event.port().number());
891 post(event);
892 }
893 }
894
895 @Override
samuele1fa7322015-07-14 16:35:16 +0800896 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700897 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700898 // Several things can happen here:
899 // 1. request and response match
900 // 2. request and response don't match
901 // 3. MastershipRole and requested match (and 1 or 2 are true)
902 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
903 //
904 // 2, 4, and 3 with case 2 are failure modes.
905
tom3f2bbd72014-09-24 12:07:58 -0700906 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700907
Madan Jampanif2af7712015-05-29 18:43:52 -0700908 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700909 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700910
911 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800912 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530913 log.warn("Failed to assert role onto Device {}", deviceId);
pierventre4af48792021-12-02 09:42:28 +0100914 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100915 updateMastershipFor(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700916 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700917 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700918
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800919 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
920
921 if (requested == null) {
922 // Provider is not able to reconcile role responses with
923 // requests. We assume what was requested is what we expect.
924 // This will work only if mastership doesn't change too often,
925 // and devices are left enough time to provide responses before
926 // a different role is requested.
927 requested = expected;
928 }
929
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700930 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800931 if (Objects.equals(requested, expected)) {
pierventre14a76e72022-02-28 20:34:42 -0800932 if (log.isDebugEnabled()) {
933 log.debug("Role has been acknowledged for device {}", deviceId);
934 } else if (!requested.equals(lastAcknowledgedRole.get(deviceId))) {
935 log.info("Role has been acknowledged for device {}", deviceId);
936 }
937 // Update the last known role and stop the timer
938 lastAcknowledgedRole.put(deviceId, requested);
pierventre4af48792021-12-02 09:42:28 +0100939 roleToAcknowledge.remove(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700940 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800941 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
942 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800943 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700944 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800945 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700946 }
947 } else {
948 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200949 log.warn("Failed to assert role onto device {}. requested={}, response={}",
950 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200951 if (requested == MastershipRole.MASTER) {
pierventre4af48792021-12-02 09:42:28 +0100952 // Stop the timer
953 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100954 updateMastershipFor(deviceId);
Charles Chan48103842021-01-06 01:33:03 +0000955 } else if (requested == MastershipRole.STANDBY) {
956 // For P4RT devices, the response role will be NONE when this node is expected to be STANDBY
957 // but the stream channel is not opened correctly.
958 // Calling reassertRole will trigger the mechanism in GeneralDeviceProvider that
959 // attempts to re-establish the stream channel
960 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700961 }
962 }
tom3f2bbd72014-09-24 12:07:58 -0700963 }
sangho538108b2015-04-08 14:29:20 -0700964
965 @Override
samuele1fa7322015-07-14 16:35:16 +0800966 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700967 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700968 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700969 checkValidity();
970
samuele1fa7322015-07-14 16:35:16 +0800971 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
972 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700973 post(event);
974 }
pierventreb8856852021-10-01 22:01:22 +0200975
976 @Override
977 public DeviceDescription getDeviceDescription(DeviceId deviceId) {
978 checkNotNull(deviceId, DEVICE_ID_NULL);
979 checkValidity();
980
981 return store.getDeviceDescription(provider().id(), deviceId);
982 }
tomd3097b02014-08-26 10:40:29 -0700983 }
tom32f66842014-08-27 19:27:47 -0700984
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700985 // by default allowed, otherwise check flag
986 private boolean isAllowed(BasicDeviceConfig cfg) {
987 return (cfg == null || cfg.isAllowed());
988 }
989
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700990 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800991 DeviceProvider provider = getProvider(device.id());
992 if (provider == null) {
993 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
994 return false;
995 }
996 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700997 }
998
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800999 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001000
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001001 /**
1002 * Apply role to device and send probe if MASTER.
1003 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001004 * @param deviceId device identifier
1005 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001006 * @return true if the request was sent to provider
1007 */
1008 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
1009 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +08001010 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001011 return true;
1012 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001013
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001014 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001015 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +08001016 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001017 return false;
1018 }
pierventre4af48792021-12-02 09:42:28 +01001019 // Start the timer
1020 roleToAcknowledge.put(deviceId, currentTimeMillis());
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001021 provider.roleChanged(deviceId, newRole);
1022
1023 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -08001024 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001025 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001026 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001027 }
1028 return true;
1029 }
1030
pierventre2bb50162022-01-03 17:19:24 +01001031 private boolean probeReachability(DeviceId deviceId) {
1032 DeviceProvider provider = getProvider(deviceId);
1033 if (provider == null) {
1034 log.warn("Provider for {} was not found. Cannot probe reachability", deviceId);
1035 return false;
1036 }
1037 return provider.isReachable(deviceId) && Tools.futureGetOrElse(provider.probeReachability(deviceId),
1038 PROBE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, Boolean.FALSE);
1039 }
1040
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001041 /**
Harold Huangff6e1e62017-11-09 16:25:36 +08001042 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001043 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001044 * @param did device identifier
1045 * @param nextRole role to apply. If NONE is specified,
1046 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001047 */
samuele1fa7322015-07-14 16:35:16 +08001048 private void reassertRole(final DeviceId did,
1049 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001050
Jordan Halterman9416aea2017-11-17 12:40:21 -08001051 MastershipRole myNextRole = nextRole;
1052 if (myNextRole == NONE && upgradeService.isLocalActive()) {
1053 try {
1054 mastershipService.requestRoleFor(did).get();
1055 MastershipTerm term = termService.getMastershipTerm(did);
1056 if (term != null && localNodeId.equals(term.master())) {
1057 myNextRole = MASTER;
1058 } else {
1059 myNextRole = STANDBY;
1060 }
1061 } catch (InterruptedException e) {
1062 Thread.currentThread().interrupt();
1063 log.error("Interrupted waiting for Mastership", e);
1064 } catch (ExecutionException e) {
1065 log.error("Encountered an error waiting for Mastership", e);
1066 }
1067 }
1068
1069 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001070 case MASTER:
1071 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001072 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +09001073 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001074 }
1075 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -08001076 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001077 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001078 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001079 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001080 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001081 // FIXME disconnect?
1082 }
1083 break;
1084 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -08001085 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001086 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001087 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001088 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001089 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001090 // FIXME disconnect?
1091 }
1092 break;
1093 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -07001094 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001095 default:
1096 // should never reach here
1097 log.error("You didn't see anything. I did not exist.");
1098 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001099 }
1100 }
1101
Madan Jampani328371d2015-05-29 14:06:27 -07001102 private void handleMastershipEvent(MastershipEvent event) {
pierventrebc91cea2022-02-18 05:16:48 -08001103 log.debug("Handling mastership event");
Madan Jampani328371d2015-05-29 14:06:27 -07001104 final DeviceId did = event.subject();
1105
pierventre2bb50162022-01-03 17:19:24 +01001106 // myNextRole suggested by MastershipService event
Madan Jampani328371d2015-05-29 14:06:27 -07001107 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -07001108 if (event.type() == MastershipEvent.Type.SUSPENDED) {
1109 myNextRole = NONE; // FIXME STANDBY OR NONE?
1110 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -07001111 // confirm latest info
1112 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +08001113 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -07001114 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -07001115 myNextRole = MASTER;
1116 } else {
1117 myNextRole = STANDBY;
1118 }
1119 } else if (event.roleInfo().backups().contains(localNodeId)) {
1120 myNextRole = STANDBY;
1121 } else {
1122 myNextRole = NONE;
1123 }
1124
pierventrebc91cea2022-02-18 05:16:48 -08001125 log.debug("Device {} local status is {}", did, localStatus(did));
1126 final boolean isGracePeriodOn = inGracePeriod(did);
1127 final boolean isReachable = isReachable(did, isGracePeriodOn);
1128 // Passed the grace period and it is still not reachable
1129 if (!isGracePeriodOn && !isReachable) {
pierventre2bb50162022-01-03 17:19:24 +01001130 // device is not connected to this node, nevertheless we should get a role
Jon Halla90c44c2017-01-24 16:02:07 -08001131 if (mastershipService.getLocalRole(did) == NONE) {
1132 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -07001133 + "but this node cannot reach the device "
pierventre2bb50162022-01-03 17:19:24 +01001134 + "and role is already None. Asking a new role "
1135 + "and then apply the disconnection protocol.",
Simon Huntffbad3b2017-05-16 15:37:51 -07001136 myNextRole, did);
pierventre2bb50162022-01-03 17:19:24 +01001137 try {
1138 mastershipService.requestRoleFor(did).get();
1139 } catch (InterruptedException e) {
1140 Thread.currentThread().interrupt();
1141 log.error("Interrupted waiting for Mastership", e);
1142 } catch (ExecutionException e) {
1143 log.error("Encountered an error waiting for Mastership", e);
1144 }
Jon Halla90c44c2017-01-24 16:02:07 -08001145 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -07001146 log.warn("Node was instructed to be {} role for {}, "
pierventre2bb50162022-01-03 17:19:24 +01001147 + "but this node cannot reach the device. "
1148 + "Apply the disconnection protocol.",
samuele1fa7322015-07-14 16:35:16 +08001149 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -07001150 }
pierventre2bb50162022-01-03 17:19:24 +01001151 // Let's put some order in the candidates list
1152 roleToAcknowledge.remove(did);
1153 updateMastershipFor(did);
pierventrebc91cea2022-02-18 05:16:48 -08001154 } else if (isReachable) {
1155 // Device is connected to this node - always reassert the role.
1156 // Ideally, protocols like OpenFlow would not need to reassert the
1157 // role because the instances are only identified by the role. However,
1158 // other protocols like P4RT require to provide also an election id
1159 // which maybe different over time, by reasserting the role will guarantee
1160 // that updated election ids are communicated to the devices. It should not
1161 // cost us a lot as it is equivalent to a probe.
1162 if (store.getDevice(did) != null) {
1163 log.info("{} is reachable - reasserting the role", did);
1164 reassertRole(did, myNextRole);
1165 } else {
1166 log.debug("Device is not yet/no longer in the store: {}", did);
1167 }
Madan Jampani328371d2015-05-29 14:06:27 -07001168 } else {
pierventrebc91cea2022-02-18 05:16:48 -08001169 // Do not proceed furthermore if the grace period is still on
1170 log.debug("Skipping mastership event {}", event);
Madan Jampani328371d2015-05-29 14:06:27 -07001171 }
1172 }
1173
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001174 // Intercepts mastership events
1175 private class InternalMastershipListener implements MastershipListener {
1176
tomb41d1ac2014-09-24 01:51:24 -07001177 @Override
1178 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001179 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001180 try {
1181 handleMastershipEvent(event);
1182 } catch (Exception e) {
1183 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001184 }
Madan Jampani328371d2015-05-29 14:06:27 -07001185 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001186 }
tomb41d1ac2014-09-24 01:51:24 -07001187 }
tomf80c9722014-09-24 14:49:18 -07001188
1189 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001190 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001191 @Override
1192 public void notify(DeviceEvent event) {
1193 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001194 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001195 // When device is administratively removed, force disconnect.
1196 DeviceId deviceId = event.subject().id();
1197 deviceLocalStatus.remove(deviceId);
pierventre14a76e72022-02-28 20:34:42 -08001198 lastAcknowledgedRole.remove(deviceId);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001199
1200 DeviceProvider provider = getProvider(deviceId);
1201 if (provider != null) {
1202 log.info("Triggering disconnect for device {}", deviceId);
1203 try {
1204 provider.triggerDisconnect(deviceId);
1205 } catch (UnsupportedOperationException e) {
1206 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1207 }
1208 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001209 }
tomf80c9722014-09-24 14:49:18 -07001210 }
1211 }
samuel738dfaf2015-07-11 11:08:57 +08001212
1213 @Override
1214 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001215 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001216 Set<Device> results = new HashSet<>();
1217 Iterable<Device> devices = store.getDevices();
1218 if (devices != null) {
1219 devices.forEach(d -> {
1220 if (type.equals(d.type())) {
1221 results.add(d);
1222 }
1223 });
1224 }
1225 return results;
1226 }
1227
1228 @Override
1229 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001230 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001231 Set<Device> results = new HashSet<>();
1232 Iterable<Device> availableDevices = store.getAvailableDevices();
1233 if (availableDevices != null) {
1234 availableDevices.forEach(d -> {
1235 if (type.equals(d.type())) {
1236 results.add(d);
1237 }
1238 });
1239 }
1240 return results;
1241 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001242
1243 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001244 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1245 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301246 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001247 if (event.subject().getClass() == ConnectPoint.class) {
1248 deviceId = ((ConnectPoint) event.subject()).deviceId();
1249 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001250 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301251 deviceId = (DeviceId) event.subject();
1252 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001253 return deviceId;
1254 }
1255
1256 @Override
1257 public boolean isRelevant(NetworkConfigEvent event) {
1258 DeviceId deviceId = extractDeviceId(event);
1259
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001260 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301261 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1262 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001263 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001264 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001265 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001266 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001267 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001268 }
1269
1270 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001271 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001272 DeviceEvent de = null;
1273 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001274 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001275 DeviceId did = (DeviceId) event.subject();
1276 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001277 BasicDeviceConfig cfg =
1278 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001279
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001280 if (!isAllowed(cfg)) {
1281 kickOutBadDevice(did);
1282 } else {
1283 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001284 DeviceDescription desc =
1285 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001286 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001287 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001288 store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001289 }
1290 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001291 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1292 DeviceId did = (DeviceId) event.subject();
1293 DeviceProvider dp = getProvider(did);
1294 if (!event.config().isPresent() ||
1295 getDevice(did) == null || dp == null) {
1296 // sanity check failed, ignore
1297 return;
1298 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001299 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001300 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001301 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1302 .collect(Collectors.toList());
1303 complete.addAll(portConfig.portDescriptions());
1304 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001305 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1306 DeviceId did = (DeviceId) event.subject();
1307 DeviceProvider dp = getProvider(did);
1308 Device dev = getDevice(did);
1309 DeviceDescription desc =
1310 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1311 Optional<Config> prevConfig = event.prevConfig();
Anurag Chadha61946392020-08-28 15:18:03 +05301312 if (desc != null) { // Fix for NPE due to desc being null
1313 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1314 }
Palash Kalaa06a6162017-11-15 20:42:40 +09001315 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001316 store.createOrUpdateDevice(dp.id(), did, desc);
Palash Kalaa06a6162017-11-15 20:42:40 +09001317 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001318 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001319 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001320 DeviceId did = cpt.deviceId();
1321 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001322
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001323 // Note: assuming PortOperator can modify existing port,
1324 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001325 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001326 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301327 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001328 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001329 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001330 }
1331
1332 if (de != null) {
1333 post(de);
1334 }
1335 }
1336
Simon Hunt8f60ff82017-04-24 17:19:30 -07001337 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001338 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001339 Device badDevice = getDevice(deviceId);
1340 if (badDevice != null) {
1341 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001342 }
1343 }
1344 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001345
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001346 @Override
1347 @SafeVarargs
1348 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001349 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001350 checkNotNull(portOp);
1351
1352 portOp.bindService(networkConfigService);
1353
1354 // update both portOpsIndex and portOps
1355 synchronized (portOpsIndex) {
1356 for (Class<? extends Config<ConnectPoint>> config : configs) {
1357 portOpsIndex.put(config, portOp);
1358 }
1359
1360 portOps.add(portOp);
1361 }
1362
1363 // TODO: Should we be applying to all existing Ports?
1364 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001365 .map(Device::id)
1366 .filter(mastershipService::isLocalMaster)
1367 // for each locally managed Device, update all port descriptions
1368 .map(did -> {
1369 ProviderId pid = Optional.ofNullable(getProvider(did))
1370 .map(Provider::id)
1371 .orElse(null);
1372 if (pid == null) {
1373 log.warn("Provider not found for {}", did);
1374 return ImmutableList.<DeviceEvent>of();
1375 }
1376 List<PortDescription> pds
1377 = store.getPortDescriptions(pid, did)
1378 .map(pdesc -> applyAllPortOps(did, pdesc))
1379 .collect(Collectors.toList());
1380 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001381 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001382 // ..and port port update event if necessary
1383 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001384 }
1385
1386 @Override
1387 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1388 checkNotNull(portOp);
1389
1390
1391 // remove all portOp
1392 synchronized (portOpsIndex) {
1393 portOps.remove(portOp);
1394
1395 // had to do this since COWArrayList iterator doesn't support remove
1396 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1397 }
1398
1399 }
1400
1401 /**
1402 * Merges the appropriate PortConfig with the description.
1403 *
1404 * @param did ID of the Device where the port is attached
1405 * @param desc {@link PortDescription}
1406 * @return merged {@link PortDescription}
1407 */
1408 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1409 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1410 }
1411
1412 /**
1413 * Merges the appropriate PortConfig with the description.
1414 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001415 * @param cpt ConnectPoint where the port is attached
1416 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001417 * @return merged {@link PortDescription}
1418 */
1419 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1420 PortDescription work = desc;
1421 for (PortConfigOperator portOp : portOps) {
1422 work = portOp.combine(cpt, work);
1423 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001424 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001425 }
1426
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001427 /**
debmaiti9553ed72019-03-18 14:27:42 +05301428 * Merges the appropriate PortConfig with the description.
1429 *
1430 * @param cpt ConnectPoint where the port is attached
1431 * @param desc {@link PortDescription}
1432 * @param prevConfig previous configuration
1433 * @return merged {@link PortDescription}
1434 */
1435 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1436 Optional<Config> prevConfig) {
1437 PortDescription work = desc;
1438 for (PortConfigOperator portOp : portOps) {
1439 work = portOp.combine(cpt, work, prevConfig);
1440 }
1441 return portAnnotationOp.combine(cpt, work, prevConfig);
1442 }
1443
1444 /**
pierventre2bb50162022-01-03 17:19:24 +01001445 * Handler for remote probe requests.
1446 *
1447 * @param deviceId the device to check
1448 * @return whether or not the device is reachable
1449 */
1450 private boolean handleProbeRequest(DeviceId deviceId) {
1451 int attempt = 0;
1452 // Let's do a number of attempts
1453 while (attempt < PROBE_ATTEMPTS) {
1454 if (!probeReachability(deviceId)) {
1455 return false;
1456 }
1457 attempt++;
1458 }
1459 return true;
1460 }
1461
1462 /**
1463 * Update the mastership for this device. If there is a node able
1464 * to reach the device and this node is the master move the
1465 * mastership to the next node still connected to this device.
1466 * If the current node is a backup, it demotes itself to the bottom
1467 * of the candidates list
1468 *
1469 * @param deviceId the device for which we have to update the mastership
1470 * @return the NodeId of any node that can reach the device, or null if
1471 * none of the ONOS instances can reach the device
1472 */
1473 private NodeId updateMastershipFor(DeviceId deviceId) {
1474 Map<NodeId, CompletableFuture<Boolean>> probes = Maps.newHashMap();
1475 // Request a probe only if the node is ready
1476 for (ControllerNode onosNode : clusterService.getNodes()) {
1477 if (!clusterService.getState(onosNode.id()).isReady() || localNodeId.equals(onosNode.id())) {
1478 continue;
1479 }
1480 probes.put(onosNode.id(), communicationService.sendAndReceive(deviceId, PROBE_SUBJECT, SERIALIZER::encode,
1481 SERIALIZER::decode, onosNode.id()));
1482 }
1483
1484 // Returns the first node able to reach the device
1485 // FIXME [SDFAB-935] optimize by looking at the MastershipInfo
1486 boolean isReachable;
1487 NodeId nextMaster = null;
1488 // FIXME Should we expose timeout? Understand if there is need to signal to the caller
1489 for (Map.Entry<NodeId, CompletableFuture<Boolean>> probe : probes.entrySet()) {
1490 isReachable = Tools.futureGetOrElse(probe.getValue(), PROBE_TIMEOUT_MILLIS,
1491 TimeUnit.MILLISECONDS, Boolean.FALSE);
1492 if (isReachable) {
1493 nextMaster = probe.getKey();
1494 }
1495 }
1496
1497 // FIXME [SDFAB-935] optimize demote by looking at the MastershipInfo;
1498 if (nextMaster != null) {
1499 log.info("Device {} is still connected to {}", deviceId, nextMaster);
1500 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1501 if (myRole == MASTER) {
1502 log.info("Handing over the mastership of {} to next master {}", deviceId, nextMaster);
1503 mastershipAdminService.setRole(nextMaster, deviceId, MASTER);
pierventrebc91cea2022-02-18 05:16:48 -08001504 // Do not demote here because setRole can return before the mastership has been passed.
1505 // Current implementation promotes first the nextMaster as top of candidate list and then
1506 // transfer the leadership. We can use the BACKUP events to do demote or leverage periodic
1507 // checks.
pierventre2bb50162022-01-03 17:19:24 +01001508 } else if (myRole == STANDBY) {
1509 log.info("Demote current instance to the bottom of the candidates list for {}", deviceId);
1510 mastershipAdminService.demote(localNodeId, deviceId);
1511 } else {
1512 log.debug("No valid role for {}", deviceId);
1513 }
1514 }
1515
1516 return nextMaster;
1517 }
1518
pierventre2bb50162022-01-03 17:19:24 +01001519 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001520 * Port Enable/Disable message sent to the device's MASTER node.
1521 */
1522 private class InternalPortUpDownEvent {
1523 private final DeviceId deviceId;
1524 private final PortNumber portNumber;
1525 private final boolean enable;
1526
1527 protected InternalPortUpDownEvent(
1528 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1529 this.deviceId = deviceId;
1530 this.portNumber = portNumber;
1531 this.enable = enable;
1532 }
1533
1534 public DeviceId deviceId() {
1535 return deviceId;
1536 }
1537 public PortNumber portNumber() {
1538 return portNumber;
1539 }
1540 public boolean isEnable() {
1541 return enable;
1542 }
1543
1544 protected InternalPortUpDownEvent() {
1545 this.deviceId = null;
1546 this.portNumber = null;
1547 this.enable = false;
1548 }
1549 }
tomd3097b02014-08-26 10:40:29 -07001550}