new API v3 that consumes OSM IM models
[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 :param uuid_list: list of created uuids, first one is the root (#TODO to store at uuid table)
740 :return: None if success, raise exception otherwise
741 """
742 tries = 2
743 while tries:
744 created_time = time.time()
745 try:
746 with self.con:
747 self.cur = self.con.cursor()
748 for table in tables:
749 for table_name, row_list in table.items():
750 index = 0
751 if isinstance(row_list, dict):
752 row_list = (row_list, ) #create a list with the single value
753 for row in row_list:
754 if table_name in self.tables_with_created_field:
755 created_time_param = created_time + index*0.00001
756 else:
757 created_time_param=0
758 self._new_row_internal(table_name, row, add_uuid=False, root_uuid=None,
759 created_time=created_time_param)
760 index += 1
761 return
762 except (mdb.Error, AttributeError) as e:
763 self._format_error(e, tries)
764 tries -= 1
765
766 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
767 tries = 2
768 while tries:
769 created_time = time.time()
770 try:
771 with self.con:
772 self.cur = self.con.cursor()
773 #instance_scenarios
774 datacenter_id = scenarioDict['datacenter_id']
775 INSERT_={'tenant_id': tenant_id,
776 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
777 'name': instance_scenario_name,
778 'description': instance_scenario_description,
779 'scenario_id' : scenarioDict['uuid'],
780 'datacenter_id': datacenter_id
781 }
782 if scenarioDict.get("cloud-config"):
783 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
784
785 instance_uuid = self._new_row_internal('instance_scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
786
787 net_scene2instance={}
788 #instance_nets #nets interVNF
789 for net in scenarioDict['nets']:
790 net_scene2instance[ net['uuid'] ] ={}
791 datacenter_site_id = net.get('datacenter_id', datacenter_id)
792 if not "vim_id_sites" in net:
793 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
794 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
795 sce_net_id = net.get("uuid")
796
797 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
798 INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
799 INSERT_['datacenter_id'] = datacenter_site_id
800 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
801 if not net.get('created', False):
802 INSERT_['status'] = "ACTIVE"
803 if sce_net_id:
804 INSERT_['sce_net_id'] = sce_net_id
805 created_time += 0.00001
806 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
807 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
808 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
809
810 if 'ip_profile' in net:
811 net['ip_profile']['net_id'] = None
812 net['ip_profile']['sce_net_id'] = None
813 net['ip_profile']['instance_net_id'] = instance_net_uuid
814 created_time += 0.00001
815 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
816
817 #instance_vnfs
818 for vnf in scenarioDict['vnfs']:
819 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
820 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
821 INSERT_['datacenter_id'] = datacenter_site_id
822 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
823 if vnf.get("uuid"):
824 INSERT_['sce_vnf_id'] = vnf['uuid']
825 created_time += 0.00001
826 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
827 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
828
829 #instance_nets #nets intraVNF
830 for net in vnf['nets']:
831 net_scene2instance[ net['uuid'] ] = {}
832 INSERT_={'vim_net_id': net['vim_id'], 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
833 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
834 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
835 if net.get("uuid"):
836 INSERT_['net_id'] = net['uuid']
837 created_time += 0.00001
838 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
839 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
840 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
841
842 if 'ip_profile' in net:
843 net['ip_profile']['net_id'] = None
844 net['ip_profile']['sce_net_id'] = None
845 net['ip_profile']['instance_net_id'] = instance_net_uuid
846 created_time += 0.00001
847 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
848
849 #instance_vms
850 for vm in vnf['vms']:
851 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
852 created_time += 0.00001
853 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
854 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
855
856 #instance_interfaces
857 for interface in vm['interfaces']:
858 net_id = interface.get('net_id', None)
859 if net_id is None:
860 #check if is connected to a inter VNFs net
861 for iface in vnf['interfaces']:
862 if iface['interface_id'] == interface['uuid']:
863 if 'ip_address' in iface:
864 interface['ip_address'] = iface['ip_address']
865 net_id = iface.get('sce_net_id', None)
866 break
867 if net_id is None:
868 continue
869 interface_type='external' if interface['external_name'] is not None else 'internal'
870 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
871 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
872 'ip_address': interface.get('ip_address'), 'floating_ip': int(interface.get('floating-ip',False)),
873 'port_security': int(interface.get('port-security',True))}
874 #created_time += 0.00001
875 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
876 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
877 return instance_uuid
878 except (mdb.Error, AttributeError) as e:
879 self._format_error(e, tries)
880 tries -= 1
881
882 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
883 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
884 instance_id is the uuid or the name if it is not a valid uuid format
885 Only one instance must mutch the filtering or an error is returned
886 '''
887 tries = 2
888 while tries:
889 try:
890 with self.con:
891 self.cur = self.con.cursor(mdb.cursors.DictCursor)
892 #instance table
893 where_list=[]
894 if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
895 if db_base._check_valid_uuid(instance_id):
896 where_list.append( "inst.uuid='" + instance_id +"'" )
897 else:
898 where_list.append( "inst.name='" + instance_id +"'" )
899 where_text = " AND ".join(where_list)
900 cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
901 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
902 " ,inst.description as description,inst.created_at as created_at" +\
903 " ,inst.cloud_config as 'cloud_config'" +\
904 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
905 " WHERE " + where_text
906 self.logger.debug(cmd)
907 self.cur.execute(cmd)
908 rows = self.cur.fetchall()
909
910 if self.cur.rowcount==0:
911 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
912 elif self.cur.rowcount>1:
913 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
914 instance_dict = rows[0]
915 if instance_dict["cloud_config"]:
916 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
917 del instance_dict["cloud_config"]
918
919 #instance_vnfs
920 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"\
921 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
922 " WHERE iv.instance_scenario_id='{}'" \
923 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
924 self.logger.debug(cmd)
925 self.cur.execute(cmd)
926 instance_dict['vnfs'] = self.cur.fetchall()
927 for vnf in instance_dict['vnfs']:
928 vnf_manage_iface_list=[]
929 #instance vms
930 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
931 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
932 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
933 self.logger.debug(cmd)
934 self.cur.execute(cmd)
935 vnf['vms'] = self.cur.fetchall()
936 for vm in vnf['vms']:
937 vm_manage_iface_list=[]
938 #instance_interfaces
939 cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
940 " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id"\
941 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
942 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
943 self.logger.debug(cmd)
944 self.cur.execute(cmd )
945 vm['interfaces'] = self.cur.fetchall()
946 for iface in vm['interfaces']:
947 if iface["type"] == "mgmt" and iface["ip_address"]:
948 vnf_manage_iface_list.append(iface["ip_address"])
949 vm_manage_iface_list.append(iface["ip_address"])
950 if not verbose:
951 del iface["type"]
952 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
953 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
954
955 #instance_nets
956 #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"
957 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
958 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
959 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
960 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"\
961 " FROM instance_nets" \
962 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
963 self.logger.debug(cmd)
964 self.cur.execute(cmd)
965 instance_dict['nets'] = self.cur.fetchall()
966
967 db_base._convert_datetime2str(instance_dict)
968 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
969 return instance_dict
970 except (mdb.Error, AttributeError) as e:
971 self._format_error(e, tries)
972 tries -= 1
973
974 def delete_instance_scenario(self, instance_id, tenant_id=None):
975 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
976 instance_id is the uuid or the name if it is not a valid uuid format
977 Only one instance_scenario must mutch the filtering or an error is returned
978 '''
979 tries = 2
980 while tries:
981 try:
982 with self.con:
983 self.cur = self.con.cursor(mdb.cursors.DictCursor)
984
985 #instance table
986 where_list=[]
987 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
988 if db_base._check_valid_uuid(instance_id):
989 where_list.append( "uuid='" + instance_id +"'" )
990 else:
991 where_list.append( "name='" + instance_id +"'" )
992 where_text = " AND ".join(where_list)
993 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
994 self.logger.debug(cmd)
995 self.cur.execute(cmd)
996 rows = self.cur.fetchall()
997
998 if self.cur.rowcount==0:
999 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
1000 elif self.cur.rowcount>1:
1001 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
1002 instance_uuid = rows[0]["uuid"]
1003 instance_name = rows[0]["name"]
1004
1005 #sce_vnfs
1006 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
1007 self.logger.debug(cmd)
1008 self.cur.execute(cmd)
1009
1010 return instance_uuid + " " + instance_name
1011 except (mdb.Error, AttributeError) as e:
1012 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
1013 tries -= 1
1014
1015 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
1016 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1017 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
1018
1019 def update_instance_scenario(self, instance_scenario_dict):
1020 #TODO:
1021 return
1022
1023 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
1024 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1025 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1026
1027 def update_instance_vnf(self, instance_vnf_dict):
1028 #TODO:
1029 return
1030
1031 def delete_instance_vnf(self, instance_vnf_id):
1032 #TODO:
1033 return
1034
1035 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1036 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1037 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1038
1039 def update_instance_vm(self, instance_vm_dict):
1040 #TODO:
1041 return
1042
1043 def delete_instance_vm(self, instance_vm_id):
1044 #TODO:
1045 return
1046
1047 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1048 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1049
1050 def update_instance_net(self, instance_net_dict):
1051 #TODO:
1052 return
1053
1054 def delete_instance_net(self, instance_net_id):
1055 #TODO:
1056 return
1057
1058 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1059 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1060
1061 def update_instance_interface(self, instance_interface_dict):
1062 #TODO:
1063 return
1064
1065 def delete_instance_interface(self, instance_interface_dict):
1066 #TODO:
1067 return
1068
1069 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1070 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1071 Attribute
1072 datacenter_id: uuid of the datacenter to act upon
1073 table: table where to insert
1074 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1075 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1076 '''
1077 tries = 2
1078 while tries:
1079 created_time = time.time()
1080 try:
1081 with self.con:
1082 self.cur = self.con.cursor()
1083 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1084 self.logger.debug(cmd)
1085 self.cur.execute(cmd)
1086 deleted = self.cur.rowcount
1087 inserted = 0
1088 for new_net in new_net_list:
1089 created_time += 0.00001
1090 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1091 inserted += 1
1092 return inserted, deleted
1093 except (mdb.Error, AttributeError) as e:
1094 self._format_error(e, tries)
1095 tries -= 1
1096
1097