Fixes for latest juju-2 beta
[osm/N2VC.git] / juju / client / facade.py
1 import argparse
2 import builtins
3 import functools
4 import json
5 import keyword
6 from pathlib import Path
7 import pprint
8 import textwrap
9 from typing import Sequence, Mapping, TypeVar, Any, Union
10 import typing
11
12 from . import codegen
13
14 _marker = object()
15
16 # Map basic types to Python's typing with a callable
17 SCHEMA_TO_PYTHON = {
18 'string': str,
19 'integer': int,
20 'float': float,
21 'number': float,
22 'boolean': bool,
23 'object': Any,
24 }
25
26
27 class KindRegistry(dict):
28 def register(self, name, version, obj):
29 self[name] = {version: {
30 "object": obj,
31 }}
32
33 def lookup(self, name, version=None):
34 """If version is omitted, max version is used"""
35 versions = self.get(name)
36 if not versions:
37 return None
38 if version:
39 return versions[version]
40 return versions[max(versions)]
41
42 def getObj(self, name, version=None):
43 result = self.lookup(name, version)
44 if result:
45 obj = result["object"]
46 return obj
47 return None
48
49
50 class TypeRegistry(dict):
51 def get(self, name):
52 # Two way mapping
53 refname = Schema.referenceName(name)
54 if refname not in self:
55 result = TypeVar(refname)
56 self[refname] = result
57 self[result] = refname
58
59 return self[refname]
60
61 _types = TypeRegistry()
62 _registry = KindRegistry()
63 classes = {}
64
65
66 def booler(v):
67 if isinstance(v, str):
68 if v == "false":
69 return False
70 return bool(v)
71
72
73 def getRefType(ref):
74 return _types.get(ref)
75
76
77 def refType(obj):
78 return getRefType(obj["$ref"])
79
80
81 def objType(obj):
82 kind = obj.get('type')
83 if not kind:
84 raise ValueError("%s has no type" % obj)
85 result = SCHEMA_TO_PYTHON.get(kind)
86 if not result:
87 raise ValueError("%s has type %s" % (obj, kind))
88 return result
89
90
91 basic_types = [str, bool, int, float]
92
93
94 def name_to_py(name):
95 result = name.replace("-", "_")
96 result = result.lower()
97 if keyword.iskeyword(result) or result in dir(builtins):
98 result += "_"
99 return result
100
101
102 def strcast(kind, keep_builtins=False):
103 if issubclass(kind, typing.GenericMeta):
104 return str(kind)[1:]
105 if str(kind).startswith('~'):
106 return str(kind)[1:]
107 if (kind in basic_types or
108 type(kind) in basic_types) and keep_builtins is False:
109 return kind.__name__
110 return kind
111
112
113 class Args(list):
114 def __init__(self, defs):
115 self.defs = defs
116 if defs:
117 rtypes = _registry.getObj(_types[defs])
118 if len(rtypes) == 1:
119 if not self.do_explode(rtypes[0][1]):
120 for name, rtype in rtypes:
121 self.append((name, rtype))
122 else:
123 for name, rtype in rtypes:
124 self.append((name, rtype))
125
126 def do_explode(self, kind):
127 if kind in basic_types:
128 return False
129 if not issubclass(kind, (typing.Sequence,
130 typing.Mapping)):
131 self.clear()
132 self.extend(Args(kind))
133 return True
134 return False
135
136 def PyToSchemaMapping(self):
137 m = {}
138 for n, rt in self:
139 m[name_to_py(n)] = n
140 return m
141
142 def SchemaToPyMapping(self):
143 m = {}
144 for n, tr in self:
145 m[n] = name_to_py(n)
146 return m
147
148 def _format(self, name, rtype, typed=True):
149 if typed:
150 return "{} : {}".format(
151 name_to_py(name),
152 strcast(rtype)
153 )
154 else:
155 return name_to_py(name)
156
157 def _get_arg_str(self, typed=False, joined=", "):
158 if self:
159 parts = []
160 for item in self:
161 parts.append(self._format(item[0], item[1], typed))
162 if joined:
163 return joined.join(parts)
164 return parts
165 return ''
166
167 def as_kwargs(self):
168 if self:
169 parts = []
170 for item in self:
171 parts.append('{}=None'.format(name_to_py(item[0])))
172 return ', '.join(parts)
173 return ''
174
175 def typed(self):
176 return self._get_arg_str(True)
177
178 def __str__(self):
179 return self._get_arg_str(False)
180
181 def get_doc(self):
182 return self._get_arg_str(True, "\n")
183
184
185 def buildTypes(schema, capture):
186 global classes
187 INDENT = " "
188 for kind in sorted((k for k in _types if not isinstance(k, str)),
189 key=lambda x: str(x)):
190 name = _types[kind]
191 args = Args(kind)
192 if name in classes:
193 continue
194 source = ["""
195 class {}(Type):
196 _toSchema = {}
197 _toPy = {}
198 def __init__(self{}{}):
199 '''
200 {}
201 '''""".format(
202 name,
203 args.PyToSchemaMapping(),
204 args.SchemaToPyMapping(),
205 ", " if args else "",
206 args.as_kwargs(),
207 textwrap.indent(args.get_doc(), INDENT * 2))
208 ]
209 assignments = args._get_arg_str(False, False)
210
211 if not args:
212 source.append("{}pass".format(INDENT * 2))
213 else:
214 for arg in args:
215 arg_name = name_to_py(arg[0])
216 arg_type = arg[1]
217 arg_type_name = strcast(arg_type)
218 if arg_type in basic_types:
219 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
220 elif issubclass(arg_type, typing.Sequence):
221 value_type = (
222 arg_type_name.__parameters__[0]
223 if len(arg_type_name.__parameters__)
224 else None
225 )
226 if type(value_type) is typing.TypeVar:
227 source.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
228 INDENT * 2, arg_name, strcast(value_type), arg_name))
229 else:
230 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
231 elif issubclass(arg_type, typing.Mapping):
232 value_type = (
233 arg_type_name.__parameters__[1]
234 if len(arg_type_name.__parameters__) > 1
235 else None
236 )
237 if type(value_type) is typing.TypeVar:
238 source.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
239 INDENT * 2, arg_name, strcast(value_type), arg_name))
240 else:
241 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
242 elif type(arg_type) is typing.TypeVar:
243 source.append("{}self.{} = {}.from_json({}) if {} else None".format(
244 INDENT * 2, arg_name, arg_type_name, arg_name, arg_name))
245 else:
246 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
247
248 source = "\n".join(source)
249 capture.write(source)
250 capture.write("\n\n")
251 co = compile(source, __name__, "exec")
252 ns = _getns()
253 exec(co, ns)
254 cls = ns[name]
255 classes[name] = cls
256
257
258 def retspec(defs):
259 # return specs
260 # only return 1, so if there is more than one type
261 # we need to include a union
262 # In truth there is only 1 return
263 # Error or the expected Type
264 if not defs:
265 return None
266 rtypes = _registry.getObj(_types[defs])
267 if not rtypes:
268 return None
269 if len(rtypes) > 1:
270 return Union[tuple([strcast(r[1], True) for r in rtypes])]
271 return strcast(rtypes[0][1], False)
272
273
274 def return_type(defs):
275 if not defs:
276 return None
277 rtypes = _registry.getObj(_types[defs])
278 if not rtypes:
279 return None
280 if len(rtypes) > 1:
281 for n, t in rtypes:
282 if n == "Error":
283 continue
284 return t
285 return rtypes[0][1]
286
287
288 def type_anno_func(func, defs, is_result=False):
289 annos = {}
290 if not defs:
291 return func
292 rtypes = _registry.getObj(_types[defs])
293 if is_result:
294 kn = "return"
295 if not rtypes:
296 annos[kn] = None
297 elif len(rtypes) > 1:
298 annos[kn] = Union[tuple([r[1] for r in rtypes])]
299 else:
300 annos[kn] = rtypes[0][1]
301 else:
302 for name, rtype in rtypes:
303 name = name_to_py(name)
304 annos[name] = rtype
305 func.__annotations__.update(annos)
306 return func
307
308
309 def ReturnMapping(cls):
310 # Annotate the method with a return Type
311 # so the value can be cast
312 def decorator(f):
313 @functools.wraps(f)
314 async def wrapper(*args, **kwargs):
315 nonlocal cls
316 reply = await f(*args, **kwargs)
317 if cls is None:
318 return reply
319 if 'error' in reply:
320 cls = classes['Error']
321 if issubclass(cls, typing.Sequence):
322 result = []
323 item_cls = cls.__parameters__[0]
324 for item in reply:
325 result.append(item_cls.from_json(item))
326 else:
327 result = cls.from_json(reply['response'])
328
329 return result
330 return wrapper
331 return decorator
332
333
334 def makeFunc(cls, name, params, result, async=True):
335 INDENT = " "
336 args = Args(params)
337 assignments = []
338 toschema = args.PyToSchemaMapping()
339 for arg in args._get_arg_str(False, False):
340 assignments.append("{}params[\'{}\'] = {}".format(INDENT,
341 toschema[arg],
342 arg))
343 assignments = "\n".join(assignments)
344 res = retspec(result)
345 source = """
346
347 @ReturnMapping({rettype})
348 {async}def {name}(self{argsep}{args}):
349 '''
350 {docstring}
351 Returns -> {res}
352 '''
353 # map input types to rpc msg
354 params = dict()
355 msg = dict(type='{cls.name}', request='{name}', version={cls.version}, params=params)
356 {assignments}
357 reply = {await}self.rpc(msg)
358 return reply
359
360 """
361
362 fsource = source.format(async="async " if async else "",
363 name=name,
364 argsep=", " if args else "",
365 args=args,
366 res=res,
367 rettype=result.__name__ if result else None,
368 docstring=textwrap.indent(args.get_doc(), INDENT),
369 cls=cls,
370 assignments=assignments,
371 await="await " if async else "")
372 ns = _getns()
373 exec(fsource, ns)
374 func = ns[name]
375 return func, fsource
376
377
378 def buildMethods(cls, capture):
379 properties = cls.schema['properties']
380 for methodname in sorted(properties):
381 method, source = _buildMethod(cls, methodname)
382 setattr(cls, methodname, method)
383 capture.write(source, depth=1)
384
385
386 def _buildMethod(cls, name):
387 params = None
388 result = None
389 method = cls.schema['properties'][name]
390 if 'properties' in method:
391 prop = method['properties']
392 spec = prop.get('Params')
393 if spec:
394 params = _types.get(spec['$ref'])
395 spec = prop.get('Result')
396 if spec:
397 result = _types.get(spec['$ref'])
398 return makeFunc(cls, name, params, result)
399
400
401 def buildFacade(schema):
402 cls = type(schema.name, (Type,), dict(name=schema.name,
403 version=schema.version,
404 schema=schema))
405 source = """
406 class {name}Facade(Type):
407 name = '{name}'
408 version = {version}
409 schema = {schema}
410 """.format(name=schema.name,
411 version=schema.version,
412 schema=textwrap.indent(pprint.pformat(schema), " "))
413 return cls, source
414
415
416 class TypeEncoder(json.JSONEncoder):
417 def default(self, obj):
418 if isinstance(obj, Type):
419 return obj.serialize()
420 return json.JSONEncoder.default(self, obj)
421
422
423 class Type:
424 def connect(self, connection):
425 self.connection = connection
426
427 async def rpc(self, msg):
428 result = await self.connection.rpc(msg, encoder=TypeEncoder)
429 return result
430
431 @classmethod
432 def from_json(cls, data):
433 if isinstance(data, str):
434 data = json.loads(data)
435 d = {}
436 for k, v in (data or {}).items():
437 d[cls._toPy.get(k, k)] = v
438
439 try:
440 return cls(**d)
441 except TypeError:
442 print(cls)
443 raise
444
445 def serialize(self):
446 d = {}
447 for attr, tgt in self._toSchema.items():
448 d[tgt] = getattr(self, attr)
449 return d
450
451 def to_json(self):
452 return json.dumps(self.serialize())
453
454
455 class Schema(dict):
456 def __init__(self, schema):
457 self.name = schema['Name']
458 self.version = schema['Version']
459 self.update(schema['Schema'])
460
461 @classmethod
462 def referenceName(cls, ref):
463 if ref.startswith("#/definitions/"):
464 ref = ref.rsplit("/", 1)[-1]
465 return ref
466
467 def resolveDefinition(self, ref):
468 return self['definitions'][self.referenceName(ref)]
469
470 def deref(self, prop, name):
471 if not isinstance(prop, dict):
472 raise TypeError(prop)
473 if "$ref" not in prop:
474 return prop
475
476 target = self.resolveDefinition(prop["$ref"])
477 return target
478
479 def buildDefinitions(self):
480 # here we are building the types out
481 # anything in definitions is a type
482 # but these may contain references themselves
483 # so we dfs to the bottom and build upwards
484 # when a types is already in the registry
485 defs = self.get('definitions')
486 if not defs:
487 return
488 for d, data in defs.items():
489 if d in _registry:
490 continue
491 node = self.deref(data, d)
492 kind = node.get("type")
493 if kind == "object":
494 result = self.buildObject(node, d)
495 elif kind == "array":
496 pass
497 _registry.register(d, self.version, result)
498 # XXX: This makes sure that the type gets added to the global
499 # _types dict even if no other type in the schema has a ref
500 # to it.
501 getRefType(d)
502
503 def buildObject(self, node, name=None, d=0):
504 # we don't need to build types recursively here
505 # they are all in definitions already
506 # we only want to include the type reference
507 # which we can derive from the name
508 struct = []
509 add = struct.append
510 props = node.get("properties")
511 pprops = node.get("patternProperties")
512 if props:
513 # Sort these so the __init__ arg list for each Type remains
514 # consistently ordered across regens of client.py
515 for p in sorted(props):
516 prop = props[p]
517 if "$ref" in prop:
518 add((p, refType(prop)))
519 else:
520 kind = prop['type']
521 if kind == "array":
522 add((p, self.buildArray(prop, d + 1)))
523 elif kind == "object":
524 struct.extend(self.buildObject(prop, p, d + 1))
525 else:
526 add((p, objType(prop)))
527 if pprops:
528 if ".*" not in pprops:
529 raise ValueError(
530 "Cannot handle actual pattern in patternProperties %s" %
531 pprops)
532 pprop = pprops[".*"]
533 if "$ref" in pprop:
534 add((name, Mapping[str, refType(pprop)]))
535 return struct
536 ppkind = pprop["type"]
537 if ppkind == "array":
538 add((name, self.buildArray(pprop, d + 1)))
539 else:
540 add((name, Mapping[str, SCHEMA_TO_PYTHON[ppkind]]))
541
542 if not struct and node.get('additionalProperties', False):
543 add((name, Mapping[str, SCHEMA_TO_PYTHON['object']]))
544
545 return struct
546
547 def buildArray(self, obj, d=0):
548 # return a sequence from an array in the schema
549 if "$ref" in obj:
550 return Sequence[refType(obj)]
551 else:
552 kind = obj.get("type")
553 if kind and kind == "array":
554 items = obj['items']
555 return self.buildArray(items, d + 1)
556 else:
557 return Sequence[objType(obj)]
558
559
560 def _getns():
561 ns = {'Type': Type,
562 'typing': typing,
563 'ReturnMapping': ReturnMapping
564 }
565 # Copy our types into the globals of the method
566 for facade in _registry:
567 ns[facade] = _registry.getObj(facade)
568 return ns
569
570
571
572 def generate_facacdes(options):
573 global classes
574 schemas = json.loads(Path(options.schema).read_text("utf-8"))
575 capture = codegen.CodeWriter()
576 capture.write(textwrap.dedent("""\
577 # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
578 # Changes will be overwritten/lost when the file is regenerated.
579
580 from juju.client.facade import Type, ReturnMapping
581
582 """))
583 schemas = [Schema(s) for s in schemas]
584
585 for schema in schemas:
586 schema.buildDefinitions()
587 buildTypes(schema, capture)
588
589 for schema in schemas:
590 # TODO generate class now with a metaclass that takes the schema
591 # the generated class has the right name and it in turn uses
592 # the metaclass to populate cls
593 cls, source = buildFacade(schema)
594 capture.write(source)
595 buildMethods(cls, capture)
596 classes[schema.name] = cls
597
598 return capture
599
600 def setup():
601 parser = argparse.ArgumentParser()
602 parser.add_argument("-s", "--schema", default="schemas.json")
603 parser.add_argument("-o", "--output", default="client.py")
604 options = parser.parse_args()
605 return options
606
607 def main():
608 options = setup()
609 capture = generate_facacdes(options)
610 with open(options.output, "w") as fp:
611 print(capture, file=fp)
612
613
614
615 if __name__ == '__main__':
616 main()