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 bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
79 bridgeInterfacesDict
= {}
80 for vm
in vnf_descriptor
['vnf']['VNFC']:
81 if 'bridge-ifaces' in vm
:
82 bridgeInterfacesDict
[vm
['name']] = {}
83 for bridgeiface
in vm
['bridge-ifaces']:
84 created_time
+= 0.00001
85 if 'port-security' in bridgeiface
:
86 bridgeiface
['port_security'] = bridgeiface
.pop('port-security')
87 if 'floating-ip' in bridgeiface
:
88 bridgeiface
['floating_ip'] = bridgeiface
.pop('floating-ip')
89 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
90 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = {}
91 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['vpci'] = bridgeiface
.get('vpci',None)
92 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['mac'] = bridgeiface
.get('mac_address',None)
93 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['bw'] = bridgeiface
.get('bandwidth', None)
94 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['model'] = bridgeiface
.get('model', None)
95 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['port_security'] = \
96 int(bridgeiface
.get('port_security', True))
97 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['floating_ip'] = \
98 int(bridgeiface
.get('floating_ip', False))
99 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['created_time'] = created_time
101 # Collect the data interfaces of each VM/VNFC under the 'numas' field
103 for vm
in vnf_descriptor
['vnf']['VNFC']:
104 dataifacesDict
[vm
['name']] = {}
105 for numa
in vm
.get('numas', []):
106 for dataiface
in numa
.get('interfaces', []):
107 created_time
+= 0.00001
108 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
109 dataifacesDict
[vm
['name']][dataiface
['name']] = {}
110 dataifacesDict
[vm
['name']][dataiface
['name']]['vpci'] = dataiface
['vpci']
111 dataifacesDict
[vm
['name']][dataiface
['name']]['bw'] = dataiface
['bandwidth']
112 dataifacesDict
[vm
['name']][dataiface
['name']]['model'] = "PF" if dataiface
[
113 'dedicated'] == "yes" else (
114 "VF" if dataiface
['dedicated'] == "no" else "VFnotShared")
115 dataifacesDict
[vm
['name']][dataiface
['name']]['created_time'] = created_time
117 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
118 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
119 internalconnList
= []
120 if 'internal-connections' in vnf_descriptor
['vnf']:
121 for net
in vnf_descriptor
['vnf']['internal-connections']:
122 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
125 myNetDict
["name"] = net
['name']
126 myNetDict
["description"] = net
['description']
127 myNetDict
["type"] = net
['type']
128 myNetDict
["vnf_id"] = vnf_id
130 created_time
+= 0.00001
131 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
133 for element
in net
['elements']:
135 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
136 ifaceItem
["internal_name"] = element
['local_iface_name']
137 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
138 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
139 ifaceItem
["net_id"] = net_id
140 ifaceItem
["type"] = net
['type']
141 if ifaceItem
["type"] == "data":
142 dataiface
= dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
143 ifaceItem
["vpci"] = dataiface
['vpci']
144 ifaceItem
["bw"] = dataiface
['bw']
145 ifaceItem
["model"] = dataiface
['model']
146 created_time_iface
= dataiface
['created_time']
148 bridgeiface
= bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
149 ifaceItem
["vpci"] = bridgeiface
['vpci']
150 ifaceItem
["mac"] = bridgeiface
['mac']
151 ifaceItem
["bw"] = bridgeiface
['bw']
152 ifaceItem
["model"] = bridgeiface
['model']
153 ifaceItem
["port_security"] = bridgeiface
['port_security']
154 ifaceItem
["floating_ip"] = bridgeiface
['floating_ip']
155 created_time_iface
= bridgeiface
['created_time']
156 internalconnList
.append(ifaceItem
)
157 #print "Internal net id in NFVO DB: %s" % net_id
159 #print "Adding internal interfaces to the NFVO database (if any)"
160 for iface
in internalconnList
:
161 #print "Iface name: %s" % iface['internal_name']
162 iface_id
= self
._new
_row
_internal
('interfaces', iface
, add_uuid
=True, root_uuid
=vnf_id
, created_time
= created_time_iface
)
163 #print "Iface id in NFVO DB: %s" % iface_id
165 #print "Adding external interfaces to the NFVO database"
166 for iface
in vnf_descriptor
['vnf']['external-connections']:
168 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
169 myIfaceDict
["internal_name"] = iface
['local_iface_name']
170 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
171 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
172 myIfaceDict
["external_name"] = iface
['name']
173 myIfaceDict
["type"] = iface
['type']
174 if iface
["type"] == "data":
175 dataiface
= dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]
176 myIfaceDict
["vpci"] = dataiface
['vpci']
177 myIfaceDict
["bw"] = dataiface
['bw']
178 myIfaceDict
["model"] = dataiface
['model']
179 created_time_iface
= dataiface
['created_time']
181 bridgeiface
= bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]
182 myIfaceDict
["vpci"] = bridgeiface
['vpci']
183 myIfaceDict
["bw"] = bridgeiface
['bw']
184 myIfaceDict
["model"] = bridgeiface
['model']
185 myIfaceDict
["mac"] = bridgeiface
['mac']
186 myIfaceDict
["port_security"]= bridgeiface
['port_security']
187 myIfaceDict
["floating_ip"] = bridgeiface
['floating_ip']
188 created_time_iface
= bridgeiface
['created_time']
189 #print "Iface name: %s" % iface['name']
190 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
= created_time_iface
)
191 #print "Iface id in NFVO DB: %s" % iface_id
195 except (mdb
.Error
, AttributeError) as e
:
196 self
._format
_error
(e
, tries
)
199 def new_vnf_as_a_whole2(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
200 self
.logger
.debug("Adding new vnf to the NFVO database")
203 created_time
= time
.time()
208 myVNFDict
["name"] = vnf_name
209 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
210 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
211 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
212 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
213 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
215 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
216 #print "Adding new vms to the NFVO database"
217 #For each vm, we must create the appropriate vm in the NFVO database.
219 for _
,vm
in VNFCDict
.iteritems():
220 #This code could make the name of the vms grow and grow.
221 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
222 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
223 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
224 vm
["vnf_id"] = vnf_id
225 created_time
+= 0.00001
226 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
227 #print "Internal vm id in NFVO DB: %s" % vm_id
228 vmDict
[vm
['name']] = vm_id
230 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
231 bridgeInterfacesDict
= {}
232 for vm
in vnf_descriptor
['vnf']['VNFC']:
233 if 'bridge-ifaces' in vm
:
234 bridgeInterfacesDict
[vm
['name']] = {}
235 for bridgeiface
in vm
['bridge-ifaces']:
236 created_time
+= 0.00001
237 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
238 if 'port-security' in bridgeiface
:
239 bridgeiface
['port_security'] = bridgeiface
.pop('port-security')
240 if 'floating-ip' in bridgeiface
:
241 bridgeiface
['floating_ip'] = bridgeiface
.pop('floating-ip')
243 ifaceDict
['vpci'] = bridgeiface
.get('vpci',None)
244 ifaceDict
['mac'] = bridgeiface
.get('mac_address',None)
245 ifaceDict
['bw'] = bridgeiface
.get('bandwidth', None)
246 ifaceDict
['model'] = bridgeiface
.get('model', None)
247 ifaceDict
['port_security'] = int(bridgeiface
.get('port_security', True))
248 ifaceDict
['floating_ip'] = int(bridgeiface
.get('floating_ip', False))
249 ifaceDict
['created_time'] = created_time
250 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = ifaceDict
252 # Collect the data interfaces of each VM/VNFC under the 'numas' field
254 for vm
in vnf_descriptor
['vnf']['VNFC']:
255 dataifacesDict
[vm
['name']] = {}
256 for numa
in vm
.get('numas', []):
257 for dataiface
in numa
.get('interfaces', []):
258 created_time
+= 0.00001
259 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
261 ifaceDict
['vpci'] = dataiface
['vpci']
262 ifaceDict
['bw'] = dataiface
['bandwidth']
263 ifaceDict
['model'] = "PF" if dataiface
['dedicated'] == "yes" else \
264 ("VF" if dataiface
['dedicated'] == "no" else "VFnotShared")
265 ifaceDict
['created_time'] = created_time
266 dataifacesDict
[vm
['name']][dataiface
['name']] = ifaceDict
268 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
269 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
270 if 'internal-connections' in vnf_descriptor
['vnf']:
271 for net
in vnf_descriptor
['vnf']['internal-connections']:
272 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
275 myNetDict
["name"] = net
['name']
276 myNetDict
["description"] = net
['description']
277 if (net
["implementation"] == "overlay"):
278 net
["type"] = "bridge"
279 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
280 elif (net
["implementation"] == "underlay"):
281 if (net
["type"] == "e-line"):
283 elif (net
["type"] == "e-lan"):
285 net
.pop("implementation")
286 myNetDict
["type"] = net
['type']
287 myNetDict
["vnf_id"] = vnf_id
289 created_time
+= 0.00001
290 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
292 if "ip-profile" in net
:
293 ip_profile
= net
["ip-profile"]
295 myIPProfileDict
["net_id"] = net_id
296 myIPProfileDict
["ip_version"] = ip_profile
.get('ip-version',"IPv4")
297 myIPProfileDict
["subnet_address"] = ip_profile
.get('subnet-address',None)
298 myIPProfileDict
["gateway_address"] = ip_profile
.get('gateway-address',None)
299 myIPProfileDict
["dns_address"] = ip_profile
.get('dns-address',None)
300 if ("dhcp" in ip_profile
):
301 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled',"true")
302 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address',None)
303 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count',None)
305 created_time
+= 0.00001
306 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
308 for element
in net
['elements']:
310 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
311 ifaceItem
["internal_name"] = element
['local_iface_name']
312 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
313 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
314 ifaceItem
["net_id"] = net_id
315 ifaceItem
["type"] = net
['type']
316 ifaceItem
["ip_address"] = element
.get('ip_address',None)
317 if ifaceItem
["type"] == "data":
318 ifaceDict
= dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
319 ifaceItem
["vpci"] = ifaceDict
['vpci']
320 ifaceItem
["bw"] = ifaceDict
['bw']
321 ifaceItem
["model"] = ifaceDict
['model']
323 ifaceDict
= bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
324 ifaceItem
["vpci"] = ifaceDict
['vpci']
325 ifaceItem
["mac"] = ifaceDict
['mac']
326 ifaceItem
["bw"] = ifaceDict
['bw']
327 ifaceItem
["model"] = ifaceDict
['model']
328 ifaceItem
["port_security"] = ifaceDict
['port_security']
329 ifaceItem
["floating_ip"] = ifaceDict
['floating_ip']
330 created_time_iface
= ifaceDict
["created_time"]
331 #print "Iface name: %s" % iface['internal_name']
332 iface_id
= self
._new
_row
_internal
('interfaces', ifaceItem
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time_iface
)
333 #print "Iface id in NFVO DB: %s" % iface_id
335 #print "Adding external interfaces to the NFVO database"
336 for iface
in vnf_descriptor
['vnf']['external-connections']:
338 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
339 myIfaceDict
["internal_name"] = iface
['local_iface_name']
340 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
341 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
342 myIfaceDict
["external_name"] = iface
['name']
343 myIfaceDict
["type"] = iface
['type']
344 if iface
["type"] == "data":
345 myIfaceDict
["vpci"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
346 myIfaceDict
["bw"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
347 myIfaceDict
["model"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
348 created_time_iface
= dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['created_time']
350 myIfaceDict
["vpci"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
351 myIfaceDict
["bw"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
352 myIfaceDict
["model"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
353 myIfaceDict
["mac"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['mac']
354 myIfaceDict
["port_security"] = \
355 bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['port_security']
356 myIfaceDict
["floating_ip"] = \
357 bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['floating_ip']
358 created_time_iface
= bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['created_time']
359 #print "Iface name: %s" % iface['name']
360 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time_iface
)
361 #print "Iface id in NFVO DB: %s" % iface_id
365 except (mdb
.Error
, AttributeError) as e
:
366 self
._format
_error
(e
, tries
)
367 # except KeyError as e2:
368 # exc_type, exc_obj, exc_tb = sys.exc_info()
369 # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
370 # self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
374 def new_scenario(self
, scenario_dict
):
377 created_time
= time
.time()
380 self
.cur
= self
.con
.cursor()
381 tenant_id
= scenario_dict
.get('tenant_id')
383 INSERT_
={'tenant_id': tenant_id
,
384 'name': scenario_dict
['name'],
385 'description': scenario_dict
['description'],
386 'public': scenario_dict
.get('public', "false")}
388 scenario_uuid
= self
._new
_row
_internal
('scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
390 for net
in scenario_dict
['nets'].values():
391 net_dict
={'scenario_id': scenario_uuid
}
392 net_dict
["name"] = net
["name"]
393 net_dict
["type"] = net
["type"]
394 net_dict
["description"] = net
.get("description")
395 net_dict
["external"] = net
.get("external", False)
397 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
398 #TODO, must be json because of the GUI, change to yaml
399 net_dict
["graph"]=json
.dumps(net
["graph"])
400 created_time
+= 0.00001
401 net_uuid
= self
._new
_row
_internal
('sce_nets', net_dict
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
404 if net
.get("ip-profile"):
405 ip_profile
= net
["ip-profile"]
407 "sce_net_id": net_uuid
,
408 "ip_version": ip_profile
.get('ip-version', "IPv4"),
409 "subnet_address": ip_profile
.get('subnet-address'),
410 "gateway_address": ip_profile
.get('gateway-address'),
411 "dns_address": ip_profile
.get('dns-address')}
412 if "dhcp" in ip_profile
:
413 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled', "true")
414 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address')
415 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count')
416 self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
419 for k
, vnf
in scenario_dict
['vnfs'].items():
420 INSERT_
= {'scenario_id': scenario_uuid
,
422 'vnf_id': vnf
['uuid'],
423 # 'description': scenario_dict['name']
424 'description': vnf
['description']}
426 #I NSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
427 # TODO, must be json because of the GUI, change to yaml
428 INSERT_
["graph"] = json
.dumps(vnf
["graph"])
429 created_time
+= 0.00001
430 scn_vnf_uuid
= self
._new
_row
_internal
('sce_vnfs', INSERT_
, add_uuid
=True,
431 root_uuid
=scenario_uuid
, created_time
=created_time
)
432 vnf
['scn_vnf_uuid']=scn_vnf_uuid
434 for iface
in vnf
['ifaces'].values():
435 # print 'iface', iface
436 if 'net_key' not in iface
:
438 iface
['net_id'] = scenario_dict
['nets'][ iface
['net_key'] ]['uuid']
439 INSERT_
={'sce_vnf_id': scn_vnf_uuid
,
440 'sce_net_id': iface
['net_id'],
441 'interface_id': iface
['uuid'],
442 'ip_address': iface
.get('ip_address')}
443 created_time
+= 0.00001
444 iface_uuid
= self
._new
_row
_internal
('sce_interfaces', INSERT_
, add_uuid
=True,
445 root_uuid
=scenario_uuid
, created_time
=created_time
)
449 except (mdb
.Error
, AttributeError) as e
:
450 self
._format
_error
(e
, tries
)
453 def edit_scenario(self
, scenario_dict
):
456 modified_time
= time
.time()
460 self
.cur
= self
.con
.cursor()
461 #check that scenario exist
462 tenant_id
= scenario_dict
.get('tenant_id')
463 scenario_uuid
= scenario_dict
['uuid']
465 where_text
= "uuid='{}'".format(scenario_uuid
)
466 if not tenant_id
and tenant_id
!= "any":
467 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
468 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
469 self
.logger
.debug(cmd
)
470 self
.cur
.execute(cmd
)
472 if self
.cur
.rowcount
==0:
473 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
474 elif self
.cur
.rowcount
>1:
475 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
479 topology
= scenario_dict
.pop("topology", None)
480 if topology
!= None and "nodes" in topology
:
481 nodes
= topology
.get("nodes",{})
483 if "name" in scenario_dict
: UPDATE_
["name"] = scenario_dict
["name"]
484 if "description" in scenario_dict
: UPDATE_
["description"] = scenario_dict
["description"]
486 WHERE_
={'tenant_id': tenant_id
, 'uuid': scenario_uuid
}
487 item_changed
+= self
._update
_rows
('scenarios', UPDATE_
, WHERE_
, modified_time
=modified_time
)
489 for node_id
, node
in nodes
.items():
491 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
492 #TODO, must be json because of the GUI, change to yaml
493 node
["graph"] = json
.dumps(node
["graph"])
494 WHERE_
={'scenario_id': scenario_uuid
, 'uuid': node_id
}
495 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
496 item_changed
+= self
._update
_rows
('sce_nets', node
, WHERE_
)
497 item_changed
+= self
._update
_rows
('sce_vnfs', node
, WHERE_
, modified_time
=modified_time
)
500 except (mdb
.Error
, AttributeError) as e
:
501 self
._format
_error
(e
, tries
)
504 # def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
505 # '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
506 # instance_scenario_id is the uuid or the name if it is not a valid uuid format
507 # Only one scenario isntance must mutch the filtering or an error is returned
509 # print "1******************************************************************"
512 # self.cur = self.con.cursor(mdb.cursors.DictCursor)
515 # if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
516 # if db_base._check_valid_uuid(instance_scenario_id):
517 # where_list.append( "uuid='" + instance_scenario_id +"'" )
519 # where_list.append( "name='" + instance_scenario_id +"'" )
520 # where_text = " AND ".join(where_list)
521 # self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
522 # rows = self.cur.fetchall()
523 # if self.cur.rowcount==0:
524 # return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
525 # elif self.cur.rowcount>1:
526 # return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
527 # instance_scenario_dict = rows[0]
530 # self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
531 # instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
532 # for vnf in instance_scenario_dict['instance_vnfs']:
534 # self.cur.execute("SELECT uuid, vim_vm_id "+
535 # "FROM instance_vms "+
536 # "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
538 # vnf['instance_vms'] = self.cur.fetchall()
540 # self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
541 # instance_scenario_dict['instance_nets'] = self.cur.fetchall()
543 # #instance_interfaces
544 # 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'] + "'")
545 # instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
547 # db_base._convert_datetime2str(instance_scenario_dict)
548 # db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
549 # print "2******************************************************************"
550 # return 1, instance_scenario_dict
551 # except (mdb.Error, AttributeError) as e:
552 # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
553 # return self._format_error(e)
555 def get_scenario(self
, scenario_id
, tenant_id
=None, datacenter_id
=None):
556 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
557 scenario_id is the uuid or the name if it is not a valid uuid format
558 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
559 Only one scenario must mutch the filtering or an error is returned
565 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
566 where_text
= "uuid='{}'".format(scenario_id
)
567 if not tenant_id
and tenant_id
!= "any":
568 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
569 cmd
= "SELECT * FROM scenarios WHERE " + where_text
570 self
.logger
.debug(cmd
)
571 self
.cur
.execute(cmd
)
572 rows
= self
.cur
.fetchall()
573 if self
.cur
.rowcount
==0:
574 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
575 elif self
.cur
.rowcount
>1:
576 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
577 scenario_dict
= rows
[0]
578 if scenario_dict
["cloud_config"]:
579 scenario_dict
["cloud-config"] = yaml
.load(scenario_dict
["cloud_config"])
580 del scenario_dict
["cloud_config"]
582 cmd
= "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict
['uuid'])
583 self
.logger
.debug(cmd
)
584 self
.cur
.execute(cmd
)
585 scenario_dict
['vnfs'] = self
.cur
.fetchall()
586 for vnf
in scenario_dict
['vnfs']:
588 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'])
589 self
.logger
.debug(cmd
)
590 self
.cur
.execute(cmd
)
591 vnf
['interfaces'] = self
.cur
.fetchall()
593 cmd
= "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name, vms.description as description, vms.boot_data as boot_data " \
594 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id " \
595 " WHERE vnfs.uuid='" + vnf
['vnf_id'] +"'" \
596 " ORDER BY vms.created_at"
597 self
.logger
.debug(cmd
)
598 self
.cur
.execute(cmd
)
599 vnf
['vms'] = self
.cur
.fetchall()
600 for vm
in vnf
['vms']:
602 vm
["boot_data"] = yaml
.safe_load(vm
["boot_data"])
605 if datacenter_id
!=None:
606 cmd
= "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm
['image_id'],datacenter_id
)
607 self
.logger
.debug(cmd
)
608 self
.cur
.execute(cmd
)
609 if self
.cur
.rowcount
==1:
610 vim_image_dict
= self
.cur
.fetchone()
611 vm
['vim_image_id']=vim_image_dict
['vim_id']
612 cmd
= "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm
['flavor_id'],datacenter_id
)
613 self
.logger
.debug(cmd
)
614 self
.cur
.execute(cmd
)
615 if self
.cur
.rowcount
==1:
616 vim_flavor_dict
= self
.cur
.fetchone()
617 vm
['vim_flavor_id']=vim_flavor_dict
['vim_id']
620 cmd
= "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
621 "floating_ip, port_security" \
623 " WHERE vm_id='{}'" \
624 " ORDER BY created_at".format(vm
['uuid'])
625 self
.logger
.debug(cmd
)
626 self
.cur
.execute(cmd
)
627 vm
['interfaces'] = self
.cur
.fetchall()
628 for index
in range(0,len(vm
['interfaces'])):
629 vm
['interfaces'][index
]['port-security'] = vm
['interfaces'][index
].pop("port_security")
630 vm
['interfaces'][index
]['floating-ip'] = vm
['interfaces'][index
].pop("floating_ip")
631 #nets every net of a vms
632 cmd
= "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf
['vnf_id'])
633 self
.logger
.debug(cmd
)
634 self
.cur
.execute(cmd
)
635 vnf
['nets'] = self
.cur
.fetchall()
636 for vnf_net
in vnf
['nets']:
637 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
638 cmd
= "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_
,vnf_net
['uuid'])
639 self
.logger
.debug(cmd
)
640 self
.cur
.execute(cmd
)
641 ipprofiles
= self
.cur
.fetchall()
642 if self
.cur
.rowcount
==1:
643 vnf_net
["ip_profile"] = ipprofiles
[0]
644 elif self
.cur
.rowcount
>1:
645 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
)
648 cmd
= "SELECT uuid,name,type,external,description" \
649 " FROM sce_nets WHERE scenario_id='{}'" \
650 " ORDER BY created_at ".format(scenario_dict
['uuid'])
651 self
.logger
.debug(cmd
)
652 self
.cur
.execute(cmd
)
653 scenario_dict
['nets'] = self
.cur
.fetchall()
655 for net
in scenario_dict
['nets']:
656 if str(net
['external']) == 'false':
657 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
658 cmd
= "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_
,net
['uuid'])
659 self
.logger
.debug(cmd
)
660 self
.cur
.execute(cmd
)
661 ipprofiles
= self
.cur
.fetchall()
662 if self
.cur
.rowcount
==1:
663 net
["ip_profile"] = ipprofiles
[0]
664 elif self
.cur
.rowcount
>1:
665 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
)
667 WHERE_
=" WHERE name='{}'".format(net
['name'])
668 if datacenter_id
!=None:
669 WHERE_
+= " AND datacenter_id='{}'".format(datacenter_id
)
670 cmd
= "SELECT vim_net_id FROM datacenter_nets" + WHERE_
671 self
.logger
.debug(cmd
)
672 self
.cur
.execute(cmd
)
673 d_net
= self
.cur
.fetchone()
674 if d_net
==None or datacenter_id
==None:
675 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
678 net
['vim_id']=d_net
['vim_net_id']
680 db_base
._convert
_datetime
2str
(scenario_dict
)
681 db_base
._convert
_str
2boolean
(scenario_dict
, ('public','shared','external','port-security','floating-ip') )
683 except (mdb
.Error
, AttributeError) as e
:
684 self
._format
_error
(e
, tries
)
687 def delete_scenario(self
, scenario_id
, tenant_id
=None):
688 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
689 scenario_id is the uuid or the name if it is not a valid uuid format
690 Only one scenario must mutch the filtering or an error is returned
696 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
699 where_text
= "uuid='{}'".format(scenario_id
)
700 if not tenant_id
and tenant_id
!= "any":
701 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
702 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
703 self
.logger
.debug(cmd
)
704 self
.cur
.execute(cmd
)
705 rows
= self
.cur
.fetchall()
706 if self
.cur
.rowcount
==0:
707 raise db_base
.db_base_Exception("No scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
708 elif self
.cur
.rowcount
>1:
709 raise db_base
.db_base_Exception("More than one scenario found where " + where_text
, db_base
.HTTP_Bad_Request
)
710 scenario_uuid
= rows
[0]["uuid"]
711 scenario_name
= rows
[0]["name"]
714 cmd
= "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid
)
715 self
.logger
.debug(cmd
)
716 self
.cur
.execute(cmd
)
718 return scenario_uuid
+ " " + scenario_name
719 except (mdb
.Error
, AttributeError) as e
:
720 self
._format
_error
(e
, tries
, "delete", "instances running")
723 def new_instance_scenario_as_a_whole(self
,tenant_id
,instance_scenario_name
,instance_scenario_description
,scenarioDict
):
726 created_time
= time
.time()
729 self
.cur
= self
.con
.cursor()
731 datacenter_id
= scenarioDict
['datacenter_id']
732 INSERT_
={'tenant_id': tenant_id
,
733 'datacenter_tenant_id': scenarioDict
["datacenter2tenant"][datacenter_id
],
734 'name': instance_scenario_name
,
735 'description': instance_scenario_description
,
736 'scenario_id' : scenarioDict
['uuid'],
737 'datacenter_id': datacenter_id
739 if scenarioDict
.get("cloud-config"):
740 INSERT_
["cloud_config"] = yaml
.safe_dump(scenarioDict
["cloud-config"], default_flow_style
=True, width
=256)
742 instance_uuid
= self
._new
_row
_internal
('instance_scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
744 net_scene2instance
={}
745 #instance_nets #nets interVNF
746 for net
in scenarioDict
['nets']:
747 net_scene2instance
[ net
['uuid'] ] ={}
748 datacenter_site_id
= net
.get('datacenter_id', datacenter_id
)
749 if not "vim_id_sites" in net
:
750 net
["vim_id_sites"] ={datacenter_site_id
: net
['vim_id']}
751 net
["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id
: net
['vim_id']}
752 sce_net_id
= net
.get("uuid")
754 for datacenter_site_id
,vim_id
in net
["vim_id_sites"].iteritems():
755 INSERT_
={'vim_net_id': vim_id
, 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
756 INSERT_
['datacenter_id'] = datacenter_site_id
757 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
759 INSERT_
['sce_net_id'] = sce_net_id
760 created_time
+= 0.00001
761 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
762 net_scene2instance
[ sce_net_id
][datacenter_site_id
] = instance_net_uuid
763 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
765 if 'ip_profile' in net
:
766 net
['ip_profile']['net_id'] = None
767 net
['ip_profile']['sce_net_id'] = None
768 net
['ip_profile']['instance_net_id'] = instance_net_uuid
769 created_time
+= 0.00001
770 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
773 for vnf
in scenarioDict
['vnfs']:
774 datacenter_site_id
= vnf
.get('datacenter_id', datacenter_id
)
775 INSERT_
={'instance_scenario_id': instance_uuid
, 'vnf_id': vnf
['vnf_id'] }
776 INSERT_
['datacenter_id'] = datacenter_site_id
777 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
779 INSERT_
['sce_vnf_id'] = vnf
['uuid']
780 created_time
+= 0.00001
781 instance_vnf_uuid
= self
._new
_row
_internal
('instance_vnfs', INSERT_
, True, instance_uuid
, created_time
)
782 vnf
['uuid'] = instance_vnf_uuid
#overwrite scnario uuid by instance uuid
784 #instance_nets #nets intraVNF
785 for net
in vnf
['nets']:
786 net_scene2instance
[ net
['uuid'] ] = {}
787 INSERT_
={'vim_net_id': net
['vim_id'], 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
788 INSERT_
['datacenter_id'] = net
.get('datacenter_id', datacenter_site_id
)
789 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_id
]
791 INSERT_
['net_id'] = net
['uuid']
792 created_time
+= 0.00001
793 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
794 net_scene2instance
[ net
['uuid'] ][datacenter_site_id
] = instance_net_uuid
795 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
797 if 'ip_profile' in net
:
798 net
['ip_profile']['net_id'] = None
799 net
['ip_profile']['sce_net_id'] = None
800 net
['ip_profile']['instance_net_id'] = instance_net_uuid
801 created_time
+= 0.00001
802 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
805 for vm
in vnf
['vms']:
806 INSERT_
={'instance_vnf_id': instance_vnf_uuid
, 'vm_id': vm
['uuid'], 'vim_vm_id': vm
['vim_id'] }
807 created_time
+= 0.00001
808 instance_vm_uuid
= self
._new
_row
_internal
('instance_vms', INSERT_
, True, instance_uuid
, created_time
)
809 vm
['uuid'] = instance_vm_uuid
#overwrite scnario uuid by instance uuid
812 for interface
in vm
['interfaces']:
813 net_id
= interface
.get('net_id', None)
815 #check if is connected to a inter VNFs net
816 for iface
in vnf
['interfaces']:
817 if iface
['interface_id'] == interface
['uuid']:
818 if 'ip_address' in iface
:
819 interface
['ip_address'] = iface
['ip_address']
820 net_id
= iface
.get('sce_net_id', None)
824 interface_type
='external' if interface
['external_name'] is not None else 'internal'
825 INSERT_
={'instance_vm_id': instance_vm_uuid
, 'instance_net_id': net_scene2instance
[net_id
][datacenter_site_id
],
826 'interface_id': interface
['uuid'], 'vim_interface_id': interface
.get('vim_id'), 'type': interface_type
,
827 'ip_address': interface
.get('ip_address'), 'floating_ip': int(interface
.get('floating-ip',False)),
828 'port_security': int(interface
.get('port-security',True))}
829 #created_time += 0.00001
830 interface_uuid
= self
._new
_row
_internal
('instance_interfaces', INSERT_
, True, instance_uuid
) #, created_time)
831 interface
['uuid'] = interface_uuid
#overwrite scnario uuid by instance uuid
833 except (mdb
.Error
, AttributeError) as e
:
834 self
._format
_error
(e
, tries
)
837 def get_instance_scenario(self
, instance_id
, tenant_id
=None, verbose
=False):
838 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
839 instance_id is the uuid or the name if it is not a valid uuid format
840 Only one instance must mutch the filtering or an error is returned
846 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
849 if tenant_id
is not None: where_list
.append( "inst.tenant_id='" + tenant_id
+"'" )
850 if db_base
._check
_valid
_uuid
(instance_id
):
851 where_list
.append( "inst.uuid='" + instance_id
+"'" )
853 where_list
.append( "inst.name='" + instance_id
+"'" )
854 where_text
= " AND ".join(where_list
)
855 cmd
= "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
856 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
857 " ,inst.description as description,inst.created_at as created_at" +\
858 " ,inst.cloud_config as 'cloud_config'" +\
859 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
860 " WHERE " + where_text
861 self
.logger
.debug(cmd
)
862 self
.cur
.execute(cmd
)
863 rows
= self
.cur
.fetchall()
865 if self
.cur
.rowcount
==0:
866 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Not_Found
)
867 elif self
.cur
.rowcount
>1:
868 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
869 instance_dict
= rows
[0]
870 if instance_dict
["cloud_config"]:
871 instance_dict
["cloud-config"] = yaml
.load(instance_dict
["cloud_config"])
872 del instance_dict
["cloud_config"]
875 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"\
876 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
877 " WHERE iv.instance_scenario_id='{}'" \
878 " ORDER BY iv.created_at ".format(instance_dict
['uuid'])
879 self
.logger
.debug(cmd
)
880 self
.cur
.execute(cmd
)
881 instance_dict
['vnfs'] = self
.cur
.fetchall()
882 for vnf
in instance_dict
['vnfs']:
883 vnf_manage_iface_list
=[]
885 cmd
= "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
886 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
887 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf
['uuid'])
888 self
.logger
.debug(cmd
)
889 self
.cur
.execute(cmd
)
890 vnf
['vms'] = self
.cur
.fetchall()
891 for vm
in vnf
['vms']:
892 vm_manage_iface_list
=[]
894 cmd
= "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
895 " ii.ip_address as ip_address, vim_info, i.type as type"\
896 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
897 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm
['uuid'])
898 self
.logger
.debug(cmd
)
899 self
.cur
.execute(cmd
)
900 vm
['interfaces'] = self
.cur
.fetchall()
901 for iface
in vm
['interfaces']:
902 if iface
["type"] == "mgmt" and iface
["ip_address"]:
903 vnf_manage_iface_list
.append(iface
["ip_address"])
904 vm_manage_iface_list
.append(iface
["ip_address"])
907 if vm_manage_iface_list
: vm
["ip_address"] = ",".join(vm_manage_iface_list
)
908 if vnf_manage_iface_list
: vnf
["ip_address"] = ",".join(vnf_manage_iface_list
)
911 #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"
912 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
913 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
914 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
915 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, sdn_net_id"\
916 " FROM instance_nets" \
917 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
918 self
.logger
.debug(cmd
)
919 self
.cur
.execute(cmd
)
920 instance_dict
['nets'] = self
.cur
.fetchall()
922 db_base
._convert
_datetime
2str
(instance_dict
)
923 db_base
._convert
_str
2boolean
(instance_dict
, ('public','shared','created') )
925 except (mdb
.Error
, AttributeError) as e
:
926 self
._format
_error
(e
, tries
)
929 def delete_instance_scenario(self
, instance_id
, tenant_id
=None):
930 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
931 instance_id is the uuid or the name if it is not a valid uuid format
932 Only one instance_scenario must mutch the filtering or an error is returned
938 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
942 if tenant_id
is not None: where_list
.append( "tenant_id='" + tenant_id
+"'" )
943 if db_base
._check
_valid
_uuid
(instance_id
):
944 where_list
.append( "uuid='" + instance_id
+"'" )
946 where_list
.append( "name='" + instance_id
+"'" )
947 where_text
= " AND ".join(where_list
)
948 cmd
= "SELECT * FROM instance_scenarios WHERE "+ where_text
949 self
.logger
.debug(cmd
)
950 self
.cur
.execute(cmd
)
951 rows
= self
.cur
.fetchall()
953 if self
.cur
.rowcount
==0:
954 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
955 elif self
.cur
.rowcount
>1:
956 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
957 instance_uuid
= rows
[0]["uuid"]
958 instance_name
= rows
[0]["name"]
961 cmd
= "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid
)
962 self
.logger
.debug(cmd
)
963 self
.cur
.execute(cmd
)
965 return instance_uuid
+ " " + instance_name
966 except (mdb
.Error
, AttributeError) as e
:
967 self
._format
_error
(e
, tries
, "delete", "No dependences can avoid deleting!!!!")
970 def new_instance_scenario(self
, instance_scenario_dict
, tenant_id
):
971 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
972 return self
._new
_row
_internal
('instance_scenarios', instance_scenario_dict
, tenant_id
, add_uuid
=True, root_uuid
=None, log
=True)
974 def update_instance_scenario(self
, instance_scenario_dict
):
978 def new_instance_vnf(self
, instance_vnf_dict
, tenant_id
, instance_scenario_id
= None):
979 #return self.new_row('vms', vm_dict, tenant_id, True, True)
980 return self
._new
_row
_internal
('instance_vnfs', instance_vnf_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
982 def update_instance_vnf(self
, instance_vnf_dict
):
986 def delete_instance_vnf(self
, instance_vnf_id
):
990 def new_instance_vm(self
, instance_vm_dict
, tenant_id
, instance_scenario_id
= None):
991 #return self.new_row('vms', vm_dict, tenant_id, True, True)
992 return self
._new
_row
_internal
('instance_vms', instance_vm_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
994 def update_instance_vm(self
, instance_vm_dict
):
998 def delete_instance_vm(self
, instance_vm_id
):
1002 def new_instance_net(self
, instance_net_dict
, tenant_id
, instance_scenario_id
= None):
1003 return self
._new
_row
_internal
('instance_nets', instance_net_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1005 def update_instance_net(self
, instance_net_dict
):
1009 def delete_instance_net(self
, instance_net_id
):
1013 def new_instance_interface(self
, instance_interface_dict
, tenant_id
, instance_scenario_id
= None):
1014 return self
._new
_row
_internal
('instance_interfaces', instance_interface_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1016 def update_instance_interface(self
, instance_interface_dict
):
1020 def delete_instance_interface(self
, instance_interface_dict
):
1024 def update_datacenter_nets(self
, datacenter_id
, new_net_list
=[]):
1025 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1027 datacenter_id: uuid of the datacenter to act upon
1028 table: table where to insert
1029 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1030 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1034 created_time
= time
.time()
1037 self
.cur
= self
.con
.cursor()
1038 cmd
="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id
)
1039 self
.logger
.debug(cmd
)
1040 self
.cur
.execute(cmd
)
1041 deleted
= self
.cur
.rowcount
1043 for new_net
in new_net_list
:
1044 created_time
+= 0.00001
1045 self
._new
_row
_internal
('datacenter_nets', new_net
, add_uuid
=True, created_time
=created_time
)
1047 return inserted
, deleted
1048 except (mdb
.Error
, AttributeError) as e
:
1049 self
._format
_error
(e
, tries
)