blob: e2f24cae4cbc67e4ca270e8a3aaba173c3c46087 [file] [log] [blame]
Zsolt Haraszti162de172016-09-25 14:49:30 -07001#!/usr/bin/env python
2#
3# Copyright 2016 the original author or authors.
4#
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
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
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.
16#
17
18"""Load a protobuf description file an make sense of it"""
19
20# This is very experimental
21import os
22import inspect
23from collections import OrderedDict
24
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070025from google.protobuf.descriptor import FieldDescriptor, Descriptor
26from google.protobuf.message import Message
Zsolt Haraszti162de172016-09-25 14:49:30 -070027from simplejson import dumps
28
29from google.protobuf import descriptor_pb2
30
Zsolt Haraszti162de172016-09-25 14:49:30 -070031from google.api import http_pb2
32
33
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070034class InvalidDescriptorError(Exception): pass
Zsolt Haraszti162de172016-09-25 14:49:30 -070035
36
37class DescriptorParser(object):
38
39 def __init__(self, ignore_empty_source_code_info=True):
40 self.ignore_empty_source_code_info = ignore_empty_source_code_info
41 self.catalog = {}
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070042 self.meta, blob = self.load_root_descriptor()
43 self.load_descriptor(blob)
44
45 def load_root_descriptor(self):
46 """Load descriptor.desc to make things more data driven"""
47 with open('descriptor.desc', 'r') as f:
48 blob = f.read()
49 proto = descriptor_pb2.FileDescriptorSet()
50 proto.ParseFromString(blob)
51 assert len(proto.file) == 1
52 fdp = proto.file[0]
53
54 # for i, (fd, v) in enumerate(fdp.ListFields()):
55 # assert isinstance(fd, FieldDescriptor)
56 # print fd.name, fd.full_name, fd.number, fd.type, fd.label, fd.message_type, type(v)
57
58 return fdp, blob
Zsolt Haraszti162de172016-09-25 14:49:30 -070059
60 def get_catalog(self):
61 return self.catalog
62
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070063 def load_descriptor(self, descriptor_blob,
64 fold_comments=True,
65 type_tag_name='_type'):
Zsolt Haraszti162de172016-09-25 14:49:30 -070066
67 # decode desciription
68 file_descriptor_set = descriptor_pb2.FileDescriptorSet()
69 file_descriptor_set.ParseFromString(descriptor_blob)
70
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070071 d = self.parse(file_descriptor_set, type_tag_name=type_tag_name)
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070072 for _file in d['file']:
73 if fold_comments:
74 self.fold_comments_in(_file)
75 self.catalog[_file['package']] = _file
Zsolt Haraszti162de172016-09-25 14:49:30 -070076
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070077 def parse_message(self, m, type_tag_name=None):
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070078 assert isinstance(m, Message)
Zsolt Haraszti162de172016-09-25 14:49:30 -070079 d = OrderedDict()
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070080 for fd, v in m.ListFields():
81 assert isinstance(fd, FieldDescriptor)
82 if fd.label in (1, 2):
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070083 d[fd.name] = self.parse(v, type_tag_name)
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070084 elif fd.label == 3:
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070085 d[fd.name] = [self.parse(x, type_tag_name) for x in v]
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070086 else:
87 raise InvalidDescriptorError()
88
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -070089 if type_tag_name is not None:
90 d[type_tag_name] = m.DESCRIPTOR.full_name
91
Zsolt Haraszti162de172016-09-25 14:49:30 -070092 return d
93
Zsolt Harasztid9f400f2016-09-25 17:19:49 -070094 parser_table = {
95 unicode: lambda x: x,
96 int: lambda x: x,
97 bool: lambda x: x,
98 }
Zsolt Haraszti162de172016-09-25 14:49:30 -070099
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -0700100 def parse(self, o, type_tag_name=None):
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700101 if isinstance(o, Message):
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -0700102 return self.parse_message(o, type_tag_name)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700103 else:
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700104 return self.parser_table[type(o)](o)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700105
106 def fold_comments_in(self, descriptor):
107 assert isinstance(descriptor, dict)
108
109 locations = descriptor.get('source_code_info', {}).get('location', [])
110 for location in locations:
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700111 path = location.get('path', [])
Zsolt Haraszti162de172016-09-25 14:49:30 -0700112 comments = ''.join([
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700113 location.get('leading_comments', '').strip(' '),
114 location.get('trailing_comments', '').strip(' '),
Zsolt Haraszti162de172016-09-25 14:49:30 -0700115 ''.join(block.strip(' ') for block
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700116 in location.get('leading_detached_comments', ''))
Zsolt Haraszti162de172016-09-25 14:49:30 -0700117 ]).strip()
Zsolt Haraszti162de172016-09-25 14:49:30 -0700118
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700119 # ignore locations with no comments
120 if not comments:
121 continue
Zsolt Haraszti162de172016-09-25 14:49:30 -0700122
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700123 # we ignore path with odd number of entries, since these do
124 # not address our schema nodes, but rather the meta schema
125 if (len(path) % 2 == 0):
126 node = self.find_node_by_path(
127 path, self.meta.DESCRIPTOR, descriptor)
128 assert isinstance(node, dict)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700129 node['_description'] = comments
130
131 # remove source_code_info
132 del descriptor['source_code_info']
133
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700134 def find_node_by_path(self, path, meta, o):
Zsolt Haraszti162de172016-09-25 14:49:30 -0700135
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700136 # stop recursion when path is empty
Zsolt Haraszti162de172016-09-25 14:49:30 -0700137 if not path:
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700138 return o
Zsolt Haraszti162de172016-09-25 14:49:30 -0700139
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700140 # sanity check
141 assert len(path) >= 2
142 assert isinstance(meta, Descriptor)
143 assert isinstance(o, dict)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700144
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700145 # find field name, then actual field
146 field_number = path.pop(0)
147 field_def = meta.fields_by_number[field_number]
148 field = o[field_def.name]
Zsolt Haraszti162de172016-09-25 14:49:30 -0700149
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700150 # field must be a list, extract entry with given index
151 assert isinstance(field, list) # expected to be a list field
Zsolt Haraszti162de172016-09-25 14:49:30 -0700152 index = path.pop(0)
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700153 child_o = field[index]
Zsolt Haraszti162de172016-09-25 14:49:30 -0700154
Zsolt Harasztid9f400f2016-09-25 17:19:49 -0700155 child_meta = field_def.message_type
156 return self.find_node_by_path(path, child_meta, child_o)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700157
158
159if __name__ == '__main__':
Zsolt Haraszti162de172016-09-25 14:49:30 -0700160
Zsolt Haraszti80259ec2016-09-25 22:38:03 -0700161 # try loading voltha descriptor and turn it into JSON data as a preparation
162 # for generating JSON Schema / swagger file (to be done later)
Zsolt Haraszti5cd64702016-09-27 13:48:35 -0700163 from voltha.protos import voltha_pb2
Zsolt Haraszti162de172016-09-25 14:49:30 -0700164 desc_dir = os.path.dirname(inspect.getfile(voltha_pb2))
165 desc_file = os.path.join(desc_dir, 'voltha.desc')
166 with open(desc_file, 'rb') as f:
167 descriptor_blob = f.read()
Zsolt Haraszti162de172016-09-25 14:49:30 -0700168 parser = DescriptorParser()
169 parser.load_descriptor(descriptor_blob)
Zsolt Haraszti162de172016-09-25 14:49:30 -0700170 print dumps(parser.get_catalog(), indent=4)
171
Zsolt Haraszti80259ec2016-09-25 22:38:03 -0700172 # try to see if we can decode binary data into JSON automatically
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -0700173 from random import seed, randint
174 seed(0)
175
176 def make_mc(name, n_children=0):
177 mc = voltha_pb2.MoreComplex(
178 name=name,
179 foo_counter=randint(0, 10000),
180 health=voltha_pb2.HealthStatus(
181 state=voltha_pb2.HealthStatus.OVERLOADED
182 ),
183 address=voltha_pb2.MoreComplex.Address(
184 street='1383 N McDowell Blvd',
185 city='Petaluma',
186 zip=94954,
187 state='CA'
188 ),
189 children=[make_mc('child%d' % (i + 1)) for i in xrange(n_children)]
190 )
Zsolt Haraszti80259ec2016-09-25 22:38:03 -0700191 return mc
Zsolt Haraszti162de172016-09-25 14:49:30 -0700192
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -0700193 mc = make_mc('root', 3)
Zsolt Haraszti80259ec2016-09-25 22:38:03 -0700194 blob = mc.SerializeToString()
195 print len(blob), 'bytes'
196 mc2 = voltha_pb2.MoreComplex()
197 mc2.ParseFromString(blob)
198 assert mc == mc2
199
Zsolt Haraszti0650d1a2016-09-26 17:29:25 -0700200 print dumps(parser.parse(mc, type_tag_name='_type'), indent=4)