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