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", "datacenter_nets"]
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
=None):
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
47 def new_vnf_as_a_whole(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
48 self
.logger
.debug("Adding new vnf to the NFVO database")
51 created_time
= time
.time()
56 myVNFDict
["name"] = vnf_name
57 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
58 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
59 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
60 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
61 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
63 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
64 #print "Adding new vms to the NFVO database"
65 #For each vm, we must create the appropriate vm in the NFVO database.
67 for _
,vm
in VNFCDict
.iteritems():
68 #This code could make the name of the vms grow and grow.
69 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
70 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
71 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
73 created_time
+= 0.00001
74 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
75 #print "Internal vm id in NFVO DB: %s" % vm_id
76 vmDict
[vm
['name']] = vm_id
78 #Collect the data interfaces of each VM/VNFC under the 'numas' field
80 for vm
in vnf_descriptor
['vnf']['VNFC']:
81 dataifacesDict
[vm
['name']] = {}
82 for numa
in vm
.get('numas', []):
83 for dataiface
in numa
.get('interfaces',[]):
84 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
85 dataifacesDict
[vm
['name']][dataiface
['name']] = {}
86 dataifacesDict
[vm
['name']][dataiface
['name']]['vpci'] = dataiface
['vpci']
87 dataifacesDict
[vm
['name']][dataiface
['name']]['bw'] = dataiface
['bandwidth']
88 dataifacesDict
[vm
['name']][dataiface
['name']]['model'] = "PF" if dataiface
['dedicated']=="yes" else ("VF" if dataiface
['dedicated']=="no" else "VFnotShared")
90 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
91 bridgeInterfacesDict
= {}
92 for vm
in vnf_descriptor
['vnf']['VNFC']:
93 if 'bridge-ifaces' in vm
:
94 bridgeInterfacesDict
[vm
['name']] = {}
95 for bridgeiface
in vm
['bridge-ifaces']:
96 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
97 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = {}
98 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['vpci'] = bridgeiface
.get('vpci',None)
99 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['mac'] = bridgeiface
.get('mac_address',None)
100 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['bw'] = bridgeiface
.get('bandwidth', None)
101 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['model'] = bridgeiface
.get('model', None)
103 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
104 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
105 internalconnList
= []
106 if 'internal-connections' in vnf_descriptor
['vnf']:
107 for net
in vnf_descriptor
['vnf']['internal-connections']:
108 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
111 myNetDict
["name"] = net
['name']
112 myNetDict
["description"] = net
['description']
113 myNetDict
["type"] = net
['type']
114 myNetDict
["vnf_id"] = vnf_id
116 created_time
+= 0.00001
117 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
119 for element
in net
['elements']:
121 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
122 ifaceItem
["internal_name"] = element
['local_iface_name']
123 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
124 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
125 ifaceItem
["net_id"] = net_id
126 ifaceItem
["type"] = net
['type']
127 if ifaceItem
["type"] == "data":
128 ifaceItem
["vpci"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
129 ifaceItem
["bw"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
130 ifaceItem
["model"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
132 ifaceItem
["vpci"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
133 ifaceItem
["mac"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['mac_address']
134 ifaceItem
["bw"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
135 ifaceItem
["model"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
136 internalconnList
.append(ifaceItem
)
137 #print "Internal net id in NFVO DB: %s" % net_id
139 #print "Adding internal interfaces to the NFVO database (if any)"
140 for iface
in internalconnList
:
141 print "Iface name: %s" % iface
['internal_name']
142 created_time
+= 0.00001
143 iface_id
= self
._new
_row
_internal
('interfaces', iface
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
144 #print "Iface id in NFVO DB: %s" % iface_id
146 #print "Adding external interfaces to the NFVO database"
147 for iface
in vnf_descriptor
['vnf']['external-connections']:
149 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
150 myIfaceDict
["internal_name"] = iface
['local_iface_name']
151 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
152 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
153 myIfaceDict
["external_name"] = iface
['name']
154 myIfaceDict
["type"] = iface
['type']
155 if iface
["type"] == "data":
156 myIfaceDict
["vpci"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
157 myIfaceDict
["bw"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
158 myIfaceDict
["model"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
160 myIfaceDict
["vpci"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
161 myIfaceDict
["bw"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
162 myIfaceDict
["model"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
163 myIfaceDict
["mac"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['mac']
164 print "Iface name: %s" % iface
['name']
165 created_time
+= 0.00001
166 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
167 #print "Iface id in NFVO DB: %s" % iface_id
171 except (mdb
.Error
, AttributeError) as e
:
172 self
._format
_error
(e
, tries
)
175 def new_vnf_as_a_whole2(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
176 self
.logger
.debug("Adding new vnf to the NFVO database")
179 created_time
= time
.time()
184 myVNFDict
["name"] = vnf_name
185 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
186 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
187 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
188 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
189 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
191 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
192 #print "Adding new vms to the NFVO database"
193 #For each vm, we must create the appropriate vm in the NFVO database.
195 for _
,vm
in VNFCDict
.iteritems():
196 #This code could make the name of the vms grow and grow.
197 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
198 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
199 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
200 vm
["vnf_id"] = vnf_id
201 created_time
+= 0.00001
202 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
203 #print "Internal vm id in NFVO DB: %s" % vm_id
204 vmDict
[vm
['name']] = vm_id
206 #Collect the data interfaces of each VM/VNFC under the 'numas' field
208 for vm
in vnf_descriptor
['vnf']['VNFC']:
209 dataifacesDict
[vm
['name']] = {}
210 for numa
in vm
.get('numas', []):
211 for dataiface
in numa
.get('interfaces',[]):
212 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
213 dataifacesDict
[vm
['name']][dataiface
['name']] = {}
214 dataifacesDict
[vm
['name']][dataiface
['name']]['vpci'] = dataiface
['vpci']
215 dataifacesDict
[vm
['name']][dataiface
['name']]['bw'] = dataiface
['bandwidth']
216 dataifacesDict
[vm
['name']][dataiface
['name']]['model'] = "PF" if dataiface
['dedicated']=="yes" else ("VF" if dataiface
['dedicated']=="no" else "VFnotShared")
218 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
219 bridgeInterfacesDict
= {}
220 for vm
in vnf_descriptor
['vnf']['VNFC']:
221 if 'bridge-ifaces' in vm
:
222 bridgeInterfacesDict
[vm
['name']] = {}
223 for bridgeiface
in vm
['bridge-ifaces']:
224 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
225 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = {}
226 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['vpci'] = bridgeiface
.get('vpci',None)
227 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['mac'] = bridgeiface
.get('mac_address',None)
228 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['bw'] = bridgeiface
.get('bandwidth', None)
229 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['model'] = bridgeiface
.get('model', None)
231 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
232 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
233 internalconnList
= []
234 if 'internal-connections' in vnf_descriptor
['vnf']:
235 for net
in vnf_descriptor
['vnf']['internal-connections']:
236 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
239 myNetDict
["name"] = net
['name']
240 myNetDict
["description"] = net
['description']
241 if (net
["implementation"] == "overlay"):
242 net
["type"] = "bridge"
243 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
244 elif (net
["implementation"] == "underlay"):
245 if (net
["type"] == "e-line"):
247 elif (net
["type"] == "e-lan"):
249 net
.pop("implementation")
250 myNetDict
["type"] = net
['type']
251 myNetDict
["vnf_id"] = vnf_id
253 created_time
+= 0.00001
254 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
256 if "ip-profile" in net
:
257 ip_profile
= net
["ip-profile"]
259 myIPProfileDict
["net_id"] = net_id
260 myIPProfileDict
["ip_version"] = ip_profile
.get('ip-version',"IPv4")
261 myIPProfileDict
["subnet_address"] = ip_profile
.get('subnet-address',None)
262 myIPProfileDict
["gateway_address"] = ip_profile
.get('gateway-address',None)
263 myIPProfileDict
["dns_address"] = ip_profile
.get('dns-address',None)
264 if ("dhcp" in ip_profile
):
265 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled',"true")
266 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address',None)
267 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count',None)
269 created_time
+= 0.00001
270 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
272 for element
in net
['elements']:
274 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
275 ifaceItem
["internal_name"] = element
['local_iface_name']
276 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
277 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
278 ifaceItem
["net_id"] = net_id
279 ifaceItem
["type"] = net
['type']
280 ifaceItem
["ip_address"] = element
.get('ip_address',None)
281 if ifaceItem
["type"] == "data":
282 ifaceItem
["vpci"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
283 ifaceItem
["bw"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
284 ifaceItem
["model"] = dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
286 ifaceItem
["vpci"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['vpci']
287 ifaceItem
["mac"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['mac']
288 ifaceItem
["bw"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['bw']
289 ifaceItem
["model"] = bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]['model']
290 internalconnList
.append(ifaceItem
)
291 #print "Internal net id in NFVO DB: %s" % net_id
293 #print "Adding internal interfaces to the NFVO database (if any)"
294 for iface
in internalconnList
:
295 print "Iface name: %s" % iface
['internal_name']
296 created_time
+= 0.00001
297 iface_id
= self
._new
_row
_internal
('interfaces', iface
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
298 #print "Iface id in NFVO DB: %s" % iface_id
300 #print "Adding external interfaces to the NFVO database"
301 for iface
in vnf_descriptor
['vnf']['external-connections']:
303 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
304 myIfaceDict
["internal_name"] = iface
['local_iface_name']
305 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
306 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
307 myIfaceDict
["external_name"] = iface
['name']
308 myIfaceDict
["type"] = iface
['type']
309 if iface
["type"] == "data":
310 myIfaceDict
["vpci"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
311 myIfaceDict
["bw"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
312 myIfaceDict
["model"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
314 myIfaceDict
["vpci"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
315 myIfaceDict
["bw"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
316 myIfaceDict
["model"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
317 myIfaceDict
["mac"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['mac']
318 print "Iface name: %s" % iface
['name']
319 created_time
+= 0.00001
320 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
321 #print "Iface id in NFVO DB: %s" % iface_id
325 except (mdb
.Error
, AttributeError) as e
:
326 self
._format
_error
(e
, tries
)
327 # except KeyError as e2:
328 # exc_type, exc_obj, exc_tb = sys.exc_info()
329 # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
330 # self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
334 def new_scenario(self
, scenario_dict
):
337 created_time
= time
.time()
340 self
.cur
= self
.con
.cursor()
341 tenant_id
= scenario_dict
.get('tenant_id')
343 INSERT_
={'tenant_id': tenant_id
,
344 'name': scenario_dict
['name'],
345 'description': scenario_dict
['description'],
346 'public': scenario_dict
.get('public', "false")}
348 scenario_uuid
= self
._new
_row
_internal
('scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
350 for net
in scenario_dict
['nets'].values():
351 net_dict
={'scenario_id': scenario_uuid
}
352 net_dict
["name"] = net
["name"]
353 net_dict
["type"] = net
["type"]
354 net_dict
["description"] = net
.get("description")
355 net_dict
["external"] = net
.get("external", False)
357 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
358 #TODO, must be json because of the GUI, change to yaml
359 net_dict
["graph"]=json
.dumps(net
["graph"])
360 created_time
+= 0.00001
361 net_uuid
= self
._new
_row
_internal
('sce_nets', net_dict
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
364 for k
,vnf
in scenario_dict
['vnfs'].items():
365 INSERT_
={'scenario_id': scenario_uuid
,
367 'vnf_id': vnf
['uuid'],
368 #'description': scenario_dict['name']
369 'description': vnf
['description']
372 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
373 #TODO, must be json because of the GUI, change to yaml
374 INSERT_
["graph"]=json
.dumps(vnf
["graph"])
375 created_time
+= 0.00001
376 scn_vnf_uuid
= self
._new
_row
_internal
('sce_vnfs', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
377 vnf
['scn_vnf_uuid']=scn_vnf_uuid
379 for iface
in vnf
['ifaces'].values():
380 #print 'iface', iface
381 if 'net_key' not in iface
:
383 iface
['net_id'] = scenario_dict
['nets'][ iface
['net_key'] ]['uuid']
384 INSERT_
={'sce_vnf_id': scn_vnf_uuid
,
385 'sce_net_id': iface
['net_id'],
386 'interface_id': iface
[ 'uuid' ]
388 created_time
+= 0.00001
389 iface_uuid
= self
._new
_row
_internal
('sce_interfaces', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
393 except (mdb
.Error
, AttributeError) as e
:
394 self
._format
_error
(e
, tries
)
397 def new_scenario2(self
, scenario_dict
):
400 created_time
= time
.time()
403 self
.cur
= self
.con
.cursor()
404 tenant_id
= scenario_dict
.get('tenant_id')
406 INSERT_
={'tenant_id': tenant_id
,
407 'name': scenario_dict
['name'],
408 'description': scenario_dict
['description'],
409 'public': scenario_dict
.get('public', "false")}
411 scenario_uuid
= self
._new
_row
_internal
('scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
413 for net
in scenario_dict
['nets'].values():
414 net_dict
={'scenario_id': scenario_uuid
}
415 net_dict
["name"] = net
["name"]
416 net_dict
["type"] = net
["type"]
417 net_dict
["description"] = net
.get("description")
418 net_dict
["external"] = net
.get("external", False)
420 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
421 #TODO, must be json because of the GUI, change to yaml
422 net_dict
["graph"]=json
.dumps(net
["graph"])
423 created_time
+= 0.00001
424 net_uuid
= self
._new
_row
_internal
('sce_nets', net_dict
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
427 if "ip-profile" in net
:
428 ip_profile
= net
["ip-profile"]
430 myIPProfileDict
["sce_net_id"] = net_uuid
431 myIPProfileDict
["ip_version"] = ip_profile
.get('ip-version',"IPv4")
432 myIPProfileDict
["subnet_address"] = ip_profile
.get('subnet-address',None)
433 myIPProfileDict
["gateway_address"] = ip_profile
.get('gateway-address',None)
434 myIPProfileDict
["dns_address"] = ip_profile
.get('dns-address',None)
435 if ("dhcp" in ip_profile
):
436 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled',"true")
437 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address',None)
438 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count',None)
440 created_time
+= 0.00001
441 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
444 for k
,vnf
in scenario_dict
['vnfs'].items():
445 INSERT_
={'scenario_id': scenario_uuid
,
447 'vnf_id': vnf
['uuid'],
448 #'description': scenario_dict['name']
449 'description': vnf
['description']
452 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
453 #TODO, must be json because of the GUI, change to yaml
454 INSERT_
["graph"]=json
.dumps(vnf
["graph"])
455 created_time
+= 0.00001
456 scn_vnf_uuid
= self
._new
_row
_internal
('sce_vnfs', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
457 vnf
['scn_vnf_uuid']=scn_vnf_uuid
459 for iface
in vnf
['ifaces'].values():
460 #print 'iface', iface
461 if 'net_key' not in iface
:
463 iface
['net_id'] = scenario_dict
['nets'][ iface
['net_key'] ]['uuid']
464 INSERT_
={'sce_vnf_id': scn_vnf_uuid
,
465 'sce_net_id': iface
['net_id'],
466 'interface_id': iface
['uuid'],
467 'ip_address': iface
['ip_address']
469 created_time
+= 0.00001
470 iface_uuid
= self
._new
_row
_internal
('sce_interfaces', INSERT_
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
474 except (mdb
.Error
, AttributeError) as e
:
475 self
._format
_error
(e
, tries
)
476 # except KeyError as e2:
477 # exc_type, exc_obj, exc_tb = sys.exc_info()
478 # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
479 # self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
483 def edit_scenario(self
, scenario_dict
):
486 modified_time
= time
.time()
490 self
.cur
= self
.con
.cursor()
491 #check that scenario exist
492 tenant_id
= scenario_dict
.get('tenant_id')
493 scenario_uuid
= scenario_dict
['uuid']
495 where_text
= "uuid='{}'".format(scenario_uuid
)
496 if not tenant_id
and tenant_id
!= "any":
497 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
498 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
499 self
.logger
.debug(cmd
)
500 self
.cur
.execute(cmd
)
502 if self
.cur
.rowcount
==0:
503 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
504 elif self
.cur
.rowcount
>1:
505 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
509 topology
= scenario_dict
.pop("topology", None)
510 if topology
!= None and "nodes" in topology
:
511 nodes
= topology
.get("nodes",{})
513 if "name" in scenario_dict
: UPDATE_
["name"] = scenario_dict
["name"]
514 if "description" in scenario_dict
: UPDATE_
["description"] = scenario_dict
["description"]
516 WHERE_
={'tenant_id': tenant_id
, 'uuid': scenario_uuid
}
517 item_changed
+= self
._update
_rows
('scenarios', UPDATE_
, WHERE_
, modified_time
=modified_time
)
519 for node_id
, node
in nodes
.items():
521 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
522 #TODO, must be json because of the GUI, change to yaml
523 node
["graph"] = json
.dumps(node
["graph"])
524 WHERE_
={'scenario_id': scenario_uuid
, 'uuid': node_id
}
525 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
526 item_changed
+= self
._update
_rows
('sce_nets', node
, WHERE_
)
527 item_changed
+= self
._update
_rows
('sce_vnfs', node
, WHERE_
, modified_time
=modified_time
)
530 except (mdb
.Error
, AttributeError) as e
:
531 self
._format
_error
(e
, tries
)
534 # def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
535 # '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
536 # instance_scenario_id is the uuid or the name if it is not a valid uuid format
537 # Only one scenario isntance must mutch the filtering or an error is returned
539 # print "1******************************************************************"
542 # self.cur = self.con.cursor(mdb.cursors.DictCursor)
545 # if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
546 # if db_base._check_valid_uuid(instance_scenario_id):
547 # where_list.append( "uuid='" + instance_scenario_id +"'" )
549 # where_list.append( "name='" + instance_scenario_id +"'" )
550 # where_text = " AND ".join(where_list)
551 # self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
552 # rows = self.cur.fetchall()
553 # if self.cur.rowcount==0:
554 # return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
555 # elif self.cur.rowcount>1:
556 # return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
557 # instance_scenario_dict = rows[0]
560 # self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
561 # instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
562 # for vnf in instance_scenario_dict['instance_vnfs']:
564 # self.cur.execute("SELECT uuid, vim_vm_id "+
565 # "FROM instance_vms "+
566 # "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
568 # vnf['instance_vms'] = self.cur.fetchall()
570 # self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
571 # instance_scenario_dict['instance_nets'] = self.cur.fetchall()
573 # #instance_interfaces
574 # 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'] + "'")
575 # instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
577 # db_base._convert_datetime2str(instance_scenario_dict)
578 # db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
579 # print "2******************************************************************"
580 # return 1, instance_scenario_dict
581 # except (mdb.Error, AttributeError) as e:
582 # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
583 # return self._format_error(e)
585 def get_scenario(self
, scenario_id
, tenant_id
=None, datacenter_id
=None):
586 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
587 scenario_id is the uuid or the name if it is not a valid uuid format
588 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
589 Only one scenario must mutch the filtering or an error is returned
595 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
596 where_text
= "uuid='{}'".format(scenario_id
)
597 if not tenant_id
and tenant_id
!= "any":
598 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
599 cmd
= "SELECT * FROM scenarios WHERE " + where_text
600 self
.logger
.debug(cmd
)
601 self
.cur
.execute(cmd
)
602 rows
= self
.cur
.fetchall()
603 if self
.cur
.rowcount
==0:
604 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
605 elif self
.cur
.rowcount
>1:
606 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
607 scenario_dict
= rows
[0]
608 if scenario_dict
["cloud_config"]:
609 scenario_dict
["cloud-config"] = yaml
.load(scenario_dict
["cloud_config"])
610 del scenario_dict
["cloud_config"]
612 cmd
= "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict
['uuid'])
613 self
.logger
.debug(cmd
)
614 self
.cur
.execute(cmd
)
615 scenario_dict
['vnfs'] = self
.cur
.fetchall()
616 for vnf
in scenario_dict
['vnfs']:
618 cmd
= "SELECT scei.uuid,scei.sce_net_id,scei.interface_id,i.external_name,scei.ip_address FROM sce_interfaces as scei join interfaces as i on scei.interface_id=i.uuid WHERE scei.sce_vnf_id='{}' ORDER BY scei.created_at".format(vnf
['uuid'])
619 self
.logger
.debug(cmd
)
620 self
.cur
.execute(cmd
)
621 vnf
['interfaces'] = self
.cur
.fetchall()
623 cmd
= "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name, vms.description as description " \
624 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id " \
625 " WHERE vnfs.uuid='" + vnf
['vnf_id'] +"'" \
626 " ORDER BY vms.created_at"
627 self
.logger
.debug(cmd
)
628 self
.cur
.execute(cmd
)
629 vnf
['vms'] = self
.cur
.fetchall()
630 for vm
in vnf
['vms']:
631 if datacenter_id
!=None:
632 cmd
= "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm
['image_id'],datacenter_id
)
633 self
.logger
.debug(cmd
)
634 self
.cur
.execute(cmd
)
635 if self
.cur
.rowcount
==1:
636 vim_image_dict
= self
.cur
.fetchone()
637 vm
['vim_image_id']=vim_image_dict
['vim_id']
638 cmd
= "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm
['flavor_id'],datacenter_id
)
639 self
.logger
.debug(cmd
)
640 self
.cur
.execute(cmd
)
641 if self
.cur
.rowcount
==1:
642 vim_flavor_dict
= self
.cur
.fetchone()
643 vm
['vim_flavor_id']=vim_flavor_dict
['vim_id']
646 cmd
= "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address" \
648 " WHERE vm_id='{}'" \
649 " ORDER BY created_at".format(vm
['uuid'])
650 self
.logger
.debug(cmd
)
651 self
.cur
.execute(cmd
)
652 vm
['interfaces'] = self
.cur
.fetchall()
653 #nets every net of a vms
654 cmd
= "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf
['vnf_id'])
655 self
.logger
.debug(cmd
)
656 self
.cur
.execute(cmd
)
657 vnf
['nets'] = self
.cur
.fetchall()
658 for vnf_net
in vnf
['nets']:
659 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
660 cmd
= "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_
,vnf_net
['uuid'])
661 self
.logger
.debug(cmd
)
662 self
.cur
.execute(cmd
)
663 ipprofiles
= self
.cur
.fetchall()
664 if self
.cur
.rowcount
==1:
665 vnf_net
["ip_profile"] = ipprofiles
[0]
666 elif self
.cur
.rowcount
>1:
667 raise db_base
.db_base_Exception("More than one ip-profile found with this criteria: net_id='{}'".format(vnf_net
['uuid']), db_base
.HTTP_Bad_Request
)
670 cmd
= "SELECT uuid,name,type,external,description" \
671 " FROM sce_nets WHERE scenario_id='{}'" \
672 " ORDER BY created_at ".format(scenario_dict
['uuid'])
673 self
.logger
.debug(cmd
)
674 self
.cur
.execute(cmd
)
675 scenario_dict
['nets'] = self
.cur
.fetchall()
677 for net
in scenario_dict
['nets']:
678 if str(net
['external']) == 'false':
679 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
680 cmd
= "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_
,net
['uuid'])
681 self
.logger
.debug(cmd
)
682 self
.cur
.execute(cmd
)
683 ipprofiles
= self
.cur
.fetchall()
684 if self
.cur
.rowcount
==1:
685 net
["ip_profile"] = ipprofiles
[0]
686 elif self
.cur
.rowcount
>1:
687 raise db_base
.db_base_Exception("More than one ip-profile found with this criteria: sce_net_id='{}'".format(net
['uuid']), db_base
.HTTP_Bad_Request
)
689 WHERE_
=" WHERE name='{}'".format(net
['name'])
690 if datacenter_id
!=None:
691 WHERE_
+= " AND datacenter_id='{}'".format(datacenter_id
)
692 cmd
= "SELECT vim_net_id FROM datacenter_nets" + WHERE_
693 self
.logger
.debug(cmd
)
694 self
.cur
.execute(cmd
)
695 d_net
= self
.cur
.fetchone()
696 if d_net
==None or datacenter_id
==None:
697 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
700 net
['vim_id']=d_net
['vim_net_id']
702 db_base
._convert
_datetime
2str
(scenario_dict
)
703 db_base
._convert
_str
2boolean
(scenario_dict
, ('public','shared','external') )
705 except (mdb
.Error
, AttributeError) as e
:
706 self
._format
_error
(e
, tries
)
709 def delete_scenario(self
, scenario_id
, tenant_id
=None):
710 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
711 scenario_id is the uuid or the name if it is not a valid uuid format
712 Only one scenario must mutch the filtering or an error is returned
718 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
721 where_text
= "uuid='{}'".format(scenario_id
)
722 if not tenant_id
and tenant_id
!= "any":
723 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
724 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
725 self
.logger
.debug(cmd
)
726 self
.cur
.execute(cmd
)
727 rows
= self
.cur
.fetchall()
728 if self
.cur
.rowcount
==0:
729 raise db_base
.db_base_Exception("No scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
730 elif self
.cur
.rowcount
>1:
731 raise db_base
.db_base_Exception("More than one scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
732 scenario_uuid
= rows
[0]["uuid"]
733 scenario_name
= rows
[0]["name"]
736 cmd
= "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid
)
737 self
.logger
.debug(cmd
)
738 self
.cur
.execute(cmd
)
740 return scenario_uuid
+ " " + scenario_name
741 except (mdb
.Error
, AttributeError) as e
:
742 self
._format
_error
(e
, tries
, "delete", "instances running")
745 def new_instance_scenario_as_a_whole(self
,tenant_id
,instance_scenario_name
,instance_scenario_description
,scenarioDict
):
748 created_time
= time
.time()
751 self
.cur
= self
.con
.cursor()
753 datacenter_id
= scenarioDict
['datacenter_id']
754 INSERT_
={'tenant_id': tenant_id
,
755 'datacenter_tenant_id': scenarioDict
["datacenter2tenant"][datacenter_id
],
756 'name': instance_scenario_name
,
757 'description': instance_scenario_description
,
758 'scenario_id' : scenarioDict
['uuid'],
759 'datacenter_id': datacenter_id
761 if scenarioDict
.get("cloud-config"):
762 INSERT_
["cloud_config"] = yaml
.safe_dump(scenarioDict
["cloud-config"], default_flow_style
=True, width
=256)
764 instance_uuid
= self
._new
_row
_internal
('instance_scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
766 net_scene2instance
={}
767 #instance_nets #nets interVNF
768 for net
in scenarioDict
['nets']:
769 net_scene2instance
[ net
['uuid'] ] ={}
770 datacenter_site_id
= net
.get('datacenter_id', datacenter_id
)
771 if not "vim_id_sites" in net
:
772 net
["vim_id_sites"] ={datacenter_site_id
: net
['vim_id']}
773 net
["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id
: net
['vim_id']}
774 sce_net_id
= net
.get("uuid")
776 for datacenter_site_id
,vim_id
in net
["vim_id_sites"].iteritems():
777 INSERT_
={'vim_net_id': vim_id
, 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
778 INSERT_
['datacenter_id'] = datacenter_site_id
779 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
781 INSERT_
['sce_net_id'] = sce_net_id
782 created_time
+= 0.00001
783 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
784 net_scene2instance
[ sce_net_id
][datacenter_site_id
] = instance_net_uuid
785 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
787 if 'ip_profile' in net
:
788 net
['ip_profile']['net_id'] = None
789 net
['ip_profile']['sce_net_id'] = None
790 net
['ip_profile']['instance_net_id'] = instance_net_uuid
791 created_time
+= 0.00001
792 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
795 for vnf
in scenarioDict
['vnfs']:
796 datacenter_site_id
= vnf
.get('datacenter_id', datacenter_id
)
797 INSERT_
={'instance_scenario_id': instance_uuid
, 'vnf_id': vnf
['vnf_id'] }
798 INSERT_
['datacenter_id'] = datacenter_site_id
799 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
801 INSERT_
['sce_vnf_id'] = vnf
['uuid']
802 created_time
+= 0.00001
803 instance_vnf_uuid
= self
._new
_row
_internal
('instance_vnfs', INSERT_
, True, instance_uuid
, created_time
)
804 vnf
['uuid'] = instance_vnf_uuid
#overwrite scnario uuid by instance uuid
806 #instance_nets #nets intraVNF
807 for net
in vnf
['nets']:
808 net_scene2instance
[ net
['uuid'] ] = {}
809 INSERT_
={'vim_net_id': net
['vim_id'], 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
810 INSERT_
['datacenter_id'] = net
.get('datacenter_id', datacenter_site_id
)
811 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_id
]
813 INSERT_
['net_id'] = net
['uuid']
814 created_time
+= 0.00001
815 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
816 net_scene2instance
[ net
['uuid'] ][datacenter_site_id
] = instance_net_uuid
817 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
819 if 'ip_profile' in net
:
820 net
['ip_profile']['net_id'] = None
821 net
['ip_profile']['sce_net_id'] = None
822 net
['ip_profile']['instance_net_id'] = instance_net_uuid
823 created_time
+= 0.00001
824 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
827 for vm
in vnf
['vms']:
828 INSERT_
={'instance_vnf_id': instance_vnf_uuid
, 'vm_id': vm
['uuid'], 'vim_vm_id': vm
['vim_id'] }
829 created_time
+= 0.00001
830 instance_vm_uuid
= self
._new
_row
_internal
('instance_vms', INSERT_
, True, instance_uuid
, created_time
)
831 vm
['uuid'] = instance_vm_uuid
#overwrite scnario uuid by instance uuid
834 for interface
in vm
['interfaces']:
835 net_id
= interface
.get('net_id', None)
837 #check if is connected to a inter VNFs net
838 for iface
in vnf
['interfaces']:
839 if iface
['interface_id'] == interface
['uuid']:
840 if 'ip_address' in iface
:
841 interface
['ip_address'] = iface
['ip_address']
842 net_id
= iface
.get('sce_net_id', None)
846 interface_type
='external' if interface
['external_name'] is not None else 'internal'
847 INSERT_
={'instance_vm_id': instance_vm_uuid
, 'instance_net_id': net_scene2instance
[net_id
][datacenter_site_id
],
848 'interface_id': interface
['uuid'], 'vim_interface_id': interface
.get('vim_id'), 'type': interface_type
,
849 'ip_address': interface
.get('ip_address') }
850 #created_time += 0.00001
851 interface_uuid
= self
._new
_row
_internal
('instance_interfaces', INSERT_
, True, instance_uuid
) #, created_time)
852 interface
['uuid'] = interface_uuid
#overwrite scnario uuid by instance uuid
854 except (mdb
.Error
, AttributeError) as e
:
855 self
._format
_error
(e
, tries
)
858 def get_instance_scenario(self
, instance_id
, tenant_id
=None, verbose
=False):
859 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
860 instance_id is the uuid or the name if it is not a valid uuid format
861 Only one instance must mutch the filtering or an error is returned
867 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
870 if tenant_id
is not None: where_list
.append( "inst.tenant_id='" + tenant_id
+"'" )
871 if db_base
._check
_valid
_uuid
(instance_id
):
872 where_list
.append( "inst.uuid='" + instance_id
+"'" )
874 where_list
.append( "inst.name='" + instance_id
+"'" )
875 where_text
= " AND ".join(where_list
)
876 cmd
= "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
877 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
878 " ,inst.description as description,inst.created_at as created_at" +\
879 " ,inst.cloud_config as 'cloud_config'" +\
880 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
881 " WHERE " + where_text
882 self
.logger
.debug(cmd
)
883 self
.cur
.execute(cmd
)
884 rows
= self
.cur
.fetchall()
886 if self
.cur
.rowcount
==0:
887 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Not_Found
)
888 elif self
.cur
.rowcount
>1:
889 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
890 instance_dict
= rows
[0]
891 if instance_dict
["cloud_config"]:
892 instance_dict
["cloud-config"] = yaml
.load(instance_dict
["cloud_config"])
893 del instance_dict
["cloud_config"]
896 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"\
897 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
898 " WHERE iv.instance_scenario_id='{}'" \
899 " ORDER BY iv.created_at ".format(instance_dict
['uuid'])
900 self
.logger
.debug(cmd
)
901 self
.cur
.execute(cmd
)
902 instance_dict
['vnfs'] = self
.cur
.fetchall()
903 for vnf
in instance_dict
['vnfs']:
904 vnf_manage_iface_list
=[]
906 cmd
= "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
907 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
908 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf
['uuid'])
909 self
.logger
.debug(cmd
)
910 self
.cur
.execute(cmd
)
911 vnf
['vms'] = self
.cur
.fetchall()
912 for vm
in vnf
['vms']:
913 vm_manage_iface_list
=[]
915 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 "\
916 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid "\
917 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm
['uuid'])
918 self
.logger
.debug(cmd
)
919 self
.cur
.execute(cmd
)
920 vm
['interfaces'] = self
.cur
.fetchall()
921 for iface
in vm
['interfaces']:
922 if iface
["type"] == "mgmt" and iface
["ip_address"]:
923 vnf_manage_iface_list
.append(iface
["ip_address"])
924 vm_manage_iface_list
.append(iface
["ip_address"])
927 if vm_manage_iface_list
: vm
["ip_address"] = ",".join(vm_manage_iface_list
)
928 if vnf_manage_iface_list
: vnf
["ip_address"] = ",".join(vnf_manage_iface_list
)
931 #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"
932 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
933 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
934 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
935 cmd
= "SELECT uuid,vim_net_id,status,error_msg,vim_info,created, sce_net_id, net_id as vnf_net_id, datacenter_id, datacenter_tenant_id"\
936 " FROM instance_nets" \
937 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
938 self
.logger
.debug(cmd
)
939 self
.cur
.execute(cmd
)
940 instance_dict
['nets'] = self
.cur
.fetchall()
942 db_base
._convert
_datetime
2str
(instance_dict
)
943 db_base
._convert
_str
2boolean
(instance_dict
, ('public','shared','created') )
945 except (mdb
.Error
, AttributeError) as e
:
946 self
._format
_error
(e
, tries
)
949 def delete_instance_scenario(self
, instance_id
, tenant_id
=None):
950 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
951 instance_id is the uuid or the name if it is not a valid uuid format
952 Only one instance_scenario must mutch the filtering or an error is returned
958 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
962 if tenant_id
is not None: where_list
.append( "tenant_id='" + tenant_id
+"'" )
963 if db_base
._check
_valid
_uuid
(instance_id
):
964 where_list
.append( "uuid='" + instance_id
+"'" )
966 where_list
.append( "name='" + instance_id
+"'" )
967 where_text
= " AND ".join(where_list
)
968 cmd
= "SELECT * FROM instance_scenarios WHERE "+ where_text
969 self
.logger
.debug(cmd
)
970 self
.cur
.execute(cmd
)
971 rows
= self
.cur
.fetchall()
973 if self
.cur
.rowcount
==0:
974 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
975 elif self
.cur
.rowcount
>1:
976 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
977 instance_uuid
= rows
[0]["uuid"]
978 instance_name
= rows
[0]["name"]
981 cmd
= "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid
)
982 self
.logger
.debug(cmd
)
983 self
.cur
.execute(cmd
)
985 return instance_uuid
+ " " + instance_name
986 except (mdb
.Error
, AttributeError) as e
:
987 self
._format
_error
(e
, tries
, "delete", "No dependences can avoid deleting!!!!")
990 def new_instance_scenario(self
, instance_scenario_dict
, tenant_id
):
991 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
992 return self
._new
_row
_internal
('instance_scenarios', instance_scenario_dict
, tenant_id
, add_uuid
=True, root_uuid
=None, log
=True)
994 def update_instance_scenario(self
, instance_scenario_dict
):
998 def new_instance_vnf(self
, instance_vnf_dict
, tenant_id
, instance_scenario_id
= None):
999 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1000 return self
._new
_row
_internal
('instance_vnfs', instance_vnf_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1002 def update_instance_vnf(self
, instance_vnf_dict
):
1006 def delete_instance_vnf(self
, instance_vnf_id
):
1010 def new_instance_vm(self
, instance_vm_dict
, tenant_id
, instance_scenario_id
= None):
1011 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1012 return self
._new
_row
_internal
('instance_vms', instance_vm_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1014 def update_instance_vm(self
, instance_vm_dict
):
1018 def delete_instance_vm(self
, instance_vm_id
):
1022 def new_instance_net(self
, instance_net_dict
, tenant_id
, instance_scenario_id
= None):
1023 return self
._new
_row
_internal
('instance_nets', instance_net_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1025 def update_instance_net(self
, instance_net_dict
):
1029 def delete_instance_net(self
, instance_net_id
):
1033 def new_instance_interface(self
, instance_interface_dict
, tenant_id
, instance_scenario_id
= None):
1034 return self
._new
_row
_internal
('instance_interfaces', instance_interface_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1036 def update_instance_interface(self
, instance_interface_dict
):
1040 def delete_instance_interface(self
, instance_interface_dict
):
1044 def update_datacenter_nets(self
, datacenter_id
, new_net_list
=[]):
1045 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1047 datacenter_id: uuid of the datacenter to act upon
1048 table: table where to insert
1049 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1050 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1054 created_time
= time
.time()
1057 self
.cur
= self
.con
.cursor()
1058 cmd
="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id
)
1059 self
.logger
.debug(cmd
)
1060 self
.cur
.execute(cmd
)
1061 deleted
= self
.cur
.rowcount
1063 for new_net
in new_net_list
:
1064 created_time
+= 0.00001
1065 self
._new
_row
_internal
('datacenter_nets', new_net
, add_uuid
=True, created_time
=created_time
)
1067 return inserted
, deleted
1068 except (mdb
.Error
, AttributeError) as e
:
1069 self
._format
_error
(e
, tries
)