Add buildArtifacts and build_interfaces
[vfc/nfvo/lcm.git] / lcm / pub / utils / toscaparser / basemodel.py
1 import copy
2 import json
3 import os
4 import re
5 import shutil
6 import urllib
7
8 from toscaparser.functions import GetInput
9 from toscaparser.tosca_template import ToscaTemplate
10
11 from lcm.pub.utils.toscaparser.dataentityext import DataEntityExt
12
13
14 class BaseInfoModel(object):
15
16     def buildToscaTemplate(self, path, params):
17         file_name = None
18         try:
19             file_name = self._check_download_file(path)
20             valid_params = self._validate_input_params(file_name, params)
21             return self._create_tosca_template(file_name, valid_params)
22         finally:
23             if file_name != None and file_name != path and os.path.exists(file_name):
24                 try:
25                     os.remove(file_name)
26                 except Exception, e:
27                     pass
28
29     def _validate_input_params(self, path, params):
30         valid_params = {}
31         if params and len(params) > 0:
32             tmp = self._create_tosca_template(path, None)
33             for key,value in params.items():
34                 if hasattr(tmp, 'inputs') and len(tmp.inputs) > 0:
35                     for input_def in tmp.inputs:
36                         if (input_def.name == key):
37                             valid_params[key] = DataEntityExt.validate_datatype(input_def.type, value)
38
39         return valid_params
40
41     def _create_tosca_template(self, file_name, valid_params):
42         tosca_tpl = None
43         try:
44             tosca_tpl = ToscaTemplate(file_name, valid_params)
45             print "-----------------------------"
46             print '\n'.join(['%s:%s' % item for item in tosca_tpl.__dict__.items()])
47             print "-----------------------------"
48             return tosca_tpl
49         finally:
50             if tosca_tpl != None and hasattr(tosca_tpl, "temp_dir") and os.path.exists(tosca_tpl.temp_dir):
51                 try:
52                     shutil.rmtree(tosca_tpl.temp_dir)
53                 except Exception, e:
54                     pass
55
56     def _check_download_file(self, path):
57         if (path.startswith("ftp") or path.startswith("sftp")):
58             return self.downloadFileFromFtpServer(path)
59         elif (path.startswith("http")):
60             return self.download_file_from_httpserver(path)
61         return path
62
63     def download_file_from_httpserver(self, path):
64         path = path.encode("utf-8")
65         tmps = str.split(path, '/')
66         localFileName = tmps[len(tmps) - 1]
67         urllib.urlretrieve(path, localFileName)
68         return localFileName
69
70     def downloadFileFromFtpServer(self, path):
71         path = path.encode("utf-8")
72         tmp = str.split(path, '://')
73         protocol = tmp[0]
74         tmp = str.split(tmp[1], ':')
75         if len(tmp) == 2:
76             userName = tmp[0]
77             tmp = str.split(tmp[1], '@')
78             userPwd = tmp[0]
79             index = tmp[1].index('/')
80             hostIp = tmp[1][0:index]
81             remoteFileName = tmp[1][index:len(tmp[1])]
82             if protocol.lower() == 'ftp':
83                 hostPort = 21
84             else:
85                 hostPort = 22
86
87         if len(tmp) == 3:
88             userName = tmp[0]
89             userPwd = str.split(tmp[1], '@')[0]
90             hostIp = str.split(tmp[1], '@')[1]
91             index = tmp[2].index('/')
92             hostPort = tmp[2][0:index]
93             remoteFileName = tmp[2][index:len(tmp[2])]
94
95         localFileName = str.split(remoteFileName, '/')
96         localFileName = localFileName[len(localFileName) - 1]
97
98         if protocol.lower() == 'sftp':
99             self.sftp_get(userName, userPwd, hostIp, hostPort, remoteFileName, localFileName)
100         else:
101             self.ftp_get(userName, userPwd, hostIp, hostPort, remoteFileName, localFileName)
102         return localFileName
103
104     def buidMetadata(self, tosca):
105         if 'metadata' in tosca.tpl:
106             self.metadata = copy.deepcopy(tosca.tpl['metadata'])
107
108         def buildProperties(self, nodeTemplate, parsed_params):
109             properties = {}
110             isMappingParams = parsed_params and len(parsed_params) > 0
111             for k, item in nodeTemplate.get_properties().items():
112                 properties[k] = item.value
113                 if isinstance(item.value, GetInput):
114                     if item.value.result() and isMappingParams:
115                         properties[k] = DataEntityExt.validate_datatype(item.type, item.value.result())
116                     else:
117                         tmp = {}
118                         tmp[item.value.name] = item.value.input_name
119                         properties[k] = tmp
120             if 'attributes' in nodeTemplate.entity_tpl:
121                 for k, item in nodeTemplate.entity_tpl['attributes'].items():
122                     properties[k] = str(item)
123             return properties
124
125     def buildProperties(self, nodeTemplate, parsed_params):
126         properties = {}
127         isMappingParams = parsed_params and len(parsed_params) > 0
128         for k, item in nodeTemplate.get_properties().items():
129             properties[k] = item.value
130             if isinstance(item.value, GetInput):
131                 if item.value.result() and isMappingParams:
132                     properties[k] = DataEntityExt.validate_datatype(item.type, item.value.result())
133                 else:
134                     tmp = {}
135                     tmp[item.value.name] = item.value.input_name
136                     properties[k] = tmp
137         if 'attributes' in nodeTemplate.entity_tpl:
138             for k, item in nodeTemplate.entity_tpl['attributes'].items():
139                 properties[k] = str(item)
140         return properties
141
142
143     def verify_properties(self, props, inputs, parsed_params):
144         ret_props = {}
145         if (props and len(props) > 0):
146             for key, value in props.items():
147                 ret_props[key] = self._verify_value(value, inputs, parsed_params)
148                 #                 if isinstance(value, str):
149                 #                     ret_props[key] = self._verify_string(inputs, parsed_params, value);
150                 #                     continue
151                 #                 if isinstance(value, list):
152                 #                     ret_props[key] = map(lambda x: self._verify_dict(inputs, parsed_params, x), value)
153                 #                     continue
154                 #                 if isinstance(value, dict):
155                 #                     ret_props[key] = self._verify_map(inputs, parsed_params, value)
156                 #                     continue
157                 #                 ret_props[key] = value
158         return ret_props
159
160     def build_requirements(self, node_template):
161         rets = []
162         for req in node_template.requirements:
163             for req_name, req_value in req.items():
164                 if (isinstance(req_value, dict)):
165                     if ('node' in req_value and req_value['node'] not in node_template.templates):
166                         continue  # No target requirement for aria parser, not add to result.
167                 rets.append({req_name : req_value})
168         return rets
169
170     def buildCapabilities(self, nodeTemplate, inputs, ret):
171         capabilities = json.dumps(nodeTemplate.entity_tpl.get('capabilities', None))
172         match = re.findall(r'\{"get_input":\s*"([\w|\-]+)"\}',capabilities)
173         for m in match:
174             aa= [input_def for input_def in inputs
175                  if m == input_def.name][0]
176             capabilities = re.sub(r'\{"get_input":\s*"([\w|\-]+)"\}', json.dumps(aa.default), capabilities,1)
177         if capabilities != 'null':
178             ret['capabilities'] = json.loads(capabilities)
179
180     def buildArtifacts(self, nodeTemplate, inputs, ret):
181         artifacts = json.dumps(nodeTemplate.entity_tpl.get('artifacts', None))
182         match = re.findall(r'\{"get_input":\s*"([\w|\-]+)"\}',artifacts)
183         for m in match:
184             aa= [input_def for input_def in inputs
185                  if m == input_def.name][0]
186             artifacts = re.sub(r'\{"get_input":\s*"([\w|\-]+)"\}', json.dumps(aa.default), artifacts,1)
187         if artifacts != 'null':
188             ret['artifacts'] = json.loads(artifacts)
189
190     def build_interfaces(self, node_template):
191         if 'interfaces' in node_template.entity_tpl:
192             return node_template.entity_tpl['interfaces']
193         return None