-
Notifications
You must be signed in to change notification settings - Fork 168
/
yang2proto.py
389 lines (326 loc) · 12.7 KB
/
yang2proto.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
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
#!/usr/bin/env python
#
# Copyright 2016 the original author or authors.
#
# 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.
#
"""pyang plugin to convert a yang schema to a protobuf schema
- basic support for leaf, leaf-list, containers, list
- this plugin requires pyang to be present and is run using pyang as
follows:
$ pyang --plugindir /voltha/experiments/netconf/yang2proto -f proto -o
<protofile> -p /voltha/experiments/netconf/tests/yang2proto
/voltha/experiments/netconf/tests/yang2proto/<yang file>
- pyang validates the yang definition first and then invoke this plugin
to convert the yang model into protobuf.
"""
from pyang import plugin, statements, error
from pyang.util import unique_prefixes
# Register the Protobuf plugin
def pyang_plugin_init():
plugin.register_plugin(ProtobufPlugin())
class Protobuf(object):
def __init__(self, module_name):
self.module_name = module_name.replace('-', '_')
self.tree = {}
self.containers = []
self.ylist = []
self.leafs = []
self.enums = []
self.headers = []
self.services = []
self.rpcs = []
def set_headers(self, module_name):
self.headers.append('syntax = "proto3";')
self.headers.append('package {};'.format(module_name.replace('-',
'_')))
def _filter_duplicate_names(self, list_obj):
current_names = []
def _filter_dup(obj):
if obj.name not in current_names:
current_names.append(obj.name)
return True
return filter(_filter_dup, list_obj)
def _print_rpc(self, out, level=0):
spaces = ' ' * level
out.append(''.join([spaces, 'service {} '.format(self.module_name)]))
out.append(''.join('{\n'))
rpc_space = spaces + ' '
for rpc in self.rpcs:
out.append(''.join([rpc_space, 'rpc {}({}) returns({})'.format(
rpc.name.replace('-','_'),
rpc.input.replace('-','_'),
rpc.output.replace('-','_'))]))
out.append(''.join(' {}\n'))
out.append(''.join([spaces, '}\n']))
def _print_container(self, container, out, level=0):
spaces = ' ' * level
out.append(''.join([spaces, 'message {} '.format(
container.name.replace('-','_'))]))
out.append(''.join('{\n'))
self._print_leaf(container.leafs, out, spaces=spaces)
for l in container.ylist:
self._print_list(l, out, level + 1)
for inner in container.containers:
self._print_container(inner, out, level + 1)
out.append(''.join([spaces, '}\n']))
def _print_list(self, ylist, out, level=0):
spaces = ' ' * level
out.append(''.join([spaces, 'message {} '.format(ylist.name.replace(
'-', '_'))]))
out.append(''.join('{\n'))
self._print_leaf(ylist.leafs, out, spaces=spaces)
for l in ylist.ylist:
self._print_list(l, out, level + 1)
out.append(''.join([spaces, '}\n']))
def _print_leaf(self, leafs, out, spaces='', include_message=False):
leafspaces = ''.join([spaces, ' '])
for idx, l in enumerate(leafs):
if l.type == "enum":
out.append(''.join([leafspaces, 'enum {}\n'.format(
l.name.replace('-','_'))]))
out.append(''.join([leafspaces, '{\n']))
self._print_enumeration(l.enumeration, out, leafspaces)
out.append(''.join([leafspaces, '}\n']))
else:
if include_message:
out.append(''.join([spaces, 'message {} '.format(
l.name.replace('-','_'))]))
out.append(''.join([spaces, '{\n']))
out.append(''.join([leafspaces, '{}{} {} = {} ;\n'.format(
'repeated ' if l.leaf_list else '',
l.type,
l.name.replace('-', '_'),
idx + 1)]))
if include_message:
out.append(''.join([spaces, '}\n']))
def _print_enumeration(self, yang_enum, out, spaces):
enumspaces = ''.join([spaces, ' '])
for idx, e in enumerate(yang_enum):
out.append(''.join([enumspaces, '{}\n'.format(e)]))
def print_proto(self):
out = []
for h in self.headers:
out.append('{}\n'.format(h))
out.append('\n')
if self.leafs:
# Risk of duplicates if leaf was processed as both a
# children and a substatement. Filter duplicates.
self.leafs = self._filter_duplicate_names(self.leafs)
self._print_leaf(self.leafs, out, spaces='', include_message=True)
out.append('\n')
if self.ylist:
# remove duplicates
self.ylist = self._filter_duplicate_names(self.ylist)
for l in self.ylist:
self._print_list(l, out)
out.append('\n')
if self.containers:
# remove duplicates
self.containers = self._filter_duplicate_names(self.containers)
for c in self.containers:
self._print_container(c, out)
out.append('\n')
if self.rpcs:
self.rpcs = self._filter_duplicate_names(self.rpcs)
self._print_rpc(out)
return out
class YangContainer(object):
def __init__(self):
self.name = None
self.containers = []
self.enums = []
self.leafs = []
self.ylist = []
class YangList(object):
def __init__(self):
self.name = None
self.leafs = []
self.containers = []
self.ylist = []
class YangLeaf(object):
def __init__(self):
self.name = None
self.type = None
self.leaf_list = False
self.enumeration = []
self.description = None
class YangEnumeration(object):
def __init__(self):
self.value = []
class YangRpc(object):
def __init__(self):
self.name = None
self.input = ''
self.output = ''
class ProtobufPlugin(plugin.PyangPlugin):
def add_output_format(self, fmts):
self.multiple_modules = True
fmts['proto'] = self
def setup_fmt(self, ctx):
ctx.implicit_errors = False
def emit(self, ctx, modules, fd):
"""Main control function.
"""
self.real_prefix = unique_prefixes(ctx)
for m in modules:
# m.pprint()
# statements.print_tree(m)
proto = Protobuf(m.i_modulename)
proto.set_headers(m.i_modulename)
self.process_substatements(m, proto, None)
self.process_children(m, proto, None)
out = proto.print_proto()
for i in out:
fd.write(i)
def process_substatements(self, node, parent, pmod):
"""Process all substmts.
"""
for st in node.substmts:
if st.keyword in ["rpc"]:
self.process_rpc(st, parent)
if st.keyword in ["notification"]:
continue
if st.keyword in ["choice", "case"]:
self.process_substatements(st, parent, pmod)
continue
if st.i_module.i_modulename == pmod:
nmod = pmod
else:
nmod = st.i_module.i_modulename
if st.keyword in ["container", "grouping"]:
c = YangContainer()
c.name = st.arg
self.process_substatements(st, c, nmod)
parent.containers.append(c)
elif st.keyword == "list":
l = YangList()
l.name = st.arg
self.process_substatements(st, l, nmod)
parent.ylist.append(l)
elif st.keyword in ["leaf", "leaf-list"]:
self.process_leaf(st, parent, st.keyword == "leaf-list")
def process_children(self, node, parent, pmod):
"""Process all children of `node`, except "rpc" and "notification".
"""
for ch in node.i_children:
if ch.keyword in ["rpc"]:
self.process_rpc(ch, parent)
if ch.keyword in ["notification"]:
continue
if ch.keyword in ["choice", "case"]:
self.process_children(ch, parent, pmod)
continue
if ch.i_module.i_modulename == pmod:
nmod = pmod
else:
nmod = ch.i_module.i_modulename
if ch.keyword in ["container", "grouping"]:
c = YangContainer()
c.name = ch.arg
self.process_children(ch, c, nmod)
parent.containers.append(c)
# self.process_container(ch, p, nmod)
elif ch.keyword == "list":
l = YangList()
l.name = ch.arg
self.process_children(ch, l, nmod)
parent.ylist.append(l)
elif ch.keyword in ["leaf", "leaf-list"]:
self.process_leaf(ch, parent, ch.keyword == "leaf-list")
def process_leaf(self, node, parent, leaf_list=False):
# Leaf have specific sub statements
leaf = YangLeaf()
leaf.name = node.arg
leaf.type = self.get_protobuf_type(node.search_one("type"))
if leaf.type == "enum":
self.process_enumeration(node, leaf)
# leaf.type = self.base_type(node.search_one("type"))
leaf.description = node.search_one("description")
leaf.leaf_list = leaf_list
parent.leafs.append(leaf)
def process_enumeration(self, node, leaf):
enumeration_dict = {}
start_node = None
for child in node.substmts:
if child.keyword == "type":
start_node = child;
break
for enum in start_node.search('enum'):
val = enum.search_one('value')
if val is not None:
enumeration_dict[enum.arg] = int(val.arg)
else:
enumeration_dict[enum.arg] = '0'
for key, value in enumerate(enumeration_dict):
leaf.enumeration.append('{} = {} ;'.format(value, key))
def process_rpc(self, node, parent):
yrpc = YangRpc()
yrpc.name = node.arg # name of rpc call
# look for input node
input_node = node.search_one("input")
if input_node and input_node.substmts:
self.process_children(input_node, parent, None)
# Get the first children - there should be only 1
yrpc.input = input_node.i_children[0].arg
output_node = node.search_one("output")
if output_node and output_node.substmts:
self.process_children(output_node, parent, None)
# Get the first children - there should be only 1
yrpc.output = output_node.i_children[0].arg
# print yrpc.ouput
# print yrpc.input
parent.rpcs.append(yrpc)
def get_protobuf_type(self, type):
type = self.base_type(type)
if type in self.protobuf_types_map.keys():
return self.protobuf_types_map[type]
else:
return type
def base_type(self, type):
"""Return the base type of `type`."""
while 1:
if type.arg == "leafref":
node = type.i_type_spec.i_target_node
elif type.i_typedef is None:
break
else:
node = type.i_typedef
type = node.search_one("type")
if type.arg == "decimal64":
return [type.arg, int(type.search_one("fraction-digits").arg)]
elif type.arg == "union":
# TODO convert union properly
return type.arg
# return [type.arg,
# [self.base_type(x) for x in type.i_type_spec.types]]
else:
return type.arg
protobuf_types_map = dict(
binary='Any',
bits='bytes',
boolean='bool',
decimal64='sint64',
empty='string',
int8='int32',
int16='int32',
int32='int32',
int64='int64',
string='string',
uint8='uint32',
uint16='uint32',
uint32='uint32',
uint64='uint64',
union='string', # TODO : not correct mapping
enumeration='enum'
)