blob: 9893fdbda8a31e31c16f0e6b8b1a12aac02281e3 [file] [log] [blame]
Ivan Eroshkin45ff4862019-10-08 14:59:38 +02001/*
2 * Copyright 2018-present Open Networking Foundation
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 * This work was partially supported by EC H2020 project METRO-HAUL (761727).
17 */
18
19package org.onosproject.drivers.odtn;
20
21import com.google.common.collect.Range;
22import org.apache.commons.configuration.XMLConfiguration;
23import org.onlab.osgi.DefaultServiceDirectory;
24import org.onosproject.drivers.utilities.XmlConfigParser;
25import org.onosproject.net.DeviceId;
26import org.onosproject.net.PortNumber;
27import org.onosproject.net.behaviour.PowerConfig;
28import org.onosproject.net.device.DeviceService;
29import org.onosproject.net.driver.AbstractHandlerBehaviour;
30import org.onosproject.netconf.NetconfController;
31import org.onosproject.netconf.NetconfDevice;
32import org.onosproject.netconf.NetconfException;
33import org.onosproject.netconf.NetconfSession;
34import org.slf4j.Logger;
35
36import java.util.ArrayList;
37import java.util.List;
38import java.util.Optional;
39
40import static com.google.common.base.Preconditions.checkNotNull;
41import static org.slf4j.LoggerFactory.getLogger;
42
43/**
44 * Driver Implementation of the PowerConfig for OpenConfig terminal devices.
45 * Currently works only with PSI-2T.
46 * If you want to make it work with ROADM, you need to implement this interface again.
47 *
48 */
49public class NokiaTerminalDevicePowerConfig<T>
50 extends AbstractHandlerBehaviour implements PowerConfig<T> {
51
52 private static final String RPC_TAG_NETCONF_BASE =
53 "<rpc xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">";
54
55 private static final String RPC_CLOSE_TAG = "</rpc>";
56
57 private static final String OPTICAL_CHANNEL = "OCH";
58
59 private static final Logger log = getLogger(NokiaTerminalDevicePowerConfig.class);
60
61 private ComponentType state = ComponentType.DIRECTION;
62
63 //The username and password are different from the username and password in the netconf-cfg file
64 private static final String USER_NAME = "admin";
65 private static final String PASSWORD = "admin";
66
67
68 /**
69 * Login to the device by providing the correct user and password in order to configure the device
70 * Returns the NetconfSession with the device for which the method was called.
71 *
72 * @param deviceId device identifier
73 * @param userName username to access the device
74 * @param passwd password to access the device
75 * @return The netconf session or null
76 */
77 private NetconfSession getNetconfSessionAndLogin(DeviceId deviceId, String userName, String passwd) {
78 NetconfController nc = handler().get(NetconfController.class);
79 NetconfDevice ndev = nc.getDevicesMap().get(deviceId);
80 if (ndev == null) {
81 log.debug("NetConf device " + deviceId + " is not found, returning null session");
82 return null;
83 }
84 NetconfSession ns = ndev.getSession();
85 if (ns == null) {
86 log.error("discoverPorts called with null session for \n {}", deviceId);
87 return null;
88 }
89
90 try {
91 String reply = ns.requestSync(buildLoginRpc(userName, passwd));
92 if (reply.contains("<ok/>")) {
93 return ns;
94 } else {
95 log.debug("Reply contains this: \n {}", reply);
96 return null;
97 }
98 } catch (NetconfException e) {
99 log.error("Can NOT login to the device", e);
100 }
101 return ns;
102 }
103
104 /**
105 * Construct a rpc login message.
106 *
107 * @param userName username to access the device
108 * @param passwd password to access the device
109 * @return RPC message
110 */
111 private String buildLoginRpc(String userName, String passwd) {
112 StringBuilder rpc = new StringBuilder(RPC_TAG_NETCONF_BASE);
113 rpc.append("<login xmlns=\"http://nokia.com/yang/nokia-security\">");
114 rpc.append("<username>");
115 rpc.append(userName);
116 rpc.append("</username>");
117 rpc.append("<password>");
118 rpc.append(passwd);
119 rpc.append("</password>");
120 rpc.append("</login>");
121 rpc.append(RPC_CLOSE_TAG);
122 return rpc.toString();
123 }
124
125 //crude way of removing rpc-reply envelope (copy from netconf session)
126 private String getDataOfRpcReply(String rpcReply) {
127 String data = null;
128 int begin = rpcReply.indexOf("<data>");
129 int end = rpcReply.lastIndexOf("</data>");
130 if (begin != -1 && end != -1) {
131 data = (String) rpcReply.subSequence(begin, end + "</data>".length());
132 } else {
133 data = rpcReply;
134 }
135 return data;
136 }
137
138 /**
139 * Get the deviceId for which the methods apply.
140 *
141 * @return The deviceId as contained in the handler data
142 */
143 private DeviceId did() {
144 return handler().data().deviceId();
145 }
146
147 /**
148 * Execute RPC request.
149 * @param session Netconf session
150 * @param message Netconf message in XML format
151 * @return XMLConfiguration object
152 */
153
154 //TODO: rewrite with requestSync operation..
155 private XMLConfiguration executeRpcReq(NetconfSession session, String message) {
156 try {
157 String reply = session.requestSync(message);
158 String data = getDataOfRpcReply(reply);
159 log.debug("\n\n [executeRpcReq] RPC request returned this: \n {} \n\n", data);
160 XMLConfiguration cfg = (XMLConfiguration) XmlConfigParser.loadXmlString(getDataOfRpcReply(reply));
161 return cfg;
162 } catch (NetconfException ne) {
163 log.error("Exception on NetConf protocol: {}.", ne);
164 } catch (Exception e) {
165 log.debug("Error loading data to internal XML Configuration format: \n {}", e);
166 }
167 return null;
168 }
169
170 /**
171 * Get the target-output-power value on specific optical-channel.
172 * @param port the port
173 * @param component the port component. It should be 'oc-name' in the Annotations of Port.
174 * 'oc-name' could be mapped to '/component/name' in openconfig yang.
175 * @return target power value
176 */
177 @Override
178 public Optional<Double> getTargetPower(PortNumber port, T component) {
179 checkState(component);
180 return state.getTargetPower(port, component);
181 }
182
183 @Override
184 public void setTargetPower(PortNumber port, T component, double power) {
185 checkState(component);
186 state.setTargetPower(port, component, power);
187 }
188
189 @Override
190 public Optional<Double> currentPower(PortNumber port, T component) {
191 checkState(component);
192 return state.currentPower(port, component);
193 }
194
195 @Override
196 public Optional<Double> currentInputPower(PortNumber port, T component) {
197 checkState(component);
198 return state.currentInputPower(port, component);
199 }
200
201 @Override
202 public Optional<Range<Double>> getTargetPowerRange(PortNumber port, T component) {
203 checkState(component);
204 return state.getTargetPowerRange(port, component);
205 }
206
207 @Override
208 public Optional<Range<Double>> getInputPowerRange(PortNumber port, T component) {
209 checkState(component);
210 return state.getInputPowerRange(port, component);
211 }
212
213 @Override
214 public List<PortNumber> getPorts(T component) {
215 checkState(component);
216 return state.getPorts(component);
217 }
218
219
220 /**
221 * Set the ComponentType to invoke proper methods for different template T.
222 * @param component the component.
223 */
224 void checkState(Object component) {
225 String clsName = component.getClass().getName();
226 switch (clsName) {
227 case "org.onosproject.net.Direction":
228 state = ComponentType.DIRECTION;
229 break;
230 case "org.onosproject.net.OchSignal":
231 state = ComponentType.OCHSIGNAL;
232 break;
233 default:
234 log.error("Cannot parse the component type {}.", clsName);
235 log.info("The component content is {}.", component.toString());
236 }
237 state.nokia = this;
238 }
239
240 /**
241 * Component type.
242 */
243 enum ComponentType {
244
245 /**
246 * Direction.
247 */
248 DIRECTION() {
249 @Override
250 public Optional<Double> getTargetPower(PortNumber port, Object component) {
251 return super.getTargetPower(port, component);
252 }
253 @Override
254 public void setTargetPower(PortNumber port, Object component, double power) {
255 super.setTargetPower(port, component, power);
256 }
257 },
258
259 /**
260 * OchSignal.
261 */
262 OCHSIGNAL() {
263 @Override
264 public Optional<Double> getTargetPower(PortNumber port, Object component) {
265 return super.getTargetPower(port, component);
266 }
267
268 @Override
269 public void setTargetPower(PortNumber port, Object component, double power) {
270 super.setTargetPower(port, component, power);
271 }
272 };
273
274
275
276 NokiaTerminalDevicePowerConfig nokia;
277
278 /**
279 * mirror method in the internal class.
280 * @param port port
281 * @param component component
282 * @return target power
283 */
284 //TODO: Overlap with getTargetPowerRange function..
285 Optional<Double> getTargetPower(PortNumber port, Object component) {
286 NetconfSession session = nokia.getNetconfSessionAndLogin(nokia.did(), USER_NAME, PASSWORD);
287 checkNotNull(session);
288 String filter = parsePort(nokia, port, null, null);
289 if (filter != null) {
290 StringBuilder rpcReq = new StringBuilder();
291 rpcReq.append(RPC_TAG_NETCONF_BASE)
292 .append("<get>")
293 .append("<filter type='subtree'>")
294 .append(filter)
295 .append("</filter>")
296 .append("</get>")
297 .append(RPC_CLOSE_TAG);
298 XMLConfiguration xconf = nokia.executeRpcReq(session, rpcReq.toString());
299 log.debug("\n\n [getTargetPower] Obtained information " +
300 "from getTargetPower function is.. \n {} \n\n", xconf);
301 try {
302 String tpower = xconf.getString("components.component." +
303 "oc-opt-term:optical-channel." +
304 "oc-opt-term:config." +
305 "oc-opt-term:target-output-power");
306 double power = Float.valueOf(tpower).doubleValue();
307 log.debug("\n\n [getTargetPower] Target OUTPUT power is.. {} \n\n", power);
308 return Optional.of(power);
309 } catch (IllegalArgumentException e) {
310 log.debug("\n\n [getTargetPower] Something went wrong " +
311 "during the parsing of configuration in getTargetPower function.. \n\n");
312 return Optional.empty();
313 }
314 } else {
315 log.debug("Port you're trying to get ({}) is not optical", port.toString());
316 return Optional.empty();
317 }
318 }
319
320 /**
321 * mirror method in the internal class.
322 * @param port port
323 * @param component component
324 * @param power target value
325 */
326 void setTargetPower(PortNumber port, Object component, double power) {
327 NetconfSession session = nokia.getNetconfSessionAndLogin(nokia.did(), USER_NAME, PASSWORD);
328 checkNotNull(session);
329 String editConfig = parsePort(nokia, port, null, power);
330 if (editConfig != null) {
331 StringBuilder rpcReq = new StringBuilder();
332 rpcReq.append(RPC_TAG_NETCONF_BASE)
333 .append("<edit-config>")
334 .append("<target><running/></target>")
335 .append("<config xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">")
336 .append(editConfig)
337 .append("</config>")
338 .append("</edit-config>")
339 .append(RPC_CLOSE_TAG);
340 XMLConfiguration xconf = nokia.executeRpcReq(session, rpcReq.toString());
341 log.debug("\n\n [setTargetPower] Obtained information is.. \n {} \n\n", xconf);
342 // The successful reply should be "<rpc-reply ...><ok /></rpc-reply>"
343 if (!xconf.getRoot().getChild(0).getName().equals("ok")) {
344 log.error("[setTargetPower] The <edit-config> operation " +
345 "to set target-output-power of Port({}:{}) is failed.",
346 port.toString(), component.toString());
347 } else {
348 log.debug("[setTargetPower] Answer on <edit-config> request " +
349 "is following: \n {}\n", xconf.toString());
350 }
351 } else {
352 log.debug("[setTargetPower] Port you're trying " +
353 "to set ({}) is not optical", port.toString());
354 }
355 }
356
357 /**
358 * mirror method in the internal class.
359 * @param port port
360 * @param component the component.
361 * @return current output power.
362 */
363 Optional<Double> currentPower(PortNumber port, Object component) {
364 XMLConfiguration xconf = getOpticalChannelState(
365 nokia, port, "<oc-opt-term:output-power>" +
366 "<oc-opt-term:instant/>" +
367 "</oc-opt-term:output-power>");
368 try {
369 String oipower = xconf.getString("components.component." +
370 "oc-opt-term:optical-channel." +
371 "oc-opt-term:state." +
372 "oc-opt-term:output-power." +
373 "oc-opt-term:instant");
374 log.debug("\n\n [currentPower] That's what we read: \n {} \n\n", oipower);
375 double currentPower = Float.valueOf(oipower).doubleValue();
376 return Optional.of(currentPower);
377 } catch (Exception e) {
378 log.debug("\n\n [currentPower] Something went wrong " +
379 "during the parsing of obtained answer.. \n\n");
380 return Optional.empty();
381 }
382 }
383
384 /**
385 * mirror method in the internal class.
386 * @param port port
387 * @param component the component
388 * @return current input power
389 */
390 Optional<Double> currentInputPower(PortNumber port, Object component) {
391 XMLConfiguration xconf = getOpticalChannelState(
392 nokia, port, "<oc-opt-term:input-power>" +
393 "<oc-opt-term:instant/>" +
394 "</oc-opt-term:input-power>");
395 try {
396 String iipower = xconf.getString("components.component." +
397 "oc-opt-term:optical-channel." +
398 "oc-opt-term:state." +
399 "oc-opt-term:input-power." +
400 "oc-opt-term:instant");
401 log.debug("\n\n [currentInputPower] That's what we read: \n {} \n\n", iipower);
402 double currentPower = Float.valueOf(iipower).doubleValue();
403
404 return Optional.of(currentPower);
405 } catch (Exception e) {
406 log.debug("\n\n [currentInputPower] Something went wrong " +
407 "during the parsing of obtained answer.. \n\n");
408 return Optional.empty();
409 }
410 }
411
412 /**
413 * Getting target value of output power.
414 * @param port port
415 * @param component the component
416 * @return target output power range
417 */
418
419 Optional<Range<Double>> getTargetPowerRange(PortNumber port, Object component) {
420 double targetMin = -20;
421 double targetMax = 5;
422 return Optional.of(Range.open(targetMin, targetMax));
423 }
424
425 Optional<Range<Double>> getInputPowerRange(PortNumber port, Object component) {
426 double targetMin = -20;
427 double targetMax = 5;
428 return Optional.of(Range.open(targetMin, targetMax));
429 }
430
431 List<PortNumber> getPorts(Object component) {
432 // FIXME
433 log.warn("[getPorts] Not Implemented Yet!");
434 return new ArrayList<PortNumber>();
435 }
436
437 /**
438 * Get filtered content under <optical-channel><state>.
439 * @param pc power config instance
440 * @param port the port number
441 * @param underState the filter condition
442 * @return RPC reply
443 */
444 private static XMLConfiguration getOpticalChannelState(NokiaTerminalDevicePowerConfig pc,
445 PortNumber port, String underState) {
446 NetconfSession session = pc.getNetconfSessionAndLogin(pc.did(), USER_NAME, PASSWORD);
447 checkNotNull(session);
448 String name = ocName(pc, port);
449 StringBuilder rpcReq = new StringBuilder(RPC_TAG_NETCONF_BASE);
450 rpcReq.append("<get><filter><components xmlns=\"http://openconfig.net/yang/platform\"><component>")
451 .append("<name>").append(name).append("</name>")
452 .append("<oc-opt-term:optical-channel " +
453 "xmlns:oc-opt-term=\"http://openconfig.net/yang/terminal-device\">")
454 .append("<oc-opt-term:state>")
455 .append(underState)
456 .append("</oc-opt-term:state>")
457 .append("</oc-opt-term:optical-channel>")
458 .append("</component></components></filter></get>")
459 .append(RPC_CLOSE_TAG);
460 XMLConfiguration xconf = pc.executeRpcReq(session, rpcReq.toString());
461 return xconf;
462 }
463
464 /**
465 * Extract component name from portNumber's annotations.
466 * @param pc power config instance
467 * @param portNumber the port number
468 * @return the component name
469 */
470 private static String ocName(NokiaTerminalDevicePowerConfig pc, PortNumber portNumber) {
471 DeviceService deviceService = DefaultServiceDirectory.getService(DeviceService.class);
472 DeviceId deviceId = pc.handler().data().deviceId();
473 String port = deviceService.getPort(deviceId, portNumber).annotations().value("oc-name");
474
475 // Applying some magic to return the correct port with the correct name
476 String portType = deviceService.getPort(deviceId, portNumber).type().toString();
477 log.debug("\n\n [ocName] Type of the port taken from ONOS storage " +
478 "has following properties.. \n {} \n", portType);
479 if (portType.equals(OPTICAL_CHANNEL)) {
480 String[] textStr = port.split("-");
481 String och = "OCH-" + textStr[1] + "-" + textStr[2] + "-" + textStr[3];
482 log.debug("\n\n [ocName] Optical channel returned is.. {} \n\n", och);
483 return och;
484 } else {
485 log.debug("[ocName] This port is not an optical one");
486 return null;
487 }
488 }
489
490 /**
491 * Parse filtering string from port and component.
492 * @param portNumber Port Number
493 * @param component port component (optical-channel)
494 * @param power power value set.
495 * @return filtering string in xml format
496 */
497 private static String parsePort(NokiaTerminalDevicePowerConfig pc, PortNumber portNumber,
498 Object component, Double power) {
499 if (component == null) {
500 String name = ocName(pc, portNumber);
501 if (name != null) {
502 StringBuilder sb = new StringBuilder("<components " +
503 "xmlns=\"http://openconfig.net/yang/platform\">");
504 sb.append("<component>").append("<name>").append(name).append("</name>");
505 if (power != null) {
506 // This is an edit-config operation.
507 sb.append("<oc-opt-term:optical-channel " +
508 "xmlns:oc-opt-term=\"http://openconfig.net/yang/terminal-device\">")
509 .append("<oc-opt-term:config>")
510 .append("<oc-opt-term:target-output-power>")
511 .append(power)
512 .append("</oc-opt-term:target-output-power>")
513 .append("</oc-opt-term:config>")
514 .append("</oc-opt-term:optical-channel>");
515 }
516 sb.append("</component>").append("</components>");
517 return sb.toString();
518 }
519 } else {
520 log.error("[parsePort] Cannot process the component {}.", component.getClass());
521 return null;
522 }
523 return null;
524 }
525 }
526}