blob: be24991e6861a8c382b271656e4051b8555a6112 [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;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070022import org.onlab.util.KryoNamespace;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070023import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080024import org.onosproject.cluster.ClusterService;
25import org.onosproject.cluster.NodeId;
Brian O'Connorabafb502014-12-02 22:26:20 -080026import org.onosproject.mastership.MastershipEvent;
27import org.onosproject.mastership.MastershipListener;
28import org.onosproject.mastership.MastershipService;
29import org.onosproject.mastership.MastershipTerm;
30import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070031import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080032import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080033import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.net.DeviceId;
35import org.onosproject.net.MastershipRole;
36import org.onosproject.net.Port;
37import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070038import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030039import org.onosproject.net.config.NetworkConfigEvent;
40import org.onosproject.net.config.NetworkConfigListener;
41import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070042import org.onosproject.net.config.PortConfigOperator;
43import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030044import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090045import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080046import org.onosproject.net.config.basics.PortAnnotationConfig;
Carmelo Cascone3977ea42019-02-28 13:43:42 -080047import org.onosproject.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080048import org.onosproject.net.device.DefaultPortDescription;
49import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080050import org.onosproject.net.device.DeviceDescription;
51import org.onosproject.net.device.DeviceEvent;
52import org.onosproject.net.device.DeviceListener;
53import org.onosproject.net.device.DeviceProvider;
54import org.onosproject.net.device.DeviceProviderRegistry;
55import org.onosproject.net.device.DeviceProviderService;
56import org.onosproject.net.device.DeviceService;
57import org.onosproject.net.device.DeviceStore;
58import org.onosproject.net.device.DeviceStoreDelegate;
59import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070060import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030061import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080062import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080063import org.onosproject.net.provider.Provider;
64import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070065import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
66import org.onosproject.store.cluster.messaging.MessageSubject;
67import org.onosproject.store.serializers.KryoNamespaces;
68import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080069import org.onosproject.upgrade.UpgradeService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070070import org.osgi.service.component.annotations.Activate;
71import org.osgi.service.component.annotations.Component;
72import org.osgi.service.component.annotations.Deactivate;
73import org.osgi.service.component.annotations.Reference;
74import org.osgi.service.component.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070075import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070076
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070077import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070078import java.util.Collection;
79import java.util.HashSet;
80import java.util.List;
81import java.util.Map;
82import java.util.Objects;
83import java.util.Optional;
84import java.util.Set;
85import java.util.concurrent.CompletableFuture;
86import java.util.concurrent.ConcurrentHashMap;
87import java.util.concurrent.CopyOnWriteArrayList;
88import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070089import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070090import java.util.concurrent.ScheduledExecutorService;
91import java.util.concurrent.TimeUnit;
92import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080093
Ray Milkey9ef22232016-07-14 12:42:37 -070094import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070095import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070096import static com.google.common.collect.Multimaps.newListMultimap;
97import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070098import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -070099import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
100import static org.onlab.util.Tools.groupedThreads;
101import static org.onosproject.net.MastershipRole.MASTER;
102import static org.onosproject.net.MastershipRole.NONE;
103import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700104import static org.onosproject.security.AppGuard.checkPermission;
105import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
106import static org.slf4j.LoggerFactory.getLogger;
107
tomd3097b02014-08-26 10:40:29 -0700108/**
tome4729872014-09-23 00:37:37 -0700109 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700110 */
Ray Milkey86ad7bb2018-09-27 12:32:28 -0700111@Component(immediate = true,
112 service = {DeviceService.class, DeviceAdminService.class,
113 DeviceProviderRegistry.class, PortConfigOperatorRegistry.class })
tom41a2c5f2014-09-19 09:20:35 -0700114public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700115 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700116 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700117
tome5ec3fd2014-09-04 15:18:06 -0700118 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
119 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
120 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
121 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700122 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700123 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700124
tom5f38b3a2014-08-27 23:50:54 -0700125 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700126
alshabib339a3d92014-09-26 17:54:32 -0700127 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700128
tomc78acee2014-09-24 15:16:55 -0700129 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700130 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700131
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800132 private ScheduledExecutorService backgroundService;
133
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700134 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
135
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom41a2c5f2014-09-19 09:20:35 -0700137 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700138
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tomb41d1ac2014-09-24 01:51:24 -0700140 protected ClusterService clusterService;
141
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700142 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700143 protected MastershipService mastershipService;
144
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700145 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700146 protected MastershipTermService termService;
147
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800149 protected UpgradeService upgradeService;
150
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700151 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700152 protected NetworkConfigService networkConfigService;
153
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700155 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700156
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700157 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700158 /**
159 * List of all registered PortConfigOperator.
160 */
161 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
162
163 /**
164 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
165 */
166 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700167 = synchronizedListMultimap(
168 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700169
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800170 // not part of portOps. must be executed at the end
171 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900172 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800173
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700174 private static final MessageSubject PORT_UPDOWN_SUBJECT =
175 new MessageSubject("port-updown-req");
176
177 private static final Serializer SERIALIZER = Serializer.using(
178 KryoNamespace.newBuilder()
179 .register(KryoNamespaces.API)
180 .register(InternalPortUpDownEvent.class)
181 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
182 .build("DeviceManager"));
183
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800184 /**
185 * Local storage for connectivity status of devices.
186 */
187 private class LocalStatus {
188 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700189 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800190
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700191 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800192 connected = b;
193 dateTime = now;
194 }
195 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700196
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800197 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
198 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700199
tomd3097b02014-08-26 10:40:29 -0700200 @Activate
201 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800202 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900203 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800204 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
205
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800206 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700207 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700208 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800209
tomf80c9722014-09-24 14:49:18 -0700210 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700211 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700212 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700213 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800214
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700215 backgroundService.scheduleWithFixedDelay(() -> {
216 try {
217 mastershipCheck();
218 } catch (Exception e) {
219 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800220 }
221 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700222
223 portReqeustExecutor = newSingleThreadExecutor();
224
225 communicationService.<InternalPortUpDownEvent>addSubscriber(
226 PORT_UPDOWN_SUBJECT,
227 SERIALIZER::decode,
228 this::handlePortRequest,
229 portReqeustExecutor);
230
tomd3097b02014-08-26 10:40:29 -0700231 log.info("Started");
232 }
233
234 @Deactivate
235 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800236 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700237 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700238 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700239 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700240 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700241 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
242 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700243 log.info("Stopped");
244 }
245
246 @Override
tomad2d2092014-09-06 23:24:20 -0700247 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900248 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700249 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700250 }
251
252 @Override
mskala32000d32017-07-14 16:27:06 +0200253 public int getAvailableDeviceCount() {
254 checkPermission(DEVICE_READ);
255 return store.getAvailableDeviceCount();
256 }
257
258 @Override
tom32f66842014-08-27 19:27:47 -0700259 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900260 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700261 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700262 }
263
tom32f66842014-08-27 19:27:47 -0700264 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800265 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900266 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800267 return store.getAvailableDevices();
268 }
269
270 @Override
tom32f66842014-08-27 19:27:47 -0700271 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900272 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700273 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700274 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700275 }
276
277 @Override
tomad2d2092014-09-06 23:24:20 -0700278 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700280 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700281 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700282 }
283
284 @Override
tom32f66842014-08-27 19:27:47 -0700285 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900286 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700287 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700288 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700289 }
290
291 @Override
sangho538108b2015-04-08 14:29:20 -0700292 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900293 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700294 checkNotNull(deviceId, DEVICE_ID_NULL);
295 return store.getPortStatistics(deviceId);
296 }
297
298 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200299 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900300 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200301 checkNotNull(deviceId, DEVICE_ID_NULL);
302 return store.getPortDeltaStatistics(deviceId);
303 }
304
305 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530306 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
307 checkPermission(DEVICE_READ);
308 checkNotNull(deviceId, DEVICE_ID_NULL);
309 checkNotNull(portNumber, PORT_NUMBER_NULL);
310 return store.getStatisticsForPort(deviceId, portNumber);
311 }
312
313 @Override
314 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
315 checkPermission(DEVICE_READ);
316 checkNotNull(deviceId, DEVICE_ID_NULL);
317 checkNotNull(portNumber, PORT_NUMBER_NULL);
318 return store.getDeltaStatisticsForPort(deviceId, portNumber);
319 }
320
321 @Override
tom32f66842014-08-27 19:27:47 -0700322 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900323 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700324 checkNotNull(deviceId, DEVICE_ID_NULL);
325 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700326 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700327 }
328
329 @Override
tomff7eb7c2014-09-08 12:49:03 -0700330 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900331 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900332
tomff7eb7c2014-09-08 12:49:03 -0700333 checkNotNull(deviceId, DEVICE_ID_NULL);
334 return store.isAvailable(deviceId);
335 }
336
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800337 @Override
338 public String localStatus(DeviceId deviceId) {
339 LocalStatus ls = deviceLocalStatus.get(deviceId);
340 if (ls == null) {
341 return "No Record";
342 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700343 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800344 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
345 }
346
Palash Kala0d817b02018-03-23 18:09:45 +0900347 private boolean isLocallyConnected(DeviceId deviceId) {
348 LocalStatus ls = deviceLocalStatus.get(deviceId);
349 if (ls == null) {
350 return false;
351 }
352 return ls.connected;
353 }
354
Ray Milkey054e23d2018-03-22 13:37:11 -0700355 @Override
356 public long getLastUpdatedInstant(DeviceId deviceId) {
357 LocalStatus ls = deviceLocalStatus.get(deviceId);
358 if (ls == null) {
359 return 0;
360 }
361 return ls.dateTime.toEpochMilli();
362 }
363
Palash Kala0d817b02018-03-23 18:09:45 +0900364 // Check a device for control channel connectivity
365 // and changes local-status appropriately.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700366 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800367 if (deviceId == null) {
368 return false;
369 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700370 DeviceProvider provider = getProvider(deviceId);
371 if (provider != null) {
Palash Kala0d817b02018-03-23 18:09:45 +0900372 boolean reachable = provider.isReachable(deviceId);
373 if (reachable && !isLocallyConnected(deviceId)) {
374 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
375 } else if (!reachable && isLocallyConnected(deviceId)) {
376 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
377 }
378 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700379 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800380 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700381 return false;
382 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700383 }
384
tome5ec3fd2014-09-04 15:18:06 -0700385 @Override
386 public void removeDevice(DeviceId deviceId) {
387 checkNotNull(deviceId, DEVICE_ID_NULL);
388 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700389 if (event != null) {
390 log.info("Device {} administratively removed", deviceId);
391 post(event);
392 }
tome5ec3fd2014-09-04 15:18:06 -0700393 }
394
Thomas Vachuska811ea2b2020-02-11 10:20:10 -0800395 @Override
396 public void removeDevicePorts(DeviceId deviceId) {
397 checkNotNull(deviceId, DEVICE_ID_NULL);
398 if (isAvailable(deviceId)) {
399 log.debug("Cannot remove ports of device {} while it is available.", deviceId);
400 return;
401 }
402
403 List<PortDescription> portDescriptions = ImmutableList.of();
404 List<DeviceEvent> events = store.updatePorts(getProvider(deviceId).id(),
405 deviceId, portDescriptions);
406 if (events != null) {
407 for (DeviceEvent event : events) {
408 post(event);
409 }
410 }
411 }
412
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700413 private void handlePortRequest(InternalPortUpDownEvent event) {
414 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700415 checkNotNull(deviceId, DEVICE_ID_NULL);
416 checkNotNull(deviceId, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700417 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
418 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
419 }
420
421 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
422 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700423 DeviceProvider provider = getProvider(deviceId);
424 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700425 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700426 portNumber, deviceId,
427 (enable) ? "UP" : "DOWN");
428 provider.changePortState(deviceId, portNumber, enable);
429 } else {
430 log.warn("Provider not found for {}", deviceId);
431 }
432 }
433
434 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700435 public void changePortState(DeviceId deviceId, PortNumber portNumber,
436 boolean enable) {
437 checkNotNull(deviceId, DEVICE_ID_NULL);
438 checkNotNull(deviceId, PORT_NUMBER_NULL);
439 NodeId masterId = mastershipService.getMasterFor(deviceId);
440
Ray Milkey4ef245e2018-05-10 15:41:16 -0700441 if (masterId == null) {
442 // No master found; device is offline
443 log.info("No master found for port state change for {}", deviceId);
444 return;
445 }
446
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700447 if (!masterId.equals(localNodeId)) {
448 //Send the request to the master node for the device
449 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
450 deviceId, masterId);
451 communicationService.unicast(
452 new InternalPortUpDownEvent(deviceId, portNumber, enable),
453 PORT_UPDOWN_SUBJECT,
454 SERIALIZER::encode,
455 masterId).whenComplete((r, error) -> {
456 if (error != null) {
457 log.warn("Failed to send packet-updown-req to {}", masterId, error);
458 }
459 });
460 } else {
461 changePortStateAtMaster(deviceId, portNumber, enable);
462 }
463 }
464
465 @Override
samuele1fa7322015-07-14 16:35:16 +0800466 protected DeviceProviderService createProviderService(
467 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700468 return new InternalDeviceProviderService(provider);
469 }
470
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800471 /**
472 * Checks if all the reachable devices have a valid mastership role.
473 */
474 private void mastershipCheck() {
475 log.debug("Checking mastership");
476 for (Device device : getDevices()) {
477 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700478 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
479 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800480 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700481 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700482 // can't be master if device is not reachable
483 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700484 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100485 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700486 post(store.markOffline(deviceId));
487 }
helenyrwufd296b62016-06-22 17:43:02 -0700488 //relinquish master role and ability to be backup.
489 mastershipService.relinquishMastership(deviceId).get();
490 } catch (InterruptedException e) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700491 log.warn("Interrupted while relinquishing role for {}", deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700492 Thread.currentThread().interrupt();
493 } catch (ExecutionException e) {
494 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
495 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530496 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100497 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530498 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100499 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800500 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100501 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800502 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
503 roleFuture.thenAccept(role -> {
504 MastershipTerm term = termService.getMastershipTerm(deviceId);
505 if (term != null && localNodeId.equals(term.master())) {
506 log.info("Marking unreachable device {} offline", deviceId);
507 post(store.markOffline(deviceId));
508 } else {
509 log.info("Failed marking {} offline. {}", deviceId, role);
510 }
511 mastershipService.relinquishMastership(deviceId);
512 });
513 }
helenyrwufd296b62016-06-22 17:43:02 -0700514 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800515 continue;
516 }
517
Jordan Halterman368bd3d2019-01-04 12:45:57 -0800518 // If this node is the master, ensure the device is marked online.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800519 if (myRole == MASTER && canMarkOnline(device)) {
Jordan Halterman368bd3d2019-01-04 12:45:57 -0800520 post(store.markOnline(deviceId));
521 }
522
Ray Milkeyc7104672016-08-31 12:04:34 -0700523 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800524 continue;
525 }
526
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700527 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800528
529 // isReachable but was not MASTER or STANDBY, get a role and apply
530 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800531 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800532 }
533 }
534
tomd3097b02014-08-26 10:40:29 -0700535 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700536 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700537 extends AbstractProviderService<DeviceProvider>
538 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700539
tomcfde0622014-09-09 11:02:42 -0700540 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700541 super(provider);
542 }
543
Ray Milkey33306ba2018-09-20 13:27:25 -0700544 /**
545 * Apply role in reaction to provider event.
546 *
547 * @param deviceId device identifier
548 * @param newRole new role to apply to the device
549 * @return true if the request was sent to provider
550 */
551 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
552
553 if (newRole.equals(MastershipRole.NONE)) {
554 //no-op
555 return true;
556 }
557
558 DeviceProvider provider = provider();
559 if (provider == null) {
560 log.warn("Provider for {} was not found. Cannot apply role {}",
561 deviceId, newRole);
562 return false;
563 }
564 provider.roleChanged(deviceId, newRole);
565 // not triggering probe when triggered by provider service event
566 return true;
567 }
568
tomd3097b02014-08-26 10:40:29 -0700569 @Override
alshabibb7b40632014-09-28 21:30:00 -0700570 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700571 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700572 checkNotNull(deviceId, DEVICE_ID_NULL);
573 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700574 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700575
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700576 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800577
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700578 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
579 if (!isAllowed(cfg)) {
580 log.warn("Device {} is not allowed", deviceId);
581 return;
582 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200583 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700584 // Generate updated description and establish my Role
585 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900586 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
587 if (annoConfig != null) {
588 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
589 }
590
jaegonkim8eabcec2018-07-27 23:40:43 +0900591 MastershipRole role = mastershipService.requestRoleForSync(deviceId);
592 log.info("Local role is {} for {}", role, deviceId);
Yi Tseng7be4e672017-12-05 15:03:26 -0800593 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
jaegonkim8eabcec2018-07-27 23:40:43 +0900594 deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700595 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700596
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200597 if (portConfig != null) {
598 //updating the ports if configration exists
599 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
600 .collect(Collectors.toList());
601 complete.addAll(portConfig.portDescriptions());
602 List<PortDescription> portDescriptions = complete.stream()
603 .map(e -> applyAllPortOps(deviceId, e))
604 .collect(Collectors.toList());
605 store.updatePorts(provider().id(), deviceId, portDescriptions);
606 }
607
helenyrwufd296b62016-06-22 17:43:02 -0700608 if (deviceDescription.isDefaultAvailable()) {
609 log.info("Device {} connected", deviceId);
610 } else {
611 log.info("Device {} registered", deviceId);
612 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200613
tom80c0e5e2014-09-08 18:08:58 -0700614 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700615 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700616 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700617 }
tomd3097b02014-08-26 10:40:29 -0700618 }
619
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700620 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
621 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800622 return DefaultPortDescription.builder(desc)
623 .isEnabled(enabled)
624 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700625 }
626 return desc;
627 }
628
tomd3097b02014-08-26 10:40:29 -0700629 @Override
630 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700631 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700632 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700633 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700634 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700635
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700636 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
637 .map(desc -> ensurePortEnabledState(desc, false))
638 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300639
alshabibafc514a2014-12-01 14:44:05 -0800640 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700641 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700642 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700643 post(store.markOffline(deviceId));
644 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700645 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700646 log.warn("Failed to mark {} offline", deviceId);
647 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800648 // but if I was the last STANDBY connection, etc. and no one else
649 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700650 // temporarily request for Master Role and mark offline.
651
samuele1fa7322015-07-14 16:35:16 +0800652 //there are times when this node will correctly have mastership, BUT
653 //that isn't reflected in the ClockManager before the device disconnects.
654 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700655
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700656 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800657 // Consider revising store API to handle this scenario.
658 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700659 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800660 MastershipTerm term = termService.getMastershipTerm(deviceId);
661 // TODO: Move this type of check inside device clock manager, etc.
662 if (term != null && localNodeId.equals(term.master())) {
663 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800664 post(store.markOffline(deviceId));
665 } else {
666 log.info("Failed again marking {} offline. {}", deviceId, role);
667 }
668 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700669 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700670 try {
samuele1fa7322015-07-14 16:35:16 +0800671 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700672 mastershipService.relinquishMastership(deviceId).get();
673 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800674 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700675 Thread.currentThread().interrupt();
676 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800677 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700678 }
tom0efbb1d2014-09-09 11:54:28 -0700679 }
tomd3097b02014-08-26 10:40:29 -0700680 }
681
682 @Override
alshabibb7b40632014-09-28 21:30:00 -0700683 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700684 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700685 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700686 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700687 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700688 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700689 // Never been a master for this device
690 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800691 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700692 return;
693 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200694 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
695 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200696 // Updating the ports if configuration exists (on new lists as
697 // the passed one might be immutable)
698 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200699 portDescriptions.addAll(portConfig.portDescriptions());
700 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700701 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700702 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700703 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700704 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800705 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800706 if (events != null) {
707 for (DeviceEvent event : events) {
708 post(event);
709 }
tom32f66842014-08-27 19:27:47 -0700710 }
tomd3097b02014-08-26 10:40:29 -0700711 }
712
713 @Override
alshabibb7b40632014-09-28 21:30:00 -0700714 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700715 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700716 checkNotNull(deviceId, DEVICE_ID_NULL);
717 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700718 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700719
Madan Jampani565a66a2015-07-25 17:01:13 -0700720 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700721 // Never been a master for this device
722 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700723 log.trace("Ignoring {} port update on standby node. {}", deviceId,
724 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700725 return;
726 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700727 Device device = getDevice(deviceId);
728 if (device == null) {
729 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530730 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700731 }
Andrea Campanella1c24fb92018-12-20 16:43:59 +0100732 if ((Type.ROADM.equals(device.type())) || (Type.OTN.equals(device.type())) ||
733 (Type.OLS.equals(device.type())) || (Type.TERMINAL_DEVICE.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700734 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700735 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700736 deviceId,
737 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700738 portDescription = ensurePortEnabledState(storedPortDesc,
739 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300740 }
741
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700742 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800743 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700744 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700745 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700746 if (event != null) {
Carmelo Casconeab5d41e2019-03-06 18:02:34 -0800747 log.info("Device {} port {} status changed (enabled={})",
748 deviceId, event.port().number(), portDescription.isEnabled());
tom0efbb1d2014-09-09 11:54:28 -0700749 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700750 }
tomd3097b02014-08-26 10:40:29 -0700751 }
tom3f2bbd72014-09-24 12:07:58 -0700752
753 @Override
Michal Machce774332017-01-25 11:02:55 +0100754 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
755
756 checkNotNull(deviceId, DEVICE_ID_NULL);
757 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
758 checkValidity();
759
760 if (!mastershipService.isLocalMaster(deviceId)) {
761 // Never been a master for this device
762 // any update will be ignored.
763 log.trace("Ignoring {} port update on standby node. {}", deviceId,
764 basePortDescription);
765 return;
766 }
767
768 Device device = getDevice(deviceId);
769 if (device == null) {
770 log.trace("Device not found: {}", deviceId);
771 }
772
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800773 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
774 .isRemoved(true)
775 .build();
776
Michal Machce774332017-01-25 11:02:55 +0100777 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
778 deviceId,
779 newPortDescription);
780 if (event != null) {
781 log.info("Device {} port {} status changed", deviceId, event.port().number());
782 post(event);
783 }
784 }
785
786 @Override
samuele1fa7322015-07-14 16:35:16 +0800787 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700788 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700789 // Several things can happen here:
790 // 1. request and response match
791 // 2. request and response don't match
792 // 3. MastershipRole and requested match (and 1 or 2 are true)
793 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
794 //
795 // 2, 4, and 3 with case 2 are failure modes.
796
tom3f2bbd72014-09-24 12:07:58 -0700797 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700798
Madan Jampanif2af7712015-05-29 18:43:52 -0700799 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700800 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700801
802 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800803 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530804 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700805 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700806 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700807 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700808
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800809 final MastershipRole expected = mastershipService.getLocalRole(deviceId);
810
811 if (requested == null) {
812 // Provider is not able to reconcile role responses with
813 // requests. We assume what was requested is what we expect.
814 // This will work only if mastership doesn't change too often,
815 // and devices are left enough time to provide responses before
816 // a different role is requested.
817 requested = expected;
818 }
819
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700820 if (Objects.equals(requested, response)) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800821 if (Objects.equals(requested, expected)) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700822 return;
823 } else {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800824 log.warn("Role mismatch on {}. Set to {}, but store demands {}",
825 deviceId, response, expected);
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800826 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700827 // the store; use the store's view, then try to reassert.
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800828 backgroundService.execute(() -> reassertRole(deviceId, expected));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800829 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700830 }
831 } else {
832 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200833 log.warn("Failed to assert role onto device {}. requested={}, response={}",
834 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200835 if (requested == MastershipRole.MASTER) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700836 mastershipService.relinquishMastership(deviceId);
837 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800838 //final Device device = getDevice(deviceId);
839 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700840 }
841 }
tom3f2bbd72014-09-24 12:07:58 -0700842 }
sangho538108b2015-04-08 14:29:20 -0700843
844 @Override
samuele1fa7322015-07-14 16:35:16 +0800845 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700846 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700847 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700848 checkValidity();
849
samuele1fa7322015-07-14 16:35:16 +0800850 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
851 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700852 post(event);
853 }
tomd3097b02014-08-26 10:40:29 -0700854 }
tom32f66842014-08-27 19:27:47 -0700855
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700856 // by default allowed, otherwise check flag
857 private boolean isAllowed(BasicDeviceConfig cfg) {
858 return (cfg == null || cfg.isAllowed());
859 }
860
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700861 private boolean canMarkOnline(Device device) {
Carmelo Cascone3977ea42019-02-28 13:43:42 -0800862 DeviceProvider provider = getProvider(device.id());
863 if (provider == null) {
864 log.warn("Provider for {} was not found. Cannot evaluate availability", device.id());
865 return false;
866 }
867 return provider.isAvailable(device.id());
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700868 }
869
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800870 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700871
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800872 /**
873 * Apply role to device and send probe if MASTER.
874 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700875 * @param deviceId device identifier
876 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800877 * @return true if the request was sent to provider
878 */
879 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
880 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800881 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700882 return true;
883 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700884
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800885 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800886 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800887 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800888 return false;
889 }
890 provider.roleChanged(deviceId, newRole);
891
892 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800893 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800894 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800895 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800896 }
897 return true;
898 }
899
900 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800901 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800902 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700903 * @param did device identifier
904 * @param nextRole role to apply. If NONE is specified,
905 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800906 */
samuele1fa7322015-07-14 16:35:16 +0800907 private void reassertRole(final DeviceId did,
908 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800909
Jordan Halterman9416aea2017-11-17 12:40:21 -0800910 MastershipRole myNextRole = nextRole;
911 if (myNextRole == NONE && upgradeService.isLocalActive()) {
912 try {
913 mastershipService.requestRoleFor(did).get();
914 MastershipTerm term = termService.getMastershipTerm(did);
915 if (term != null && localNodeId.equals(term.master())) {
916 myNextRole = MASTER;
917 } else {
918 myNextRole = STANDBY;
919 }
920 } catch (InterruptedException e) {
921 Thread.currentThread().interrupt();
922 log.error("Interrupted waiting for Mastership", e);
923 } catch (ExecutionException e) {
924 log.error("Encountered an error waiting for Mastership", e);
925 }
926 }
927
928 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700929 case MASTER:
930 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700931 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +0900932 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700933 }
934 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800935 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700936 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800937 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700938 // immediately failed to apply role
939 mastershipService.relinquishMastership(did);
940 // FIXME disconnect?
941 }
942 break;
943 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -0800944 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700945 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800946 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700947 // immediately failed to apply role
948 mastershipService.relinquishMastership(did);
949 // FIXME disconnect?
950 }
951 break;
952 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700953 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700954 default:
955 // should never reach here
956 log.error("You didn't see anything. I did not exist.");
957 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800958 }
959 }
960
Madan Jampani328371d2015-05-29 14:06:27 -0700961 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700962 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700963 // Don't care if backup list changed.
964 return;
965 }
Madan Jampani328371d2015-05-29 14:06:27 -0700966 final DeviceId did = event.subject();
967
968 // myRole suggested by MastershipService
969 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700970 if (event.type() == MastershipEvent.Type.SUSPENDED) {
971 myNextRole = NONE; // FIXME STANDBY OR NONE?
972 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700973 // confirm latest info
974 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800975 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700976 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700977 myNextRole = MASTER;
978 } else {
979 myNextRole = STANDBY;
980 }
981 } else if (event.roleInfo().backups().contains(localNodeId)) {
982 myNextRole = STANDBY;
983 } else {
984 myNextRole = NONE;
985 }
986
Madan Jampani328371d2015-05-29 14:06:27 -0700987 final boolean isReachable = isReachable(did);
988 if (!isReachable) {
989 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800990 if (mastershipService.getLocalRole(did) == NONE) {
991 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700992 + "but this node cannot reach the device "
993 + "and role is already None. Ignoring request.",
994 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800995 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700996 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700997 + "but this node cannot reach the device. "
998 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800999 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -07001000 mastershipService.relinquishMastership(did);
1001 }
1002 return;
1003 }
1004
1005 // device is connected to this node:
1006 if (store.getDevice(did) != null) {
1007 reassertRole(did, myNextRole);
1008 } else {
1009 log.debug("Device is not yet/no longer in the store: {}", did);
1010 }
1011 }
1012
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -08001013 // Intercepts mastership events
1014 private class InternalMastershipListener implements MastershipListener {
1015
tomb41d1ac2014-09-24 01:51:24 -07001016 @Override
1017 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -08001018 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -07001019 try {
1020 handleMastershipEvent(event);
1021 } catch (Exception e) {
1022 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -07001023 }
Madan Jampani328371d2015-05-29 14:06:27 -07001024 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -07001025 }
tomb41d1ac2014-09-24 01:51:24 -07001026 }
tomf80c9722014-09-24 14:49:18 -07001027
1028 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -07001029 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -07001030 @Override
1031 public void notify(DeviceEvent event) {
1032 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001033 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -07001034 // When device is administratively removed, force disconnect.
1035 DeviceId deviceId = event.subject().id();
1036 deviceLocalStatus.remove(deviceId);
1037
1038 DeviceProvider provider = getProvider(deviceId);
1039 if (provider != null) {
1040 log.info("Triggering disconnect for device {}", deviceId);
1041 try {
1042 provider.triggerDisconnect(deviceId);
1043 } catch (UnsupportedOperationException e) {
1044 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1045 }
1046 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001047 }
tomf80c9722014-09-24 14:49:18 -07001048 }
1049 }
samuel738dfaf2015-07-11 11:08:57 +08001050
1051 @Override
1052 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001053 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001054 Set<Device> results = new HashSet<>();
1055 Iterable<Device> devices = store.getDevices();
1056 if (devices != null) {
1057 devices.forEach(d -> {
1058 if (type.equals(d.type())) {
1059 results.add(d);
1060 }
1061 });
1062 }
1063 return results;
1064 }
1065
1066 @Override
1067 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001068 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001069 Set<Device> results = new HashSet<>();
1070 Iterable<Device> availableDevices = store.getAvailableDevices();
1071 if (availableDevices != null) {
1072 availableDevices.forEach(d -> {
1073 if (type.equals(d.type())) {
1074 results.add(d);
1075 }
1076 });
1077 }
1078 return results;
1079 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001080
1081 private class InternalNetworkConfigListener implements NetworkConfigListener {
Ray Milkey69ca82a2019-03-28 09:24:40 -07001082 private DeviceId extractDeviceId(NetworkConfigEvent event) {
1083 DeviceId deviceId = null;
debmaiti9553ed72019-03-18 14:27:42 +05301084 if (event.configClass().equals(PortAnnotationConfig.class)) {
Ray Milkey397caca2019-04-01 16:27:50 -07001085 if (event.subject().getClass() == ConnectPoint.class) {
1086 deviceId = ((ConnectPoint) event.subject()).deviceId();
1087 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001088 } else if (event.subject().getClass() == DeviceId.class) {
debmaiti9553ed72019-03-18 14:27:42 +05301089 deviceId = (DeviceId) event.subject();
1090 }
Ray Milkey69ca82a2019-03-28 09:24:40 -07001091 return deviceId;
1092 }
1093
1094 @Override
1095 public boolean isRelevant(NetworkConfigEvent event) {
1096 DeviceId deviceId = extractDeviceId(event);
1097
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001098 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
debmaiti9553ed72019-03-18 14:27:42 +05301099 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED
1100 || event.type() == NetworkConfigEvent.Type.CONFIG_REMOVED)
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001101 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001102 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001103 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001104 || event.configClass().equals(DeviceAnnotationConfig.class))
Ray Milkey69ca82a2019-03-28 09:24:40 -07001105 && deviceId != null && mastershipService.isLocalMaster(deviceId);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001106 }
1107
1108 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001109 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001110 DeviceEvent de = null;
1111 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001112 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001113 DeviceId did = (DeviceId) event.subject();
1114 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001115 BasicDeviceConfig cfg =
1116 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001117
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001118 if (!isAllowed(cfg)) {
1119 kickOutBadDevice(did);
1120 } else {
1121 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001122 DeviceDescription desc =
1123 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001124 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001125 if (desc != null && dp != null) {
1126 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001127 }
1128 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001129 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1130 DeviceId did = (DeviceId) event.subject();
1131 DeviceProvider dp = getProvider(did);
1132 if (!event.config().isPresent() ||
1133 getDevice(did) == null || dp == null) {
1134 // sanity check failed, ignore
1135 return;
1136 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001137 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001138 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001139 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1140 .collect(Collectors.toList());
1141 complete.addAll(portConfig.portDescriptions());
1142 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001143 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1144 DeviceId did = (DeviceId) event.subject();
1145 DeviceProvider dp = getProvider(did);
1146 Device dev = getDevice(did);
1147 DeviceDescription desc =
1148 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1149 Optional<Config> prevConfig = event.prevConfig();
1150 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1151 if (desc != null && dp != null) {
1152 de = store.createOrUpdateDevice(dp.id(), did, desc);
1153 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001154 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001155 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001156 DeviceId did = cpt.deviceId();
1157 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001158
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001159 // Note: assuming PortOperator can modify existing port,
1160 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001161 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001162 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
debmaiti9553ed72019-03-18 14:27:42 +05301163 .map(desc -> applyAllPortOps(cpt, desc, event.prevConfig()))
Simon Huntffbad3b2017-05-16 15:37:51 -07001164 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001165 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001166 }
1167
1168 if (de != null) {
1169 post(de);
1170 }
1171 }
1172
Simon Hunt8f60ff82017-04-24 17:19:30 -07001173 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001174 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001175 Device badDevice = getDevice(deviceId);
1176 if (badDevice != null) {
1177 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001178 }
1179 }
1180 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001181
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001182 @Override
1183 @SafeVarargs
1184 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001185 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001186 checkNotNull(portOp);
1187
1188 portOp.bindService(networkConfigService);
1189
1190 // update both portOpsIndex and portOps
1191 synchronized (portOpsIndex) {
1192 for (Class<? extends Config<ConnectPoint>> config : configs) {
1193 portOpsIndex.put(config, portOp);
1194 }
1195
1196 portOps.add(portOp);
1197 }
1198
1199 // TODO: Should we be applying to all existing Ports?
1200 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001201 .map(Device::id)
1202 .filter(mastershipService::isLocalMaster)
1203 // for each locally managed Device, update all port descriptions
1204 .map(did -> {
1205 ProviderId pid = Optional.ofNullable(getProvider(did))
1206 .map(Provider::id)
1207 .orElse(null);
1208 if (pid == null) {
1209 log.warn("Provider not found for {}", did);
1210 return ImmutableList.<DeviceEvent>of();
1211 }
1212 List<PortDescription> pds
1213 = store.getPortDescriptions(pid, did)
1214 .map(pdesc -> applyAllPortOps(did, pdesc))
1215 .collect(Collectors.toList());
1216 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001217 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001218 // ..and port port update event if necessary
1219 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001220 }
1221
1222 @Override
1223 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1224 checkNotNull(portOp);
1225
1226
1227 // remove all portOp
1228 synchronized (portOpsIndex) {
1229 portOps.remove(portOp);
1230
1231 // had to do this since COWArrayList iterator doesn't support remove
1232 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1233 }
1234
1235 }
1236
1237 /**
1238 * Merges the appropriate PortConfig with the description.
1239 *
1240 * @param did ID of the Device where the port is attached
1241 * @param desc {@link PortDescription}
1242 * @return merged {@link PortDescription}
1243 */
1244 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1245 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1246 }
1247
1248 /**
1249 * Merges the appropriate PortConfig with the description.
1250 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001251 * @param cpt ConnectPoint where the port is attached
1252 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001253 * @return merged {@link PortDescription}
1254 */
1255 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1256 PortDescription work = desc;
1257 for (PortConfigOperator portOp : portOps) {
1258 work = portOp.combine(cpt, work);
1259 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001260 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001261 }
1262
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001263 /**
debmaiti9553ed72019-03-18 14:27:42 +05301264 * Merges the appropriate PortConfig with the description.
1265 *
1266 * @param cpt ConnectPoint where the port is attached
1267 * @param desc {@link PortDescription}
1268 * @param prevConfig previous configuration
1269 * @return merged {@link PortDescription}
1270 */
1271 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc,
1272 Optional<Config> prevConfig) {
1273 PortDescription work = desc;
1274 for (PortConfigOperator portOp : portOps) {
1275 work = portOp.combine(cpt, work, prevConfig);
1276 }
1277 return portAnnotationOp.combine(cpt, work, prevConfig);
1278 }
1279
1280 /**
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001281 * Port Enable/Disable message sent to the device's MASTER node.
1282 */
1283 private class InternalPortUpDownEvent {
1284 private final DeviceId deviceId;
1285 private final PortNumber portNumber;
1286 private final boolean enable;
1287
1288 protected InternalPortUpDownEvent(
1289 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1290 this.deviceId = deviceId;
1291 this.portNumber = portNumber;
1292 this.enable = enable;
1293 }
1294
1295 public DeviceId deviceId() {
1296 return deviceId;
1297 }
1298 public PortNumber portNumber() {
1299 return portNumber;
1300 }
1301 public boolean isEnable() {
1302 return enable;
1303 }
1304
1305 protected InternalPortUpDownEvent() {
1306 this.deviceId = null;
1307 this.portNumber = null;
1308 this.enable = false;
1309 }
1310 }
tomd3097b02014-08-26 10:40:29 -07001311}