Hook up Unit.run() to api
[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 = arg_type_name.__parameters__[0]
222 if type(value_type) is typing.TypeVar:
223 source.append("{}self.{} = [{}.from_json(o) for o in {} or []]".format(
224 INDENT * 2, arg_name, strcast(value_type), arg_name))
225 else:
226 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
227 elif issubclass(arg_type, typing.Mapping):
228 value_type = arg_type_name.__parameters__[1]
229 if type(value_type) is typing.TypeVar:
230 source.append("{}self.{} = {{k: {}.from_json(v) for k, v in ({} or dict()).items()}}".format(
231 INDENT * 2, arg_name, strcast(value_type), arg_name))
232 else:
233 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
234 elif type(arg_type) is typing.TypeVar:
235 source.append("{}self.{} = {}.from_json({}) if {} else None".format(
236 INDENT * 2, arg_name, arg_type_name, arg_name, arg_name))
237 else:
238 source.append("{}self.{} = {}".format(INDENT * 2, arg_name, arg_name))
239
240 source = "\n".join(source)
241 capture.write(source)
242 capture.write("\n\n")
243 co = compile(source, __name__, "exec")
244 ns = _getns()
245 exec(co, ns)
246 cls = ns[name]
247 classes[name] = cls
248
249
250 def retspec(defs):
251 # return specs
252 # only return 1, so if there is more than one type
253 # we need to include a union
254 # In truth there is only 1 return
255 # Error or the expected Type
256 if not defs:
257 return None
258 rtypes = _registry.getObj(_types[defs])
259 if not rtypes:
260 return None
261 if len(rtypes) > 1:
262 return Union[tuple([strcast(r[1], True) for r in rtypes])]
263 return strcast(rtypes[0][1], False)
264
265
266 def return_type(defs):
267 if not defs:
268 return None
269 rtypes = _registry.getObj(_types[defs])
270 if not rtypes:
271 return None
272 if len(rtypes) > 1:
273 for n, t in rtypes:
274 if n == "Error":
275 continue
276 return t
277 return rtypes[0][1]
278
279
280 def type_anno_func(func, defs, is_result=False):
281 annos = {}
282 if not defs:
283 return func
284 rtypes = _registry.getObj(_types[defs])
285 if is_result:
286 kn = "return"
287 if not rtypes:
288 annos[kn] = None
289 elif len(rtypes) > 1:
290 annos[kn] = Union[tuple([r[1] for r in rtypes])]
291 else:
292 annos[kn] = rtypes[0][1]
293 else:
294 for name, rtype in rtypes:
295 name = name_to_py(name)
296 annos[name] = rtype
297 func.__annotations__.update(annos)
298 return func
299
300
301 def ReturnMapping(cls):
302 # Annotate the method with a return Type
303 # so the value can be cast
304 def decorator(f):
305 @functools.wraps(f)
306 async def wrapper(*args, **kwargs):
307 nonlocal cls
308 reply = await f(*args, **kwargs)
309 if cls is None:
310 return reply
311 if 'Error' in reply:
312 cls = classes['Error']
313 if issubclass(cls, typing.Sequence):
314 result = []
315 item_cls = cls.__parameters__[0]
316 for item in reply:
317 result.append(item_cls.from_json(item))
318 else:
319 result = cls.from_json(reply['Response'])
320
321 return result
322 return wrapper
323 return decorator
324
325
326 def makeFunc(cls, name, params, result, async=True):
327 INDENT = " "
328 args = Args(params)
329 assignments = []
330 toschema = args.PyToSchemaMapping()
331 for arg in args._get_arg_str(False, False):
332 assignments.append("{}params[\'{}\'] = {}".format(INDENT,
333 toschema[arg],
334 arg))
335 assignments = "\n".join(assignments)
336 res = retspec(result)
337 source = """
338
339 @ReturnMapping({rettype})
340 {async}def {name}(self{argsep}{args}):
341 '''
342 {docstring}
343 Returns -> {res}
344 '''
345 # map input types to rpc msg
346 params = dict()
347 msg = dict(Type='{cls.name}', Request='{name}', Version={cls.version}, Params=params)
348 {assignments}
349 reply = {await}self.rpc(msg)
350 return reply
351
352 """
353
354 fsource = source.format(async="async " if async else "",
355 name=name,
356 argsep=", " if args else "",
357 args=args,
358 res=res,
359 rettype=result.__name__ if result else None,
360 docstring=textwrap.indent(args.get_doc(), INDENT),
361 cls=cls,
362 assignments=assignments,
363 await="await " if async else "")
364 ns = _getns()
365 exec(fsource, ns)
366 func = ns[name]
367 return func, fsource
368
369
370 def buildMethods(cls, capture):
371 properties = cls.schema['properties']
372 for methodname in sorted(properties):
373 method, source = _buildMethod(cls, methodname)
374 setattr(cls, methodname, method)
375 capture.write(source, depth=1)
376
377
378 def _buildMethod(cls, name):
379 params = None
380 result = None
381 method = cls.schema['properties'][name]
382 if 'properties' in method:
383 prop = method['properties']
384 spec = prop.get('Params')
385 if spec:
386 params = _types.get(spec['$ref'])
387 spec = prop.get('Result')
388 if spec:
389 result = _types.get(spec['$ref'])
390 return makeFunc(cls, name, params, result)
391
392
393 def buildFacade(schema):
394 cls = type(schema.name, (Type,), dict(name=schema.name,
395 version=schema.version,
396 schema=schema))
397 source = """
398 class {name}Facade(Type):
399 name = '{name}'
400 version = {version}
401 schema = {schema}
402 """.format(name=schema.name,
403 version=schema.version,
404 schema=textwrap.indent(pprint.pformat(schema), " "))
405 return cls, source
406
407
408 class TypeEncoder(json.JSONEncoder):
409 def default(self, obj):
410 if isinstance(obj, Type):
411 return obj.serialize()
412 return json.JSONEncoder.default(self, obj)
413
414
415 class Type:
416 def connect(self, connection):
417 self.connection = connection
418
419 async def rpc(self, msg):
420 result = await self.connection.rpc(msg, encoder=TypeEncoder)
421 return result
422
423 @classmethod
424 def from_json(cls, data):
425 if isinstance(data, str):
426 data = json.loads(data)
427 d = {}
428 for k, v in (data or {}).items():
429 d[cls._toPy.get(k, k)] = v
430
431 try:
432 return cls(**d)
433 except TypeError:
434 print(cls)
435 raise
436
437 def serialize(self):
438 d = {}
439 for attr, tgt in self._toSchema.items():
440 d[tgt] = getattr(self, attr)
441 return d
442
443 def to_json(self):
444 return json.dumps(self.serialize())
445
446
447 class Schema(dict):
448 def __init__(self, schema):
449 self.name = schema['Name']
450 self.version = schema['Version']
451 self.update(schema['Schema'])
452
453 @classmethod
454 def referenceName(cls, ref):
455 if ref.startswith("#/definitions/"):
456 ref = ref.rsplit("/", 1)[-1]
457 return ref
458
459 def resolveDefinition(self, ref):
460 return self['definitions'][self.referenceName(ref)]
461
462 def deref(self, prop, name):
463 if not isinstance(prop, dict):
464 raise TypeError(prop)
465 if "$ref" not in prop:
466 return prop
467
468 target = self.resolveDefinition(prop["$ref"])
469 return target
470
471 def buildDefinitions(self):
472 # here we are building the types out
473 # anything in definitions is a type
474 # but these may contain references themselves
475 # so we dfs to the bottom and build upwards
476 # when a types is already in the registry
477 defs = self.get('definitions')
478 if not defs:
479 return
480 for d, data in defs.items():
481 if d in _registry:
482 continue
483 node = self.deref(data, d)
484 kind = node.get("type")
485 if kind == "object":
486 result = self.buildObject(node, d)
487 elif kind == "array":
488 pass
489 _registry.register(d, self.version, result)
490 # XXX: This makes sure that the type gets added to the global
491 # _types dict even if no other type in the schema has a ref
492 # to it.
493 getRefType(d)
494
495 def buildObject(self, node, name=None, d=0):
496 # we don't need to build types recursively here
497 # they are all in definitions already
498 # we only want to include the type reference
499 # which we can derive from the name
500 struct = []
501 add = struct.append
502 props = node.get("properties")
503 pprops = node.get("patternProperties")
504 if props:
505 # Sort these so the __init__ arg list for each Type remains
506 # consistently ordered across regens of client.py
507 for p in sorted(props):
508 prop = props[p]
509 if "$ref" in prop:
510 add((p, refType(prop)))
511 else:
512 kind = prop['type']
513 if kind == "array":
514 add((p, self.buildArray(prop, d + 1)))
515 elif kind == "object":
516 struct.extend(self.buildObject(prop, p, d + 1))
517 else:
518 add((p, objType(prop)))
519 if pprops:
520 if ".*" not in pprops:
521 raise ValueError(
522 "Cannot handle actual pattern in patternProperties %s" %
523 pprops)
524 pprop = pprops[".*"]
525 if "$ref" in pprop:
526 add((name, Mapping[str, refType(pprop)]))
527 return struct
528 ppkind = pprop["type"]
529 if ppkind == "array":
530 add((name, self.buildArray(pprop, d + 1)))
531 else:
532 add((name, Mapping[str, SCHEMA_TO_PYTHON[ppkind]]))
533
534 if not struct and node.get('additionalProperties', False):
535 add((name, Mapping[str, SCHEMA_TO_PYTHON['object']]))
536
537 return struct
538
539 def buildArray(self, obj, d=0):
540 # return a sequence from an array in the schema
541 if "$ref" in obj:
542 return Sequence[refType(obj)]
543 else:
544 kind = obj.get("type")
545 if kind and kind == "array":
546 items = obj['items']
547 return self.buildArray(items, d + 1)
548 else:
549 return Sequence[objType(obj)]
550
551
552 def _getns():
553 ns = {'Type': Type,
554 'typing': typing,
555 'ReturnMapping': ReturnMapping
556 }
557 # Copy our types into the globals of the method
558 for facade in _registry:
559 ns[facade] = _registry.getObj(facade)
560 return ns
561
562
563
564 def generate_facacdes(options):
565 global classes
566 schemas = json.loads(Path(options.schema).read_text("utf-8"))
567 capture = codegen.CodeWriter()
568 capture.write(textwrap.dedent("""\
569 # DO NOT CHANGE THIS FILE! This file is auto-generated by facade.py.
570 # Changes will be overwritten/lost when the file is regenerated.
571
572 from juju.client.facade import Type, ReturnMapping
573
574 """))
575 schemas = [Schema(s) for s in schemas]
576
577 for schema in schemas:
578 schema.buildDefinitions()
579 buildTypes(schema, capture)
580
581 for schema in schemas:
582 # TODO generate class now with a metaclass that takes the schema
583 # the generated class has the right name and it in turn uses
584 # the metaclass to populate cls
585 cls, source = buildFacade(schema)
586 capture.write(source)
587 buildMethods(cls, capture)
588 classes[schema.name] = cls
589
590 return capture
591
592 def setup():
593 parser = argparse.ArgumentParser()
594 parser.add_argument("-s", "--schema", default="schemas.json")
595 parser.add_argument("-o", "--output", default="client.py")
596 options = parser.parse_args()
597 return options
598
599 def main():
600 options = setup()
601 capture = generate_facacdes(options)
602 with open(options.output, "w") as fp:
603 print(capture, file=fp)
604
605
606
607 if __name__ == '__main__':
608 main()