blob: 458d100edee1d8b3c077e1c227d64fe394df8cc1 [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;
19import com.google.common.collect.Maps;
20import com.google.common.collect.Multimap;
21import com.google.common.util.concurrent.Futures;
tomd3097b02014-08-26 10:40:29 -070022import org.apache.felix.scr.annotations.Activate;
23import org.apache.felix.scr.annotations.Component;
24import org.apache.felix.scr.annotations.Deactivate;
tom5f38b3a2014-08-27 23:50:54 -070025import org.apache.felix.scr.annotations.Reference;
26import org.apache.felix.scr.annotations.ReferenceCardinality;
tomd3097b02014-08-26 10:40:29 -070027import org.apache.felix.scr.annotations.Service;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070028import org.onlab.util.KryoNamespace;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070029import org.onlab.util.Tools;
Brian O'Connorabafb502014-12-02 22:26:20 -080030import org.onosproject.cluster.ClusterService;
31import org.onosproject.cluster.NodeId;
Andrea Campanella75ef9f52017-07-27 20:14:32 +020032import org.onosproject.incubator.net.config.basics.PortDescriptionsConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080033import org.onosproject.mastership.MastershipEvent;
34import org.onosproject.mastership.MastershipListener;
35import org.onosproject.mastership.MastershipService;
36import org.onosproject.mastership.MastershipTerm;
37import org.onosproject.mastership.MastershipTermService;
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -070038import org.onosproject.net.ConnectPoint;
Brian O'Connorabafb502014-12-02 22:26:20 -080039import org.onosproject.net.Device;
samuel738dfaf2015-07-11 11:08:57 +080040import org.onosproject.net.Device.Type;
Brian O'Connorabafb502014-12-02 22:26:20 -080041import org.onosproject.net.DeviceId;
42import org.onosproject.net.MastershipRole;
43import org.onosproject.net.Port;
44import org.onosproject.net.PortNumber;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070045import org.onosproject.net.config.Config;
Yafit Hadara9a73de2015-09-06 13:52:52 +030046import org.onosproject.net.config.NetworkConfigEvent;
47import org.onosproject.net.config.NetworkConfigListener;
48import org.onosproject.net.config.NetworkConfigService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -070049import org.onosproject.net.config.PortConfigOperator;
50import org.onosproject.net.config.PortConfigOperatorRegistry;
Yafit Hadara9a73de2015-09-06 13:52:52 +030051import org.onosproject.net.config.basics.BasicDeviceConfig;
Palash Kalaa06a6162017-11-15 20:42:40 +090052import org.onosproject.net.config.basics.DeviceAnnotationConfig;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -080053import org.onosproject.net.config.basics.PortAnnotationConfig;
Brian O'Connorabafb502014-12-02 22:26:20 -080054import org.onosproject.net.device.DefaultPortDescription;
55import org.onosproject.net.device.DeviceAdminService;
Brian O'Connorabafb502014-12-02 22:26:20 -080056import org.onosproject.net.device.DeviceDescription;
57import org.onosproject.net.device.DeviceEvent;
58import org.onosproject.net.device.DeviceListener;
59import org.onosproject.net.device.DeviceProvider;
60import org.onosproject.net.device.DeviceProviderRegistry;
61import org.onosproject.net.device.DeviceProviderService;
62import org.onosproject.net.device.DeviceService;
63import org.onosproject.net.device.DeviceStore;
64import org.onosproject.net.device.DeviceStoreDelegate;
65import org.onosproject.net.device.PortDescription;
sangho538108b2015-04-08 14:29:20 -070066import org.onosproject.net.device.PortStatistics;
Yafit Hadara9a73de2015-09-06 13:52:52 +030067import org.onosproject.net.provider.AbstractListenerProviderRegistry;
Brian O'Connorabafb502014-12-02 22:26:20 -080068import org.onosproject.net.provider.AbstractProviderService;
Yuta HIGUCHI3a2a9872016-11-29 20:24:23 -080069import org.onosproject.net.provider.Provider;
70import org.onosproject.net.provider.ProviderId;
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -070071import org.onosproject.store.cluster.messaging.ClusterCommunicationService;
72import org.onosproject.store.cluster.messaging.MessageSubject;
73import org.onosproject.store.serializers.KryoNamespaces;
74import org.onosproject.store.service.Serializer;
Jordan Halterman9416aea2017-11-17 12:40:21 -080075import org.onosproject.upgrade.UpgradeService;
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 */
112@Component(immediate = true)
113@Service
tom41a2c5f2014-09-19 09:20:35 -0700114public class DeviceManager
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700115 extends AbstractListenerProviderRegistry<DeviceEvent, DeviceListener, DeviceProvider, DeviceProviderService>
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700116 implements DeviceService, DeviceAdminService, DeviceProviderRegistry, PortConfigOperatorRegistry {
tom32f66842014-08-27 19:27:47 -0700117
tome5ec3fd2014-09-04 15:18:06 -0700118 private static final String DEVICE_ID_NULL = "Device ID cannot be null";
119 private static final String PORT_NUMBER_NULL = "Port number cannot be null";
120 private static final String DEVICE_DESCRIPTION_NULL = "Device description cannot be null";
121 private static final String PORT_DESCRIPTION_NULL = "Port description cannot be null";
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700122 private static final String PORT_DESC_LIST_NULL = "Port description list cannot be null";
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700123 private static final String EVENT_NON_MASTER = "Non-master node cannot handle this event";
tomd3097b02014-08-26 10:40:29 -0700124
tom5f38b3a2014-08-27 23:50:54 -0700125 private final Logger log = getLogger(getClass());
tomd3097b02014-08-26 10:40:29 -0700126
alshabib339a3d92014-09-26 17:54:32 -0700127 private final DeviceStoreDelegate delegate = new InternalStoreDelegate();
tomf80c9722014-09-24 14:49:18 -0700128
tomc78acee2014-09-24 15:16:55 -0700129 private final MastershipListener mastershipListener = new InternalMastershipListener();
Madan Jampanide003d92015-05-11 17:14:20 -0700130 private NodeId localNodeId;
tomb41d1ac2014-09-24 01:51:24 -0700131
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800132 private ScheduledExecutorService backgroundService;
133
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700134 private final NetworkConfigListener networkConfigListener = new InternalNetworkConfigListener();
135
tom41a2c5f2014-09-19 09:20:35 -0700136 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
137 protected DeviceStore store;
tomd3097b02014-08-26 10:40:29 -0700138
tom5f38b3a2014-08-27 23:50:54 -0700139 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
tomb41d1ac2014-09-24 01:51:24 -0700140 protected ClusterService clusterService;
141
142 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibea7f044e2014-09-23 16:56:20 -0700143 protected MastershipService mastershipService;
144
Yuta HIGUCHIbcac4992014-11-22 19:27:57 -0800145 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Ayaka Koshibe3de43ca2014-09-26 16:40:23 -0700146 protected MastershipTermService termService;
147
Madan Jampani61056bc2014-09-27 09:07:26 -0700148 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Jordan Halterman9416aea2017-11-17 12:40:21 -0800149 protected UpgradeService upgradeService;
150
151 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700152 protected NetworkConfigService networkConfigService;
153
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700154 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
155 protected ClusterCommunicationService communicationService;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700156
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700157 private ExecutorService portReqeustExecutor;
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700158 /**
159 * List of all registered PortConfigOperator.
160 */
161 private final List<PortConfigOperator> portOps = new CopyOnWriteArrayList<>();
162
163 /**
164 * Index to look up PortConfigOperator from Config each PortConfigOperator uses.
165 */
166 private final Multimap<Class<? extends Config<ConnectPoint>>, PortConfigOperator> portOpsIndex
Simon Huntffbad3b2017-05-16 15:37:51 -0700167 = synchronizedListMultimap(
168 newListMultimap(new ConcurrentHashMap<>(), CopyOnWriteArrayList::new));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700169
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800170 // not part of portOps. must be executed at the end
171 private PortAnnotationOperator portAnnotationOp;
Palash Kalaa06a6162017-11-15 20:42:40 +0900172 private DeviceAnnotationOperator deviceAnnotationOp;
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800173
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700174 private static final MessageSubject PORT_UPDOWN_SUBJECT =
175 new MessageSubject("port-updown-req");
176
177 private static final Serializer SERIALIZER = Serializer.using(
178 KryoNamespace.newBuilder()
179 .register(KryoNamespaces.API)
180 .register(InternalPortUpDownEvent.class)
181 .nextId(KryoNamespaces.BEGIN_USER_CUSTOM_ID)
182 .build("DeviceManager"));
183
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800184 /**
185 * Local storage for connectivity status of devices.
186 */
187 private class LocalStatus {
188 boolean connected;
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700189 Instant dateTime;
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800190
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700191 public LocalStatus(boolean b, Instant now) {
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800192 connected = b;
193 dateTime = now;
194 }
195 }
Simon Huntffbad3b2017-05-16 15:37:51 -0700196
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800197 private final Map<DeviceId, LocalStatus> deviceLocalStatus =
198 Maps.newConcurrentMap();
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700199
tomd3097b02014-08-26 10:40:29 -0700200 @Activate
201 public void activate() {
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800202 portAnnotationOp = new PortAnnotationOperator(networkConfigService);
Palash Kalaa06a6162017-11-15 20:42:40 +0900203 deviceAnnotationOp = new DeviceAnnotationOperator(networkConfigService);
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -0800204 portOpsIndex.put(PortAnnotationConfig.class, portAnnotationOp);
205
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800206 backgroundService = newSingleThreadScheduledExecutor(
Simon Huntffbad3b2017-05-16 15:37:51 -0700207 groupedThreads("onos/device", "manager-background", log));
Madan Jampanide003d92015-05-11 17:14:20 -0700208 localNodeId = clusterService.getLocalNode().id();
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800209
tomf80c9722014-09-24 14:49:18 -0700210 store.setDelegate(delegate);
tom96dfcab2014-08-28 09:26:03 -0700211 eventDispatcher.addSink(DeviceEvent.class, listenerRegistry);
tomb41d1ac2014-09-24 01:51:24 -0700212 mastershipService.addListener(mastershipListener);
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700213 networkConfigService.addListener(networkConfigListener);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800214
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700215 backgroundService.scheduleWithFixedDelay(() -> {
216 try {
217 mastershipCheck();
218 } catch (Exception e) {
219 log.error("Exception thrown during integrity check", e);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800220 }
221 }, 1, 1, TimeUnit.MINUTES);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700222
223 portReqeustExecutor = newSingleThreadExecutor();
224
225 communicationService.<InternalPortUpDownEvent>addSubscriber(
226 PORT_UPDOWN_SUBJECT,
227 SERIALIZER::decode,
228 this::handlePortRequest,
229 portReqeustExecutor);
230
tomd3097b02014-08-26 10:40:29 -0700231 log.info("Started");
232 }
233
234 @Deactivate
235 public void deactivate() {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800236 backgroundService.shutdown();
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700237 networkConfigService.removeListener(networkConfigListener);
tomf80c9722014-09-24 14:49:18 -0700238 store.unsetDelegate(delegate);
tomb41d1ac2014-09-24 01:51:24 -0700239 mastershipService.removeListener(mastershipListener);
tom5f38b3a2014-08-27 23:50:54 -0700240 eventDispatcher.removeSink(DeviceEvent.class);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700241 communicationService.removeSubscriber(PORT_UPDOWN_SUBJECT);
242 portReqeustExecutor.shutdown();
tomd3097b02014-08-26 10:40:29 -0700243 log.info("Stopped");
244 }
245
246 @Override
tomad2d2092014-09-06 23:24:20 -0700247 public int getDeviceCount() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900248 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700249 return store.getDeviceCount();
tomd3097b02014-08-26 10:40:29 -0700250 }
251
252 @Override
mskala32000d32017-07-14 16:27:06 +0200253 public int getAvailableDeviceCount() {
254 checkPermission(DEVICE_READ);
255 return store.getAvailableDeviceCount();
256 }
257
258 @Override
tom32f66842014-08-27 19:27:47 -0700259 public Iterable<Device> getDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900260 checkPermission(DEVICE_READ);
tome5ec3fd2014-09-04 15:18:06 -0700261 return store.getDevices();
tomd3097b02014-08-26 10:40:29 -0700262 }
263
tom32f66842014-08-27 19:27:47 -0700264 @Override
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800265 public Iterable<Device> getAvailableDevices() {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900266 checkPermission(DEVICE_READ);
Yuta HIGUCHIf1f2ac02014-11-26 14:02:22 -0800267 return store.getAvailableDevices();
268 }
269
270 @Override
tom32f66842014-08-27 19:27:47 -0700271 public Device getDevice(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900272 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700273 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700274 return store.getDevice(deviceId);
tom32f66842014-08-27 19:27:47 -0700275 }
276
277 @Override
tomad2d2092014-09-06 23:24:20 -0700278 public MastershipRole getRole(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900279 checkPermission(DEVICE_READ);
tomad2d2092014-09-06 23:24:20 -0700280 checkNotNull(deviceId, DEVICE_ID_NULL);
tomb41d1ac2014-09-24 01:51:24 -0700281 return mastershipService.getLocalRole(deviceId);
tomad2d2092014-09-06 23:24:20 -0700282 }
283
284 @Override
tom32f66842014-08-27 19:27:47 -0700285 public List<Port> getPorts(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900286 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700287 checkNotNull(deviceId, DEVICE_ID_NULL);
tom132b58a2014-08-28 16:11:28 -0700288 return store.getPorts(deviceId);
tom32f66842014-08-27 19:27:47 -0700289 }
290
291 @Override
sangho538108b2015-04-08 14:29:20 -0700292 public List<PortStatistics> getPortStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900293 checkPermission(DEVICE_READ);
sangho538108b2015-04-08 14:29:20 -0700294 checkNotNull(deviceId, DEVICE_ID_NULL);
295 return store.getPortStatistics(deviceId);
296 }
297
298 @Override
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200299 public List<PortStatistics> getPortDeltaStatistics(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900300 checkPermission(DEVICE_READ);
Dusan Pajin11ff4a82015-08-20 18:03:05 +0200301 checkNotNull(deviceId, DEVICE_ID_NULL);
302 return store.getPortDeltaStatistics(deviceId);
303 }
304
305 @Override
Viswanath KSP22774cd2016-08-20 20:06:30 +0530306 public PortStatistics getStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
307 checkPermission(DEVICE_READ);
308 checkNotNull(deviceId, DEVICE_ID_NULL);
309 checkNotNull(portNumber, PORT_NUMBER_NULL);
310 return store.getStatisticsForPort(deviceId, portNumber);
311 }
312
313 @Override
314 public PortStatistics getDeltaStatisticsForPort(DeviceId deviceId, PortNumber portNumber) {
315 checkPermission(DEVICE_READ);
316 checkNotNull(deviceId, DEVICE_ID_NULL);
317 checkNotNull(portNumber, PORT_NUMBER_NULL);
318 return store.getDeltaStatisticsForPort(deviceId, portNumber);
319 }
320
321 @Override
tom32f66842014-08-27 19:27:47 -0700322 public Port getPort(DeviceId deviceId, PortNumber portNumber) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900323 checkPermission(DEVICE_READ);
tom32f66842014-08-27 19:27:47 -0700324 checkNotNull(deviceId, DEVICE_ID_NULL);
325 checkNotNull(portNumber, PORT_NUMBER_NULL);
tom132b58a2014-08-28 16:11:28 -0700326 return store.getPort(deviceId, portNumber);
tom32f66842014-08-27 19:27:47 -0700327 }
328
329 @Override
tomff7eb7c2014-09-08 12:49:03 -0700330 public boolean isAvailable(DeviceId deviceId) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900331 checkPermission(DEVICE_READ);
Changhoon Yoon541ef712015-05-23 17:18:34 +0900332
tomff7eb7c2014-09-08 12:49:03 -0700333 checkNotNull(deviceId, DEVICE_ID_NULL);
334 return store.isAvailable(deviceId);
335 }
336
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800337 @Override
338 public String localStatus(DeviceId deviceId) {
339 LocalStatus ls = deviceLocalStatus.get(deviceId);
340 if (ls == null) {
341 return "No Record";
342 }
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700343 String timeAgo = Tools.timeAgo(ls.dateTime.toEpochMilli());
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800344 return (ls.connected) ? "connected " + timeAgo : "disconnected " + timeAgo;
345 }
346
Palash Kala0d817b02018-03-23 18:09:45 +0900347 private boolean isLocallyConnected(DeviceId deviceId) {
348 LocalStatus ls = deviceLocalStatus.get(deviceId);
349 if (ls == null) {
350 return false;
351 }
352 return ls.connected;
353 }
354
Ray Milkey054e23d2018-03-22 13:37:11 -0700355 @Override
356 public long getLastUpdatedInstant(DeviceId deviceId) {
357 LocalStatus ls = deviceLocalStatus.get(deviceId);
358 if (ls == null) {
359 return 0;
360 }
361 return ls.dateTime.toEpochMilli();
362 }
363
Palash Kala0d817b02018-03-23 18:09:45 +0900364 // Check a device for control channel connectivity
365 // and changes local-status appropriately.
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700366 private boolean isReachable(DeviceId deviceId) {
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800367 if (deviceId == null) {
368 return false;
369 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700370 DeviceProvider provider = getProvider(deviceId);
371 if (provider != null) {
Palash Kala0d817b02018-03-23 18:09:45 +0900372 boolean reachable = provider.isReachable(deviceId);
373 if (reachable && !isLocallyConnected(deviceId)) {
374 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
375 } else if (!reachable && isLocallyConnected(deviceId)) {
376 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
377 }
378 return reachable;
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700379 } else {
Yuta HIGUCHI72669c42014-11-13 14:48:17 -0800380 log.debug("Provider not found for {}", deviceId);
Ayaka Koshibee60d4522014-10-28 15:07:00 -0700381 return false;
382 }
Ayaka Koshibee8708e32014-10-22 13:40:18 -0700383 }
384
tome5ec3fd2014-09-04 15:18:06 -0700385 @Override
386 public void removeDevice(DeviceId deviceId) {
387 checkNotNull(deviceId, DEVICE_ID_NULL);
388 DeviceEvent event = store.removeDevice(deviceId);
tom0efbb1d2014-09-09 11:54:28 -0700389 if (event != null) {
390 log.info("Device {} administratively removed", deviceId);
391 post(event);
392 }
tome5ec3fd2014-09-04 15:18:06 -0700393 }
394
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700395 private void handlePortRequest(InternalPortUpDownEvent event) {
396 DeviceId deviceId = event.deviceId();
Saurav Dasa2d37502016-03-25 17:50:40 -0700397 checkNotNull(deviceId, DEVICE_ID_NULL);
398 checkNotNull(deviceId, PORT_NUMBER_NULL);
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700399 checkState(mastershipService.isLocalMaster(deviceId), EVENT_NON_MASTER);
400 changePortStateAtMaster(event.deviceId(), event.portNumber(), event.isEnable());
401 }
402
403 private void changePortStateAtMaster(DeviceId deviceId, PortNumber portNumber,
404 boolean enable) {
Saurav Dasa2d37502016-03-25 17:50:40 -0700405 DeviceProvider provider = getProvider(deviceId);
406 if (provider != null) {
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700407 log.info("Port {} on device {} being administratively brought {}",
Saurav Dasa2d37502016-03-25 17:50:40 -0700408 portNumber, deviceId,
409 (enable) ? "UP" : "DOWN");
410 provider.changePortState(deviceId, portNumber, enable);
411 } else {
412 log.warn("Provider not found for {}", deviceId);
413 }
414 }
415
416 @Override
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700417 public void changePortState(DeviceId deviceId, PortNumber portNumber,
418 boolean enable) {
419 checkNotNull(deviceId, DEVICE_ID_NULL);
420 checkNotNull(deviceId, PORT_NUMBER_NULL);
421 NodeId masterId = mastershipService.getMasterFor(deviceId);
422
Ray Milkey4ef245e2018-05-10 15:41:16 -0700423 if (masterId == null) {
424 // No master found; device is offline
425 log.info("No master found for port state change for {}", deviceId);
426 return;
427 }
428
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -0700429 if (!masterId.equals(localNodeId)) {
430 //Send the request to the master node for the device
431 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
432 deviceId, masterId);
433 communicationService.unicast(
434 new InternalPortUpDownEvent(deviceId, portNumber, enable),
435 PORT_UPDOWN_SUBJECT,
436 SERIALIZER::encode,
437 masterId).whenComplete((r, error) -> {
438 if (error != null) {
439 log.warn("Failed to send packet-updown-req to {}", masterId, error);
440 }
441 });
442 } else {
443 changePortStateAtMaster(deviceId, portNumber, enable);
444 }
445 }
446
447 @Override
samuele1fa7322015-07-14 16:35:16 +0800448 protected DeviceProviderService createProviderService(
449 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700450 return new InternalDeviceProviderService(provider);
451 }
452
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800453 /**
454 * Checks if all the reachable devices have a valid mastership role.
455 */
456 private void mastershipCheck() {
457 log.debug("Checking mastership");
458 for (Device device : getDevices()) {
459 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700460 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
461 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800462 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700463 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700464 // can't be master if device is not reachable
465 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700466 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100467 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700468 post(store.markOffline(deviceId));
469 }
helenyrwufd296b62016-06-22 17:43:02 -0700470 //relinquish master role and ability to be backup.
471 mastershipService.relinquishMastership(deviceId).get();
472 } catch (InterruptedException e) {
473 log.warn("Interrupted while reliquishing role for {}", deviceId);
474 Thread.currentThread().interrupt();
475 } catch (ExecutionException e) {
476 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
477 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530478 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100479 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530480 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100481 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800482 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100483 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800484 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
485 roleFuture.thenAccept(role -> {
486 MastershipTerm term = termService.getMastershipTerm(deviceId);
487 if (term != null && localNodeId.equals(term.master())) {
488 log.info("Marking unreachable device {} offline", deviceId);
489 post(store.markOffline(deviceId));
490 } else {
491 log.info("Failed marking {} offline. {}", deviceId, role);
492 }
493 mastershipService.relinquishMastership(deviceId);
494 });
495 }
helenyrwufd296b62016-06-22 17:43:02 -0700496 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800497 continue;
498 }
499
Ray Milkeyc7104672016-08-31 12:04:34 -0700500 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800501 continue;
502 }
503
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700504 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800505
506 // isReachable but was not MASTER or STANDBY, get a role and apply
507 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800508 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800509 }
510 }
511
tomd3097b02014-08-26 10:40:29 -0700512 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700513 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700514 extends AbstractProviderService<DeviceProvider>
515 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700516
tomcfde0622014-09-09 11:02:42 -0700517 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700518 super(provider);
519 }
520
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700521 /**
522 * Apply role in reaction to provider event.
523 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700524 * @param deviceId device identifier
525 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700526 * @return true if the request was sent to provider
527 */
528 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
529
530 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800531 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700532 return true;
533 }
534
535 DeviceProvider provider = provider();
536 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700537 log.warn("Provider for {} was not found. Cannot apply role {}",
538 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700539 return false;
540 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700541 provider.roleChanged(deviceId, newRole);
542 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700543 return true;
544 }
545
tomd3097b02014-08-26 10:40:29 -0700546 @Override
alshabibb7b40632014-09-28 21:30:00 -0700547 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700548 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700549 checkNotNull(deviceId, DEVICE_ID_NULL);
550 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700551 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700552
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700553 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800554
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700555 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
556 if (!isAllowed(cfg)) {
557 log.warn("Device {} is not allowed", deviceId);
558 return;
559 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200560 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700561 // Generate updated description and establish my Role
562 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900563 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
564 if (annoConfig != null) {
565 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
566 }
567
Yi Tseng7be4e672017-12-05 15:03:26 -0800568 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
569 deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700570 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700571 .thenAccept(role -> {
572 log.info("Local role is {} for {}", role, deviceId);
573 applyRole(deviceId, role);
574 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700575
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200576 if (portConfig != null) {
577 //updating the ports if configration exists
578 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
579 .collect(Collectors.toList());
580 complete.addAll(portConfig.portDescriptions());
581 List<PortDescription> portDescriptions = complete.stream()
582 .map(e -> applyAllPortOps(deviceId, e))
583 .collect(Collectors.toList());
584 store.updatePorts(provider().id(), deviceId, portDescriptions);
585 }
586
helenyrwufd296b62016-06-22 17:43:02 -0700587 if (deviceDescription.isDefaultAvailable()) {
588 log.info("Device {} connected", deviceId);
589 } else {
590 log.info("Device {} registered", deviceId);
591 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200592
tom80c0e5e2014-09-08 18:08:58 -0700593 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700594 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700595 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700596 }
tomd3097b02014-08-26 10:40:29 -0700597 }
598
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700599 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
600 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800601 return DefaultPortDescription.builder(desc)
602 .isEnabled(enabled)
603 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700604 }
605 return desc;
606 }
607
tomd3097b02014-08-26 10:40:29 -0700608 @Override
609 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700610 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700611 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700612 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700613 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700614
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700615 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
616 .map(desc -> ensurePortEnabledState(desc, false))
617 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300618
alshabibafc514a2014-12-01 14:44:05 -0800619 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700620 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700621 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700622 post(store.markOffline(deviceId));
623 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700624 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700625 log.warn("Failed to mark {} offline", deviceId);
626 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800627 // but if I was the last STANDBY connection, etc. and no one else
628 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700629 // temporarily request for Master Role and mark offline.
630
samuele1fa7322015-07-14 16:35:16 +0800631 //there are times when this node will correctly have mastership, BUT
632 //that isn't reflected in the ClockManager before the device disconnects.
633 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700634
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700635 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800636 // Consider revising store API to handle this scenario.
637 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700638 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800639 MastershipTerm term = termService.getMastershipTerm(deviceId);
640 // TODO: Move this type of check inside device clock manager, etc.
641 if (term != null && localNodeId.equals(term.master())) {
642 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800643 post(store.markOffline(deviceId));
644 } else {
645 log.info("Failed again marking {} offline. {}", deviceId, role);
646 }
647 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700648 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700649 try {
samuele1fa7322015-07-14 16:35:16 +0800650 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700651 mastershipService.relinquishMastership(deviceId).get();
652 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800653 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700654 Thread.currentThread().interrupt();
655 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800656 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700657 }
tom0efbb1d2014-09-09 11:54:28 -0700658 }
tomd3097b02014-08-26 10:40:29 -0700659 }
660
661 @Override
alshabibb7b40632014-09-28 21:30:00 -0700662 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700663 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700664 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700665 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700666 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700667 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700668 // Never been a master for this device
669 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800670 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700671 return;
672 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200673 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
674 if (portConfig != null) {
675 //updating the ports if configration exists
676 portDescriptions.addAll(portConfig.portDescriptions());
677 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700678 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700679 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700680 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700681 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800682 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800683 if (events != null) {
684 for (DeviceEvent event : events) {
685 post(event);
686 }
tom32f66842014-08-27 19:27:47 -0700687 }
tomd3097b02014-08-26 10:40:29 -0700688 }
689
690 @Override
alshabibb7b40632014-09-28 21:30:00 -0700691 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700692 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700693 checkNotNull(deviceId, DEVICE_ID_NULL);
694 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700695 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700696
Madan Jampani565a66a2015-07-25 17:01:13 -0700697 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700698 // Never been a master for this device
699 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700700 log.trace("Ignoring {} port update on standby node. {}", deviceId,
701 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700702 return;
703 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700704 Device device = getDevice(deviceId);
705 if (device == null) {
706 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530707 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700708 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200709 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700710 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700711 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700712 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700713 deviceId,
714 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700715 portDescription = ensurePortEnabledState(storedPortDesc,
716 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300717 }
718
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700719 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800720 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700721 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700722 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700723 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700724 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700725 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700726 }
tomd3097b02014-08-26 10:40:29 -0700727 }
tom3f2bbd72014-09-24 12:07:58 -0700728
729 @Override
Michal Machce774332017-01-25 11:02:55 +0100730 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
731
732 checkNotNull(deviceId, DEVICE_ID_NULL);
733 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
734 checkValidity();
735
736 if (!mastershipService.isLocalMaster(deviceId)) {
737 // Never been a master for this device
738 // any update will be ignored.
739 log.trace("Ignoring {} port update on standby node. {}", deviceId,
740 basePortDescription);
741 return;
742 }
743
744 Device device = getDevice(deviceId);
745 if (device == null) {
746 log.trace("Device not found: {}", deviceId);
747 }
748
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800749 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
750 .isRemoved(true)
751 .build();
752
Michal Machce774332017-01-25 11:02:55 +0100753 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
754 deviceId,
755 newPortDescription);
756 if (event != null) {
757 log.info("Device {} port {} status changed", deviceId, event.port().number());
758 post(event);
759 }
760 }
761
762 @Override
samuele1fa7322015-07-14 16:35:16 +0800763 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700764 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700765 // Several things can happen here:
766 // 1. request and response match
767 // 2. request and response don't match
768 // 3. MastershipRole and requested match (and 1 or 2 are true)
769 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
770 //
771 // 2, 4, and 3 with case 2 are failure modes.
772
tom3f2bbd72014-09-24 12:07:58 -0700773 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700774
Madan Jampanif2af7712015-05-29 18:43:52 -0700775 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700776 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700777
778 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800779 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530780 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700781 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700782 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700783 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700784
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700785 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800786 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700787 return;
788 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800789 log.warn("Role mismatch on {}. set to {}, but store demands {}",
790 deviceId, response, mastershipService.getLocalRole(deviceId));
791 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700792 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800793 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800794 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700795 }
796 } else {
797 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800798 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700799 if (response == MastershipRole.MASTER) {
800 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
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800825 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700826
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800827 /**
828 * Apply role to device and send probe if MASTER.
829 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700830 * @param deviceId device identifier
831 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800832 * @return true if the request was sent to provider
833 */
834 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
835 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800836 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700837 return true;
838 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700839
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800840 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800841 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800842 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800843 return false;
844 }
845 provider.roleChanged(deviceId, newRole);
846
847 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800848 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800849 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800850 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800851 }
852 return true;
853 }
854
855 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800856 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800857 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700858 * @param did device identifier
859 * @param nextRole role to apply. If NONE is specified,
860 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800861 */
samuele1fa7322015-07-14 16:35:16 +0800862 private void reassertRole(final DeviceId did,
863 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800864
Jordan Halterman9416aea2017-11-17 12:40:21 -0800865 MastershipRole myNextRole = nextRole;
866 if (myNextRole == NONE && upgradeService.isLocalActive()) {
867 try {
868 mastershipService.requestRoleFor(did).get();
869 MastershipTerm term = termService.getMastershipTerm(did);
870 if (term != null && localNodeId.equals(term.master())) {
871 myNextRole = MASTER;
872 } else {
873 myNextRole = STANDBY;
874 }
875 } catch (InterruptedException e) {
876 Thread.currentThread().interrupt();
877 log.error("Interrupted waiting for Mastership", e);
878 } catch (ExecutionException e) {
879 log.error("Encountered an error waiting for Mastership", e);
880 }
881 }
882
883 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700884 case MASTER:
885 final Device device = getDevice(did);
886 if ((device != null) && !isAvailable(did)) {
Palash Kala6c526062018-04-03 18:25:11 +0900887 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700888 }
889 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800890 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700891 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800892 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700893 // immediately failed to apply role
894 mastershipService.relinquishMastership(did);
895 // FIXME disconnect?
896 }
897 break;
898 case STANDBY:
Jordan Halterman9416aea2017-11-17 12:40:21 -0800899 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700900 if (!applyRoleAndProbe(did, STANDBY)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800901 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700902 // immediately failed to apply role
903 mastershipService.relinquishMastership(did);
904 // FIXME disconnect?
905 }
906 break;
907 case NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700908 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700909 default:
910 // should never reach here
911 log.error("You didn't see anything. I did not exist.");
912 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800913 }
914 }
915
Madan Jampani328371d2015-05-29 14:06:27 -0700916 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700917 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700918 // Don't care if backup list changed.
919 return;
920 }
Madan Jampani328371d2015-05-29 14:06:27 -0700921 final DeviceId did = event.subject();
922
923 // myRole suggested by MastershipService
924 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700925 if (event.type() == MastershipEvent.Type.SUSPENDED) {
926 myNextRole = NONE; // FIXME STANDBY OR NONE?
927 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700928 // confirm latest info
929 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800930 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700931 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700932 myNextRole = MASTER;
933 } else {
934 myNextRole = STANDBY;
935 }
936 } else if (event.roleInfo().backups().contains(localNodeId)) {
937 myNextRole = STANDBY;
938 } else {
939 myNextRole = NONE;
940 }
941
Madan Jampani328371d2015-05-29 14:06:27 -0700942 final boolean isReachable = isReachable(did);
943 if (!isReachable) {
944 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800945 if (mastershipService.getLocalRole(did) == NONE) {
946 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700947 + "but this node cannot reach the device "
948 + "and role is already None. Ignoring request.",
949 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800950 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700951 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700952 + "but this node cannot reach the device. "
953 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800954 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700955 mastershipService.relinquishMastership(did);
956 }
957 return;
958 }
959
960 // device is connected to this node:
961 if (store.getDevice(did) != null) {
962 reassertRole(did, myNextRole);
963 } else {
964 log.debug("Device is not yet/no longer in the store: {}", did);
965 }
966 }
967
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800968 // Intercepts mastership events
969 private class InternalMastershipListener implements MastershipListener {
970
tomb41d1ac2014-09-24 01:51:24 -0700971 @Override
972 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800973 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700974 try {
975 handleMastershipEvent(event);
976 } catch (Exception e) {
977 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700978 }
Madan Jampani328371d2015-05-29 14:06:27 -0700979 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700980 }
tomb41d1ac2014-09-24 01:51:24 -0700981 }
tomf80c9722014-09-24 14:49:18 -0700982
983 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700984 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700985 @Override
986 public void notify(DeviceEvent event) {
987 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +0100988 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
989 deviceLocalStatus.remove(event.subject().id());
990 }
tomf80c9722014-09-24 14:49:18 -0700991 }
992 }
samuel738dfaf2015-07-11 11:08:57 +0800993
994 @Override
995 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900996 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800997 Set<Device> results = new HashSet<>();
998 Iterable<Device> devices = store.getDevices();
999 if (devices != null) {
1000 devices.forEach(d -> {
1001 if (type.equals(d.type())) {
1002 results.add(d);
1003 }
1004 });
1005 }
1006 return results;
1007 }
1008
1009 @Override
1010 public Iterable<Device> getAvailableDevices(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> availableDevices = store.getAvailableDevices();
1014 if (availableDevices != null) {
1015 availableDevices.forEach(d -> {
1016 if (type.equals(d.type())) {
1017 results.add(d);
1018 }
1019 });
1020 }
1021 return results;
1022 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001023
1024 private class InternalNetworkConfigListener implements NetworkConfigListener {
1025 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001026 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001027 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
1028 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
1029 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001030 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001031 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001032 || event.configClass().equals(DeviceAnnotationConfig.class))
1033 && mastershipService.isLocalMaster((DeviceId) event.subject());
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001034 }
1035
1036 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001037 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001038 DeviceEvent de = null;
1039 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001040 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001041 DeviceId did = (DeviceId) event.subject();
1042 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001043 BasicDeviceConfig cfg =
1044 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001045
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001046 if (!isAllowed(cfg)) {
1047 kickOutBadDevice(did);
1048 } else {
1049 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001050 DeviceDescription desc =
1051 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001052 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001053 if (desc != null && dp != null) {
1054 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001055 }
1056 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001057 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1058 DeviceId did = (DeviceId) event.subject();
1059 DeviceProvider dp = getProvider(did);
1060 if (!event.config().isPresent() ||
1061 getDevice(did) == null || dp == null) {
1062 // sanity check failed, ignore
1063 return;
1064 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001065 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001066 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001067 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1068 .collect(Collectors.toList());
1069 complete.addAll(portConfig.portDescriptions());
1070 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001071 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1072 DeviceId did = (DeviceId) event.subject();
1073 DeviceProvider dp = getProvider(did);
1074 Device dev = getDevice(did);
1075 DeviceDescription desc =
1076 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1077 Optional<Config> prevConfig = event.prevConfig();
1078 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1079 if (desc != null && dp != null) {
1080 de = store.createOrUpdateDevice(dp.id(), did, desc);
1081 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001082 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001083 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001084 DeviceId did = cpt.deviceId();
1085 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001086
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001087 // Note: assuming PortOperator can modify existing port,
1088 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001089 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001090 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1091 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001092 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001093 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001094 }
1095
1096 if (de != null) {
1097 post(de);
1098 }
1099 }
1100
Simon Hunt8f60ff82017-04-24 17:19:30 -07001101 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001102 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001103 Device badDevice = getDevice(deviceId);
1104 if (badDevice != null) {
1105 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001106 }
1107 }
1108 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001109
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001110 @Override
1111 @SafeVarargs
1112 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001113 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001114 checkNotNull(portOp);
1115
1116 portOp.bindService(networkConfigService);
1117
1118 // update both portOpsIndex and portOps
1119 synchronized (portOpsIndex) {
1120 for (Class<? extends Config<ConnectPoint>> config : configs) {
1121 portOpsIndex.put(config, portOp);
1122 }
1123
1124 portOps.add(portOp);
1125 }
1126
1127 // TODO: Should we be applying to all existing Ports?
1128 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001129 .map(Device::id)
1130 .filter(mastershipService::isLocalMaster)
1131 // for each locally managed Device, update all port descriptions
1132 .map(did -> {
1133 ProviderId pid = Optional.ofNullable(getProvider(did))
1134 .map(Provider::id)
1135 .orElse(null);
1136 if (pid == null) {
1137 log.warn("Provider not found for {}", did);
1138 return ImmutableList.<DeviceEvent>of();
1139 }
1140 List<PortDescription> pds
1141 = store.getPortDescriptions(pid, did)
1142 .map(pdesc -> applyAllPortOps(did, pdesc))
1143 .collect(Collectors.toList());
1144 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001145 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001146 // ..and port port update event if necessary
1147 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001148 }
1149
1150 @Override
1151 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1152 checkNotNull(portOp);
1153
1154
1155 // remove all portOp
1156 synchronized (portOpsIndex) {
1157 portOps.remove(portOp);
1158
1159 // had to do this since COWArrayList iterator doesn't support remove
1160 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1161 }
1162
1163 }
1164
1165 /**
1166 * Merges the appropriate PortConfig with the description.
1167 *
1168 * @param did ID of the Device where the port is attached
1169 * @param desc {@link PortDescription}
1170 * @return merged {@link PortDescription}
1171 */
1172 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1173 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1174 }
1175
1176 /**
1177 * Merges the appropriate PortConfig with the description.
1178 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001179 * @param cpt ConnectPoint where the port is attached
1180 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001181 * @return merged {@link PortDescription}
1182 */
1183 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1184 PortDescription work = desc;
1185 for (PortConfigOperator portOp : portOps) {
1186 work = portOp.combine(cpt, work);
1187 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001188 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001189 }
1190
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001191 /**
1192 * Port Enable/Disable message sent to the device's MASTER node.
1193 */
1194 private class InternalPortUpDownEvent {
1195 private final DeviceId deviceId;
1196 private final PortNumber portNumber;
1197 private final boolean enable;
1198
1199 protected InternalPortUpDownEvent(
1200 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1201 this.deviceId = deviceId;
1202 this.portNumber = portNumber;
1203 this.enable = enable;
1204 }
1205
1206 public DeviceId deviceId() {
1207 return deviceId;
1208 }
1209 public PortNumber portNumber() {
1210 return portNumber;
1211 }
1212 public boolean isEnable() {
1213 return enable;
1214 }
1215
1216 protected InternalPortUpDownEvent() {
1217 this.deviceId = null;
1218 this.portNumber = null;
1219 this.enable = false;
1220 }
1221 }
tomd3097b02014-08-26 10:40:29 -07001222}