forked from tscheffl/netconf-mqtt-bridge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
netconf_Server.py
225 lines (183 loc) · 6.72 KB
/
netconf_Server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# -*- coding: utf-8 -*-#
#
# February 23 2017, Thomas Scheffler <[email protected]>
#
# Copyright (c) 2017
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import absolute_import, division, unicode_literals, print_function, nested_scopes
import getpass
import logging
from lxml import etree
#from netconf import client as netconf_client
from netconf import server as netconf_server
from ncclient.xml_ import new_ele, sub_ele
#from netconf.error import RPCError
import paho.mqtt.client as mqtt
from parse_json import generate_yang
#from sets import Set
logger = logging.getLogger(__name__)
nc_server = None
NC_PORT = 44555 #None
NC_DEBUG = False
test ='''
{
"dummy":
{
"description": "blabla_3",
"output": "0"
}
}'''
#test =
'''
{
"rpc": {
"set_color_green": {
"description": "RPC call that sets the LIFX-Led Color to green",
"mqtt-command": "GREEN"
},
"switch_off": {
"description": "Switches the LIFX-Led off",
"mqtt-command": "OFF"
}
}
}
'''
yangModel = ""
command_dict = {}
uuid_set = set()
device_category = ""
class NetconfMethods (netconf_server.NetconfMethods):
#build the config
nc_config = new_ele('config')
configuration = sub_ele(nc_config, 'configuration')
system = sub_ele(configuration, 'system')
location = sub_ele(system, 'location')
sub_ele(location, 'building').text = "Main Campus, A"
sub_ele(location, 'floor').text = "5"
sub_ele(location, 'rack').text = "27"
#<netconf-state xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring">
#<schemas/>
#</netconf-state>
@classmethod
def rpc_get (cls, unused_session, rpc, *unused_params):
#return etree.Element("ok")
#return cls.nc_config
root = etree.Element('data')
child1 = etree.SubElement(root, 'device', xmlns="http://ipv6lab.beuth-hochschule.de/led")
#for element in elementCollections:
#listOfElements = ['1', '2', '3']
#for ele in listOfElements: #set
for ele in uuid_set:
child2 = etree.SubElement(child1, "device-id")
child3 = etree.SubElement(child2, "uuid")
child3.text = ele
child4 = etree.SubElement(child1, "device-category")
child4.text = device_category
#newtree = etree.tostring(root, encoding='utf-8')
#newtree = newtree.decode("utf-8")
#print newtree
return root
def rpc_hubble (self, unused_session, rpc, *unused_params):
return etree.Element("okidoki")
def rpc_get_schema(self, unused_session, rpc, *unused_params):
root = etree.Element("data", xmlns="urn:ietf:params:xml:ns:yang:ietf-netconf-monitoring")
root.text = etree.CDATA(yangModel)
print (command_dict)
return root
#return etree.Element("okiki")
#return generate_yang()
def setup_module (unused_module):
global nc_server, uuid_set, device_category
yangModel, command_dict, uuid_set, device_category = generate_yang(test, uuid_set)
logging.basicConfig(level=logging.DEBUG)
if nc_server is not None:
logger.error("XXX Called setup_module multiple times")
else:
sctrl = netconf_server.SSHUserPassController(username=getpass.getuser(),
password="admin")
nc_server = netconf_server.NetconfSSHServer(server_ctl=sctrl,
server_methods=NetconfMethods(),
port=NC_PORT,
host_key="tests/host_key",
debug=NC_DEBUG)
### Generate Netconf Methods
def build_Netconf_Methods(method_Name, mqtt_Parameter):
logger.info("build_Netconf_Methods called: " + method_Name + mqtt_Parameter)
ld = {}
string = 'self.extra = "Hello"'
exec("""
def rpc_%s(self, unused_session, rpc, *unused_params):
%s
#print (locals().keys())
for k in unused_params:
print ("Element: " + k.tag + "Text: " + k.text)
#print(self.extra)
topic = "LIFX/" + k.text
mqtt_client.publish(topic, "%s")
return etree.Element("%s")
""" % (method_Name, string, mqtt_Parameter, method_Name), None, ld)
print('locals got: {}'.format(ld))
for name, value in ld.items():
setattr(NetconfMethods, name, value)
#attach RPC to configuration
rpc = sub_ele(NetconfMethods.configuration,"""rpc_%s""" % (method_Name))
### MQTT functions
def mqtt_connect(mqtt_client, userdata, flags, rc):
print("Connected with result code " + str(rc))
mqtt_client.subscribe("yang/config/#")
def mqtt_message(mqtt_client, userdata, msg):
global test
global yangModel, command_dict
global uuid_set
global device_category
logger.info(msg.topic + " " + str(msg.payload))
a = (msg.topic.split("/"))
if a[0] == "yang" and a[1] == "config":
print ("Split", a[0], a[1])
test = msg.payload
yangModel,command_dict,uuid_set,device_category = generate_yang(test, uuid_set)
for i in command_dict:
print (i, command_dict[i])
build_Netconf_Methods(i, command_dict[i])
mqtt_client = mqtt.Client()
mqtt_client.on_connect = mqtt_connect
mqtt_client.on_message = mqtt_message
### Run....
mqtt_client.connect("localhost", 1883, 60)
#mqtt_client.loop_forever()
mqtt_client.loop_start()
print ("#\n#\n#\n#\n")
query = """
<get><filter>
<devices xmlns="http://tail-f.com/ns/ncs">
<global-settings/>
</devices></filter></get>
"""
query1 = "<hubble/>"
setup_module(None)
logger.info("Connecting to 127.0.0.1 port %d", nc_server.port)
#session = netconf_client.NetconfSSHSession("127.0.0.1",
# username=getpass.getuser(),
# password="admin",
# port=nc_server.port,
# debug=NC_DEBUG)
#session.send_rpc(query)
def rpc_zack (self, unused_session, rpc, *unused_params):
return etree.Element("blue")
NetconfMethods.rpc_zack = rpc_zack
# del NetconfMethods.rpc_zack
#calling functions from string
#getattr(session,'send_rpc')("<get/>")
#session.send_rpc("<BELL/>")