blob: 32d2584b4a284d812b33e37223d0cb5a382fd35e [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;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +020025import org.onosproject.cfg.ComponentConfigService;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.cluster.ClusterService;
pierventre2bb50162022-01-03 17:19:24 +010027import org.onosproject.cluster.ControllerNode;
Brian O'Connorabafb502014-12-02 22:26:20 -080028import org.onosproject.cluster.NodeId;
pierventre2bb50162022-01-03 17:19:24 +010029import org.onosproject.mastership.MastershipAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.mastership.MastershipEvent;
31import org.onosproject.mastership.MastershipListener;
32import org.onosproject.mastership.MastershipService;
33import org.onosproject.mastership.MastershipTerm;
34import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070035import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080036import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080037import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080038import org.onosproject.net.DeviceId;
39import org.onosproject.net.MastershipRole;
40import org.onosproject.net.Port;
41import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070042import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030043import org.onosproject.net.config.NetworkConfigEvent;
44import org.onosproject.net.config.NetworkConfigListener;
45import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070046import org.onosproject.net.config.PortConfigOperator;
47import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030048import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090049import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080050import org.onosproject.net.config.basics.PortAnnotationConfig;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080051import org.onosproject.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080052import org.onosproject.net.device.DefaultPortDescription;
53import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DeviceDescription;
55import org.onosproject.net.device.DeviceEvent;
56import org.onosproject.net.device.DeviceListener;
57import org.onosproject.net.device.DeviceProvider;
58import org.onosproject.net.device.DeviceProviderRegistry;
59import org.onosproject.net.device.DeviceProviderService;
60import org.onosproject.net.device.DeviceService;
61import org.onosproject.net.device.DeviceStore;
62import org.onosproject.net.device.DeviceStoreDelegate;
63import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070064import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030065import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080066import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080067import org.onosproject.net.provider.Provider;
68import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070069import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
70import org.onosproject.store.cluster.messaging.MessageSubject;
71import org.onosproject.store.serializers.KryoNamespaces;
72import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080073import org.onosproject.upgrade.UpgradeService;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +020074import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070075import org.osgi.service.component.annotations.Activate;
76import org.osgi.service.component.annotations.Component;
77import org.osgi.service.component.annotations.Deactivate;
78import org.osgi.service.component.annotations.Reference;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +020079import org.osgi.service.component.annotations.Modified;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070080import org.osgi.service.component.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070081import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070082
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070083import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070084import java.util.Collection;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +020085import java.util.Dictionary;
Simon Huntffbad3b2017-05-16 15:37:51 -070086import java.util.HashSet;
87import java.util.List;
88import java.util.Map;
89import java.util.Objects;
90import java.util.Optional;
91import java.util.Set;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +020092import java.util.Properties;
Simon Huntffbad3b2017-05-16 15:37:51 -070093import java.util.concurrent.CompletableFuture;
94import java.util.concurrent.ConcurrentHashMap;
95import java.util.concurrent.CopyOnWriteArrayList;
96import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070097import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070098import java.util.concurrent.ScheduledExecutorService;
99import java.util.concurrent.TimeUnit;
pierventre4af48792021-12-02 09:42:28 +0100100import java.util.concurrent.atomic.AtomicBoolean;
Simon Huntffbad3b2017-05-16 15:37:51 -0700101import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -0800102
Ray Milkey9ef22232016-07-14 12:42:37 -0700103import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700104import static com.google.common.base.Preconditions.checkState;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200105import static com.google.common.base.Strings.isNullOrEmpty;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700106import static com.google.common.collect.Multimaps.newListMultimap;
107import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700108import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -0700109import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
pierventre4af48792021-12-02 09:42:28 +0100110import static java.lang.System.currentTimeMillis;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200111import static org.onlab.util.Tools.get;
Ray Milkey9ef22232016-07-14 12:42:37 -0700112import static org.onlab.util.Tools.groupedThreads;
113import static org.onosproject.net.MastershipRole.MASTER;
114import static org.onosproject.net.MastershipRole.NONE;
115import static org.onosproject.net.MastershipRole.STANDBY;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200116import static org.onosproject.net.device.impl.OsgiPropertyConstants.ROLE_TIMEOUT_SECONDS;
117import static org.onosproject.net.device.impl.OsgiPropertyConstants.ROLE_TIMEOUT_SECONDS_DEFAULT;
Ray Milkey9ef22232016-07-14 12:42:37 -0700118import static org.onosproject.security.AppGuard.checkPermission;
119import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
120import static org.slf4j.LoggerFactory.getLogger;
121
tomd3097b02014-08-26 10:40:29 -0700122/**
tome4729872014-09-23 00:37:37 -0700123 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700124 */
Ray Milkey86ad7bb2018-09-27 12:32:28 -0700125@Component(immediate = true,
126 service = {DeviceService.class, DeviceAdminService.class,
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200127 DeviceProviderRegistry.class, PortConfigOperatorRegistry.class },
128 property = {
129 ROLE_TIMEOUT_SECONDS + ":Integer=" + ROLE_TIMEOUT_SECONDS_DEFAULT
130 })
tom41a2c5f2014-09-19 09:20:35 -0700131public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700132 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700133 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700134
tome5ec3fd2014-09-04 15:18:06 -0700135 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
136 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
137 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
138 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700139 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700140 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700141
tom5f38b3a2014-08-27 23:50:54 -0700142 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700143
alshabib339a3d92014-09-26 17:54:32 -0700144 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700145
tomc78acee2014-09-24 15:16:55 -0700146 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700147 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700148
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800149 private ScheduledExecutorService backgroundService;
150
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700151 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
152
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700153 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom41a2c5f2014-09-19 09:20:35 -0700154 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700155
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700156 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tomb41d1ac2014-09-24 01:51:24 -0700157 protected ClusterService clusterService;
158
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700159 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700160 protected MastershipService mastershipService;
161
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700162 @Reference(cardinality = ReferenceCardinality.MANDATORY)
pierventre2bb50162022-01-03 17:19:24 +0100163 protected MastershipAdminService mastershipAdminService;
164
165 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700166 protected MastershipTermService termService;
167
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700168 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800169 protected UpgradeService upgradeService;
170
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700171 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700172 protected NetworkConfigService networkConfigService;
173
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700174 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700175 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700176
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200177 @Reference(cardinality = ReferenceCardinality.MANDATORY)
178 protected ComponentConfigService cfgService;
179
pierventre2bb50162022-01-03 17:19:24 +0100180 private ExecutorService clusterRequestExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700181 /**
182 * List of all registered PortConfigOperator.
183 */
184 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
185
186 /**
187 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
188 */
189 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700190 = synchronizedListMultimap(
191 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700192
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800193 // not part of portOps. must be executed at the end
194 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900195 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800196
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700197 private static final MessageSubject PORT_UPDOWN_SUBJECT =
198 new MessageSubject("port-updown-req");
199
pierventre2bb50162022-01-03 17:19:24 +0100200 private static final MessageSubject PROBE_SUBJECT =
201 new MessageSubject("probe-req");
202 private static final long PROBE_TIMEOUT_MILLIS = 5000;
203 private static final int PROBE_ATTEMPTS = 3;
204
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700205 private static final Serializer SERIALIZER = Serializer.using(
206 KryoNamespace.newBuilder()
207 .register(KryoNamespaces.API)
208 .register(InternalPortUpDownEvent.class)
209 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
210 .build("DeviceManager"));
211
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800212 /**
213 * Local storage for connectivity status of devices.
214 */
215 private class LocalStatus {
216 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700217 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800218
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700219 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800220 connected = b;
221 dateTime = now;
222 }
223 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700224
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800225 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
226 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700227
pierventre4af48792021-12-02 09:42:28 +0100228 // To remember whether or not the role was acknowledged by the device
229 private final Map<DeviceId, Long> roleToAcknowledge =
230 Maps.newConcurrentMap();
231 private ScheduledExecutorService backgroundRoleChecker;
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200232
233
234 /**
235 * Timeout for role acknowledgement check.
236 **/
237 protected int roleTimeoutSeconds = ROLE_TIMEOUT_SECONDS_DEFAULT;
pierventre4af48792021-12-02 09:42:28 +0100238
pierventre14a76e72022-02-28 20:34:42 -0800239 // FIXME join this map with roleToAcknowledge and fix the back to back event issue here
240 private final Map<DeviceId, MastershipRole> lastAcknowledgedRole =
241 Maps.newConcurrentMap();
242
tomd3097b02014-08-26 10:40:29 -0700243 @Activate
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200244 public void activate(ComponentContext context) {
245 cfgService.registerProperties(getClass());
246
247 modified(context);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800248 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900249 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800250 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
251
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800252 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700253 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700254 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800255
tomf80c9722014-09-24 14:49:18 -0700256 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700257 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700258 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700259 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800260
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700261 backgroundService.scheduleWithFixedDelay(() -> {
262 try {
263 mastershipCheck();
264 } catch (Exception e) {
pierventre4af48792021-12-02 09:42:28 +0100265 log.error("Exception thrown during mastership integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800266 }
267 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700268
pierventre2bb50162022-01-03 17:19:24 +0100269 clusterRequestExecutor = newSingleThreadExecutor();
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700270
pierventre2bb50162022-01-03 17:19:24 +0100271 communicationService.addSubscriber(
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700272 PORT_UPDOWN_SUBJECT,
273 SERIALIZER::decode,
274 this::handlePortRequest,
pierventre2bb50162022-01-03 17:19:24 +0100275 clusterRequestExecutor);
276
277 communicationService.addSubscriber(
278 PROBE_SUBJECT,
279 SERIALIZER::decode,
280 this::handleProbeRequest,
281 SERIALIZER::encode,
282 clusterRequestExecutor);
pierventre4af48792021-12-02 09:42:28 +0100283
284 backgroundRoleChecker = newSingleThreadScheduledExecutor(
285 groupedThreads("onos/device", "manager-role", log));
286 backgroundRoleChecker.scheduleAtFixedRate(() -> {
287 try {
288 roleCheck();
289 } catch (Exception e) {
290 log.error("Exception thrown while verifying role acknowledgement from all devices", e);
291 }
292 }, 0, 10, TimeUnit.SECONDS);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700293
tomd3097b02014-08-26 10:40:29 -0700294 log.info("Started");
295 }
296
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200297 @Modified
298 public void modified(ComponentContext context) {
299 Dictionary<?, ?> properties = context != null ? context.getProperties() : new Properties();
300 String roleTimeoutSec = get(properties, ROLE_TIMEOUT_SECONDS);
301 int oldRoleTimeoutSeconds = roleTimeoutSeconds;
302 try {
303 roleTimeoutSeconds = isNullOrEmpty(roleTimeoutSec) ?
304 oldRoleTimeoutSeconds : Integer.parseInt(roleTimeoutSec.trim());
305 } catch (NumberFormatException e) {
306 log.warn("Can't parse {}, setting the old value {}", roleTimeoutSec, oldRoleTimeoutSeconds, e);
307 roleTimeoutSeconds = oldRoleTimeoutSeconds;
308 }
309 log.info("Modified. Values = {}: {}",
310 ROLE_TIMEOUT_SECONDS, roleTimeoutSeconds);
311 }
312
tomd3097b02014-08-26 10:40:29 -0700313 @Deactivate
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200314 public void deactivate(ComponentContext context) {
315 cfgService.unregisterProperties(getClass(), true);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800316 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700317 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700318 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700319 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700320 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700321 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
pierventre2bb50162022-01-03 17:19:24 +0100322 clusterRequestExecutor.shutdown();
pierventre4af48792021-12-02 09:42:28 +0100323 backgroundRoleChecker.shutdown();
tomd3097b02014-08-26 10:40:29 -0700324 log.info("Stopped");
325 }
326
327 @Override
tomad2d2092014-09-06 23:24:20 -0700328 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900329 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700330 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700331 }
332
333 @Override
mskala32000d32017-07-14 16:27:06 +0200334 public int getAvailableDeviceCount() {
335 checkPermission(DEVICE_READ);
336 return store.getAvailableDeviceCount();
337 }
338
339 @Override
tom32f66842014-08-27 19:27:47 -0700340 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900341 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700342 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700343 }
344
tom32f66842014-08-27 19:27:47 -0700345 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800346 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900347 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800348 return store.getAvailableDevices();
349 }
350
351 @Override
tom32f66842014-08-27 19:27:47 -0700352 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900353 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700354 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700355 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700356 }
357
358 @Override
tomad2d2092014-09-06 23:24:20 -0700359 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900360 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700361 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700362 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700363 }
364
365 @Override
tom32f66842014-08-27 19:27:47 -0700366 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900367 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700368 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700369 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700370 }
371
372 @Override
sangho538108b2015-04-08 14:29:20 -0700373 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900374 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700375 checkNotNull(deviceId, DEVICE_ID_NULL);
376 return store.getPortStatistics(deviceId);
377 }
378
379 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200380 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900381 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200382 checkNotNull(deviceId, DEVICE_ID_NULL);
383 return store.getPortDeltaStatistics(deviceId);
384 }
385
386 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530387 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
388 checkPermission(DEVICE_READ);
389 checkNotNull(deviceId, DEVICE_ID_NULL);
390 checkNotNull(portNumber, PORT_NUMBER_NULL);
391 return store.getStatisticsForPort(deviceId, portNumber);
392 }
393
394 @Override
395 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
396 checkPermission(DEVICE_READ);
397 checkNotNull(deviceId, DEVICE_ID_NULL);
398 checkNotNull(portNumber, PORT_NUMBER_NULL);
399 return store.getDeltaStatisticsForPort(deviceId, portNumber);
400 }
401
402 @Override
tom32f66842014-08-27 19:27:47 -0700403 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900404 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700405 checkNotNull(deviceId, DEVICE_ID_NULL);
406 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700407 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700408 }
409
410 @Override
tomff7eb7c2014-09-08 12:49:03 -0700411 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900412 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900413
tomff7eb7c2014-09-08 12:49:03 -0700414 checkNotNull(deviceId, DEVICE_ID_NULL);
415 return store.isAvailable(deviceId);
416 }
417
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800418 @Override
419 public String localStatus(DeviceId deviceId) {
420 LocalStatus ls = deviceLocalStatus.get(deviceId);
421 if (ls == null) {
422 return "No Record";
423 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700424 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800425 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
426 }
427
Palash Kala0d817b02018-03-23 18:09:45 +0900428 private boolean isLocallyConnected(DeviceId deviceId) {
429 LocalStatus ls = deviceLocalStatus.get(deviceId);
430 if (ls == null) {
431 return false;
432 }
433 return ls.connected;
434 }
435
Ray Milkey054e23d2018-03-22 13:37:11 -0700436 @Override
437 public long getLastUpdatedInstant(DeviceId deviceId) {
438 LocalStatus ls = deviceLocalStatus.get(deviceId);
439 if (ls == null) {
440 return 0;
441 }
442 return ls.dateTime.toEpochMilli();
443 }
444
pierventrebc91cea2022-02-18 05:16:48 -0800445 // Returns true if the grace period is still on
446 private boolean inGracePeriod(DeviceId deviceId) {
447 LocalStatus ls = deviceLocalStatus.get(deviceId);
448 if (ls == null) {
449 // This should not be possible, unless the device is removed
450 log.warn("Not found a recent local status for {}", deviceId);
451 return true;
452 }
453 DeviceProvider provider = getProvider(deviceId);
454 return ls.connected &&
455 (Instant.now().toEpochMilli() - ls.dateTime.toEpochMilli()) < provider.gracePeriod();
456 }
457
Palash Kala0d817b02018-03-23 18:09:45 +0900458 // Check a device for control channel connectivity
459 // and changes local-status appropriately.
pierventrebc91cea2022-02-18 05:16:48 -0800460 private boolean isReachable(DeviceId deviceId, boolean inGracePeriod) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800461 if (deviceId == null) {
462 return false;
463 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700464 DeviceProvider provider = getProvider(deviceId);
465 if (provider != null) {
pierventre2bb50162022-01-03 17:19:24 +0100466 boolean reachable = probeReachability(deviceId);
Palash Kala0d817b02018-03-23 18:09:45 +0900467 if (reachable && !isLocallyConnected(deviceId)) {
468 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
pierventrebc91cea2022-02-18 05:16:48 -0800469 } else if (!reachable && isLocallyConnected(deviceId) && !inGracePeriod) {
470 // Do not update if the grace period is still on
Palash Kala0d817b02018-03-23 18:09:45 +0900471 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
472 }
473 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700474 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800475 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700476 return false;
477 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700478 }
479
tome5ec3fd2014-09-04 15:18:06 -0700480 @Override
481 public void removeDevice(DeviceId deviceId) {
482 checkNotNull(deviceId, DEVICE_ID_NULL);
483 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700484 if (event != null) {
485 log.info("Device {} administratively removed", deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700486 }
tome5ec3fd2014-09-04 15:18:06 -0700487 }
488
Thomas Vachuska811ea2b2020-02-11 10:20:10 -0800489 @Override
490 public void removeDevicePorts(DeviceId deviceId) {
491 checkNotNull(deviceId, DEVICE_ID_NULL);
492 if (isAvailable(deviceId)) {
493 log.debug("Cannot remove ports of device {} while it is available.", deviceId);
494 return;
495 }
496
497 List<PortDescription> portDescriptions = ImmutableList.of();
498 List<DeviceEvent> events = store.updatePorts(getProvider(deviceId).id(),
499 deviceId, portDescriptions);
500 if (events != null) {
501 for (DeviceEvent event : events) {
502 post(event);
503 }
504 }
505 }
506
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700507 private void handlePortRequest(InternalPortUpDownEvent event) {
508 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700509 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon436c60a2021-01-01 14:23:29 +0000510 checkNotNull(event.portNumber(), PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700511 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
512 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
513 }
514
515 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
516 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700517 DeviceProvider provider = getProvider(deviceId);
518 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700519 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700520 portNumber, deviceId,
521 (enable) ? "UP" : "DOWN");
522 provider.changePortState(deviceId, portNumber, enable);
523 } else {
524 log.warn("Provider not found for {}", deviceId);
525 }
526 }
527
528 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700529 public void changePortState(DeviceId deviceId, PortNumber portNumber,
530 boolean enable) {
531 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon436c60a2021-01-01 14:23:29 +0000532 checkNotNull(portNumber, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700533 NodeId masterId = mastershipService.getMasterFor(deviceId);
534
Ray Milkey4ef245e2018-05-10 15:41:16 -0700535 if (masterId == null) {
536 // No master found; device is offline
537 log.info("No master found for port state change for {}", deviceId);
538 return;
539 }
540
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700541 if (!masterId.equals(localNodeId)) {
542 //Send the request to the master node for the device
543 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
544 deviceId, masterId);
545 communicationService.unicast(
546 new InternalPortUpDownEvent(deviceId, portNumber, enable),
547 PORT_UPDOWN_SUBJECT,
548 SERIALIZER::encode,
549 masterId).whenComplete((r, error) -> {
550 if (error != null) {
551 log.warn("Failed to send packet-updown-req to {}", masterId, error);
552 }
553 });
554 } else {
555 changePortStateAtMaster(deviceId, portNumber, enable);
556 }
557 }
558
559 @Override
samuele1fa7322015-07-14 16:35:16 +0800560 protected DeviceProviderService createProviderService(
561 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700562 return new InternalDeviceProviderService(provider);
563 }
564
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800565 /**
566 * Checks if all the reachable devices have a valid mastership role.
567 */
568 private void mastershipCheck() {
569 log.debug("Checking mastership");
570 for (Device device : getDevices()) {
571 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700572 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
573 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
pierventrebc91cea2022-02-18 05:16:48 -0800574
575 log.debug("Device {} local status is {}", deviceId, localStatus(deviceId));
576 final boolean isGracePeriodOn = inGracePeriod(deviceId);
577 final boolean isReachable = isReachable(deviceId, isGracePeriodOn);
578 // Passed the grace period and it is still not reachable
579 if (!isGracePeriodOn && !isReachable) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700580 if (myRole != NONE) {
pierventre2bb50162022-01-03 17:19:24 +0100581 // Verify if the device is fully disconnected from the cluster
582 if (updateMastershipFor(deviceId) == null
583 && myRole == MASTER && isAvailable(deviceId)) {
584 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Andrea Campanella3971df82022-04-27 13:24:34 +0200585 // Following the deviceDisconnected method logic (line 734) we are marking also all the
586 // ports as disabled.
587 List<PortDescription> descs = store.getPortDescriptions(getProvider(deviceId).id(), deviceId)
588 .map(desc -> ensurePortEnabledState(desc, false))
589 .collect(Collectors.toList());
590 store.updatePorts(getProvider(deviceId).id(), deviceId, descs);
pierventre2bb50162022-01-03 17:19:24 +0100591 post(store.markOffline(deviceId));
helenyrwufd296b62016-06-22 17:43:02 -0700592 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530593 } else {
pierventrebc91cea2022-02-18 05:16:48 -0800594 // Firstly get a role and then check if the device is available in the store.
595 // if it is, if this node is the master and the device is fully disconnected
596 // from the cluster mark the device offline. In principle, this condition should
597 // never be hit unless in a device removed phase for NONE mastership roles.
pierventre2bb50162022-01-03 17:19:24 +0100598 try {
599 mastershipService.requestRoleFor(deviceId).get();
600 } catch (InterruptedException e) {
601 Thread.currentThread().interrupt();
602 log.error("Interrupted waiting for Mastership", e);
603 } catch (ExecutionException e) {
604 log.error("Encountered an error waiting for Mastership", e);
605 }
606
607 MastershipTerm term = termService.getMastershipTerm(deviceId);
608 if (updateMastershipFor(deviceId) == null &&
609 term != null && localNodeId.equals(term.master()) &&
610 isAvailable(deviceId)) {
611 log.info("Marking unreachable device {} offline", deviceId);
Andrea Campanella3971df82022-04-27 13:24:34 +0200612 // Following the deviceDisconnected method logic (line 734) we are marking also all the
613 // ports as disabled.
614 List<PortDescription> descs = store.getPortDescriptions(getProvider(deviceId).id(), deviceId)
615 .map(desc -> ensurePortEnabledState(desc, false))
616 .collect(Collectors.toList());
617 store.updatePorts(getProvider(deviceId).id(), deviceId, descs);
pierventre2bb50162022-01-03 17:19:24 +0100618 post(store.markOffline(deviceId));
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800619 }
helenyrwufd296b62016-06-22 17:43:02 -0700620 }
pierventre2bb50162022-01-03 17:19:24 +0100621 roleToAcknowledge.remove(deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800622 } else if (isReachable) {
623 // If this node is the master, ensure the device is marked online.
624 if (myRole == MASTER && canMarkOnline(device)) {
pierventre14a76e72022-02-28 20:34:42 -0800625 log.debug("Can mark online {}", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800626 post(store.markOnline(deviceId));
627 }
628
pierventre14a76e72022-02-28 20:34:42 -0800629 log.debug("{} is reachable - reasserting the role", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800630
631 // Device is still reachable. It is useful for some protocols
632 // to reassert the role. Note: NONE triggers request to MastershipService
633 reassertRole(deviceId, myRole);
634 } else {
635 // Do not proceed furthermore if the grace period is still on
636 log.debug("Skipping mastership check for {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800637 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800638 }
639 }
640
pierventre4af48792021-12-02 09:42:28 +0100641 /**
642 * Checks if all the devices have acknowledged the mastership role.
643 */
644 private void roleCheck() {
645 log.debug("Checking role");
646 for (Device device : getDevices()) {
647 final DeviceId deviceId = device.id();
648 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
649 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
650 final AtomicBoolean exists = new AtomicBoolean(false);
651 final Long ts = roleToAcknowledge.compute(deviceId, (key, value) -> {
652 if (value == null) {
653 return null;
654 }
655 exists.set(true);
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200656 if (currentTimeMillis() - value < (roleTimeoutSeconds * 1000)) {
pierventre4af48792021-12-02 09:42:28 +0100657 return value;
658 }
659 return null;
660 });
661 // Nobody applied the role recently
662 if (!exists.get()) {
663 log.trace("Role was not applied or it has been acknowledged for device {}", deviceId);
664 continue;
665 }
666 // Timeout still on
667 if (ts != null) {
Andrea Campanellaa42a6ab2022-06-29 16:24:00 +0200668 log.debug("Timeout expires in {} ms", ((roleTimeoutSeconds * 1000) - currentTimeMillis() + ts));
pierventre4af48792021-12-02 09:42:28 +0100669 continue;
670 }
671 if (myRole != MASTER) {
672 log.debug("Timeout is expired but current role is not MASTER ({}), nothing to do", myRole);
673 continue;
674 }
pierventrebc91cea2022-02-18 05:16:48 -0800675 // Switch failed to acknowledge master role we asked for.
676 // Yield mastership to other instance
pierventre4af48792021-12-02 09:42:28 +0100677 log.warn("Failed to assert role onto device {}. requested={}, no response",
678 deviceId, myRole);
pierventre2bb50162022-01-03 17:19:24 +0100679 updateMastershipFor(deviceId);
pierventre4af48792021-12-02 09:42:28 +0100680 }
681 }
682
Andrea Campanella3971df82022-04-27 13:24:34 +0200683 PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
684 if (desc.isEnabled() != enabled) {
685 return DefaultPortDescription.builder(desc)
686 .isEnabled(enabled)
687 .build();
688 }
689 return desc;
690 }
691
tomd3097b02014-08-26 10:40:29 -0700692 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700693 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700694 extends AbstractProviderService<DeviceProvider>
695 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700696
tomcfde0622014-09-09 11:02:42 -0700697 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700698 super(provider);
699 }
700
Ray Milkey33306ba2018-09-20 13:27:25 -0700701 /**
702 * Apply role in reaction to provider event.
703 *
704 * @param deviceId device identifier
705 * @param newRole new role to apply to the device
706 * @return true if the request was sent to provider
707 */
708 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
709
710 if (newRole.equals(MastershipRole.NONE)) {
711 //no-op
712 return true;
713 }
714
715 DeviceProvider provider = provider();
716 if (provider == null) {
717 log.warn("Provider for {} was not found. Cannot apply role {}",
718 deviceId, newRole);
719 return false;
720 }
pierventre4af48792021-12-02 09:42:28 +0100721 // Start the timer
722 roleToAcknowledge.put(deviceId, currentTimeMillis());
Ray Milkey33306ba2018-09-20 13:27:25 -0700723 provider.roleChanged(deviceId, newRole);
724 // not triggering probe when triggered by provider service event
725 return true;
726 }
727
tomd3097b02014-08-26 10:40:29 -0700728 @Override
alshabibb7b40632014-09-28 21:30:00 -0700729 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700730 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700731 checkNotNull(deviceId, DEVICE_ID_NULL);
732 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700733 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700734
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700735 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800736
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700737 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
738 if (!isAllowed(cfg)) {
739 log.warn("Device {} is not allowed", deviceId);
740 return;
741 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200742 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700743 // Generate updated description and establish my Role
744 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900745 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
746 if (annoConfig != null) {
747 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
748 }
749
pier388ec252020-04-15 20:53:14 +0200750 // Wait for the end of the election. sync call of requestRoleFor
751 // wait only 3s and it is not entirely safe since the leadership
752 // election timer can be higher.
753 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
jaegonkim8eabcec2018-07-27 23:40:43 +0900754 log.info("Local role is {} for {}", role, deviceId);
pier388ec252020-04-15 20:53:14 +0200755 store.createOrUpdateDevice(provider().id(), deviceId, deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700756 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700757
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200758 if (portConfig != null) {
759 //updating the ports if configration exists
760 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
761 .collect(Collectors.toList());
762 complete.addAll(portConfig.portDescriptions());
763 List<PortDescription> portDescriptions = complete.stream()
764 .map(e -> applyAllPortOps(deviceId, e))
765 .collect(Collectors.toList());
766 store.updatePorts(provider().id(), deviceId, portDescriptions);
767 }
768
helenyrwufd296b62016-06-22 17:43:02 -0700769 if (deviceDescription.isDefaultAvailable()) {
770 log.info("Device {} connected", deviceId);
771 } else {
772 log.info("Device {} registered", deviceId);
773 }
tomd3097b02014-08-26 10:40:29 -0700774 }
775
776 @Override
777 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700778 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700779 checkValidity();
pierventre2bb50162022-01-03 17:19:24 +0100780 // Update the local status
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700781 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Andrea Campanella18fdda82021-09-13 12:37:36 +0200782 log.info("Device {} disconnected from this node: {}", deviceId,
783 clusterService.getLocalNode().id());
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700784
pierventrebc91cea2022-02-18 05:16:48 -0800785 // If none can reach the device, we will continue with the disconnection logic.
786 // If there is one instance that reported device is still reachable, we hand over
787 // the mastership to it if we are the current master, otherwise if we are a backup
788 // we demote ourselves to the bottom of the backups list
pierventre2bb50162022-01-03 17:19:24 +0100789 if (updateMastershipFor(deviceId) == null) {
790 log.info("Device {} is fully disconnected from the cluster", deviceId);
791 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
792 .map(desc -> ensurePortEnabledState(desc, false))
793 .collect(Collectors.toList());
794 store.updatePorts(this.provider().id(), deviceId, descs);
Yafit Hadara9a73de2015-09-06 13:52:52 +0300795
Madan Jampanic6e574f2015-05-29 13:41:52 -0700796 try {
pierventre2bb50162022-01-03 17:19:24 +0100797 if (mastershipService.isLocalMaster(deviceId)) {
798 post(store.markOffline(deviceId));
799 }
800 } catch (IllegalStateException e) {
801 log.warn("Failed to mark {} offline", deviceId);
802 // only the MASTER should be marking off-line in normal cases,
803 // but if I was the last STANDBY connection, etc. and no one else
804 // was there to mark the device offline, this instance may need to
805 // temporarily request for Master Role and mark offline.
806
807 //there are times when this node will correctly have mastership, BUT
808 //that isn't reflected in the ClockManager before the device disconnects.
809 //we want to let go of the device anyways, so make sure this happens.
810
811 // FIXME: Store semantics leaking out as IllegalStateException.
812 // Consider revising store API to handle this scenario.
813 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
814 roleFuture.whenComplete((role, error) -> {
815 MastershipTerm term = termService.getMastershipTerm(deviceId);
816 // TODO: Move this type of check inside device clock manager, etc.
817 if (term != null && localNodeId.equals(term.master())) {
818 log.info("Retry marking {} offline", deviceId);
819 post(store.markOffline(deviceId));
820 } else {
821 log.info("Failed again marking {} offline. {}", deviceId, role);
822 }
823 });
824 } finally {
pierventre4af48792021-12-02 09:42:28 +0100825 roleToAcknowledge.remove(deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700826 }
tom0efbb1d2014-09-09 11:54:28 -0700827 }
pierventre2bb50162022-01-03 17:19:24 +0100828
tomd3097b02014-08-26 10:40:29 -0700829 }
830
831 @Override
alshabibb7b40632014-09-28 21:30:00 -0700832 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700833 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700834 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700835 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700836 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700837 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700838 // Never been a master for this device
839 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800840 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700841 return;
842 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200843 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
844 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200845 // Updating the ports if configuration exists (on new lists as
846 // the passed one might be immutable)
847 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200848 portDescriptions.addAll(portConfig.portDescriptions());
849 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700850 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700851 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700852 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700853 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800854 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800855 if (events != null) {
856 for (DeviceEvent event : events) {
857 post(event);
858 }
tom32f66842014-08-27 19:27:47 -0700859 }
tomd3097b02014-08-26 10:40:29 -0700860 }
861
862 @Override
alshabibb7b40632014-09-28 21:30:00 -0700863 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700864 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700865 checkNotNull(deviceId, DEVICE_ID_NULL);
866 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700867 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700868
Madan Jampani565a66a2015-07-25 17:01:13 -0700869 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700870 // Never been a master for this device
871 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700872 log.trace("Ignoring {} port update on standby node. {}", deviceId,
873 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700874 return;
875 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700876 Device device = getDevice(deviceId);
877 if (device == null) {
878 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530879 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700880 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100881 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
882 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700883 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700884 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700885 deviceId,
886 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700887 portDescription = ensurePortEnabledState(storedPortDesc,
888 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300889 }
890
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700891 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800892 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700893 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700894 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700895 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800896 log.info("Device {} port {} status changed (enabled={})",
897 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700898 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700899 }
tomd3097b02014-08-26 10:40:29 -0700900 }
tom3f2bbd72014-09-24 12:07:58 -0700901
902 @Override
Michal Machce774332017-01-25 11:02:55 +0100903 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
904
905 checkNotNull(deviceId, DEVICE_ID_NULL);
906 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
907 checkValidity();
908
909 if (!mastershipService.isLocalMaster(deviceId)) {
910 // Never been a master for this device
911 // any update will be ignored.
912 log.trace("Ignoring {} port update on standby node. {}", deviceId,
913 basePortDescription);
914 return;
915 }
916
917 Device device = getDevice(deviceId);
918 if (device == null) {
919 log.trace("Device not found: {}", deviceId);
920 }
921
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800922 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
923 .isRemoved(true)
924 .build();
925
Michal Machce774332017-01-25 11:02:55 +0100926 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
927 deviceId,
928 newPortDescription);
929 if (event != null) {
930 log.info("Device {} port {} status changed", deviceId, event.port().number());
931 post(event);
932 }
933 }
934
935 @Override
samuele1fa7322015-07-14 16:35:16 +0800936 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700937 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700938 // Several things can happen here:
939 // 1. request and response match
940 // 2. request and response don't match
941 // 3. MastershipRole and requested match (and 1 or 2 are true)
942 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
943 //
944 // 2, 4, and 3 with case 2 are failure modes.
945
tom3f2bbd72014-09-24 12:07:58 -0700946 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700947
Madan Jampanif2af7712015-05-29 18:43:52 -0700948 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700949 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700950
951 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800952 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530953 log.warn("Failed to assert role onto Device {}", deviceId);
pierventre4af48792021-12-02 09:42:28 +0100954 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100955 updateMastershipFor(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700956 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700957 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700958
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800959 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
960
961 if (requested == null) {
962 // Provider is not able to reconcile role responses with
963 // requests. We assume what was requested is what we expect.
964 // This will work only if mastership doesn't change too often,
965 // and devices are left enough time to provide responses before
966 // a different role is requested.
967 requested = expected;
968 }
969
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700970 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800971 if (Objects.equals(requested, expected)) {
pierventre14a76e72022-02-28 20:34:42 -0800972 if (log.isDebugEnabled()) {
973 log.debug("Role has been acknowledged for device {}", deviceId);
974 } else if (!requested.equals(lastAcknowledgedRole.get(deviceId))) {
975 log.info("Role has been acknowledged for device {}", deviceId);
976 }
977 // Update the last known role and stop the timer
978 lastAcknowledgedRole.put(deviceId, requested);
pierventre4af48792021-12-02 09:42:28 +0100979 roleToAcknowledge.remove(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700980 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800981 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
982 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800983 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700984 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800985 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700986 }
987 } else {
988 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200989 log.warn("Failed to assert role onto device {}. requested={}, response={}",
990 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200991 if (requested == MastershipRole.MASTER) {
pierventre4af48792021-12-02 09:42:28 +0100992 // Stop the timer
993 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100994 updateMastershipFor(deviceId);
Charles Chan48103842021-01-06 01:33:03 +0000995 } else if (requested == MastershipRole.STANDBY) {
996 // For P4RT devices, the response role will be NONE when this node is expected to be STANDBY
997 // but the stream channel is not opened correctly.
998 // Calling reassertRole will trigger the mechanism in GeneralDeviceProvider that
999 // attempts to re-establish the stream channel
1000 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -07001001 }
1002 }
tom3f2bbd72014-09-24 12:07:58 -07001003 }
sangho538108b2015-04-08 14:29:20 -07001004
1005 @Override
samuele1fa7322015-07-14 16:35:16 +08001006 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -07001007 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001008 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -07001009 checkValidity();
1010
samuele1fa7322015-07-14 16:35:16 +08001011 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
1012 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -07001013 post(event);
1014 }
pierventreb8856852021-10-01 22:01:22 +02001015
1016 @Override
1017 public DeviceDescription getDeviceDescription(DeviceId deviceId) {
1018 checkNotNull(deviceId, DEVICE_ID_NULL);
1019 checkValidity();
1020
1021 return store.getDeviceDescription(provider().id(), deviceId);
1022 }
tomd3097b02014-08-26 10:40:29 -07001023 }
tom32f66842014-08-27 19:27:47 -07001024
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001025 // by default allowed, otherwise check flag
1026 private boolean isAllowed(BasicDeviceConfig cfg) {
1027 return (cfg == null || cfg.isAllowed());
1028 }
1029
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001030 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -08001031 DeviceProvider provider = getProvider(device.id());
1032 if (provider == null) {
1033 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
1034 return false;
1035 }
1036 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001037 }
1038
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001039 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001040
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001041 /**
1042 * Apply role to device and send probe if MASTER.
1043 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001044 * @param deviceId device identifier
1045 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001046 * @return true if the request was sent to provider
1047 */
1048 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
1049 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +08001050 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001051 return true;
1052 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001053
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001054 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001055 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +08001056 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001057 return false;
1058 }
pierventre4af48792021-12-02 09:42:28 +01001059 // Start the timer
1060 roleToAcknowledge.put(deviceId, currentTimeMillis());
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001061 provider.roleChanged(deviceId, newRole);
1062
1063 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -08001064 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001065 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001066 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001067 }
1068 return true;
1069 }
1070
pierventre2bb50162022-01-03 17:19:24 +01001071 private boolean probeReachability(DeviceId deviceId) {
1072 DeviceProvider provider = getProvider(deviceId);
1073 if (provider == null) {
1074 log.warn("Provider for {} was not found. Cannot probe reachability", deviceId);
1075 return false;
1076 }
1077 return provider.isReachable(deviceId) && Tools.futureGetOrElse(provider.probeReachability(deviceId),
1078 PROBE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, Boolean.FALSE);
1079 }
1080
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001081 /**
Harold Huangff6e1e62017-11-09 16:25:36 +08001082 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001083 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001084 * @param did device identifier
1085 * @param nextRole role to apply. If NONE is specified,
1086 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001087 */
samuele1fa7322015-07-14 16:35:16 +08001088 private void reassertRole(final DeviceId did,
1089 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001090
Jordan Halterman9416aea2017-11-17 12:40:21 -08001091 MastershipRole myNextRole = nextRole;
1092 if (myNextRole == NONE && upgradeService.isLocalActive()) {
1093 try {
1094 mastershipService.requestRoleFor(did).get();
1095 MastershipTerm term = termService.getMastershipTerm(did);
1096 if (term != null && localNodeId.equals(term.master())) {
1097 myNextRole = MASTER;
1098 } else {
1099 myNextRole = STANDBY;
1100 }
1101 } catch (InterruptedException e) {
1102 Thread.currentThread().interrupt();
1103 log.error("Interrupted waiting for Mastership", e);
1104 } catch (ExecutionException e) {
1105 log.error("Encountered an error waiting for Mastership", e);
1106 }
1107 }
1108
1109 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001110 case MASTER:
1111 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001112 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +09001113 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001114 }
1115 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -08001116 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001117 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001118 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001119 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001120 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001121 // FIXME disconnect?
1122 }
1123 break;
1124 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -08001125 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001126 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001127 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001128 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001129 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001130 // FIXME disconnect?
1131 }
1132 break;
1133 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -07001134 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001135 default:
1136 // should never reach here
1137 log.error("You didn't see anything. I did not exist.");
1138 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001139 }
1140 }
1141
Madan Jampani328371d2015-05-29 14:06:27 -07001142 private void handleMastershipEvent(MastershipEvent event) {
pierventrebc91cea2022-02-18 05:16:48 -08001143 log.debug("Handling mastership event");
Madan Jampani328371d2015-05-29 14:06:27 -07001144 final DeviceId did = event.subject();
1145
pierventre2bb50162022-01-03 17:19:24 +01001146 // myNextRole suggested by MastershipService event
Madan Jampani328371d2015-05-29 14:06:27 -07001147 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -07001148 if (event.type() == MastershipEvent.Type.SUSPENDED) {
1149 myNextRole = NONE; // FIXME STANDBY OR NONE?
1150 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -07001151 // confirm latest info
1152 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +08001153 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -07001154 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -07001155 myNextRole = MASTER;
1156 } else {
1157 myNextRole = STANDBY;
1158 }
1159 } else if (event.roleInfo().backups().contains(localNodeId)) {
1160 myNextRole = STANDBY;
1161 } else {
1162 myNextRole = NONE;
1163 }
1164
pierventrebc91cea2022-02-18 05:16:48 -08001165 log.debug("Device {} local status is {}", did, localStatus(did));
1166 final boolean isGracePeriodOn = inGracePeriod(did);
1167 final boolean isReachable = isReachable(did, isGracePeriodOn);
1168 // Passed the grace period and it is still not reachable
1169 if (!isGracePeriodOn && !isReachable) {
pierventre2bb50162022-01-03 17:19:24 +01001170 // device is not connected to this node, nevertheless we should get a role
Jon Halla90c44c2017-01-24 16:02:07 -08001171 if (mastershipService.getLocalRole(did) == NONE) {
1172 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -07001173 + "but this node cannot reach the device "
pierventre2bb50162022-01-03 17:19:24 +01001174 + "and role is already None. Asking a new role "
1175 + "and then apply the disconnection protocol.",
Simon Huntffbad3b2017-05-16 15:37:51 -07001176 myNextRole, did);
pierventre2bb50162022-01-03 17:19:24 +01001177 try {
1178 mastershipService.requestRoleFor(did).get();
1179 } catch (InterruptedException e) {
1180 Thread.currentThread().interrupt();
1181 log.error("Interrupted waiting for Mastership", e);
1182 } catch (ExecutionException e) {
1183 log.error("Encountered an error waiting for Mastership", e);
1184 }
Jon Halla90c44c2017-01-24 16:02:07 -08001185 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -07001186 log.warn("Node was instructed to be {} role for {}, "
pierventre2bb50162022-01-03 17:19:24 +01001187 + "but this node cannot reach the device. "
1188 + "Apply the disconnection protocol.",
samuele1fa7322015-07-14 16:35:16 +08001189 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -07001190 }
pierventre2bb50162022-01-03 17:19:24 +01001191 // Let's put some order in the candidates list
1192 roleToAcknowledge.remove(did);
1193 updateMastershipFor(did);
pierventrebc91cea2022-02-18 05:16:48 -08001194 } else if (isReachable) {
1195 // Device is connected to this node - always reassert the role.
1196 // Ideally, protocols like OpenFlow would not need to reassert the
1197 // role because the instances are only identified by the role. However,
1198 // other protocols like P4RT require to provide also an election id
1199 // which maybe different over time, by reasserting the role will guarantee
1200 // that updated election ids are communicated to the devices. It should not
1201 // cost us a lot as it is equivalent to a probe.
1202 if (store.getDevice(did) != null) {
1203 log.info("{} is reachable - reasserting the role", did);
1204 reassertRole(did, myNextRole);
1205 } else {
1206 log.debug("Device is not yet/no longer in the store: {}", did);
1207 }
Madan Jampani328371d2015-05-29 14:06:27 -07001208 } else {
pierventrebc91cea2022-02-18 05:16:48 -08001209 // Do not proceed furthermore if the grace period is still on
1210 log.debug("Skipping mastership event {}", event);
Madan Jampani328371d2015-05-29 14:06:27 -07001211 }
1212 }
1213
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001214 // Intercepts mastership events
1215 private class InternalMastershipListener implements MastershipListener {
1216
tomb41d1ac2014-09-24 01:51:24 -07001217 @Override
1218 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001219 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001220 try {
1221 handleMastershipEvent(event);
1222 } catch (Exception e) {
1223 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001224 }
Madan Jampani328371d2015-05-29 14:06:27 -07001225 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001226 }
tomb41d1ac2014-09-24 01:51:24 -07001227 }
tomf80c9722014-09-24 14:49:18 -07001228
1229 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001230 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001231 @Override
1232 public void notify(DeviceEvent event) {
1233 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001234 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001235 // When device is administratively removed, force disconnect.
1236 DeviceId deviceId = event.subject().id();
1237 deviceLocalStatus.remove(deviceId);
pierventre14a76e72022-02-28 20:34:42 -08001238 lastAcknowledgedRole.remove(deviceId);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001239
1240 DeviceProvider provider = getProvider(deviceId);
1241 if (provider != null) {
1242 log.info("Triggering disconnect for device {}", deviceId);
1243 try {
1244 provider.triggerDisconnect(deviceId);
1245 } catch (UnsupportedOperationException e) {
1246 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1247 }
1248 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001249 }
tomf80c9722014-09-24 14:49:18 -07001250 }
1251 }
samuel738dfaf2015-07-11 11:08:57 +08001252
1253 @Override
1254 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001255 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001256 Set<Device> results = new HashSet<>();
1257 Iterable<Device> devices = store.getDevices();
1258 if (devices != null) {
1259 devices.forEach(d -> {
1260 if (type.equals(d.type())) {
1261 results.add(d);
1262 }
1263 });
1264 }
1265 return results;
1266 }
1267
1268 @Override
1269 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001270 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001271 Set<Device> results = new HashSet<>();
1272 Iterable<Device> availableDevices = store.getAvailableDevices();
1273 if (availableDevices != null) {
1274 availableDevices.forEach(d -> {
1275 if (type.equals(d.type())) {
1276 results.add(d);
1277 }
1278 });
1279 }
1280 return results;
1281 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001282
1283 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001284 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1285 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301286 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001287 if (event.subject().getClass() == ConnectPoint.class) {
1288 deviceId = ((ConnectPoint) event.subject()).deviceId();
1289 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001290 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301291 deviceId = (DeviceId) event.subject();
1292 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001293 return deviceId;
1294 }
1295
1296 @Override
1297 public boolean isRelevant(NetworkConfigEvent event) {
1298 DeviceId deviceId = extractDeviceId(event);
1299
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001300 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301301 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1302 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001303 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001304 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001305 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001306 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001307 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001308 }
1309
1310 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001311 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001312 DeviceEvent de = null;
1313 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001314 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001315 DeviceId did = (DeviceId) event.subject();
1316 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001317 BasicDeviceConfig cfg =
1318 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001319
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001320 if (!isAllowed(cfg)) {
1321 kickOutBadDevice(did);
1322 } else {
1323 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001324 DeviceDescription desc =
1325 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001326 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001327 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001328 store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001329 }
1330 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001331 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1332 DeviceId did = (DeviceId) event.subject();
1333 DeviceProvider dp = getProvider(did);
1334 if (!event.config().isPresent() ||
1335 getDevice(did) == null || dp == null) {
1336 // sanity check failed, ignore
1337 return;
1338 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001339 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001340 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001341 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1342 .collect(Collectors.toList());
1343 complete.addAll(portConfig.portDescriptions());
1344 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001345 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1346 DeviceId did = (DeviceId) event.subject();
1347 DeviceProvider dp = getProvider(did);
1348 Device dev = getDevice(did);
1349 DeviceDescription desc =
1350 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1351 Optional<Config> prevConfig = event.prevConfig();
Anurag Chadha61946392020-08-28 15:18:03 +05301352 if (desc != null) { // Fix for NPE due to desc being null
1353 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1354 }
Palash Kalaa06a6162017-11-15 20:42:40 +09001355 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001356 store.createOrUpdateDevice(dp.id(), did, desc);
Palash Kalaa06a6162017-11-15 20:42:40 +09001357 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001358 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001359 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001360 DeviceId did = cpt.deviceId();
1361 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001362
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001363 // Note: assuming PortOperator can modify existing port,
1364 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001365 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001366 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301367 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001368 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001369 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001370 }
1371
1372 if (de != null) {
1373 post(de);
1374 }
1375 }
1376
Simon Hunt8f60ff82017-04-24 17:19:30 -07001377 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001378 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001379 Device badDevice = getDevice(deviceId);
1380 if (badDevice != null) {
1381 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001382 }
1383 }
1384 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001385
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001386 @Override
1387 @SafeVarargs
1388 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001389 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001390 checkNotNull(portOp);
1391
1392 portOp.bindService(networkConfigService);
1393
1394 // update both portOpsIndex and portOps
1395 synchronized (portOpsIndex) {
1396 for (Class<? extends Config<ConnectPoint>> config : configs) {
1397 portOpsIndex.put(config, portOp);
1398 }
1399
1400 portOps.add(portOp);
1401 }
1402
1403 // TODO: Should we be applying to all existing Ports?
1404 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001405 .map(Device::id)
1406 .filter(mastershipService::isLocalMaster)
1407 // for each locally managed Device, update all port descriptions
1408 .map(did -> {
1409 ProviderId pid = Optional.ofNullable(getProvider(did))
1410 .map(Provider::id)
1411 .orElse(null);
1412 if (pid == null) {
1413 log.warn("Provider not found for {}", did);
1414 return ImmutableList.<DeviceEvent>of();
1415 }
1416 List<PortDescription> pds
1417 = store.getPortDescriptions(pid, did)
1418 .map(pdesc -> applyAllPortOps(did, pdesc))
1419 .collect(Collectors.toList());
1420 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001421 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001422 // ..and port port update event if necessary
1423 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001424 }
1425
1426 @Override
1427 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1428 checkNotNull(portOp);
1429
1430
1431 // remove all portOp
1432 synchronized (portOpsIndex) {
1433 portOps.remove(portOp);
1434
1435 // had to do this since COWArrayList iterator doesn't support remove
1436 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1437 }
1438
1439 }
1440
1441 /**
1442 * Merges the appropriate PortConfig with the description.
1443 *
1444 * @param did ID of the Device where the port is attached
1445 * @param desc {@link PortDescription}
1446 * @return merged {@link PortDescription}
1447 */
1448 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1449 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1450 }
1451
1452 /**
1453 * Merges the appropriate PortConfig with the description.
1454 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001455 * @param cpt ConnectPoint where the port is attached
1456 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001457 * @return merged {@link PortDescription}
1458 */
1459 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1460 PortDescription work = desc;
1461 for (PortConfigOperator portOp : portOps) {
1462 work = portOp.combine(cpt, work);
1463 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001464 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001465 }
1466
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001467 /**
debmaiti9553ed72019-03-18 14:27:42 +05301468 * Merges the appropriate PortConfig with the description.
1469 *
1470 * @param cpt ConnectPoint where the port is attached
1471 * @param desc {@link PortDescription}
1472 * @param prevConfig previous configuration
1473 * @return merged {@link PortDescription}
1474 */
1475 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1476 Optional<Config> prevConfig) {
1477 PortDescription work = desc;
1478 for (PortConfigOperator portOp : portOps) {
1479 work = portOp.combine(cpt, work, prevConfig);
1480 }
1481 return portAnnotationOp.combine(cpt, work, prevConfig);
1482 }
1483
1484 /**
pierventre2bb50162022-01-03 17:19:24 +01001485 * Handler for remote probe requests.
1486 *
1487 * @param deviceId the device to check
1488 * @return whether or not the device is reachable
1489 */
1490 private boolean handleProbeRequest(DeviceId deviceId) {
1491 int attempt = 0;
1492 // Let's do a number of attempts
1493 while (attempt < PROBE_ATTEMPTS) {
1494 if (!probeReachability(deviceId)) {
1495 return false;
1496 }
1497 attempt++;
1498 }
1499 return true;
1500 }
1501
1502 /**
1503 * Update the mastership for this device. If there is a node able
1504 * to reach the device and this node is the master move the
1505 * mastership to the next node still connected to this device.
1506 * If the current node is a backup, it demotes itself to the bottom
1507 * of the candidates list
1508 *
1509 * @param deviceId the device for which we have to update the mastership
1510 * @return the NodeId of any node that can reach the device, or null if
1511 * none of the ONOS instances can reach the device
1512 */
1513 private NodeId updateMastershipFor(DeviceId deviceId) {
1514 Map<NodeId, CompletableFuture<Boolean>> probes = Maps.newHashMap();
1515 // Request a probe only if the node is ready
1516 for (ControllerNode onosNode : clusterService.getNodes()) {
1517 if (!clusterService.getState(onosNode.id()).isReady() || localNodeId.equals(onosNode.id())) {
1518 continue;
1519 }
1520 probes.put(onosNode.id(), communicationService.sendAndReceive(deviceId, PROBE_SUBJECT, SERIALIZER::encode,
1521 SERIALIZER::decode, onosNode.id()));
1522 }
1523
1524 // Returns the first node able to reach the device
1525 // FIXME [SDFAB-935] optimize by looking at the MastershipInfo
1526 boolean isReachable;
1527 NodeId nextMaster = null;
1528 // FIXME Should we expose timeout? Understand if there is need to signal to the caller
1529 for (Map.Entry<NodeId, CompletableFuture<Boolean>> probe : probes.entrySet()) {
1530 isReachable = Tools.futureGetOrElse(probe.getValue(), PROBE_TIMEOUT_MILLIS,
1531 TimeUnit.MILLISECONDS, Boolean.FALSE);
1532 if (isReachable) {
1533 nextMaster = probe.getKey();
1534 }
1535 }
1536
1537 // FIXME [SDFAB-935] optimize demote by looking at the MastershipInfo;
1538 if (nextMaster != null) {
1539 log.info("Device {} is still connected to {}", deviceId, nextMaster);
1540 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1541 if (myRole == MASTER) {
1542 log.info("Handing over the mastership of {} to next master {}", deviceId, nextMaster);
1543 mastershipAdminService.setRole(nextMaster, deviceId, MASTER);
pierventrebc91cea2022-02-18 05:16:48 -08001544 // Do not demote here because setRole can return before the mastership has been passed.
1545 // Current implementation promotes first the nextMaster as top of candidate list and then
1546 // transfer the leadership. We can use the BACKUP events to do demote or leverage periodic
1547 // checks.
pierventre2bb50162022-01-03 17:19:24 +01001548 } else if (myRole == STANDBY) {
1549 log.info("Demote current instance to the bottom of the candidates list for {}", deviceId);
1550 mastershipAdminService.demote(localNodeId, deviceId);
1551 } else {
1552 log.debug("No valid role for {}", deviceId);
1553 }
1554 }
1555
1556 return nextMaster;
1557 }
1558
pierventre2bb50162022-01-03 17:19:24 +01001559 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001560 * Port Enable/Disable message sent to the device's MASTER node.
1561 */
1562 private class InternalPortUpDownEvent {
1563 private final DeviceId deviceId;
1564 private final PortNumber portNumber;
1565 private final boolean enable;
1566
1567 protected InternalPortUpDownEvent(
1568 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1569 this.deviceId = deviceId;
1570 this.portNumber = portNumber;
1571 this.enable = enable;
1572 }
1573
1574 public DeviceId deviceId() {
1575 return deviceId;
1576 }
1577 public PortNumber portNumber() {
1578 return portNumber;
1579 }
1580 public boolean isEnable() {
1581 return enable;
1582 }
1583
1584 protected InternalPortUpDownEvent() {
1585 this.deviceId = null;
1586 this.portNumber = null;
1587 this.enable = false;
1588 }
1589 }
tomd3097b02014-08-26 10:40:29 -07001590}