blob: 477601090c722d941fb08a0217ea23f008342ff7 [file] [log] [blame]
lombardoffb37bca2018-05-03 16:20:04 +02001#
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
17from __future__ import unicode_literals
18
19import copy
20import json
21import os.path
22import yaml
23from lib.util import Util
24import logging
25from projecthandler.models import ProjectStateless
26
27from lib.osm.osm_parser import OsmParser
28from lib.osm.osm_rdcl_graph import OsmRdclGraph
29from lib.osm.osmclient.client import Client
30
31logging.basicConfig(level=logging.DEBUG)
32log = logging.getLogger('OsmModel.py')
33
34
35PATH_TO_SCHEMAS = 'lib/osm/schemas/'
36PATH_TO_DESCRIPTORS_TEMPLATES = 'lib/osm/descriptor_template'
37DESCRIPTOR_TEMPLATE_SUFFIX = '.json'
38GRAPH_MODEL_FULL_NAME = 'lib/TopologyModels/osm/osm.yaml'
39EXAMPLES_FOLDER = 'usecases/OSM/'
40
41
42class 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 result = {
146 'owner': self.owner.__str__(),
147 'name': self.name,
148 'updated_date': self.updated_date.strftime('%Y-%m-%d %H:%M'),
149 'info': self.info,
150 'type': 'osm',
151 'nsd': len(nsd) if nsd else 0,
152 'vnfd': len(vnfd) if vnfd else 0,
153 'ns': len(ns) if ns else 0,
154 'validated': self.validated
155 }
156
157 return result
158
159 def get_graph_data_json_topology(self, descriptor_id):
160 rdcl_graph = OsmRdclGraph()
161 project = self.get_dataproject()
162 topology = rdcl_graph.build_graph_from_project(project,
163 model=self.get_graph_model(GRAPH_MODEL_FULL_NAME))
164 return json.dumps(topology)
165
166 def create_descriptor(self, descriptor_name, type_descriptor, new_data, data_type, file_uploaded):
167 """Creates a descriptor of a given type from a json or yaml representation
168
169 Returns the descriptor id or False
170 """
171 log.debug('Create descriptor')
172
173 try:
174 client = Client()
175 if type_descriptor == 'nsd':
176 result = client.nsd_onboard(file_uploaded)
177 elif type_descriptor == 'vnfd':
178 result = client.vnfd_onboard(file_uploaded)
179
180 else:
181 log.debug('Create descriptor: Unknown data type')
182 return False
183
184 except Exception as e:
185 log.exception(e)
186 result = False
187 return result
188
189 def delete_descriptor(self, type_descriptor, descriptor_id):
190 log.debug('Delete descriptor')
191 try:
192 client = Client()
193 if type_descriptor == 'nsd':
194 result = client.nsd_delete(descriptor_id)
195 elif type_descriptor == 'vnfd':
196 result = client.vnfd_delete(descriptor_id)
197
198 else:
199 log.debug('Create descriptor: Unknown data type')
200 return False
201
202 except Exception as e:
203 log.exception(e)
204 result = False
205 return result
206
207 def edit_descriptor(self, type_descriptor, descriptor_id, new_data, data_type):
208 log.debug("Edit descriptor")
209 try:
210 client = Client()
211 if type_descriptor == 'nsd':
212 if data_type == 'yaml':
213 new_data = yaml.load(new_data)
214 elif data_type == 'json':
215 new_data = json.loads(new_data)
216 result = client.nsd_update(descriptor_id, new_data)
217 elif type_descriptor == 'vnfd':
218 if data_type == 'yaml':
219 new_data = yaml.load(new_data)
220 elif data_type == 'json':
221 new_data = json.loads(new_data)
222 result = client.vnfd_update(descriptor_id, new_data)
223
224 else:
225 log.debug('Create descriptor: Unknown data type')
226 return False
227 except Exception as e:
228 log.exception(e)
229 result = False
230 return result
231
232 def get_package_files_list(self, type_descriptor, descriptor_id):
233 try:
234 client = Client()
235 if type_descriptor == 'nsd':
236 result = client.nsd_artifacts(descriptor_id)
237 elif type_descriptor == 'vnfd':
238 result = client.vnf_packages_artifacts(descriptor_id)
239 else:
240 return False
241 result = yaml.load(result)
242 print result
243 except Exception as e:
244 log.exception(e)
245 result = False
246 print result
247 return result
248
249 def set_validated(self, value):
250 self.validated = True if value is not None and value == True else False
251
252 def get_add_element(self, request):
253 result = False
254
255 return result
256
257 def get_remove_element(self, request):
258 result = False
259
260 return result
261
262 def get_add_link(self, request):
263
264 result = False
265
266 return result
267
268 def get_remove_link(self, request):
269 result = False
270
271 return result
272
273 def create_ns(self, descriptor_type, descriptor_id, data_ns):
274 try:
275 client = Client()
276 if descriptor_type == 'nsd':
277 result = client.ns_create( data_ns)
278 else:
279 return False
280
281 except Exception as e:
282 log.exception(e)
283 result = False
284 print result
285 return result
286
287 def download_pkg(self, project, descriptor_id, descriptor_type):
288 try:
289 client = Client()
290 if descriptor_type == 'nsd':
291 result = client.get_nsd_pkg(descriptor_id)
292 elif descriptor_type == 'vnfd':
293 result = client.get_vnfd_pkg(descriptor_id)
294 else:
295 return False
296
297 except Exception as e:
298 log.exception(e)
299 result = False
300 print result
301 return result
302
303 def get_available_nodes(self, args):
304 """Returns all available node """
305 log.debug('get_available_nodes')
306 try:
307 result = []
308 #current_data = json.loads(self.data_project)
309 model_graph = self.get_graph_model(GRAPH_MODEL_FULL_NAME)
310 for node in model_graph['layer'][args['layer']]['nodes']:
311
312 current_data = {
313 "id": node,
314 "category_name": model_graph['nodes'][node]['label'],
315 "types": [
316 {
317 "name": "generic",
318 "id": node
319 }
320 ]
321 }
322 result.append(current_data)
323
324 #result = current_data[type_descriptor][descriptor_id]
325 except Exception as e:
326 log.debug(e)
327 result = []
328 return result