blob: 54e26019c7c04bfc896e8805a17e436a869617d9 [file] [log] [blame]
Yuta HIGUCHI8c6e1942018-04-05 13:40:51 -07001/*
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 */
16package org.onosproject.drivers.odtn;
17
18import static com.google.common.base.Preconditions.checkNotNull;
19import static org.slf4j.LoggerFactory.getLogger;
20
21import java.io.IOException;
22import java.util.HashMap;
23import java.util.List;
24import java.util.Map;
25import java.util.Objects;
26import java.util.Optional;
27import java.util.stream.Collectors;
28
29import org.apache.commons.configuration.ConfigurationException;
30import org.apache.commons.configuration.HierarchicalConfiguration;
31import org.apache.commons.configuration.XMLConfiguration;
32import org.apache.commons.configuration.tree.xpath.XPathExpressionEngine;
33import org.onosproject.net.DefaultAnnotations;
34import org.onosproject.net.DeviceId;
35import org.onosproject.net.Port.Type;
36import org.onosproject.net.PortNumber;
37import org.onosproject.net.device.DefaultPortDescription;
38import org.onosproject.net.device.DefaultPortDescription.Builder;
39import org.onosproject.net.device.DeviceDescription;
40import org.onosproject.net.device.DeviceDescriptionDiscovery;
41import org.onosproject.net.device.PortDescription;
42import org.onosproject.net.driver.AbstractHandlerBehaviour;
43import org.onosproject.netconf.NetconfController;
44import org.onosproject.netconf.NetconfDevice;
45import org.onosproject.netconf.NetconfRpcParserUtil;
46import org.onosproject.netconf.NetconfRpcReply;
47import org.onosproject.netconf.NetconfSession;
48import org.onosproject.odtn.behaviour.OdtnDeviceDescriptionDiscovery;
49import org.slf4j.Logger;
50
51import com.google.common.annotations.VisibleForTesting;
52import com.google.common.collect.ImmutableList;
53import com.google.common.io.CharSource;
54
55/**
56 * OpenConfig based device and port discovery.
57 */
58public class OpenConfigDeviceDiscovery
59 extends AbstractHandlerBehaviour
60 implements OdtnDeviceDescriptionDiscovery, DeviceDescriptionDiscovery {
61
62 private static final Logger log = getLogger(OpenConfigDeviceDiscovery.class);
63
64 @Override
65 public DeviceDescription discoverDeviceDetails() {
66 // TODO Auto-generated method stub
67 // Not really used right now
68 return null;
69 }
70
71 @Override
72 public List<PortDescription> discoverPortDetails() {
73 try {
74 return discoverPorts();
75 } catch (Exception e) {
76 log.error("Error discovering port details on {}", data().deviceId(), e);
77 return ImmutableList.of();
78 }
79 }
80
81 private List<PortDescription> discoverPorts() throws ConfigurationException, IOException {
82 DeviceId did = data().deviceId();
83 NetconfSession ns = Optional.ofNullable(handler().get(NetconfController.class))
84 .map(c -> c.getNetconfDevice(did))
85 .map(NetconfDevice::getSession)
86 .orElseThrow(() -> new IllegalStateException("No NetconfSession found for " + did));
87
88 // TODO convert this method into non-blocking form?
89
90 NetconfRpcReply reply = ns.asyncGet()
91 .thenApply(NetconfRpcParserUtil::parseRpcReply)
92 .join();
93
94 if (reply.hasError()) {
95 log.error("Netconf error replies from {}:\n{}", did, reply.errors());
96 return ImmutableList.of();
97 }
98
99 String data = reply.responses().stream()
100 .filter(s -> s.startsWith("<data"))
101 .findFirst()
102 .orElse(null);
103
104 if (data == null) {
105 log.error("No valid response found from {}:\n{}", did, reply);
106 return ImmutableList.of();
107 }
108
109 XMLConfiguration cfg = new XMLConfiguration();
110 cfg.load(CharSource.wrap(data).openStream());
111
112 return discoverPorts(cfg);
113 }
114
115 /**
116 * Parses port information from OpenConfig XML configuration.
117 *
118 * @param cfg tree where the root node is {@literal <data>}
119 * @return List of ports
120 */
121 @VisibleForTesting
122 protected List<PortDescription> discoverPorts(XMLConfiguration cfg) {
123 // If we want to use XPath
124 cfg.setExpressionEngine(new XPathExpressionEngine());
125
126 // converting components into PortDescription.
127 List<HierarchicalConfiguration> components = cfg.configurationsAt("components/component");
128 return components.stream()
129 .map(this::toPortDescription)
130 .filter(Objects::nonNull)
131 .collect(Collectors.toList());
132 }
133
134 // wrapper to make parsing exception safe
135 private PortDescription toPortDescription(HierarchicalConfiguration component) {
136 try {
137 return toPortDescriptionInternal(component);
138 } catch (Exception e) {
139 log.error("Unexpected exception parsing component {} on {}",
140 component.getString("name"),
141 data().deviceId(), e);
142 return null;
143 }
144 }
145
146 /**
147 * Converts Component subtree to PortDescription.
148 *
149 * @param component subtree to parse
150 * @return PortDescription or null if component is not an ONOS Port
151 */
152 private PortDescription toPortDescriptionInternal(HierarchicalConfiguration component) {
153
154 // to access other part of <data> tree:
155 //log.warn("parent data Node: {}",
156 // ((SubnodeConfiguration) component).getParent().getRootNode().getName());
157
158 Map<String, String> props = new HashMap<>();
159
160 String name = component.getString("name");
161 String type = component.getString("state/type");
162 checkNotNull(name);
163 checkNotNull(type);
164 props.put(OdtnDeviceDescriptionDiscovery.OC_NAME, name);
165 props.put(OdtnDeviceDescriptionDiscovery.OC_TYPE, type);
166
167 component.configurationsAt("properties/property").forEach(prop -> {
168 String pName = prop.getString("name");
169 String pValue = prop.getString("config/value");
170 props.put(pName, pValue);
171 });
172
173 if (!props.containsKey("onos-index")) {
174 log.info("DEBUG: Component {} does not include onos-index, skipping", name);
175 // ODTN: port must have onos-index property
176 return null;
177 }
178
179 Builder builder = DefaultPortDescription.builder();
180 builder.withPortNumber(PortNumber.portNumber(Long.parseLong(props.get("onos-index")), name));
181
182 switch (type) {
183 case "oc-platform-types:PORT":
184 case "oc-platform-types:TRANSCEIVER":
185 case "oc-opt-types:OPTICAL_CHANNEL":
186 // TODO assign appropriate port type & annotations at some point
187 // for now we just need a Port with annotations
188 builder.type(Type.PACKET);
189 break;
190
191 default:
192 log.info("DEBUG: Unknown component type {}", type);
193 return null;
194 }
195
196 builder.annotations(DefaultAnnotations.builder().putAll(props).build());
197
198 return builder.build();
199
200 }
201
202}