Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 1 | from resources import RESOURCES |
| 2 | |
| 3 | class GRPCModelsAccessor: |
| 4 | """ |
| 5 | This class provide the glue between the models managed by TOSCA and the ones living in xos-core |
| 6 | """ |
| 7 | |
| 8 | @staticmethod |
Matteo Scandolo | 21dde41 | 2017-07-11 18:54:12 -0700 | [diff] [blame^] | 9 | def get_model_from_classname(class_name, data, username, password): |
Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 10 | """ |
| 11 | Give a Model Class Name and some data, check if that exits or instantiate a new one |
| 12 | """ |
| 13 | |
Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 14 | if data.get('name'): |
| 15 | used_key = 'name' |
| 16 | else: |
| 17 | used_key = data.keys()[0] |
| 18 | |
Matteo Scandolo | 21dde41 | 2017-07-11 18:54:12 -0700 | [diff] [blame^] | 19 | key = "%s~%s" % (username, password) |
| 20 | if not key in RESOURCES: |
| 21 | raise Exception("[XOS-TOSCA] User '%s' does not have ready resources" % username) |
| 22 | if class_name not in RESOURCES[key]: |
Matteo Scandolo | d12be21 | 2017-07-07 10:44:34 -0700 | [diff] [blame] | 23 | raise Exception('[XOS-TOSCA] The model you are trying to create (%s: %s, class: %s) is not know by xos-core' % (used_key, data[used_key], class_name)) |
Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 24 | |
Matteo Scandolo | 21dde41 | 2017-07-11 18:54:12 -0700 | [diff] [blame^] | 25 | cls = RESOURCES[key][class_name] |
Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 26 | models = cls.objects.filter(**{used_key: data[used_key]}) |
| 27 | |
| 28 | if len(models) == 1: |
| 29 | print "[XOS-Tosca] Model %s already exist, retrieving instance..." % data[used_key] |
| 30 | model = models[0] |
| 31 | elif len(models) == 0: |
Matteo Scandolo | d12be21 | 2017-07-07 10:44:34 -0700 | [diff] [blame] | 32 | |
| 33 | if 'must-exist' in data and data['must-exist']: |
| 34 | raise Exception("[XOS-TOSCA] Model %s:%s has property 'must-exist' but cannot be found" % (class_name, data[used_key])) |
| 35 | |
Matteo Scandolo | 485b713 | 2017-06-30 11:46:47 -0700 | [diff] [blame] | 36 | model = cls.objects.new() |
| 37 | print "[XOS-Tosca] Model %s is new, creating new instance..." % data[used_key] |
| 38 | else: |
| 39 | raise Exception("[XOS-Tosca] Model %s has multiple instances, I can't handle it" % data[used_key]) |
| 40 | return model |