bug 544 Adding license headers
[osm/LCM.git] / osm_lcm / vim_sdn.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2018 Telefonica S.A.
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License"); you may
7 # not use this file except in compliance with the License. You may obtain
8 # a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
14 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
15 # License for the specific language governing permissions and limitations
16 # under the License.
17 ##
18
19 import asyncio
20 import logging
21 import logging.handlers
22 import ROclient
23 from lcm_utils import LcmException, LcmBase
24 from osm_common.dbbase import DbException
25 from copy import deepcopy
26
27 __author__ = "Alfonso Tierno"
28
29
30 class VimLcm(LcmBase):
31 # values that are encrypted at vim config because they are passwords
32 vim_config_encrypted = ("admin_password", "nsx_password", "vcenter_password")
33
34 def __init__(self, db, msg, fs, lcm_tasks, ro_config, loop):
35 """
36 Init, Connect to database, filesystem storage, and messaging
37 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
38 :return: None
39 """
40
41 self.logger = logging.getLogger('lcm.vim')
42 self.loop = loop
43 self.lcm_tasks = lcm_tasks
44 self.ro_config = ro_config
45
46 super().__init__(db, msg, fs, self.logger)
47
48 async def create(self, vim_content, order_id):
49 vim_id = vim_content["_id"]
50 logging_text = "Task vim_create={} ".format(vim_id)
51 self.logger.debug(logging_text + "Enter")
52 db_vim = None
53 db_vim_update = {}
54 exc = None
55 RO_sdn_id = None
56 try:
57 step = "Getting vim-id='{}' from db".format(vim_id)
58 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
59 db_vim_update["_admin.deployed.RO"] = None
60 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
61 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
62 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
63 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
64 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
65 else:
66 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
67 vim_content["config"]["sdn-controller"]))
68
69 step = "Creating vim at RO"
70 db_vim_update["_admin.detailed-status"] = step
71 self.update_db_2("vim_accounts", vim_id, db_vim_update)
72 RO = ROclient.ROClient(self.loop, **self.ro_config)
73 vim_RO = deepcopy(vim_content)
74 vim_RO.pop("_id", None)
75 vim_RO.pop("_admin", None)
76 schema_version = vim_RO.pop("schema_version", None)
77 vim_RO.pop("schema_type", None)
78 vim_RO.pop("vim_tenant_name", None)
79 vim_RO["type"] = vim_RO.pop("vim_type")
80 vim_RO.pop("vim_user", None)
81 vim_RO.pop("vim_password", None)
82 if RO_sdn_id:
83 vim_RO["config"]["sdn-controller"] = RO_sdn_id
84 desc = await RO.create("vim", descriptor=vim_RO)
85 RO_vim_id = desc["uuid"]
86 db_vim_update["_admin.deployed.RO"] = RO_vim_id
87
88 step = "Creating vim_account at RO"
89 db_vim_update["_admin.detailed-status"] = step
90 self.update_db_2("vim_accounts", vim_id, db_vim_update)
91
92 if vim_content.get("vim_password"):
93 vim_content["vim_password"] = self.db.decrypt(vim_content["vim_password"],
94 schema_version=schema_version,
95 salt=vim_id)
96 vim_account_RO = {"vim_tenant_name": vim_content["vim_tenant_name"],
97 "vim_username": vim_content["vim_user"],
98 "vim_password": vim_content["vim_password"]
99 }
100 if vim_RO.get("config"):
101 vim_account_RO["config"] = vim_RO["config"]
102 if "sdn-controller" in vim_account_RO["config"]:
103 del vim_account_RO["config"]["sdn-controller"]
104 if "sdn-port-mapping" in vim_account_RO["config"]:
105 del vim_account_RO["config"]["sdn-port-mapping"]
106 for p in self.vim_config_encrypted:
107 if vim_account_RO["config"].get(p):
108 vim_account_RO["config"][p] = self.db.decrypt(vim_account_RO["config"][p],
109 schema_version=schema_version,
110 salt=vim_id)
111
112 desc = await RO.attach_datacenter(RO_vim_id, descriptor=vim_account_RO)
113 db_vim_update["_admin.deployed.RO-account"] = desc["uuid"]
114 db_vim_update["_admin.operationalState"] = "ENABLED"
115 db_vim_update["_admin.detailed-status"] = "Done"
116
117 # await asyncio.sleep(15) # TODO remove. This is for test
118 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
119 return
120
121 except (ROclient.ROClientException, DbException) as e:
122 self.logger.error(logging_text + "Exit Exception {}".format(e))
123 exc = e
124 except Exception as e:
125 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
126 exc = e
127 finally:
128 if exc and db_vim:
129 db_vim_update["_admin.operationalState"] = "ERROR"
130 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
131 if db_vim_update:
132 self.update_db_2("vim_accounts", vim_id, db_vim_update)
133 self.lcm_tasks.remove("vim_account", vim_id, order_id)
134
135 async def edit(self, vim_content, order_id):
136 vim_id = vim_content["_id"]
137 logging_text = "Task vim_edit={} ".format(vim_id)
138 self.logger.debug(logging_text + "Enter")
139 db_vim = None
140 exc = None
141 RO_sdn_id = None
142 RO_vim_id = None
143 db_vim_update = {}
144 step = "Getting vim-id='{}' from db".format(vim_id)
145 try:
146 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
147
148 # look if previous tasks in process
149 task_name, task_dependency = self.lcm_tasks.lookfor_related("vim_account", vim_id, order_id)
150 if task_dependency:
151 step = "Waiting for related tasks to be completed: {}".format(task_name)
152 self.logger.debug(logging_text + step)
153 # TODO write this to database
154 _, pending = await asyncio.wait(task_dependency, timeout=3600)
155 if pending:
156 raise LcmException("Timeout waiting related tasks to be completed")
157
158 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
159 if vim_content.get("config") and vim_content["config"].get("sdn-controller"):
160 step = "Getting sdn-controller-id='{}' from db".format(vim_content["config"]["sdn-controller"])
161 db_sdn = self.db.get_one("sdns", {"_id": vim_content["config"]["sdn-controller"]})
162
163 # look if previous tasks in process
164 task_name, task_dependency = self.lcm_tasks.lookfor_related("sdn", db_sdn["_id"])
165 if task_dependency:
166 step = "Waiting for related tasks to be completed: {}".format(task_name)
167 self.logger.debug(logging_text + step)
168 # TODO write this to database
169 _, pending = await asyncio.wait(task_dependency, timeout=3600)
170 if pending:
171 raise LcmException("Timeout waiting related tasks to be completed")
172
173 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get(
174 "RO"):
175 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
176 else:
177 raise LcmException("sdn-controller={} is not available. Not deployed at RO".format(
178 vim_content["config"]["sdn-controller"]))
179
180 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
181 step = "Editing vim at RO"
182 RO = ROclient.ROClient(self.loop, **self.ro_config)
183 vim_RO = deepcopy(vim_content)
184 vim_RO.pop("_id", None)
185 vim_RO.pop("_admin", None)
186 schema_version = vim_RO.pop("schema_version", None)
187 vim_RO.pop("schema_type", None)
188 vim_RO.pop("vim_tenant_name", None)
189 if "vim_type" in vim_RO:
190 vim_RO["type"] = vim_RO.pop("vim_type")
191 vim_RO.pop("vim_user", None)
192 vim_RO.pop("vim_password", None)
193 if RO_sdn_id:
194 vim_RO["config"]["sdn-controller"] = RO_sdn_id
195 # TODO make a deep update of sdn-port-mapping
196 if vim_RO:
197 await RO.edit("vim", RO_vim_id, descriptor=vim_RO)
198
199 step = "Editing vim-account at RO tenant"
200 vim_account_RO = {}
201 if "config" in vim_content:
202 if "sdn-controller" in vim_content["config"]:
203 del vim_content["config"]["sdn-controller"]
204 if "sdn-port-mapping" in vim_content["config"]:
205 del vim_content["config"]["sdn-port-mapping"]
206 if not vim_content["config"]:
207 del vim_content["config"]
208 if "vim_tenant_name" in vim_content:
209 vim_account_RO["vim_tenant_name"] = vim_content["vim_tenant_name"]
210 if "vim_password" in vim_content:
211 vim_account_RO["vim_password"] = vim_content["vim_password"]
212 if vim_content.get("vim_password"):
213 vim_account_RO["vim_password"] = self.db.decrypt(vim_content["vim_password"],
214 schema_version=schema_version,
215 salt=vim_id)
216 if "config" in vim_content:
217 vim_account_RO["config"] = vim_content["config"]
218 if vim_content.get("config"):
219 for p in self.vim_config_encrypted:
220 if vim_content["config"].get(p):
221 vim_account_RO["config"][p] = self.db.decrypt(vim_content["config"][p],
222 schema_version=schema_version,
223 salt=vim_id)
224
225 if "vim_user" in vim_content:
226 vim_content["vim_username"] = vim_content["vim_user"]
227 # vim_account must be edited always even if empty in order to ensure changes are translated to RO
228 # vim_thread. RO will remove and relaunch a new thread for this vim_account
229 await RO.edit("vim_account", RO_vim_id, descriptor=vim_account_RO)
230 db_vim_update["_admin.operationalState"] = "ENABLED"
231
232 self.logger.debug(logging_text + "Exit Ok RO_vim_id={}".format(RO_vim_id))
233 return
234
235 except (ROclient.ROClientException, DbException) as e:
236 self.logger.error(logging_text + "Exit Exception {}".format(e))
237 exc = e
238 except Exception as e:
239 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
240 exc = e
241 finally:
242 if exc and db_vim:
243 db_vim_update["_admin.operationalState"] = "ERROR"
244 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
245 if db_vim_update:
246 self.update_db_2("vim_accounts", vim_id, db_vim_update)
247 self.lcm_tasks.remove("vim_account", vim_id, order_id)
248
249 async def delete(self, vim_id, order_id):
250 logging_text = "Task vim_delete={} ".format(vim_id)
251 self.logger.debug(logging_text + "Enter")
252 db_vim = None
253 db_vim_update = {}
254 exc = None
255 step = "Getting vim from db"
256 try:
257 db_vim = self.db.get_one("vim_accounts", {"_id": vim_id})
258 if db_vim.get("_admin") and db_vim["_admin"].get("deployed") and db_vim["_admin"]["deployed"].get("RO"):
259 RO_vim_id = db_vim["_admin"]["deployed"]["RO"]
260 RO = ROclient.ROClient(self.loop, **self.ro_config)
261 step = "Detaching vim from RO tenant"
262 try:
263 await RO.detach_datacenter(RO_vim_id)
264 except ROclient.ROClientException as e:
265 if e.http_code == 404: # not found
266 self.logger.debug(logging_text + "RO_vim_id={} already detached".format(RO_vim_id))
267 else:
268 raise
269
270 step = "Deleting vim from RO"
271 try:
272 await RO.delete("vim", RO_vim_id)
273 except ROclient.ROClientException as e:
274 if e.http_code == 404: # not found
275 self.logger.debug(logging_text + "RO_vim_id={} already deleted".format(RO_vim_id))
276 else:
277 raise
278 else:
279 # nothing to delete
280 self.logger.error(logging_text + "Nohing to remove at RO")
281 self.db.del_one("vim_accounts", {"_id": vim_id})
282 self.logger.debug(logging_text + "Exit Ok")
283 return
284
285 except (ROclient.ROClientException, DbException) as e:
286 self.logger.error(logging_text + "Exit Exception {}".format(e))
287 exc = e
288 except Exception as e:
289 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
290 exc = e
291 finally:
292 self.lcm_tasks.remove("vim_account", vim_id, order_id)
293 if exc and db_vim:
294 db_vim_update["_admin.operationalState"] = "ERROR"
295 db_vim_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
296 if db_vim_update:
297 self.update_db_2("vim_accounts", vim_id, db_vim_update)
298 self.lcm_tasks.remove("vim_account", vim_id, order_id)
299
300
301 class SdnLcm(LcmBase):
302
303 def __init__(self, db, msg, fs, lcm_tasks, ro_config, loop):
304 """
305 Init, Connect to database, filesystem storage, and messaging
306 :param config: two level dictionary with configuration. Top level should contain 'database', 'storage',
307 :return: None
308 """
309
310 self.logger = logging.getLogger('lcm.sdn')
311 self.loop = loop
312 self.lcm_tasks = lcm_tasks
313 self.ro_config = ro_config
314
315 super().__init__(db, msg, fs, self.logger)
316
317 async def create(self, sdn_content, order_id):
318 sdn_id = sdn_content["_id"]
319 logging_text = "Task sdn_create={} ".format(sdn_id)
320 self.logger.debug(logging_text + "Enter")
321 db_sdn = None
322 db_sdn_update = {}
323 RO_sdn_id = None
324 exc = None
325 try:
326 step = "Getting sdn from db"
327 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
328 db_sdn_update["_admin.deployed.RO"] = None
329
330 step = "Creating sdn at RO"
331 RO = ROclient.ROClient(self.loop, **self.ro_config)
332 sdn_RO = deepcopy(sdn_content)
333 sdn_RO.pop("_id", None)
334 sdn_RO.pop("_admin", None)
335 schema_version = sdn_RO.pop("schema_version", None)
336 sdn_RO.pop("schema_type", None)
337 sdn_RO.pop("description", None)
338 if sdn_RO.get("password"):
339 sdn_RO["password"] = self.db.decrypt(sdn_RO["password"], schema_version=schema_version, salt=sdn_id)
340
341 desc = await RO.create("sdn", descriptor=sdn_RO)
342 RO_sdn_id = desc["uuid"]
343 db_sdn_update["_admin.deployed.RO"] = RO_sdn_id
344 db_sdn_update["_admin.operationalState"] = "ENABLED"
345 self.logger.debug(logging_text + "Exit Ok RO_sdn_id={}".format(RO_sdn_id))
346 return
347
348 except (ROclient.ROClientException, DbException) as e:
349 self.logger.error(logging_text + "Exit Exception {}".format(e))
350 exc = e
351 except Exception as e:
352 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
353 exc = e
354 finally:
355 if exc and db_sdn:
356 db_sdn_update["_admin.operationalState"] = "ERROR"
357 db_sdn_update["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
358 if db_sdn_update:
359 self.update_db_2("sdns", sdn_id, db_sdn_update)
360 self.lcm_tasks.remove("sdn", sdn_id, order_id)
361
362 async def edit(self, sdn_content, order_id):
363 sdn_id = sdn_content["_id"]
364 logging_text = "Task sdn_edit={} ".format(sdn_id)
365 self.logger.debug(logging_text + "Enter")
366 db_sdn = None
367 db_sdn_update = {}
368 exc = None
369 step = "Getting sdn from db"
370 try:
371 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
372 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
373 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
374 RO = ROclient.ROClient(self.loop, **self.ro_config)
375 step = "Editing sdn at RO"
376 sdn_RO = deepcopy(sdn_content)
377 sdn_RO.pop("_id", None)
378 sdn_RO.pop("_admin", None)
379 schema_version = sdn_RO.pop("schema_version", None)
380 sdn_RO.pop("schema_type", None)
381 sdn_RO.pop("description", None)
382 if sdn_RO.get("password"):
383 sdn_RO["password"] = self.db.decrypt(sdn_RO["password"], schema_version=schema_version, salt=sdn_id)
384 if sdn_RO:
385 await RO.edit("sdn", RO_sdn_id, descriptor=sdn_RO)
386 db_sdn_update["_admin.operationalState"] = "ENABLED"
387
388 self.logger.debug(logging_text + "Exit Ok RO_sdn_id".format(RO_sdn_id))
389 return
390
391 except (ROclient.ROClientException, DbException) as e:
392 self.logger.error(logging_text + "Exit Exception {}".format(e))
393 exc = e
394 except Exception as e:
395 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
396 exc = e
397 finally:
398 if exc and db_sdn:
399 db_sdn["_admin.operationalState"] = "ERROR"
400 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
401 if db_sdn_update:
402 self.update_db_2("sdns", sdn_id, db_sdn_update)
403 self.lcm_tasks.remove("sdn", sdn_id, order_id)
404
405 async def delete(self, sdn_id, order_id):
406 logging_text = "Task sdn_delete={} ".format(sdn_id)
407 self.logger.debug(logging_text + "Enter")
408 db_sdn = None
409 db_sdn_update = {}
410 exc = None
411 step = "Getting sdn from db"
412 try:
413 db_sdn = self.db.get_one("sdns", {"_id": sdn_id})
414 if db_sdn.get("_admin") and db_sdn["_admin"].get("deployed") and db_sdn["_admin"]["deployed"].get("RO"):
415 RO_sdn_id = db_sdn["_admin"]["deployed"]["RO"]
416 RO = ROclient.ROClient(self.loop, **self.ro_config)
417 step = "Deleting sdn from RO"
418 try:
419 await RO.delete("sdn", RO_sdn_id)
420 except ROclient.ROClientException as e:
421 if e.http_code == 404: # not found
422 self.logger.debug(logging_text + "RO_sdn_id={} already deleted".format(RO_sdn_id))
423 else:
424 raise
425 else:
426 # nothing to delete
427 self.logger.error(logging_text + "Skipping. There is not RO information at database")
428 self.db.del_one("sdns", {"_id": sdn_id})
429 self.logger.debug("sdn_delete task sdn_id={} Exit Ok".format(sdn_id))
430 return
431
432 except (ROclient.ROClientException, DbException) as e:
433 self.logger.error(logging_text + "Exit Exception {}".format(e))
434 exc = e
435 except Exception as e:
436 self.logger.critical(logging_text + "Exit Exception {}".format(e), exc_info=True)
437 exc = e
438 finally:
439 if exc and db_sdn:
440 db_sdn["_admin.operationalState"] = "ERROR"
441 db_sdn["_admin.detailed-status"] = "ERROR {}: {}".format(step, exc)
442 if db_sdn_update:
443 self.update_db_2("sdns", sdn_id, db_sdn_update)
444 self.lcm_tasks.remove("sdn", sdn_id, order_id)