blob: 2128435dacf133f38e683adfdc244022a0bb9f1b [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;
Andrea Campanella75ef9f52017-07-27 20:14:32 +020026import org.onosproject.incubator.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080027import org.onosproject.mastership.MastershipEvent;
28import org.onosproject.mastership.MastershipListener;
29import org.onosproject.mastership.MastershipService;
30import org.onosproject.mastership.MastershipTerm;
31import org.onosproject.mastership.MastershipTermService;
Carmelo Cascone0761cd32018-08-29 19:22:50 -070032import org.onosproject.net.AnnotationKeys;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070033import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080035import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080036import org.onosproject.net.DeviceId;
37import org.onosproject.net.MastershipRole;
38import org.onosproject.net.Port;
39import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070040import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030041import org.onosproject.net.config.NetworkConfigEvent;
42import org.onosproject.net.config.NetworkConfigListener;
43import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070044import org.onosproject.net.config.PortConfigOperator;
45import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030046import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090047import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080048import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080049import org.onosproject.net.device.DefaultPortDescription;
50import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080051import org.onosproject.net.device.DeviceDescription;
52import org.onosproject.net.device.DeviceEvent;
53import org.onosproject.net.device.DeviceListener;
54import org.onosproject.net.device.DeviceProvider;
55import org.onosproject.net.device.DeviceProviderRegistry;
56import org.onosproject.net.device.DeviceProviderService;
57import org.onosproject.net.device.DeviceService;
58import org.onosproject.net.device.DeviceStore;
59import org.onosproject.net.device.DeviceStoreDelegate;
60import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070061import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030062import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080063import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080064import org.onosproject.net.provider.Provider;
65import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070066import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
67import org.onosproject.store.cluster.messaging.MessageSubject;
68import org.onosproject.store.serializers.KryoNamespaces;
69import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080070import org.onosproject.upgrade.UpgradeService;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070071import org.osgi.service.component.annotations.Activate;
72import org.osgi.service.component.annotations.Component;
73import org.osgi.service.component.annotations.Deactivate;
74import org.osgi.service.component.annotations.Reference;
75import org.osgi.service.component.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070076import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070077
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070078import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070079import java.util.Collection;
80import java.util.HashSet;
81import java.util.List;
82import java.util.Map;
83import java.util.Objects;
84import java.util.Optional;
85import java.util.Set;
86import java.util.concurrent.CompletableFuture;
87import java.util.concurrent.ConcurrentHashMap;
88import java.util.concurrent.CopyOnWriteArrayList;
89import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070090import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070091import java.util.concurrent.ScheduledExecutorService;
92import java.util.concurrent.TimeUnit;
93import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080094
Ray Milkey9ef22232016-07-14 12:42:37 -070095import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070096import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070097import static com.google.common.collect.Multimaps.newListMultimap;
98import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070099import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -0700100import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
101import static org.onlab.util.Tools.groupedThreads;
102import static org.onosproject.net.MastershipRole.MASTER;
103import static org.onosproject.net.MastershipRole.NONE;
104import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700105import static org.onosproject.security.AppGuard.checkPermission;
106import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
107import static org.slf4j.LoggerFactory.getLogger;
108
tomd3097b02014-08-26 10:40:29 -0700109/**
tome4729872014-09-23 00:37:37 -0700110 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700111 */
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700112@Component(immediate = true, service = {DeviceService.class, DeviceAdminService.class, DeviceProviderRegistry.class, PortConfigOperatorRegistry.class })
tom41a2c5f2014-09-19 09:20:35 -0700113public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700114 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700115 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700116
tome5ec3fd2014-09-04 15:18:06 -0700117 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
118 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
119 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
120 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700121 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700122 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700123
tom5f38b3a2014-08-27 23:50:54 -0700124 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700125
alshabib339a3d92014-09-26 17:54:32 -0700126 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700127
tomc78acee2014-09-24 15:16:55 -0700128 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700129 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700130
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800131 private ScheduledExecutorService backgroundService;
132
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700133 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
134
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700135 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tom41a2c5f2014-09-19 09:20:35 -0700136 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700137
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700138 @Reference(cardinality = ReferenceCardinality.MANDATORY)
tomb41d1ac2014-09-24 01:51:24 -0700139 protected ClusterService clusterService;
140
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700141 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700142 protected MastershipService mastershipService;
143
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700144 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700145 protected MastershipTermService termService;
146
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700147 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800148 protected UpgradeService upgradeService;
149
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700150 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700151 protected NetworkConfigService networkConfigService;
152
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700153 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700154 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700155
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700156 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700157 /**
158 * List of all registered PortConfigOperator.
159 */
160 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
161
162 /**
163 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
164 */
165 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700166 = synchronizedListMultimap(
167 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700168
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800169 // not part of portOps. must be executed at the end
170 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900171 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800172
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700173 private static final MessageSubject PORT_UPDOWN_SUBJECT =
174 new MessageSubject("port-updown-req");
175
176 private static final Serializer SERIALIZER = Serializer.using(
177 KryoNamespace.newBuilder()
178 .register(KryoNamespaces.API)
179 .register(InternalPortUpDownEvent.class)
180 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
181 .build("DeviceManager"));
182
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800183 /**
184 * Local storage for connectivity status of devices.
185 */
186 private class LocalStatus {
187 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700188 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800189
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700190 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800191 connected = b;
192 dateTime = now;
193 }
194 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700195
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800196 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
197 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700198
tomd3097b02014-08-26 10:40:29 -0700199 @Activate
200 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800201 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900202 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800203 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
204
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800205 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700206 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700207 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800208
tomf80c9722014-09-24 14:49:18 -0700209 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700210 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700211 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700212 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800213
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700214 backgroundService.scheduleWithFixedDelay(() -> {
215 try {
216 mastershipCheck();
217 } catch (Exception e) {
218 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800219 }
220 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700221
222 portReqeustExecutor = newSingleThreadExecutor();
223
224 communicationService.<InternalPortUpDownEvent>addSubscriber(
225 PORT_UPDOWN_SUBJECT,
226 SERIALIZER::decode,
227 this::handlePortRequest,
228 portReqeustExecutor);
229
tomd3097b02014-08-26 10:40:29 -0700230 log.info("Started");
231 }
232
233 @Deactivate
234 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800235 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700236 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700237 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700238 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700239 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700240 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
241 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700242 log.info("Stopped");
243 }
244
245 @Override
tomad2d2092014-09-06 23:24:20 -0700246 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900247 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700248 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700249 }
250
251 @Override
mskala32000d32017-07-14 16:27:06 +0200252 public int getAvailableDeviceCount() {
253 checkPermission(DEVICE_READ);
254 return store.getAvailableDeviceCount();
255 }
256
257 @Override
tom32f66842014-08-27 19:27:47 -0700258 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900259 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700260 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700261 }
262
tom32f66842014-08-27 19:27:47 -0700263 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800264 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900265 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800266 return store.getAvailableDevices();
267 }
268
269 @Override
tom32f66842014-08-27 19:27:47 -0700270 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900271 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700272 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700273 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700274 }
275
276 @Override
tomad2d2092014-09-06 23:24:20 -0700277 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900278 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700279 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700280 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700281 }
282
283 @Override
tom32f66842014-08-27 19:27:47 -0700284 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900285 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700286 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700287 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700288 }
289
290 @Override
sangho538108b2015-04-08 14:29:20 -0700291 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900292 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700293 checkNotNull(deviceId, DEVICE_ID_NULL);
294 return store.getPortStatistics(deviceId);
295 }
296
297 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200298 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900299 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200300 checkNotNull(deviceId, DEVICE_ID_NULL);
301 return store.getPortDeltaStatistics(deviceId);
302 }
303
304 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530305 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
306 checkPermission(DEVICE_READ);
307 checkNotNull(deviceId, DEVICE_ID_NULL);
308 checkNotNull(portNumber, PORT_NUMBER_NULL);
309 return store.getStatisticsForPort(deviceId, portNumber);
310 }
311
312 @Override
313 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
314 checkPermission(DEVICE_READ);
315 checkNotNull(deviceId, DEVICE_ID_NULL);
316 checkNotNull(portNumber, PORT_NUMBER_NULL);
317 return store.getDeltaStatisticsForPort(deviceId, portNumber);
318 }
319
320 @Override
tom32f66842014-08-27 19:27:47 -0700321 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900322 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700323 checkNotNull(deviceId, DEVICE_ID_NULL);
324 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700325 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700326 }
327
328 @Override
tomff7eb7c2014-09-08 12:49:03 -0700329 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900330 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900331
tomff7eb7c2014-09-08 12:49:03 -0700332 checkNotNull(deviceId, DEVICE_ID_NULL);
333 return store.isAvailable(deviceId);
334 }
335
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800336 @Override
337 public String localStatus(DeviceId deviceId) {
338 LocalStatus ls = deviceLocalStatus.get(deviceId);
339 if (ls == null) {
340 return "No Record";
341 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700342 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800343 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
344 }
345
Palash Kala0d817b02018-03-23 18:09:45 +0900346 private boolean isLocallyConnected(DeviceId deviceId) {
347 LocalStatus ls = deviceLocalStatus.get(deviceId);
348 if (ls == null) {
349 return false;
350 }
351 return ls.connected;
352 }
353
Ray Milkey054e23d2018-03-22 13:37:11 -0700354 @Override
355 public long getLastUpdatedInstant(DeviceId deviceId) {
356 LocalStatus ls = deviceLocalStatus.get(deviceId);
357 if (ls == null) {
358 return 0;
359 }
360 return ls.dateTime.toEpochMilli();
361 }
362
Palash Kala0d817b02018-03-23 18:09:45 +0900363 // Check a device for control channel connectivity
364 // and changes local-status appropriately.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700365 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800366 if (deviceId == null) {
367 return false;
368 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700369 DeviceProvider provider = getProvider(deviceId);
370 if (provider != null) {
Palash Kala0d817b02018-03-23 18:09:45 +0900371 boolean reachable = provider.isReachable(deviceId);
372 if (reachable && !isLocallyConnected(deviceId)) {
373 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
374 } else if (!reachable && isLocallyConnected(deviceId)) {
375 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
376 }
377 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700378 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800379 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700380 return false;
381 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700382 }
383
tome5ec3fd2014-09-04 15:18:06 -0700384 @Override
385 public void removeDevice(DeviceId deviceId) {
386 checkNotNull(deviceId, DEVICE_ID_NULL);
387 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700388 if (event != null) {
389 log.info("Device {} administratively removed", deviceId);
390 post(event);
391 }
tome5ec3fd2014-09-04 15:18:06 -0700392 }
393
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700394 private void handlePortRequest(InternalPortUpDownEvent event) {
395 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700396 checkNotNull(deviceId, DEVICE_ID_NULL);
397 checkNotNull(deviceId, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700398 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
399 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
400 }
401
402 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
403 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700404 DeviceProvider provider = getProvider(deviceId);
405 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700406 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700407 portNumber, deviceId,
408 (enable) ? "UP" : "DOWN");
409 provider.changePortState(deviceId, portNumber, enable);
410 } else {
411 log.warn("Provider not found for {}", deviceId);
412 }
413 }
414
415 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700416 public void changePortState(DeviceId deviceId, PortNumber portNumber,
417 boolean enable) {
418 checkNotNull(deviceId, DEVICE_ID_NULL);
419 checkNotNull(deviceId, PORT_NUMBER_NULL);
420 NodeId masterId = mastershipService.getMasterFor(deviceId);
421
Ray Milkey4ef245e2018-05-10 15:41:16 -0700422 if (masterId == null) {
423 // No master found; device is offline
424 log.info("No master found for port state change for {}", deviceId);
425 return;
426 }
427
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700428 if (!masterId.equals(localNodeId)) {
429 //Send the request to the master node for the device
430 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
431 deviceId, masterId);
432 communicationService.unicast(
433 new InternalPortUpDownEvent(deviceId, portNumber, enable),
434 PORT_UPDOWN_SUBJECT,
435 SERIALIZER::encode,
436 masterId).whenComplete((r, error) -> {
437 if (error != null) {
438 log.warn("Failed to send packet-updown-req to {}", masterId, error);
439 }
440 });
441 } else {
442 changePortStateAtMaster(deviceId, portNumber, enable);
443 }
444 }
445
446 @Override
samuele1fa7322015-07-14 16:35:16 +0800447 protected DeviceProviderService createProviderService(
448 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700449 return new InternalDeviceProviderService(provider);
450 }
451
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800452 /**
453 * Checks if all the reachable devices have a valid mastership role.
454 */
455 private void mastershipCheck() {
456 log.debug("Checking mastership");
457 for (Device device : getDevices()) {
458 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700459 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
460 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800461 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700462 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700463 // can't be master if device is not reachable
464 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700465 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100466 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700467 post(store.markOffline(deviceId));
468 }
helenyrwufd296b62016-06-22 17:43:02 -0700469 //relinquish master role and ability to be backup.
470 mastershipService.relinquishMastership(deviceId).get();
471 } catch (InterruptedException e) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700472 log.warn("Interrupted while relinquishing role for {}", deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700473 Thread.currentThread().interrupt();
474 } catch (ExecutionException e) {
475 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
476 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530477 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100478 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530479 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100480 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800481 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100482 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800483 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
484 roleFuture.thenAccept(role -> {
485 MastershipTerm term = termService.getMastershipTerm(deviceId);
486 if (term != null && localNodeId.equals(term.master())) {
487 log.info("Marking unreachable device {} offline", deviceId);
488 post(store.markOffline(deviceId));
489 } else {
490 log.info("Failed marking {} offline. {}", deviceId, role);
491 }
492 mastershipService.relinquishMastership(deviceId);
493 });
494 }
helenyrwufd296b62016-06-22 17:43:02 -0700495 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800496 continue;
497 }
498
Ray Milkeyc7104672016-08-31 12:04:34 -0700499 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800500 continue;
501 }
502
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700503 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800504
505 // isReachable but was not MASTER or STANDBY, get a role and apply
506 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800507 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800508 }
509 }
510
tomd3097b02014-08-26 10:40:29 -0700511 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700512 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700513 extends AbstractProviderService<DeviceProvider>
514 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700515
tomcfde0622014-09-09 11:02:42 -0700516 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700517 super(provider);
518 }
519
Ray Milkey33306ba2018-09-20 13:27:25 -0700520 /**
521 * Apply role in reaction to provider event.
522 *
523 * @param deviceId device identifier
524 * @param newRole new role to apply to the device
525 * @return true if the request was sent to provider
526 */
527 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
528
529 if (newRole.equals(MastershipRole.NONE)) {
530 //no-op
531 return true;
532 }
533
534 DeviceProvider provider = provider();
535 if (provider == null) {
536 log.warn("Provider for {} was not found. Cannot apply role {}",
537 deviceId, newRole);
538 return false;
539 }
540 provider.roleChanged(deviceId, newRole);
541 // not triggering probe when triggered by provider service event
542 return true;
543 }
544
tomd3097b02014-08-26 10:40:29 -0700545 @Override
alshabibb7b40632014-09-28 21:30:00 -0700546 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700547 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700548 checkNotNull(deviceId, DEVICE_ID_NULL);
549 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700550 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700551
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700552 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800553
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700554 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
555 if (!isAllowed(cfg)) {
556 log.warn("Device {} is not allowed", deviceId);
557 return;
558 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200559 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700560 // Generate updated description and establish my Role
561 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900562 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
563 if (annoConfig != null) {
564 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
565 }
566
jaegonkim8eabcec2018-07-27 23:40:43 +0900567 MastershipRole role = mastershipService.requestRoleForSync(deviceId);
568 log.info("Local role is {} for {}", role, deviceId);
Yi Tseng7be4e672017-12-05 15:03:26 -0800569 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
jaegonkim8eabcec2018-07-27 23:40:43 +0900570 deviceDescription);
Ray Milkey33306ba2018-09-20 13:27:25 -0700571 applyRole(deviceId, role);
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700572
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200573 if (portConfig != null) {
574 //updating the ports if configration exists
575 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
576 .collect(Collectors.toList());
577 complete.addAll(portConfig.portDescriptions());
578 List<PortDescription> portDescriptions = complete.stream()
579 .map(e -> applyAllPortOps(deviceId, e))
580 .collect(Collectors.toList());
581 store.updatePorts(provider().id(), deviceId, portDescriptions);
582 }
583
helenyrwufd296b62016-06-22 17:43:02 -0700584 if (deviceDescription.isDefaultAvailable()) {
585 log.info("Device {} connected", deviceId);
586 } else {
587 log.info("Device {} registered", deviceId);
588 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200589
tom80c0e5e2014-09-08 18:08:58 -0700590 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700591 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700592 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700593 }
tomd3097b02014-08-26 10:40:29 -0700594 }
595
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700596 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
597 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800598 return DefaultPortDescription.builder(desc)
599 .isEnabled(enabled)
600 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700601 }
602 return desc;
603 }
604
tomd3097b02014-08-26 10:40:29 -0700605 @Override
606 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700607 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700608 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700609 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700610 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700611
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700612 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
613 .map(desc -> ensurePortEnabledState(desc, false))
614 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300615
alshabibafc514a2014-12-01 14:44:05 -0800616 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700617 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700618 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700619 post(store.markOffline(deviceId));
620 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700621 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700622 log.warn("Failed to mark {} offline", deviceId);
623 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800624 // but if I was the last STANDBY connection, etc. and no one else
625 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700626 // temporarily request for Master Role and mark offline.
627
samuele1fa7322015-07-14 16:35:16 +0800628 //there are times when this node will correctly have mastership, BUT
629 //that isn't reflected in the ClockManager before the device disconnects.
630 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700631
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700632 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800633 // Consider revising store API to handle this scenario.
634 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700635 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800636 MastershipTerm term = termService.getMastershipTerm(deviceId);
637 // TODO: Move this type of check inside device clock manager, etc.
638 if (term != null && localNodeId.equals(term.master())) {
639 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800640 post(store.markOffline(deviceId));
641 } else {
642 log.info("Failed again marking {} offline. {}", deviceId, role);
643 }
644 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700645 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700646 try {
samuele1fa7322015-07-14 16:35:16 +0800647 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700648 mastershipService.relinquishMastership(deviceId).get();
649 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800650 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700651 Thread.currentThread().interrupt();
652 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800653 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700654 }
tom0efbb1d2014-09-09 11:54:28 -0700655 }
tomd3097b02014-08-26 10:40:29 -0700656 }
657
658 @Override
alshabibb7b40632014-09-28 21:30:00 -0700659 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700660 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700661 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700662 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700663 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700664 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700665 // Never been a master for this device
666 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800667 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700668 return;
669 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200670 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
671 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200672 // Updating the ports if configuration exists (on new lists as
673 // the passed one might be immutable)
674 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200675 portDescriptions.addAll(portConfig.portDescriptions());
676 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700677 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700678 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700679 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700680 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800681 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800682 if (events != null) {
683 for (DeviceEvent event : events) {
684 post(event);
685 }
tom32f66842014-08-27 19:27:47 -0700686 }
tomd3097b02014-08-26 10:40:29 -0700687 }
688
689 @Override
alshabibb7b40632014-09-28 21:30:00 -0700690 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700691 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700692 checkNotNull(deviceId, DEVICE_ID_NULL);
693 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700694 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700695
Madan Jampani565a66a2015-07-25 17:01:13 -0700696 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700697 // Never been a master for this device
698 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700699 log.trace("Ignoring {} port update on standby node. {}", deviceId,
700 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700701 return;
702 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700703 Device device = getDevice(deviceId);
704 if (device == null) {
705 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530706 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700707 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200708 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700709 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700710 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700711 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700712 deviceId,
713 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700714 portDescription = ensurePortEnabledState(storedPortDesc,
715 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300716 }
717
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700718 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800719 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700720 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700721 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700722 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700723 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700724 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700725 }
tomd3097b02014-08-26 10:40:29 -0700726 }
tom3f2bbd72014-09-24 12:07:58 -0700727
728 @Override
Michal Machce774332017-01-25 11:02:55 +0100729 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
730
731 checkNotNull(deviceId, DEVICE_ID_NULL);
732 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
733 checkValidity();
734
735 if (!mastershipService.isLocalMaster(deviceId)) {
736 // Never been a master for this device
737 // any update will be ignored.
738 log.trace("Ignoring {} port update on standby node. {}", deviceId,
739 basePortDescription);
740 return;
741 }
742
743 Device device = getDevice(deviceId);
744 if (device == null) {
745 log.trace("Device not found: {}", deviceId);
746 }
747
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800748 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
749 .isRemoved(true)
750 .build();
751
Michal Machce774332017-01-25 11:02:55 +0100752 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
753 deviceId,
754 newPortDescription);
755 if (event != null) {
756 log.info("Device {} port {} status changed", deviceId, event.port().number());
757 post(event);
758 }
759 }
760
761 @Override
samuele1fa7322015-07-14 16:35:16 +0800762 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700763 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700764 // Several things can happen here:
765 // 1. request and response match
766 // 2. request and response don't match
767 // 3. MastershipRole and requested match (and 1 or 2 are true)
768 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
769 //
770 // 2, 4, and 3 with case 2 are failure modes.
771
tom3f2bbd72014-09-24 12:07:58 -0700772 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700773
Madan Jampanif2af7712015-05-29 18:43:52 -0700774 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700775 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700776
777 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800778 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530779 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700780 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700781 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700782 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700783
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700784 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800785 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700786 return;
787 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800788 log.warn("Role mismatch on {}. set to {}, but store demands {}",
789 deviceId, response, mastershipService.getLocalRole(deviceId));
790 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700791 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800792 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800793 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700794 }
795 } else {
796 // we didn't get back what we asked for. Reelect someone else.
Carmelo Casconee5b28722018-06-22 17:28:28 +0200797 log.warn("Failed to assert role onto device {}. requested={}, response={}",
798 deviceId, requested, response);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200799 if (requested == MastershipRole.MASTER) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700800 mastershipService.relinquishMastership(deviceId);
801 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800802 //final Device device = getDevice(deviceId);
803 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700804 }
805 }
tom3f2bbd72014-09-24 12:07:58 -0700806 }
sangho538108b2015-04-08 14:29:20 -0700807
808 @Override
samuele1fa7322015-07-14 16:35:16 +0800809 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700810 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700811 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700812 checkValidity();
813
samuele1fa7322015-07-14 16:35:16 +0800814 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
815 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700816 post(event);
817 }
tomd3097b02014-08-26 10:40:29 -0700818 }
tom32f66842014-08-27 19:27:47 -0700819
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700820 // by default allowed, otherwise check flag
821 private boolean isAllowed(BasicDeviceConfig cfg) {
822 return (cfg == null || cfg.isAllowed());
823 }
824
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700825 private boolean canMarkOnline(Device device) {
826 final boolean providerMarkOnline = Boolean.parseBoolean(
827 device.annotations().value(AnnotationKeys.PROVIDER_MARK_ONLINE));
828 return !providerMarkOnline;
829 }
830
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800831 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700832
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800833 /**
834 * Apply role to device and send probe if MASTER.
835 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700836 * @param deviceId device identifier
837 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800838 * @return true if the request was sent to provider
839 */
840 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
841 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800842 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700843 return true;
844 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700845
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800846 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800847 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800848 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800849 return false;
850 }
851 provider.roleChanged(deviceId, newRole);
852
853 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800854 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800855 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800856 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800857 }
858 return true;
859 }
860
861 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800862 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800863 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700864 * @param did device identifier
865 * @param nextRole role to apply. If NONE is specified,
866 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800867 */
samuele1fa7322015-07-14 16:35:16 +0800868 private void reassertRole(final DeviceId did,
869 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800870
Jordan Halterman9416aea2017-11-17 12:40:21 -0800871 MastershipRole myNextRole = nextRole;
872 if (myNextRole == NONE && upgradeService.isLocalActive()) {
873 try {
874 mastershipService.requestRoleFor(did).get();
875 MastershipTerm term = termService.getMastershipTerm(did);
876 if (term != null && localNodeId.equals(term.master())) {
877 myNextRole = MASTER;
878 } else {
879 myNextRole = STANDBY;
880 }
881 } catch (InterruptedException e) {
882 Thread.currentThread().interrupt();
883 log.error("Interrupted waiting for Mastership", e);
884 } catch (ExecutionException e) {
885 log.error("Encountered an error waiting for Mastership", e);
886 }
887 }
888
889 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700890 case MASTER:
891 final Device device = getDevice(did);
Carmelo Cascone0761cd32018-08-29 19:22:50 -0700892 if (device != null && !isAvailable(did) && canMarkOnline(device)) {
Palash Kala6c526062018-04-03 18:25:11 +0900893 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700894 }
895 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800896 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700897 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800898 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700899 // immediately failed to apply role
900 mastershipService.relinquishMastership(did);
901 // FIXME disconnect?
902 }
903 break;
904 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -0800905 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700906 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800907 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700908 // immediately failed to apply role
909 mastershipService.relinquishMastership(did);
910 // FIXME disconnect?
911 }
912 break;
913 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700914 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700915 default:
916 // should never reach here
917 log.error("You didn't see anything. I did not exist.");
918 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800919 }
920 }
921
Madan Jampani328371d2015-05-29 14:06:27 -0700922 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700923 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700924 // Don't care if backup list changed.
925 return;
926 }
Madan Jampani328371d2015-05-29 14:06:27 -0700927 final DeviceId did = event.subject();
928
929 // myRole suggested by MastershipService
930 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700931 if (event.type() == MastershipEvent.Type.SUSPENDED) {
932 myNextRole = NONE; // FIXME STANDBY OR NONE?
933 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700934 // confirm latest info
935 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800936 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700937 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700938 myNextRole = MASTER;
939 } else {
940 myNextRole = STANDBY;
941 }
942 } else if (event.roleInfo().backups().contains(localNodeId)) {
943 myNextRole = STANDBY;
944 } else {
945 myNextRole = NONE;
946 }
947
Madan Jampani328371d2015-05-29 14:06:27 -0700948 final boolean isReachable = isReachable(did);
949 if (!isReachable) {
950 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800951 if (mastershipService.getLocalRole(did) == NONE) {
952 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700953 + "but this node cannot reach the device "
954 + "and role is already None. Ignoring request.",
955 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800956 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700957 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700958 + "but this node cannot reach the device. "
959 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800960 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700961 mastershipService.relinquishMastership(did);
962 }
963 return;
964 }
965
966 // device is connected to this node:
967 if (store.getDevice(did) != null) {
968 reassertRole(did, myNextRole);
969 } else {
970 log.debug("Device is not yet/no longer in the store: {}", did);
971 }
972 }
973
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800974 // Intercepts mastership events
975 private class InternalMastershipListener implements MastershipListener {
976
tomb41d1ac2014-09-24 01:51:24 -0700977 @Override
978 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800979 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700980 try {
981 handleMastershipEvent(event);
982 } catch (Exception e) {
983 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700984 }
Madan Jampani328371d2015-05-29 14:06:27 -0700985 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700986 }
tomb41d1ac2014-09-24 01:51:24 -0700987 }
tomf80c9722014-09-24 14:49:18 -0700988
989 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700990 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700991 @Override
992 public void notify(DeviceEvent event) {
993 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +0100994 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700995 // When device is administratively removed, force disconnect.
996 DeviceId deviceId = event.subject().id();
997 deviceLocalStatus.remove(deviceId);
998
999 DeviceProvider provider = getProvider(deviceId);
1000 if (provider != null) {
1001 log.info("Triggering disconnect for device {}", deviceId);
1002 try {
1003 provider.triggerDisconnect(deviceId);
1004 } catch (UnsupportedOperationException e) {
1005 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1006 }
1007 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001008 }
tomf80c9722014-09-24 14:49:18 -07001009 }
1010 }
samuel738dfaf2015-07-11 11:08:57 +08001011
1012 @Override
1013 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001014 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001015 Set<Device> results = new HashSet<>();
1016 Iterable<Device> devices = store.getDevices();
1017 if (devices != null) {
1018 devices.forEach(d -> {
1019 if (type.equals(d.type())) {
1020 results.add(d);
1021 }
1022 });
1023 }
1024 return results;
1025 }
1026
1027 @Override
1028 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001029 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001030 Set<Device> results = new HashSet<>();
1031 Iterable<Device> availableDevices = store.getAvailableDevices();
1032 if (availableDevices != null) {
1033 availableDevices.forEach(d -> {
1034 if (type.equals(d.type())) {
1035 results.add(d);
1036 }
1037 });
1038 }
1039 return results;
1040 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001041
1042 private class InternalNetworkConfigListener implements NetworkConfigListener {
1043 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001044 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001045 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
1046 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
1047 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001048 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001049 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001050 || event.configClass().equals(DeviceAnnotationConfig.class))
1051 && mastershipService.isLocalMaster((DeviceId) event.subject());
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001052 }
1053
1054 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001055 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001056 DeviceEvent de = null;
1057 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001058 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001059 DeviceId did = (DeviceId) event.subject();
1060 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001061 BasicDeviceConfig cfg =
1062 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001063
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001064 if (!isAllowed(cfg)) {
1065 kickOutBadDevice(did);
1066 } else {
1067 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001068 DeviceDescription desc =
1069 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001070 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001071 if (desc != null && dp != null) {
1072 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001073 }
1074 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001075 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1076 DeviceId did = (DeviceId) event.subject();
1077 DeviceProvider dp = getProvider(did);
1078 if (!event.config().isPresent() ||
1079 getDevice(did) == null || dp == null) {
1080 // sanity check failed, ignore
1081 return;
1082 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001083 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001084 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001085 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1086 .collect(Collectors.toList());
1087 complete.addAll(portConfig.portDescriptions());
1088 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001089 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1090 DeviceId did = (DeviceId) event.subject();
1091 DeviceProvider dp = getProvider(did);
1092 Device dev = getDevice(did);
1093 DeviceDescription desc =
1094 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1095 Optional<Config> prevConfig = event.prevConfig();
1096 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1097 if (desc != null && dp != null) {
1098 de = store.createOrUpdateDevice(dp.id(), did, desc);
1099 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001100 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001101 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001102 DeviceId did = cpt.deviceId();
1103 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001104
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001105 // Note: assuming PortOperator can modify existing port,
1106 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001107 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001108 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1109 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001110 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001111 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001112 }
1113
1114 if (de != null) {
1115 post(de);
1116 }
1117 }
1118
Simon Hunt8f60ff82017-04-24 17:19:30 -07001119 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001120 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001121 Device badDevice = getDevice(deviceId);
1122 if (badDevice != null) {
1123 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001124 }
1125 }
1126 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001127
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001128 @Override
1129 @SafeVarargs
1130 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001131 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001132 checkNotNull(portOp);
1133
1134 portOp.bindService(networkConfigService);
1135
1136 // update both portOpsIndex and portOps
1137 synchronized (portOpsIndex) {
1138 for (Class<? extends Config<ConnectPoint>> config : configs) {
1139 portOpsIndex.put(config, portOp);
1140 }
1141
1142 portOps.add(portOp);
1143 }
1144
1145 // TODO: Should we be applying to all existing Ports?
1146 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001147 .map(Device::id)
1148 .filter(mastershipService::isLocalMaster)
1149 // for each locally managed Device, update all port descriptions
1150 .map(did -> {
1151 ProviderId pid = Optional.ofNullable(getProvider(did))
1152 .map(Provider::id)
1153 .orElse(null);
1154 if (pid == null) {
1155 log.warn("Provider not found for {}", did);
1156 return ImmutableList.<DeviceEvent>of();
1157 }
1158 List<PortDescription> pds
1159 = store.getPortDescriptions(pid, did)
1160 .map(pdesc -> applyAllPortOps(did, pdesc))
1161 .collect(Collectors.toList());
1162 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001163 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001164 // ..and port port update event if necessary
1165 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001166 }
1167
1168 @Override
1169 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1170 checkNotNull(portOp);
1171
1172
1173 // remove all portOp
1174 synchronized (portOpsIndex) {
1175 portOps.remove(portOp);
1176
1177 // had to do this since COWArrayList iterator doesn't support remove
1178 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1179 }
1180
1181 }
1182
1183 /**
1184 * Merges the appropriate PortConfig with the description.
1185 *
1186 * @param did ID of the Device where the port is attached
1187 * @param desc {@link PortDescription}
1188 * @return merged {@link PortDescription}
1189 */
1190 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1191 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1192 }
1193
1194 /**
1195 * Merges the appropriate PortConfig with the description.
1196 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001197 * @param cpt ConnectPoint where the port is attached
1198 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001199 * @return merged {@link PortDescription}
1200 */
1201 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1202 PortDescription work = desc;
1203 for (PortConfigOperator portOp : portOps) {
1204 work = portOp.combine(cpt, work);
1205 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001206 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001207 }
1208
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001209 /**
1210 * Port Enable/Disable message sent to the device's MASTER node.
1211 */
1212 private class InternalPortUpDownEvent {
1213 private final DeviceId deviceId;
1214 private final PortNumber portNumber;
1215 private final boolean enable;
1216
1217 protected InternalPortUpDownEvent(
1218 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1219 this.deviceId = deviceId;
1220 this.portNumber = portNumber;
1221 this.enable = enable;
1222 }
1223
1224 public DeviceId deviceId() {
1225 return deviceId;
1226 }
1227 public PortNumber portNumber() {
1228 return portNumber;
1229 }
1230 public boolean isEnable() {
1231 return enable;
1232 }
1233
1234 protected InternalPortUpDownEvent() {
1235 this.deviceId = null;
1236 this.portNumber = null;
1237 this.enable = false;
1238 }
1239 }
tomd3097b02014-08-26 10:40:29 -07001240}