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",
40 "instance_actions", "vim_actions", "sce_vnffgs", "sce_rsps", "sce_rsp_hops",
41 "sce_classifiers", "sce_classifier_matches", "instance_sfis", "instance_sfs",
42 "instance_classifications", "instance_sfps"]
45 class nfvo_db(db_base
.db_base
):
46 def __init__(self
, host
=None, user
=None, passwd
=None, database
=None, log_name
='openmano.db', log_level
=None):
47 db_base
.db_base
.__init
__(self
, host
, user
, passwd
, database
, log_name
, log_level
)
48 db_base
.db_base
.tables_with_created_field
=tables_with_createdat_field
51 def new_vnf_as_a_whole(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
52 self
.logger
.debug("Adding new vnf to the NFVO database")
55 created_time
= time
.time()
60 myVNFDict
["name"] = vnf_name
61 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
62 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
63 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
64 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
65 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
67 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
68 #print "Adding new vms to the NFVO database"
69 #For each vm, we must create the appropriate vm in the NFVO database.
71 for _
,vm
in VNFCDict
.iteritems():
72 #This code could make the name of the vms grow and grow.
73 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
74 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
75 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
77 created_time
+= 0.00001
78 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
79 #print "Internal vm id in NFVO DB: %s" % vm_id
80 vmDict
[vm
['name']] = vm_id
82 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
83 bridgeInterfacesDict
= {}
84 for vm
in vnf_descriptor
['vnf']['VNFC']:
85 if 'bridge-ifaces' in vm
:
86 bridgeInterfacesDict
[vm
['name']] = {}
87 for bridgeiface
in vm
['bridge-ifaces']:
88 created_time
+= 0.00001
89 if 'port-security' in bridgeiface
:
90 bridgeiface
['port_security'] = bridgeiface
.pop('port-security')
91 if 'floating-ip' in bridgeiface
:
92 bridgeiface
['floating_ip'] = bridgeiface
.pop('floating-ip')
93 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
94 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = {}
95 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['vpci'] = bridgeiface
.get('vpci',None)
96 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['mac'] = bridgeiface
.get('mac_address',None)
97 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['bw'] = bridgeiface
.get('bandwidth', None)
98 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['model'] = bridgeiface
.get('model', None)
99 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['port_security'] = \
100 int(bridgeiface
.get('port_security', True))
101 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['floating_ip'] = \
102 int(bridgeiface
.get('floating_ip', False))
103 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']]['created_time'] = created_time
105 # Collect the data interfaces of each VM/VNFC under the 'numas' field
107 for vm
in vnf_descriptor
['vnf']['VNFC']:
108 dataifacesDict
[vm
['name']] = {}
109 for numa
in vm
.get('numas', []):
110 for dataiface
in numa
.get('interfaces', []):
111 created_time
+= 0.00001
112 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
113 dataifacesDict
[vm
['name']][dataiface
['name']] = {}
114 dataifacesDict
[vm
['name']][dataiface
['name']]['vpci'] = dataiface
.get('vpci')
115 dataifacesDict
[vm
['name']][dataiface
['name']]['bw'] = dataiface
['bandwidth']
116 dataifacesDict
[vm
['name']][dataiface
['name']]['model'] = "PF" if dataiface
[
117 'dedicated'] == "yes" else (
118 "VF" if dataiface
['dedicated'] == "no" else "VFnotShared")
119 dataifacesDict
[vm
['name']][dataiface
['name']]['created_time'] = created_time
121 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
122 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
123 internalconnList
= []
124 if 'internal-connections' in vnf_descriptor
['vnf']:
125 for net
in vnf_descriptor
['vnf']['internal-connections']:
126 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
129 myNetDict
["name"] = net
['name']
130 myNetDict
["description"] = net
['description']
131 myNetDict
["type"] = net
['type']
132 myNetDict
["vnf_id"] = vnf_id
134 created_time
+= 0.00001
135 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
137 for element
in net
['elements']:
139 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
140 ifaceItem
["internal_name"] = element
['local_iface_name']
141 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
142 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
143 ifaceItem
["net_id"] = net_id
144 ifaceItem
["type"] = net
['type']
145 if ifaceItem
["type"] == "data":
146 dataiface
= dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
147 ifaceItem
["vpci"] = dataiface
['vpci']
148 ifaceItem
["bw"] = dataiface
['bw']
149 ifaceItem
["model"] = dataiface
['model']
150 created_time_iface
= dataiface
['created_time']
152 bridgeiface
= bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
153 ifaceItem
["vpci"] = bridgeiface
['vpci']
154 ifaceItem
["mac"] = bridgeiface
['mac']
155 ifaceItem
["bw"] = bridgeiface
['bw']
156 ifaceItem
["model"] = bridgeiface
['model']
157 ifaceItem
["port_security"] = bridgeiface
['port_security']
158 ifaceItem
["floating_ip"] = bridgeiface
['floating_ip']
159 created_time_iface
= bridgeiface
['created_time']
160 internalconnList
.append(ifaceItem
)
161 #print "Internal net id in NFVO DB: %s" % net_id
163 #print "Adding internal interfaces to the NFVO database (if any)"
164 for iface
in internalconnList
:
165 #print "Iface name: %s" % iface['internal_name']
166 iface_id
= self
._new
_row
_internal
('interfaces', iface
, add_uuid
=True, root_uuid
=vnf_id
, created_time
= created_time_iface
)
167 #print "Iface id in NFVO DB: %s" % iface_id
169 #print "Adding external interfaces to the NFVO database"
170 for iface
in vnf_descriptor
['vnf']['external-connections']:
172 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
173 myIfaceDict
["internal_name"] = iface
['local_iface_name']
174 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
175 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
176 myIfaceDict
["external_name"] = iface
['name']
177 myIfaceDict
["type"] = iface
['type']
178 if iface
["type"] == "data":
179 dataiface
= dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]
180 myIfaceDict
["vpci"] = dataiface
['vpci']
181 myIfaceDict
["bw"] = dataiface
['bw']
182 myIfaceDict
["model"] = dataiface
['model']
183 created_time_iface
= dataiface
['created_time']
185 bridgeiface
= bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]
186 myIfaceDict
["vpci"] = bridgeiface
['vpci']
187 myIfaceDict
["bw"] = bridgeiface
['bw']
188 myIfaceDict
["model"] = bridgeiface
['model']
189 myIfaceDict
["mac"] = bridgeiface
['mac']
190 myIfaceDict
["port_security"]= bridgeiface
['port_security']
191 myIfaceDict
["floating_ip"] = bridgeiface
['floating_ip']
192 created_time_iface
= bridgeiface
['created_time']
193 #print "Iface name: %s" % iface['name']
194 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
= created_time_iface
)
195 #print "Iface id in NFVO DB: %s" % iface_id
199 except (mdb
.Error
, AttributeError) as e
:
200 self
._format
_error
(e
, tries
)
203 def new_vnf_as_a_whole2(self
,nfvo_tenant
,vnf_name
,vnf_descriptor
,VNFCDict
):
204 self
.logger
.debug("Adding new vnf to the NFVO database")
207 created_time
= time
.time()
212 myVNFDict
["name"] = vnf_name
213 myVNFDict
["descriptor"] = vnf_descriptor
['vnf'].get('descriptor')
214 myVNFDict
["public"] = vnf_descriptor
['vnf'].get('public', "false")
215 myVNFDict
["description"] = vnf_descriptor
['vnf']['description']
216 myVNFDict
["class"] = vnf_descriptor
['vnf'].get('class',"MISC")
217 myVNFDict
["tenant_id"] = vnf_descriptor
['vnf'].get("tenant_id")
219 vnf_id
= self
._new
_row
_internal
('vnfs', myVNFDict
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
220 #print "Adding new vms to the NFVO database"
221 #For each vm, we must create the appropriate vm in the NFVO database.
223 for _
,vm
in VNFCDict
.iteritems():
224 #This code could make the name of the vms grow and grow.
225 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
226 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
227 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
228 vm
["vnf_id"] = vnf_id
229 created_time
+= 0.00001
230 vm_id
= self
._new
_row
_internal
('vms', vm
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
231 #print "Internal vm id in NFVO DB: %s" % vm_id
232 vmDict
[vm
['name']] = vm_id
234 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
235 bridgeInterfacesDict
= {}
236 for vm
in vnf_descriptor
['vnf']['VNFC']:
237 if 'bridge-ifaces' in vm
:
238 bridgeInterfacesDict
[vm
['name']] = {}
239 for bridgeiface
in vm
['bridge-ifaces']:
240 created_time
+= 0.00001
241 db_base
._convert
_bandwidth
(bridgeiface
, logger
=self
.logger
)
242 if 'port-security' in bridgeiface
:
243 bridgeiface
['port_security'] = bridgeiface
.pop('port-security')
244 if 'floating-ip' in bridgeiface
:
245 bridgeiface
['floating_ip'] = bridgeiface
.pop('floating-ip')
247 ifaceDict
['vpci'] = bridgeiface
.get('vpci',None)
248 ifaceDict
['mac'] = bridgeiface
.get('mac_address',None)
249 ifaceDict
['bw'] = bridgeiface
.get('bandwidth', None)
250 ifaceDict
['model'] = bridgeiface
.get('model', None)
251 ifaceDict
['port_security'] = int(bridgeiface
.get('port_security', True))
252 ifaceDict
['floating_ip'] = int(bridgeiface
.get('floating_ip', False))
253 ifaceDict
['created_time'] = created_time
254 bridgeInterfacesDict
[vm
['name']][bridgeiface
['name']] = ifaceDict
256 # Collect the data interfaces of each VM/VNFC under the 'numas' field
258 for vm
in vnf_descriptor
['vnf']['VNFC']:
259 dataifacesDict
[vm
['name']] = {}
260 for numa
in vm
.get('numas', []):
261 for dataiface
in numa
.get('interfaces', []):
262 created_time
+= 0.00001
263 db_base
._convert
_bandwidth
(dataiface
, logger
=self
.logger
)
265 ifaceDict
['vpci'] = dataiface
.get('vpci')
266 ifaceDict
['bw'] = dataiface
['bandwidth']
267 ifaceDict
['model'] = "PF" if dataiface
['dedicated'] == "yes" else \
268 ("VF" if dataiface
['dedicated'] == "no" else "VFnotShared")
269 ifaceDict
['created_time'] = created_time
270 dataifacesDict
[vm
['name']][dataiface
['name']] = ifaceDict
272 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
273 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
274 if 'internal-connections' in vnf_descriptor
['vnf']:
275 for net
in vnf_descriptor
['vnf']['internal-connections']:
276 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
279 myNetDict
["name"] = net
['name']
280 myNetDict
["description"] = net
['description']
281 if (net
["implementation"] == "overlay"):
282 net
["type"] = "bridge"
283 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
284 elif (net
["implementation"] == "underlay"):
285 if (net
["type"] == "e-line"):
287 elif (net
["type"] == "e-lan"):
289 net
.pop("implementation")
290 myNetDict
["type"] = net
['type']
291 myNetDict
["vnf_id"] = vnf_id
293 created_time
+= 0.00001
294 net_id
= self
._new
_row
_internal
('nets', myNetDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time
)
296 if "ip-profile" in net
:
297 ip_profile
= net
["ip-profile"]
299 myIPProfileDict
["net_id"] = net_id
300 myIPProfileDict
["ip_version"] = ip_profile
.get('ip-version',"IPv4")
301 myIPProfileDict
["subnet_address"] = ip_profile
.get('subnet-address',None)
302 myIPProfileDict
["gateway_address"] = ip_profile
.get('gateway-address',None)
303 myIPProfileDict
["dns_address"] = ip_profile
.get('dns-address',None)
304 if ("dhcp" in ip_profile
):
305 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled',"true")
306 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address',None)
307 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count',None)
309 created_time
+= 0.00001
310 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
312 for element
in net
['elements']:
314 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
315 ifaceItem
["internal_name"] = element
['local_iface_name']
316 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
317 ifaceItem
["vm_id"] = vmDict
[element
['VNFC']]
318 ifaceItem
["net_id"] = net_id
319 ifaceItem
["type"] = net
['type']
320 ifaceItem
["ip_address"] = element
.get('ip_address',None)
321 if ifaceItem
["type"] == "data":
322 ifaceDict
= dataifacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
323 ifaceItem
["vpci"] = ifaceDict
['vpci']
324 ifaceItem
["bw"] = ifaceDict
['bw']
325 ifaceItem
["model"] = ifaceDict
['model']
327 ifaceDict
= bridgeInterfacesDict
[ element
['VNFC'] ][ element
['local_iface_name'] ]
328 ifaceItem
["vpci"] = ifaceDict
['vpci']
329 ifaceItem
["mac"] = ifaceDict
['mac']
330 ifaceItem
["bw"] = ifaceDict
['bw']
331 ifaceItem
["model"] = ifaceDict
['model']
332 ifaceItem
["port_security"] = ifaceDict
['port_security']
333 ifaceItem
["floating_ip"] = ifaceDict
['floating_ip']
334 created_time_iface
= ifaceDict
["created_time"]
335 #print "Iface name: %s" % iface['internal_name']
336 iface_id
= self
._new
_row
_internal
('interfaces', ifaceItem
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time_iface
)
337 #print "Iface id in NFVO DB: %s" % iface_id
339 #print "Adding external interfaces to the NFVO database"
340 for iface
in vnf_descriptor
['vnf']['external-connections']:
342 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
343 myIfaceDict
["internal_name"] = iface
['local_iface_name']
344 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
345 myIfaceDict
["vm_id"] = vmDict
[iface
['VNFC']]
346 myIfaceDict
["external_name"] = iface
['name']
347 myIfaceDict
["type"] = iface
['type']
348 if iface
["type"] == "data":
349 myIfaceDict
["vpci"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
350 myIfaceDict
["bw"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
351 myIfaceDict
["model"] = dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
352 created_time_iface
= dataifacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['created_time']
354 myIfaceDict
["vpci"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['vpci']
355 myIfaceDict
["bw"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['bw']
356 myIfaceDict
["model"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['model']
357 myIfaceDict
["mac"] = bridgeInterfacesDict
[ iface
['VNFC'] ][ iface
['local_iface_name'] ]['mac']
358 myIfaceDict
["port_security"] = \
359 bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['port_security']
360 myIfaceDict
["floating_ip"] = \
361 bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['floating_ip']
362 created_time_iface
= bridgeInterfacesDict
[iface
['VNFC']][iface
['local_iface_name']]['created_time']
363 #print "Iface name: %s" % iface['name']
364 iface_id
= self
._new
_row
_internal
('interfaces', myIfaceDict
, add_uuid
=True, root_uuid
=vnf_id
, created_time
=created_time_iface
)
365 #print "Iface id in NFVO DB: %s" % iface_id
369 except (mdb
.Error
, AttributeError) as e
:
370 self
._format
_error
(e
, tries
)
371 # except KeyError as e2:
372 # exc_type, exc_obj, exc_tb = sys.exc_info()
373 # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
374 # self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
378 def new_scenario(self
, scenario_dict
):
381 created_time
= time
.time()
384 self
.cur
= self
.con
.cursor()
385 tenant_id
= scenario_dict
.get('tenant_id')
387 INSERT_
={'tenant_id': tenant_id
,
388 'name': scenario_dict
['name'],
389 'description': scenario_dict
['description'],
390 'public': scenario_dict
.get('public', "false")}
392 scenario_uuid
= self
._new
_row
_internal
('scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
394 for net
in scenario_dict
['nets'].values():
395 net_dict
={'scenario_id': scenario_uuid
}
396 net_dict
["name"] = net
["name"]
397 net_dict
["type"] = net
["type"]
398 net_dict
["description"] = net
.get("description")
399 net_dict
["external"] = net
.get("external", False)
401 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
402 #TODO, must be json because of the GUI, change to yaml
403 net_dict
["graph"]=json
.dumps(net
["graph"])
404 created_time
+= 0.00001
405 net_uuid
= self
._new
_row
_internal
('sce_nets', net_dict
, add_uuid
=True, root_uuid
=scenario_uuid
, created_time
=created_time
)
408 if net
.get("ip-profile"):
409 ip_profile
= net
["ip-profile"]
411 "sce_net_id": net_uuid
,
412 "ip_version": ip_profile
.get('ip-version', "IPv4"),
413 "subnet_address": ip_profile
.get('subnet-address'),
414 "gateway_address": ip_profile
.get('gateway-address'),
415 "dns_address": ip_profile
.get('dns-address')}
416 if "dhcp" in ip_profile
:
417 myIPProfileDict
["dhcp_enabled"] = ip_profile
["dhcp"].get('enabled', "true")
418 myIPProfileDict
["dhcp_start_address"] = ip_profile
["dhcp"].get('start-address')
419 myIPProfileDict
["dhcp_count"] = ip_profile
["dhcp"].get('count')
420 self
._new
_row
_internal
('ip_profiles', myIPProfileDict
)
423 for k
, vnf
in scenario_dict
['vnfs'].items():
424 INSERT_
= {'scenario_id': scenario_uuid
,
426 'vnf_id': vnf
['uuid'],
427 # 'description': scenario_dict['name']
428 'description': vnf
['description']}
430 #I NSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
431 # TODO, must be json because of the GUI, change to yaml
432 INSERT_
["graph"] = json
.dumps(vnf
["graph"])
433 created_time
+= 0.00001
434 scn_vnf_uuid
= self
._new
_row
_internal
('sce_vnfs', INSERT_
, add_uuid
=True,
435 root_uuid
=scenario_uuid
, created_time
=created_time
)
436 vnf
['scn_vnf_uuid']=scn_vnf_uuid
438 for iface
in vnf
['ifaces'].values():
439 # print 'iface', iface
440 if 'net_key' not in iface
:
442 iface
['net_id'] = scenario_dict
['nets'][ iface
['net_key'] ]['uuid']
443 INSERT_
={'sce_vnf_id': scn_vnf_uuid
,
444 'sce_net_id': iface
['net_id'],
445 'interface_id': iface
['uuid'],
446 'ip_address': iface
.get('ip_address')}
447 created_time
+= 0.00001
448 iface_uuid
= self
._new
_row
_internal
('sce_interfaces', INSERT_
, add_uuid
=True,
449 root_uuid
=scenario_uuid
, created_time
=created_time
)
453 except (mdb
.Error
, AttributeError) as e
:
454 self
._format
_error
(e
, tries
)
457 def edit_scenario(self
, scenario_dict
):
460 modified_time
= time
.time()
464 self
.cur
= self
.con
.cursor()
465 #check that scenario exist
466 tenant_id
= scenario_dict
.get('tenant_id')
467 scenario_uuid
= scenario_dict
['uuid']
469 where_text
= "uuid='{}'".format(scenario_uuid
)
470 if not tenant_id
and tenant_id
!= "any":
471 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
472 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
473 self
.logger
.debug(cmd
)
474 self
.cur
.execute(cmd
)
476 if self
.cur
.rowcount
==0:
477 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
478 elif self
.cur
.rowcount
>1:
479 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
483 topology
= scenario_dict
.pop("topology", None)
484 if topology
!= None and "nodes" in topology
:
485 nodes
= topology
.get("nodes",{})
487 if "name" in scenario_dict
: UPDATE_
["name"] = scenario_dict
["name"]
488 if "description" in scenario_dict
: UPDATE_
["description"] = scenario_dict
["description"]
490 WHERE_
={'tenant_id': tenant_id
, 'uuid': scenario_uuid
}
491 item_changed
+= self
._update
_rows
('scenarios', UPDATE_
, WHERE_
, modified_time
=modified_time
)
493 for node_id
, node
in nodes
.items():
495 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
496 #TODO, must be json because of the GUI, change to yaml
497 node
["graph"] = json
.dumps(node
["graph"])
498 WHERE_
={'scenario_id': scenario_uuid
, 'uuid': node_id
}
499 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
500 item_changed
+= self
._update
_rows
('sce_nets', node
, WHERE_
)
501 item_changed
+= self
._update
_rows
('sce_vnfs', node
, WHERE_
, modified_time
=modified_time
)
504 except (mdb
.Error
, AttributeError) as e
:
505 self
._format
_error
(e
, tries
)
508 # def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
509 # '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
510 # instance_scenario_id is the uuid or the name if it is not a valid uuid format
511 # Only one scenario isntance must mutch the filtering or an error is returned
513 # print "1******************************************************************"
516 # self.cur = self.con.cursor(mdb.cursors.DictCursor)
519 # if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
520 # if db_base._check_valid_uuid(instance_scenario_id):
521 # where_list.append( "uuid='" + instance_scenario_id +"'" )
523 # where_list.append( "name='" + instance_scenario_id +"'" )
524 # where_text = " AND ".join(where_list)
525 # self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
526 # rows = self.cur.fetchall()
527 # if self.cur.rowcount==0:
528 # return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
529 # elif self.cur.rowcount>1:
530 # return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
531 # instance_scenario_dict = rows[0]
534 # self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
535 # instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
536 # for vnf in instance_scenario_dict['instance_vnfs']:
538 # self.cur.execute("SELECT uuid, vim_vm_id "+
539 # "FROM instance_vms "+
540 # "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
542 # vnf['instance_vms'] = self.cur.fetchall()
544 # self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
545 # instance_scenario_dict['instance_nets'] = self.cur.fetchall()
547 # #instance_interfaces
548 # 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'] + "'")
549 # instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
551 # db_base._convert_datetime2str(instance_scenario_dict)
552 # db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
553 # print "2******************************************************************"
554 # return 1, instance_scenario_dict
555 # except (mdb.Error, AttributeError) as e:
556 # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
557 # return self._format_error(e)
559 def get_scenario(self
, scenario_id
, tenant_id
=None, datacenter_vim_id
=None, datacenter_id
=None):
560 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
561 scenario_id is the uuid or the name if it is not a valid uuid format
562 if datacenter_vim_id,d datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
563 Only one scenario must mutch the filtering or an error is returned
569 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
570 where_text
= "uuid='{}'".format(scenario_id
)
571 if not tenant_id
and tenant_id
!= "any":
572 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
573 cmd
= "SELECT * FROM scenarios WHERE " + where_text
574 self
.logger
.debug(cmd
)
575 self
.cur
.execute(cmd
)
576 rows
= self
.cur
.fetchall()
577 if self
.cur
.rowcount
==0:
578 raise db_base
.db_base_Exception("No scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
579 elif self
.cur
.rowcount
>1:
580 raise db_base
.db_base_Exception("More than one scenario found with this criteria " + where_text
, db_base
.HTTP_Bad_Request
)
581 scenario_dict
= rows
[0]
582 if scenario_dict
["cloud_config"]:
583 scenario_dict
["cloud-config"] = yaml
.load(scenario_dict
["cloud_config"])
584 del scenario_dict
["cloud_config"]
586 cmd
= "SELECT uuid,name,member_vnf_index,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' "\
587 "ORDER BY created_at".format(scenario_dict
['uuid'])
588 self
.logger
.debug(cmd
)
589 self
.cur
.execute(cmd
)
590 scenario_dict
['vnfs'] = self
.cur
.fetchall()
592 for vnf
in scenario_dict
['vnfs']:
593 cmd
= "SELECT mgmt_access FROM vnfs WHERE uuid='{}'".format(scenario_dict
['vnfs'][0]['vnf_id'])
594 self
.logger
.debug(cmd
)
595 self
.cur
.execute(cmd
)
596 mgmt_access_dict
= self
.cur
.fetchall()
597 if mgmt_access_dict
[0].get('mgmt_access'):
598 vnf
['mgmt_access'] = yaml
.load(mgmt_access_dict
[0]['mgmt_access'])
600 vnf
['mgmt_access'] = None
602 cmd
= "SELECT scei.uuid,scei.sce_net_id,scei.interface_id,i.external_name,scei.ip_address"\
603 " FROM sce_interfaces as scei join interfaces as i on scei.interface_id=i.uuid"\
604 " WHERE scei.sce_vnf_id='{}' ORDER BY scei.created_at".format(vnf
['uuid'])
605 self
.logger
.debug(cmd
)
606 self
.cur
.execute(cmd
)
607 vnf
['interfaces'] = self
.cur
.fetchall()
609 cmd
= "SELECT vms.uuid as uuid, flavor_id, image_id, image_list, vms.name as name," \
610 " vms.description as description, vms.boot_data as boot_data, count," \
611 " vms.availability_zone as availability_zone, vms.osm_id as osm_id" \
612 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id" \
613 " WHERE vnfs.uuid='" + vnf
['vnf_id'] + "'" \
614 " ORDER BY vms.created_at"
615 self
.logger
.debug(cmd
)
616 self
.cur
.execute(cmd
)
617 vnf
['vms'] = self
.cur
.fetchall()
618 for vm
in vnf
['vms']:
620 vm
["boot_data"] = yaml
.safe_load(vm
["boot_data"])
624 vm
["image_list"] = yaml
.safe_load(vm
["image_list"])
627 if datacenter_vim_id
!=None:
628 cmd
= "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_vim_id='{}'".format(vm
['image_id'],datacenter_vim_id
)
629 self
.logger
.debug(cmd
)
630 self
.cur
.execute(cmd
)
631 if self
.cur
.rowcount
==1:
632 vim_image_dict
= self
.cur
.fetchone()
633 vm
['vim_image_id']=vim_image_dict
['vim_id']
634 cmd
= "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_vim_id='{}'".format(vm
['flavor_id'],datacenter_vim_id
)
635 self
.logger
.debug(cmd
)
636 self
.cur
.execute(cmd
)
637 if self
.cur
.rowcount
==1:
638 vim_flavor_dict
= self
.cur
.fetchone()
639 vm
['vim_flavor_id']=vim_flavor_dict
['vim_id']
642 cmd
= "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
643 "floating_ip, port_security" \
645 " WHERE vm_id='{}'" \
646 " ORDER BY created_at".format(vm
['uuid'])
647 self
.logger
.debug(cmd
)
648 self
.cur
.execute(cmd
)
649 vm
['interfaces'] = self
.cur
.fetchall()
650 for iface
in vm
['interfaces']:
651 iface
['port-security'] = iface
.pop("port_security")
652 iface
['floating-ip'] = iface
.pop("floating_ip")
653 for sce_interface
in vnf
["interfaces"]:
654 if sce_interface
["interface_id"] == iface
["uuid"]:
655 if sce_interface
["ip_address"]:
656 iface
["ip_address"] = sce_interface
["ip_address"]
658 #nets every net of a vms
659 cmd
= "SELECT uuid,name,type,description, osm_id FROM nets WHERE vnf_id='{}'".format(vnf
['vnf_id'])
660 self
.logger
.debug(cmd
)
661 self
.cur
.execute(cmd
)
662 vnf
['nets'] = self
.cur
.fetchall()
663 for vnf_net
in vnf
['nets']:
664 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
665 cmd
= "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_
,vnf_net
['uuid'])
666 self
.logger
.debug(cmd
)
667 self
.cur
.execute(cmd
)
668 ipprofiles
= self
.cur
.fetchall()
669 if self
.cur
.rowcount
==1:
670 vnf_net
["ip_profile"] = ipprofiles
[0]
671 elif self
.cur
.rowcount
>1:
672 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
)
675 cmd
= "SELECT uuid,name,type,external,description,vim_network_name, osm_id" \
676 " FROM sce_nets WHERE scenario_id='{}'" \
677 " ORDER BY created_at ".format(scenario_dict
['uuid'])
678 self
.logger
.debug(cmd
)
679 self
.cur
.execute(cmd
)
680 scenario_dict
['nets'] = self
.cur
.fetchall()
682 for net
in scenario_dict
['nets']:
683 if str(net
['external']) == 'false':
684 SELECT_
= "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
685 cmd
= "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_
,net
['uuid'])
686 self
.logger
.debug(cmd
)
687 self
.cur
.execute(cmd
)
688 ipprofiles
= self
.cur
.fetchall()
689 if self
.cur
.rowcount
==1:
690 net
["ip_profile"] = ipprofiles
[0]
691 elif self
.cur
.rowcount
>1:
692 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
)
694 WHERE_
=" WHERE name='{}'".format(net
['name'])
695 if datacenter_id
!=None:
696 WHERE_
+= " AND datacenter_id='{}'".format(datacenter_id
)
697 cmd
= "SELECT vim_net_id FROM datacenter_nets" + WHERE_
698 self
.logger
.debug(cmd
)
699 self
.cur
.execute(cmd
)
700 d_net
= self
.cur
.fetchone()
701 if d_net
==None or datacenter_vim_id
==None:
702 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
705 net
['vim_id']=d_net
['vim_net_id']
707 db_base
._convert
_datetime
2str
(scenario_dict
)
708 db_base
._convert
_str
2boolean
(scenario_dict
, ('public','shared','external','port-security','floating-ip') )
711 cmd
= "SELECT uuid,name,description,vendor FROM sce_vnffgs WHERE scenario_id='{}' "\
712 "ORDER BY created_at".format(scenario_dict
['uuid'])
713 self
.logger
.debug(cmd
)
714 self
.cur
.execute(cmd
)
715 scenario_dict
['vnffgs'] = self
.cur
.fetchall()
716 for vnffg
in scenario_dict
['vnffgs']:
717 cmd
= "SELECT uuid,name FROM sce_rsps WHERE sce_vnffg_id='{}' "\
718 "ORDER BY created_at".format(vnffg
['uuid'])
719 self
.logger
.debug(cmd
)
720 self
.cur
.execute(cmd
)
721 vnffg
['rsps'] = self
.cur
.fetchall()
722 for rsp
in vnffg
['rsps']:
723 cmd
= "SELECT uuid,if_order,interface_id,sce_vnf_id FROM sce_rsp_hops WHERE sce_rsp_id='{}' "\
724 "ORDER BY created_at".format(rsp
['uuid'])
725 self
.logger
.debug(cmd
)
726 self
.cur
.execute(cmd
)
727 rsp
['connection_points'] = self
.cur
.fetchall();
728 cmd
= "SELECT uuid,name,sce_vnf_id,interface_id FROM sce_classifiers WHERE sce_vnffg_id='{}' "\
729 "AND sce_rsp_id='{}' ORDER BY created_at".format(vnffg
['uuid'], rsp
['uuid'])
730 self
.logger
.debug(cmd
)
731 self
.cur
.execute(cmd
)
732 rsp
['classifier'] = self
.cur
.fetchone();
733 cmd
= "SELECT uuid,ip_proto,source_ip,destination_ip,source_port,destination_port FROM sce_classifier_matches "\
734 "WHERE sce_classifier_id='{}' ORDER BY created_at".format(rsp
['classifier']['uuid'])
735 self
.logger
.debug(cmd
)
736 self
.cur
.execute(cmd
)
737 rsp
['classifier']['matches'] = self
.cur
.fetchall()
740 except (mdb
.Error
, AttributeError) as e
:
741 self
._format
_error
(e
, tries
)
744 def delete_scenario(self
, scenario_id
, tenant_id
=None):
745 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
746 scenario_id is the uuid or the name if it is not a valid uuid format
747 Only one scenario must mutch the filtering or an error is returned
753 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
756 where_text
= "uuid='{}'".format(scenario_id
)
757 if not tenant_id
and tenant_id
!= "any":
758 where_text
+= " AND (tenant_id='{}' OR public='True')".format(tenant_id
)
759 cmd
= "SELECT * FROM scenarios WHERE "+ where_text
760 self
.logger
.debug(cmd
)
761 self
.cur
.execute(cmd
)
762 rows
= self
.cur
.fetchall()
763 if self
.cur
.rowcount
==0:
764 raise db_base
.db_base_Exception("No scenario found where " + where_text
, db_base
.HTTP_Not_Found
)
765 elif self
.cur
.rowcount
>1:
766 raise db_base
.db_base_Exception("More than one scenario found where " + where_text
, db_base
.HTTP_Conflict
)
767 scenario_uuid
= rows
[0]["uuid"]
768 scenario_name
= rows
[0]["name"]
771 cmd
= "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid
)
772 self
.logger
.debug(cmd
)
773 self
.cur
.execute(cmd
)
775 return scenario_uuid
+ " " + scenario_name
776 except (mdb
.Error
, AttributeError) as e
:
777 self
._format
_error
(e
, tries
, "delete", "instances running")
780 def new_rows(self
, tables
, uuid_list
=None):
782 Make a transactional insertion of rows at several tables. Can be also a deletion
783 :param tables: list with dictionary where the keys are the table names and the values are a row or row list
784 with the values to be inserted at the table. Each row is a dictionary with the key values. E.g.:
786 {"table1": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
787 {"table2": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
788 {"table3": {"column1": value, "column2: value, ... }
790 If tables does not contain the 'created_at', it is generated incrementally with the order of tables. You can
791 provide a integer value, that it is an index multiply by 0.00001 to add to the created time to manually set
793 If dict contains {"TO-DELETE": uuid} the entry is deleted if exist instead of inserted
794 :param uuid_list: list of created uuids, first one is the root (#TODO to store at uuid table)
795 :return: None if success, raise exception otherwise
799 created_time
= time
.time()
802 self
.cur
= self
.con
.cursor()
804 for table_name
, row_list
in table
.items():
806 if isinstance(row_list
, dict):
807 row_list
= (row_list
, ) #create a list with the single value
809 if "TO-DELETE" in row
:
810 self
._delete
_row
_by
_id
_internal
(table_name
, row
["TO-DELETE"])
813 if table_name
in self
.tables_with_created_field
:
814 if "created_at" in row
:
815 created_time_param
= created_time
+ (index
+ row
.pop("created_at"))*0.00001
817 created_time_param
= created_time
+ index
*0.00001
820 created_time_param
= 0
821 self
._new
_row
_internal
(table_name
, row
, add_uuid
=False, root_uuid
=None,
822 created_time
=created_time_param
)
824 except (mdb
.Error
, AttributeError) as e
:
825 self
._format
_error
(e
, tries
)
828 def new_instance_scenario_as_a_whole(self
,tenant_id
,instance_scenario_name
,instance_scenario_description
,scenarioDict
):
831 created_time
= time
.time()
834 self
.cur
= self
.con
.cursor()
836 datacenter_id
= scenarioDict
['datacenter_id']
837 INSERT_
={'tenant_id': tenant_id
,
838 'datacenter_tenant_id': scenarioDict
["datacenter2tenant"][datacenter_id
],
839 'name': instance_scenario_name
,
840 'description': instance_scenario_description
,
841 'scenario_id' : scenarioDict
['uuid'],
842 'datacenter_id': datacenter_id
844 if scenarioDict
.get("cloud-config"):
845 INSERT_
["cloud_config"] = yaml
.safe_dump(scenarioDict
["cloud-config"], default_flow_style
=True, width
=256)
847 instance_uuid
= self
._new
_row
_internal
('instance_scenarios', INSERT_
, add_uuid
=True, root_uuid
=None, created_time
=created_time
)
849 net_scene2instance
={}
850 #instance_nets #nets interVNF
851 for net
in scenarioDict
['nets']:
852 net_scene2instance
[ net
['uuid'] ] ={}
853 datacenter_site_id
= net
.get('datacenter_id', datacenter_id
)
854 if not "vim_id_sites" in net
:
855 net
["vim_id_sites"] ={datacenter_site_id
: net
['vim_id']}
856 net
["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id
: net
['vim_id']}
857 sce_net_id
= net
.get("uuid")
859 for datacenter_site_id
,vim_id
in net
["vim_id_sites"].iteritems():
860 INSERT_
={'vim_net_id': vim_id
, 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
861 INSERT_
['datacenter_id'] = datacenter_site_id
862 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
863 if not net
.get('created', False):
864 INSERT_
['status'] = "ACTIVE"
866 INSERT_
['sce_net_id'] = sce_net_id
867 created_time
+= 0.00001
868 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
869 net_scene2instance
[ sce_net_id
][datacenter_site_id
] = instance_net_uuid
870 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
872 if 'ip_profile' in net
:
873 net
['ip_profile']['net_id'] = None
874 net
['ip_profile']['sce_net_id'] = None
875 net
['ip_profile']['instance_net_id'] = instance_net_uuid
876 created_time
+= 0.00001
877 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
880 for vnf
in scenarioDict
['vnfs']:
881 datacenter_site_id
= vnf
.get('datacenter_id', datacenter_id
)
882 INSERT_
={'instance_scenario_id': instance_uuid
, 'vnf_id': vnf
['vnf_id'] }
883 INSERT_
['datacenter_id'] = datacenter_site_id
884 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_site_id
]
886 INSERT_
['sce_vnf_id'] = vnf
['uuid']
887 created_time
+= 0.00001
888 instance_vnf_uuid
= self
._new
_row
_internal
('instance_vnfs', INSERT_
, True, instance_uuid
, created_time
)
889 vnf
['uuid'] = instance_vnf_uuid
#overwrite scnario uuid by instance uuid
891 #instance_nets #nets intraVNF
892 for net
in vnf
['nets']:
893 net_scene2instance
[ net
['uuid'] ] = {}
894 INSERT_
={'vim_net_id': net
['vim_id'], 'created': net
.get('created', False), 'instance_scenario_id':instance_uuid
} #, 'type': net['type']
895 INSERT_
['datacenter_id'] = net
.get('datacenter_id', datacenter_site_id
)
896 INSERT_
['datacenter_tenant_id'] = scenarioDict
["datacenter2tenant"][datacenter_id
]
898 INSERT_
['net_id'] = net
['uuid']
899 created_time
+= 0.00001
900 instance_net_uuid
= self
._new
_row
_internal
('instance_nets', INSERT_
, True, instance_uuid
, created_time
)
901 net_scene2instance
[ net
['uuid'] ][datacenter_site_id
] = instance_net_uuid
902 net
['uuid'] = instance_net_uuid
#overwrite scnario uuid by instance uuid
904 if 'ip_profile' in net
:
905 net
['ip_profile']['net_id'] = None
906 net
['ip_profile']['sce_net_id'] = None
907 net
['ip_profile']['instance_net_id'] = instance_net_uuid
908 created_time
+= 0.00001
909 ip_profile_id
= self
._new
_row
_internal
('ip_profiles', net
['ip_profile'])
912 for vm
in vnf
['vms']:
913 INSERT_
={'instance_vnf_id': instance_vnf_uuid
, 'vm_id': vm
['uuid'], 'vim_vm_id': vm
['vim_id'] }
914 created_time
+= 0.00001
915 instance_vm_uuid
= self
._new
_row
_internal
('instance_vms', INSERT_
, True, instance_uuid
, created_time
)
916 vm
['uuid'] = instance_vm_uuid
#overwrite scnario uuid by instance uuid
919 for interface
in vm
['interfaces']:
920 net_id
= interface
.get('net_id', None)
922 #check if is connected to a inter VNFs net
923 for iface
in vnf
['interfaces']:
924 if iface
['interface_id'] == interface
['uuid']:
925 if 'ip_address' in iface
:
926 interface
['ip_address'] = iface
['ip_address']
927 net_id
= iface
.get('sce_net_id', None)
931 interface_type
='external' if interface
['external_name'] is not None else 'internal'
932 INSERT_
={'instance_vm_id': instance_vm_uuid
, 'instance_net_id': net_scene2instance
[net_id
][datacenter_site_id
],
933 'interface_id': interface
['uuid'], 'vim_interface_id': interface
.get('vim_id'), 'type': interface_type
,
934 'ip_address': interface
.get('ip_address'), 'floating_ip': int(interface
.get('floating-ip',False)),
935 'port_security': int(interface
.get('port-security',True))}
936 #created_time += 0.00001
937 interface_uuid
= self
._new
_row
_internal
('instance_interfaces', INSERT_
, True, instance_uuid
) #, created_time)
938 interface
['uuid'] = interface_uuid
#overwrite scnario uuid by instance uuid
940 except (mdb
.Error
, AttributeError) as e
:
941 self
._format
_error
(e
, tries
)
944 def get_instance_scenario(self
, instance_id
, tenant_id
=None, verbose
=False):
945 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
946 instance_id is the uuid or the name if it is not a valid uuid format
947 Only one instance must mutch the filtering or an error is returned
953 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
957 where_list
.append("inst.tenant_id='{}'".format(tenant_id
))
958 if db_base
._check
_valid
_uuid
(instance_id
):
959 where_list
.append("inst.uuid='{}'".format(instance_id
))
961 where_list
.append("inst.name='{}'".format(instance_id
))
962 where_text
= " AND ".join(where_list
)
963 cmd
= "SELECT inst.uuid as uuid, inst.name as name, inst.scenario_id as scenario_id, datacenter_id"\
964 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" \
965 " ,inst.description as description, inst.created_at as created_at" \
966 " ,inst.cloud_config as cloud_config, s.osm_id as nsd_osm_id" \
967 " FROM instance_scenarios as inst left join scenarios as s on inst.scenario_id=s.uuid" \
968 " 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_Not_Found
)
975 elif self
.cur
.rowcount
> 1:
976 raise db_base
.db_base_Exception("More than one instance found where " + where_text
,
977 db_base
.HTTP_Bad_Request
)
978 instance_dict
= rows
[0]
979 if instance_dict
["cloud_config"]:
980 instance_dict
["cloud-config"] = yaml
.load(instance_dict
["cloud_config"])
981 del instance_dict
["cloud_config"]
984 cmd
= "SELECT iv.uuid as uuid, iv.vnf_id as vnf_id, sv.name as vnf_name, sce_vnf_id, datacenter_id"\
985 ", datacenter_tenant_id, v.mgmt_access, sv.member_vnf_index, v.osm_id as vnfd_osm_id "\
986 "FROM instance_vnfs as iv left join sce_vnfs as sv "\
987 " on iv.sce_vnf_id=sv.uuid join vnfs as v on iv.vnf_id=v.uuid " \
988 "WHERE iv.instance_scenario_id='{}' " \
989 "ORDER BY iv.created_at ".format(instance_dict
['uuid'])
990 self
.logger
.debug(cmd
)
991 self
.cur
.execute(cmd
)
992 instance_dict
['vnfs'] = self
.cur
.fetchall()
993 for vnf
in instance_dict
['vnfs']:
995 vnf_mgmt_access_iface
= None
996 vnf_mgmt_access_vm
= None
997 if vnf
["mgmt_access"]:
998 vnf_mgmt_access
= yaml
.load(vnf
["mgmt_access"])
999 vnf_mgmt_access_iface
= vnf_mgmt_access
.get("interface_id")
1000 vnf_mgmt_access_vm
= vnf_mgmt_access
.get("vm_id")
1001 vnf
["ip_address"] = vnf_mgmt_access
.get("ip-address")
1004 cmd
= "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as "\
1005 "created_at, name, vms.osm_id as vdu_osm_id, vim_name, vms.uuid as vm_uuid"\
1006 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
1007 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf
['uuid'])
1008 self
.logger
.debug(cmd
)
1009 self
.cur
.execute(cmd
)
1010 vnf
['vms'] = self
.cur
.fetchall()
1011 for vm
in vnf
['vms']:
1012 vm_manage_iface_list
=[]
1013 # instance_interfaces
1014 cmd
= "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
1015 " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id, i.uuid"\
1016 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
1017 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm
['uuid'])
1018 self
.logger
.debug(cmd
)
1019 self
.cur
.execute(cmd
)
1020 vm
['interfaces'] = self
.cur
.fetchall()
1021 for iface
in vm
['interfaces']:
1022 if vnf_mgmt_access_iface
and vnf_mgmt_access_iface
== iface
["uuid"]:
1023 vnf
["ip_address"] = iface
["ip_address"]
1024 if iface
["type"] == "mgmt" and iface
["ip_address"]:
1025 vm_manage_iface_list
.append(iface
["ip_address"])
1029 if vm_manage_iface_list
:
1030 vm
["ip_address"] = ",".join(vm_manage_iface_list
)
1031 if vnf_mgmt_access_vm
== vm
["vm_uuid"]:
1032 vnf
["ip_address"] = vm
["ip_address"]
1033 elif not vnf
.get("ip_address"):
1034 vnf
["ip_address"] = vm
["ip_address"]
1038 #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"
1039 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
1040 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
1041 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
1042 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"\
1043 " FROM instance_nets" \
1044 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
1045 self
.logger
.debug(cmd
)
1046 self
.cur
.execute(cmd
)
1047 instance_dict
['nets'] = self
.cur
.fetchall()
1050 cmd
= "SELECT uuid,vim_sfp_id,sce_rsp_id,datacenter_id,"\
1051 "datacenter_tenant_id,status,error_msg,vim_info"\
1052 " FROM instance_sfps" \
1053 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
1054 self
.logger
.debug(cmd
)
1055 self
.cur
.execute(cmd
)
1056 instance_dict
['sfps'] = self
.cur
.fetchall()
1058 # for sfp in instance_dict['sfps']:
1060 cmd
= "SELECT uuid,vim_sf_id,sce_rsp_hop_id,datacenter_id,"\
1061 "datacenter_tenant_id,status,error_msg,vim_info"\
1062 " FROM instance_sfs" \
1063 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid']) # TODO: replace instance_scenario_id with instance_sfp_id
1064 self
.logger
.debug(cmd
)
1065 self
.cur
.execute(cmd
)
1066 instance_dict
['sfs'] = self
.cur
.fetchall()
1068 #for sf in instance_dict['sfs']:
1070 cmd
= "SELECT uuid,vim_sfi_id,sce_rsp_hop_id,datacenter_id,"\
1071 "datacenter_tenant_id,status,error_msg,vim_info"\
1072 " FROM instance_sfis" \
1073 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid']) # TODO: replace instance_scenario_id with instance_sf_id
1074 self
.logger
.debug(cmd
)
1075 self
.cur
.execute(cmd
)
1076 instance_dict
['sfis'] = self
.cur
.fetchall()
1077 # for sfi in instance_dict['sfi']:
1079 #instance_classifications
1080 cmd
= "SELECT uuid,vim_classification_id,sce_classifier_match_id,datacenter_id,"\
1081 "datacenter_tenant_id,status,error_msg,vim_info"\
1082 " FROM instance_classifications" \
1083 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict
['uuid'])
1084 self
.logger
.debug(cmd
)
1085 self
.cur
.execute(cmd
)
1086 instance_dict
['classifications'] = self
.cur
.fetchall()
1087 # for classification in instance_dict['classifications']
1089 db_base
._convert
_datetime
2str
(instance_dict
)
1090 db_base
._convert
_str
2boolean
(instance_dict
, ('public','shared','created') )
1091 return instance_dict
1092 except (mdb
.Error
, AttributeError) as e
:
1093 self
._format
_error
(e
, tries
)
1096 def delete_instance_scenario(self
, instance_id
, tenant_id
=None):
1097 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
1098 instance_id is the uuid or the name if it is not a valid uuid format
1099 Only one instance_scenario must mutch the filtering or an error is returned
1105 self
.cur
= self
.con
.cursor(mdb
.cursors
.DictCursor
)
1109 if tenant_id
is not None: where_list
.append( "tenant_id='" + tenant_id
+"'" )
1110 if db_base
._check
_valid
_uuid
(instance_id
):
1111 where_list
.append( "uuid='" + instance_id
+"'" )
1113 where_list
.append( "name='" + instance_id
+"'" )
1114 where_text
= " AND ".join(where_list
)
1115 cmd
= "SELECT * FROM instance_scenarios WHERE "+ where_text
1116 self
.logger
.debug(cmd
)
1117 self
.cur
.execute(cmd
)
1118 rows
= self
.cur
.fetchall()
1120 if self
.cur
.rowcount
==0:
1121 raise db_base
.db_base_Exception("No instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
1122 elif self
.cur
.rowcount
>1:
1123 raise db_base
.db_base_Exception("More than one instance found where " + where_text
, db_base
.HTTP_Bad_Request
)
1124 instance_uuid
= rows
[0]["uuid"]
1125 instance_name
= rows
[0]["name"]
1128 cmd
= "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid
)
1129 self
.logger
.debug(cmd
)
1130 self
.cur
.execute(cmd
)
1132 return instance_uuid
+ " " + instance_name
1133 except (mdb
.Error
, AttributeError) as e
:
1134 self
._format
_error
(e
, tries
, "delete", "No dependences can avoid deleting!!!!")
1137 def new_instance_scenario(self
, instance_scenario_dict
, tenant_id
):
1138 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1139 return self
._new
_row
_internal
('instance_scenarios', instance_scenario_dict
, tenant_id
, add_uuid
=True, root_uuid
=None, log
=True)
1141 def update_instance_scenario(self
, instance_scenario_dict
):
1145 def new_instance_vnf(self
, instance_vnf_dict
, tenant_id
, instance_scenario_id
= None):
1146 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1147 return self
._new
_row
_internal
('instance_vnfs', instance_vnf_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1149 def update_instance_vnf(self
, instance_vnf_dict
):
1153 def delete_instance_vnf(self
, instance_vnf_id
):
1157 def new_instance_vm(self
, instance_vm_dict
, tenant_id
, instance_scenario_id
= None):
1158 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1159 return self
._new
_row
_internal
('instance_vms', instance_vm_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1161 def update_instance_vm(self
, instance_vm_dict
):
1165 def delete_instance_vm(self
, instance_vm_id
):
1169 def new_instance_net(self
, instance_net_dict
, tenant_id
, instance_scenario_id
= None):
1170 return self
._new
_row
_internal
('instance_nets', instance_net_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1172 def update_instance_net(self
, instance_net_dict
):
1176 def delete_instance_net(self
, instance_net_id
):
1180 def new_instance_interface(self
, instance_interface_dict
, tenant_id
, instance_scenario_id
= None):
1181 return self
._new
_row
_internal
('instance_interfaces', instance_interface_dict
, tenant_id
, add_uuid
=True, root_uuid
=instance_scenario_id
, log
=True)
1183 def update_instance_interface(self
, instance_interface_dict
):
1187 def delete_instance_interface(self
, instance_interface_dict
):
1191 def update_datacenter_nets(self
, datacenter_id
, new_net_list
=[]):
1192 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1194 datacenter_id: uuid of the datacenter to act upon
1195 table: table where to insert
1196 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1197 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1201 created_time
= time
.time()
1204 self
.cur
= self
.con
.cursor()
1205 cmd
="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id
)
1206 self
.logger
.debug(cmd
)
1207 self
.cur
.execute(cmd
)
1208 deleted
= self
.cur
.rowcount
1210 for new_net
in new_net_list
:
1211 created_time
+= 0.00001
1212 self
._new
_row
_internal
('datacenter_nets', new_net
, add_uuid
=True, created_time
=created_time
)
1214 return inserted
, deleted
1215 except (mdb
.Error
, AttributeError) as e
:
1216 self
._format
_error
(e
, tries
)