blob: d9afbe34077bd421c3bb23d2fa24058ea842879f [file] [log] [blame]
Sanjay Se8dcfee2015-04-23 10:07:08 +05301/*
Brian O'Connora09fe5b2017-08-03 21:12:30 -07002 * Copyright 2015-present Open Networking Foundation
Sanjay Se8dcfee2015-04-23 10:07:08 +05303 *
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 */
andreaeb70a942015-10-16 21:34:46 -070016
Sanjay Se8dcfee2015-04-23 10:07:08 +053017package org.onosproject.provider.netconf.device.impl;
18
Michele Santuari00cc1f72016-09-08 17:05:24 +020019import com.google.common.base.Objects;
andreaeb70a942015-10-16 21:34:46 -070020import com.google.common.base.Preconditions;
Andrea Campanella42e7b862018-09-21 11:56:48 +020021import com.google.common.util.concurrent.Striped;
Sanjay Se8dcfee2015-04-23 10:07:08 +053022import org.onlab.packet.ChassisId;
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -070023import org.onlab.util.Tools;
24import org.onosproject.cfg.ComponentConfigService;
andreaeb70a942015-10-16 21:34:46 -070025import org.onosproject.core.ApplicationId;
26import org.onosproject.core.CoreService;
Andrea Campanella7e6200a2016-03-21 09:48:40 -070027import org.onosproject.mastership.MastershipService;
Marc De Leenheerb0d131c2016-03-01 20:34:59 -080028import org.onosproject.net.AnnotationKeys;
andreaeb70a942015-10-16 21:34:46 -070029import org.onosproject.net.DefaultAnnotations;
Sanjay Se8dcfee2015-04-23 10:07:08 +053030import org.onosproject.net.Device;
31import org.onosproject.net.DeviceId;
32import org.onosproject.net.MastershipRole;
Ray Milkey02710432018-02-13 17:08:28 -080033import org.onosproject.net.Port;
Saurav Dasa2d37502016-03-25 17:50:40 -070034import org.onosproject.net.PortNumber;
andreaeb70a942015-10-16 21:34:46 -070035import org.onosproject.net.SparseAnnotations;
Ray Milkey02710432018-02-13 17:08:28 -080036import org.onosproject.net.behaviour.PortAdmin;
andreaeb70a942015-10-16 21:34:46 -070037import org.onosproject.net.config.ConfigFactory;
38import org.onosproject.net.config.NetworkConfigEvent;
39import org.onosproject.net.config.NetworkConfigListener;
40import org.onosproject.net.config.NetworkConfigRegistry;
Andrea Campanella34cf65c2017-04-12 13:51:32 +020041import org.onosproject.net.config.basics.SubjectFactories;
Sanjay Se8dcfee2015-04-23 10:07:08 +053042import org.onosproject.net.device.DefaultDeviceDescription;
Andrea Campanella32813682017-10-23 15:29:24 +020043import org.onosproject.net.device.DefaultPortDescription;
Sanjay Se8dcfee2015-04-23 10:07:08 +053044import org.onosproject.net.device.DeviceDescription;
Andrea Campanella6c71a052016-04-22 11:56:31 -070045import org.onosproject.net.device.DeviceDescriptionDiscovery;
Andrea Campanella7e6200a2016-03-21 09:48:40 -070046import org.onosproject.net.device.DeviceEvent;
47import org.onosproject.net.device.DeviceListener;
Sanjay Se8dcfee2015-04-23 10:07:08 +053048import org.onosproject.net.device.DeviceProvider;
49import org.onosproject.net.device.DeviceProviderRegistry;
50import org.onosproject.net.device.DeviceProviderService;
Aaron Kruglikov17b4c852016-01-15 16:37:04 -080051import org.onosproject.net.device.DeviceService;
Andrea Campanellac3627842017-04-04 18:06:54 +020052import org.onosproject.net.device.PortStatistics;
Gaurav Agrawaldab4d772017-03-29 15:15:13 +053053import org.onosproject.net.device.PortStatisticsDiscovery;
Andrea Campanella7e6200a2016-03-21 09:48:40 -070054import org.onosproject.net.key.DeviceKey;
55import org.onosproject.net.key.DeviceKeyAdminService;
56import org.onosproject.net.key.DeviceKeyId;
Sanjay Se8dcfee2015-04-23 10:07:08 +053057import org.onosproject.net.provider.AbstractProvider;
58import org.onosproject.net.provider.ProviderId;
andreaeb70a942015-10-16 21:34:46 -070059import org.onosproject.netconf.NetconfController;
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -070060import org.onosproject.netconf.NetconfDevice;
andreaeb70a942015-10-16 21:34:46 -070061import org.onosproject.netconf.NetconfDeviceListener;
Andrea Campanella8b1cb672016-01-25 13:58:58 -080062import org.onosproject.netconf.NetconfException;
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -070063import org.onosproject.netconf.config.NetconfDeviceConfig;
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -070064import org.osgi.service.component.ComponentContext;
Ray Milkeyd84f89b2018-08-17 14:54:17 -070065import org.osgi.service.component.annotations.Activate;
66import org.osgi.service.component.annotations.Component;
67import org.osgi.service.component.annotations.Deactivate;
68import org.osgi.service.component.annotations.Modified;
69import org.osgi.service.component.annotations.Reference;
70import org.osgi.service.component.annotations.ReferenceCardinality;
Sanjay Se8dcfee2015-04-23 10:07:08 +053071import org.slf4j.Logger;
72
Andrea Campanella087ceb92015-12-07 09:58:34 -080073import java.io.IOException;
Andrea Campanella42e7b862018-09-21 11:56:48 +020074import java.net.InetSocketAddress;
Andrea Campanella7e6200a2016-03-21 09:48:40 -070075import java.net.Socket;
76import java.net.URI;
77import java.net.URISyntaxException;
78import java.util.Arrays;
Andrea Campanellac3627842017-04-04 18:06:54 +020079import java.util.Collection;
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -070080import java.util.Dictionary;
mskala832d0472017-06-09 16:31:42 +020081import java.util.Map;
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -070082import java.util.Optional;
Andrea Campanella34cf65c2017-04-12 13:51:32 +020083import java.util.Set;
Andrea Campanella32813682017-10-23 15:29:24 +020084import java.util.concurrent.CompletableFuture;
mskala832d0472017-06-09 16:31:42 +020085import java.util.concurrent.ConcurrentHashMap;
Andrea Campanella5c999e22016-03-01 15:12:53 -080086import java.util.concurrent.ExecutorService;
87import java.util.concurrent.Executors;
helenyrwufd296b62016-06-22 17:43:02 -070088import java.util.concurrent.ScheduledExecutorService;
89import java.util.concurrent.ScheduledFuture;
90import java.util.concurrent.TimeUnit;
mskala832d0472017-06-09 16:31:42 +020091import java.util.concurrent.atomic.AtomicInteger;
Andrea Campanella42e7b862018-09-21 11:56:48 +020092import java.util.concurrent.locks.Lock;
93import java.util.function.Supplier;
andreaeb70a942015-10-16 21:34:46 -070094
Yuta HIGUCHI1624df12016-07-21 16:54:33 -070095import static java.util.concurrent.Executors.newScheduledThreadPool;
Andrea Campanella5c999e22016-03-01 15:12:53 -080096import static org.onlab.util.Tools.groupedThreads;
Thomas Vachuska4167c3f2018-10-16 07:16:31 -070097import static org.onosproject.provider.netconf.device.impl.OsgiPropertyConstants.*;
andreaeb70a942015-10-16 21:34:46 -070098import static org.slf4j.LoggerFactory.getLogger;
99
Sanjay Se8dcfee2015-04-23 10:07:08 +0530100/**
andreaeb70a942015-10-16 21:34:46 -0700101 * Provider which uses an NETCONF controller to detect device.
Sanjay Se8dcfee2015-04-23 10:07:08 +0530102 */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700103@Component(immediate = true,
104 property = {
105 POLL_FREQUENCY_SECONDS_DEFAULT + ":Integer=" + POLL_FREQUENCY_SECONDS_DEFAULT,
106 MAX_RETRIES + ":Integer=" + MAX_RETRIES_DEFAULT,
107 })
Sanjay Se8dcfee2015-04-23 10:07:08 +0530108public class NetconfDeviceProvider extends AbstractProvider
109 implements DeviceProvider {
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700110
andreaeb70a942015-10-16 21:34:46 -0700111 private final Logger log = getLogger(getClass());
Sanjay Se8dcfee2015-04-23 10:07:08 +0530112
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700113 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Sanjay Se8dcfee2015-04-23 10:07:08 +0530114 protected DeviceProviderRegistry providerRegistry;
115
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700116 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanella101417d2015-12-11 17:58:07 -0800117 protected NetconfController controller;
Sanjay Se8dcfee2015-04-23 10:07:08 +0530118
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700119 @Reference(cardinality = ReferenceCardinality.MANDATORY)
andreaeb70a942015-10-16 21:34:46 -0700120 protected NetworkConfigRegistry cfgService;
Sanjay Se8dcfee2015-04-23 10:07:08 +0530121
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700122 @Reference(cardinality = ReferenceCardinality.MANDATORY)
andreaeb70a942015-10-16 21:34:46 -0700123 protected CoreService coreService;
Thomas Vachuskad6811712015-04-29 21:37:04 -0700124
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700125 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700126 protected DeviceService deviceService;
Aaron Kruglikov17b4c852016-01-15 16:37:04 -0800127
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700128 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700129 protected DeviceKeyAdminService deviceKeyAdminService;
130
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700131 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700132 protected MastershipService mastershipService;
133
Ray Milkeyd84f89b2018-08-17 14:54:17 -0700134 @Reference(cardinality = ReferenceCardinality.MANDATORY)
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700135 protected ComponentConfigService componentConfigService;
136
137
Michele Santuari576f09c2016-09-28 14:20:00 +0200138 protected static final String APP_NAME = "org.onosproject.netconf";
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200139 protected static final String SCHEME_NAME = "netconf";
Andrea Campanella101417d2015-12-11 17:58:07 -0800140 private static final String DEVICE_PROVIDER_PACKAGE = "org.onosproject.netconf.provider.device";
141 private static final String UNKNOWN = "unknown";
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700142 protected static final String ISNULL = "NetconfDeviceInfo is null";
143 private static final String IPADDRESS = "ipaddress";
144 private static final String NETCONF = "netconf";
145 private static final String PORT = "port";
helenyrwufd296b62016-06-22 17:43:02 -0700146 private static final int CORE_POOL_SIZE = 10;
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700147
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700148 /** Configure poll frequency for port status and statistics; default is 30 sec. */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700149 private int pollFrequency = POLL_FREQUENCY_SECONDS_DEFAULT;
Sanjay Se8dcfee2015-04-23 10:07:08 +0530150
Thomas Vachuska00b5d4f2018-10-30 15:13:20 -0700151 /** Configure maximum allowed number of retries for obtaining list of ports; default is 5 times. */
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700152 private int maxRetries = MAX_RETRIES_DEFAULT;
mskala832d0472017-06-09 16:31:42 +0200153
Michal Mach26a90fa2017-06-07 11:12:46 +0200154 protected ExecutorService executor =
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700155 Executors.newFixedThreadPool(5, groupedThreads("onos/netconfdeviceprovider",
156 "device-installer-%d", log));
Yuta HIGUCHI1624df12016-07-21 16:54:33 -0700157 protected ScheduledExecutorService connectionExecutor
158 = newScheduledThreadPool(CORE_POOL_SIZE,
159 groupedThreads("onos/netconfdeviceprovider",
160 "connection-executor-%d", log));
Andrea Campanella5c999e22016-03-01 15:12:53 -0800161
Michele Santuari576f09c2016-09-28 14:20:00 +0200162 protected DeviceProviderService providerService;
andreaeb70a942015-10-16 21:34:46 -0700163 private NetconfDeviceListener innerNodeListener = new InnerNetconfDeviceListener();
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700164 private InternalDeviceListener deviceListener = new InternalDeviceListener();
mskala832d0472017-06-09 16:31:42 +0200165 private final Map<DeviceId, AtomicInteger> retriedPortDiscoveryMap = new ConcurrentHashMap<>();
Michele Santuari576f09c2016-09-28 14:20:00 +0200166 protected ScheduledFuture<?> scheduledTask;
Sanjay Se8dcfee2015-04-23 10:07:08 +0530167
Ray Milkey02710432018-02-13 17:08:28 -0800168 protected final ConfigFactory factory =
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700169 // TODO consider moving Config registration to NETCONF ctl bundle
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200170 new ConfigFactory<DeviceId, NetconfDeviceConfig>(
171 SubjectFactories.DEVICE_SUBJECT_FACTORY,
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700172 NetconfDeviceConfig.class, NetconfDeviceConfig.CONFIG_KEY) {
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200173 @Override
174 public NetconfDeviceConfig createConfig() {
175 return new NetconfDeviceConfig();
176 }
Ray Milkey02710432018-02-13 17:08:28 -0800177 };
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200178
Michele Santuari576f09c2016-09-28 14:20:00 +0200179 protected final NetworkConfigListener cfgListener = new InternalNetworkConfigListener();
andreaeb70a942015-10-16 21:34:46 -0700180 private ApplicationId appId;
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700181 private boolean active;
Andrea Campanella42e7b862018-09-21 11:56:48 +0200182 private final Striped<Lock> deviceLocks = Striped.lock(30);
Sanjay Se8dcfee2015-04-23 10:07:08 +0530183
Sanjay Se8dcfee2015-04-23 10:07:08 +0530184
185 @Activate
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700186 public void activate(ComponentContext context) {
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700187 active = true;
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700188 componentConfigService.registerProperties(getClass());
Sanjay Se8dcfee2015-04-23 10:07:08 +0530189 providerService = providerRegistry.register(this);
Andrea Campanella101417d2015-12-11 17:58:07 -0800190 appId = coreService.registerApplication(APP_NAME);
Ray Milkey02710432018-02-13 17:08:28 -0800191 cfgService.registerConfigFactory(factory);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700192 cfgService.addListener(cfgListener);
andreaeb70a942015-10-16 21:34:46 -0700193 controller.addDeviceListener(innerNodeListener);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700194 deviceService.addListener(deviceListener);
Andrea Campanella7d8449b2016-03-02 10:16:42 -0800195 executor.execute(NetconfDeviceProvider.this::connectDevices);
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700196 modified(context);
Thomas Vachuskad6811712015-04-29 21:37:04 -0700197 log.info("Started");
Sanjay Se8dcfee2015-04-23 10:07:08 +0530198 }
199
andreaeb70a942015-10-16 21:34:46 -0700200
Sanjay Se8dcfee2015-04-23 10:07:08 +0530201 @Deactivate
andreaeb70a942015-10-16 21:34:46 -0700202 public void deactivate() {
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700203 componentConfigService.unregisterProperties(getClass(), false);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700204 deviceService.removeListener(deviceListener);
205 active = false;
206 controller.getNetconfDevices().forEach(id -> {
207 deviceKeyAdminService.removeKey(DeviceKeyId.deviceKeyId(id.toString()));
208 controller.disconnectDevice(id, true);
209 });
Andrea Campanella86294db2016-03-07 11:42:49 -0800210 controller.removeDeviceListener(innerNodeListener);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700211 deviceService.removeListener(deviceListener);
Sanjay Se8dcfee2015-04-23 10:07:08 +0530212 providerRegistry.unregister(this);
213 providerService = null;
mskala832d0472017-06-09 16:31:42 +0200214 retriedPortDiscoveryMap.clear();
Ray Milkey02710432018-02-13 17:08:28 -0800215 cfgService.unregisterConfigFactory(factory);
helenyrwufd296b62016-06-22 17:43:02 -0700216 scheduledTask.cancel(true);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700217 executor.shutdown();
Sanjay Seb5eebb2015-04-24 15:44:50 +0530218 log.info("Stopped");
Sanjay Se8dcfee2015-04-23 10:07:08 +0530219 }
220
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700221
222 @Modified
223 public void modified(ComponentContext context) {
224 if (context != null) {
225 Dictionary<?, ?> properties = context.getProperties();
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700226 pollFrequency = Tools.getIntegerProperty(properties, POLL_FREQUENCY_SECONDS,
227 POLL_FREQUENCY_SECONDS_DEFAULT);
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700228 log.info("Configured. Poll frequency is configured to {} seconds", pollFrequency);
mskala832d0472017-06-09 16:31:42 +0200229
Thomas Vachuska4167c3f2018-10-16 07:16:31 -0700230 maxRetries = Tools.getIntegerProperty(properties, MAX_RETRIES, MAX_RETRIES_DEFAULT);
mskala832d0472017-06-09 16:31:42 +0200231 log.info("Configured. Number of retries is configured to {} times", maxRetries);
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700232 }
233 if (scheduledTask != null) {
234 scheduledTask.cancel(false);
235 }
236 scheduledTask = schedulePolling();
237 }
238
andreaeb70a942015-10-16 21:34:46 -0700239 public NetconfDeviceProvider() {
Andrea Campanella101417d2015-12-11 17:58:07 -0800240 super(new ProviderId(SCHEME_NAME, DEVICE_PROVIDER_PACKAGE));
Sanjay Se8dcfee2015-04-23 10:07:08 +0530241 }
242
helenyrwufd296b62016-06-22 17:43:02 -0700243 // Checks connection to devices in the config file
244 // every DEFAULT_POLL_FREQUENCY_SECONDS seconds.
245 private ScheduledFuture schedulePolling() {
Yuta HIGUCHIc2b82e32017-03-10 14:33:41 -0800246 return connectionExecutor.scheduleAtFixedRate(exceptionSafe(this::checkAndUpdateDevices),
Thomas Vachuskaf3aaa8d2017-03-31 10:43:58 -0700247 pollFrequency / 10,
248 pollFrequency, TimeUnit.SECONDS);
helenyrwufd296b62016-06-22 17:43:02 -0700249 }
250
Yuta HIGUCHIc2b82e32017-03-10 14:33:41 -0800251 private Runnable exceptionSafe(Runnable runnable) {
252 return new Runnable() {
253
254 @Override
255 public void run() {
256 try {
257 runnable.run();
258 } catch (Exception e) {
259 log.error("Unhandled Exception", e);
260 }
261 }
262 };
263 }
264
Sanjay Se8dcfee2015-04-23 10:07:08 +0530265 @Override
266 public void triggerProbe(DeviceId deviceId) {
andreaeb70a942015-10-16 21:34:46 -0700267 // TODO: This will be implemented later.
Yuta HIGUCHIe4cb8cf2017-05-01 22:18:28 -0700268 log.debug("Should be triggering probe on device {}", deviceId);
Sanjay Se8dcfee2015-04-23 10:07:08 +0530269 }
270
271 @Override
272 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700273 if (active) {
274 switch (newRole) {
275 case MASTER:
Andrea Campanella42e7b862018-09-21 11:56:48 +0200276 withDeviceLock(
277 () -> initiateConnection(deviceId, newRole), deviceId).run();
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700278 log.debug("Accepting mastership role change to {} for device {}", newRole, deviceId);
279 break;
280 case STANDBY:
281 controller.disconnectDevice(deviceId, false);
282 providerService.receivedRoleReply(deviceId, newRole, MastershipRole.STANDBY);
283 //else no-op
284 break;
285 case NONE:
286 controller.disconnectDevice(deviceId, false);
287 providerService.receivedRoleReply(deviceId, newRole, MastershipRole.NONE);
288 break;
289 default:
290 log.error("Unimplemented Mastership state : {}", newRole);
291
292 }
293 }
Sanjay Se8dcfee2015-04-23 10:07:08 +0530294 }
295
296 @Override
297 public boolean isReachable(DeviceId deviceId) {
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -0700298
299 boolean sessionExists =
300 Optional.ofNullable(controller.getDevicesMap().get(deviceId))
301 .map(NetconfDevice::isActive)
302 .orElse(false);
303 if (sessionExists) {
304 return true;
305 }
306
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700307 //FIXME this is a workaround util device state is shared
308 // between controller instances.
309 Device device = deviceService.getDevice(deviceId);
310 String ip;
311 int port;
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700312 if (device != null) {
313 ip = device.annotations().value(IPADDRESS);
314 port = Integer.parseInt(device.annotations().value(PORT));
315 } else {
316 String[] info = deviceId.toString().split(":");
317 if (info.length == 3) {
318 ip = info[1];
319 port = Integer.parseInt(info[2]);
320 } else {
321 ip = Arrays.asList(info).stream().filter(el -> !el.equals(info[0])
322 && !el.equals(info[info.length - 1]))
323 .reduce((t, u) -> t + ":" + u)
324 .get();
325 log.debug("ip v6 {}", ip);
326 port = Integer.parseInt(info[info.length - 1]);
327 }
Sanjay Se8dcfee2015-04-23 10:07:08 +0530328 }
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -0700329 // FIXME just opening TCP session probably is not the appropriate
330 // method to test reachability.
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700331 //test connection to device opening a socket to it.
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -0700332 log.debug("Testing reachability for {}:{}", ip, port);
Andrea Campanella42e7b862018-09-21 11:56:48 +0200333 Socket socket = new Socket();
334 try {
335 socket.connect(new InetSocketAddress(ip, port), 1000);
Yuta HIGUCHI0454d702017-03-17 10:08:38 -0700336 log.debug("rechability of {}, {}, {}", deviceId, socket.isConnected(), !socket.isClosed());
Andrea Campanella42e7b862018-09-21 11:56:48 +0200337 boolean isConnected = socket.isConnected() && !socket.isClosed();
338 socket.close();
339 return isConnected;
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700340 } catch (IOException e) {
341 log.info("Device {} is not reachable", deviceId);
Yuta HIGUCHI3a50b0d2017-07-10 11:11:54 -0700342 log.debug(" error details", e);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700343 return false;
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700344 }
Sanjay Se8dcfee2015-04-23 10:07:08 +0530345 }
346
Saurav Dasa2d37502016-03-25 17:50:40 -0700347 @Override
348 public void changePortState(DeviceId deviceId, PortNumber portNumber,
349 boolean enable) {
Andrea Campanella32813682017-10-23 15:29:24 +0200350 Device device = deviceService.getDevice(deviceId);
351 if (mastershipService.isLocalMaster(deviceId)) {
352 if (device.is(PortAdmin.class)) {
353 PortAdmin portAdmin =
354 device.as(PortAdmin.class);
355 CompletableFuture<Boolean> modified;
356 if (enable) {
357 modified = portAdmin.enable(portNumber);
358 } else {
359 modified = portAdmin.disable(portNumber);
360 }
361 modified.thenAccept(result -> {
362 if (result) {
363 Port port = deviceService.getPort(deviceId, portNumber);
364 //rebuilding port description with admin state changed.
365 providerService.portStatusChanged(deviceId,
Yuta HIGUCHI53e47962018-03-01 23:50:48 -0800366 DefaultPortDescription.builder()
367 .withPortNumber(portNumber)
368 .isEnabled(enable)
369 .isRemoved(false)
370 .type(port.type())
371 .portSpeed(port.portSpeed())
372 .annotations((SparseAnnotations) port.annotations())
373 .build());
Andrea Campanella32813682017-10-23 15:29:24 +0200374 } else {
375 log.warn("Your device {} port {} status can't be changed to {}",
376 deviceId, portNumber, enable);
377 }
378 });
379 } else {
380 log.warn("Device {} does not support Port Admin", deviceId);
381 }
382 } else {
383 log.debug("Not master but {}, not changing port state", mastershipService.getLocalRole(deviceId));
384 }
Saurav Dasa2d37502016-03-25 17:50:40 -0700385 }
386
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700387 @Override
388 public void triggerDisconnect(DeviceId deviceId) {
389 log.debug("Forcing disconnect for device {}", deviceId);
390 controller.disconnectDevice(deviceId, true);
391 }
392
andreaeb70a942015-10-16 21:34:46 -0700393 private class InnerNetconfDeviceListener implements NetconfDeviceListener {
Sanjay Se8dcfee2015-04-23 10:07:08 +0530394
Andrea Campanella101417d2015-12-11 17:58:07 -0800395
andreaeb70a942015-10-16 21:34:46 -0700396 @Override
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700397 public void deviceAdded(DeviceId deviceId) {
398 //no-op
399 log.debug("Netconf device {} added to Netconf subController", deviceId);
Sanjay Se8dcfee2015-04-23 10:07:08 +0530400 }
401
402 @Override
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700403 public void deviceRemoved(DeviceId deviceId) {
404 Preconditions.checkNotNull(deviceId, ISNULL);
helenyrwufd296b62016-06-22 17:43:02 -0700405
406 if (deviceService.getDevice(deviceId) != null) {
407 providerService.deviceDisconnected(deviceId);
mskala832d0472017-06-09 16:31:42 +0200408 retriedPortDiscoveryMap.remove(deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700409 log.debug("Netconf device {} removed from Netconf subController", deviceId);
410 } else {
411 log.warn("Netconf device {} does not exist in the store, " +
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530412 "it may already have been removed", deviceId);
helenyrwufd296b62016-06-22 17:43:02 -0700413 }
andreaeb70a942015-10-16 21:34:46 -0700414 }
415 }
416
andreaeb70a942015-10-16 21:34:46 -0700417 private void connectDevices() {
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200418 Set<DeviceId> deviceSubjects =
419 cfgService.getSubjects(DeviceId.class, NetconfDeviceConfig.class);
420 deviceSubjects.forEach(deviceId -> {
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700421 connectDevice(cfgService.getConfig(deviceId, NetconfDeviceConfig.class));
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200422 });
helenyrwufd296b62016-06-22 17:43:02 -0700423 }
424
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700425
426 private void connectDevice(NetconfDeviceConfig config) {
427 if (config == null) {
428 return;
429 }
430 DeviceId deviceId = config.subject();
431 if (!deviceId.uri().getScheme().equals(SCHEME_NAME)) {
432 // not under my scheme, skipping
433 log.trace("{} not my scheme, skipping", deviceId);
434 return;
435 }
Andrea Campanella42e7b862018-09-21 11:56:48 +0200436 if (!isReachable(deviceId)) {
437 log.warn("Can't connect to device {}", deviceId);
438 return;
439 }
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700440 DeviceDescription deviceDescription = createDeviceRepresentation(deviceId, config);
441 log.debug("Connecting NETCONF device {}, on {}:{} with username {}",
442 deviceId, config.ip(), config.port(), config.username());
443 storeDeviceKey(config.sshKey(), config.username(), config.password(), deviceId);
Andrea Campanella105736e2017-11-23 12:52:43 +0100444 retriedPortDiscoveryMap.put(deviceId, new AtomicInteger(0));
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700445 if (deviceService.getDevice(deviceId) == null) {
446 providerService.deviceConnected(deviceId, deviceDescription);
447 }
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700448 }
449
Andrea Campanella105736e2017-11-23 12:52:43 +0100450 private void checkAndUpdateDevice(DeviceId deviceId, DeviceDescription deviceDescription, boolean newlyConnected) {
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530451 Device device = deviceService.getDevice(deviceId);
452 if (device == null) {
Andrea Campanella105736e2017-11-23 12:52:43 +0100453 log.debug("Device {} has not been added to store, since it's not reachable", deviceId);
454 return;
455 }
456 boolean isReachable = isReachable(deviceId);
457 if (!isReachable && deviceService.isAvailable(deviceId)) {
458 providerService.deviceDisconnected(deviceId);
459 return;
Andrea Campanella42e7b862018-09-21 11:56:48 +0200460 } else if (newlyConnected && mastershipService.isLocalMaster(deviceId)) {
Andrea Campanella105736e2017-11-23 12:52:43 +0100461 updateDeviceDescription(deviceId, deviceDescription, device);
462 }
463 if (isReachable && deviceService.isAvailable(deviceId) &&
464 mastershipService.isLocalMaster(deviceId)) {
465 //if ports are not discovered, retry the discovery
466 if (deviceService.getPorts(deviceId).isEmpty() &&
467 retriedPortDiscoveryMap.get(deviceId).getAndIncrement() < maxRetries) {
468 discoverPorts(deviceId);
469 }
470 updatePortStatistics(device);
471 }
472 }
473
474 private void updateDeviceDescription(DeviceId deviceId, DeviceDescription deviceDescription, Device device) {
475 if (device.is(DeviceDescriptionDiscovery.class)) {
476 if (mastershipService.isLocalMaster(deviceId)) {
477 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
478 device.as(DeviceDescriptionDiscovery.class);
479 DeviceDescription updatedDeviceDescription =
480 deviceDescriptionDiscovery.discoverDeviceDetails();
481 if (updatedDeviceDescription != null &&
482 !descriptionEquals(device, updatedDeviceDescription)) {
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530483 providerService.deviceConnected(
484 deviceId, new DefaultDeviceDescription(
Andrea Campanella105736e2017-11-23 12:52:43 +0100485 updatedDeviceDescription, true,
486 updatedDeviceDescription.annotations()));
Ray Milkey33306ba2018-09-20 13:27:25 -0700487 } else if (updatedDeviceDescription == null) {
Andrea Campanella105736e2017-11-23 12:52:43 +0100488 providerService.deviceConnected(
489 deviceId, new DefaultDeviceDescription(
490 deviceDescription, true,
491 deviceDescription.annotations()));
Konstantinos Kanonakis4d67dd82016-08-05 12:18:52 -0500492 }
helenyrwufd296b62016-06-22 17:43:02 -0700493 }
Andrea Campanella105736e2017-11-23 12:52:43 +0100494 } else {
495 log.warn("No DeviceDescriptionDiscovery behaviour for device {} " +
496 "using DefaultDeviceDescription", deviceId);
497 providerService.deviceConnected(
498 deviceId, new DefaultDeviceDescription(
499 deviceDescription, true, deviceDescription.annotations()));
helenyrwufd296b62016-06-22 17:43:02 -0700500 }
501 }
502
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530503 private void updatePortStatistics(Device device) {
504 if (device.is(PortStatisticsDiscovery.class)) {
505 PortStatisticsDiscovery d = device.as(PortStatisticsDiscovery.class);
Andrea Campanellac3627842017-04-04 18:06:54 +0200506 Collection<PortStatistics> portStatistics = d.discoverPortStatistics();
507 if (portStatistics != null) {
508 providerService.updatePortStatistics(device.id(),
509 portStatistics);
510 }
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530511 } else {
Yuta HIGUCHIe4cb8cf2017-05-01 22:18:28 -0700512 log.debug("No port statistics getter behaviour for device {}",
513 device.id());
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530514 }
515 }
516
Michele Santuari00cc1f72016-09-08 17:05:24 +0200517 private boolean descriptionEquals(Device device, DeviceDescription updatedDeviceDescription) {
Yuta HIGUCHIf381fc72017-01-03 10:39:36 -0800518 return Objects.equal(device.id().uri(), updatedDeviceDescription.deviceUri())
Michele Santuari00cc1f72016-09-08 17:05:24 +0200519 && Objects.equal(device.type(), updatedDeviceDescription.type())
520 && Objects.equal(device.manufacturer(), updatedDeviceDescription.manufacturer())
521 && Objects.equal(device.hwVersion(), updatedDeviceDescription.hwVersion())
522 && Objects.equal(device.swVersion(), updatedDeviceDescription.swVersion())
523 && Objects.equal(device.serialNumber(), updatedDeviceDescription.serialNumber())
524 && Objects.equal(device.chassisId(), updatedDeviceDescription.chassisId())
525 && Objects.equal(device.annotations(), updatedDeviceDescription.annotations());
526 }
527
helenyrwufd296b62016-06-22 17:43:02 -0700528 private void checkAndUpdateDevices() {
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200529 Set<DeviceId> deviceSubjects =
530 cfgService.getSubjects(DeviceId.class, NetconfDeviceConfig.class);
531 deviceSubjects.forEach(deviceId -> {
532 NetconfDeviceConfig config =
533 cfgService.getConfig(deviceId, NetconfDeviceConfig.class);
534 DeviceDescription deviceDescription = createDeviceRepresentation(deviceId, config);
535 storeDeviceKey(config.sshKey(), config.username(), config.password(), deviceId);
Andrea Campanella105736e2017-11-23 12:52:43 +0100536 checkAndUpdateDevice(deviceId, deviceDescription, false);
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200537 });
andreaeb70a942015-10-16 21:34:46 -0700538 }
Sanjay Se8dcfee2015-04-23 10:07:08 +0530539
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200540 private DeviceDescription createDeviceRepresentation(DeviceId deviceId, NetconfDeviceConfig config) {
541 Preconditions.checkNotNull(deviceId, ISNULL);
542 //Netconf configuration object
543 ChassisId cid = new ChassisId();
544 String ipAddress = config.ip().toString();
545 SparseAnnotations annotations = DefaultAnnotations.builder()
546 .set(IPADDRESS, ipAddress)
547 .set(PORT, String.valueOf(config.port()))
548 .set(AnnotationKeys.PROTOCOL, SCHEME_NAME.toUpperCase())
Andrea Campanella42e7b862018-09-21 11:56:48 +0200549 .set(AnnotationKeys.PROVIDER_MARK_ONLINE, String.valueOf(true))
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200550 .build();
551 return new DefaultDeviceDescription(
552 deviceId.uri(),
553 Device.Type.SWITCH,
554 UNKNOWN, UNKNOWN,
555 UNKNOWN, UNKNOWN,
556 cid, false,
557 annotations);
558 }
559
560 private void storeDeviceKey(String sshKey, String username, String password, DeviceId deviceId) {
561 if (sshKey.equals("")) {
Himanshu Ranjan7c2ee3c2017-02-13 05:10:08 -0600562 deviceKeyAdminService.addKey(
563 DeviceKey.createDeviceKeyUsingUsernamePassword(
564 DeviceKeyId.deviceKeyId(deviceId.toString()),
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200565 null, username, password));
Himanshu Ranjan7c2ee3c2017-02-13 05:10:08 -0600566 } else {
567 deviceKeyAdminService.addKey(
568 DeviceKey.createDeviceKeyUsingSshKey(
569 DeviceKeyId.deviceKeyId(deviceId.toString()),
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200570 null, username, password,
571 sshKey));
Himanshu Ranjan7c2ee3c2017-02-13 05:10:08 -0600572 }
573 }
574
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700575 private void initiateConnection(DeviceId deviceId, MastershipRole newRole) {
576 try {
577 if (isReachable(deviceId)) {
Andrea Campanella42e7b862018-09-21 11:56:48 +0200578 NetconfDevice device = controller.connectDevice(deviceId);
579 if (device != null) {
580 providerService.receivedRoleReply(deviceId, newRole, MastershipRole.MASTER);
581 } else {
582 providerService.receivedRoleReply(deviceId, newRole, MastershipRole.NONE);
583 }
584
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700585 }
586 } catch (Exception e) {
587 if (deviceService.getDevice(deviceId) != null) {
588 providerService.deviceDisconnected(deviceId);
589 }
590 deviceKeyAdminService.removeKey(DeviceKeyId.deviceKeyId(deviceId.toString()));
Ray Milkey986a47a2018-01-25 11:38:51 -0800591 throw new IllegalStateException(new NetconfException(
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200592 "Can't connect to NETCONF device " + deviceId, e));
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700593
594 }
595 }
596
597 private void discoverPorts(DeviceId deviceId) {
598 Device device = deviceService.getDevice(deviceId);
Andrea Campanella6c71a052016-04-22 11:56:31 -0700599 //TODO remove when PortDiscovery is removed from master
Ray Milkey640fedd2018-02-08 09:02:26 -0800600 if (device.is(DeviceDescriptionDiscovery.class)) {
Andrea Campanella6c71a052016-04-22 11:56:31 -0700601 DeviceDescriptionDiscovery deviceDescriptionDiscovery =
602 device.as(DeviceDescriptionDiscovery.class);
603 providerService.updatePorts(deviceId,
604 deviceDescriptionDiscovery.discoverPortDetails());
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700605 } else {
606 log.warn("No portGetter behaviour for device {}", deviceId);
607 }
Gaurav Agrawaldab4d772017-03-29 15:15:13 +0530608
609 // Port statistics discovery
Vidyashree Ramad89a1532017-03-30 15:13:52 +0530610 updatePortStatistics(device);
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700611 }
612
613 /**
614 * Return the DeviceId about the device containing the URI.
615 *
Andrea Campanella6c71a052016-04-22 11:56:31 -0700616 * @param ip IP address
Ray Milkeyd4334db2016-04-05 17:39:44 -0700617 * @param port port number
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700618 * @return DeviceId
619 */
620 public DeviceId getDeviceId(String ip, int port) {
621 try {
622 return DeviceId.deviceId(new URI(NETCONF, ip + ":" + port, null));
623 } catch (URISyntaxException e) {
624 throw new IllegalArgumentException("Unable to build deviceID for device "
625 + ip + ":" + port, e);
626 }
627 }
628
Andrea Campanella42e7b862018-09-21 11:56:48 +0200629 private <U> U withDeviceLock(Supplier<U> task, DeviceId deviceId) {
630 final Lock lock = deviceLocks.get(deviceId);
631 lock.lock();
632 try {
633 return task.get();
634 } finally {
635 lock.unlock();
636 }
637 }
638
639 private Runnable withDeviceLock(Runnable task, DeviceId deviceId) {
640 // Wrapper of withDeviceLock(Supplier, ...) for void tasks.
641 return () -> withDeviceLock(() -> {
642 task.run();
643 return null;
644 }, deviceId);
645 }
646
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700647 /**
648 * Listener for configuration events.
649 */
andreaeb70a942015-10-16 21:34:46 -0700650 private class InternalNetworkConfigListener implements NetworkConfigListener {
Sanjay Se8dcfee2015-04-23 10:07:08 +0530651
andreaeb70a942015-10-16 21:34:46 -0700652
653 @Override
654 public void event(NetworkConfigEvent event) {
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200655 if (event.configClass().equals(NetconfDeviceConfig.class)) {
Yuta HIGUCHIb6e0e912017-05-18 20:13:52 -0700656 executor.execute(() -> connectDevice((NetconfDeviceConfig) event.config().get()));
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200657 } else {
658 log.warn("Injecting device via this Json is deprecated, " +
659 "please put configuration under devices/ as shown in the wiki");
Andrea Campanella34cf65c2017-04-12 13:51:32 +0200660 }
661
Sanjay Se8dcfee2015-04-23 10:07:08 +0530662 }
663
andreaeb70a942015-10-16 21:34:46 -0700664 @Override
665 public boolean isRelevant(NetworkConfigEvent event) {
Ray Milkey02710432018-02-13 17:08:28 -0800666 return (event.configClass().equals(NetconfDeviceConfig.class)) &&
andreaeb70a942015-10-16 21:34:46 -0700667 (event.type() == NetworkConfigEvent.Type.CONFIG_ADDED ||
668 event.type() == NetworkConfigEvent.Type.CONFIG_UPDATED);
Sanjay Se8dcfee2015-04-23 10:07:08 +0530669 }
670 }
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700671
672 /**
673 * Listener for core device events.
674 */
675 private class InternalDeviceListener implements DeviceListener {
676 @Override
677 public void event(DeviceEvent event) {
Andrea Campanella36f1df92018-10-01 14:54:01 +0200678 Device device = event.subject();
679 DeviceId deviceId = device.id();
Andrea Campanella42e7b862018-09-21 11:56:48 +0200680 if (event.type() == DeviceEvent.Type.DEVICE_ADDED && !deviceService.isAvailable(event.subject().id())) {
681 try {
Andrea Campanella36f1df92018-10-01 14:54:01 +0200682 DeviceDescription description = new DefaultDeviceDescription(deviceId.uri(), device.type(),
683 device.manufacturer(), device.hwVersion(), device.swVersion(),
684 device.serialNumber(), device.chassisId(),
685 (SparseAnnotations) device.annotations());
686 checkAndUpdateDevice(deviceId, description, true);
Andrea Campanella42e7b862018-09-21 11:56:48 +0200687 } catch (Exception e) {
688 log.error("Unhandled exception checking {}", deviceId, e);
689 }
690 }
691 if (deviceService.isAvailable(event.subject().id())) {
692 executor.execute(() -> discoverPorts(event.subject().id()));
693 }
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700694 }
695
696 @Override
697 public boolean isRelevant(DeviceEvent event) {
Andrea Campanella42e7b862018-09-21 11:56:48 +0200698 if (event.type() != DeviceEvent.Type.DEVICE_ADDED &&
699 event.type() != DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED) {
Thomas Vachuska5b38dc02018-05-10 15:24:40 -0700700 return false;
701 }
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700702 if (mastershipService.getMasterFor(event.subject().id()) == null) {
703 return true;
704 }
Andrea Campanella968f93f2017-06-08 11:09:28 +0200705 return (SCHEME_NAME.equalsIgnoreCase(event.subject().annotations().value(AnnotationKeys.PROTOCOL)) ||
706 (SCHEME_NAME.equalsIgnoreCase(event.subject().id().uri().getScheme()))) &&
Michele Santuari576f09c2016-09-28 14:20:00 +0200707 mastershipService.isLocalMaster(event.subject().id());
Andrea Campanella7e6200a2016-03-21 09:48:40 -0700708 }
709 }
Sanjay Se8dcfee2015-04-23 10:07:08 +0530710}