blob: caab65bab56e95bd89508e2cea4c9d2818f78484 [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
423 if (!masterId.equals(localNodeId)) {
424 //Send the request to the master node for the device
425 log.info("Device {} is managed by {}, forwarding the request to the MASTER",
426 deviceId, masterId);
427 communicationService.unicast(
428 new InternalPortUpDownEvent(deviceId, portNumber, enable),
429 PORT_UPDOWN_SUBJECT,
430 SERIALIZER::encode,
431 masterId).whenComplete((r, error) -> {
432 if (error != null) {
433 log.warn("Failed to send packet-updown-req to {}", masterId, error);
434 }
435 });
436 } else {
437 changePortStateAtMaster(deviceId, portNumber, enable);
438 }
439 }
440
441 @Override
samuele1fa7322015-07-14 16:35:16 +0800442 protected DeviceProviderService createProviderService(
443 DeviceProvider provider) {
tom7869ad92014-09-09 14:32:08 -0700444 return new InternalDeviceProviderService(provider);
445 }
446
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800447 /**
448 * Checks if all the reachable devices have a valid mastership role.
449 */
450 private void mastershipCheck() {
451 log.debug("Checking mastership");
452 for (Device device : getDevices()) {
453 final DeviceId deviceId = device.id();
Ray Milkeyc7104672016-08-31 12:04:34 -0700454 MastershipRole myRole = mastershipService.getLocalRole(deviceId);
455 log.trace("Checking device {}. Current role is {}", deviceId, myRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800456 if (!isReachable(deviceId)) {
Ray Milkeyc7104672016-08-31 12:04:34 -0700457 if (myRole != NONE) {
helenyrwufd296b62016-06-22 17:43:02 -0700458 // can't be master if device is not reachable
459 try {
Ray Milkeyc7104672016-08-31 12:04:34 -0700460 if (myRole == MASTER) {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100461 log.info("Local Role {}, Marking unreachable device {} offline", MASTER, deviceId);
Ray Milkeyc7104672016-08-31 12:04:34 -0700462 post(store.markOffline(deviceId));
463 }
helenyrwufd296b62016-06-22 17:43:02 -0700464 //relinquish master role and ability to be backup.
465 mastershipService.relinquishMastership(deviceId).get();
466 } catch (InterruptedException e) {
467 log.warn("Interrupted while reliquishing role for {}", deviceId);
468 Thread.currentThread().interrupt();
469 } catch (ExecutionException e) {
470 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
471 }
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530472 } else {
Andrea Campanellae319dc22018-01-18 12:51:04 +0100473 // check if the device has master and is available to the store, if not, mark it offline
Bharath Thiruveedula651a7da2016-12-13 02:52:50 +0530474 // only the nodes which has mastership role can mark any device offline.
Andrea Campanellae319dc22018-01-18 12:51:04 +0100475 // This condition should never be hit unless in a device removed phase for NONE mastership roles.
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800476 NodeId master = mastershipService.getMasterFor(deviceId);
Andrea Campanellae319dc22018-01-18 12:51:04 +0100477 if (master == null && isAvailable(deviceId)) {
Jordan Haltermanbc0308f2017-11-29 15:37:34 -0800478 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
479 roleFuture.thenAccept(role -> {
480 MastershipTerm term = termService.getMastershipTerm(deviceId);
481 if (term != null && localNodeId.equals(term.master())) {
482 log.info("Marking unreachable device {} offline", deviceId);
483 post(store.markOffline(deviceId));
484 } else {
485 log.info("Failed marking {} offline. {}", deviceId, role);
486 }
487 mastershipService.relinquishMastership(deviceId);
488 });
489 }
helenyrwufd296b62016-06-22 17:43:02 -0700490 }
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800491 continue;
492 }
493
Ray Milkeyc7104672016-08-31 12:04:34 -0700494 if (myRole != NONE) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800495 continue;
496 }
497
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700498 log.info("{} is reachable but did not have a valid role, reasserting", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800499
500 // isReachable but was not MASTER or STANDBY, get a role and apply
501 // Note: NONE triggers request to MastershipService
Jordan Halterman9416aea2017-11-17 12:40:21 -0800502 reassertRole(deviceId, NONE);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800503 }
504 }
505
tomd3097b02014-08-26 10:40:29 -0700506 // Personalized device provider service issued to the supplied provider.
tomdc361b62014-09-09 20:36:52 -0700507 private class InternalDeviceProviderService
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700508 extends AbstractProviderService<DeviceProvider>
509 implements DeviceProviderService {
tomd3097b02014-08-26 10:40:29 -0700510
tomcfde0622014-09-09 11:02:42 -0700511 InternalDeviceProviderService(DeviceProvider provider) {
tomd3097b02014-08-26 10:40:29 -0700512 super(provider);
513 }
514
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700515 /**
516 * Apply role in reaction to provider event.
517 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700518 * @param deviceId device identifier
519 * @param newRole new role to apply to the device
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700520 * @return true if the request was sent to provider
521 */
522 private boolean applyRole(DeviceId deviceId, MastershipRole newRole) {
523
524 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800525 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700526 return true;
527 }
528
529 DeviceProvider provider = provider();
530 if (provider == null) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700531 log.warn("Provider for {} was not found. Cannot apply role {}",
532 deviceId, newRole);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700533 return false;
534 }
Yuta HIGUCHI54815322014-10-31 23:17:08 -0700535 provider.roleChanged(deviceId, newRole);
536 // not triggering probe when triggered by provider service event
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700537 return true;
538 }
539
tomd3097b02014-08-26 10:40:29 -0700540 @Override
alshabibb7b40632014-09-28 21:30:00 -0700541 public void deviceConnected(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700542 DeviceDescription deviceDescription) {
tom32f66842014-08-27 19:27:47 -0700543 checkNotNull(deviceId, DEVICE_ID_NULL);
544 checkNotNull(deviceDescription, DEVICE_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700545 checkValidity();
Yuta HIGUCHI24b2e2a2014-10-07 15:53:57 -0700546
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700547 deviceLocalStatus.put(deviceId, new LocalStatus(true, Instant.now()));
Saurav Dasd5ec9e92017-01-17 10:40:18 -0800548
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700549 BasicDeviceConfig cfg = networkConfigService.getConfig(deviceId, BasicDeviceConfig.class);
550 if (!isAllowed(cfg)) {
551 log.warn("Device {} is not allowed", deviceId);
552 return;
553 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200554 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700555 // Generate updated description and establish my Role
556 deviceDescription = BasicDeviceOperator.combine(cfg, deviceDescription);
jaegonkim1c1f0c22018-01-28 22:20:42 +0900557 DeviceAnnotationConfig annoConfig = networkConfigService.getConfig(deviceId, DeviceAnnotationConfig.class);
558 if (annoConfig != null) {
559 deviceDescription = deviceAnnotationOp.combine(deviceId, deviceDescription, Optional.of(annoConfig));
560 }
561
Yi Tseng7be4e672017-12-05 15:03:26 -0800562 DeviceEvent event = store.createOrUpdateDevice(provider().id(), deviceId,
563 deviceDescription);
Madan Jampani565a66a2015-07-25 17:01:13 -0700564 Futures.getUnchecked(mastershipService.requestRoleFor(deviceId)
Simon Huntffbad3b2017-05-16 15:37:51 -0700565 .thenAccept(role -> {
566 log.info("Local role is {} for {}", role, deviceId);
567 applyRole(deviceId, role);
568 }));
HIGUCHI Yuta11530fb2015-05-27 13:10:20 -0700569
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200570 if (portConfig != null) {
571 //updating the ports if configration exists
572 List<PortDescription> complete = store.getPortDescriptions(provider().id(), deviceId)
573 .collect(Collectors.toList());
574 complete.addAll(portConfig.portDescriptions());
575 List<PortDescription> portDescriptions = complete.stream()
576 .map(e -> applyAllPortOps(deviceId, e))
577 .collect(Collectors.toList());
578 store.updatePorts(provider().id(), deviceId, portDescriptions);
579 }
580
helenyrwufd296b62016-06-22 17:43:02 -0700581 if (deviceDescription.isDefaultAvailable()) {
582 log.info("Device {} connected", deviceId);
583 } else {
584 log.info("Device {} registered", deviceId);
585 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200586
tom80c0e5e2014-09-08 18:08:58 -0700587 if (event != null) {
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700588 log.trace("event: {} {}", event.type(), event);
tom568581d2014-09-08 20:13:36 -0700589 post(event);
tom80c0e5e2014-09-08 18:08:58 -0700590 }
tomd3097b02014-08-26 10:40:29 -0700591 }
592
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700593 private PortDescription ensurePortEnabledState(PortDescription desc, boolean enabled) {
594 if (desc.isEnabled() != enabled) {
Yuta HIGUCHI2b1935d2018-03-01 21:41:06 -0800595 return DefaultPortDescription.builder(desc)
596 .isEnabled(enabled)
597 .build();
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700598 }
599 return desc;
600 }
601
tomd3097b02014-08-26 10:40:29 -0700602 @Override
603 public void deviceDisconnected(DeviceId deviceId) {
tom32f66842014-08-27 19:27:47 -0700604 checkNotNull(deviceId, DEVICE_ID_NULL);
tomeadbb462014-09-07 16:10:19 -0700605 checkValidity();
Yuta HIGUCHI0c47d532017-08-18 23:16:35 -0700606 deviceLocalStatus.put(deviceId, new LocalStatus(false, Instant.now()));
Yuta HIGUCHI2d3cd312014-10-31 11:38:04 -0700607 log.info("Device {} disconnected from this node", deviceId);
Ayaka Koshibed9f693e2014-09-29 18:04:54 -0700608
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700609 List<PortDescription> descs = store.getPortDescriptions(provider().id(), deviceId)
610 .map(desc -> ensurePortEnabledState(desc, false))
611 .collect(Collectors.toList());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300612
alshabibafc514a2014-12-01 14:44:05 -0800613 store.updatePorts(this.provider().id(), deviceId, descs);
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700614 try {
Madan Jampani565a66a2015-07-25 17:01:13 -0700615 if (mastershipService.isLocalMaster(deviceId)) {
Thomas Vachuska5f429d62015-05-28 15:34:36 -0700616 post(store.markOffline(deviceId));
617 }
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700618 } catch (IllegalStateException e) {
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700619 log.warn("Failed to mark {} offline", deviceId);
620 // only the MASTER should be marking off-line in normal cases,
samuele1fa7322015-07-14 16:35:16 +0800621 // but if I was the last STANDBY connection, etc. and no one else
622 // was there to mark the device offline, this instance may need to
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700623 // temporarily request for Master Role and mark offline.
624
samuele1fa7322015-07-14 16:35:16 +0800625 //there are times when this node will correctly have mastership, BUT
626 //that isn't reflected in the ClockManager before the device disconnects.
627 //we want to let go of the device anyways, so make sure this happens.
Yuta HIGUCHI0722fb22014-10-19 01:16:33 -0700628
Yuta HIGUCHIeb24e9d2014-10-26 19:34:20 -0700629 // FIXME: Store semantics leaking out as IllegalStateException.
samuele1fa7322015-07-14 16:35:16 +0800630 // Consider revising store API to handle this scenario.
631 CompletableFuture<MastershipRole> roleFuture = mastershipService.requestRoleFor(deviceId);
Madan Jampanide003d92015-05-11 17:14:20 -0700632 roleFuture.whenComplete((role, error) -> {
samuele1fa7322015-07-14 16:35:16 +0800633 MastershipTerm term = termService.getMastershipTerm(deviceId);
634 // TODO: Move this type of check inside device clock manager, etc.
635 if (term != null && localNodeId.equals(term.master())) {
636 log.info("Retry marking {} offline", deviceId);
samuele1fa7322015-07-14 16:35:16 +0800637 post(store.markOffline(deviceId));
638 } else {
639 log.info("Failed again marking {} offline. {}", deviceId, role);
640 }
641 });
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700642 } finally {
Madan Jampanic6e574f2015-05-29 13:41:52 -0700643 try {
samuele1fa7322015-07-14 16:35:16 +0800644 //relinquish master role and ability to be backup.
Madan Jampanic6e574f2015-05-29 13:41:52 -0700645 mastershipService.relinquishMastership(deviceId).get();
646 } catch (InterruptedException e) {
samuele1fa7322015-07-14 16:35:16 +0800647 log.warn("Interrupted while reliquishing role for {}", deviceId);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700648 Thread.currentThread().interrupt();
649 } catch (ExecutionException e) {
samuele1fa7322015-07-14 16:35:16 +0800650 log.error("Exception thrown while relinquishing role for {}", deviceId, e);
Madan Jampanic6e574f2015-05-29 13:41:52 -0700651 }
tom0efbb1d2014-09-09 11:54:28 -0700652 }
tomd3097b02014-08-26 10:40:29 -0700653 }
654
655 @Override
alshabibb7b40632014-09-28 21:30:00 -0700656 public void updatePorts(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700657 List<PortDescription> portDescriptions) {
tom32f66842014-08-27 19:27:47 -0700658 checkNotNull(deviceId, DEVICE_ID_NULL);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700659 checkNotNull(portDescriptions, PORT_DESC_LIST_NULL);
tomeadbb462014-09-07 16:10:19 -0700660 checkValidity();
Madan Jampani565a66a2015-07-25 17:01:13 -0700661 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700662 // Never been a master for this device
663 // any update will be ignored.
samuele1fa7322015-07-14 16:35:16 +0800664 log.trace("Ignoring {} port updates on standby node. {}", deviceId, portDescriptions);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700665 return;
666 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +0200667 PortDescriptionsConfig portConfig = networkConfigService.getConfig(deviceId, PortDescriptionsConfig.class);
668 if (portConfig != null) {
669 //updating the ports if configration exists
670 portDescriptions.addAll(portConfig.portDescriptions());
671 }
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700672 portDescriptions = portDescriptions.stream()
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700673 .map(e -> applyAllPortOps(deviceId, e))
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700674 .collect(Collectors.toList());
Yuta HIGUCHI5f6739c2014-10-01 14:04:01 -0700675 List<DeviceEvent> events = store.updatePorts(this.provider().id(),
samuele1fa7322015-07-14 16:35:16 +0800676 deviceId, portDescriptions);
Thomas Vachuska5923b9a2016-01-26 10:52:57 -0800677 if (events != null) {
678 for (DeviceEvent event : events) {
679 post(event);
680 }
tom32f66842014-08-27 19:27:47 -0700681 }
tomd3097b02014-08-26 10:40:29 -0700682 }
683
684 @Override
alshabibb7b40632014-09-28 21:30:00 -0700685 public void portStatusChanged(DeviceId deviceId,
Thomas Vachuskad16ce182014-10-29 17:25:29 -0700686 PortDescription portDescription) {
tom32f66842014-08-27 19:27:47 -0700687 checkNotNull(deviceId, DEVICE_ID_NULL);
688 checkNotNull(portDescription, PORT_DESCRIPTION_NULL);
tomeadbb462014-09-07 16:10:19 -0700689 checkValidity();
Ayaka Koshibeb5c63a02014-10-18 18:42:27 -0700690
Madan Jampani565a66a2015-07-25 17:01:13 -0700691 if (!mastershipService.isLocalMaster(deviceId)) {
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700692 // Never been a master for this device
693 // any update will be ignored.
Sahil Lele3a0cdd52015-07-21 14:16:31 -0700694 log.trace("Ignoring {} port update on standby node. {}", deviceId,
695 portDescription);
Yuta HIGUCHI13c0b872014-10-30 18:09:22 -0700696 return;
697 }
Ray Milkey9ef22232016-07-14 12:42:37 -0700698 Device device = getDevice(deviceId);
699 if (device == null) {
700 log.trace("Device not found: {}", deviceId);
nitinanandddfa8c92017-03-24 16:14:23 +0530701 return;
Ray Milkey9ef22232016-07-14 12:42:37 -0700702 }
Rimon Ashkenazy8ebfff02016-02-01 11:56:36 +0200703 if ((Device.Type.ROADM.equals(device.type())) ||
Simon Huntffbad3b2017-05-16 15:37:51 -0700704 (Device.Type.OTN.equals(device.type()))) {
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700705 // FIXME This is ignoring all other info in portDescription given as input??
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700706 PortDescription storedPortDesc = store.getPortDescription(provider().id(),
Simon Huntffbad3b2017-05-16 15:37:51 -0700707 deviceId,
708 portDescription.portNumber());
Yuta HIGUCHI6eb00cc2016-06-10 11:55:12 -0700709 portDescription = ensurePortEnabledState(storedPortDesc,
710 portDescription.isEnabled());
Yafit Hadara9a73de2015-09-06 13:52:52 +0300711 }
712
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700713 portDescription = applyAllPortOps(deviceId, portDescription);
samuele1fa7322015-07-14 16:35:16 +0800714 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
HIGUCHI Yuta6972ae62016-05-12 19:57:46 -0700715 deviceId,
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -0700716 portDescription);
tomff7eb7c2014-09-08 12:49:03 -0700717 if (event != null) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700718 log.info("Device {} port {} status changed", deviceId, event.port().number());
tom0efbb1d2014-09-09 11:54:28 -0700719 post(event);
tomff7eb7c2014-09-08 12:49:03 -0700720 }
tomd3097b02014-08-26 10:40:29 -0700721 }
tom3f2bbd72014-09-24 12:07:58 -0700722
723 @Override
Michal Machce774332017-01-25 11:02:55 +0100724 public void deletePort(DeviceId deviceId, PortDescription basePortDescription) {
725
726 checkNotNull(deviceId, DEVICE_ID_NULL);
727 checkNotNull(basePortDescription, PORT_DESCRIPTION_NULL);
728 checkValidity();
729
730 if (!mastershipService.isLocalMaster(deviceId)) {
731 // Never been a master for this device
732 // any update will be ignored.
733 log.trace("Ignoring {} port update on standby node. {}", deviceId,
734 basePortDescription);
735 return;
736 }
737
738 Device device = getDevice(deviceId);
739 if (device == null) {
740 log.trace("Device not found: {}", deviceId);
741 }
742
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800743 PortDescription newPortDescription = DefaultPortDescription.builder(basePortDescription)
744 .isRemoved(true)
745 .build();
746
Michal Machce774332017-01-25 11:02:55 +0100747 final DeviceEvent event = store.updatePortStatus(this.provider().id(),
748 deviceId,
749 newPortDescription);
750 if (event != null) {
751 log.info("Device {} port {} status changed", deviceId, event.port().number());
752 post(event);
753 }
754 }
755
756 @Override
samuele1fa7322015-07-14 16:35:16 +0800757 public void receivedRoleReply(DeviceId deviceId, MastershipRole requested,
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700758 MastershipRole response) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700759 // Several things can happen here:
760 // 1. request and response match
761 // 2. request and response don't match
762 // 3. MastershipRole and requested match (and 1 or 2 are true)
763 // 4. MastershipRole and requested don't match (and 1 or 2 are true)
764 //
765 // 2, 4, and 3 with case 2 are failure modes.
766
tom3f2bbd72014-09-24 12:07:58 -0700767 // FIXME: implement response to this notification
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700768
Madan Jampanif2af7712015-05-29 18:43:52 -0700769 log.debug("got reply to a role request for {}: asked for {}, and got {}",
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700770 deviceId, requested, response);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700771
772 if (requested == null && response == null) {
samuele1fa7322015-07-14 16:35:16 +0800773 // something was off with DeviceProvider, maybe check channel too?
Shashikanth VH387a1ca2016-02-09 20:35:21 +0530774 log.warn("Failed to assert role onto Device {}", deviceId);
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700775 mastershipService.relinquishMastership(deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700776 return;
Yuta HIGUCHIcf603902014-10-07 23:04:32 -0700777 }
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700778
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700779 if (Objects.equals(requested, response)) {
samuele1fa7322015-07-14 16:35:16 +0800780 if (Objects.equals(requested, mastershipService.getLocalRole(deviceId))) {
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700781 return;
782 } else {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800783 log.warn("Role mismatch on {}. set to {}, but store demands {}",
784 deviceId, response, mastershipService.getLocalRole(deviceId));
785 // roleManager got the device to comply, but doesn't agree with
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700786 // the store; use the store's view, then try to reassert.
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800787 backgroundService.execute(() -> reassertRole(deviceId, mastershipService.getLocalRole(deviceId)));
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800788 return;
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700789 }
790 } else {
791 // we didn't get back what we asked for. Reelect someone else.
samuele1fa7322015-07-14 16:35:16 +0800792 log.warn("Failed to assert role [{}] onto Device {}", response, deviceId);
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700793 if (response == MastershipRole.MASTER) {
794 mastershipService.relinquishMastership(deviceId);
795 // TODO: Shouldn't we be triggering event?
samuele1fa7322015-07-14 16:35:16 +0800796 //final Device device = getDevice(deviceId);
797 //post(new DeviceEvent(DEVICE_MASTERSHIP_CHANGED, device));
Ayaka Koshibe3ef2b0d2014-10-31 13:58:27 -0700798 }
799 }
tom3f2bbd72014-09-24 12:07:58 -0700800 }
sangho538108b2015-04-08 14:29:20 -0700801
802 @Override
samuele1fa7322015-07-14 16:35:16 +0800803 public void updatePortStatistics(DeviceId deviceId, Collection<PortStatistics> portStatistics) {
sangho538108b2015-04-08 14:29:20 -0700804 checkNotNull(deviceId, DEVICE_ID_NULL);
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700805 checkNotNull(portStatistics, "Port statistics list cannot be null");
sangho538108b2015-04-08 14:29:20 -0700806 checkValidity();
807
samuele1fa7322015-07-14 16:35:16 +0800808 DeviceEvent event = store.updatePortStatistics(this.provider().id(),
809 deviceId, portStatistics);
sangho538108b2015-04-08 14:29:20 -0700810 post(event);
811 }
tomd3097b02014-08-26 10:40:29 -0700812 }
tom32f66842014-08-27 19:27:47 -0700813
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -0700814 // by default allowed, otherwise check flag
815 private boolean isAllowed(BasicDeviceConfig cfg) {
816 return (cfg == null || cfg.isAllowed());
817 }
818
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800819 // Applies the specified role to the device; ignores NONE
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700820
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800821 /**
822 * Apply role to device and send probe if MASTER.
823 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700824 * @param deviceId device identifier
825 * @param newRole new role to apply to the device
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800826 * @return true if the request was sent to provider
827 */
828 private boolean applyRoleAndProbe(DeviceId deviceId, MastershipRole newRole) {
829 if (newRole.equals(MastershipRole.NONE)) {
samuele1fa7322015-07-14 16:35:16 +0800830 //no-op
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700831 return true;
832 }
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700833
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800834 DeviceProvider provider = getProvider(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800835 if (provider == null) {
samuele1fa7322015-07-14 16:35:16 +0800836 log.warn("Provider for {} was not found. Cannot apply role {}", deviceId, newRole);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800837 return false;
838 }
839 provider.roleChanged(deviceId, newRole);
840
841 if (newRole.equals(MastershipRole.MASTER)) {
HIGUCHI Yuta1979f552015-12-28 21:24:26 -0800842 log.debug("sent TriggerProbe({})", deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800843 // only trigger event when request was sent to provider
Ayaka Koshibe78bcbc12014-11-19 14:28:58 -0800844 provider.triggerProbe(deviceId);
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800845 }
846 return true;
847 }
848
849 /**
Harold Huangff6e1e62017-11-09 16:25:36 +0800850 * Reassert role for specified device connected to this node.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800851 *
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700852 * @param did device identifier
853 * @param nextRole role to apply. If NONE is specified,
854 * it will ask mastership service for a role and apply it.
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800855 */
samuele1fa7322015-07-14 16:35:16 +0800856 private void reassertRole(final DeviceId did,
857 final MastershipRole nextRole) {
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800858
Jordan Halterman9416aea2017-11-17 12:40:21 -0800859 MastershipRole myNextRole = nextRole;
860 if (myNextRole == NONE && upgradeService.isLocalActive()) {
861 try {
862 mastershipService.requestRoleFor(did).get();
863 MastershipTerm term = termService.getMastershipTerm(did);
864 if (term != null && localNodeId.equals(term.master())) {
865 myNextRole = MASTER;
866 } else {
867 myNextRole = STANDBY;
868 }
869 } catch (InterruptedException e) {
870 Thread.currentThread().interrupt();
871 log.error("Interrupted waiting for Mastership", e);
872 } catch (ExecutionException e) {
873 log.error("Encountered an error waiting for Mastership", e);
874 }
875 }
876
877 switch (myNextRole) {
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700878 case MASTER:
879 final Device device = getDevice(did);
880 if ((device != null) && !isAvailable(did)) {
Palash Kala6c526062018-04-03 18:25:11 +0900881 post(store.markOnline(did));
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700882 }
883 // TODO: should apply role only if there is mismatch
Jordan Halterman9416aea2017-11-17 12:40:21 -0800884 log.debug("Applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700885 if (!applyRoleAndProbe(did, MASTER)) {
Jordan Halterman9416aea2017-11-17 12:40:21 -0800886 log.warn("Unsuccessful applying role {} to {}", myNextRole, did);
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700887 // immediately failed to apply role
888 mastershipService.relinquishMastership(did);
889 // FIXME disconnect?
890 }
891 break;
892 case STANDBY:
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, STANDBY)) {
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 NONE:
Jordan Halterman980a8c12017-09-22 18:01:19 -0700902 break;
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700903 default:
904 // should never reach here
905 log.error("You didn't see anything. I did not exist.");
906 break;
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800907 }
908 }
909
Madan Jampani328371d2015-05-29 14:06:27 -0700910 private void handleMastershipEvent(MastershipEvent event) {
Jon Hall7a8bfc62016-05-26 17:59:04 -0700911 if (event.type() == MastershipEvent.Type.BACKUPS_CHANGED) {
Madan Jampani328371d2015-05-29 14:06:27 -0700912 // Don't care if backup list changed.
913 return;
914 }
Madan Jampani328371d2015-05-29 14:06:27 -0700915 final DeviceId did = event.subject();
916
917 // myRole suggested by MastershipService
918 MastershipRole myNextRole;
Jon Hall7a8bfc62016-05-26 17:59:04 -0700919 if (event.type() == MastershipEvent.Type.SUSPENDED) {
920 myNextRole = NONE; // FIXME STANDBY OR NONE?
921 } else if (localNodeId.equals(event.roleInfo().master())) {
Madan Jampani328371d2015-05-29 14:06:27 -0700922 // confirm latest info
923 MastershipTerm term = termService.getMastershipTerm(did);
samuele1fa7322015-07-14 16:35:16 +0800924 final boolean iHaveControl = term != null && localNodeId.equals(term.master());
Madan Jampani328371d2015-05-29 14:06:27 -0700925 if (iHaveControl) {
Madan Jampani328371d2015-05-29 14:06:27 -0700926 myNextRole = MASTER;
927 } else {
928 myNextRole = STANDBY;
929 }
930 } else if (event.roleInfo().backups().contains(localNodeId)) {
931 myNextRole = STANDBY;
932 } else {
933 myNextRole = NONE;
934 }
935
Madan Jampani328371d2015-05-29 14:06:27 -0700936 final boolean isReachable = isReachable(did);
937 if (!isReachable) {
938 // device is not connected to this node
Jon Halla90c44c2017-01-24 16:02:07 -0800939 if (mastershipService.getLocalRole(did) == NONE) {
940 log.debug("Node was instructed to be {} role for {}, "
Simon Huntffbad3b2017-05-16 15:37:51 -0700941 + "but this node cannot reach the device "
942 + "and role is already None. Ignoring request.",
943 myNextRole, did);
Jon Halla90c44c2017-01-24 16:02:07 -0800944 } else if (myNextRole != NONE) {
Madan Jampani328371d2015-05-29 14:06:27 -0700945 log.warn("Node was instructed to be {} role for {}, "
Thomas Vachuska42e8cce2015-07-29 19:25:18 -0700946 + "but this node cannot reach the device. "
947 + "Relinquishing role. ",
samuele1fa7322015-07-14 16:35:16 +0800948 myNextRole, did);
Madan Jampani328371d2015-05-29 14:06:27 -0700949 mastershipService.relinquishMastership(did);
950 }
951 return;
952 }
953
954 // device is connected to this node:
955 if (store.getDevice(did) != null) {
956 reassertRole(did, myNextRole);
957 } else {
958 log.debug("Device is not yet/no longer in the store: {}", did);
959 }
960 }
961
Yuta HIGUCHI63323fd2014-11-11 12:16:58 -0800962 // Intercepts mastership events
963 private class InternalMastershipListener implements MastershipListener {
964
tomb41d1ac2014-09-24 01:51:24 -0700965 @Override
966 public void event(MastershipEvent event) {
HIGUCHI Yuta060da9a2016-03-11 19:16:35 -0800967 backgroundService.execute(() -> {
Madan Jampani328371d2015-05-29 14:06:27 -0700968 try {
969 handleMastershipEvent(event);
970 } catch (Exception e) {
971 log.warn("Failed to handle {}", event, e);
Yuta HIGUCHId26354d2014-10-31 14:14:38 -0700972 }
Madan Jampani328371d2015-05-29 14:06:27 -0700973 });
Ayaka Koshibe317245a2014-10-29 00:34:43 -0700974 }
tomb41d1ac2014-09-24 01:51:24 -0700975 }
tomf80c9722014-09-24 14:49:18 -0700976
977 // Store delegate to re-post events emitted from the store.
Thomas Vachuskab17c41f2015-05-19 11:16:05 -0700978 private class InternalStoreDelegate implements DeviceStoreDelegate {
tomf80c9722014-09-24 14:49:18 -0700979 @Override
980 public void notify(DeviceEvent event) {
981 post(event);
Rafał Szalecki9fb87f62017-12-06 15:06:09 +0100982 if (event.type().equals(DeviceEvent.Type.DEVICE_REMOVED)) {
983 deviceLocalStatus.remove(event.subject().id());
984 }
tomf80c9722014-09-24 14:49:18 -0700985 }
986 }
samuel738dfaf2015-07-11 11:08:57 +0800987
988 @Override
989 public Iterable<Device> getDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +0900990 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +0800991 Set<Device> results = new HashSet<>();
992 Iterable<Device> devices = store.getDevices();
993 if (devices != null) {
994 devices.forEach(d -> {
995 if (type.equals(d.type())) {
996 results.add(d);
997 }
998 });
999 }
1000 return results;
1001 }
1002
1003 @Override
1004 public Iterable<Device> getAvailableDevices(Type type) {
Changhoon Yoonb856b812015-08-10 03:47:19 +09001005 checkPermission(DEVICE_READ);
samuel738dfaf2015-07-11 11:08:57 +08001006 Set<Device> results = new HashSet<>();
1007 Iterable<Device> availableDevices = store.getAvailableDevices();
1008 if (availableDevices != null) {
1009 availableDevices.forEach(d -> {
1010 if (type.equals(d.type())) {
1011 results.add(d);
1012 }
1013 });
1014 }
1015 return results;
1016 }
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001017
1018 private class InternalNetworkConfigListener implements NetworkConfigListener {
1019 @Override
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001020 public boolean isRelevant(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001021 return (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED
1022 || event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED)
1023 && (event.configClass().equals(BasicDeviceConfig.class)
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001024 || portOpsIndex.containsKey(event.configClass())
Palash Kalaa06a6162017-11-15 20:42:40 +09001025 || event.configClass().equals(PortDescriptionsConfig.class)
Thomas Vachuskaf131e592018-05-07 11:52:14 -07001026 || event.configClass().equals(DeviceAnnotationConfig.class))
1027 && mastershipService.isLocalMaster((DeviceId) event.subject());
Thomas Vachuska42e8cce2015-07-29 19:25:18 -07001028 }
1029
1030 @Override
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001031 public void event(NetworkConfigEvent event) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001032 DeviceEvent de = null;
1033 if (event.configClass().equals(BasicDeviceConfig.class)) {
Thomas Vachuska138de8b2016-01-11 21:31:38 -08001034 log.debug("Detected device network config event {}", event.type());
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001035 DeviceId did = (DeviceId) event.subject();
1036 DeviceProvider dp = getProvider(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001037 BasicDeviceConfig cfg =
1038 networkConfigService.getConfig(did, BasicDeviceConfig.class);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001039
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001040 if (!isAllowed(cfg)) {
1041 kickOutBadDevice(did);
1042 } else {
1043 Device dev = getDevice(did);
Simon Huntffbad3b2017-05-16 15:37:51 -07001044 DeviceDescription desc =
1045 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001046 desc = BasicDeviceOperator.combine(cfg, desc);
Simon Huntffbad3b2017-05-16 15:37:51 -07001047 if (desc != null && dp != null) {
1048 de = store.createOrUpdateDevice(dp.id(), did, desc);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001049 }
1050 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001051 } else if (event.configClass().equals(PortDescriptionsConfig.class)) {
1052 DeviceId did = (DeviceId) event.subject();
1053 DeviceProvider dp = getProvider(did);
1054 if (!event.config().isPresent() ||
1055 getDevice(did) == null || dp == null) {
1056 // sanity check failed, ignore
1057 return;
1058 }
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001059 PortDescriptionsConfig portConfig = (PortDescriptionsConfig) event.config().get();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001060 //updating the ports if configuration exists
Andrea Campanella75ef9f52017-07-27 20:14:32 +02001061 List<PortDescription> complete = store.getPortDescriptions(dp.id(), did)
1062 .collect(Collectors.toList());
1063 complete.addAll(portConfig.portDescriptions());
1064 store.updatePorts(dp.id(), did, complete);
Palash Kalaa06a6162017-11-15 20:42:40 +09001065 } else if (event.configClass().equals(DeviceAnnotationConfig.class)) {
1066 DeviceId did = (DeviceId) event.subject();
1067 DeviceProvider dp = getProvider(did);
1068 Device dev = getDevice(did);
1069 DeviceDescription desc =
1070 (dev == null) ? null : BasicDeviceOperator.descriptionOf(dev);
1071 Optional<Config> prevConfig = event.prevConfig();
1072 desc = deviceAnnotationOp.combine(did, desc, prevConfig);
1073 if (desc != null && dp != null) {
1074 de = store.createOrUpdateDevice(dp.id(), did, desc);
1075 }
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001076 } else if (portOpsIndex.containsKey(event.configClass())) {
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001077 ConnectPoint cpt = (ConnectPoint) event.subject();
Yuta HIGUCHI1d4b3aa2017-08-09 15:10:18 -07001078 DeviceId did = cpt.deviceId();
1079 DeviceProvider dp = getProvider(did);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001080
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001081 // Note: assuming PortOperator can modify existing port,
1082 // but cannot add new port purely from Config.
Simon Huntffbad3b2017-05-16 15:37:51 -07001083 de = Optional.ofNullable(dp)
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001084 .map(provider -> store.getPortDescription(provider.id(), did, cpt.port()))
1085 .map(desc -> applyAllPortOps(cpt, desc))
Simon Huntffbad3b2017-05-16 15:37:51 -07001086 .map(desc -> store.updatePortStatus(dp.id(), did, desc))
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001087 .orElse(null);
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001088 }
1089
1090 if (de != null) {
1091 post(de);
1092 }
1093 }
1094
Simon Hunt8f60ff82017-04-24 17:19:30 -07001095 // removes the specified device if it exists
Ayaka Koshibed0ab3c02015-09-04 15:43:46 -07001096 private void kickOutBadDevice(DeviceId deviceId) {
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001097 Device badDevice = getDevice(deviceId);
1098 if (badDevice != null) {
1099 removeDevice(deviceId);
Sahil Lele3a0cdd52015-07-21 14:16:31 -07001100 }
1101 }
1102 }
Saurav Dasa2d37502016-03-25 17:50:40 -07001103
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001104 @Override
1105 @SafeVarargs
1106 public final void registerPortConfigOperator(PortConfigOperator portOp,
Simon Huntffbad3b2017-05-16 15:37:51 -07001107 Class<? extends Config<ConnectPoint>>... configs) {
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001108 checkNotNull(portOp);
1109
1110 portOp.bindService(networkConfigService);
1111
1112 // update both portOpsIndex and portOps
1113 synchronized (portOpsIndex) {
1114 for (Class<? extends Config<ConnectPoint>> config : configs) {
1115 portOpsIndex.put(config, portOp);
1116 }
1117
1118 portOps.add(portOp);
1119 }
1120
1121 // TODO: Should we be applying to all existing Ports?
1122 Tools.stream(store.getAvailableDevices())
Simon Huntffbad3b2017-05-16 15:37:51 -07001123 .map(Device::id)
1124 .filter(mastershipService::isLocalMaster)
1125 // for each locally managed Device, update all port descriptions
1126 .map(did -> {
1127 ProviderId pid = Optional.ofNullable(getProvider(did))
1128 .map(Provider::id)
1129 .orElse(null);
1130 if (pid == null) {
1131 log.warn("Provider not found for {}", did);
1132 return ImmutableList.<DeviceEvent>of();
1133 }
1134 List<PortDescription> pds
1135 = store.getPortDescriptions(pid, did)
1136 .map(pdesc -> applyAllPortOps(did, pdesc))
1137 .collect(Collectors.toList());
1138 return store.updatePorts(pid, did, pds);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001139 })
Simon Huntffbad3b2017-05-16 15:37:51 -07001140 // ..and port port update event if necessary
1141 .forEach(evts -> evts.forEach(this::post));
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001142 }
1143
1144 @Override
1145 public void unregisterPortConfigOperator(PortConfigOperator portOp) {
1146 checkNotNull(portOp);
1147
1148
1149 // remove all portOp
1150 synchronized (portOpsIndex) {
1151 portOps.remove(portOp);
1152
1153 // had to do this since COWArrayList iterator doesn't support remove
1154 portOpsIndex.keySet().forEach(key -> portOpsIndex.remove(key, portOp));
1155 }
1156
1157 }
1158
1159 /**
1160 * Merges the appropriate PortConfig with the description.
1161 *
1162 * @param did ID of the Device where the port is attached
1163 * @param desc {@link PortDescription}
1164 * @return merged {@link PortDescription}
1165 */
1166 private PortDescription applyAllPortOps(DeviceId did, PortDescription desc) {
1167 return applyAllPortOps(new ConnectPoint(did, desc.portNumber()), desc);
1168 }
1169
1170 /**
1171 * Merges the appropriate PortConfig with the description.
1172 *
Simon Huntffbad3b2017-05-16 15:37:51 -07001173 * @param cpt ConnectPoint where the port is attached
1174 * @param desc {@link PortDescription}
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001175 * @return merged {@link PortDescription}
1176 */
1177 private PortDescription applyAllPortOps(ConnectPoint cpt, PortDescription desc) {
1178 PortDescription work = desc;
1179 for (PortConfigOperator portOp : portOps) {
1180 work = portOp.combine(cpt, work);
1181 }
Yuta HIGUCHI7438f5a2017-02-15 22:09:46 -08001182 return portAnnotationOp.combine(cpt, work);
Yuta HIGUCHIb9af6b72016-06-10 10:52:58 -07001183 }
1184
Jonghwan Hyun6ecf56d2017-08-01 16:07:44 -07001185 /**
1186 * Port Enable/Disable message sent to the device's MASTER node.
1187 */
1188 private class InternalPortUpDownEvent {
1189 private final DeviceId deviceId;
1190 private final PortNumber portNumber;
1191 private final boolean enable;
1192
1193 protected InternalPortUpDownEvent(
1194 DeviceId deviceId, PortNumber portNumber, boolean enable) {
1195 this.deviceId = deviceId;
1196 this.portNumber = portNumber;
1197 this.enable = enable;
1198 }
1199
1200 public DeviceId deviceId() {
1201 return deviceId;
1202 }
1203 public PortNumber portNumber() {
1204 return portNumber;
1205 }
1206 public boolean isEnable() {
1207 return enable;
1208 }
1209
1210 protected InternalPortUpDownEvent() {
1211 this.deviceId = null;
1212 this.portNumber = null;
1213 this.enable = false;
1214 }
1215 }
tomd3097b02014-08-26 10:40:29 -07001216}