blob: 927eb05f8b995f47f6d56442b6ff5c4faf258b7b [file] [log] [blame]
Matteo Scandolo485b7132017-06-30 11:46:47 -07001from resources import RESOURCES
2
3class 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 Scandolo21dde412017-07-11 18:54:12 -07009 def get_model_from_classname(class_name, data, username, password):
Matteo Scandolo485b7132017-06-30 11:46:47 -070010 """
11 Give a Model Class Name and some data, check if that exits or instantiate a new one
12 """
13
Matteo Scandolo485b7132017-06-30 11:46:47 -070014 if data.get('name'):
15 used_key = 'name'
16 else:
Matteo Scandolo78ca3eb2017-07-13 16:58:22 -070017 # FIXME apparently we're not matching model without a name field
Matteo Scandolo485b7132017-06-30 11:46:47 -070018 used_key = data.keys()[0]
19
Matteo Scandolo21dde412017-07-11 18:54:12 -070020 key = "%s~%s" % (username, password)
21 if not key in RESOURCES:
22 raise Exception("[XOS-TOSCA] User '%s' does not have ready resources" % username)
23 if class_name not in RESOURCES[key]:
Matteo Scandolod12be212017-07-07 10:44:34 -070024 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 Scandolo485b7132017-06-30 11:46:47 -070025
Matteo Scandolo21dde412017-07-11 18:54:12 -070026 cls = RESOURCES[key][class_name]
Matteo Scandolo485b7132017-06-30 11:46:47 -070027 models = cls.objects.filter(**{used_key: data[used_key]})
28
29 if len(models) == 1:
30 print "[XOS-Tosca] Model %s already exist, retrieving instance..." % data[used_key]
31 model = models[0]
32 elif len(models) == 0:
Matteo Scandolod12be212017-07-07 10:44:34 -070033
34 if 'must-exist' in data and data['must-exist']:
35 raise Exception("[XOS-TOSCA] Model %s:%s has property 'must-exist' but cannot be found" % (class_name, data[used_key]))
36
Matteo Scandolo485b7132017-06-30 11:46:47 -070037 model = cls.objects.new()
38 print "[XOS-Tosca] Model %s is new, creating new instance..." % data[used_key]
39 else:
40 raise Exception("[XOS-Tosca] Model %s has multiple instances, I can't handle it" % data[used_key])
41 return model