blob: 414db4a8f8e2399ef8e4a8a83da2579b4045b726 [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;
22import com.google.common.util.concurrent.Futures;
tomd3097b02014-08-26 10:40:29 -070023import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070026import org.apache.felix.scr.annotations.Reference;
27import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070028import org.apache.felix.scr.annotations.Service;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070029import org.onlab.util.KryoNamespace;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070030import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080031import org.onosproject.cluster.ClusterService;
32import org.onosproject.cluster.NodeId;
Andrea Campanella75ef9f52017-07-27 20:14:32 +020033import org.onosproject.incubator.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080034import org.onosproject.mastership.MastershipEvent;
35import org.onosproject.mastership.MastershipListener;
36import org.onosproject.mastership.MastershipService;
37import org.onosproject.mastership.MastershipTerm;
38import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070039import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080040import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080041import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080042import org.onosproject.net.DeviceId;
43import org.onosproject.net.MastershipRole;
44import org.onosproject.net.Port;
45import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070046import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030047import org.onosproject.net.config.NetworkConfigEvent;
48import org.onosproject.net.config.NetworkConfigListener;
49import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070050import org.onosproject.net.config.PortConfigOperator;
51import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030052import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090053import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080054import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080055import org.onosproject.net.device.DefaultPortDescription;
56import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080057import org.onosproject.net.device.DeviceDescription;
58import org.onosproject.net.device.DeviceEvent;
59import org.onosproject.net.device.DeviceListener;
60import org.onosproject.net.device.DeviceProvider;
61import org.onosproject.net.device.DeviceProviderRegistry;
62import org.onosproject.net.device.DeviceProviderService;
63import org.onosproject.net.device.DeviceService;
64import org.onosproject.net.device.DeviceStore;
65import org.onosproject.net.device.DeviceStoreDelegate;
66import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070067import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030068import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080069import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080070import org.onosproject.net.provider.Provider;
71import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070072import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
73import org.onosproject.store.cluster.messaging.MessageSubject;
74import org.onosproject.store.serializers.KryoNamespaces;
75import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080076import org.onosproject.upgrade.UpgradeService;
tomd3097b02014-08-26 10:40:29 -070077import org.slf4j.Logger;
tomd3097b02014-08-26 10:40:29 -070078
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -070079import java.time.Instant;
Simon Huntffbad3b2017-05-16 15:37:51 -070080import java.util.Collection;
81import java.util.HashSet;
82import java.util.List;
83import java.util.Map;
84import java.util.Objects;
85import java.util.Optional;
86import java.util.Set;
87import java.util.concurrent.CompletableFuture;
88import java.util.concurrent.ConcurrentHashMap;
89import java.util.concurrent.CopyOnWriteArrayList;
90import java.util.concurrent.ExecutionException;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070091import java.util.concurrent.ExecutorService;
Simon Huntffbad3b2017-05-16 15:37:51 -070092import java.util.concurrent.ScheduledExecutorService;
93import java.util.concurrent.TimeUnit;
94import java.util.stream.Collectors;
Jonathan Hart2f669362015-02-11 16:19:20 -080095
Ray Milkey9ef22232016-07-14 12:42:37 -070096import static com.google.common.base.Preconditions.checkNotNull;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070097import static com.google.common.base.Preconditions.checkState;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070098import static com.google.common.collect.Multimaps.newListMultimap;
99import static com.google.common.collect.Multimaps.synchronizedListMultimap;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700100import static java.util.concurrent.Executors.newSingleThreadExecutor;
Ray Milkey9ef22232016-07-14 12:42:37 -0700101import static java.util.concurrent.Executors.newSingleThreadScheduledExecutor;
102import static org.onlab.util.Tools.groupedThreads;
103import static org.onosproject.net.MastershipRole.MASTER;
104import static org.onosproject.net.MastershipRole.NONE;
105import static org.onosproject.net.MastershipRole.STANDBY;
Ray Milkey9ef22232016-07-14 12:42:37 -0700106import static org.onosproject.security.AppGuard.checkPermission;
107import static org.onosproject.security.AppPermission.Type.DEVICE_READ;
108import static org.slf4j.LoggerFactory.getLogger;
109
tomd3097b02014-08-26 10:40:29 -0700110/**
tome4729872014-09-23 00:37:37 -0700111 * Provides implementation of the device SB & NB APIs.
tomd3097b02014-08-26 10:40:29 -0700112 */
113@Component(immediate = true)
114@Service
tom41a2c5f2014-09-19 09:20:35 -0700115public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700116 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700117 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700118
tome5ec3fd2014-09-04 15:18:06 -0700119 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
120 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
121 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
122 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700123 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700124 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700125
tom5f38b3a2014-08-27 23:50:54 -0700126 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700127
alshabib339a3d92014-09-26 17:54:32 -0700128 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700129
tomc78acee2014-09-24 15:16:55 -0700130 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700131 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700132
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800133 private ScheduledExecutorService backgroundService;
134
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700135 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
136
tom41a2c5f2014-09-19 09:20:35 -0700137 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
138 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700139
tom5f38b3a2014-08-27 23:50:54 -0700140 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700141 protected ClusterService clusterService;
142
143 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700144 protected MastershipService mastershipService;
145
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800146 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700147 protected MastershipTermService termService;
148
Madan Jampani61056bc2014-09-27 09:07:26 -0700149 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800150 protected UpgradeService upgradeService;
151
152 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700153 protected NetworkConfigService networkConfigService;
154
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700155 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
156 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700157
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700158 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700159 /**
160 * List of all registered PortConfigOperator.
161 */
162 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
163
164 /**
165 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
166 */
167 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700168 = synchronizedListMultimap(
169 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700170
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800171 // not part of portOps. must be executed at the end
172 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900173 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800174
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700175 private static final MessageSubject PORT_UPDOWN_SUBJECT =
176 new MessageSubject("port-updown-req");
177
178 private static final Serializer SERIALIZER = Serializer.using(
179 KryoNamespace.newBuilder()
180 .register(KryoNamespaces.API)
181 .register(InternalPortUpDownEvent.class)
182 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
183 .build("DeviceManager"));
184
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800185 /**
186 * Local storage for connectivity status of devices.
187 */
188 private class LocalStatus {
189 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700190 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800191
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700192 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800193 connected = b;
194 dateTime = now;
195 }
196 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700197
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800198 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
199 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700200
tomd3097b02014-08-26 10:40:29 -0700201 @Activate
202 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800203 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900204 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800205 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
206
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800207 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700208 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700209 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800210
tomf80c9722014-09-24 14:49:18 -0700211 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700212 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700213 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700214 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800215
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700216 backgroundService.scheduleWithFixedDelay(() -> {
217 try {
218 mastershipCheck();
219 } catch (Exception e) {
220 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800221 }
222 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700223
224 portReqeustExecutor = newSingleThreadExecutor();
225
226 communicationService.<InternalPortUpDownEvent>addSubscriber(
227 PORT_UPDOWN_SUBJECT,
228 SERIALIZER::decode,
229 this::handlePortRequest,
230 portReqeustExecutor);
231
tomd3097b02014-08-26 10:40:29 -0700232 log.info("Started");
233 }
234
235 @Deactivate
236 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800237 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700238 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700239 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700240 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700241 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700242 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
243 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700244 log.info("Stopped");
245 }
246
247 @Override
tomad2d2092014-09-06 23:24:20 -0700248 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900249 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700250 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700251 }
252
253 @Override
mskala32000d32017-07-14 16:27:06 +0200254 public int getAvailableDeviceCount() {
255 checkPermission(DEVICE_READ);
256 return store.getAvailableDeviceCount();
257 }
258
259 @Override
tom32f66842014-08-27 19:27:47 -0700260 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900261 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700262 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700263 }
264
tom32f66842014-08-27 19:27:47 -0700265 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800266 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900267 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800268 return store.getAvailableDevices();
269 }
270
271 @Override
tom32f66842014-08-27 19:27:47 -0700272 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900273 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700274 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700275 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700276 }
277
278 @Override
tomad2d2092014-09-06 23:24:20 -0700279 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900280 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700281 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700282 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700283 }
284
285 @Override
tom32f66842014-08-27 19:27:47 -0700286 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900287 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700288 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700289 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700290 }
291
292 @Override
sangho538108b2015-04-08 14:29:20 -0700293 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900294 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700295 checkNotNull(deviceId, DEVICE_ID_NULL);
296 return store.getPortStatistics(deviceId);
297 }
298
299 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200300 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900301 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200302 checkNotNull(deviceId, DEVICE_ID_NULL);
303 return store.getPortDeltaStatistics(deviceId);
304 }
305
306 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530307 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
308 checkPermission(DEVICE_READ);
309 checkNotNull(deviceId, DEVICE_ID_NULL);
310 checkNotNull(portNumber, PORT_NUMBER_NULL);
311 return store.getStatisticsForPort(deviceId, portNumber);
312 }
313
314 @Override
315 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
316 checkPermission(DEVICE_READ);
317 checkNotNull(deviceId, DEVICE_ID_NULL);
318 checkNotNull(portNumber, PORT_NUMBER_NULL);
319 return store.getDeltaStatisticsForPort(deviceId, portNumber);
320 }
321
322 @Override
tom32f66842014-08-27 19:27:47 -0700323 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900324 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700325 checkNotNull(deviceId, DEVICE_ID_NULL);
326 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700327 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700328 }
329
330 @Override
tomff7eb7c2014-09-08 12:49:03 -0700331 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900332 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900333
tomff7eb7c2014-09-08 12:49:03 -0700334 checkNotNull(deviceId, DEVICE_ID_NULL);
335 return store.isAvailable(deviceId);
336 }
337
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800338 @Override
339 public String localStatus(DeviceId deviceId) {
340 LocalStatus ls = deviceLocalStatus.get(deviceId);
341 if (ls == null) {
342 return "No Record";
343 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700344 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800345 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
346 }
347
Palash Kala0d817b02018-03-23 18:09:45 +0900348 private boolean isLocallyConnected(DeviceId deviceId) {
349 LocalStatus ls = deviceLocalStatus.get(deviceId);
350 if (ls == null) {
351 return false;
352 }
353 return ls.connected;
354 }
355
Ray Milkey054e23d2018-03-22 13:37:11 -0700356 @Override
357 public long getLastUpdatedInstant(DeviceId deviceId) {
358 LocalStatus ls = deviceLocalStatus.get(deviceId);
359 if (ls == null) {
360 return 0;
361 }
362 return ls.dateTime.toEpochMilli();
363 }
364
Palash Kala0d817b02018-03-23 18:09:45 +0900365 // Check a device for control channel connectivity
366 // and changes local-status appropriately.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700367 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800368 if (deviceId == null) {
369 return false;
370 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700371 DeviceProvider provider = getProvider(deviceId);
372 if (provider != null) {
Palash Kala0d817b02018-03-23 18:09:45 +0900373 boolean reachable = provider.isReachable(deviceId);
374 if (reachable && !isLocallyConnected(deviceId)) {
375 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
376 } else if (!reachable && isLocallyConnected(deviceId)) {
377 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
378 }
379 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700380 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800381 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700382 return false;
383 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700384 }
385
tome5ec3fd2014-09-04 15:18:06 -0700386 @Override
387 public void removeDevice(DeviceId deviceId) {
388 checkNotNull(deviceId, DEVICE_ID_NULL);
389 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700390 if (event != null) {
391 log.info("Device {} administratively removed", deviceId);
392 post(event);
393 }
tome5ec3fd2014-09-04 15:18:06 -0700394 }
395
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700396 private void handlePortRequest(InternalPortUpDownEvent event) {
397 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700398 checkNotNull(deviceId, DEVICE_ID_NULL);
399 checkNotNull(deviceId, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700400 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
401 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
402 }
403
404 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
405 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700406 DeviceProvider provider = getProvider(deviceId);
407 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700408 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700409 portNumber, deviceId,
410 (enable) ? "UP" : "DOWN");
411 provider.changePortState(deviceId, portNumber, enable);
412 } else {
413 log.warn("Provider not found for {}", deviceId);
414 }
415 }
416
417 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700418 public void changePortState(DeviceId deviceId, PortNumber portNumber,
419 boolean enable) {
420 checkNotNull(deviceId, DEVICE_ID_NULL);
421 checkNotNull(deviceId, PORT_NUMBER_NULL);
422 NodeId masterId = mastershipService.getMasterFor(deviceId);
423
Ray Milkey4ef245e2018-05-10 15:41:16 -0700424 if (masterId == null) {
425 // No master found; device is offline
426 log.info("No master found for port state change for {}", deviceId);
427 return;
428 }
429
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700430 if (!masterId.equals(localNodeId)) {
431 //Send the request to the master node for the device
432 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
433 deviceId, masterId);
434 communicationService.unicast(
435 new InternalPortUpDownEvent(deviceId, portNumber, enable),
436 PORT_UPDOWN_SUBJECT,
437 SERIALIZER::encode,
438 masterId).whenComplete((r, error) -> {
439 if (error != null) {
440 log.warn("Failed to send packet-updown-req to {}", masterId, error);
441 }
442 });
443 } else {
444 changePortStateAtMaster(deviceId, portNumber, enable);
445 }
446 }
447
448 @Override
samuele1fa7322015-07-14 16:35:16 +0800449 protected DeviceProviderService createProviderService(
450 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700451 return new InternalDeviceProviderService(provider);
452 }
453
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800454 /**
455 * Checks if all the reachable devices have a valid mastership role.
456 */
457 private void mastershipCheck() {
458 log.debug("Checking mastership");
459 for (Device device : getDevices()) {
460 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700461 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
462 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800463 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700464 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700465 // can't be master if device is not reachable
466 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700467 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100468 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700469 post(store.markOffline(deviceId));
470 }
helenyrwufd296b62016-06-22 17:43:02 -0700471 //relinquish master role and ability to be backup.
472 mastershipService.relinquishMastership(deviceId).get();
473 } catch (InterruptedException e) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700474 log.warn("Interrupted while relinquishing role for {}", deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700475 Thread.currentThread().interrupt();
476 } catch (ExecutionException e) {
477 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
478 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530479 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100480 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530481 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100482 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800483 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100484 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800485 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
486 roleFuture.thenAccept(role -> {
487 MastershipTerm term = termService.getMastershipTerm(deviceId);
488 if (term != null && localNodeId.equals(term.master())) {
489 log.info("Marking unreachable device {} offline", deviceId);
490 post(store.markOffline(deviceId));
491 } else {
492 log.info("Failed marking {} offline. {}", deviceId, role);
493 }
494 mastershipService.relinquishMastership(deviceId);
495 });
496 }
helenyrwufd296b62016-06-22 17:43:02 -0700497 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800498 continue;
499 }
500
Ray Milkeyc7104672016-08-31 12:04:34 -0700501 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800502 continue;
503 }
504
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700505 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800506
507 // isReachable but was not MASTER or STANDBY, get a role and apply
508 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800509 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800510 }
511 }
512
tomd3097b02014-08-26 10:40:29 -0700513 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700514 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700515 extends AbstractProviderService<DeviceProvider>
516 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700517
tomcfde0622014-09-09 11:02:42 -0700518 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700519 super(provider);
520 }
521
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700522 /**
523 * Apply role in reaction to provider event.
524 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700525 * @param deviceId device identifier
526 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700527 * @return true if the request was sent to provider
528 */
529 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
530
531 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800532 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700533 return true;
534 }
535
536 DeviceProvider provider = provider();
537 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700538 log.warn("Provider for {} was not found. Cannot apply role {}",
539 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700540 return false;
541 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700542 provider.roleChanged(deviceId, newRole);
543 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700544 return true;
545 }
546
tomd3097b02014-08-26 10:40:29 -0700547 @Override
alshabibb7b40632014-09-28 21:30:00 -0700548 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700549 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700550 checkNotNull(deviceId, DEVICE_ID_NULL);
551 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700552 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700553
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700554 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800555
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700556 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
557 if (!isAllowed(cfg)) {
558 log.warn("Device {} is not allowed", deviceId);
559 return;
560 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200561 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700562 // Generate updated description and establish my Role
563 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900564 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
565 if (annoConfig != null) {
566 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
567 }
568
Yi Tseng7be4e672017-12-05 15:03:26 -0800569 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
570 deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700571 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700572 .thenAccept(role -> {
573 log.info("Local role is {} for {}", role, deviceId);
574 applyRole(deviceId, role);
575 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700576
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200577 if (portConfig != null) {
578 //updating the ports if configration exists
579 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
580 .collect(Collectors.toList());
581 complete.addAll(portConfig.portDescriptions());
582 List<PortDescription> portDescriptions = complete.stream()
583 .map(e -> applyAllPortOps(deviceId, e))
584 .collect(Collectors.toList());
585 store.updatePorts(provider().id(), deviceId, portDescriptions);
586 }
587
helenyrwufd296b62016-06-22 17:43:02 -0700588 if (deviceDescription.isDefaultAvailable()) {
589 log.info("Device {} connected", deviceId);
590 } else {
591 log.info("Device {} registered", deviceId);
592 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200593
tom80c0e5e2014-09-08 18:08:58 -0700594 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700595 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700596 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700597 }
tomd3097b02014-08-26 10:40:29 -0700598 }
599
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700600 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
601 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800602 return DefaultPortDescription.builder(desc)
603 .isEnabled(enabled)
604 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700605 }
606 return desc;
607 }
608
tomd3097b02014-08-26 10:40:29 -0700609 @Override
610 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700611 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700612 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700613 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700614 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700615
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700616 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
617 .map(desc -> ensurePortEnabledState(desc, false))
618 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300619
alshabibafc514a2014-12-01 14:44:05 -0800620 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700621 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700622 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700623 post(store.markOffline(deviceId));
624 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700625 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700626 log.warn("Failed to mark {} offline", deviceId);
627 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800628 // but if I was the last STANDBY connection, etc. and no one else
629 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700630 // temporarily request for Master Role and mark offline.
631
samuele1fa7322015-07-14 16:35:16 +0800632 //there are times when this node will correctly have mastership, BUT
633 //that isn't reflected in the ClockManager before the device disconnects.
634 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700635
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700636 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800637 // Consider revising store API to handle this scenario.
638 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700639 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800640 MastershipTerm term = termService.getMastershipTerm(deviceId);
641 // TODO: Move this type of check inside device clock manager, etc.
642 if (term != null && localNodeId.equals(term.master())) {
643 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800644 post(store.markOffline(deviceId));
645 } else {
646 log.info("Failed again marking {} offline. {}", deviceId, role);
647 }
648 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700649 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700650 try {
samuele1fa7322015-07-14 16:35:16 +0800651 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700652 mastershipService.relinquishMastership(deviceId).get();
653 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800654 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700655 Thread.currentThread().interrupt();
656 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800657 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700658 }
tom0efbb1d2014-09-09 11:54:28 -0700659 }
tomd3097b02014-08-26 10:40:29 -0700660 }
661
662 @Override
alshabibb7b40632014-09-28 21:30:00 -0700663 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700664 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700665 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700666 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700667 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700668 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700669 // Never been a master for this device
670 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800671 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700672 return;
673 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200674 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
675 if (portConfig != null) {
Carmelo Cascone1da7a4d2018-06-27 18:03:11 +0200676 // Updating the ports if configuration exists (on new lists as
677 // the passed one might be immutable)
678 portDescriptions = Lists.newArrayList(portDescriptions);
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200679 portDescriptions.addAll(portConfig.portDescriptions());
680 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700681 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700682 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700683 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700684 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800685 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800686 if (events != null) {
687 for (DeviceEvent event : events) {
688 post(event);
689 }
tom32f66842014-08-27 19:27:47 -0700690 }
tomd3097b02014-08-26 10:40:29 -0700691 }
692
693 @Override
alshabibb7b40632014-09-28 21:30:00 -0700694 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700695 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700696 checkNotNull(deviceId, DEVICE_ID_NULL);
697 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700698 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700699
Madan Jampani565a66a2015-07-25 17:01:13 -0700700 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700701 // Never been a master for this device
702 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700703 log.trace("Ignoring {} port update on standby node. {}", deviceId,
704 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700705 return;
706 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700707 Device device = getDevice(deviceId);
708 if (device == null) {
709 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530710 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700711 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200712 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700713 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700714 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700715 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700716 deviceId,
717 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700718 portDescription = ensurePortEnabledState(storedPortDesc,
719 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300720 }
721
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700722 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800723 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700724 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700725 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700726 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700727 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700728 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700729 }
tomd3097b02014-08-26 10:40:29 -0700730 }
tom3f2bbd72014-09-24 12:07:58 -0700731
732 @Override
Michal Machce774332017-01-25 11:02:55 +0100733 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
734
735 checkNotNull(deviceId, DEVICE_ID_NULL);
736 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
737 checkValidity();
738
739 if (!mastershipService.isLocalMaster(deviceId)) {
740 // Never been a master for this device
741 // any update will be ignored.
742 log.trace("Ignoring {} port update on standby node. {}", deviceId,
743 basePortDescription);
744 return;
745 }
746
747 Device device = getDevice(deviceId);
748 if (device == null) {
749 log.trace("Device not found: {}", deviceId);
750 }
751
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800752 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
753 .isRemoved(true)
754 .build();
755
Michal Machce774332017-01-25 11:02:55 +0100756 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
757 deviceId,
758 newPortDescription);
759 if (event != null) {
760 log.info("Device {} port {} status changed", deviceId, event.port().number());
761 post(event);
762 }
763 }
764
765 @Override
samuele1fa7322015-07-14 16:35:16 +0800766 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700767 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700768 // Several things can happen here:
769 // 1. request and response match
770 // 2. request and response don't match
771 // 3. MastershipRole and requested match (and 1 or 2 are true)
772 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
773 //
774 // 2, 4, and 3 with case 2 are failure modes.
775
tom3f2bbd72014-09-24 12:07:58 -0700776 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700777
Madan Jampanif2af7712015-05-29 18:43:52 -0700778 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700779 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700780
781 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800782 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530783 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700784 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700785 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700786 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700787
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700788 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800789 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700790 return;
791 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800792 log.warn("Role mismatch on {}. set to {}, but store demands {}",
793 deviceId, response, mastershipService.getLocalRole(deviceId));
794 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700795 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800796 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800797 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700798 }
799 } else {
800 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800801 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Carmelo Casconeb37bdde2018-06-22 17:25:46 +0200802 if (requested == MastershipRole.MASTER) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700803 mastershipService.relinquishMastership(deviceId);
804 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800805 //final Device device = getDevice(deviceId);
806 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700807 }
808 }
tom3f2bbd72014-09-24 12:07:58 -0700809 }
sangho538108b2015-04-08 14:29:20 -0700810
811 @Override
samuele1fa7322015-07-14 16:35:16 +0800812 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700813 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700814 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700815 checkValidity();
816
samuele1fa7322015-07-14 16:35:16 +0800817 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
818 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700819 post(event);
820 }
tomd3097b02014-08-26 10:40:29 -0700821 }
tom32f66842014-08-27 19:27:47 -0700822
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700823 // by default allowed, otherwise check flag
824 private boolean isAllowed(BasicDeviceConfig cfg) {
825 return (cfg == null || cfg.isAllowed());
826 }
827
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800828 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700829
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800830 /**
831 * Apply role to device and send probe if MASTER.
832 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700833 * @param deviceId device identifier
834 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800835 * @return true if the request was sent to provider
836 */
837 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
838 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800839 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700840 return true;
841 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700842
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800843 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800844 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800845 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800846 return false;
847 }
848 provider.roleChanged(deviceId, newRole);
849
850 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800851 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800852 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800853 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800854 }
855 return true;
856 }
857
858 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800859 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800860 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700861 * @param did device identifier
862 * @param nextRole role to apply. If NONE is specified,
863 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800864 */
samuele1fa7322015-07-14 16:35:16 +0800865 private void reassertRole(final DeviceId did,
866 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800867
Jordan Halterman9416aea2017-11-17 12:40:21 -0800868 MastershipRole myNextRole = nextRole;
869 if (myNextRole == NONE && upgradeService.isLocalActive()) {
870 try {
871 mastershipService.requestRoleFor(did).get();
872 MastershipTerm term = termService.getMastershipTerm(did);
873 if (term != null && localNodeId.equals(term.master())) {
874 myNextRole = MASTER;
875 } else {
876 myNextRole = STANDBY;
877 }
878 } catch (InterruptedException e) {
879 Thread.currentThread().interrupt();
880 log.error("Interrupted waiting for Mastership", e);
881 } catch (ExecutionException e) {
882 log.error("Encountered an error waiting for Mastership", e);
883 }
884 }
885
886 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700887 case MASTER:
888 final Device device = getDevice(did);
889 if ((device != null) && !isAvailable(did)) {
Palash Kala6c526062018-04-03 18:25:11 +0900890 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700891 }
892 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800893 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700894 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800895 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700896 // immediately failed to apply role
897 mastershipService.relinquishMastership(did);
898 // FIXME disconnect?
899 }
900 break;
901 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -0800902 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700903 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800904 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700905 // immediately failed to apply role
906 mastershipService.relinquishMastership(did);
907 // FIXME disconnect?
908 }
909 break;
910 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700911 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700912 default:
913 // should never reach here
914 log.error("You didn't see anything. I did not exist.");
915 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800916 }
917 }
918
Madan Jampani328371d2015-05-29 14:06:27 -0700919 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700920 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700921 // Don't care if backup list changed.
922 return;
923 }
Madan Jampani328371d2015-05-29 14:06:27 -0700924 final DeviceId did = event.subject();
925
926 // myRole suggested by MastershipService
927 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700928 if (event.type() == MastershipEvent.Type.SUSPENDED) {
929 myNextRole = NONE; // FIXME STANDBY OR NONE?
930 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700931 // confirm latest info
932 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800933 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700934 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700935 myNextRole = MASTER;
936 } else {
937 myNextRole = STANDBY;
938 }
939 } else if (event.roleInfo().backups().contains(localNodeId)) {
940 myNextRole = STANDBY;
941 } else {
942 myNextRole = NONE;
943 }
944
Madan Jampani328371d2015-05-29 14:06:27 -0700945 final boolean isReachable = isReachable(did);
946 if (!isReachable) {
947 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800948 if (mastershipService.getLocalRole(did) == NONE) {
949 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700950 + "but this node cannot reach the device "
951 + "and role is already None. Ignoring request.",
952 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800953 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700954 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700955 + "but this node cannot reach the device. "
956 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800957 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700958 mastershipService.relinquishMastership(did);
959 }
960 return;
961 }
962
963 // device is connected to this node:
964 if (store.getDevice(did) != null) {
965 reassertRole(did, myNextRole);
966 } else {
967 log.debug("Device is not yet/no longer in the store: {}", did);
968 }
969 }
970
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800971 // Intercepts mastership events
972 private class InternalMastershipListener implements MastershipListener {
973
tomb41d1ac2014-09-24 01:51:24 -0700974 @Override
975 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800976 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700977 try {
978 handleMastershipEvent(event);
979 } catch (Exception e) {
980 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700981 }
Madan Jampani328371d2015-05-29 14:06:27 -0700982 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700983 }
tomb41d1ac2014-09-24 01:51:24 -0700984 }
tomf80c9722014-09-24 14:49:18 -0700985
986 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700987 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700988 @Override
989 public void notify(DeviceEvent event) {
990 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +0100991 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700992 // When device is administratively removed, force disconnect.
993 DeviceId deviceId = event.subject().id();
994 deviceLocalStatus.remove(deviceId);
995
996 DeviceProvider provider = getProvider(deviceId);
997 if (provider != null) {
998 log.info("Triggering disconnect for device {}", deviceId);
999 try {
1000 provider.triggerDisconnect(deviceId);
1001 } catch (UnsupportedOperationException e) {
1002 log.warn("Unable to trigger disconnect due to {}", e.getMessage());
1003 }
1004 }
Rafał Szalecki9fb87f62017-12-06 15:06:09 +01001005 }
tomf80c9722014-09-24 14:49:18 -07001006 }
1007 }
samuel738dfaf2015-07-11 11:08:57 +08001008
1009 @Override
1010 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001011 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001012 Set<Device> results = new HashSet<>();
1013 Iterable<Device> devices = store.getDevices();
1014 if (devices != null) {
1015 devices.forEach(d -> {
1016 if (type.equals(d.type())) {
1017 results.add(d);
1018 }
1019 });
1020 }
1021 return results;
1022 }
1023
1024 @Override
1025 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001026 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001027 Set<Device> results = new HashSet<>();
1028 Iterable<Device> availableDevices = store.getAvailableDevices();
1029 if (availableDevices != null) {
1030 availableDevices.forEach(d -> {
1031 if (type.equals(d.type())) {
1032 results.add(d);
1033 }
1034 });
1035 }
1036 return results;
1037 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001038
1039 private class InternalNetworkConfigListener implements NetworkConfigListener {
1040 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001041 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001042 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
1043 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
1044 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001045 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001046 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001047 || event.configClass().equals(DeviceAnnotationConfig.class))
1048 && mastershipService.isLocalMaster((DeviceId) event.subject());
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001049 }
1050
1051 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001052 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001053 DeviceEvent de = null;
1054 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001055 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001056 DeviceId did = (DeviceId) event.subject();
1057 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001058 BasicDeviceConfig cfg =
1059 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001060
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001061 if (!isAllowed(cfg)) {
1062 kickOutBadDevice(did);
1063 } else {
1064 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001065 DeviceDescription desc =
1066 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001067 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001068 if (desc != null && dp != null) {
1069 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001070 }
1071 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001072 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1073 DeviceId did = (DeviceId) event.subject();
1074 DeviceProvider dp = getProvider(did);
1075 if (!event.config().isPresent() ||
1076 getDevice(did) == null || dp == null) {
1077 // sanity check failed, ignore
1078 return;
1079 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001080 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001081 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001082 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1083 .collect(Collectors.toList());
1084 complete.addAll(portConfig.portDescriptions());
1085 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001086 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1087 DeviceId did = (DeviceId) event.subject();
1088 DeviceProvider dp = getProvider(did);
1089 Device dev = getDevice(did);
1090 DeviceDescription desc =
1091 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1092 Optional<Config> prevConfig = event.prevConfig();
1093 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1094 if (desc != null && dp != null) {
1095 de = store.createOrUpdateDevice(dp.id(), did, desc);
1096 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001097 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001098 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001099 DeviceId did = cpt.deviceId();
1100 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001101
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001102 // Note: assuming PortOperator can modify existing port,
1103 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001104 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001105 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1106 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001107 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001108 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001109 }
1110
1111 if (de != null) {
1112 post(de);
1113 }
1114 }
1115
Simon Hunt8f60ff82017-04-24 17:19:30 -07001116 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001117 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001118 Device badDevice = getDevice(deviceId);
1119 if (badDevice != null) {
1120 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001121 }
1122 }
1123 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001124
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001125 @Override
1126 @SafeVarargs
1127 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001128 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001129 checkNotNull(portOp);
1130
1131 portOp.bindService(networkConfigService);
1132
1133 // update both portOpsIndex and portOps
1134 synchronized (portOpsIndex) {
1135 for (Class<? extends Config<ConnectPoint>> config : configs) {
1136 portOpsIndex.put(config, portOp);
1137 }
1138
1139 portOps.add(portOp);
1140 }
1141
1142 // TODO: Should we be applying to all existing Ports?
1143 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001144 .map(Device::id)
1145 .filter(mastershipService::isLocalMaster)
1146 // for each locally managed Device, update all port descriptions
1147 .map(did -> {
1148 ProviderId pid = Optional.ofNullable(getProvider(did))
1149 .map(Provider::id)
1150 .orElse(null);
1151 if (pid == null) {
1152 log.warn("Provider not found for {}", did);
1153 return ImmutableList.<DeviceEvent>of();
1154 }
1155 List<PortDescription> pds
1156 = store.getPortDescriptions(pid, did)
1157 .map(pdesc -> applyAllPortOps(did, pdesc))
1158 .collect(Collectors.toList());
1159 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001160 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001161 // ..and port port update event if necessary
1162 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001163 }
1164
1165 @Override
1166 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1167 checkNotNull(portOp);
1168
1169
1170 // remove all portOp
1171 synchronized (portOpsIndex) {
1172 portOps.remove(portOp);
1173
1174 // had to do this since COWArrayList iterator doesn't support remove
1175 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1176 }
1177
1178 }
1179
1180 /**
1181 * Merges the appropriate PortConfig with the description.
1182 *
1183 * @param did ID of the Device where the port is attached
1184 * @param desc {@link PortDescription}
1185 * @return merged {@link PortDescription}
1186 */
1187 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1188 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1189 }
1190
1191 /**
1192 * Merges the appropriate PortConfig with the description.
1193 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001194 * @param cpt ConnectPoint where the port is attached
1195 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001196 * @return merged {@link PortDescription}
1197 */
1198 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1199 PortDescription work = desc;
1200 for (PortConfigOperator portOp : portOps) {
1201 work = portOp.combine(cpt, work);
1202 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001203 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001204 }
1205
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001206 /**
1207 * Port Enable/Disable message sent to the device's MASTER node.
1208 */
1209 private class InternalPortUpDownEvent {
1210 private final DeviceId deviceId;
1211 private final PortNumber portNumber;
1212 private final boolean enable;
1213
1214 protected InternalPortUpDownEvent(
1215 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1216 this.deviceId = deviceId;
1217 this.portNumber = portNumber;
1218 this.enable = enable;
1219 }
1220
1221 public DeviceId deviceId() {
1222 return deviceId;
1223 }
1224 public PortNumber portNumber() {
1225 return portNumber;
1226 }
1227 public boolean isEnable() {
1228 return enable;
1229 }
1230
1231 protected InternalPortUpDownEvent() {
1232 this.deviceId = null;
1233 this.portNumber = null;
1234 this.enable = false;
1235 }
1236 }
tomd3097b02014-08-26 10:40:29 -07001237}