3 # Copyright 2016 RIFT.IO Inc
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
21 import ncclient
.asyncio_manager
23 from gi
.repository
import RwYang
24 class ProxyConnectionError(Exception):
28 class NcClient(object):
29 '''Class representing a Netconf Session'''
31 OPERATION_TIMEOUT_SECS
= 240
33 def __init__(self
, host
, port
, username
, password
, loop
):
34 '''Initialize a new Netconf Session instance
39 username - credentials for accessing the host, username
40 password - credentials for accessing the host, password
43 A newly initialized Netconf session instance
47 self
.username
= username
48 self
.password
= password
52 self
._model
= RwYang
.Model
.create_libncx()
55 def connect(self
, timeout
=240):
56 '''Connect Netconf Session
59 timeout - maximum time allowed before connect fails [default 30s]
61 # logger.info("Connecting to confd (%s) SSH port (%s)", self.host, self.port)
65 start_time
= time
.time()
66 while (time
.time() - start_time
) < timeout
:
68 self
._nc
_mgr
= yield from ncclient
.asyncio_manager
.asyncio_connect(
72 username
=self
.username
,
73 password
=self
.password
,
74 # Setting allow_agent and look_for_keys to false will skip public key
75 # authentication, and use password authentication.
80 # logger.info("Successfully connected to confd (%s) SSH port (%s)", self.host, self.port)
81 self
._nc
_mgr
.timeout
= NcClient
.OPERATION_TIMEOUT_SECS
84 except ncclient
.NCClientError
as e
:
85 # logger.debug("Could not connect to (%s) confd ssh port (%s): %s",
86 # self.host, self.port, str(e))
89 yield from asyncio
.sleep(5, loop
=self
.loop
)
91 raise ProxyConnectionError("Could not connect to Confd ({}) ssh port ({}): within the timeout {} sec.".format(
92 self
.host
, self
.port
, timeout
))
94 def convert_to_xml(self
, module
, yang_obj
):
95 schema
= getattr(module
, "get_schema")
96 self
._model
.load_schema_ypbc(schema())
98 get_xml
= getattr(yang_obj
, "to_xml_v2")
100 return get_xml(self
._model
)