Merge branch 'master' into vnffg
[osm/RO.git] / osm_ro / nfvo_db.py
1 # -*- coding: utf-8 -*-
2
3 ##
4 # Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
5 # This file is part of openmano
6 # All Rights Reserved.
7 #
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
11 #
12 # http://www.apache.org/licenses/LICENSE-2.0
13 #
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
18 # under the License.
19 #
20 # For those usages not covered by the Apache License, Version 2.0 please
21 # contact with: nfvlabs@tid.es
22 ##
23
24 '''
25 NFVO DB engine. It implements all the methods to interact with the Openmano Database
26 '''
27 __author__="Alfonso Tierno, Gerardo Garcia, Pablo Montes"
28 __date__ ="$28-aug-2014 10:05:01$"
29
30 import db_base
31 import MySQLdb as mdb
32 import json
33 import yaml
34 import time
35 #import sys, os
36
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
41
42 class nfvo_db(db_base.db_base):
43 def __init__(self, host=None, user=None, passwd=None, database=None, log_name='openmano.db', log_level=None):
44 db_base.db_base.__init__(self, host, user, passwd, database, log_name, log_level)
45 db_base.db_base.tables_with_created_field=tables_with_createdat_field
46 return
47
48 def new_vnf_as_a_whole(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
49 self.logger.debug("Adding new vnf to the NFVO database")
50 tries = 2
51 while tries:
52 created_time = time.time()
53 try:
54 with self.con:
55
56 myVNFDict = {}
57 myVNFDict["name"] = vnf_name
58 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
59 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
60 myVNFDict["description"] = vnf_descriptor['vnf']['description']
61 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
62 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
63
64 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
65 #print "Adding new vms to the NFVO database"
66 #For each vm, we must create the appropriate vm in the NFVO database.
67 vmDict = {}
68 for _,vm in VNFCDict.iteritems():
69 #This code could make the name of the vms grow and grow.
70 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
71 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
72 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
73 vm["vnf_id"] = vnf_id
74 created_time += 0.00001
75 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
76 #print "Internal vm id in NFVO DB: %s" % vm_id
77 vmDict[vm['name']] = vm_id
78
79 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
80 bridgeInterfacesDict = {}
81 for vm in vnf_descriptor['vnf']['VNFC']:
82 if 'bridge-ifaces' in vm:
83 bridgeInterfacesDict[vm['name']] = {}
84 for bridgeiface in vm['bridge-ifaces']:
85 created_time += 0.00001
86 if 'port-security' in bridgeiface:
87 bridgeiface['port_security'] = bridgeiface.pop('port-security')
88 if 'floating-ip' in bridgeiface:
89 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
90 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
91 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = {}
92 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['vpci'] = bridgeiface.get('vpci',None)
93 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['mac'] = bridgeiface.get('mac_address',None)
94 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['bw'] = bridgeiface.get('bandwidth', None)
95 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['model'] = bridgeiface.get('model', None)
96 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['port_security'] = \
97 int(bridgeiface.get('port_security', True))
98 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['floating_ip'] = \
99 int(bridgeiface.get('floating_ip', False))
100 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['created_time'] = created_time
101
102 # Collect the data interfaces of each VM/VNFC under the 'numas' field
103 dataifacesDict = {}
104 for vm in vnf_descriptor['vnf']['VNFC']:
105 dataifacesDict[vm['name']] = {}
106 for numa in vm.get('numas', []):
107 for dataiface in numa.get('interfaces', []):
108 created_time += 0.00001
109 db_base._convert_bandwidth(dataiface, logger=self.logger)
110 dataifacesDict[vm['name']][dataiface['name']] = {}
111 dataifacesDict[vm['name']][dataiface['name']]['vpci'] = dataiface.get('vpci')
112 dataifacesDict[vm['name']][dataiface['name']]['bw'] = dataiface['bandwidth']
113 dataifacesDict[vm['name']][dataiface['name']]['model'] = "PF" if dataiface[
114 'dedicated'] == "yes" else (
115 "VF" if dataiface['dedicated'] == "no" else "VFnotShared")
116 dataifacesDict[vm['name']][dataiface['name']]['created_time'] = created_time
117
118 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
119 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
120 internalconnList = []
121 if 'internal-connections' in vnf_descriptor['vnf']:
122 for net in vnf_descriptor['vnf']['internal-connections']:
123 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
124
125 myNetDict = {}
126 myNetDict["name"] = net['name']
127 myNetDict["description"] = net['description']
128 myNetDict["type"] = net['type']
129 myNetDict["vnf_id"] = vnf_id
130
131 created_time += 0.00001
132 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
133
134 for element in net['elements']:
135 ifaceItem = {}
136 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
137 ifaceItem["internal_name"] = element['local_iface_name']
138 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
139 ifaceItem["vm_id"] = vmDict[element['VNFC']]
140 ifaceItem["net_id"] = net_id
141 ifaceItem["type"] = net['type']
142 if ifaceItem ["type"] == "data":
143 dataiface = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
144 ifaceItem["vpci"] = dataiface['vpci']
145 ifaceItem["bw"] = dataiface['bw']
146 ifaceItem["model"] = dataiface['model']
147 created_time_iface = dataiface['created_time']
148 else:
149 bridgeiface = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
150 ifaceItem["vpci"] = bridgeiface['vpci']
151 ifaceItem["mac"] = bridgeiface['mac']
152 ifaceItem["bw"] = bridgeiface['bw']
153 ifaceItem["model"] = bridgeiface['model']
154 ifaceItem["port_security"] = bridgeiface['port_security']
155 ifaceItem["floating_ip"] = bridgeiface['floating_ip']
156 created_time_iface = bridgeiface['created_time']
157 internalconnList.append(ifaceItem)
158 #print "Internal net id in NFVO DB: %s" % net_id
159
160 #print "Adding internal interfaces to the NFVO database (if any)"
161 for iface in internalconnList:
162 #print "Iface name: %s" % iface['internal_name']
163 iface_id = self._new_row_internal('interfaces', iface, add_uuid=True, root_uuid=vnf_id, created_time = created_time_iface)
164 #print "Iface id in NFVO DB: %s" % iface_id
165
166 #print "Adding external interfaces to the NFVO database"
167 for iface in vnf_descriptor['vnf']['external-connections']:
168 myIfaceDict = {}
169 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
170 myIfaceDict["internal_name"] = iface['local_iface_name']
171 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
172 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
173 myIfaceDict["external_name"] = iface['name']
174 myIfaceDict["type"] = iface['type']
175 if iface["type"] == "data":
176 dataiface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
177 myIfaceDict["vpci"] = dataiface['vpci']
178 myIfaceDict["bw"] = dataiface['bw']
179 myIfaceDict["model"] = dataiface['model']
180 created_time_iface = dataiface['created_time']
181 else:
182 bridgeiface = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
183 myIfaceDict["vpci"] = bridgeiface['vpci']
184 myIfaceDict["bw"] = bridgeiface['bw']
185 myIfaceDict["model"] = bridgeiface['model']
186 myIfaceDict["mac"] = bridgeiface['mac']
187 myIfaceDict["port_security"]= bridgeiface['port_security']
188 myIfaceDict["floating_ip"] = bridgeiface['floating_ip']
189 created_time_iface = bridgeiface['created_time']
190 #print "Iface name: %s" % iface['name']
191 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time = created_time_iface)
192 #print "Iface id in NFVO DB: %s" % iface_id
193
194 return vnf_id
195
196 except (mdb.Error, AttributeError) as e:
197 self._format_error(e, tries)
198 tries -= 1
199
200 def new_vnf_as_a_whole2(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
201 self.logger.debug("Adding new vnf to the NFVO database")
202 tries = 2
203 while tries:
204 created_time = time.time()
205 try:
206 with self.con:
207
208 myVNFDict = {}
209 myVNFDict["name"] = vnf_name
210 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
211 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
212 myVNFDict["description"] = vnf_descriptor['vnf']['description']
213 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
214 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
215
216 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
217 #print "Adding new vms to the NFVO database"
218 #For each vm, we must create the appropriate vm in the NFVO database.
219 vmDict = {}
220 for _,vm in VNFCDict.iteritems():
221 #This code could make the name of the vms grow and grow.
222 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
223 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
224 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
225 vm["vnf_id"] = vnf_id
226 created_time += 0.00001
227 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
228 #print "Internal vm id in NFVO DB: %s" % vm_id
229 vmDict[vm['name']] = vm_id
230
231 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
232 bridgeInterfacesDict = {}
233 for vm in vnf_descriptor['vnf']['VNFC']:
234 if 'bridge-ifaces' in vm:
235 bridgeInterfacesDict[vm['name']] = {}
236 for bridgeiface in vm['bridge-ifaces']:
237 created_time += 0.00001
238 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
239 if 'port-security' in bridgeiface:
240 bridgeiface['port_security'] = bridgeiface.pop('port-security')
241 if 'floating-ip' in bridgeiface:
242 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
243 ifaceDict = {}
244 ifaceDict['vpci'] = bridgeiface.get('vpci',None)
245 ifaceDict['mac'] = bridgeiface.get('mac_address',None)
246 ifaceDict['bw'] = bridgeiface.get('bandwidth', None)
247 ifaceDict['model'] = bridgeiface.get('model', None)
248 ifaceDict['port_security'] = int(bridgeiface.get('port_security', True))
249 ifaceDict['floating_ip'] = int(bridgeiface.get('floating_ip', False))
250 ifaceDict['created_time'] = created_time
251 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = ifaceDict
252
253 # Collect the data interfaces of each VM/VNFC under the 'numas' field
254 dataifacesDict = {}
255 for vm in vnf_descriptor['vnf']['VNFC']:
256 dataifacesDict[vm['name']] = {}
257 for numa in vm.get('numas', []):
258 for dataiface in numa.get('interfaces', []):
259 created_time += 0.00001
260 db_base._convert_bandwidth(dataiface, logger=self.logger)
261 ifaceDict = {}
262 ifaceDict['vpci'] = dataiface.get('vpci')
263 ifaceDict['bw'] = dataiface['bandwidth']
264 ifaceDict['model'] = "PF" if dataiface['dedicated'] == "yes" else \
265 ("VF" if dataiface['dedicated'] == "no" else "VFnotShared")
266 ifaceDict['created_time'] = created_time
267 dataifacesDict[vm['name']][dataiface['name']] = ifaceDict
268
269 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
270 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
271 if 'internal-connections' in vnf_descriptor['vnf']:
272 for net in vnf_descriptor['vnf']['internal-connections']:
273 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
274
275 myNetDict = {}
276 myNetDict["name"] = net['name']
277 myNetDict["description"] = net['description']
278 if (net["implementation"] == "overlay"):
279 net["type"] = "bridge"
280 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
281 elif (net["implementation"] == "underlay"):
282 if (net["type"] == "e-line"):
283 net["type"] = "ptp"
284 elif (net["type"] == "e-lan"):
285 net["type"] = "data"
286 net.pop("implementation")
287 myNetDict["type"] = net['type']
288 myNetDict["vnf_id"] = vnf_id
289
290 created_time += 0.00001
291 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
292
293 if "ip-profile" in net:
294 ip_profile = net["ip-profile"]
295 myIPProfileDict = {}
296 myIPProfileDict["net_id"] = net_id
297 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
298 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
299 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
300 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
301 if ("dhcp" in ip_profile):
302 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
303 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
304 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
305
306 created_time += 0.00001
307 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
308
309 for element in net['elements']:
310 ifaceItem = {}
311 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
312 ifaceItem["internal_name"] = element['local_iface_name']
313 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
314 ifaceItem["vm_id"] = vmDict[element['VNFC']]
315 ifaceItem["net_id"] = net_id
316 ifaceItem["type"] = net['type']
317 ifaceItem["ip_address"] = element.get('ip_address',None)
318 if ifaceItem ["type"] == "data":
319 ifaceDict = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
320 ifaceItem["vpci"] = ifaceDict['vpci']
321 ifaceItem["bw"] = ifaceDict['bw']
322 ifaceItem["model"] = ifaceDict['model']
323 else:
324 ifaceDict = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
325 ifaceItem["vpci"] = ifaceDict['vpci']
326 ifaceItem["mac"] = ifaceDict['mac']
327 ifaceItem["bw"] = ifaceDict['bw']
328 ifaceItem["model"] = ifaceDict['model']
329 ifaceItem["port_security"] = ifaceDict['port_security']
330 ifaceItem["floating_ip"] = ifaceDict['floating_ip']
331 created_time_iface = ifaceDict["created_time"]
332 #print "Iface name: %s" % iface['internal_name']
333 iface_id = self._new_row_internal('interfaces', ifaceItem, add_uuid=True, root_uuid=vnf_id, created_time=created_time_iface)
334 #print "Iface id in NFVO DB: %s" % iface_id
335
336 #print "Adding external interfaces to the NFVO database"
337 for iface in vnf_descriptor['vnf']['external-connections']:
338 myIfaceDict = {}
339 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
340 myIfaceDict["internal_name"] = iface['local_iface_name']
341 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
342 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
343 myIfaceDict["external_name"] = iface['name']
344 myIfaceDict["type"] = iface['type']
345 if iface["type"] == "data":
346 myIfaceDict["vpci"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
347 myIfaceDict["bw"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
348 myIfaceDict["model"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
349 created_time_iface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['created_time']
350 else:
351 myIfaceDict["vpci"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
352 myIfaceDict["bw"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
353 myIfaceDict["model"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
354 myIfaceDict["mac"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['mac']
355 myIfaceDict["port_security"] = \
356 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['port_security']
357 myIfaceDict["floating_ip"] = \
358 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['floating_ip']
359 created_time_iface = bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['created_time']
360 #print "Iface name: %s" % iface['name']
361 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time_iface)
362 #print "Iface id in NFVO DB: %s" % iface_id
363
364 return vnf_id
365
366 except (mdb.Error, AttributeError) as e:
367 self._format_error(e, tries)
368 # except KeyError as e2:
369 # exc_type, exc_obj, exc_tb = sys.exc_info()
370 # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
371 # self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
372 # raise KeyError
373 tries -= 1
374
375 def new_scenario(self, scenario_dict):
376 tries = 2
377 while tries:
378 created_time = time.time()
379 try:
380 with self.con:
381 self.cur = self.con.cursor()
382 tenant_id = scenario_dict.get('tenant_id')
383 #scenario
384 INSERT_={'tenant_id': tenant_id,
385 'name': scenario_dict['name'],
386 'description': scenario_dict['description'],
387 'public': scenario_dict.get('public', "false")}
388
389 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
390 #sce_nets
391 for net in scenario_dict['nets'].values():
392 net_dict={'scenario_id': scenario_uuid}
393 net_dict["name"] = net["name"]
394 net_dict["type"] = net["type"]
395 net_dict["description"] = net.get("description")
396 net_dict["external"] = net.get("external", False)
397 if "graph" in net:
398 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
399 #TODO, must be json because of the GUI, change to yaml
400 net_dict["graph"]=json.dumps(net["graph"])
401 created_time += 0.00001
402 net_uuid = self._new_row_internal('sce_nets', net_dict, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
403 net['uuid']=net_uuid
404
405 if net.get("ip-profile"):
406 ip_profile = net["ip-profile"]
407 myIPProfileDict = {
408 "sce_net_id": net_uuid,
409 "ip_version": ip_profile.get('ip-version', "IPv4"),
410 "subnet_address": ip_profile.get('subnet-address'),
411 "gateway_address": ip_profile.get('gateway-address'),
412 "dns_address": ip_profile.get('dns-address')}
413 if "dhcp" in ip_profile:
414 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled', "true")
415 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address')
416 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count')
417 self._new_row_internal('ip_profiles', myIPProfileDict)
418
419 # sce_vnfs
420 for k, vnf in scenario_dict['vnfs'].items():
421 INSERT_ = {'scenario_id': scenario_uuid,
422 'name': k,
423 'vnf_id': vnf['uuid'],
424 # 'description': scenario_dict['name']
425 'description': vnf['description']}
426 if "graph" in vnf:
427 #I NSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
428 # TODO, must be json because of the GUI, change to yaml
429 INSERT_["graph"] = json.dumps(vnf["graph"])
430 created_time += 0.00001
431 scn_vnf_uuid = self._new_row_internal('sce_vnfs', INSERT_, add_uuid=True,
432 root_uuid=scenario_uuid, created_time=created_time)
433 vnf['scn_vnf_uuid']=scn_vnf_uuid
434 # sce_interfaces
435 for iface in vnf['ifaces'].values():
436 # print 'iface', iface
437 if 'net_key' not in iface:
438 continue
439 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
440 INSERT_={'sce_vnf_id': scn_vnf_uuid,
441 'sce_net_id': iface['net_id'],
442 'interface_id': iface['uuid'],
443 'ip_address': iface.get('ip_address')}
444 created_time += 0.00001
445 iface_uuid = self._new_row_internal('sce_interfaces', INSERT_, add_uuid=True,
446 root_uuid=scenario_uuid, created_time=created_time)
447
448 return scenario_uuid
449
450 except (mdb.Error, AttributeError) as e:
451 self._format_error(e, tries)
452 tries -= 1
453
454 def edit_scenario(self, scenario_dict):
455 tries = 2
456 while tries:
457 modified_time = time.time()
458 item_changed=0
459 try:
460 with self.con:
461 self.cur = self.con.cursor()
462 #check that scenario exist
463 tenant_id = scenario_dict.get('tenant_id')
464 scenario_uuid = scenario_dict['uuid']
465
466 where_text = "uuid='{}'".format(scenario_uuid)
467 if not tenant_id and tenant_id != "any":
468 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
469 cmd = "SELECT * FROM scenarios WHERE "+ where_text
470 self.logger.debug(cmd)
471 self.cur.execute(cmd)
472 self.cur.fetchall()
473 if self.cur.rowcount==0:
474 raise db_base.db_base_Exception("No scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
475 elif self.cur.rowcount>1:
476 raise db_base.db_base_Exception("More than one scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
477
478 #scenario
479 nodes = {}
480 topology = scenario_dict.pop("topology", None)
481 if topology != None and "nodes" in topology:
482 nodes = topology.get("nodes",{})
483 UPDATE_ = {}
484 if "name" in scenario_dict: UPDATE_["name"] = scenario_dict["name"]
485 if "description" in scenario_dict: UPDATE_["description"] = scenario_dict["description"]
486 if len(UPDATE_)>0:
487 WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
488 item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
489 #sce_nets
490 for node_id, node in nodes.items():
491 if "graph" in node:
492 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
493 #TODO, must be json because of the GUI, change to yaml
494 node["graph"] = json.dumps(node["graph"])
495 WHERE_={'scenario_id': scenario_uuid, 'uuid': node_id}
496 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
497 item_changed += self._update_rows('sce_nets', node, WHERE_)
498 item_changed += self._update_rows('sce_vnfs', node, WHERE_, modified_time=modified_time)
499 return item_changed
500
501 except (mdb.Error, AttributeError) as e:
502 self._format_error(e, tries)
503 tries -= 1
504
505 # def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
506 # '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
507 # instance_scenario_id is the uuid or the name if it is not a valid uuid format
508 # Only one scenario isntance must mutch the filtering or an error is returned
509 # '''
510 # print "1******************************************************************"
511 # try:
512 # with self.con:
513 # self.cur = self.con.cursor(mdb.cursors.DictCursor)
514 # #scenario table
515 # where_list=[]
516 # if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
517 # if db_base._check_valid_uuid(instance_scenario_id):
518 # where_list.append( "uuid='" + instance_scenario_id +"'" )
519 # else:
520 # where_list.append( "name='" + instance_scenario_id +"'" )
521 # where_text = " AND ".join(where_list)
522 # self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
523 # rows = self.cur.fetchall()
524 # if self.cur.rowcount==0:
525 # return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
526 # elif self.cur.rowcount>1:
527 # return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
528 # instance_scenario_dict = rows[0]
529 #
530 # #instance_vnfs
531 # self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
532 # instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
533 # for vnf in instance_scenario_dict['instance_vnfs']:
534 # #instance_vms
535 # self.cur.execute("SELECT uuid, vim_vm_id "+
536 # "FROM instance_vms "+
537 # "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
538 # )
539 # vnf['instance_vms'] = self.cur.fetchall()
540 # #instance_nets
541 # self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
542 # instance_scenario_dict['instance_nets'] = self.cur.fetchall()
543 #
544 # #instance_interfaces
545 # 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'] + "'")
546 # instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
547 #
548 # db_base._convert_datetime2str(instance_scenario_dict)
549 # db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
550 # print "2******************************************************************"
551 # return 1, instance_scenario_dict
552 # except (mdb.Error, AttributeError) as e:
553 # print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
554 # return self._format_error(e)
555
556 def get_scenario(self, scenario_id, tenant_id=None, datacenter_id=None):
557 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
558 scenario_id is the uuid or the name if it is not a valid uuid format
559 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
560 Only one scenario must mutch the filtering or an error is returned
561 '''
562 tries = 2
563 while tries:
564 try:
565 with self.con:
566 self.cur = self.con.cursor(mdb.cursors.DictCursor)
567 where_text = "uuid='{}'".format(scenario_id)
568 if not tenant_id and tenant_id != "any":
569 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
570 cmd = "SELECT * FROM scenarios WHERE " + where_text
571 self.logger.debug(cmd)
572 self.cur.execute(cmd)
573 rows = self.cur.fetchall()
574 if self.cur.rowcount==0:
575 raise db_base.db_base_Exception("No scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
576 elif self.cur.rowcount>1:
577 raise db_base.db_base_Exception("More than one scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
578 scenario_dict = rows[0]
579 if scenario_dict["cloud_config"]:
580 scenario_dict["cloud-config"] = yaml.load(scenario_dict["cloud_config"])
581 del scenario_dict["cloud_config"]
582 #sce_vnfs
583 cmd = "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict['uuid'])
584 self.logger.debug(cmd)
585 self.cur.execute(cmd)
586 scenario_dict['vnfs'] = self.cur.fetchall()
587 for vnf in scenario_dict['vnfs']:
588 #sce_interfaces
589 cmd = "SELECT scei.uuid,scei.sce_net_id,scei.interface_id,i.external_name,scei.ip_address"\
590 " FROM sce_interfaces as scei join interfaces as i on scei.interface_id=i.uuid"\
591 " WHERE scei.sce_vnf_id='{}' ORDER BY scei.created_at".format(vnf['uuid'])
592 self.logger.debug(cmd)
593 self.cur.execute(cmd)
594 vnf['interfaces'] = self.cur.fetchall()
595 #vms
596 cmd = "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name," \
597 " vms.description as description, vms.boot_data as boot_data, count," \
598 " vms.availability_zone as availability_zone" \
599 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id" \
600 " WHERE vnfs.uuid='" + vnf['vnf_id'] + "'" \
601 " ORDER BY vms.created_at"
602 self.logger.debug(cmd)
603 self.cur.execute(cmd)
604 vnf['vms'] = self.cur.fetchall()
605 for vm in vnf['vms']:
606 if vm["boot_data"]:
607 vm["boot_data"] = yaml.safe_load(vm["boot_data"])
608 else:
609 del vm["boot_data"]
610 if datacenter_id!=None:
611 cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm['image_id'],datacenter_id)
612 self.logger.debug(cmd)
613 self.cur.execute(cmd)
614 if self.cur.rowcount==1:
615 vim_image_dict = self.cur.fetchone()
616 vm['vim_image_id']=vim_image_dict['vim_id']
617 cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm['flavor_id'],datacenter_id)
618 self.logger.debug(cmd)
619 self.cur.execute(cmd)
620 if self.cur.rowcount==1:
621 vim_flavor_dict = self.cur.fetchone()
622 vm['vim_flavor_id']=vim_flavor_dict['vim_id']
623
624 #interfaces
625 cmd = "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
626 "floating_ip, port_security" \
627 " FROM interfaces" \
628 " WHERE vm_id='{}'" \
629 " ORDER BY created_at".format(vm['uuid'])
630 self.logger.debug(cmd)
631 self.cur.execute(cmd)
632 vm['interfaces'] = self.cur.fetchall()
633 for index in range(0,len(vm['interfaces'])):
634 vm['interfaces'][index]['port-security'] = vm['interfaces'][index].pop("port_security")
635 vm['interfaces'][index]['floating-ip'] = vm['interfaces'][index].pop("floating_ip")
636 #nets every net of a vms
637 cmd = "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf['vnf_id'])
638 self.logger.debug(cmd)
639 self.cur.execute(cmd)
640 vnf['nets'] = self.cur.fetchall()
641 for vnf_net in vnf['nets']:
642 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
643 cmd = "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_,vnf_net['uuid'])
644 self.logger.debug(cmd)
645 self.cur.execute(cmd)
646 ipprofiles = self.cur.fetchall()
647 if self.cur.rowcount==1:
648 vnf_net["ip_profile"] = ipprofiles[0]
649 elif self.cur.rowcount>1:
650 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)
651
652 #sce_nets
653 cmd = "SELECT uuid,name,type,external,description" \
654 " FROM sce_nets WHERE scenario_id='{}'" \
655 " ORDER BY created_at ".format(scenario_dict['uuid'])
656 self.logger.debug(cmd)
657 self.cur.execute(cmd)
658 scenario_dict['nets'] = self.cur.fetchall()
659 #datacenter_nets
660 for net in scenario_dict['nets']:
661 if str(net['external']) == 'false':
662 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
663 cmd = "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_,net['uuid'])
664 self.logger.debug(cmd)
665 self.cur.execute(cmd)
666 ipprofiles = self.cur.fetchall()
667 if self.cur.rowcount==1:
668 net["ip_profile"] = ipprofiles[0]
669 elif self.cur.rowcount>1:
670 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)
671 continue
672 WHERE_=" WHERE name='{}'".format(net['name'])
673 if datacenter_id!=None:
674 WHERE_ += " AND datacenter_id='{}'".format(datacenter_id)
675 cmd = "SELECT vim_net_id FROM datacenter_nets" + WHERE_
676 self.logger.debug(cmd)
677 self.cur.execute(cmd)
678 d_net = self.cur.fetchone()
679 if d_net==None or datacenter_id==None:
680 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
681 net['vim_id']=None
682 else:
683 net['vim_id']=d_net['vim_net_id']
684
685 db_base._convert_datetime2str(scenario_dict)
686 db_base._convert_str2boolean(scenario_dict, ('public','shared','external','port-security','floating-ip') )
687 return scenario_dict
688 except (mdb.Error, AttributeError) as e:
689 self._format_error(e, tries)
690 tries -= 1
691
692 def delete_scenario(self, scenario_id, tenant_id=None):
693 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
694 scenario_id is the uuid or the name if it is not a valid uuid format
695 Only one scenario must mutch the filtering or an error is returned
696 '''
697 tries = 2
698 while tries:
699 try:
700 with self.con:
701 self.cur = self.con.cursor(mdb.cursors.DictCursor)
702
703 #scenario table
704 where_text = "uuid='{}'".format(scenario_id)
705 if not tenant_id and tenant_id != "any":
706 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
707 cmd = "SELECT * FROM scenarios WHERE "+ where_text
708 self.logger.debug(cmd)
709 self.cur.execute(cmd)
710 rows = self.cur.fetchall()
711 if self.cur.rowcount==0:
712 raise db_base.db_base_Exception("No scenario found where " + where_text, db_base.HTTP_Bad_Request)
713 elif self.cur.rowcount>1:
714 raise db_base.db_base_Exception("More than one scenario found where " + where_text, db_base.HTTP_Bad_Request)
715 scenario_uuid = rows[0]["uuid"]
716 scenario_name = rows[0]["name"]
717
718 #sce_vnfs
719 cmd = "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid)
720 self.logger.debug(cmd)
721 self.cur.execute(cmd)
722
723 return scenario_uuid + " " + scenario_name
724 except (mdb.Error, AttributeError) as e:
725 self._format_error(e, tries, "delete", "instances running")
726 tries -= 1
727
728 def new_rows(self, tables, uuid_list=None):
729 """
730 Make a transactional insertion of rows at several tables
731 :param tables: list with dictionary where the keys are the table names and the values are a row or row list
732 with the values to be inserted at the table. Each row is a dictionary with the key values. E.g.:
733 tables = [
734 {"table1": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
735 {"table2": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
736 {"table3": {"column1": value, "column2: value, ... }
737 }
738 :param uuid_list: list of created uuids, first one is the root (#TODO to store at uuid table)
739 :return: None if success, raise exception otherwise
740 """
741 tries = 2
742 while tries:
743 created_time = time.time()
744 try:
745 with self.con:
746 self.cur = self.con.cursor()
747 for table in tables:
748 for table_name, row_list in table.items():
749 index = 0
750 if isinstance(row_list, dict):
751 row_list = (row_list, ) #create a list with the single value
752 for row in row_list:
753 if table_name in self.tables_with_created_field:
754 created_time_param = created_time + index*0.00001
755 else:
756 created_time_param=0
757 self._new_row_internal(table_name, row, add_uuid=False, root_uuid=None,
758 created_time=created_time_param)
759 index += 1
760 return
761 except (mdb.Error, AttributeError) as e:
762 self._format_error(e, tries)
763 tries -= 1
764
765 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
766 tries = 2
767 while tries:
768 created_time = time.time()
769 try:
770 with self.con:
771 self.cur = self.con.cursor()
772 #instance_scenarios
773 datacenter_id = scenarioDict['datacenter_id']
774 INSERT_={'tenant_id': tenant_id,
775 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
776 'name': instance_scenario_name,
777 'description': instance_scenario_description,
778 'scenario_id' : scenarioDict['uuid'],
779 'datacenter_id': datacenter_id
780 }
781 if scenarioDict.get("cloud-config"):
782 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
783
784 instance_uuid = self._new_row_internal('instance_scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
785
786 net_scene2instance={}
787 #instance_nets #nets interVNF
788 for net in scenarioDict['nets']:
789 net_scene2instance[ net['uuid'] ] ={}
790 datacenter_site_id = net.get('datacenter_id', datacenter_id)
791 if not "vim_id_sites" in net:
792 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
793 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
794 sce_net_id = net.get("uuid")
795
796 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
797 INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
798 INSERT_['datacenter_id'] = datacenter_site_id
799 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
800 if not net.get('created', False):
801 INSERT_['status'] = "ACTIVE"
802 if sce_net_id:
803 INSERT_['sce_net_id'] = sce_net_id
804 created_time += 0.00001
805 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
806 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
807 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
808
809 if 'ip_profile' in net:
810 net['ip_profile']['net_id'] = None
811 net['ip_profile']['sce_net_id'] = None
812 net['ip_profile']['instance_net_id'] = instance_net_uuid
813 created_time += 0.00001
814 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
815
816 #instance_vnfs
817 for vnf in scenarioDict['vnfs']:
818 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
819 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
820 INSERT_['datacenter_id'] = datacenter_site_id
821 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
822 if vnf.get("uuid"):
823 INSERT_['sce_vnf_id'] = vnf['uuid']
824 created_time += 0.00001
825 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
826 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
827
828 #instance_nets #nets intraVNF
829 for net in vnf['nets']:
830 net_scene2instance[ net['uuid'] ] = {}
831 INSERT_={'vim_net_id': net['vim_id'], 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
832 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
833 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
834 if net.get("uuid"):
835 INSERT_['net_id'] = net['uuid']
836 created_time += 0.00001
837 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
838 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
839 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
840
841 if 'ip_profile' in net:
842 net['ip_profile']['net_id'] = None
843 net['ip_profile']['sce_net_id'] = None
844 net['ip_profile']['instance_net_id'] = instance_net_uuid
845 created_time += 0.00001
846 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
847
848 #instance_vms
849 for vm in vnf['vms']:
850 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
851 created_time += 0.00001
852 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
853 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
854
855 #instance_interfaces
856 for interface in vm['interfaces']:
857 net_id = interface.get('net_id', None)
858 if net_id is None:
859 #check if is connected to a inter VNFs net
860 for iface in vnf['interfaces']:
861 if iface['interface_id'] == interface['uuid']:
862 if 'ip_address' in iface:
863 interface['ip_address'] = iface['ip_address']
864 net_id = iface.get('sce_net_id', None)
865 break
866 if net_id is None:
867 continue
868 interface_type='external' if interface['external_name'] is not None else 'internal'
869 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
870 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
871 'ip_address': interface.get('ip_address'), 'floating_ip': int(interface.get('floating-ip',False)),
872 'port_security': int(interface.get('port-security',True))}
873 #created_time += 0.00001
874 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
875 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
876 return instance_uuid
877 except (mdb.Error, AttributeError) as e:
878 self._format_error(e, tries)
879 tries -= 1
880
881 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
882 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
883 instance_id is the uuid or the name if it is not a valid uuid format
884 Only one instance must mutch the filtering or an error is returned
885 '''
886 tries = 2
887 while tries:
888 try:
889 with self.con:
890 self.cur = self.con.cursor(mdb.cursors.DictCursor)
891 #instance table
892 where_list=[]
893 if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
894 if db_base._check_valid_uuid(instance_id):
895 where_list.append( "inst.uuid='" + instance_id +"'" )
896 else:
897 where_list.append( "inst.name='" + instance_id +"'" )
898 where_text = " AND ".join(where_list)
899 cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
900 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
901 " ,inst.description as description,inst.created_at as created_at" +\
902 " ,inst.cloud_config as 'cloud_config'" +\
903 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
904 " WHERE " + where_text
905 self.logger.debug(cmd)
906 self.cur.execute(cmd)
907 rows = self.cur.fetchall()
908
909 if self.cur.rowcount==0:
910 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
911 elif self.cur.rowcount>1:
912 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
913 instance_dict = rows[0]
914 if instance_dict["cloud_config"]:
915 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
916 del instance_dict["cloud_config"]
917
918 #instance_vnfs
919 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"\
920 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
921 " WHERE iv.instance_scenario_id='{}'" \
922 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
923 self.logger.debug(cmd)
924 self.cur.execute(cmd)
925 instance_dict['vnfs'] = self.cur.fetchall()
926 for vnf in instance_dict['vnfs']:
927 vnf_manage_iface_list=[]
928 #instance vms
929 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
930 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
931 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
932 self.logger.debug(cmd)
933 self.cur.execute(cmd)
934 vnf['vms'] = self.cur.fetchall()
935 for vm in vnf['vms']:
936 vm_manage_iface_list=[]
937 #instance_interfaces
938 cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
939 " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id"\
940 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
941 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
942 self.logger.debug(cmd)
943 self.cur.execute(cmd )
944 vm['interfaces'] = self.cur.fetchall()
945 for iface in vm['interfaces']:
946 if iface["type"] == "mgmt" and iface["ip_address"]:
947 vnf_manage_iface_list.append(iface["ip_address"])
948 vm_manage_iface_list.append(iface["ip_address"])
949 if not verbose:
950 del iface["type"]
951 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
952 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
953
954 #instance_nets
955 #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"
956 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
957 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
958 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
959 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"\
960 " FROM instance_nets" \
961 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
962 self.logger.debug(cmd)
963 self.cur.execute(cmd)
964 instance_dict['nets'] = self.cur.fetchall()
965
966 db_base._convert_datetime2str(instance_dict)
967 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
968 return instance_dict
969 except (mdb.Error, AttributeError) as e:
970 self._format_error(e, tries)
971 tries -= 1
972
973 def delete_instance_scenario(self, instance_id, tenant_id=None):
974 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
975 instance_id is the uuid or the name if it is not a valid uuid format
976 Only one instance_scenario must mutch the filtering or an error is returned
977 '''
978 tries = 2
979 while tries:
980 try:
981 with self.con:
982 self.cur = self.con.cursor(mdb.cursors.DictCursor)
983
984 #instance table
985 where_list=[]
986 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
987 if db_base._check_valid_uuid(instance_id):
988 where_list.append( "uuid='" + instance_id +"'" )
989 else:
990 where_list.append( "name='" + instance_id +"'" )
991 where_text = " AND ".join(where_list)
992 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
993 self.logger.debug(cmd)
994 self.cur.execute(cmd)
995 rows = self.cur.fetchall()
996
997 if self.cur.rowcount==0:
998 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
999 elif self.cur.rowcount>1:
1000 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
1001 instance_uuid = rows[0]["uuid"]
1002 instance_name = rows[0]["name"]
1003
1004 #sce_vnfs
1005 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
1006 self.logger.debug(cmd)
1007 self.cur.execute(cmd)
1008
1009 return instance_uuid + " " + instance_name
1010 except (mdb.Error, AttributeError) as e:
1011 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
1012 tries -= 1
1013
1014 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
1015 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1016 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
1017
1018 def update_instance_scenario(self, instance_scenario_dict):
1019 #TODO:
1020 return
1021
1022 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
1023 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1024 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1025
1026 def update_instance_vnf(self, instance_vnf_dict):
1027 #TODO:
1028 return
1029
1030 def delete_instance_vnf(self, instance_vnf_id):
1031 #TODO:
1032 return
1033
1034 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1035 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1036 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1037
1038 def update_instance_vm(self, instance_vm_dict):
1039 #TODO:
1040 return
1041
1042 def delete_instance_vm(self, instance_vm_id):
1043 #TODO:
1044 return
1045
1046 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1047 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1048
1049 def update_instance_net(self, instance_net_dict):
1050 #TODO:
1051 return
1052
1053 def delete_instance_net(self, instance_net_id):
1054 #TODO:
1055 return
1056
1057 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1058 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1059
1060 def update_instance_interface(self, instance_interface_dict):
1061 #TODO:
1062 return
1063
1064 def delete_instance_interface(self, instance_interface_dict):
1065 #TODO:
1066 return
1067
1068 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1069 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1070 Attribute
1071 datacenter_id: uuid of the datacenter to act upon
1072 table: table where to insert
1073 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1074 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1075 '''
1076 tries = 2
1077 while tries:
1078 created_time = time.time()
1079 try:
1080 with self.con:
1081 self.cur = self.con.cursor()
1082 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1083 self.logger.debug(cmd)
1084 self.cur.execute(cmd)
1085 deleted = self.cur.rowcount
1086 inserted = 0
1087 for new_net in new_net_list:
1088 created_time += 0.00001
1089 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1090 inserted += 1
1091 return inserted, deleted
1092 except (mdb.Error, AttributeError) as e:
1093 self._format_error(e, tries)
1094 tries -= 1
1095
1096