1 # -*- coding: utf-8 -*-
4 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5 # This file is part of openmano
8 # Licensed under the Apache License, Version 2.0 (the "License"); you may
9 # not use this file except in compliance with the License. You may obtain
10 # a copy of the License at
12 # http://www.apache.org/licenses/LICENSE-2.0
14 # Unless required by applicable law or agreed to in writing, software
15 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
16 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
17 # License for the specific language governing permissions and limitations
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
25 NFVO DB engine. It implements all the methods to interact with the Openmano Database
27 __author__
="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28 __date__
="$28-aug-2014 10:05:01$"
37 tables_with_createdat_field
=["datacenters","instance_nets","instance_scenarios","instance_vms","instance_vnfs",
38 "interfaces","nets","nfvo_tenants","scenarios","sce_interfaces","sce_nets",
39 "sce_vnfs","tenants_datacenters","datacenter_tenants","vms","vnfs"]
41 class nfvo_db(db_base
.db_base
):
42 def __init__(self
, host
=None, user
=None, passwd
=None, database
=None, log_name
='openmano.db', log_level
="ERROR"):
43 db_base
.db_base
.__init
__(self
, host
, user
, passwd
, database
, log_name
, log_level
)
44 db_base
.db_base
.tables_with_created_field
=tables_with_createdat_field
48 def new_vnf_as_a_whole(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
49 self
.logger
.debug("Adding new vnf to the NFVO database")
52 created_time
= time
.time()
57 myVNFDict
["name"] = vnf_name
58 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
59 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
60 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
61 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
62 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
64 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
65 #print "Adding new vms to the NFVO database"
66 #For each vm, we must create the appropriate vm in the NFVO database.
68 for _
,vm
in VNFCDict
.iteritems():
69 #This code could make the name of the vms grow and grow.
70 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
71 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
72 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
74 created_time
+= 0.00001
75 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
76 #print "Internal vm id in NFVO DB: %s" % vm_id
77 vmDict
[vm
['name']] = vm_id
79 #Collect the data interfaces of each VM/VNFC under the 'numas' field
81 for vm
in vnf_descriptor
['vnf']['VNFC']:
82 dataifacesDict
[vm
['name']] = {}
83 for numa
in vm
.get('numas', []):
84 for dataiface
in numa
.get('interfaces',[]):
85 db_base
._convert
_bandwidth
(dataiface
)
86 dataifacesDict
[vm
['name']][dataiface
['name']] = {}
87 dataifacesDict
[vm
['name']][dataiface
['name']]['vpci'] = dataiface
['vpci']
88 dataifacesDict
[vm
['name']][dataiface
['name']]['bw'] = dataiface
['bandwidth']
89 dataifacesDict
[vm
['name']][dataiface
['name']]['model'] = "PF" if dataiface
['dedicated']=="yes" else ("VF" if dataiface
['dedicated']=="no" else "VFnotShared")
91 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
92 bridgeInterfacesDict
= {}
93 for vm
in vnf_descriptor
['vnf']['VNFC']:
94 if 'bridge-ifaces' in vm
:
95 bridgeInterfacesDict
[vm
['name']] = {}
96 for bridgeiface
in vm
['bridge-ifaces']:
97 db_base
._convert
_bandwidth
(bridgeiface
)
98 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = {}
99 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['vpci'] = bridgeiface
.get('vpci',None)
100 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['mac'] = bridgeiface
.get('mac_address',None)
101 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['bw'] = bridgeiface
.get('bandwidth', None)
102 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['model'] = bridgeiface
.get('model', None)
104 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
105 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
106 internalconnList
= []
107 if 'internal-connections' in vnf_descriptor
['vnf']:
108 for net
in vnf_descriptor
['vnf']['internal-connections']:
109 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
112 myNetDict
["name"] = net
['name']
113 myNetDict
["description"] = net
['description']
114 myNetDict
["type"] = net
['type']
115 myNetDict
["vnf_id"] = vnf_id
117 created_time
+= 0.00001
118 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
120 for element
in net
['elements']:
122 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
123 ifaceItem
["internal_name"] = element
['local_iface_name']
124 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
125 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
126 ifaceItem
["net_id"] = net_id
127 ifaceItem
["type"] = net
['type']
128 if ifaceItem
["type"] == "data":
129 ifaceItem
["vpci"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
130 ifaceItem
["bw"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
131 ifaceItem
["model"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
133 ifaceItem
["vpci"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
134 ifaceItem
["mac"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['mac_address']
135 ifaceItem
["bw"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
136 ifaceItem
["model"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
137 internalconnList
.append(ifaceItem
)
138 #print "Internal net id in NFVO DB: %s" % net_id
140 #print "Adding internal interfaces to the NFVO database (if any)"
141 for iface
in internalconnList
:
142 print "Iface name: %s" % iface
['internal_name']
143 created_time
+= 0.00001
144 iface_id
= self
._new
_row
_internal
('interfaces', iface
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
145 #print "Iface id in NFVO DB: %s" % iface_id
147 #print "Adding external interfaces to the NFVO database"
148 for iface
in vnf_descriptor
['vnf']['external-connections']:
150 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
151 myIfaceDict
["internal_name"] = iface
['local_iface_name']
152 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
153 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
154 myIfaceDict
["external_name"] = iface
['name']
155 myIfaceDict
["type"] = iface
['type']
156 if iface
["type"] == "data":
157 myIfaceDict
["vpci"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
158 myIfaceDict
["bw"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
159 myIfaceDict
["model"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
161 myIfaceDict
["vpci"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
162 myIfaceDict
["bw"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
163 myIfaceDict
["model"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
164 myIfaceDict
["mac"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['mac']
165 print "Iface name: %s" % iface
['name']
166 created_time
+= 0.00001
167 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
168 #print "Iface id in NFVO DB: %s" % iface_id
172 except (mdb
.Error
, AttributeError) as e
:
173 self
._format
_error
(e
, tries
)
177 def new_scenario(self
, scenario_dict
):
180 created_time
= time
.time()
183 self
.cur
= self
.con
.cursor()
184 tenant_id
= scenario_dict
.get('tenant_id')
186 INSERT_
={'tenant_id': tenant_id
,
187 'name': scenario_dict
['name'],
188 'description': scenario_dict
['description'],
189 'public': scenario_dict
.get('public', "false")}
191 scenario_uuid
= self
._new
_row
_internal
('scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
193 for net
in scenario_dict
['nets'].values():
194 net_dict
={'scenario_id': scenario_uuid
}
195 net_dict
["name"] = net
["name"]
196 net_dict
["type"] = net
["type"]
197 net_dict
["description"] = net
.get("description")
198 net_dict
["external"] = net
.get("external", False)
200 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
201 #TODO, must be json because of the GUI, change to yaml
202 net_dict
["graph"]=json
.dumps(net
["graph"])
203 created_time
+= 0.00001
204 net_uuid
= self
._new
_row
_internal
('sce_nets', net_dict
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
207 for k
,vnf
in scenario_dict
['vnfs'].items():
208 INSERT_
={'scenario_id': scenario_uuid
,
210 'vnf_id': vnf
['uuid'],
211 #'description': scenario_dict['name']
212 'description': vnf
['description']
215 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
216 #TODO, must be json because of the GUI, change to yaml
217 INSERT_
["graph"]=json
.dumps(vnf
["graph"])
218 created_time
+= 0.00001
219 scn_vnf_uuid
= self
._new
_row
_internal
('sce_vnfs', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
220 vnf
['scn_vnf_uuid']=scn_vnf_uuid
222 for iface
in vnf
['ifaces'].values():
223 #print 'iface', iface
224 if 'net_key' not in iface
:
226 iface
['net_id'] = scenario_dict
['nets'][ iface
['net_key'] ]['uuid']
227 INSERT_
={'sce_vnf_id': scn_vnf_uuid
,
228 'sce_net_id': iface
['net_id'],
229 'interface_id': iface
[ 'uuid' ]
231 created_time
+= 0.00001
232 iface_uuid
= self
._new
_row
_internal
('sce_interfaces', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
236 except (mdb
.Error
, AttributeError) as e
:
237 self
._format
_error
(e
, tries
)
240 def edit_scenario(self
, scenario_dict
):
243 modified_time
= time
.time()
247 self
.cur
= self
.con
.cursor()
248 #check that scenario exist
249 tenant_id
= scenario_dict
.get('tenant_id')
250 scenario_uuid
= scenario_dict
['uuid']
252 where_text
= "uuid='{}'".format(scenario_uuid
)
253 if not tenant_id
and tenant_id
!= "any":
254 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
255 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
256 self
.logger
.debug(cmd
)
257 self
.cur
.execute(cmd
)
259 if self
.cur
.rowcount
==0:
260 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
261 elif self
.cur
.rowcount
>1:
262 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
266 topology
= scenario_dict
.pop("topology", None)
267 if topology
!= None and "nodes" in topology
:
268 nodes
= topology
.get("nodes",{})
270 if "name" in scenario_dict
: UPDATE_
["name"] = scenario_dict
["name"]
271 if "description" in scenario_dict
: UPDATE_
["description"] = scenario_dict
["description"]
273 WHERE_
={'tenant_id': tenant_id
, 'uuid': scenario_uuid
}
274 item_changed
+= self
._update
_rows
('scenarios', UPDATE_
, WHERE_
, modified_time
=modified_time
)
276 for node_id
, node
in nodes
.items():
278 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
279 #TODO, must be json because of the GUI, change to yaml
280 node
["graph"] = json
.dumps(node
["graph"])
281 WHERE_
={'scenario_id': scenario_uuid
, 'uuid': node_id
}
282 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
283 item_changed
+= self
._update
_rows
('sce_nets', node
, WHERE_
)
284 item_changed
+= self
._update
_rows
('sce_vnfs', node
, WHERE_
, modified_time
=modified_time
)
287 except (mdb
.Error
, AttributeError) as e
:
288 self
._format
_error
(e
, tries
)
291 # def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
292 # '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
293 # instance_scenario_id is the uuid or the name if it is not a valid uuid format
294 # Only one scenario isntance must mutch the filtering or an error is returned
296 # print "1******************************************************************"
299 # self.cur = self.con.cursor(mdb.cursors.DictCursor)
302 # if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
303 # if db_base._check_valid_uuid(instance_scenario_id):
304 # where_list.append( "uuid='" + instance_scenario_id +"'" )
306 # where_list.append( "name='" + instance_scenario_id +"'" )
307 # where_text = " AND ".join(where_list)
308 # self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
309 # rows = self.cur.fetchall()
310 # if self.cur.rowcount==0:
311 # return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
312 # elif self.cur.rowcount>1:
313 # return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
314 # instance_scenario_dict = rows[0]
317 # self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
318 # instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
319 # for vnf in instance_scenario_dict['instance_vnfs']:
321 # self.cur.execute("SELECT uuid, vim_vm_id "+
322 # "FROM instance_vms "+
323 # "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
325 # vnf['instance_vms'] = self.cur.fetchall()
327 # self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
328 # instance_scenario_dict['instance_nets'] = self.cur.fetchall()
330 # #instance_interfaces
331 # self.cur.execute("SELECT uuid, vim_interface_id, instance_vm_id, instance_net_id FROM instance_interfaces WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
332 # instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
334 # db_base._convert_datetime2str(instance_scenario_dict)
335 # db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
336 # print "2******************************************************************"
337 # return 1, instance_scenario_dict
338 # except (mdb.Error, AttributeError) as e:
339 # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
340 # return self._format_error(e)
342 def get_scenario(self
, scenario_id
, tenant_id
=None, datacenter_id
=None):
343 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
344 scenario_id is the uuid or the name if it is not a valid uuid format
345 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
346 Only one scenario must mutch the filtering or an error is returned
352 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
353 where_text
= "uuid='{}'".format(scenario_id
)
354 if not tenant_id
and tenant_id
!= "any":
355 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
356 cmd
= "SELECT * FROM scenarios WHERE " + where_text
357 self
.logger
.debug(cmd
)
358 self
.cur
.execute(cmd
)
359 rows
= self
.cur
.fetchall()
360 if self
.cur
.rowcount
==0:
361 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
362 elif self
.cur
.rowcount
>1:
363 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
364 scenario_dict
= rows
[0]
365 if scenario_dict
["cloud_config"]:
366 scenario_dict
["cloud-config"] = yaml
.load(scenario_dict
["cloud_config"])
367 del scenario_dict
["cloud_config"]
369 cmd
= "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict
['uuid'])
370 self
.logger
.debug(cmd
)
371 self
.cur
.execute(cmd
)
372 scenario_dict
['vnfs'] = self
.cur
.fetchall()
373 for vnf
in scenario_dict
['vnfs']:
375 cmd
= "SELECT uuid,sce_net_id,interface_id FROM sce_interfaces WHERE sce_vnf_id='{}' ORDER BY created_at".format(vnf
['uuid'])
376 self
.logger
.debug(cmd
)
377 self
.cur
.execute(cmd
)
378 vnf
['interfaces'] = self
.cur
.fetchall()
380 cmd
= "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name, vms.description as description " \
381 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id " \
382 " WHERE vnfs.uuid='" + vnf
['vnf_id'] +"'" \
383 " ORDER BY vms.created_at"
384 self
.logger
.debug(cmd
)
385 self
.cur
.execute(cmd
)
386 vnf
['vms'] = self
.cur
.fetchall()
387 for vm
in vnf
['vms']:
388 if datacenter_id
!=None:
389 cmd
= "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm
['image_id'],datacenter_id
)
390 self
.logger
.debug(cmd
)
391 self
.cur
.execute(cmd
)
392 if self
.cur
.rowcount
==1:
393 vim_image_dict
= self
.cur
.fetchone()
394 vm
['vim_image_id']=vim_image_dict
['vim_id']
395 cmd
= "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm
['flavor_id'],datacenter_id
)
396 self
.logger
.debug(cmd
)
397 self
.cur
.execute(cmd
)
398 if self
.cur
.rowcount
==1:
399 vim_flavor_dict
= self
.cur
.fetchone()
400 vm
['vim_flavor_id']=vim_flavor_dict
['vim_id']
403 cmd
= "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model" \
405 " WHERE vm_id='{}'" \
406 " ORDER BY created_at".format(vm
['uuid'])
407 self
.logger
.debug(cmd
)
408 self
.cur
.execute(cmd
)
409 vm
['interfaces'] = self
.cur
.fetchall()
410 #nets every net of a vms
411 cmd
= "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf
['vnf_id'])
412 self
.logger
.debug(cmd
)
413 self
.cur
.execute(cmd
)
414 vnf
['nets'] = self
.cur
.fetchall()
416 cmd
= "SELECT uuid,name,type,external,description" \
417 " FROM sce_nets WHERE scenario_id='{}'" \
418 " ORDER BY created_at ".format(scenario_dict
['uuid'])
419 self
.logger
.debug(cmd
)
420 self
.cur
.execute(cmd
)
421 scenario_dict
['nets'] = self
.cur
.fetchall()
423 for net
in scenario_dict
['nets']:
424 if str(net
['external']) == 'false':
426 WHERE_
=" WHERE name='{}'".format(net
['name'])
427 if datacenter_id
!=None:
428 WHERE_
+= " AND datacenter_id='{}'".format(datacenter_id
)
429 cmd
= "SELECT vim_net_id FROM datacenter_nets" + WHERE_
430 self
.logger
.debug(cmd
)
431 self
.cur
.execute(cmd
)
432 d_net
= self
.cur
.fetchone()
433 if d_net
==None or datacenter_id
==None:
434 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
437 net
['vim_id']=d_net
['vim_net_id']
439 db_base
._convert
_datetime
2str
(scenario_dict
)
440 db_base
._convert
_str
2boolean
(scenario_dict
, ('public','shared','external') )
442 except (mdb
.Error
, AttributeError) as e
:
443 self
._format
_error
(e
, tries
)
447 def delete_scenario(self
, scenario_id
, tenant_id
=None):
448 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
449 scenario_id is the uuid or the name if it is not a valid uuid format
450 Only one scenario must mutch the filtering or an error is returned
456 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
459 where_text
= "uuid='{}'".format(scenario_id
)
460 if not tenant_id
and tenant_id
!= "any":
461 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
462 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
463 self
.logger
.debug(cmd
)
464 self
.cur
.execute(cmd
)
465 rows
= self
.cur
.fetchall()
466 if self
.cur
.rowcount
==0:
467 raise db_base
.db_base_Exception("No scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
468 elif self
.cur
.rowcount
>1:
469 raise db_base
.db_base_Exception("More than one scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
470 scenario_uuid
= rows
[0]["uuid"]
471 scenario_name
= rows
[0]["name"]
474 cmd
= "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid
)
475 self
.logger
.debug(cmd
)
476 self
.cur
.execute(cmd
)
478 return scenario_uuid
+ " " + scenario_name
479 except (mdb
.Error
, AttributeError) as e
:
480 self
._format
_error
(e
, tries
, "delete", "instances running")
483 def new_instance_scenario_as_a_whole(self
,tenant_id
,instance_scenario_name
,instance_scenario_description
,scenarioDict
):
486 created_time
= time
.time()
489 self
.cur
= self
.con
.cursor()
491 datacenter_tenant_id
= scenarioDict
['datacenter_tenant_id']
492 datacenter_id
= scenarioDict
['datacenter_id']
493 INSERT_
={'tenant_id': tenant_id
,
494 'datacenter_tenant_id': datacenter_tenant_id
,
495 'name': instance_scenario_name
,
496 'description': instance_scenario_description
,
497 'scenario_id' : scenarioDict
['uuid'],
498 'datacenter_id': datacenter_id
500 if scenarioDict
.get("cloud-config"):
501 INSERT_
["cloud_config"] = yaml
.safe_dump(scenarioDict
["cloud-config"], default_flow_style
=True, width
=256)
503 instance_uuid
= self
._new
_row
_internal
('instance_scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
505 net_scene2instance
={}
506 #instance_nets #nets interVNF
507 for net
in scenarioDict
['nets']:
508 net_scene2instance
[ net
['uuid'] ] ={}
509 datacenter_site_id
= net
.get('datacenter_id', datacenter_id
)
510 if not "vim_id_sites" in net
:
511 net
["vim_id_sites"] ={datacenter_site_id
: net
['vim_id']}
512 sce_net_id
= net
.get("uuid")
514 for datacenter_site_id
,vim_id
in net
["vim_id_sites"].iteritems():
515 INSERT_
={'vim_net_id': vim_id
, 'external': net
['external'], 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
516 INSERT_
['datacenter_id'] = datacenter_site_id
517 INSERT_
['datacenter_tenant_id'] = net
.get('datacenter_tenant_id', datacenter_tenant_id
) #TODO revise
519 INSERT_
['sce_net_id'] = sce_net_id
520 created_time
+= 0.00001
521 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
522 net_scene2instance
[ sce_net_id
][datacenter_site_id
] = instance_net_uuid
523 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
526 for vnf
in scenarioDict
['vnfs']:
527 datacenter_site_id
= vnf
.get('datacenter_id', datacenter_id
)
528 datacenter_site_tenant_id
= vnf
.get('datacenter_tenant_id', datacenter_id
)
529 INSERT_
={'instance_scenario_id': instance_uuid
, 'vnf_id': vnf
['vnf_id'] }
530 INSERT_
['datacenter_id'] = datacenter_site_id
531 INSERT_
['datacenter_tenant_id'] = datacenter_site_tenant_id
#TODO revise
533 INSERT_
['sce_vnf_id'] = vnf
['uuid']
534 created_time
+= 0.00001
535 instance_vnf_uuid
= self
._new
_row
_internal
('instance_vnfs', INSERT_
, True, instance_uuid
, created_time
)
536 vnf
['uuid'] = instance_vnf_uuid
#overwrite scnario uuid by instance uuid
538 #instance_nets #nets intraVNF
539 for net
in vnf
['nets']:
540 net_scene2instance
[ net
['uuid'] ] = {}
541 INSERT_
={'vim_net_id': net
['vim_id'], 'external': 'false', 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
542 INSERT_
['datacenter_id'] = net
.get('datacenter_id', datacenter_site_id
)
543 INSERT_
['datacenter_tenant_id'] = net
.get('datacenter_tenant_id', datacenter_site_tenant_id
)
545 INSERT_
['net_id'] = net
['uuid']
546 created_time
+= 0.00001
547 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
548 net_scene2instance
[ net
['uuid'] ][datacenter_site_id
] = instance_net_uuid
549 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
552 for vm
in vnf
['vms']:
553 INSERT_
={'instance_vnf_id': instance_vnf_uuid
, 'vm_id': vm
['uuid'], 'vim_vm_id': vm
['vim_id'] }
554 created_time
+= 0.00001
555 instance_vm_uuid
= self
._new
_row
_internal
('instance_vms', INSERT_
, True, instance_uuid
, created_time
)
556 vm
['uuid'] = instance_vm_uuid
#overwrite scnario uuid by instance uuid
559 for interface
in vm
['interfaces']:
560 net_id
= interface
.get('net_id', None)
562 #check if is connected to a inter VNFs net
563 for iface
in vnf
['interfaces']:
564 if iface
['interface_id'] == interface
['uuid']:
565 net_id
= iface
.get('sce_net_id', None)
569 interface_type
='external' if interface
['external_name'] is not None else 'internal'
570 INSERT_
={'instance_vm_id': instance_vm_uuid
, 'instance_net_id': net_scene2instance
[net_id
][datacenter_site_id
],
571 'interface_id': interface
['uuid'], 'vim_interface_id': interface
.get('vim_id'), 'type': interface_type
}
572 #created_time += 0.00001
573 interface_uuid
= self
._new
_row
_internal
('instance_interfaces', INSERT_
, True, instance_uuid
) #, created_time)
574 interface
['uuid'] = interface_uuid
#overwrite scnario uuid by instance uuid
576 except (mdb
.Error
, AttributeError) as e
:
577 self
._format
_error
(e
, tries
)
580 def get_instance_scenario(self
, instance_id
, tenant_id
=None, verbose
=False):
581 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
582 instance_id is the uuid or the name if it is not a valid uuid format
583 Only one instance must mutch the filtering or an error is returned
589 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
592 if tenant_id
is not None: where_list
.append( "inst.tenant_id='" + tenant_id
+"'" )
593 if db_base
._check
_valid
_uuid
(instance_id
):
594 where_list
.append( "inst.uuid='" + instance_id
+"'" )
596 where_list
.append( "inst.name='" + instance_id
+"'" )
597 where_text
= " AND ".join(where_list
)
598 cmd
= "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
599 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
600 " ,inst.description as description,inst.created_at as created_at" +\
601 " ,inst.cloud_config as 'cloud_config'" +\
602 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
603 " WHERE " + where_text
604 self
.logger
.debug(cmd
)
605 self
.cur
.execute(cmd
)
606 rows
= self
.cur
.fetchall()
608 if self
.cur
.rowcount
==0:
609 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Not_Found
)
610 elif self
.cur
.rowcount
>1:
611 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
612 instance_dict
= rows
[0]
613 if instance_dict
["cloud_config"]:
614 instance_dict
["cloud-config"] = yaml
.load(instance_dict
["cloud_config"])
615 del instance_dict
["cloud_config"]
618 cmd
= "SELECT iv.uuid as uuid,sv.vnf_id as vnf_id,sv.name as vnf_name, sce_vnf_id, datacenter_id, datacenter_tenant_id"\
619 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
620 " WHERE iv.instance_scenario_id='{}'" \
621 " ORDER BY iv.created_at ".format(instance_dict
['uuid'])
622 self
.logger
.debug(cmd
)
623 self
.cur
.execute(cmd
)
624 instance_dict
['vnfs'] = self
.cur
.fetchall()
625 for vnf
in instance_dict
['vnfs']:
626 vnf_manage_iface_list
=[]
628 cmd
= "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
629 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
630 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf
['uuid'])
631 self
.logger
.debug(cmd
)
632 self
.cur
.execute(cmd
)
633 vnf
['vms'] = self
.cur
.fetchall()
634 for vm
in vnf
['vms']:
635 vm_manage_iface_list
=[]
637 cmd
= "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address, ii.ip_address as ip_address, vim_info, i.type as type "\
638 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid "\
639 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm
['uuid'])
640 self
.logger
.debug(cmd
)
641 self
.cur
.execute(cmd
)
642 vm
['interfaces'] = self
.cur
.fetchall()
643 for iface
in vm
['interfaces']:
644 if iface
["type"] == "mgmt" and iface
["ip_address"]:
645 vnf_manage_iface_list
.append(iface
["ip_address"])
646 vm_manage_iface_list
.append(iface
["ip_address"])
649 if vm_manage_iface_list
: vm
["ip_address"] = ",".join(vm_manage_iface_list
)
650 if vnf_manage_iface_list
: vnf
["ip_address"] = ",".join(vnf_manage_iface_list
)
653 #select_text = "instance_nets.uuid as uuid,sce_nets.name as net_name,instance_nets.vim_net_id as net_id,instance_nets.status as status,instance_nets.external as external"
654 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
655 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
656 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
657 cmd
= "SELECT uuid,vim_net_id,status,error_msg,vim_info,external, sce_net_id, net_id as vnf_net_id, datacenter_id, datacenter_tenant_id"\
658 " FROM instance_nets" \
659 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
660 self
.logger
.debug(cmd
)
661 self
.cur
.execute(cmd
)
662 instance_dict
['nets'] = self
.cur
.fetchall()
664 db_base
._convert
_datetime
2str
(instance_dict
)
665 db_base
._convert
_str
2boolean
(instance_dict
, ('public','shared','external') )
667 except (mdb
.Error
, AttributeError) as e
:
668 self
._format
_error
(e
, tries
)
671 def delete_instance_scenario(self
, instance_id
, tenant_id
=None):
672 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
673 instance_id is the uuid or the name if it is not a valid uuid format
674 Only one instance_scenario must mutch the filtering or an error is returned
680 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
684 if tenant_id
is not None: where_list
.append( "tenant_id='" + tenant_id
+"'" )
685 if db_base
._check
_valid
_uuid
(instance_id
):
686 where_list
.append( "uuid='" + instance_id
+"'" )
688 where_list
.append( "name='" + instance_id
+"'" )
689 where_text
= " AND ".join(where_list
)
690 cmd
= "SELECT * FROM instance_scenarios WHERE "+ where_text
691 self
.logger
.debug(cmd
)
692 self
.cur
.execute(cmd
)
693 rows
= self
.cur
.fetchall()
695 if self
.cur
.rowcount
==0:
696 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
697 elif self
.cur
.rowcount
>1:
698 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
699 instance_uuid
= rows
[0]["uuid"]
700 instance_name
= rows
[0]["name"]
703 cmd
= "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid
)
704 self
.logger
.debug(cmd
)
705 self
.cur
.execute(cmd
)
707 return instance_uuid
+ " " + instance_name
708 except (mdb
.Error
, AttributeError) as e
:
709 self
._format
_error
(e
, tries
, "delete", "No dependences can avoid deleting!!!!")
712 def new_instance_scenario(self
, instance_scenario_dict
, tenant_id
):
713 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
714 return self
._new
_row
_internal
('instance_scenarios', instance_scenario_dict
, tenant_id
, add_uuid
=True, root_uuid
=None, log
=True)
716 def update_instance_scenario(self
, instance_scenario_dict
):
720 def new_instance_vnf(self
, instance_vnf_dict
, tenant_id
, instance_scenario_id
= None):
721 #return self.new_row('vms', vm_dict, tenant_id, True, True)
722 return self
._new
_row
_internal
('instance_vnfs', instance_vnf_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
724 def update_instance_vnf(self
, instance_vnf_dict
):
728 def delete_instance_vnf(self
, instance_vnf_id
):
732 def new_instance_vm(self
, instance_vm_dict
, tenant_id
, instance_scenario_id
= None):
733 #return self.new_row('vms', vm_dict, tenant_id, True, True)
734 return self
._new
_row
_internal
('instance_vms', instance_vm_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
736 def update_instance_vm(self
, instance_vm_dict
):
740 def delete_instance_vm(self
, instance_vm_id
):
744 def new_instance_net(self
, instance_net_dict
, tenant_id
, instance_scenario_id
= None):
745 return self
._new
_row
_internal
('instance_nets', instance_net_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
747 def update_instance_net(self
, instance_net_dict
):
751 def delete_instance_net(self
, instance_net_id
):
755 def new_instance_interface(self
, instance_interface_dict
, tenant_id
, instance_scenario_id
= None):
756 return self
._new
_row
_internal
('instance_interfaces', instance_interface_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
758 def update_instance_interface(self
, instance_interface_dict
):
762 def delete_instance_interface(self
, instance_interface_dict
):
766 def update_datacenter_nets(self
, datacenter_id
, new_net_list
=[]):
767 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
769 datacenter_id: uuid of the datacenter to act upon
770 table: table where to insert
771 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
772 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
776 created_time
= time
.time()
779 self
.cur
= self
.con
.cursor()
780 cmd
="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id
)
781 self
.logger
.debug(cmd
)
782 self
.cur
.execute(cmd
)
783 deleted
= self
.cur
.rowcount
785 for new_net
in new_net_list
:
786 created_time
+= 0.00001
787 self
._new
_row
_internal
('datacenter_nets', new_net
, add_uuid
=True, created_time
=created_time
)
789 return inserted
, deleted
790 except (mdb
.Error
, AttributeError) as e
:
791 self
._format
_error
(e
, tries
)