blob: 18c376b6d3dd3fa1b603827c44a590986d4009d5 [file] [log] [blame]
Andrea Campanella945ded22016-01-07 13:17:43 -08001/*
2 * Copyright 2016 Open Networking Laboratory
3 *
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 */
16
17package org.onosproject.provider.rest.device.impl;
18
19import com.google.common.base.Preconditions;
20import org.apache.felix.scr.annotations.Activate;
21import org.apache.felix.scr.annotations.Component;
22import org.apache.felix.scr.annotations.Deactivate;
23import org.apache.felix.scr.annotations.Reference;
24import org.apache.felix.scr.annotations.ReferenceCardinality;
25import org.onlab.packet.ChassisId;
26import org.onosproject.core.ApplicationId;
27import org.onosproject.core.CoreService;
28import org.onosproject.incubator.net.config.basics.ConfigException;
29import org.onosproject.net.DefaultAnnotations;
30import org.onosproject.net.Device;
31import org.onosproject.net.DeviceId;
32import org.onosproject.net.MastershipRole;
33import org.onosproject.net.SparseAnnotations;
Andrea Campanellad8d92db2016-01-14 16:24:41 -080034import org.onosproject.net.behaviour.PortDiscovery;
Andrea Campanella945ded22016-01-07 13:17:43 -080035import org.onosproject.net.config.ConfigFactory;
36import org.onosproject.net.config.NetworkConfigEvent;
37import org.onosproject.net.config.NetworkConfigListener;
38import org.onosproject.net.config.NetworkConfigRegistry;
39import org.onosproject.net.device.DefaultDeviceDescription;
40import org.onosproject.net.device.DeviceDescription;
41import org.onosproject.net.device.DeviceProvider;
42import org.onosproject.net.device.DeviceProviderRegistry;
43import org.onosproject.net.device.DeviceProviderService;
Andrea Campanellad8d92db2016-01-14 16:24:41 -080044import org.onosproject.net.driver.DriverHandler;
45import org.onosproject.net.driver.DriverService;
Andrea Campanella945ded22016-01-07 13:17:43 -080046import org.onosproject.net.provider.AbstractProvider;
47import org.onosproject.net.provider.ProviderId;
48import org.onosproject.protocol.rest.RestSBController;
49import org.onosproject.protocol.rest.RestSBDevice;
50import org.slf4j.Logger;
51
Andrea Campanella2947e622016-01-27 09:23:46 -080052import javax.net.ssl.HttpsURLConnection;
Andrea Campanella945ded22016-01-07 13:17:43 -080053import java.io.IOException;
54import java.net.HttpURLConnection;
55import java.net.URL;
Andrea Campanella2947e622016-01-27 09:23:46 -080056import java.nio.charset.StandardCharsets;
57import java.security.KeyManagementException;
58import java.security.NoSuchAlgorithmException;
59import java.util.Base64;
Andrea Campanella945ded22016-01-07 13:17:43 -080060import java.util.HashSet;
Andrea Campanella945ded22016-01-07 13:17:43 -080061import java.util.Set;
62
63import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_ADDED;
64import static org.onosproject.net.config.NetworkConfigEvent.Type.CONFIG_UPDATED;
65import static org.onosproject.net.config.basics.SubjectFactories.APP_SUBJECT_FACTORY;
66import static org.slf4j.LoggerFactory.getLogger;
67
68/**
69 * Provider for devices that use REST as means of configuration communication.
70 */
71@Component(immediate = true)
72public class RestDeviceProvider extends AbstractProvider
73 implements DeviceProvider {
74 private static final String APP_NAME = "org.onosproject.restsb";
75 private static final String REST = "rest";
76 private static final String PROVIDER = "org.onosproject.provider.rest.device";
77 private static final String IPADDRESS = "ipaddress";
78 private static final int TEST_CONNECT_TIMEOUT = 1000;
Andrea Campanella2947e622016-01-27 09:23:46 -080079 private static final String HTTPS = "https";
80 private static final String AUTHORIZATION_PROPERTY = "authorization";
81 private static final String BASIC_AUTH_PREFIX = "Basic ";
82 private static final String URL_SEPARATOR = "://";
Andrea Campanella945ded22016-01-07 13:17:43 -080083 private final Logger log = getLogger(getClass());
84
85 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
86 protected DeviceProviderRegistry providerRegistry;
87
88 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
89 protected RestSBController controller;
90
91 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
92 protected NetworkConfigRegistry cfgService;
93
94 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
95 protected CoreService coreService;
96
Andrea Campanellad8d92db2016-01-14 16:24:41 -080097 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
98 protected DriverService driverService;
99
Andrea Campanella945ded22016-01-07 13:17:43 -0800100
101 private DeviceProviderService providerService;
102 protected static final String ISNOTNULL = "Rest device is not null";
103 private static final String UNKNOWN = "unknown";
104
105 private final ConfigFactory factory =
106 new ConfigFactory<ApplicationId, RestProviderConfig>(APP_SUBJECT_FACTORY,
107 RestProviderConfig.class,
108 "restDevices",
109 true) {
110 @Override
111 public RestProviderConfig createConfig() {
112 return new RestProviderConfig();
113 }
114 };
115 private final NetworkConfigListener cfgLister = new InternalNetworkConfigListener();
116 private ApplicationId appId;
117
118
119 @Activate
120 public void activate() {
121 appId = coreService.registerApplication(APP_NAME);
122 providerService = providerRegistry.register(this);
123 cfgService.registerConfigFactory(factory);
124 cfgService.addListener(cfgLister);
125 connectDevices();
126 log.info("Started");
127 }
128
129
130 @Deactivate
131 public void deactivate() {
132 providerRegistry.unregister(this);
133 providerService = null;
134 cfgService.unregisterConfigFactory(factory);
135 cfgService.removeListener(cfgLister);
136 log.info("Stopped");
137 }
138
139 public RestDeviceProvider() {
140 super(new ProviderId(REST, PROVIDER));
141 }
142
143 @Override
144 public void triggerProbe(DeviceId deviceId) {
145 // TODO: This will be implemented later.
146 log.info("Triggering probe on device {}", deviceId);
147 }
148
149 @Override
150 public void roleChanged(DeviceId deviceId, MastershipRole newRole) {
151 // TODO: This will be implemented later.
152 }
153
154
155 @Override
156 public boolean isReachable(DeviceId deviceId) {
157 RestSBDevice restDevice = controller.getDevice(deviceId);
158 if (restDevice == null) {
159 log.warn("BAD REQUEST: the requested device id: " +
160 deviceId.toString() +
161 " is not associated to any REST Device");
162 return false;
163 }
164 return restDevice.isActive();
165 }
166
167 private void deviceAdded(RestSBDevice nodeId) {
168 Preconditions.checkNotNull(nodeId, ISNOTNULL);
169 DeviceId deviceId = nodeId.deviceId();
170 ChassisId cid = new ChassisId();
171 String ipAddress = nodeId.ip().toString();
172 SparseAnnotations annotations = DefaultAnnotations.builder()
173 .set(IPADDRESS, ipAddress).build();
174 DeviceDescription deviceDescription = new DefaultDeviceDescription(
175 deviceId.uri(),
176 Device.Type.SWITCH,
177 UNKNOWN, UNKNOWN,
178 UNKNOWN, UNKNOWN,
179 cid,
180 annotations);
181 providerService.deviceConnected(deviceId, deviceDescription);
182 nodeId.setActive(true);
183 controller.addDevice(nodeId);
184 }
185
Andrea Campanella945ded22016-01-07 13:17:43 -0800186 //when do I call it ?
187 public void deviceRemoved(RestSBDevice nodeId) {
188 Preconditions.checkNotNull(nodeId, ISNOTNULL);
189 DeviceId deviceId = nodeId.deviceId();
190 providerService.deviceDisconnected(deviceId);
191 controller.removeDevice(nodeId);
192 }
193
194 private void connectDevices() {
195 RestProviderConfig cfg = cfgService.getConfig(appId, RestProviderConfig.class);
196 try {
197 if (cfg != null && cfg.getDevicesAddresses() != null) {
198 //Precomputing the devices to be removed
199 Set<RestSBDevice> toBeRemoved = new HashSet<>(controller.getDevices().values());
200 toBeRemoved.removeAll(cfg.getDevicesAddresses());
201 //Adding new devices
202 cfg.getDevicesAddresses().stream()
203 .filter(device -> testDeviceConnection(device))
204 .forEach(device -> {
205 deviceAdded(device);
206 });
207 //Removing devices not wanted anymore
208 toBeRemoved.stream().forEach(device -> deviceRemoved(device));
209
210 }
211 } catch (ConfigException e) {
212 log.error("Configuration error {}", e);
213 }
Andrea Campanella2947e622016-01-27 09:23:46 -0800214 log.debug("REST Devices {}", controller.getDevices());
Andrea Campanellad8d92db2016-01-14 16:24:41 -0800215 controller.getDevices().keySet().forEach(deviceId -> {
216 DriverHandler h = driverService.createHandler(deviceId);
217 PortDiscovery portConfig = h.behaviour(PortDiscovery.class);
218 if (portConfig != null) {
219 providerService.updatePorts(deviceId, portConfig.getPorts());
220 } else {
221 log.warn("No portGetter behaviour for device {}", deviceId);
222 }
223 });
Andrea Campanella945ded22016-01-07 13:17:43 -0800224 }
225
226 private boolean testDeviceConnection(RestSBDevice device) {
227 try {
Andrea Campanella2947e622016-01-27 09:23:46 -0800228 URL url;
229 if (device.url() == null) {
230 url = new URL(device.protocol(), device.ip().toString(), device.port(), "");
231 } else {
232 url = new URL(device.protocol() + URL_SEPARATOR + device.url());
233 }
234 HttpURLConnection urlConn;
235 if (device.protocol().equals(HTTPS)) {
236 //FIXME this method provides no security accepting all SSL certs.
237 RestDeviceProviderUtilities.enableSslCert();
238
239 urlConn = (HttpsURLConnection) url.openConnection();
240 } else {
241 urlConn = (HttpURLConnection) url.openConnection();
242 }
243 if (device.password() != null) {
244 String userPassword = device.name() + ":" + device.password();
245 String basicAuth = Base64.getEncoder()
246 .encodeToString(userPassword.getBytes(StandardCharsets.UTF_8));
247 urlConn.setRequestProperty(AUTHORIZATION_PROPERTY, BASIC_AUTH_PREFIX + basicAuth);
248 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800249 urlConn.setConnectTimeout(TEST_CONNECT_TIMEOUT);
Andrea Campanella2947e622016-01-27 09:23:46 -0800250 boolean open = urlConn.getResponseCode() == (HttpsURLConnection.HTTP_OK);
251 if (!open) {
252 log.error("Device {} not accessibile, response code {} ", device,
253 urlConn.getResponseCode());
254 }
Andrea Campanella945ded22016-01-07 13:17:43 -0800255 urlConn.disconnect();
256 return open;
Andrea Campanella2947e622016-01-27 09:23:46 -0800257
258 } catch (IOException | NoSuchAlgorithmException | KeyManagementException e) {
259 log.error("Device {} not reachable, error creating {} connection", device,
260 device.protocol(), e);
Andrea Campanella945ded22016-01-07 13:17:43 -0800261 }
262 return false;
263 }
264
265 private class InternalNetworkConfigListener implements NetworkConfigListener {
266
267
268 @Override
269 public void event(NetworkConfigEvent event) {
270 connectDevices();
271 }
272
273 @Override
274 public boolean isRelevant(NetworkConfigEvent event) {
275 //TODO refactor
276 return event.configClass().equals(RestProviderConfig.class) &&
277 (event.type() == CONFIG_ADDED ||
278 event.type() == CONFIG_UPDATED);
279 }
280 }
281}