blob: c1208fb0d3564fb2c36eab3660d5d2bd0a8e190b [file] [log] [blame]
Sanjay Se8dcfee2015-04-23 10:07:08 +05301/*
2 * Copyright 2015 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 */
16package org.onosproject.provider.netconf.device.impl;
17
18import static com.google.common.base.Preconditions.checkNotNull;
19import static org.onlab.util.Tools.delay;
20import static org.slf4j.LoggerFactory.getLogger;
21
22import java.io.IOException;
23import java.io.StringReader;
24import java.util.ArrayList;
25import java.util.List;
26
27import org.jdom2.Document;
28import org.jdom2.Element;
29import org.jdom2.input.SAXBuilder;
30import org.jdom2.output.Format;
31import org.jdom2.output.XMLOutputter;
32import org.slf4j.Logger;
33
34import com.tailf.jnc.Capabilities;
35import com.tailf.jnc.JNCException;
36import com.tailf.jnc.SSHConnection;
37import com.tailf.jnc.SSHSession;
38
39/**
40 * This is a logical representation of actual NETCONF device, carrying all the
41 * necessary information to connect and execute NETCONF operations.
42 */
43public class NetconfDevice {
44 private static final Logger log = getLogger(NetconfDevice.class);
45
46 /**
47 * The Device State is used to determine whether the device is active or
48 * inactive. This state infomation will help Device Creator to add or delete
49 * the device from the core.
50 */
51 public static enum DeviceState {
52 /* Used to specify Active state of the device */
53 ACTIVE,
54 /* Used to specify In Active state of the device */
55 INACTIVE,
56 /* Used to specify In Valid state of the device */
57 INVALID
58 }
59
60 private static final int DEFAULT_SSH_PORT = 22;
61 private static final String XML_CAPABILITY_KEY = "capability";
62 private static final int EVENTINTERVAL = 2000;
63 private static final int CONNECTION_CHECK_INTERVAL = 3;
64 private static final String INPUT_HELLO_XML_MSG = new StringBuilder(
65 "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
66 .append("<hello xmlns=\"urn:ietf:params:xml:ns:netconf:base:1.0\">")
67 .append("<capabilities><capability>urn:ietf:params:netconf:base:1.0</capability>")
68 .append("</capabilities></hello>").toString();
69
70 private String sshHost;
71 private int sshPort = DEFAULT_SSH_PORT;
72 private String username;
73 private String password;
74 private boolean reachable = false;
75
76 private List<String> capabilities = new ArrayList<String>();
77 private SSHConnection sshConnection = null;
78
79 private DeviceState deviceState = DeviceState.INVALID;
80
81 protected NetconfDevice(String sshHost, int sshPort, String username,
82 String password) {
83 this.username = checkNotNull(username,
84 "Netconf Username Cannot be null");
85 this.sshHost = checkNotNull(sshHost, "Netconf Device IP cannot be null");
86 this.sshPort = checkNotNull(sshPort,
87 "Netconf Device SSH port cannot be null");
88 this.password = password;
89 }
90
91 /**
92 * This will try to connect to NETCONF device and find all the capabilities.
93 */
94 public void init() throws Exception {
95 try {
96 if (sshConnection == null) {
97 sshConnection = new SSHConnection(sshHost, sshPort);
98 sshConnection.authenticateWithPassword(username, password);
99 }
100 // Send hello message to retrieve capabilities.
101 } catch (IOException e) {
102 NetconfDevice.log
103 .error("Fatal Error while creating connection to the device: "
104 + deviceInfo(), e);
105 throw e;
106 } catch (JNCException e) {
107 NetconfDevice.log.error("Failed to connect to the device: "
108 + deviceInfo(), e);
109 throw e;
110 }
111
112 hello();
113 }
114
115 private void hello() {
116 SSHSession ssh = null;
117 try {
118 ssh = new SSHSession(sshConnection);
119 String helloRequestXML = INPUT_HELLO_XML_MSG.trim();
120
121 if (NetconfDevice.log.isDebugEnabled()) {
122 NetconfDevice.log
123 .debug("++++++++++++++++++++++++++++++++++Sending Hello: "
124 + sshConnection.getGanymedConnection()
125 .getHostname()
126 + "++++++++++++++++++++++++++++++++++");
127 printPrettyXML(helloRequestXML);
128 }
129 ssh.print(helloRequestXML);
130 // ssh.print(endCharSeq);
131 ssh.flush();
132 String xmlResponse = null;
133 int i = CONNECTION_CHECK_INTERVAL;
134 while (!ssh.ready() && i > 0) {
135 delay(EVENTINTERVAL);
136 i--;
137 }
138
139 if (ssh.ready()) {
140 StringBuffer readOne = ssh.readOne();
141 if (readOne == null) {
142 NetconfDevice.log
143 .error("The Hello Contains No Capabilites");
144 throw new JNCException(
145 JNCException.SESSION_ERROR,
146 "server does not support NETCONF base capability: "
147 + Capabilities.NETCONF_BASE_CAPABILITY);
148 } else {
149 xmlResponse = readOne.toString().trim();
150
151 if (NetconfDevice.log.isDebugEnabled()) {
152 NetconfDevice.log
153 .debug("++++++++++++++++++++++++++++++++++Reading Capabilities: "
154 + sshConnection.getGanymedConnection()
155 .getHostname()
156 + "++++++++++++++++++++++++++++++++++");
157
158 printPrettyXML(xmlResponse);
159 }
160 processCapabilities(xmlResponse);
161 }
162 }
163 reachable = true;
164 } catch (IOException e) {
165 NetconfDevice.log
166 .error("Fatal Error while sending Hello Message to the device: "
167 + deviceInfo(), e);
168 } catch (JNCException e) {
169 NetconfDevice.log
170 .error("Fatal Error while sending Hello Message to the device: "
171 + deviceInfo(), e);
172 } finally {
173 if (NetconfDevice.log.isDebugEnabled()) {
174 NetconfDevice.log
175 .debug("Closing the session after successful execution");
176 }
177 ssh.close();
178 }
179 }
180
181 private void processCapabilities(String xmlResponse) throws JNCException {
182 if (xmlResponse.isEmpty()) {
183 NetconfDevice.log.error("The capability response cannot be empty");
184 throw new JNCException(
185 JNCException.SESSION_ERROR,
186 "server does not support NETCONF base capability: "
187 + Capabilities.NETCONF_BASE_CAPABILITY);
188 }
189 try {
190 Document doc = new SAXBuilder()
191 .build(new StringReader(xmlResponse));
192 Element rootElement = doc.getRootElement();
193 processCapabilities(rootElement);
194 } catch (Exception e) {
195 NetconfDevice.log.error("ERROR while parsing the XML "
196 + xmlResponse);
197 }
198 }
199
200 private void processCapabilities(Element rootElement) {
201 List<Element> children = rootElement.getChildren();
202 if (children.isEmpty()) {
203 return;
204 }
205 for (Element child : children) {
206
207 if (child.getName().equals(XML_CAPABILITY_KEY)) {
208 capabilities.add(child.getValue());
209 }
210 if (!child.getChildren().isEmpty()) {
211 processCapabilities(child);
212 }
213 }
214 }
215
216 private void printPrettyXML(String xmlstring) {
217 try {
218 Document doc = new SAXBuilder().build(new StringReader(xmlstring));
219 XMLOutputter xmOut = new XMLOutputter(Format.getPrettyFormat());
220 String outputString = xmOut.outputString(doc);
221 if (NetconfDevice.log.isDebugEnabled()) {
222 NetconfDevice.log.debug(outputString);
223 }
224 } catch (Exception e) {
225 NetconfDevice.log.error("ERROR while parsing the XML " + xmlstring,
226 e);
227
228 }
229 }
230
231 /**
232 * This would return host IP and host Port, used by this particular Netconf
233 * Device.
234 * @return Device Information.
235 */
236 public String deviceInfo() {
237 return new StringBuilder("host: ").append(sshHost).append(". port: ")
238 .append(sshPort).toString();
239 }
240
241 /**
242 * This will terminate the device connection.
243 */
244 public void disconnect() {
245 sshConnection.close();
246 reachable = false;
247 }
248
249 /**
250 * This will list down all the capabilities supported on the device.
251 * @return Capability list.
252 */
253 public List<String> getCapabilities() {
254 return capabilities;
255 }
256
257 /**
258 * This api is intended to know whether the device is connected or not.
259 * @return true if connected
260 */
261 public boolean isReachable() {
262 return reachable;
263 }
264
265 /**
266 * This will return the IP used connect ssh on the device.
267 * @return Netconf Device IP
268 */
269 public String getSshHost() {
270 return sshHost;
271 }
272
273 /**
274 * This will return the SSH Port used connect the device.
275 * @return SSH Port number
276 */
277 public int getSshPort() {
278 return sshPort;
279 }
280
281 /**
282 * The usename used to connect Netconf Device.
283 * @return Device Username
284 */
285 public String getUsername() {
286 return username;
287 }
288
289 /**
290 * Retrieve current state of the device.
291 * @return Current Device State
292 */
293 public DeviceState getDeviceState() {
294 return deviceState;
295 }
296
297 /**
298 * This is set the state information for the device.
299 * @param deviceState Next Device State
300 */
301 public void setDeviceState(DeviceState deviceState) {
302 this.deviceState = deviceState;
303 }
304
305 /**
306 * Check whether the device is in Active state.
307 * @return true if the device is Active
308 */
309 public boolean isActive() {
310 return deviceState == DeviceState.ACTIVE ? true : false;
311 }
312}