Merge branch '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,member_vnf_index,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' "\
584 "ORDER BY created_at".format(scenario_dict['uuid'])
585 self.logger.debug(cmd)
586 self.cur.execute(cmd)
587 scenario_dict['vnfs'] = self.cur.fetchall()
588 for vnf in scenario_dict['vnfs']:
589 #sce_interfaces
590 cmd = "SELECT scei.uuid,scei.sce_net_id,scei.interface_id,i.external_name,scei.ip_address"\
591 " FROM sce_interfaces as scei join interfaces as i on scei.interface_id=i.uuid"\
592 " WHERE scei.sce_vnf_id='{}' ORDER BY scei.created_at".format(vnf['uuid'])
593 self.logger.debug(cmd)
594 self.cur.execute(cmd)
595 vnf['interfaces'] = self.cur.fetchall()
596 #vms
597 cmd = "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name," \
598 " vms.description as description, vms.boot_data as boot_data, count," \
599 " vms.availability_zone as availability_zone" \
600 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id" \
601 " WHERE vnfs.uuid='" + vnf['vnf_id'] + "'" \
602 " ORDER BY vms.created_at"
603 self.logger.debug(cmd)
604 self.cur.execute(cmd)
605 vnf['vms'] = self.cur.fetchall()
606 for vm in vnf['vms']:
607 if vm["boot_data"]:
608 vm["boot_data"] = yaml.safe_load(vm["boot_data"])
609 else:
610 del vm["boot_data"]
611 if datacenter_id!=None:
612 cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm['image_id'],datacenter_id)
613 self.logger.debug(cmd)
614 self.cur.execute(cmd)
615 if self.cur.rowcount==1:
616 vim_image_dict = self.cur.fetchone()
617 vm['vim_image_id']=vim_image_dict['vim_id']
618 cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm['flavor_id'],datacenter_id)
619 self.logger.debug(cmd)
620 self.cur.execute(cmd)
621 if self.cur.rowcount==1:
622 vim_flavor_dict = self.cur.fetchone()
623 vm['vim_flavor_id']=vim_flavor_dict['vim_id']
624
625 #interfaces
626 cmd = "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
627 "floating_ip, port_security" \
628 " FROM interfaces" \
629 " WHERE vm_id='{}'" \
630 " ORDER BY created_at".format(vm['uuid'])
631 self.logger.debug(cmd)
632 self.cur.execute(cmd)
633 vm['interfaces'] = self.cur.fetchall()
634 for index in range(0,len(vm['interfaces'])):
635 vm['interfaces'][index]['port-security'] = vm['interfaces'][index].pop("port_security")
636 vm['interfaces'][index]['floating-ip'] = vm['interfaces'][index].pop("floating_ip")
637 #nets every net of a vms
638 cmd = "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf['vnf_id'])
639 self.logger.debug(cmd)
640 self.cur.execute(cmd)
641 vnf['nets'] = self.cur.fetchall()
642 for vnf_net in vnf['nets']:
643 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
644 cmd = "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_,vnf_net['uuid'])
645 self.logger.debug(cmd)
646 self.cur.execute(cmd)
647 ipprofiles = self.cur.fetchall()
648 if self.cur.rowcount==1:
649 vnf_net["ip_profile"] = ipprofiles[0]
650 elif self.cur.rowcount>1:
651 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)
652
653 #sce_nets
654 cmd = "SELECT uuid,name,type,external,description" \
655 " FROM sce_nets WHERE scenario_id='{}'" \
656 " ORDER BY created_at ".format(scenario_dict['uuid'])
657 self.logger.debug(cmd)
658 self.cur.execute(cmd)
659 scenario_dict['nets'] = self.cur.fetchall()
660 #datacenter_nets
661 for net in scenario_dict['nets']:
662 if str(net['external']) == 'false':
663 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
664 cmd = "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_,net['uuid'])
665 self.logger.debug(cmd)
666 self.cur.execute(cmd)
667 ipprofiles = self.cur.fetchall()
668 if self.cur.rowcount==1:
669 net["ip_profile"] = ipprofiles[0]
670 elif self.cur.rowcount>1:
671 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)
672 continue
673 WHERE_=" WHERE name='{}'".format(net['name'])
674 if datacenter_id!=None:
675 WHERE_ += " AND datacenter_id='{}'".format(datacenter_id)
676 cmd = "SELECT vim_net_id FROM datacenter_nets" + WHERE_
677 self.logger.debug(cmd)
678 self.cur.execute(cmd)
679 d_net = self.cur.fetchone()
680 if d_net==None or datacenter_id==None:
681 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
682 net['vim_id']=None
683 else:
684 net['vim_id']=d_net['vim_net_id']
685
686 db_base._convert_datetime2str(scenario_dict)
687 db_base._convert_str2boolean(scenario_dict, ('public','shared','external','port-security','floating-ip') )
688 return scenario_dict
689 except (mdb.Error, AttributeError) as e:
690 self._format_error(e, tries)
691 tries -= 1
692
693 def delete_scenario(self, scenario_id, tenant_id=None):
694 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
695 scenario_id is the uuid or the name if it is not a valid uuid format
696 Only one scenario must mutch the filtering or an error is returned
697 '''
698 tries = 2
699 while tries:
700 try:
701 with self.con:
702 self.cur = self.con.cursor(mdb.cursors.DictCursor)
703
704 #scenario table
705 where_text = "uuid='{}'".format(scenario_id)
706 if not tenant_id and tenant_id != "any":
707 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
708 cmd = "SELECT * FROM scenarios WHERE "+ where_text
709 self.logger.debug(cmd)
710 self.cur.execute(cmd)
711 rows = self.cur.fetchall()
712 if self.cur.rowcount==0:
713 raise db_base.db_base_Exception("No scenario found where " + where_text, db_base.HTTP_Bad_Request)
714 elif self.cur.rowcount>1:
715 raise db_base.db_base_Exception("More than one scenario found where " + where_text, db_base.HTTP_Bad_Request)
716 scenario_uuid = rows[0]["uuid"]
717 scenario_name = rows[0]["name"]
718
719 #sce_vnfs
720 cmd = "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid)
721 self.logger.debug(cmd)
722 self.cur.execute(cmd)
723
724 return scenario_uuid + " " + scenario_name
725 except (mdb.Error, AttributeError) as e:
726 self._format_error(e, tries, "delete", "instances running")
727 tries -= 1
728
729 def new_rows(self, tables, uuid_list=None):
730 """
731 Make a transactional insertion of rows at several tables
732 :param tables: list with dictionary where the keys are the table names and the values are a row or row list
733 with the values to be inserted at the table. Each row is a dictionary with the key values. E.g.:
734 tables = [
735 {"table1": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
736 {"table2": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
737 {"table3": {"column1": value, "column2: value, ... }
738 }
739 If tables does not contain the 'created_at', it is generated incrementally with the order of tables. You can
740 provide a integer value, that it is an index multiply by 0.00001 to add to the created time to manually set
741 up and order
742 :param uuid_list: list of created uuids, first one is the root (#TODO to store at uuid table)
743 :return: None if success, raise exception otherwise
744 """
745 tries = 2
746 while tries:
747 created_time = time.time()
748 try:
749 with self.con:
750 self.cur = self.con.cursor()
751 for table in tables:
752 for table_name, row_list in table.items():
753 index = 0
754 if isinstance(row_list, dict):
755 row_list = (row_list, ) #create a list with the single value
756 for row in row_list:
757 if table_name in self.tables_with_created_field:
758 if "created_at" in row:
759 created_time_param = created_time + row.pop("created_at")*0.00001
760 else:
761 created_time_param = created_time + index*0.00001
762 index += 1
763 else:
764 created_time_param = 0
765 self._new_row_internal(table_name, row, add_uuid=False, root_uuid=None,
766 created_time=created_time_param)
767 return
768 except (mdb.Error, AttributeError) as e:
769 self._format_error(e, tries)
770 tries -= 1
771
772 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
773 tries = 2
774 while tries:
775 created_time = time.time()
776 try:
777 with self.con:
778 self.cur = self.con.cursor()
779 #instance_scenarios
780 datacenter_id = scenarioDict['datacenter_id']
781 INSERT_={'tenant_id': tenant_id,
782 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
783 'name': instance_scenario_name,
784 'description': instance_scenario_description,
785 'scenario_id' : scenarioDict['uuid'],
786 'datacenter_id': datacenter_id
787 }
788 if scenarioDict.get("cloud-config"):
789 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
790
791 instance_uuid = self._new_row_internal('instance_scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
792
793 net_scene2instance={}
794 #instance_nets #nets interVNF
795 for net in scenarioDict['nets']:
796 net_scene2instance[ net['uuid'] ] ={}
797 datacenter_site_id = net.get('datacenter_id', datacenter_id)
798 if not "vim_id_sites" in net:
799 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
800 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
801 sce_net_id = net.get("uuid")
802
803 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
804 INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
805 INSERT_['datacenter_id'] = datacenter_site_id
806 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
807 if not net.get('created', False):
808 INSERT_['status'] = "ACTIVE"
809 if sce_net_id:
810 INSERT_['sce_net_id'] = sce_net_id
811 created_time += 0.00001
812 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
813 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
814 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
815
816 if 'ip_profile' in net:
817 net['ip_profile']['net_id'] = None
818 net['ip_profile']['sce_net_id'] = None
819 net['ip_profile']['instance_net_id'] = instance_net_uuid
820 created_time += 0.00001
821 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
822
823 #instance_vnfs
824 for vnf in scenarioDict['vnfs']:
825 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
826 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
827 INSERT_['datacenter_id'] = datacenter_site_id
828 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
829 if vnf.get("uuid"):
830 INSERT_['sce_vnf_id'] = vnf['uuid']
831 created_time += 0.00001
832 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
833 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
834
835 #instance_nets #nets intraVNF
836 for net in vnf['nets']:
837 net_scene2instance[ net['uuid'] ] = {}
838 INSERT_={'vim_net_id': net['vim_id'], 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
839 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
840 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
841 if net.get("uuid"):
842 INSERT_['net_id'] = net['uuid']
843 created_time += 0.00001
844 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
845 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
846 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
847
848 if 'ip_profile' in net:
849 net['ip_profile']['net_id'] = None
850 net['ip_profile']['sce_net_id'] = None
851 net['ip_profile']['instance_net_id'] = instance_net_uuid
852 created_time += 0.00001
853 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
854
855 #instance_vms
856 for vm in vnf['vms']:
857 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
858 created_time += 0.00001
859 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
860 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
861
862 #instance_interfaces
863 for interface in vm['interfaces']:
864 net_id = interface.get('net_id', None)
865 if net_id is None:
866 #check if is connected to a inter VNFs net
867 for iface in vnf['interfaces']:
868 if iface['interface_id'] == interface['uuid']:
869 if 'ip_address' in iface:
870 interface['ip_address'] = iface['ip_address']
871 net_id = iface.get('sce_net_id', None)
872 break
873 if net_id is None:
874 continue
875 interface_type='external' if interface['external_name'] is not None else 'internal'
876 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
877 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
878 'ip_address': interface.get('ip_address'), 'floating_ip': int(interface.get('floating-ip',False)),
879 'port_security': int(interface.get('port-security',True))}
880 #created_time += 0.00001
881 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
882 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
883 return instance_uuid
884 except (mdb.Error, AttributeError) as e:
885 self._format_error(e, tries)
886 tries -= 1
887
888 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
889 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
890 instance_id is the uuid or the name if it is not a valid uuid format
891 Only one instance must mutch the filtering or an error is returned
892 '''
893 tries = 2
894 while tries:
895 try:
896 with self.con:
897 self.cur = self.con.cursor(mdb.cursors.DictCursor)
898 #instance table
899 where_list=[]
900 if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
901 if db_base._check_valid_uuid(instance_id):
902 where_list.append( "inst.uuid='" + instance_id +"'" )
903 else:
904 where_list.append( "inst.name='" + instance_id +"'" )
905 where_text = " AND ".join(where_list)
906 cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
907 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
908 " ,inst.description as description,inst.created_at as created_at" +\
909 " ,inst.cloud_config as 'cloud_config'" +\
910 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
911 " WHERE " + where_text
912 self.logger.debug(cmd)
913 self.cur.execute(cmd)
914 rows = self.cur.fetchall()
915
916 if self.cur.rowcount==0:
917 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
918 elif self.cur.rowcount>1:
919 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
920 instance_dict = rows[0]
921 if instance_dict["cloud_config"]:
922 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
923 del instance_dict["cloud_config"]
924
925 #instance_vnfs
926 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"\
927 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
928 " WHERE iv.instance_scenario_id='{}'" \
929 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
930 self.logger.debug(cmd)
931 self.cur.execute(cmd)
932 instance_dict['vnfs'] = self.cur.fetchall()
933 for vnf in instance_dict['vnfs']:
934 vnf_manage_iface_list=[]
935 #instance vms
936 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
937 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
938 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
939 self.logger.debug(cmd)
940 self.cur.execute(cmd)
941 vnf['vms'] = self.cur.fetchall()
942 for vm in vnf['vms']:
943 vm_manage_iface_list=[]
944 #instance_interfaces
945 cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
946 " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id"\
947 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
948 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
949 self.logger.debug(cmd)
950 self.cur.execute(cmd )
951 vm['interfaces'] = self.cur.fetchall()
952 for iface in vm['interfaces']:
953 if iface["type"] == "mgmt" and iface["ip_address"]:
954 vnf_manage_iface_list.append(iface["ip_address"])
955 vm_manage_iface_list.append(iface["ip_address"])
956 if not verbose:
957 del iface["type"]
958 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
959 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
960
961 #instance_nets
962 #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"
963 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
964 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
965 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
966 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"\
967 " FROM instance_nets" \
968 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
969 self.logger.debug(cmd)
970 self.cur.execute(cmd)
971 instance_dict['nets'] = self.cur.fetchall()
972
973 db_base._convert_datetime2str(instance_dict)
974 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
975 return instance_dict
976 except (mdb.Error, AttributeError) as e:
977 self._format_error(e, tries)
978 tries -= 1
979
980 def delete_instance_scenario(self, instance_id, tenant_id=None):
981 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
982 instance_id is the uuid or the name if it is not a valid uuid format
983 Only one instance_scenario must mutch the filtering or an error is returned
984 '''
985 tries = 2
986 while tries:
987 try:
988 with self.con:
989 self.cur = self.con.cursor(mdb.cursors.DictCursor)
990
991 #instance table
992 where_list=[]
993 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
994 if db_base._check_valid_uuid(instance_id):
995 where_list.append( "uuid='" + instance_id +"'" )
996 else:
997 where_list.append( "name='" + instance_id +"'" )
998 where_text = " AND ".join(where_list)
999 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
1000 self.logger.debug(cmd)
1001 self.cur.execute(cmd)
1002 rows = self.cur.fetchall()
1003
1004 if self.cur.rowcount==0:
1005 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
1006 elif self.cur.rowcount>1:
1007 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
1008 instance_uuid = rows[0]["uuid"]
1009 instance_name = rows[0]["name"]
1010
1011 #sce_vnfs
1012 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
1013 self.logger.debug(cmd)
1014 self.cur.execute(cmd)
1015
1016 return instance_uuid + " " + instance_name
1017 except (mdb.Error, AttributeError) as e:
1018 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
1019 tries -= 1
1020
1021 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
1022 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1023 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
1024
1025 def update_instance_scenario(self, instance_scenario_dict):
1026 #TODO:
1027 return
1028
1029 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
1030 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1031 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1032
1033 def update_instance_vnf(self, instance_vnf_dict):
1034 #TODO:
1035 return
1036
1037 def delete_instance_vnf(self, instance_vnf_id):
1038 #TODO:
1039 return
1040
1041 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1042 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1043 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1044
1045 def update_instance_vm(self, instance_vm_dict):
1046 #TODO:
1047 return
1048
1049 def delete_instance_vm(self, instance_vm_id):
1050 #TODO:
1051 return
1052
1053 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1054 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1055
1056 def update_instance_net(self, instance_net_dict):
1057 #TODO:
1058 return
1059
1060 def delete_instance_net(self, instance_net_id):
1061 #TODO:
1062 return
1063
1064 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1065 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1066
1067 def update_instance_interface(self, instance_interface_dict):
1068 #TODO:
1069 return
1070
1071 def delete_instance_interface(self, instance_interface_dict):
1072 #TODO:
1073 return
1074
1075 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1076 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1077 Attribute
1078 datacenter_id: uuid of the datacenter to act upon
1079 table: table where to insert
1080 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1081 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1082 '''
1083 tries = 2
1084 while tries:
1085 created_time = time.time()
1086 try:
1087 with self.con:
1088 self.cur = self.con.cursor()
1089 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1090 self.logger.debug(cmd)
1091 self.cur.execute(cmd)
1092 deleted = self.cur.rowcount
1093 inserted = 0
1094 for new_net in new_net_list:
1095 created_time += 0.00001
1096 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1097 inserted += 1
1098 return inserted, deleted
1099 except (mdb.Error, AttributeError) as e:
1100 self._format_error(e, tries)
1101 tries -= 1
1102
1103