VNF info in project overview
[osm/LW-UI.git] / projecthandler / osm_model.py
1 #
2 # Copyright 2017 CNIT - Consorzio Nazionale Interuniversitario per le Telecomunicazioni
3 #
4 # Licensed under the Apache License, Version 2.0 (the "License");
5 # you may not use this file except in compliance with the License.
6 # You may obtain a copy of the License at
7 #
8 # http://www.apache.org/licenses/LICENSE-2.0
9 #
10 # Unless required by applicable law or agreed to in writing, software
11 # distributed under the License is distributed on an BASIS,
12 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 # See the License for the specific language governing permissions and
14 # limitations under the License.
15 #
16
17 from __future__ import unicode_literals
18
19 import copy
20 import json
21 import os.path
22 import yaml
23 from lib.util import Util
24 import logging
25 from projecthandler.models import ProjectStateless
26
27 from lib.osm.osm_parser import OsmParser
28 from lib.osm.osm_rdcl_graph import OsmRdclGraph
29 from lib.osm.osmclient.client import Client
30
31 logging.basicConfig(level=logging.DEBUG)
32 log = logging.getLogger('OsmModel.py')
33
34
35 PATH_TO_SCHEMAS = 'lib/osm/schemas/'
36 PATH_TO_DESCRIPTORS_TEMPLATES = 'lib/osm/descriptor_template'
37 DESCRIPTOR_TEMPLATE_SUFFIX = '.json'
38 GRAPH_MODEL_FULL_NAME = 'lib/TopologyModels/osm/osm.yaml'
39 EXAMPLES_FOLDER = 'usecases/OSM/'
40
41
42 class OsmProject(ProjectStateless):
43 """Osm Project class
44 The data model has the following descriptors:
45 # descrtiptor list in comment #
46
47 """
48
49 def get_descriptors(self, type_descriptor):
50 """Returns all descriptors of a given type"""
51 log.debug("Get %s descriptors", type_descriptor)
52 try:
53 client = Client()
54 if type_descriptor == 'nsd':
55 result = client.nsd_list()
56
57 elif type_descriptor == 'vnfd':
58 result = client.vnfd_list()
59
60 except Exception as e:
61 log.exception(e)
62 result = {}
63 return result
64
65 def get_descriptor(self, descriptor_id, type_descriptor):
66 """Returns a specific descriptor"""
67 try:
68 client = Client()
69 if type_descriptor == 'nsd':
70 result = client.nsd_get(descriptor_id)
71 print result
72 elif type_descriptor == 'vnfd':
73 result = client.vnfd_get(descriptor_id)
74
75 print result
76 except Exception as e:
77 log.exception(e)
78 result = {}
79
80 return result
81
82 @classmethod
83 def data_project_from_files(cls, request):
84
85 file_dict = {}
86 for my_key in request.FILES.keys():
87 file_dict[my_key] = request.FILES.getlist(my_key)
88
89 log.debug(file_dict)
90
91 data_project = OsmParser.importprojectfiles(file_dict)
92
93 return data_project
94
95 @classmethod
96 def data_project_from_example(cls, request):
97 osm_id = request.POST.get('example-osm-id', '')
98 data_project = OsmParser.importprojectdir(EXAMPLES_FOLDER + osm_id + '/JSON', 'yaml')
99 return data_project
100
101 @classmethod
102 def get_example_list(cls):
103 """Returns a list of directories, in each directory there is a project osm"""
104
105 path = EXAMPLES_FOLDER
106 dirs = [d for d in os.listdir(path) if os.path.isdir(os.path.join(path, d))]
107 return {'osm': dirs}
108
109 @classmethod
110 def get_new_descriptor(cls, descriptor_type, request_id):
111
112 json_template = cls.get_descriptor_template(descriptor_type)
113
114 return json_template
115
116 @classmethod
117 def get_descriptor_template(cls, type_descriptor):
118 """Returns a descriptor template for a given descriptor type"""
119
120 try:
121 schema = Util.loadjsonfile(os.path.join(PATH_TO_DESCRIPTORS_TEMPLATES, type_descriptor + DESCRIPTOR_TEMPLATE_SUFFIX))
122 return schema
123 except Exception as e:
124 log.exception(e)
125 return False
126
127 @classmethod
128 def get_clone_descriptor(cls, descriptor, type_descriptor, new_descriptor_id):
129 new_descriptor = copy.deepcopy(descriptor)
130
131 return new_descriptor
132
133 def get_type(self):
134 return "osm"
135
136 def __str__(self):
137 return self.name
138
139 def get_overview_data(self):
140 current_data = json.loads(self.data_project)
141 client = Client()
142 nsd = client.nsd_list()
143 vnfd = client.vnfd_list()
144 ns = client.ns_list()
145 vnf = client.vnf_list()
146 result = {
147 'owner': self.owner.__str__(),
148 'name': self.name,
149 'updated_date': self.updated_date.strftime('%Y-%m-%d %H:%M'),
150 'info': self.info,
151 'type': 'osm',
152 'nsd': len(nsd) if nsd else 0,
153 'vnfd': len(vnfd) if vnfd else 0,
154 'ns': len(ns) if ns else 0,
155 'vnf': len(vnf) if vnf else 0,
156 #'validated': self.validated
157 }
158
159 return result
160
161 def get_graph_data_json_topology(self, descriptor_id):
162 rdcl_graph = OsmRdclGraph()
163 project = self.get_dataproject()
164 topology = rdcl_graph.build_graph_from_project(project,
165 model=self.get_graph_model(GRAPH_MODEL_FULL_NAME))
166 return json.dumps(topology)
167
168 def create_descriptor(self, descriptor_name, type_descriptor, new_data, data_type, file_uploaded):
169 """Creates a descriptor of a given type from a json or yaml representation
170
171 Returns the descriptor id or False
172 """
173 log.debug('Create descriptor')
174
175 try:
176 client = Client()
177 if type_descriptor == 'nsd':
178 result = client.nsd_onboard(file_uploaded)
179 elif type_descriptor == 'vnfd':
180 result = client.vnfd_onboard(file_uploaded)
181
182 else:
183 log.debug('Create descriptor: Unknown data type')
184 return False
185
186 except Exception as e:
187 log.exception(e)
188 result = False
189 return result
190
191 def delete_descriptor(self, type_descriptor, descriptor_id):
192 log.debug('Delete descriptor')
193 try:
194 client = Client()
195 if type_descriptor == 'nsd':
196 result = client.nsd_delete(descriptor_id)
197 elif type_descriptor == 'vnfd':
198 result = client.vnfd_delete(descriptor_id)
199
200 else:
201 log.debug('Create descriptor: Unknown data type')
202 return False
203
204 except Exception as e:
205 log.exception(e)
206 result = False
207 return result
208
209 def edit_descriptor(self, type_descriptor, descriptor_id, new_data, data_type):
210 log.debug("Edit descriptor")
211 try:
212 client = Client()
213 if type_descriptor == 'nsd':
214 if data_type == 'yaml':
215 new_data = yaml.load(new_data)
216 elif data_type == 'json':
217 new_data = json.loads(new_data)
218 result = client.nsd_update(descriptor_id, new_data)
219 elif type_descriptor == 'vnfd':
220 if data_type == 'yaml':
221 new_data = yaml.load(new_data)
222 elif data_type == 'json':
223 new_data = json.loads(new_data)
224 result = client.vnfd_update(descriptor_id, new_data)
225
226 else:
227 log.debug('Create descriptor: Unknown data type')
228 return False
229 except Exception as e:
230 log.exception(e)
231 result = False
232 return result
233
234 def get_package_files_list(self, type_descriptor, descriptor_id):
235 try:
236 client = Client()
237 if type_descriptor == 'nsd':
238 result = client.nsd_artifacts(descriptor_id)
239 elif type_descriptor == 'vnfd':
240 result = client.vnf_packages_artifacts(descriptor_id)
241 else:
242 return False
243 result = yaml.load(result)
244 print result
245 except Exception as e:
246 log.exception(e)
247 result = False
248 print result
249 return result
250
251 def set_validated(self, value):
252 self.validated = True if value is not None and value == True else False
253
254 def get_add_element(self, request):
255 result = False
256
257 return result
258
259 def get_remove_element(self, request):
260 result = False
261
262 return result
263
264 def get_add_link(self, request):
265
266 result = False
267
268 return result
269
270 def get_remove_link(self, request):
271 result = False
272
273 return result
274
275 def create_ns(self, descriptor_type, descriptor_id, data_ns):
276 try:
277 client = Client()
278 if descriptor_type == 'nsd':
279 result = client.ns_create( data_ns)
280 else:
281 return False
282
283 except Exception as e:
284 log.exception(e)
285 result = False
286 print result
287 return result
288
289 def download_pkg(self, project, descriptor_id, descriptor_type):
290 try:
291 client = Client()
292 if descriptor_type == 'nsd':
293 result = client.get_nsd_pkg(descriptor_id)
294 elif descriptor_type == 'vnfd':
295 result = client.get_vnfd_pkg(descriptor_id)
296 else:
297 return False
298
299 except Exception as e:
300 log.exception(e)
301 result = False
302 print result
303 return result
304
305 def get_available_nodes(self, args):
306 """Returns all available node """
307 log.debug('get_available_nodes')
308 try:
309 result = []
310 #current_data = json.loads(self.data_project)
311 model_graph = self.get_graph_model(GRAPH_MODEL_FULL_NAME)
312 for node in model_graph['layer'][args['layer']]['nodes']:
313
314 current_data = {
315 "id": node,
316 "category_name": model_graph['nodes'][node]['label'],
317 "types": [
318 {
319 "name": "generic",
320 "id": node
321 }
322 ]
323 }
324 result.append(current_data)
325
326 #result = current_data[type_descriptor][descriptor_id]
327 except Exception as e:
328 log.debug(e)
329 result = []
330 return result