blob: be114c4138353c0234326edd20462d1c21bc787d [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);
545 post(store.markOffline(deviceId));
helenyrwufd296b62016-06-22 17:43:02 -0700546 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530547 } else {
pierventrebc91cea2022-02-18 05:16:48 -0800548 // Firstly get a role and then check if the device is available in the store.
549 // if it is, if this node is the master and the device is fully disconnected
550 // from the cluster mark the device offline. In principle, this condition should
551 // never be hit unless in a device removed phase for NONE mastership roles.
pierventre2bb50162022-01-03 17:19:24 +0100552 try {
553 mastershipService.requestRoleFor(deviceId).get();
554 } catch (InterruptedException e) {
555 Thread.currentThread().interrupt();
556 log.error("Interrupted waiting for Mastership", e);
557 } catch (ExecutionException e) {
558 log.error("Encountered an error waiting for Mastership", e);
559 }
560
561 MastershipTerm term = termService.getMastershipTerm(deviceId);
562 if (updateMastershipFor(deviceId) == null &&
563 term != null && localNodeId.equals(term.master()) &&
564 isAvailable(deviceId)) {
565 log.info("Marking unreachable device {} offline", deviceId);
566 post(store.markOffline(deviceId));
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800567 }
helenyrwufd296b62016-06-22 17:43:02 -0700568 }
pierventre2bb50162022-01-03 17:19:24 +0100569 roleToAcknowledge.remove(deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800570 } else if (isReachable) {
571 // If this node is the master, ensure the device is marked online.
572 if (myRole == MASTER && canMarkOnline(device)) {
pierventre14a76e72022-02-28 20:34:42 -0800573 log.debug("Can mark online {}", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800574 post(store.markOnline(deviceId));
575 }
576
pierventre14a76e72022-02-28 20:34:42 -0800577 log.debug("{} is reachable - reasserting the role", deviceId);
pierventrebc91cea2022-02-18 05:16:48 -0800578
579 // Device is still reachable. It is useful for some protocols
580 // to reassert the role. Note: NONE triggers request to MastershipService
581 reassertRole(deviceId, myRole);
582 } else {
583 // Do not proceed furthermore if the grace period is still on
584 log.debug("Skipping mastership check for {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800585 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800586 }
587 }
588
pierventre4af48792021-12-02 09:42:28 +0100589 /**
590 * Checks if all the devices have acknowledged the mastership role.
591 */
592 private void roleCheck() {
593 log.debug("Checking role");
594 for (Device device : getDevices()) {
595 final DeviceId deviceId = device.id();
596 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
597 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
598 final AtomicBoolean exists = new AtomicBoolean(false);
599 final Long ts = roleToAcknowledge.compute(deviceId, (key, value) -> {
600 if (value == null) {
601 return null;
602 }
603 exists.set(true);
604 if (currentTimeMillis() - value < (ROLE_TIMEOUT_SECONDS * 1000)) {
605 return value;
606 }
607 return null;
608 });
609 // Nobody applied the role recently
610 if (!exists.get()) {
611 log.trace("Role was not applied or it has been acknowledged for device {}", deviceId);
612 continue;
613 }
614 // Timeout still on
615 if (ts != null) {
616 log.debug("Timeout expires in {} ms", ((ROLE_TIMEOUT_SECONDS * 1000) - currentTimeMillis() + ts));
617 continue;
618 }
619 if (myRole != MASTER) {
620 log.debug("Timeout is expired but current role is not MASTER ({}), nothing to do", myRole);
621 continue;
622 }
pierventrebc91cea2022-02-18 05:16:48 -0800623 // Switch failed to acknowledge master role we asked for.
624 // Yield mastership to other instance
pierventre4af48792021-12-02 09:42:28 +0100625 log.warn("Failed to assert role onto device {}. requested={}, no response",
626 deviceId, myRole);
pierventre2bb50162022-01-03 17:19:24 +0100627 updateMastershipFor(deviceId);
pierventre4af48792021-12-02 09:42:28 +0100628 }
629 }
630
tomd3097b02014-08-26 10:40:29 -0700631 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700632 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700633 extends AbstractProviderService<DeviceProvider>
634 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700635
tomcfde0622014-09-09 11:02:42 -0700636 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700637 super(provider);
638 }
639
Ray Milkey33306ba2018-09-20 13:27:25 -0700640 /**
641 * Apply role in reaction to provider event.
642 *
643 * @param deviceId device identifier
644 * @param newRole new role to apply to the device
645 * @return true if the request was sent to provider
646 */
647 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
648
649 if (newRole.equals(MastershipRole.NONE)) {
650 //no-op
651 return true;
652 }
653
654 DeviceProvider provider = provider();
655 if (provider == null) {
656 log.warn("Provider for {} was not found. Cannot apply role {}",
657 deviceId, newRole);
658 return false;
659 }
pierventre4af48792021-12-02 09:42:28 +0100660 // Start the timer
661 roleToAcknowledge.put(deviceId, currentTimeMillis());
Ray Milkey33306ba2018-09-20 13:27:25 -0700662 provider.roleChanged(deviceId, newRole);
663 // not triggering probe when triggered by provider service event
664 return true;
665 }
666
tomd3097b02014-08-26 10:40:29 -0700667 @Override
alshabibb7b40632014-09-28 21:30:00 -0700668 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700669 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700670 checkNotNull(deviceId, DEVICE_ID_NULL);
671 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700672 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700673
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700674 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800675
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700676 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
677 if (!isAllowed(cfg)) {
678 log.warn("Device {} is not allowed", deviceId);
679 return;
680 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200681 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700682 // Generate updated description and establish my Role
683 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900684 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
685 if (annoConfig != null) {
686 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
687 }
688
pier388ec252020-04-15 20:53:14 +0200689 // Wait for the end of the election. sync call of requestRoleFor
690 // wait only 3s and it is not entirely safe since the leadership
691 // election timer can be higher.
692 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
jaegonkim8eabcec2018-07-27 23:40:43 +0900693 log.info("Local role is {} for {}", role, deviceId);
pier388ec252020-04-15 20:53:14 +0200694 store.createOrUpdateDevice(provider().id(), deviceId, deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700695 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700696
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200697 if (portConfig != null) {
698 //updating the ports if configration exists
699 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
700 .collect(Collectors.toList());
701 complete.addAll(portConfig.portDescriptions());
702 List<PortDescription> portDescriptions = complete.stream()
703 .map(e -> applyAllPortOps(deviceId, e))
704 .collect(Collectors.toList());
705 store.updatePorts(provider().id(), deviceId, portDescriptions);
706 }
707
helenyrwufd296b62016-06-22 17:43:02 -0700708 if (deviceDescription.isDefaultAvailable()) {
709 log.info("Device {} connected", deviceId);
710 } else {
711 log.info("Device {} registered", deviceId);
712 }
tomd3097b02014-08-26 10:40:29 -0700713 }
714
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700715 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
716 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800717 return DefaultPortDescription.builder(desc)
718 .isEnabled(enabled)
719 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700720 }
721 return desc;
722 }
723
tomd3097b02014-08-26 10:40:29 -0700724 @Override
725 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700726 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700727 checkValidity();
pierventre2bb50162022-01-03 17:19:24 +0100728 // Update the local status
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700729 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Andrea Campanella18fdda82021-09-13 12:37:36 +0200730 log.info("Device {} disconnected from this node: {}", deviceId,
731 clusterService.getLocalNode().id());
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700732
pierventrebc91cea2022-02-18 05:16:48 -0800733 // If none can reach the device, we will continue with the disconnection logic.
734 // If there is one instance that reported device is still reachable, we hand over
735 // the mastership to it if we are the current master, otherwise if we are a backup
736 // we demote ourselves to the bottom of the backups list
pierventre2bb50162022-01-03 17:19:24 +0100737 if (updateMastershipFor(deviceId) == null) {
738 log.info("Device {} is fully disconnected from the cluster", deviceId);
739 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
740 .map(desc -> ensurePortEnabledState(desc, false))
741 .collect(Collectors.toList());
742 store.updatePorts(this.provider().id(), deviceId, descs);
Yafit Hadara9a73de2015-09-06 13:52:52 +0300743
Madan Jampanic6e574f2015-05-29 13:41:52 -0700744 try {
pierventre2bb50162022-01-03 17:19:24 +0100745 if (mastershipService.isLocalMaster(deviceId)) {
746 post(store.markOffline(deviceId));
747 }
748 } catch (IllegalStateException e) {
749 log.warn("Failed to mark {} offline", deviceId);
750 // only the MASTER should be marking off-line in normal cases,
751 // but if I was the last STANDBY connection, etc. and no one else
752 // was there to mark the device offline, this instance may need to
753 // temporarily request for Master Role and mark offline.
754
755 //there are times when this node will correctly have mastership, BUT
756 //that isn't reflected in the ClockManager before the device disconnects.
757 //we want to let go of the device anyways, so make sure this happens.
758
759 // FIXME: Store semantics leaking out as IllegalStateException.
760 // Consider revising store API to handle this scenario.
761 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
762 roleFuture.whenComplete((role, error) -> {
763 MastershipTerm term = termService.getMastershipTerm(deviceId);
764 // TODO: Move this type of check inside device clock manager, etc.
765 if (term != null && localNodeId.equals(term.master())) {
766 log.info("Retry marking {} offline", deviceId);
767 post(store.markOffline(deviceId));
768 } else {
769 log.info("Failed again marking {} offline. {}", deviceId, role);
770 }
771 });
772 } finally {
pierventre4af48792021-12-02 09:42:28 +0100773 roleToAcknowledge.remove(deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700774 }
tom0efbb1d2014-09-09 11:54:28 -0700775 }
pierventre2bb50162022-01-03 17:19:24 +0100776
tomd3097b02014-08-26 10:40:29 -0700777 }
778
779 @Override
alshabibb7b40632014-09-28 21:30:00 -0700780 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700781 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700782 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700783 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700784 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700785 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700786 // Never been a master for this device
787 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800788 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700789 return;
790 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200791 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
792 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200793 // Updating the ports if configuration exists (on new lists as
794 // the passed one might be immutable)
795 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200796 portDescriptions.addAll(portConfig.portDescriptions());
797 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700798 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700799 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700800 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700801 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800802 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800803 if (events != null) {
804 for (DeviceEvent event : events) {
805 post(event);
806 }
tom32f66842014-08-27 19:27:47 -0700807 }
tomd3097b02014-08-26 10:40:29 -0700808 }
809
810 @Override
alshabibb7b40632014-09-28 21:30:00 -0700811 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700812 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700813 checkNotNull(deviceId, DEVICE_ID_NULL);
814 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700815 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700816
Madan Jampani565a66a2015-07-25 17:01:13 -0700817 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700818 // Never been a master for this device
819 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700820 log.trace("Ignoring {} port update on standby node. {}", deviceId,
821 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700822 return;
823 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700824 Device device = getDevice(deviceId);
825 if (device == null) {
826 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530827 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700828 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100829 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
830 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700831 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700832 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700833 deviceId,
834 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700835 portDescription = ensurePortEnabledState(storedPortDesc,
836 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300837 }
838
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700839 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800840 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700841 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700842 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700843 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800844 log.info("Device {} port {} status changed (enabled={})",
845 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700846 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700847 }
tomd3097b02014-08-26 10:40:29 -0700848 }
tom3f2bbd72014-09-24 12:07:58 -0700849
850 @Override
Michal Machce774332017-01-25 11:02:55 +0100851 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
852
853 checkNotNull(deviceId, DEVICE_ID_NULL);
854 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
855 checkValidity();
856
857 if (!mastershipService.isLocalMaster(deviceId)) {
858 // Never been a master for this device
859 // any update will be ignored.
860 log.trace("Ignoring {} port update on standby node. {}", deviceId,
861 basePortDescription);
862 return;
863 }
864
865 Device device = getDevice(deviceId);
866 if (device == null) {
867 log.trace("Device not found: {}", deviceId);
868 }
869
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800870 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
871 .isRemoved(true)
872 .build();
873
Michal Machce774332017-01-25 11:02:55 +0100874 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
875 deviceId,
876 newPortDescription);
877 if (event != null) {
878 log.info("Device {} port {} status changed", deviceId, event.port().number());
879 post(event);
880 }
881 }
882
883 @Override
samuele1fa7322015-07-14 16:35:16 +0800884 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700885 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700886 // Several things can happen here:
887 // 1. request and response match
888 // 2. request and response don't match
889 // 3. MastershipRole and requested match (and 1 or 2 are true)
890 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
891 //
892 // 2, 4, and 3 with case 2 are failure modes.
893
tom3f2bbd72014-09-24 12:07:58 -0700894 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700895
Madan Jampanif2af7712015-05-29 18:43:52 -0700896 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700897 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700898
899 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800900 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530901 log.warn("Failed to assert role onto Device {}", deviceId);
pierventre4af48792021-12-02 09:42:28 +0100902 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100903 updateMastershipFor(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700904 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700905 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700906
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800907 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
908
909 if (requested == null) {
910 // Provider is not able to reconcile role responses with
911 // requests. We assume what was requested is what we expect.
912 // This will work only if mastership doesn't change too often,
913 // and devices are left enough time to provide responses before
914 // a different role is requested.
915 requested = expected;
916 }
917
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700918 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800919 if (Objects.equals(requested, expected)) {
pierventre14a76e72022-02-28 20:34:42 -0800920 if (log.isDebugEnabled()) {
921 log.debug("Role has been acknowledged for device {}", deviceId);
922 } else if (!requested.equals(lastAcknowledgedRole.get(deviceId))) {
923 log.info("Role has been acknowledged for device {}", deviceId);
924 }
925 // Update the last known role and stop the timer
926 lastAcknowledgedRole.put(deviceId, requested);
pierventre4af48792021-12-02 09:42:28 +0100927 roleToAcknowledge.remove(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700928 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800929 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
930 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800931 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700932 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800933 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700934 }
935 } else {
936 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200937 log.warn("Failed to assert role onto device {}. requested={}, response={}",
938 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200939 if (requested == MastershipRole.MASTER) {
pierventre4af48792021-12-02 09:42:28 +0100940 // Stop the timer
941 roleToAcknowledge.remove(deviceId);
pierventre2bb50162022-01-03 17:19:24 +0100942 updateMastershipFor(deviceId);
Charles Chan48103842021-01-06 01:33:03 +0000943 } else if (requested == MastershipRole.STANDBY) {
944 // For P4RT devices, the response role will be NONE when this node is expected to be STANDBY
945 // but the stream channel is not opened correctly.
946 // Calling reassertRole will trigger the mechanism in GeneralDeviceProvider that
947 // attempts to re-establish the stream channel
948 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700949 }
950 }
tom3f2bbd72014-09-24 12:07:58 -0700951 }
sangho538108b2015-04-08 14:29:20 -0700952
953 @Override
samuele1fa7322015-07-14 16:35:16 +0800954 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700955 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700956 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700957 checkValidity();
958
samuele1fa7322015-07-14 16:35:16 +0800959 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
960 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700961 post(event);
962 }
pierventreb8856852021-10-01 22:01:22 +0200963
964 @Override
965 public DeviceDescription getDeviceDescription(DeviceId deviceId) {
966 checkNotNull(deviceId, DEVICE_ID_NULL);
967 checkValidity();
968
969 return store.getDeviceDescription(provider().id(), deviceId);
970 }
tomd3097b02014-08-26 10:40:29 -0700971 }
tom32f66842014-08-27 19:27:47 -0700972
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700973 // by default allowed, otherwise check flag
974 private boolean isAllowed(BasicDeviceConfig cfg) {
975 return (cfg == null || cfg.isAllowed());
976 }
977
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700978 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800979 DeviceProvider provider = getProvider(device.id());
980 if (provider == null) {
981 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
982 return false;
983 }
984 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700985 }
986
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800987 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700988
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800989 /**
990 * Apply role to device and send probe if MASTER.
991 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700992 * @param deviceId device identifier
993 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800994 * @return true if the request was sent to provider
995 */
996 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
997 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800998 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700999 return true;
1000 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001001
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001002 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001003 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +08001004 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001005 return false;
1006 }
pierventre4af48792021-12-02 09:42:28 +01001007 // Start the timer
1008 roleToAcknowledge.put(deviceId, currentTimeMillis());
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001009 provider.roleChanged(deviceId, newRole);
1010
1011 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -08001012 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001013 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001014 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001015 }
1016 return true;
1017 }
1018
pierventre2bb50162022-01-03 17:19:24 +01001019 private boolean probeReachability(DeviceId deviceId) {
1020 DeviceProvider provider = getProvider(deviceId);
1021 if (provider == null) {
1022 log.warn("Provider for {} was not found. Cannot probe reachability", deviceId);
1023 return false;
1024 }
1025 return provider.isReachable(deviceId) && Tools.futureGetOrElse(provider.probeReachability(deviceId),
1026 PROBE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, Boolean.FALSE);
1027 }
1028
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001029 /**
Harold Huangff6e1e62017-11-09 16:25:36 +08001030 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001031 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001032 * @param did device identifier
1033 * @param nextRole role to apply. If NONE is specified,
1034 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001035 */
samuele1fa7322015-07-14 16:35:16 +08001036 private void reassertRole(final DeviceId did,
1037 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001038
Jordan Halterman9416aea2017-11-17 12:40:21 -08001039 MastershipRole myNextRole = nextRole;
1040 if (myNextRole == NONE && upgradeService.isLocalActive()) {
1041 try {
1042 mastershipService.requestRoleFor(did).get();
1043 MastershipTerm term = termService.getMastershipTerm(did);
1044 if (term != null && localNodeId.equals(term.master())) {
1045 myNextRole = MASTER;
1046 } else {
1047 myNextRole = STANDBY;
1048 }
1049 } catch (InterruptedException e) {
1050 Thread.currentThread().interrupt();
1051 log.error("Interrupted waiting for Mastership", e);
1052 } catch (ExecutionException e) {
1053 log.error("Encountered an error waiting for Mastership", e);
1054 }
1055 }
1056
1057 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001058 case MASTER:
1059 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001060 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +09001061 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001062 }
1063 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -08001064 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001065 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001066 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001067 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001068 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001069 // FIXME disconnect?
1070 }
1071 break;
1072 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -08001073 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001074 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001075 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001076 // immediately failed to apply role
pierventre2bb50162022-01-03 17:19:24 +01001077 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001078 // FIXME disconnect?
1079 }
1080 break;
1081 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -07001082 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001083 default:
1084 // should never reach here
1085 log.error("You didn't see anything. I did not exist.");
1086 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001087 }
1088 }
1089
Madan Jampani328371d2015-05-29 14:06:27 -07001090 private void handleMastershipEvent(MastershipEvent event) {
pierventrebc91cea2022-02-18 05:16:48 -08001091 log.debug("Handling mastership event");
Madan Jampani328371d2015-05-29 14:06:27 -07001092 final DeviceId did = event.subject();
1093
pierventre2bb50162022-01-03 17:19:24 +01001094 // myNextRole suggested by MastershipService event
Madan Jampani328371d2015-05-29 14:06:27 -07001095 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -07001096 if (event.type() == MastershipEvent.Type.SUSPENDED) {
1097 myNextRole = NONE; // FIXME STANDBY OR NONE?
1098 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -07001099 // confirm latest info
1100 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +08001101 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -07001102 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -07001103 myNextRole = MASTER;
1104 } else {
1105 myNextRole = STANDBY;
1106 }
1107 } else if (event.roleInfo().backups().contains(localNodeId)) {
1108 myNextRole = STANDBY;
1109 } else {
1110 myNextRole = NONE;
1111 }
1112
pierventrebc91cea2022-02-18 05:16:48 -08001113 log.debug("Device {} local status is {}", did, localStatus(did));
1114 final boolean isGracePeriodOn = inGracePeriod(did);
1115 final boolean isReachable = isReachable(did, isGracePeriodOn);
1116 // Passed the grace period and it is still not reachable
1117 if (!isGracePeriodOn && !isReachable) {
pierventre2bb50162022-01-03 17:19:24 +01001118 // device is not connected to this node, nevertheless we should get a role
Jon Halla90c44c2017-01-24 16:02:07 -08001119 if (mastershipService.getLocalRole(did) == NONE) {
1120 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -07001121 + "but this node cannot reach the device "
pierventre2bb50162022-01-03 17:19:24 +01001122 + "and role is already None. Asking a new role "
1123 + "and then apply the disconnection protocol.",
Simon Huntffbad3b2017-05-16 15:37:51 -07001124 myNextRole, did);
pierventre2bb50162022-01-03 17:19:24 +01001125 try {
1126 mastershipService.requestRoleFor(did).get();
1127 } catch (InterruptedException e) {
1128 Thread.currentThread().interrupt();
1129 log.error("Interrupted waiting for Mastership", e);
1130 } catch (ExecutionException e) {
1131 log.error("Encountered an error waiting for Mastership", e);
1132 }
Jon Halla90c44c2017-01-24 16:02:07 -08001133 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -07001134 log.warn("Node was instructed to be {} role for {}, "
pierventre2bb50162022-01-03 17:19:24 +01001135 + "but this node cannot reach the device. "
1136 + "Apply the disconnection protocol.",
samuele1fa7322015-07-14 16:35:16 +08001137 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -07001138 }
pierventre2bb50162022-01-03 17:19:24 +01001139 // Let's put some order in the candidates list
1140 roleToAcknowledge.remove(did);
1141 updateMastershipFor(did);
pierventrebc91cea2022-02-18 05:16:48 -08001142 } else if (isReachable) {
1143 // Device is connected to this node - always reassert the role.
1144 // Ideally, protocols like OpenFlow would not need to reassert the
1145 // role because the instances are only identified by the role. However,
1146 // other protocols like P4RT require to provide also an election id
1147 // which maybe different over time, by reasserting the role will guarantee
1148 // that updated election ids are communicated to the devices. It should not
1149 // cost us a lot as it is equivalent to a probe.
1150 if (store.getDevice(did) != null) {
1151 log.info("{} is reachable - reasserting the role", did);
1152 reassertRole(did, myNextRole);
1153 } else {
1154 log.debug("Device is not yet/no longer in the store: {}", did);
1155 }
Madan Jampani328371d2015-05-29 14:06:27 -07001156 } else {
pierventrebc91cea2022-02-18 05:16:48 -08001157 // Do not proceed furthermore if the grace period is still on
1158 log.debug("Skipping mastership event {}", event);
Madan Jampani328371d2015-05-29 14:06:27 -07001159 }
1160 }
1161
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001162 // Intercepts mastership events
1163 private class InternalMastershipListener implements MastershipListener {
1164
tomb41d1ac2014-09-24 01:51:24 -07001165 @Override
1166 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001167 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001168 try {
1169 handleMastershipEvent(event);
1170 } catch (Exception e) {
1171 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001172 }
Madan Jampani328371d2015-05-29 14:06:27 -07001173 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001174 }
tomb41d1ac2014-09-24 01:51:24 -07001175 }
tomf80c9722014-09-24 14:49:18 -07001176
1177 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001178 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001179 @Override
1180 public void notify(DeviceEvent event) {
1181 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001182 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001183 // When device is administratively removed, force disconnect.
1184 DeviceId deviceId = event.subject().id();
1185 deviceLocalStatus.remove(deviceId);
pierventre14a76e72022-02-28 20:34:42 -08001186 lastAcknowledgedRole.remove(deviceId);
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001187
1188 DeviceProvider provider = getProvider(deviceId);
1189 if (provider != null) {
1190 log.info("Triggering disconnect for device {}", deviceId);
1191 try {
1192 provider.triggerDisconnect(deviceId);
1193 } catch (UnsupportedOperationException e) {
1194 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1195 }
1196 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001197 }
tomf80c9722014-09-24 14:49:18 -07001198 }
1199 }
samuel738dfaf2015-07-11 11:08:57 +08001200
1201 @Override
1202 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001203 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001204 Set<Device> results = new HashSet<>();
1205 Iterable<Device> devices = store.getDevices();
1206 if (devices != null) {
1207 devices.forEach(d -> {
1208 if (type.equals(d.type())) {
1209 results.add(d);
1210 }
1211 });
1212 }
1213 return results;
1214 }
1215
1216 @Override
1217 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001218 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001219 Set<Device> results = new HashSet<>();
1220 Iterable<Device> availableDevices = store.getAvailableDevices();
1221 if (availableDevices != null) {
1222 availableDevices.forEach(d -> {
1223 if (type.equals(d.type())) {
1224 results.add(d);
1225 }
1226 });
1227 }
1228 return results;
1229 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001230
1231 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001232 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1233 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301234 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001235 if (event.subject().getClass() == ConnectPoint.class) {
1236 deviceId = ((ConnectPoint) event.subject()).deviceId();
1237 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001238 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301239 deviceId = (DeviceId) event.subject();
1240 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001241 return deviceId;
1242 }
1243
1244 @Override
1245 public boolean isRelevant(NetworkConfigEvent event) {
1246 DeviceId deviceId = extractDeviceId(event);
1247
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001248 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301249 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1250 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001251 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001252 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001253 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001254 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001255 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001256 }
1257
1258 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001259 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001260 DeviceEvent de = null;
1261 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001262 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001263 DeviceId did = (DeviceId) event.subject();
1264 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001265 BasicDeviceConfig cfg =
1266 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001267
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001268 if (!isAllowed(cfg)) {
1269 kickOutBadDevice(did);
1270 } else {
1271 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001272 DeviceDescription desc =
1273 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001274 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001275 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001276 store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001277 }
1278 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001279 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1280 DeviceId did = (DeviceId) event.subject();
1281 DeviceProvider dp = getProvider(did);
1282 if (!event.config().isPresent() ||
1283 getDevice(did) == null || dp == null) {
1284 // sanity check failed, ignore
1285 return;
1286 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001287 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001288 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001289 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1290 .collect(Collectors.toList());
1291 complete.addAll(portConfig.portDescriptions());
1292 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001293 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1294 DeviceId did = (DeviceId) event.subject();
1295 DeviceProvider dp = getProvider(did);
1296 Device dev = getDevice(did);
1297 DeviceDescription desc =
1298 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1299 Optional<Config> prevConfig = event.prevConfig();
Anurag Chadha61946392020-08-28 15:18:03 +05301300 if (desc != null) { // Fix for NPE due to desc being null
1301 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1302 }
Palash Kalaa06a6162017-11-15 20:42:40 +09001303 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001304 store.createOrUpdateDevice(dp.id(), did, desc);
Palash Kalaa06a6162017-11-15 20:42:40 +09001305 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001306 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001307 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001308 DeviceId did = cpt.deviceId();
1309 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001310
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001311 // Note: assuming PortOperator can modify existing port,
1312 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001313 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001314 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301315 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001316 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001317 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001318 }
1319
1320 if (de != null) {
1321 post(de);
1322 }
1323 }
1324
Simon Hunt8f60ff82017-04-24 17:19:30 -07001325 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001326 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001327 Device badDevice = getDevice(deviceId);
1328 if (badDevice != null) {
1329 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001330 }
1331 }
1332 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001333
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001334 @Override
1335 @SafeVarargs
1336 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001337 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001338 checkNotNull(portOp);
1339
1340 portOp.bindService(networkConfigService);
1341
1342 // update both portOpsIndex and portOps
1343 synchronized (portOpsIndex) {
1344 for (Class<? extends Config<ConnectPoint>> config : configs) {
1345 portOpsIndex.put(config, portOp);
1346 }
1347
1348 portOps.add(portOp);
1349 }
1350
1351 // TODO: Should we be applying to all existing Ports?
1352 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001353 .map(Device::id)
1354 .filter(mastershipService::isLocalMaster)
1355 // for each locally managed Device, update all port descriptions
1356 .map(did -> {
1357 ProviderId pid = Optional.ofNullable(getProvider(did))
1358 .map(Provider::id)
1359 .orElse(null);
1360 if (pid == null) {
1361 log.warn("Provider not found for {}", did);
1362 return ImmutableList.<DeviceEvent>of();
1363 }
1364 List<PortDescription> pds
1365 = store.getPortDescriptions(pid, did)
1366 .map(pdesc -> applyAllPortOps(did, pdesc))
1367 .collect(Collectors.toList());
1368 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001369 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001370 // ..and port port update event if necessary
1371 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001372 }
1373
1374 @Override
1375 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1376 checkNotNull(portOp);
1377
1378
1379 // remove all portOp
1380 synchronized (portOpsIndex) {
1381 portOps.remove(portOp);
1382
1383 // had to do this since COWArrayList iterator doesn't support remove
1384 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1385 }
1386
1387 }
1388
1389 /**
1390 * Merges the appropriate PortConfig with the description.
1391 *
1392 * @param did ID of the Device where the port is attached
1393 * @param desc {@link PortDescription}
1394 * @return merged {@link PortDescription}
1395 */
1396 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1397 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1398 }
1399
1400 /**
1401 * Merges the appropriate PortConfig with the description.
1402 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001403 * @param cpt ConnectPoint where the port is attached
1404 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001405 * @return merged {@link PortDescription}
1406 */
1407 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1408 PortDescription work = desc;
1409 for (PortConfigOperator portOp : portOps) {
1410 work = portOp.combine(cpt, work);
1411 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001412 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001413 }
1414
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001415 /**
debmaiti9553ed72019-03-18 14:27:42 +05301416 * Merges the appropriate PortConfig with the description.
1417 *
1418 * @param cpt ConnectPoint where the port is attached
1419 * @param desc {@link PortDescription}
1420 * @param prevConfig previous configuration
1421 * @return merged {@link PortDescription}
1422 */
1423 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1424 Optional<Config> prevConfig) {
1425 PortDescription work = desc;
1426 for (PortConfigOperator portOp : portOps) {
1427 work = portOp.combine(cpt, work, prevConfig);
1428 }
1429 return portAnnotationOp.combine(cpt, work, prevConfig);
1430 }
1431
1432 /**
pierventre2bb50162022-01-03 17:19:24 +01001433 * Handler for remote probe requests.
1434 *
1435 * @param deviceId the device to check
1436 * @return whether or not the device is reachable
1437 */
1438 private boolean handleProbeRequest(DeviceId deviceId) {
1439 int attempt = 0;
1440 // Let's do a number of attempts
1441 while (attempt < PROBE_ATTEMPTS) {
1442 if (!probeReachability(deviceId)) {
1443 return false;
1444 }
1445 attempt++;
1446 }
1447 return true;
1448 }
1449
1450 /**
1451 * Update the mastership for this device. If there is a node able
1452 * to reach the device and this node is the master move the
1453 * mastership to the next node still connected to this device.
1454 * If the current node is a backup, it demotes itself to the bottom
1455 * of the candidates list
1456 *
1457 * @param deviceId the device for which we have to update the mastership
1458 * @return the NodeId of any node that can reach the device, or null if
1459 * none of the ONOS instances can reach the device
1460 */
1461 private NodeId updateMastershipFor(DeviceId deviceId) {
1462 Map<NodeId, CompletableFuture<Boolean>> probes = Maps.newHashMap();
1463 // Request a probe only if the node is ready
1464 for (ControllerNode onosNode : clusterService.getNodes()) {
1465 if (!clusterService.getState(onosNode.id()).isReady() || localNodeId.equals(onosNode.id())) {
1466 continue;
1467 }
1468 probes.put(onosNode.id(), communicationService.sendAndReceive(deviceId, PROBE_SUBJECT, SERIALIZER::encode,
1469 SERIALIZER::decode, onosNode.id()));
1470 }
1471
1472 // Returns the first node able to reach the device
1473 // FIXME [SDFAB-935] optimize by looking at the MastershipInfo
1474 boolean isReachable;
1475 NodeId nextMaster = null;
1476 // FIXME Should we expose timeout? Understand if there is need to signal to the caller
1477 for (Map.Entry<NodeId, CompletableFuture<Boolean>> probe : probes.entrySet()) {
1478 isReachable = Tools.futureGetOrElse(probe.getValue(), PROBE_TIMEOUT_MILLIS,
1479 TimeUnit.MILLISECONDS, Boolean.FALSE);
1480 if (isReachable) {
1481 nextMaster = probe.getKey();
1482 }
1483 }
1484
1485 // FIXME [SDFAB-935] optimize demote by looking at the MastershipInfo;
1486 if (nextMaster != null) {
1487 log.info("Device {} is still connected to {}", deviceId, nextMaster);
1488 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1489 if (myRole == MASTER) {
1490 log.info("Handing over the mastership of {} to next master {}", deviceId, nextMaster);
1491 mastershipAdminService.setRole(nextMaster, deviceId, MASTER);
pierventrebc91cea2022-02-18 05:16:48 -08001492 // Do not demote here because setRole can return before the mastership has been passed.
1493 // Current implementation promotes first the nextMaster as top of candidate list and then
1494 // transfer the leadership. We can use the BACKUP events to do demote or leverage periodic
1495 // checks.
pierventre2bb50162022-01-03 17:19:24 +01001496 } else if (myRole == STANDBY) {
1497 log.info("Demote current instance to the bottom of the candidates list for {}", deviceId);
1498 mastershipAdminService.demote(localNodeId, deviceId);
1499 } else {
1500 log.debug("No valid role for {}", deviceId);
1501 }
1502 }
1503
1504 return nextMaster;
1505 }
1506
pierventre2bb50162022-01-03 17:19:24 +01001507 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001508 * Port Enable/Disable message sent to the device's MASTER node.
1509 */
1510 private class InternalPortUpDownEvent {
1511 private final DeviceId deviceId;
1512 private final PortNumber portNumber;
1513 private final boolean enable;
1514
1515 protected InternalPortUpDownEvent(
1516 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1517 this.deviceId = deviceId;
1518 this.portNumber = portNumber;
1519 this.enable = enable;
1520 }
1521
1522 public DeviceId deviceId() {
1523 return deviceId;
1524 }
1525 public PortNumber portNumber() {
1526 return portNumber;
1527 }
1528 public boolean isEnable() {
1529 return enable;
1530 }
1531
1532 protected InternalPortUpDownEvent() {
1533 this.deviceId = null;
1534 this.portNumber = null;
1535 this.enable = false;
1536 }
1537 }
tomd3097b02014-08-26 10:40:29 -07001538}