blob: e78e6d2c2f7e0f7f68eda3c405b13dd3653f647a [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;
pierventreb2f636b2022-01-03 17:19:24 +010026import org.onosproject.cluster.ControllerNode;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.cluster.NodeId;
pierventreb2f636b2022-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;
pierventre00ac2502021-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;
pierventre00ac2502021-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)
pierventreb2f636b2022-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
pierventreb2f636b2022-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
pierventreb2f636b2022-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
pierventre00ac2502021-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
tomd3097b02014-08-26 10:40:29 -0700219 @Activate
220 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800221 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900222 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800223 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
224
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800225 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700226 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700227 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800228
tomf80c9722014-09-24 14:49:18 -0700229 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700230 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700231 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700232 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800233
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700234 backgroundService.scheduleWithFixedDelay(() -> {
235 try {
236 mastershipCheck();
237 } catch (Exception e) {
pierventre00ac2502021-12-02 09:42:28 +0100238 log.error("Exception thrown during mastership integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800239 }
240 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700241
pierventreb2f636b2022-01-03 17:19:24 +0100242 clusterRequestExecutor = newSingleThreadExecutor();
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700243
pierventreb2f636b2022-01-03 17:19:24 +0100244 communicationService.addSubscriber(
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700245 PORT_UPDOWN_SUBJECT,
246 SERIALIZER::decode,
247 this::handlePortRequest,
pierventreb2f636b2022-01-03 17:19:24 +0100248 clusterRequestExecutor);
249
250 communicationService.addSubscriber(
251 PROBE_SUBJECT,
252 SERIALIZER::decode,
253 this::handleProbeRequest,
254 SERIALIZER::encode,
255 clusterRequestExecutor);
pierventre00ac2502021-12-02 09:42:28 +0100256
257 backgroundRoleChecker = newSingleThreadScheduledExecutor(
258 groupedThreads("onos/device", "manager-role", log));
259 backgroundRoleChecker.scheduleAtFixedRate(() -> {
260 try {
261 roleCheck();
262 } catch (Exception e) {
263 log.error("Exception thrown while verifying role acknowledgement from all devices", e);
264 }
265 }, 0, 10, TimeUnit.SECONDS);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700266
tomd3097b02014-08-26 10:40:29 -0700267 log.info("Started");
268 }
269
270 @Deactivate
271 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800272 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700273 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700274 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700275 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700276 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700277 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
pierventreb2f636b2022-01-03 17:19:24 +0100278 clusterRequestExecutor.shutdown();
pierventre00ac2502021-12-02 09:42:28 +0100279 backgroundRoleChecker.shutdown();
tomd3097b02014-08-26 10:40:29 -0700280 log.info("Stopped");
281 }
282
283 @Override
tomad2d2092014-09-06 23:24:20 -0700284 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900285 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700286 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700287 }
288
289 @Override
mskala32000d32017-07-14 16:27:06 +0200290 public int getAvailableDeviceCount() {
291 checkPermission(DEVICE_READ);
292 return store.getAvailableDeviceCount();
293 }
294
295 @Override
tom32f66842014-08-27 19:27:47 -0700296 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900297 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700298 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700299 }
300
tom32f66842014-08-27 19:27:47 -0700301 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800302 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900303 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800304 return store.getAvailableDevices();
305 }
306
307 @Override
tom32f66842014-08-27 19:27:47 -0700308 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900309 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700310 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700311 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700312 }
313
314 @Override
tomad2d2092014-09-06 23:24:20 -0700315 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900316 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700317 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700318 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700319 }
320
321 @Override
tom32f66842014-08-27 19:27:47 -0700322 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900323 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700324 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700325 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700326 }
327
328 @Override
sangho538108b2015-04-08 14:29:20 -0700329 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900330 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700331 checkNotNull(deviceId, DEVICE_ID_NULL);
332 return store.getPortStatistics(deviceId);
333 }
334
335 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200336 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900337 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200338 checkNotNull(deviceId, DEVICE_ID_NULL);
339 return store.getPortDeltaStatistics(deviceId);
340 }
341
342 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530343 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
344 checkPermission(DEVICE_READ);
345 checkNotNull(deviceId, DEVICE_ID_NULL);
346 checkNotNull(portNumber, PORT_NUMBER_NULL);
347 return store.getStatisticsForPort(deviceId, portNumber);
348 }
349
350 @Override
351 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
352 checkPermission(DEVICE_READ);
353 checkNotNull(deviceId, DEVICE_ID_NULL);
354 checkNotNull(portNumber, PORT_NUMBER_NULL);
355 return store.getDeltaStatisticsForPort(deviceId, portNumber);
356 }
357
358 @Override
tom32f66842014-08-27 19:27:47 -0700359 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900360 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700361 checkNotNull(deviceId, DEVICE_ID_NULL);
362 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700363 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700364 }
365
366 @Override
tomff7eb7c2014-09-08 12:49:03 -0700367 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900368 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900369
tomff7eb7c2014-09-08 12:49:03 -0700370 checkNotNull(deviceId, DEVICE_ID_NULL);
371 return store.isAvailable(deviceId);
372 }
373
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800374 @Override
375 public String localStatus(DeviceId deviceId) {
376 LocalStatus ls = deviceLocalStatus.get(deviceId);
377 if (ls == null) {
378 return "No Record";
379 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700380 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800381 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
382 }
383
Palash Kala0d817b02018-03-23 18:09:45 +0900384 private boolean isLocallyConnected(DeviceId deviceId) {
385 LocalStatus ls = deviceLocalStatus.get(deviceId);
386 if (ls == null) {
387 return false;
388 }
389 return ls.connected;
390 }
391
Ray Milkey054e23d2018-03-22 13:37:11 -0700392 @Override
393 public long getLastUpdatedInstant(DeviceId deviceId) {
394 LocalStatus ls = deviceLocalStatus.get(deviceId);
395 if (ls == null) {
396 return 0;
397 }
398 return ls.dateTime.toEpochMilli();
399 }
400
pierventreeed482b2022-02-18 05:16:48 -0800401 // Returns true if the grace period is still on
402 private boolean inGracePeriod(DeviceId deviceId) {
403 LocalStatus ls = deviceLocalStatus.get(deviceId);
404 if (ls == null) {
405 // This should not be possible, unless the device is removed
406 log.warn("Not found a recent local status for {}", deviceId);
407 return true;
408 }
409 DeviceProvider provider = getProvider(deviceId);
410 return ls.connected &&
411 (Instant.now().toEpochMilli() - ls.dateTime.toEpochMilli()) < provider.gracePeriod();
412 }
413
Palash Kala0d817b02018-03-23 18:09:45 +0900414 // Check a device for control channel connectivity
415 // and changes local-status appropriately.
pierventreeed482b2022-02-18 05:16:48 -0800416 private boolean isReachable(DeviceId deviceId, boolean inGracePeriod) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800417 if (deviceId == null) {
418 return false;
419 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700420 DeviceProvider provider = getProvider(deviceId);
421 if (provider != null) {
pierventreb2f636b2022-01-03 17:19:24 +0100422 boolean reachable = probeReachability(deviceId);
Palash Kala0d817b02018-03-23 18:09:45 +0900423 if (reachable && !isLocallyConnected(deviceId)) {
424 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
pierventreeed482b2022-02-18 05:16:48 -0800425 } else if (!reachable && isLocallyConnected(deviceId) && !inGracePeriod) {
426 // Do not update if the grace period is still on
Palash Kala0d817b02018-03-23 18:09:45 +0900427 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
428 }
429 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700430 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800431 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700432 return false;
433 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700434 }
435
tome5ec3fd2014-09-04 15:18:06 -0700436 @Override
437 public void removeDevice(DeviceId deviceId) {
438 checkNotNull(deviceId, DEVICE_ID_NULL);
439 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700440 if (event != null) {
441 log.info("Device {} administratively removed", deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700442 }
tome5ec3fd2014-09-04 15:18:06 -0700443 }
444
Thomas Vachuska811ea2b2020-02-11 10:20:10 -0800445 @Override
446 public void removeDevicePorts(DeviceId deviceId) {
447 checkNotNull(deviceId, DEVICE_ID_NULL);
448 if (isAvailable(deviceId)) {
449 log.debug("Cannot remove ports of device {} while it is available.", deviceId);
450 return;
451 }
452
453 List<PortDescription> portDescriptions = ImmutableList.of();
454 List<DeviceEvent> events = store.updatePorts(getProvider(deviceId).id(),
455 deviceId, portDescriptions);
456 if (events != null) {
457 for (DeviceEvent event : events) {
458 post(event);
459 }
460 }
461 }
462
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700463 private void handlePortRequest(InternalPortUpDownEvent event) {
464 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700465 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon0bd777c2021-01-01 14:23:29 +0000466 checkNotNull(event.portNumber(), PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700467 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
468 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
469 }
470
471 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
472 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700473 DeviceProvider provider = getProvider(deviceId);
474 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700475 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700476 portNumber, deviceId,
477 (enable) ? "UP" : "DOWN");
478 provider.changePortState(deviceId, portNumber, enable);
479 } else {
480 log.warn("Provider not found for {}", deviceId);
481 }
482 }
483
484 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700485 public void changePortState(DeviceId deviceId, PortNumber portNumber,
486 boolean enable) {
487 checkNotNull(deviceId, DEVICE_ID_NULL);
Sean Condon0bd777c2021-01-01 14:23:29 +0000488 checkNotNull(portNumber, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700489 NodeId masterId = mastershipService.getMasterFor(deviceId);
490
Ray Milkey4ef245e2018-05-10 15:41:16 -0700491 if (masterId == null) {
492 // No master found; device is offline
493 log.info("No master found for port state change for {}", deviceId);
494 return;
495 }
496
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700497 if (!masterId.equals(localNodeId)) {
498 //Send the request to the master node for the device
499 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
500 deviceId, masterId);
501 communicationService.unicast(
502 new InternalPortUpDownEvent(deviceId, portNumber, enable),
503 PORT_UPDOWN_SUBJECT,
504 SERIALIZER::encode,
505 masterId).whenComplete((r, error) -> {
506 if (error != null) {
507 log.warn("Failed to send packet-updown-req to {}", masterId, error);
508 }
509 });
510 } else {
511 changePortStateAtMaster(deviceId, portNumber, enable);
512 }
513 }
514
515 @Override
samuele1fa7322015-07-14 16:35:16 +0800516 protected DeviceProviderService createProviderService(
517 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700518 return new InternalDeviceProviderService(provider);
519 }
520
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800521 /**
522 * Checks if all the reachable devices have a valid mastership role.
523 */
524 private void mastershipCheck() {
525 log.debug("Checking mastership");
526 for (Device device : getDevices()) {
527 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700528 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
529 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
pierventreeed482b2022-02-18 05:16:48 -0800530
531 log.debug("Device {} local status is {}", deviceId, localStatus(deviceId));
532 final boolean isGracePeriodOn = inGracePeriod(deviceId);
533 final boolean isReachable = isReachable(deviceId, isGracePeriodOn);
534 // Passed the grace period and it is still not reachable
535 if (!isGracePeriodOn && !isReachable) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700536 if (myRole != NONE) {
pierventreb2f636b2022-01-03 17:19:24 +0100537 // Verify if the device is fully disconnected from the cluster
538 if (updateMastershipFor(deviceId) == null
539 && myRole == MASTER && isAvailable(deviceId)) {
540 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
541 post(store.markOffline(deviceId));
helenyrwufd296b62016-06-22 17:43:02 -0700542 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530543 } else {
pierventreeed482b2022-02-18 05:16:48 -0800544 // Firstly get a role and then check if the device is available in the store.
545 // if it is, if this node is the master and the device is fully disconnected
546 // from the cluster mark the device offline. In principle, this condition should
547 // never be hit unless in a device removed phase for NONE mastership roles.
pierventreb2f636b2022-01-03 17:19:24 +0100548 try {
549 mastershipService.requestRoleFor(deviceId).get();
550 } catch (InterruptedException e) {
551 Thread.currentThread().interrupt();
552 log.error("Interrupted waiting for Mastership", e);
553 } catch (ExecutionException e) {
554 log.error("Encountered an error waiting for Mastership", e);
555 }
556
557 MastershipTerm term = termService.getMastershipTerm(deviceId);
558 if (updateMastershipFor(deviceId) == null &&
559 term != null && localNodeId.equals(term.master()) &&
560 isAvailable(deviceId)) {
561 log.info("Marking unreachable device {} offline", deviceId);
562 post(store.markOffline(deviceId));
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800563 }
helenyrwufd296b62016-06-22 17:43:02 -0700564 }
pierventreb2f636b2022-01-03 17:19:24 +0100565 roleToAcknowledge.remove(deviceId);
pierventreeed482b2022-02-18 05:16:48 -0800566 } else if (isReachable) {
567 // If this node is the master, ensure the device is marked online.
568 if (myRole == MASTER && canMarkOnline(device)) {
569 log.info("Can mark online {}", deviceId);
570 post(store.markOnline(deviceId));
571 }
572
573 log.info("{} is reachable - reasserting the role", deviceId);
574
575 // Device is still reachable. It is useful for some protocols
576 // to reassert the role. Note: NONE triggers request to MastershipService
577 reassertRole(deviceId, myRole);
578 } else {
579 // Do not proceed furthermore if the grace period is still on
580 log.debug("Skipping mastership check for {}", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800581 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800582 }
583 }
584
pierventre00ac2502021-12-02 09:42:28 +0100585 /**
586 * Checks if all the devices have acknowledged the mastership role.
587 */
588 private void roleCheck() {
589 log.debug("Checking role");
590 for (Device device : getDevices()) {
591 final DeviceId deviceId = device.id();
592 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
593 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
594 final AtomicBoolean exists = new AtomicBoolean(false);
595 final Long ts = roleToAcknowledge.compute(deviceId, (key, value) -> {
596 if (value == null) {
597 return null;
598 }
599 exists.set(true);
600 if (currentTimeMillis() - value < (ROLE_TIMEOUT_SECONDS * 1000)) {
601 return value;
602 }
603 return null;
604 });
605 // Nobody applied the role recently
606 if (!exists.get()) {
607 log.trace("Role was not applied or it has been acknowledged for device {}", deviceId);
608 continue;
609 }
610 // Timeout still on
611 if (ts != null) {
612 log.debug("Timeout expires in {} ms", ((ROLE_TIMEOUT_SECONDS * 1000) - currentTimeMillis() + ts));
613 continue;
614 }
615 if (myRole != MASTER) {
616 log.debug("Timeout is expired but current role is not MASTER ({}), nothing to do", myRole);
617 continue;
618 }
pierventreeed482b2022-02-18 05:16:48 -0800619 // Switch failed to acknowledge master role we asked for.
620 // Yield mastership to other instance
pierventre00ac2502021-12-02 09:42:28 +0100621 log.warn("Failed to assert role onto device {}. requested={}, no response",
622 deviceId, myRole);
pierventreb2f636b2022-01-03 17:19:24 +0100623 updateMastershipFor(deviceId);
pierventre00ac2502021-12-02 09:42:28 +0100624 }
625 }
626
tomd3097b02014-08-26 10:40:29 -0700627 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700628 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700629 extends AbstractProviderService<DeviceProvider>
630 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700631
tomcfde0622014-09-09 11:02:42 -0700632 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700633 super(provider);
634 }
635
Ray Milkey33306ba2018-09-20 13:27:25 -0700636 /**
637 * Apply role in reaction to provider event.
638 *
639 * @param deviceId device identifier
640 * @param newRole new role to apply to the device
641 * @return true if the request was sent to provider
642 */
643 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
644
645 if (newRole.equals(MastershipRole.NONE)) {
646 //no-op
647 return true;
648 }
649
650 DeviceProvider provider = provider();
651 if (provider == null) {
652 log.warn("Provider for {} was not found. Cannot apply role {}",
653 deviceId, newRole);
654 return false;
655 }
pierventre00ac2502021-12-02 09:42:28 +0100656 // Start the timer
657 roleToAcknowledge.put(deviceId, currentTimeMillis());
Ray Milkey33306ba2018-09-20 13:27:25 -0700658 provider.roleChanged(deviceId, newRole);
659 // not triggering probe when triggered by provider service event
660 return true;
661 }
662
tomd3097b02014-08-26 10:40:29 -0700663 @Override
alshabibb7b40632014-09-28 21:30:00 -0700664 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700665 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700666 checkNotNull(deviceId, DEVICE_ID_NULL);
667 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700668 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700669
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700670 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800671
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700672 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
673 if (!isAllowed(cfg)) {
674 log.warn("Device {} is not allowed", deviceId);
675 return;
676 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200677 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700678 // Generate updated description and establish my Role
679 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900680 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
681 if (annoConfig != null) {
682 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
683 }
684
pier388ec252020-04-15 20:53:14 +0200685 // Wait for the end of the election. sync call of requestRoleFor
686 // wait only 3s and it is not entirely safe since the leadership
687 // election timer can be higher.
688 MastershipRole role = Futures.getUnchecked(mastershipService.requestRoleFor(deviceId));
jaegonkim8eabcec2018-07-27 23:40:43 +0900689 log.info("Local role is {} for {}", role, deviceId);
pier388ec252020-04-15 20:53:14 +0200690 store.createOrUpdateDevice(provider().id(), deviceId, deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700691 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700692
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200693 if (portConfig != null) {
694 //updating the ports if configration exists
695 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
696 .collect(Collectors.toList());
697 complete.addAll(portConfig.portDescriptions());
698 List<PortDescription> portDescriptions = complete.stream()
699 .map(e -> applyAllPortOps(deviceId, e))
700 .collect(Collectors.toList());
701 store.updatePorts(provider().id(), deviceId, portDescriptions);
702 }
703
helenyrwufd296b62016-06-22 17:43:02 -0700704 if (deviceDescription.isDefaultAvailable()) {
705 log.info("Device {} connected", deviceId);
706 } else {
707 log.info("Device {} registered", deviceId);
708 }
tomd3097b02014-08-26 10:40:29 -0700709 }
710
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700711 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
712 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800713 return DefaultPortDescription.builder(desc)
714 .isEnabled(enabled)
715 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700716 }
717 return desc;
718 }
719
tomd3097b02014-08-26 10:40:29 -0700720 @Override
721 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700722 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700723 checkValidity();
pierventreb2f636b2022-01-03 17:19:24 +0100724 // Update the local status
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700725 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Andrea Campanellab0b93ac2021-09-13 12:37:36 +0200726 log.info("Device {} disconnected from this node: {}", deviceId,
727 clusterService.getLocalNode().id());
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700728
pierventreeed482b2022-02-18 05:16:48 -0800729 // If none can reach the device, we will continue with the disconnection logic.
730 // If there is one instance that reported device is still reachable, we hand over
731 // the mastership to it if we are the current master, otherwise if we are a backup
732 // we demote ourselves to the bottom of the backups list
pierventreb2f636b2022-01-03 17:19:24 +0100733 if (updateMastershipFor(deviceId) == null) {
734 log.info("Device {} is fully disconnected from the cluster", deviceId);
735 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
736 .map(desc -> ensurePortEnabledState(desc, false))
737 .collect(Collectors.toList());
738 store.updatePorts(this.provider().id(), deviceId, descs);
Yafit Hadara9a73de2015-09-06 13:52:52 +0300739
Madan Jampanic6e574f2015-05-29 13:41:52 -0700740 try {
pierventreb2f636b2022-01-03 17:19:24 +0100741 if (mastershipService.isLocalMaster(deviceId)) {
742 post(store.markOffline(deviceId));
743 }
744 } catch (IllegalStateException e) {
745 log.warn("Failed to mark {} offline", deviceId);
746 // only the MASTER should be marking off-line in normal cases,
747 // but if I was the last STANDBY connection, etc. and no one else
748 // was there to mark the device offline, this instance may need to
749 // temporarily request for Master Role and mark offline.
750
751 //there are times when this node will correctly have mastership, BUT
752 //that isn't reflected in the ClockManager before the device disconnects.
753 //we want to let go of the device anyways, so make sure this happens.
754
755 // FIXME: Store semantics leaking out as IllegalStateException.
756 // Consider revising store API to handle this scenario.
757 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
758 roleFuture.whenComplete((role, error) -> {
759 MastershipTerm term = termService.getMastershipTerm(deviceId);
760 // TODO: Move this type of check inside device clock manager, etc.
761 if (term != null && localNodeId.equals(term.master())) {
762 log.info("Retry marking {} offline", deviceId);
763 post(store.markOffline(deviceId));
764 } else {
765 log.info("Failed again marking {} offline. {}", deviceId, role);
766 }
767 });
768 } finally {
pierventre00ac2502021-12-02 09:42:28 +0100769 roleToAcknowledge.remove(deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700770 }
tom0efbb1d2014-09-09 11:54:28 -0700771 }
pierventreb2f636b2022-01-03 17:19:24 +0100772
tomd3097b02014-08-26 10:40:29 -0700773 }
774
775 @Override
alshabibb7b40632014-09-28 21:30:00 -0700776 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700777 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700778 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700779 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700780 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700781 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700782 // Never been a master for this device
783 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800784 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700785 return;
786 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200787 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
788 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200789 // Updating the ports if configuration exists (on new lists as
790 // the passed one might be immutable)
791 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200792 portDescriptions.addAll(portConfig.portDescriptions());
793 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700794 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700795 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700796 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700797 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800798 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800799 if (events != null) {
800 for (DeviceEvent event : events) {
801 post(event);
802 }
tom32f66842014-08-27 19:27:47 -0700803 }
tomd3097b02014-08-26 10:40:29 -0700804 }
805
806 @Override
alshabibb7b40632014-09-28 21:30:00 -0700807 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700808 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700809 checkNotNull(deviceId, DEVICE_ID_NULL);
810 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700811 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700812
Madan Jampani565a66a2015-07-25 17:01:13 -0700813 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700814 // Never been a master for this device
815 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700816 log.trace("Ignoring {} port update on standby node. {}", deviceId,
817 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700818 return;
819 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700820 Device device = getDevice(deviceId);
821 if (device == null) {
822 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530823 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700824 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100825 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
826 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700827 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700828 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700829 deviceId,
830 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700831 portDescription = ensurePortEnabledState(storedPortDesc,
832 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300833 }
834
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700835 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800836 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700837 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700838 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700839 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800840 log.info("Device {} port {} status changed (enabled={})",
841 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700842 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700843 }
tomd3097b02014-08-26 10:40:29 -0700844 }
tom3f2bbd72014-09-24 12:07:58 -0700845
846 @Override
Michal Machce774332017-01-25 11:02:55 +0100847 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
848
849 checkNotNull(deviceId, DEVICE_ID_NULL);
850 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
851 checkValidity();
852
853 if (!mastershipService.isLocalMaster(deviceId)) {
854 // Never been a master for this device
855 // any update will be ignored.
856 log.trace("Ignoring {} port update on standby node. {}", deviceId,
857 basePortDescription);
858 return;
859 }
860
861 Device device = getDevice(deviceId);
862 if (device == null) {
863 log.trace("Device not found: {}", deviceId);
864 }
865
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800866 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
867 .isRemoved(true)
868 .build();
869
Michal Machce774332017-01-25 11:02:55 +0100870 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
871 deviceId,
872 newPortDescription);
873 if (event != null) {
874 log.info("Device {} port {} status changed", deviceId, event.port().number());
875 post(event);
876 }
877 }
878
879 @Override
samuele1fa7322015-07-14 16:35:16 +0800880 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700881 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700882 // Several things can happen here:
883 // 1. request and response match
884 // 2. request and response don't match
885 // 3. MastershipRole and requested match (and 1 or 2 are true)
886 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
887 //
888 // 2, 4, and 3 with case 2 are failure modes.
889
tom3f2bbd72014-09-24 12:07:58 -0700890 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700891
Madan Jampanif2af7712015-05-29 18:43:52 -0700892 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700893 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700894
895 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800896 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530897 log.warn("Failed to assert role onto Device {}", deviceId);
pierventre00ac2502021-12-02 09:42:28 +0100898 roleToAcknowledge.remove(deviceId);
pierventreb2f636b2022-01-03 17:19:24 +0100899 updateMastershipFor(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700900 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700901 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700902
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800903 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
904
905 if (requested == null) {
906 // Provider is not able to reconcile role responses with
907 // requests. We assume what was requested is what we expect.
908 // This will work only if mastership doesn't change too often,
909 // and devices are left enough time to provide responses before
910 // a different role is requested.
911 requested = expected;
912 }
913
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700914 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800915 if (Objects.equals(requested, expected)) {
pierventre00ac2502021-12-02 09:42:28 +0100916 // Stop the timer
917 log.info("Role has been acknowledged for device {}", deviceId);
918 roleToAcknowledge.remove(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700919 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800920 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
921 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800922 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700923 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800924 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700925 }
926 } else {
927 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200928 log.warn("Failed to assert role onto device {}. requested={}, response={}",
929 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200930 if (requested == MastershipRole.MASTER) {
pierventre00ac2502021-12-02 09:42:28 +0100931 // Stop the timer
932 roleToAcknowledge.remove(deviceId);
pierventreb2f636b2022-01-03 17:19:24 +0100933 updateMastershipFor(deviceId);
Charles Chan3855dc12021-01-06 01:33:03 +0000934 } else if (requested == MastershipRole.STANDBY) {
935 // For P4RT devices, the response role will be NONE when this node is expected to be STANDBY
936 // but the stream channel is not opened correctly.
937 // Calling reassertRole will trigger the mechanism in GeneralDeviceProvider that
938 // attempts to re-establish the stream channel
939 backgroundService.execute(() -> reassertRole(deviceId, expected));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700940 }
941 }
tom3f2bbd72014-09-24 12:07:58 -0700942 }
sangho538108b2015-04-08 14:29:20 -0700943
944 @Override
samuele1fa7322015-07-14 16:35:16 +0800945 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700946 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700947 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700948 checkValidity();
949
samuele1fa7322015-07-14 16:35:16 +0800950 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
951 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700952 post(event);
953 }
pierventree1f80102021-10-01 22:01:22 +0200954
955 @Override
956 public DeviceDescription getDeviceDescription(DeviceId deviceId) {
957 checkNotNull(deviceId, DEVICE_ID_NULL);
958 checkValidity();
959
960 return store.getDeviceDescription(provider().id(), deviceId);
961 }
tomd3097b02014-08-26 10:40:29 -0700962 }
tom32f66842014-08-27 19:27:47 -0700963
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700964 // by default allowed, otherwise check flag
965 private boolean isAllowed(BasicDeviceConfig cfg) {
966 return (cfg == null || cfg.isAllowed());
967 }
968
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700969 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800970 DeviceProvider provider = getProvider(device.id());
971 if (provider == null) {
972 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
973 return false;
974 }
975 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700976 }
977
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800978 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700979
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800980 /**
981 * Apply role to device and send probe if MASTER.
982 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700983 * @param deviceId device identifier
984 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800985 * @return true if the request was sent to provider
986 */
987 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
988 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800989 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700990 return true;
991 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700992
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800993 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800994 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800995 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800996 return false;
997 }
pierventre00ac2502021-12-02 09:42:28 +0100998 // Start the timer
999 roleToAcknowledge.put(deviceId, currentTimeMillis());
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001000 provider.roleChanged(deviceId, newRole);
1001
1002 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -08001003 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001004 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -08001005 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001006 }
1007 return true;
1008 }
1009
pierventreb2f636b2022-01-03 17:19:24 +01001010 private boolean probeReachability(DeviceId deviceId) {
1011 DeviceProvider provider = getProvider(deviceId);
1012 if (provider == null) {
1013 log.warn("Provider for {} was not found. Cannot probe reachability", deviceId);
1014 return false;
1015 }
1016 return provider.isReachable(deviceId) && Tools.futureGetOrElse(provider.probeReachability(deviceId),
1017 PROBE_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS, Boolean.FALSE);
1018 }
1019
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001020 /**
Harold Huangff6e1e62017-11-09 16:25:36 +08001021 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001022 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001023 * @param did device identifier
1024 * @param nextRole role to apply. If NONE is specified,
1025 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001026 */
samuele1fa7322015-07-14 16:35:16 +08001027 private void reassertRole(final DeviceId did,
1028 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001029
Jordan Halterman9416aea2017-11-17 12:40:21 -08001030 MastershipRole myNextRole = nextRole;
1031 if (myNextRole == NONE && upgradeService.isLocalActive()) {
1032 try {
1033 mastershipService.requestRoleFor(did).get();
1034 MastershipTerm term = termService.getMastershipTerm(did);
1035 if (term != null && localNodeId.equals(term.master())) {
1036 myNextRole = MASTER;
1037 } else {
1038 myNextRole = STANDBY;
1039 }
1040 } catch (InterruptedException e) {
1041 Thread.currentThread().interrupt();
1042 log.error("Interrupted waiting for Mastership", e);
1043 } catch (ExecutionException e) {
1044 log.error("Encountered an error waiting for Mastership", e);
1045 }
1046 }
1047
1048 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001049 case MASTER:
1050 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -07001051 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +09001052 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001053 }
1054 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -08001055 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001056 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -08001057 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001058 // immediately failed to apply role
pierventreb2f636b2022-01-03 17:19:24 +01001059 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001060 // FIXME disconnect?
1061 }
1062 break;
1063 case STANDBY:
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, STANDBY)) {
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
pierventreb2f636b2022-01-03 17:19:24 +01001068 updateMastershipFor(did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001069 // FIXME disconnect?
1070 }
1071 break;
1072 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -07001073 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001074 default:
1075 // should never reach here
1076 log.error("You didn't see anything. I did not exist.");
1077 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001078 }
1079 }
1080
Madan Jampani328371d2015-05-29 14:06:27 -07001081 private void handleMastershipEvent(MastershipEvent event) {
pierventreeed482b2022-02-18 05:16:48 -08001082 log.debug("Handling mastership event");
Madan Jampani328371d2015-05-29 14:06:27 -07001083 final DeviceId did = event.subject();
1084
pierventreb2f636b2022-01-03 17:19:24 +01001085 // myNextRole suggested by MastershipService event
Madan Jampani328371d2015-05-29 14:06:27 -07001086 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -07001087 if (event.type() == MastershipEvent.Type.SUSPENDED) {
1088 myNextRole = NONE; // FIXME STANDBY OR NONE?
1089 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -07001090 // confirm latest info
1091 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +08001092 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -07001093 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -07001094 myNextRole = MASTER;
1095 } else {
1096 myNextRole = STANDBY;
1097 }
1098 } else if (event.roleInfo().backups().contains(localNodeId)) {
1099 myNextRole = STANDBY;
1100 } else {
1101 myNextRole = NONE;
1102 }
1103
pierventreeed482b2022-02-18 05:16:48 -08001104 log.debug("Device {} local status is {}", did, localStatus(did));
1105 final boolean isGracePeriodOn = inGracePeriod(did);
1106 final boolean isReachable = isReachable(did, isGracePeriodOn);
1107 // Passed the grace period and it is still not reachable
1108 if (!isGracePeriodOn && !isReachable) {
pierventreb2f636b2022-01-03 17:19:24 +01001109 // device is not connected to this node, nevertheless we should get a role
Jon Halla90c44c2017-01-24 16:02:07 -08001110 if (mastershipService.getLocalRole(did) == NONE) {
1111 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -07001112 + "but this node cannot reach the device "
pierventreb2f636b2022-01-03 17:19:24 +01001113 + "and role is already None. Asking a new role "
1114 + "and then apply the disconnection protocol.",
Simon Huntffbad3b2017-05-16 15:37:51 -07001115 myNextRole, did);
pierventreb2f636b2022-01-03 17:19:24 +01001116 try {
1117 mastershipService.requestRoleFor(did).get();
1118 } catch (InterruptedException e) {
1119 Thread.currentThread().interrupt();
1120 log.error("Interrupted waiting for Mastership", e);
1121 } catch (ExecutionException e) {
1122 log.error("Encountered an error waiting for Mastership", e);
1123 }
Jon Halla90c44c2017-01-24 16:02:07 -08001124 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -07001125 log.warn("Node was instructed to be {} role for {}, "
pierventreb2f636b2022-01-03 17:19:24 +01001126 + "but this node cannot reach the device. "
1127 + "Apply the disconnection protocol.",
samuele1fa7322015-07-14 16:35:16 +08001128 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -07001129 }
pierventreb2f636b2022-01-03 17:19:24 +01001130 // Let's put some order in the candidates list
1131 roleToAcknowledge.remove(did);
1132 updateMastershipFor(did);
pierventreeed482b2022-02-18 05:16:48 -08001133 } else if (isReachable) {
1134 // Device is connected to this node - always reassert the role.
1135 // Ideally, protocols like OpenFlow would not need to reassert the
1136 // role because the instances are only identified by the role. However,
1137 // other protocols like P4RT require to provide also an election id
1138 // which maybe different over time, by reasserting the role will guarantee
1139 // that updated election ids are communicated to the devices. It should not
1140 // cost us a lot as it is equivalent to a probe.
1141 if (store.getDevice(did) != null) {
1142 log.info("{} is reachable - reasserting the role", did);
1143 reassertRole(did, myNextRole);
1144 } else {
1145 log.debug("Device is not yet/no longer in the store: {}", did);
1146 }
Madan Jampani328371d2015-05-29 14:06:27 -07001147 } else {
pierventreeed482b2022-02-18 05:16:48 -08001148 // Do not proceed furthermore if the grace period is still on
1149 log.debug("Skipping mastership event {}", event);
Madan Jampani328371d2015-05-29 14:06:27 -07001150 }
1151 }
1152
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001153 // Intercepts mastership events
1154 private class InternalMastershipListener implements MastershipListener {
1155
tomb41d1ac2014-09-24 01:51:24 -07001156 @Override
1157 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001158 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001159 try {
1160 handleMastershipEvent(event);
1161 } catch (Exception e) {
1162 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001163 }
Madan Jampani328371d2015-05-29 14:06:27 -07001164 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001165 }
tomb41d1ac2014-09-24 01:51:24 -07001166 }
tomf80c9722014-09-24 14:49:18 -07001167
1168 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001169 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001170 @Override
1171 public void notify(DeviceEvent event) {
1172 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001173 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001174 // When device is administratively removed, force disconnect.
1175 DeviceId deviceId = event.subject().id();
1176 deviceLocalStatus.remove(deviceId);
1177
1178 DeviceProvider provider = getProvider(deviceId);
1179 if (provider != null) {
1180 log.info("Triggering disconnect for device {}", deviceId);
1181 try {
1182 provider.triggerDisconnect(deviceId);
1183 } catch (UnsupportedOperationException e) {
1184 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1185 }
1186 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001187 }
tomf80c9722014-09-24 14:49:18 -07001188 }
1189 }
samuel738dfaf2015-07-11 11:08:57 +08001190
1191 @Override
1192 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001193 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001194 Set<Device> results = new HashSet<>();
1195 Iterable<Device> devices = store.getDevices();
1196 if (devices != null) {
1197 devices.forEach(d -> {
1198 if (type.equals(d.type())) {
1199 results.add(d);
1200 }
1201 });
1202 }
1203 return results;
1204 }
1205
1206 @Override
1207 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001208 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001209 Set<Device> results = new HashSet<>();
1210 Iterable<Device> availableDevices = store.getAvailableDevices();
1211 if (availableDevices != null) {
1212 availableDevices.forEach(d -> {
1213 if (type.equals(d.type())) {
1214 results.add(d);
1215 }
1216 });
1217 }
1218 return results;
1219 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001220
1221 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001222 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1223 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301224 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001225 if (event.subject().getClass() == ConnectPoint.class) {
1226 deviceId = ((ConnectPoint) event.subject()).deviceId();
1227 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001228 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301229 deviceId = (DeviceId) event.subject();
1230 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001231 return deviceId;
1232 }
1233
1234 @Override
1235 public boolean isRelevant(NetworkConfigEvent event) {
1236 DeviceId deviceId = extractDeviceId(event);
1237
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001238 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301239 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1240 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001241 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001242 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001243 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001244 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001245 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001246 }
1247
1248 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001249 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001250 DeviceEvent de = null;
1251 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001252 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001253 DeviceId did = (DeviceId) event.subject();
1254 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001255 BasicDeviceConfig cfg =
1256 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001257
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001258 if (!isAllowed(cfg)) {
1259 kickOutBadDevice(did);
1260 } else {
1261 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001262 DeviceDescription desc =
1263 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001264 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001265 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001266 store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001267 }
1268 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001269 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1270 DeviceId did = (DeviceId) event.subject();
1271 DeviceProvider dp = getProvider(did);
1272 if (!event.config().isPresent() ||
1273 getDevice(did) == null || dp == null) {
1274 // sanity check failed, ignore
1275 return;
1276 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001277 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001278 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001279 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1280 .collect(Collectors.toList());
1281 complete.addAll(portConfig.portDescriptions());
1282 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001283 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1284 DeviceId did = (DeviceId) event.subject();
1285 DeviceProvider dp = getProvider(did);
1286 Device dev = getDevice(did);
1287 DeviceDescription desc =
1288 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1289 Optional<Config> prevConfig = event.prevConfig();
Anurag Chadha61946392020-08-28 15:18:03 +05301290 if (desc != null) { // Fix for NPE due to desc being null
1291 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1292 }
Palash Kalaa06a6162017-11-15 20:42:40 +09001293 if (desc != null && dp != null) {
pier388ec252020-04-15 20:53:14 +02001294 store.createOrUpdateDevice(dp.id(), did, desc);
Palash Kalaa06a6162017-11-15 20:42:40 +09001295 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001296 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001297 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001298 DeviceId did = cpt.deviceId();
1299 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001300
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001301 // Note: assuming PortOperator can modify existing port,
1302 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001303 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001304 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301305 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001306 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001307 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001308 }
1309
1310 if (de != null) {
1311 post(de);
1312 }
1313 }
1314
Simon Hunt8f60ff82017-04-24 17:19:30 -07001315 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001316 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001317 Device badDevice = getDevice(deviceId);
1318 if (badDevice != null) {
1319 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001320 }
1321 }
1322 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001323
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001324 @Override
1325 @SafeVarargs
1326 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001327 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001328 checkNotNull(portOp);
1329
1330 portOp.bindService(networkConfigService);
1331
1332 // update both portOpsIndex and portOps
1333 synchronized (portOpsIndex) {
1334 for (Class<? extends Config<ConnectPoint>> config : configs) {
1335 portOpsIndex.put(config, portOp);
1336 }
1337
1338 portOps.add(portOp);
1339 }
1340
1341 // TODO: Should we be applying to all existing Ports?
1342 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001343 .map(Device::id)
1344 .filter(mastershipService::isLocalMaster)
1345 // for each locally managed Device, update all port descriptions
1346 .map(did -> {
1347 ProviderId pid = Optional.ofNullable(getProvider(did))
1348 .map(Provider::id)
1349 .orElse(null);
1350 if (pid == null) {
1351 log.warn("Provider not found for {}", did);
1352 return ImmutableList.<DeviceEvent>of();
1353 }
1354 List<PortDescription> pds
1355 = store.getPortDescriptions(pid, did)
1356 .map(pdesc -> applyAllPortOps(did, pdesc))
1357 .collect(Collectors.toList());
1358 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001359 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001360 // ..and port port update event if necessary
1361 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001362 }
1363
1364 @Override
1365 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1366 checkNotNull(portOp);
1367
1368
1369 // remove all portOp
1370 synchronized (portOpsIndex) {
1371 portOps.remove(portOp);
1372
1373 // had to do this since COWArrayList iterator doesn't support remove
1374 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1375 }
1376
1377 }
1378
1379 /**
1380 * Merges the appropriate PortConfig with the description.
1381 *
1382 * @param did ID of the Device where the port is attached
1383 * @param desc {@link PortDescription}
1384 * @return merged {@link PortDescription}
1385 */
1386 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1387 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1388 }
1389
1390 /**
1391 * Merges the appropriate PortConfig with the description.
1392 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001393 * @param cpt ConnectPoint where the port is attached
1394 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001395 * @return merged {@link PortDescription}
1396 */
1397 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1398 PortDescription work = desc;
1399 for (PortConfigOperator portOp : portOps) {
1400 work = portOp.combine(cpt, work);
1401 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001402 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001403 }
1404
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001405 /**
debmaiti9553ed72019-03-18 14:27:42 +05301406 * Merges the appropriate PortConfig with the description.
1407 *
1408 * @param cpt ConnectPoint where the port is attached
1409 * @param desc {@link PortDescription}
1410 * @param prevConfig previous configuration
1411 * @return merged {@link PortDescription}
1412 */
1413 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1414 Optional<Config> prevConfig) {
1415 PortDescription work = desc;
1416 for (PortConfigOperator portOp : portOps) {
1417 work = portOp.combine(cpt, work, prevConfig);
1418 }
1419 return portAnnotationOp.combine(cpt, work, prevConfig);
1420 }
1421
1422 /**
pierventreb2f636b2022-01-03 17:19:24 +01001423 * Handler for remote probe requests.
1424 *
1425 * @param deviceId the device to check
1426 * @return whether or not the device is reachable
1427 */
1428 private boolean handleProbeRequest(DeviceId deviceId) {
1429 int attempt = 0;
1430 // Let's do a number of attempts
1431 while (attempt < PROBE_ATTEMPTS) {
1432 if (!probeReachability(deviceId)) {
1433 return false;
1434 }
1435 attempt++;
1436 }
1437 return true;
1438 }
1439
1440 /**
1441 * Update the mastership for this device. If there is a node able
1442 * to reach the device and this node is the master move the
1443 * mastership to the next node still connected to this device.
1444 * If the current node is a backup, it demotes itself to the bottom
1445 * of the candidates list
1446 *
1447 * @param deviceId the device for which we have to update the mastership
1448 * @return the NodeId of any node that can reach the device, or null if
1449 * none of the ONOS instances can reach the device
1450 */
1451 private NodeId updateMastershipFor(DeviceId deviceId) {
1452 Map<NodeId, CompletableFuture<Boolean>> probes = Maps.newHashMap();
1453 // Request a probe only if the node is ready
1454 for (ControllerNode onosNode : clusterService.getNodes()) {
1455 if (!clusterService.getState(onosNode.id()).isReady() || localNodeId.equals(onosNode.id())) {
1456 continue;
1457 }
1458 probes.put(onosNode.id(), communicationService.sendAndReceive(deviceId, PROBE_SUBJECT, SERIALIZER::encode,
1459 SERIALIZER::decode, onosNode.id()));
1460 }
1461
1462 // Returns the first node able to reach the device
1463 // FIXME [SDFAB-935] optimize by looking at the MastershipInfo
1464 boolean isReachable;
1465 NodeId nextMaster = null;
1466 // FIXME Should we expose timeout? Understand if there is need to signal to the caller
1467 for (Map.Entry<NodeId, CompletableFuture<Boolean>> probe : probes.entrySet()) {
1468 isReachable = Tools.futureGetOrElse(probe.getValue(), PROBE_TIMEOUT_MILLIS,
1469 TimeUnit.MILLISECONDS, Boolean.FALSE);
1470 if (isReachable) {
1471 nextMaster = probe.getKey();
1472 }
1473 }
1474
1475 // FIXME [SDFAB-935] optimize demote by looking at the MastershipInfo;
1476 if (nextMaster != null) {
1477 log.info("Device {} is still connected to {}", deviceId, nextMaster);
1478 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
1479 if (myRole == MASTER) {
1480 log.info("Handing over the mastership of {} to next master {}", deviceId, nextMaster);
1481 mastershipAdminService.setRole(nextMaster, deviceId, MASTER);
pierventreeed482b2022-02-18 05:16:48 -08001482 // Do not demote here because setRole can return before the mastership has been passed.
1483 // Current implementation promotes first the nextMaster as top of candidate list and then
1484 // transfer the leadership. We can use the BACKUP events to do demote or leverage periodic
1485 // checks.
pierventreb2f636b2022-01-03 17:19:24 +01001486 } else if (myRole == STANDBY) {
1487 log.info("Demote current instance to the bottom of the candidates list for {}", deviceId);
1488 mastershipAdminService.demote(localNodeId, deviceId);
1489 } else {
1490 log.debug("No valid role for {}", deviceId);
1491 }
1492 }
1493
1494 return nextMaster;
1495 }
1496
pierventreb2f636b2022-01-03 17:19:24 +01001497 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001498 * Port Enable/Disable message sent to the device's MASTER node.
1499 */
1500 private class InternalPortUpDownEvent {
1501 private final DeviceId deviceId;
1502 private final PortNumber portNumber;
1503 private final boolean enable;
1504
1505 protected InternalPortUpDownEvent(
1506 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1507 this.deviceId = deviceId;
1508 this.portNumber = portNumber;
1509 this.enable = enable;
1510 }
1511
1512 public DeviceId deviceId() {
1513 return deviceId;
1514 }
1515 public PortNumber portNumber() {
1516 return portNumber;
1517 }
1518 public boolean isEnable() {
1519 return enable;
1520 }
1521
1522 protected InternalPortUpDownEvent() {
1523 this.deviceId = null;
1524 this.portNumber = null;
1525 this.enable = false;
1526 }
1527 }
tomd3097b02014-08-26 10:40:29 -07001528}