blob: 6ab73e95180e78d62839c1b38982782c89a795e2 [file] [log] [blame]
tierno7edb6752016-03-21 17:37:52 +01001# -*- 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'''
25NFVO 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
tiernof97fd272016-07-11 14:32:37 +020030import db_base
tierno7edb6752016-03-21 17:37:52 +010031import MySQLdb as mdb
tierno7edb6752016-03-21 17:37:52 +010032import json
tiernoa4e1a6e2016-08-31 14:19:40 +020033import yaml
tierno7edb6752016-03-21 17:37:52 +010034import time
tierno4319dad2016-09-05 12:11:11 +020035#import sys, os
tierno7edb6752016-03-21 17:37:52 +010036
tiernof97fd272016-07-11 14:32:37 +020037tables_with_createdat_field=["datacenters","instance_nets","instance_scenarios","instance_vms","instance_vnfs",
tierno7edb6752016-03-21 17:37:52 +010038 "interfaces","nets","nfvo_tenants","scenarios","sce_interfaces","sce_nets",
tierno327465f2016-09-07 09:54:47 +020039 "sce_vnfs","tenants_datacenters","datacenter_tenants","vms","vnfs", "datacenter_nets"]
tierno7edb6752016-03-21 17:37:52 +010040
tiernof97fd272016-07-11 14:32:37 +020041class nfvo_db(db_base.db_base):
tiernob13f3cc2016-09-26 10:14:44 +020042 def __init__(self, host=None, user=None, passwd=None, database=None, log_name='openmano.db', log_level=None):
tiernof97fd272016-07-11 14:32:37 +020043 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
tierno7edb6752016-03-21 17:37:52 +010045 return
46
tierno7edb6752016-03-21 17:37:52 +010047 def new_vnf_as_a_whole(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
tiernof97fd272016-07-11 14:32:37 +020048 self.logger.debug("Adding new vnf to the NFVO database")
49 tries = 2
50 while tries:
tierno7edb6752016-03-21 17:37:52 +010051 created_time = time.time()
52 try:
53 with self.con:
54
55 myVNFDict = {}
56 myVNFDict["name"] = vnf_name
57 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
58 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
59 myVNFDict["description"] = vnf_descriptor['vnf']['description']
60 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
61 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
62
tiernof97fd272016-07-11 14:32:37 +020063 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
64 #print "Adding new vms to the NFVO database"
tierno7edb6752016-03-21 17:37:52 +010065 #For each vm, we must create the appropriate vm in the NFVO database.
66 vmDict = {}
67 for _,vm in VNFCDict.iteritems():
68 #This code could make the name of the vms grow and grow.
69 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
70 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
tiernof97fd272016-07-11 14:32:37 +020071 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
tierno7edb6752016-03-21 17:37:52 +010072 vm["vnf_id"] = vnf_id
73 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +020074 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
75 #print "Internal vm id in NFVO DB: %s" % vm_id
tierno7edb6752016-03-21 17:37:52 +010076 vmDict[vm['name']] = vm_id
77
78 #Collect the data interfaces of each VM/VNFC under the 'numas' field
79 dataifacesDict = {}
80 for vm in vnf_descriptor['vnf']['VNFC']:
81 dataifacesDict[vm['name']] = {}
82 for numa in vm.get('numas', []):
83 for dataiface in numa.get('interfaces',[]):
tierno44528e42016-10-11 12:06:25 +000084 db_base._convert_bandwidth(dataiface, logger=self.logger)
tierno7edb6752016-03-21 17:37:52 +010085 dataifacesDict[vm['name']][dataiface['name']] = {}
86 dataifacesDict[vm['name']][dataiface['name']]['vpci'] = dataiface['vpci']
87 dataifacesDict[vm['name']][dataiface['name']]['bw'] = dataiface['bandwidth']
88 dataifacesDict[vm['name']][dataiface['name']]['model'] = "PF" if dataiface['dedicated']=="yes" else ("VF" if dataiface['dedicated']=="no" else "VFnotShared")
89
90 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
91 bridgeInterfacesDict = {}
92 for vm in vnf_descriptor['vnf']['VNFC']:
93 if 'bridge-ifaces' in vm:
94 bridgeInterfacesDict[vm['name']] = {}
95 for bridgeiface in vm['bridge-ifaces']:
tierno44528e42016-10-11 12:06:25 +000096 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
tierno7edb6752016-03-21 17:37:52 +010097 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = {}
98 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['vpci'] = bridgeiface.get('vpci',None)
99 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['mac'] = bridgeiface.get('mac_address',None)
100 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['bw'] = bridgeiface.get('bandwidth', None)
101 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['model'] = bridgeiface.get('model', None)
102
103 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
tiernof97fd272016-07-11 14:32:37 +0200104 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100105 internalconnList = []
106 if 'internal-connections' in vnf_descriptor['vnf']:
107 for net in vnf_descriptor['vnf']['internal-connections']:
tiernof97fd272016-07-11 14:32:37 +0200108 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
tierno7edb6752016-03-21 17:37:52 +0100109
110 myNetDict = {}
111 myNetDict["name"] = net['name']
112 myNetDict["description"] = net['description']
113 myNetDict["type"] = net['type']
114 myNetDict["vnf_id"] = vnf_id
115
116 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200117 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100118
119 for element in net['elements']:
120 ifaceItem = {}
121 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
122 ifaceItem["internal_name"] = element['local_iface_name']
123 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
124 ifaceItem["vm_id"] = vmDict[element['VNFC']]
125 ifaceItem["net_id"] = net_id
126 ifaceItem["type"] = net['type']
127 if ifaceItem ["type"] == "data":
128 ifaceItem["vpci"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['vpci']
129 ifaceItem["bw"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['bw']
130 ifaceItem["model"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['model']
131 else:
132 ifaceItem["vpci"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['vpci']
133 ifaceItem["mac"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['mac_address']
134 ifaceItem["bw"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['bw']
135 ifaceItem["model"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['model']
136 internalconnList.append(ifaceItem)
tiernof97fd272016-07-11 14:32:37 +0200137 #print "Internal net id in NFVO DB: %s" % net_id
tierno7edb6752016-03-21 17:37:52 +0100138
tiernof97fd272016-07-11 14:32:37 +0200139 #print "Adding internal interfaces to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100140 for iface in internalconnList:
141 print "Iface name: %s" % iface['internal_name']
142 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200143 iface_id = self._new_row_internal('interfaces', iface, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
144 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100145
tiernof97fd272016-07-11 14:32:37 +0200146 #print "Adding external interfaces to the NFVO database"
tierno7edb6752016-03-21 17:37:52 +0100147 for iface in vnf_descriptor['vnf']['external-connections']:
148 myIfaceDict = {}
149 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
150 myIfaceDict["internal_name"] = iface['local_iface_name']
151 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
152 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
153 myIfaceDict["external_name"] = iface['name']
154 myIfaceDict["type"] = iface['type']
155 if iface["type"] == "data":
156 myIfaceDict["vpci"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
157 myIfaceDict["bw"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
158 myIfaceDict["model"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
159 else:
160 myIfaceDict["vpci"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
161 myIfaceDict["bw"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
162 myIfaceDict["model"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
163 myIfaceDict["mac"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['mac']
164 print "Iface name: %s" % iface['name']
165 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200166 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
167 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100168
tiernof97fd272016-07-11 14:32:37 +0200169 return vnf_id
tierno7edb6752016-03-21 17:37:52 +0100170
tiernof97fd272016-07-11 14:32:37 +0200171 except (mdb.Error, AttributeError) as e:
172 self._format_error(e, tries)
173 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100174
garciadeblas9f8456e2016-09-05 05:02:59 +0200175 def new_vnf_as_a_whole2(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
176 self.logger.debug("Adding new vnf to the NFVO database")
177 tries = 2
178 while tries:
179 created_time = time.time()
180 try:
181 with self.con:
182
183 myVNFDict = {}
184 myVNFDict["name"] = vnf_name
185 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
186 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
187 myVNFDict["description"] = vnf_descriptor['vnf']['description']
188 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
189 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
190
191 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
192 #print "Adding new vms to the NFVO database"
193 #For each vm, we must create the appropriate vm in the NFVO database.
194 vmDict = {}
195 for _,vm in VNFCDict.iteritems():
196 #This code could make the name of the vms grow and grow.
197 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
198 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
199 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
200 vm["vnf_id"] = vnf_id
201 created_time += 0.00001
202 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
203 #print "Internal vm id in NFVO DB: %s" % vm_id
204 vmDict[vm['name']] = vm_id
205
206 #Collect the data interfaces of each VM/VNFC under the 'numas' field
207 dataifacesDict = {}
208 for vm in vnf_descriptor['vnf']['VNFC']:
209 dataifacesDict[vm['name']] = {}
210 for numa in vm.get('numas', []):
211 for dataiface in numa.get('interfaces',[]):
tierno44528e42016-10-11 12:06:25 +0000212 db_base._convert_bandwidth(dataiface, logger=self.logger)
garciadeblas9f8456e2016-09-05 05:02:59 +0200213 dataifacesDict[vm['name']][dataiface['name']] = {}
214 dataifacesDict[vm['name']][dataiface['name']]['vpci'] = dataiface['vpci']
215 dataifacesDict[vm['name']][dataiface['name']]['bw'] = dataiface['bandwidth']
216 dataifacesDict[vm['name']][dataiface['name']]['model'] = "PF" if dataiface['dedicated']=="yes" else ("VF" if dataiface['dedicated']=="no" else "VFnotShared")
217
218 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
219 bridgeInterfacesDict = {}
220 for vm in vnf_descriptor['vnf']['VNFC']:
221 if 'bridge-ifaces' in vm:
222 bridgeInterfacesDict[vm['name']] = {}
223 for bridgeiface in vm['bridge-ifaces']:
tierno44528e42016-10-11 12:06:25 +0000224 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
garciadeblas9f8456e2016-09-05 05:02:59 +0200225 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = {}
226 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['vpci'] = bridgeiface.get('vpci',None)
227 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['mac'] = bridgeiface.get('mac_address',None)
228 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['bw'] = bridgeiface.get('bandwidth', None)
229 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['model'] = bridgeiface.get('model', None)
230
231 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
232 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
233 internalconnList = []
234 if 'internal-connections' in vnf_descriptor['vnf']:
235 for net in vnf_descriptor['vnf']['internal-connections']:
236 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
237
238 myNetDict = {}
239 myNetDict["name"] = net['name']
240 myNetDict["description"] = net['description']
241 if (net["implementation"] == "overlay"):
242 net["type"] = "bridge"
243 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
244 elif (net["implementation"] == "underlay"):
245 if (net["type"] == "e-line"):
246 net["type"] = "ptp"
247 elif (net["type"] == "e-lan"):
248 net["type"] = "data"
249 net.pop("implementation")
250 myNetDict["type"] = net['type']
251 myNetDict["vnf_id"] = vnf_id
252
253 created_time += 0.00001
254 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
255
256 if "ip-profile" in net:
257 ip_profile = net["ip-profile"]
258 myIPProfileDict = {}
259 myIPProfileDict["net_id"] = net_id
260 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
261 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
262 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
263 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
264 if ("dhcp" in ip_profile):
265 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
266 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
267 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
268
269 created_time += 0.00001
270 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
271
272 for element in net['elements']:
273 ifaceItem = {}
274 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
275 ifaceItem["internal_name"] = element['local_iface_name']
276 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
277 ifaceItem["vm_id"] = vmDict[element['VNFC']]
278 ifaceItem["net_id"] = net_id
279 ifaceItem["type"] = net['type']
280 ifaceItem["ip_address"] = element.get('ip_address',None)
281 if ifaceItem ["type"] == "data":
282 ifaceItem["vpci"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['vpci']
283 ifaceItem["bw"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['bw']
284 ifaceItem["model"] = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['model']
285 else:
286 ifaceItem["vpci"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['vpci']
287 ifaceItem["mac"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['mac']
288 ifaceItem["bw"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['bw']
289 ifaceItem["model"] = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]['model']
290 internalconnList.append(ifaceItem)
291 #print "Internal net id in NFVO DB: %s" % net_id
292
293 #print "Adding internal interfaces to the NFVO database (if any)"
294 for iface in internalconnList:
295 print "Iface name: %s" % iface['internal_name']
296 created_time += 0.00001
297 iface_id = self._new_row_internal('interfaces', iface, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
298 #print "Iface id in NFVO DB: %s" % iface_id
299
300 #print "Adding external interfaces to the NFVO database"
301 for iface in vnf_descriptor['vnf']['external-connections']:
302 myIfaceDict = {}
303 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
304 myIfaceDict["internal_name"] = iface['local_iface_name']
305 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
306 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
307 myIfaceDict["external_name"] = iface['name']
308 myIfaceDict["type"] = iface['type']
309 if iface["type"] == "data":
310 myIfaceDict["vpci"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
311 myIfaceDict["bw"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
312 myIfaceDict["model"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
313 else:
314 myIfaceDict["vpci"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
315 myIfaceDict["bw"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
316 myIfaceDict["model"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
317 myIfaceDict["mac"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['mac']
318 print "Iface name: %s" % iface['name']
319 created_time += 0.00001
320 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
321 #print "Iface id in NFVO DB: %s" % iface_id
322
323 return vnf_id
324
325 except (mdb.Error, AttributeError) as e:
326 self._format_error(e, tries)
327# except KeyError as e2:
328# exc_type, exc_obj, exc_tb = sys.exc_info()
329# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
330# self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
331# raise KeyError
332 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100333
334 def new_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200335 tries = 2
336 while tries:
tierno7edb6752016-03-21 17:37:52 +0100337 created_time = time.time()
338 try:
339 with self.con:
340 self.cur = self.con.cursor()
341 tenant_id = scenario_dict.get('tenant_id')
342 #scenario
343 INSERT_={'tenant_id': tenant_id,
tiernof97fd272016-07-11 14:32:37 +0200344 'name': scenario_dict['name'],
345 'description': scenario_dict['description'],
346 'public': scenario_dict.get('public', "false")}
tierno7edb6752016-03-21 17:37:52 +0100347
tiernof97fd272016-07-11 14:32:37 +0200348 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100349 #sce_nets
350 for net in scenario_dict['nets'].values():
351 net_dict={'scenario_id': scenario_uuid}
352 net_dict["name"] = net["name"]
353 net_dict["type"] = net["type"]
354 net_dict["description"] = net.get("description")
355 net_dict["external"] = net.get("external", False)
356 if "graph" in net:
357 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
358 #TODO, must be json because of the GUI, change to yaml
359 net_dict["graph"]=json.dumps(net["graph"])
360 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200361 net_uuid = self._new_row_internal('sce_nets', net_dict, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100362 net['uuid']=net_uuid
363 #sce_vnfs
364 for k,vnf in scenario_dict['vnfs'].items():
365 INSERT_={'scenario_id': scenario_uuid,
366 'name': k,
367 'vnf_id': vnf['uuid'],
368 #'description': scenario_dict['name']
369 'description': vnf['description']
370 }
371 if "graph" in vnf:
372 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
373 #TODO, must be json because of the GUI, change to yaml
374 INSERT_["graph"]=json.dumps(vnf["graph"])
375 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200376 scn_vnf_uuid = self._new_row_internal('sce_vnfs', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100377 vnf['scn_vnf_uuid']=scn_vnf_uuid
378 #sce_interfaces
379 for iface in vnf['ifaces'].values():
tiernof97fd272016-07-11 14:32:37 +0200380 #print 'iface', iface
tierno7edb6752016-03-21 17:37:52 +0100381 if 'net_key' not in iface:
382 continue
383 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
384 INSERT_={'sce_vnf_id': scn_vnf_uuid,
385 'sce_net_id': iface['net_id'],
386 'interface_id': iface[ 'uuid' ]
387 }
388 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200389 iface_uuid = self._new_row_internal('sce_interfaces', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100390
tiernof97fd272016-07-11 14:32:37 +0200391 return scenario_uuid
tierno7edb6752016-03-21 17:37:52 +0100392
tiernof97fd272016-07-11 14:32:37 +0200393 except (mdb.Error, AttributeError) as e:
394 self._format_error(e, tries)
395 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100396
garciadeblas9f8456e2016-09-05 05:02:59 +0200397 def new_scenario2(self, scenario_dict):
398 tries = 2
399 while tries:
400 created_time = time.time()
401 try:
402 with self.con:
403 self.cur = self.con.cursor()
404 tenant_id = scenario_dict.get('tenant_id')
405 #scenario
406 INSERT_={'tenant_id': tenant_id,
407 'name': scenario_dict['name'],
408 'description': scenario_dict['description'],
409 'public': scenario_dict.get('public', "false")}
410
411 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
412 #sce_nets
413 for net in scenario_dict['nets'].values():
414 net_dict={'scenario_id': scenario_uuid}
415 net_dict["name"] = net["name"]
416 net_dict["type"] = net["type"]
417 net_dict["description"] = net.get("description")
418 net_dict["external"] = net.get("external", False)
419 if "graph" in net:
420 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
421 #TODO, must be json because of the GUI, change to yaml
422 net_dict["graph"]=json.dumps(net["graph"])
423 created_time += 0.00001
424 net_uuid = self._new_row_internal('sce_nets', net_dict, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
425 net['uuid']=net_uuid
426
427 if "ip-profile" in net:
428 ip_profile = net["ip-profile"]
429 myIPProfileDict = {}
430 myIPProfileDict["sce_net_id"] = net_uuid
431 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
432 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
433 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
434 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
435 if ("dhcp" in ip_profile):
436 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
437 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
438 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
439
440 created_time += 0.00001
441 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
442
443 #sce_vnfs
444 for k,vnf in scenario_dict['vnfs'].items():
445 INSERT_={'scenario_id': scenario_uuid,
446 'name': k,
447 'vnf_id': vnf['uuid'],
448 #'description': scenario_dict['name']
449 'description': vnf['description']
450 }
451 if "graph" in vnf:
452 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
453 #TODO, must be json because of the GUI, change to yaml
454 INSERT_["graph"]=json.dumps(vnf["graph"])
455 created_time += 0.00001
456 scn_vnf_uuid = self._new_row_internal('sce_vnfs', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
457 vnf['scn_vnf_uuid']=scn_vnf_uuid
458 #sce_interfaces
459 for iface in vnf['ifaces'].values():
460 #print 'iface', iface
461 if 'net_key' not in iface:
462 continue
463 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
464 INSERT_={'sce_vnf_id': scn_vnf_uuid,
465 'sce_net_id': iface['net_id'],
466 'interface_id': iface['uuid'],
467 'ip_address': iface['ip_address']
468 }
469 created_time += 0.00001
470 iface_uuid = self._new_row_internal('sce_interfaces', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
471
472 return scenario_uuid
473
474 except (mdb.Error, AttributeError) as e:
475 self._format_error(e, tries)
476# except KeyError as e2:
477# exc_type, exc_obj, exc_tb = sys.exc_info()
478# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
479# self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
480# raise KeyError
481 tries -= 1
482
tierno7edb6752016-03-21 17:37:52 +0100483 def edit_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200484 tries = 2
485 while tries:
tierno7edb6752016-03-21 17:37:52 +0100486 modified_time = time.time()
tiernof97fd272016-07-11 14:32:37 +0200487 item_changed=0
tierno7edb6752016-03-21 17:37:52 +0100488 try:
489 with self.con:
490 self.cur = self.con.cursor()
491 #check that scenario exist
492 tenant_id = scenario_dict.get('tenant_id')
493 scenario_uuid = scenario_dict['uuid']
494
tiernof97fd272016-07-11 14:32:37 +0200495 where_text = "uuid='{}'".format(scenario_uuid)
tierno7edb6752016-03-21 17:37:52 +0100496 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200497 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
498 cmd = "SELECT * FROM scenarios WHERE "+ where_text
499 self.logger.debug(cmd)
500 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100501 self.cur.fetchall()
502 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200503 raise db_base.db_base_Exception("No scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100504 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200505 raise db_base.db_base_Exception("More than one scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100506
507 #scenario
508 nodes = {}
509 topology = scenario_dict.pop("topology", None)
510 if topology != None and "nodes" in topology:
511 nodes = topology.get("nodes",{})
512 UPDATE_ = {}
513 if "name" in scenario_dict: UPDATE_["name"] = scenario_dict["name"]
514 if "description" in scenario_dict: UPDATE_["description"] = scenario_dict["description"]
515 if len(UPDATE_)>0:
516 WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
tiernof97fd272016-07-11 14:32:37 +0200517 item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
tierno7edb6752016-03-21 17:37:52 +0100518 #sce_nets
519 for node_id, node in nodes.items():
520 if "graph" in node:
521 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
522 #TODO, must be json because of the GUI, change to yaml
523 node["graph"] = json.dumps(node["graph"])
524 WHERE_={'scenario_id': scenario_uuid, 'uuid': node_id}
tiernof97fd272016-07-11 14:32:37 +0200525 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
526 item_changed += self._update_rows('sce_nets', node, WHERE_)
527 item_changed += self._update_rows('sce_vnfs', node, WHERE_, modified_time=modified_time)
528 return item_changed
tierno7edb6752016-03-21 17:37:52 +0100529
tiernof97fd272016-07-11 14:32:37 +0200530 except (mdb.Error, AttributeError) as e:
531 self._format_error(e, tries)
532 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100533
534# def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
535# '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
536# instance_scenario_id is the uuid or the name if it is not a valid uuid format
537# Only one scenario isntance must mutch the filtering or an error is returned
538# '''
539# print "1******************************************************************"
540# try:
541# with self.con:
542# self.cur = self.con.cursor(mdb.cursors.DictCursor)
543# #scenario table
544# where_list=[]
545# if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200546# if db_base._check_valid_uuid(instance_scenario_id):
tierno7edb6752016-03-21 17:37:52 +0100547# where_list.append( "uuid='" + instance_scenario_id +"'" )
548# else:
549# where_list.append( "name='" + instance_scenario_id +"'" )
550# where_text = " AND ".join(where_list)
551# self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
552# rows = self.cur.fetchall()
553# if self.cur.rowcount==0:
554# return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
555# elif self.cur.rowcount>1:
556# return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
557# instance_scenario_dict = rows[0]
558#
559# #instance_vnfs
560# self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
561# instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
562# for vnf in instance_scenario_dict['instance_vnfs']:
563# #instance_vms
564# self.cur.execute("SELECT uuid, vim_vm_id "+
565# "FROM instance_vms "+
566# "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
567# )
568# vnf['instance_vms'] = self.cur.fetchall()
569# #instance_nets
570# self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
571# instance_scenario_dict['instance_nets'] = self.cur.fetchall()
572#
573# #instance_interfaces
574# 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'] + "'")
575# instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
576#
tiernof97fd272016-07-11 14:32:37 +0200577# db_base._convert_datetime2str(instance_scenario_dict)
578# db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
tierno7edb6752016-03-21 17:37:52 +0100579# print "2******************************************************************"
580# return 1, instance_scenario_dict
tiernof97fd272016-07-11 14:32:37 +0200581# except (mdb.Error, AttributeError) as e:
tierno7edb6752016-03-21 17:37:52 +0100582# print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
tiernof97fd272016-07-11 14:32:37 +0200583# return self._format_error(e)
tierno7edb6752016-03-21 17:37:52 +0100584
585 def get_scenario(self, scenario_id, tenant_id=None, datacenter_id=None):
586 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
587 scenario_id is the uuid or the name if it is not a valid uuid format
588 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
589 Only one scenario must mutch the filtering or an error is returned
590 '''
tiernof97fd272016-07-11 14:32:37 +0200591 tries = 2
592 while tries:
tierno7edb6752016-03-21 17:37:52 +0100593 try:
594 with self.con:
595 self.cur = self.con.cursor(mdb.cursors.DictCursor)
tiernof97fd272016-07-11 14:32:37 +0200596 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100597 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200598 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
599 cmd = "SELECT * FROM scenarios WHERE " + where_text
600 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100601 self.cur.execute(cmd)
602 rows = self.cur.fetchall()
603 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200604 raise db_base.db_base_Exception("No scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100605 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200606 raise db_base.db_base_Exception("More than one scenario found with this criteria " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100607 scenario_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200608 if scenario_dict["cloud_config"]:
609 scenario_dict["cloud-config"] = yaml.load(scenario_dict["cloud_config"])
610 del scenario_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100611 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200612 cmd = "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict['uuid'])
613 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100614 self.cur.execute(cmd)
615 scenario_dict['vnfs'] = self.cur.fetchall()
616 for vnf in scenario_dict['vnfs']:
617 #sce_interfaces
garciadeblas9f8456e2016-09-05 05:02:59 +0200618 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'])
tiernof97fd272016-07-11 14:32:37 +0200619 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100620 self.cur.execute(cmd)
621 vnf['interfaces'] = self.cur.fetchall()
622 #vms
623 cmd = "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name, vms.description as description " \
624 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id " \
625 " WHERE vnfs.uuid='" + vnf['vnf_id'] +"'" \
626 " ORDER BY vms.created_at"
tiernof97fd272016-07-11 14:32:37 +0200627 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100628 self.cur.execute(cmd)
629 vnf['vms'] = self.cur.fetchall()
630 for vm in vnf['vms']:
631 if datacenter_id!=None:
tiernof97fd272016-07-11 14:32:37 +0200632 cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm['image_id'],datacenter_id)
633 self.logger.debug(cmd)
634 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100635 if self.cur.rowcount==1:
636 vim_image_dict = self.cur.fetchone()
637 vm['vim_image_id']=vim_image_dict['vim_id']
tiernof97fd272016-07-11 14:32:37 +0200638 cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm['flavor_id'],datacenter_id)
639 self.logger.debug(cmd)
640 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100641 if self.cur.rowcount==1:
642 vim_flavor_dict = self.cur.fetchone()
643 vm['vim_flavor_id']=vim_flavor_dict['vim_id']
644
645 #interfaces
garciadeblas9f8456e2016-09-05 05:02:59 +0200646 cmd = "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address" \
tierno7edb6752016-03-21 17:37:52 +0100647 " FROM interfaces" \
tiernof97fd272016-07-11 14:32:37 +0200648 " WHERE vm_id='{}'" \
649 " ORDER BY created_at".format(vm['uuid'])
650 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100651 self.cur.execute(cmd)
652 vm['interfaces'] = self.cur.fetchall()
653 #nets every net of a vms
tiernof97fd272016-07-11 14:32:37 +0200654 cmd = "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf['vnf_id'])
655 self.logger.debug(cmd)
656 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100657 vnf['nets'] = self.cur.fetchall()
garciadeblas9f8456e2016-09-05 05:02:59 +0200658 for vnf_net in vnf['nets']:
659 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
660 cmd = "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_,vnf_net['uuid'])
661 self.logger.debug(cmd)
662 self.cur.execute(cmd)
663 ipprofiles = self.cur.fetchall()
664 if self.cur.rowcount==1:
665 vnf_net["ip_profile"] = ipprofiles[0]
666 elif self.cur.rowcount>1:
667 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)
668
tierno7edb6752016-03-21 17:37:52 +0100669 #sce_nets
670 cmd = "SELECT uuid,name,type,external,description" \
tiernof97fd272016-07-11 14:32:37 +0200671 " FROM sce_nets WHERE scenario_id='{}'" \
672 " ORDER BY created_at ".format(scenario_dict['uuid'])
673 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100674 self.cur.execute(cmd)
675 scenario_dict['nets'] = self.cur.fetchall()
676 #datacenter_nets
677 for net in scenario_dict['nets']:
678 if str(net['external']) == 'false':
garciadeblas9f8456e2016-09-05 05:02:59 +0200679 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
680 cmd = "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_,net['uuid'])
681 self.logger.debug(cmd)
682 self.cur.execute(cmd)
683 ipprofiles = self.cur.fetchall()
684 if self.cur.rowcount==1:
685 net["ip_profile"] = ipprofiles[0]
686 elif self.cur.rowcount>1:
687 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)
tierno7edb6752016-03-21 17:37:52 +0100688 continue
tiernof97fd272016-07-11 14:32:37 +0200689 WHERE_=" WHERE name='{}'".format(net['name'])
tierno7edb6752016-03-21 17:37:52 +0100690 if datacenter_id!=None:
tiernof97fd272016-07-11 14:32:37 +0200691 WHERE_ += " AND datacenter_id='{}'".format(datacenter_id)
692 cmd = "SELECT vim_net_id FROM datacenter_nets" + WHERE_
693 self.logger.debug(cmd)
694 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100695 d_net = self.cur.fetchone()
696 if d_net==None or datacenter_id==None:
697 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
698 net['vim_id']=None
699 else:
700 net['vim_id']=d_net['vim_net_id']
701
tiernof97fd272016-07-11 14:32:37 +0200702 db_base._convert_datetime2str(scenario_dict)
703 db_base._convert_str2boolean(scenario_dict, ('public','shared','external') )
704 return scenario_dict
705 except (mdb.Error, AttributeError) as e:
706 self._format_error(e, tries)
707 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100708
tierno7edb6752016-03-21 17:37:52 +0100709 def delete_scenario(self, scenario_id, tenant_id=None):
710 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
711 scenario_id is the uuid or the name if it is not a valid uuid format
712 Only one scenario must mutch the filtering or an error is returned
713 '''
tiernof97fd272016-07-11 14:32:37 +0200714 tries = 2
715 while tries:
tierno7edb6752016-03-21 17:37:52 +0100716 try:
717 with self.con:
718 self.cur = self.con.cursor(mdb.cursors.DictCursor)
719
720 #scenario table
tiernof97fd272016-07-11 14:32:37 +0200721 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100722 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200723 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
724 cmd = "SELECT * FROM scenarios WHERE "+ where_text
725 self.logger.debug(cmd)
726 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100727 rows = self.cur.fetchall()
728 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200729 raise db_base.db_base_Exception("No scenario found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100730 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200731 raise db_base.db_base_Exception("More than one scenario found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100732 scenario_uuid = rows[0]["uuid"]
733 scenario_name = rows[0]["name"]
734
735 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200736 cmd = "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid)
737 self.logger.debug(cmd)
738 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100739
tiernof97fd272016-07-11 14:32:37 +0200740 return scenario_uuid + " " + scenario_name
741 except (mdb.Error, AttributeError) as e:
742 self._format_error(e, tries, "delete", "instances running")
743 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100744
745 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
tiernof97fd272016-07-11 14:32:37 +0200746 tries = 2
747 while tries:
tierno7edb6752016-03-21 17:37:52 +0100748 created_time = time.time()
749 try:
750 with self.con:
751 self.cur = self.con.cursor()
752 #instance_scenarios
tierno7edb6752016-03-21 17:37:52 +0100753 datacenter_id = scenarioDict['datacenter_id']
754 INSERT_={'tenant_id': tenant_id,
tiernoa2793912016-10-04 08:15:08 +0000755 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
tierno7edb6752016-03-21 17:37:52 +0100756 'name': instance_scenario_name,
757 'description': instance_scenario_description,
758 'scenario_id' : scenarioDict['uuid'],
759 'datacenter_id': datacenter_id
760 }
tiernoa4e1a6e2016-08-31 14:19:40 +0200761 if scenarioDict.get("cloud-config"):
762 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
763
tiernof97fd272016-07-11 14:32:37 +0200764 instance_uuid = self._new_row_internal('instance_scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100765
766 net_scene2instance={}
767 #instance_nets #nets interVNF
768 for net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +0200769 net_scene2instance[ net['uuid'] ] ={}
770 datacenter_site_id = net.get('datacenter_id', datacenter_id)
771 if not "vim_id_sites" in net:
772 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
tiernoa2793912016-10-04 08:15:08 +0000773 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
tiernobe41e222016-09-02 15:16:13 +0200774 sce_net_id = net.get("uuid")
775
776 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
tierno66345bc2016-09-26 11:37:55 +0200777 INSERT_={'vim_net_id': vim_id, 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
tiernobe41e222016-09-02 15:16:13 +0200778 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000779 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tiernobe41e222016-09-02 15:16:13 +0200780 if sce_net_id:
781 INSERT_['sce_net_id'] = sce_net_id
782 created_time += 0.00001
783 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
784 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
785 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200786
787 if 'ip_profile' in net:
788 net['ip_profile']['net_id'] = None
789 net['ip_profile']['sce_net_id'] = None
790 net['ip_profile']['instance_net_id'] = instance_net_uuid
791 created_time += 0.00001
792 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
tierno7edb6752016-03-21 17:37:52 +0100793
794 #instance_vnfs
795 for vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +0200796 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
tierno7edb6752016-03-21 17:37:52 +0100797 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
tiernobe41e222016-09-02 15:16:13 +0200798 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000799 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tierno7edb6752016-03-21 17:37:52 +0100800 if vnf.get("uuid"):
801 INSERT_['sce_vnf_id'] = vnf['uuid']
802 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200803 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100804 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
805
806 #instance_nets #nets intraVNF
807 for net in vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +0200808 net_scene2instance[ net['uuid'] ] = {}
tierno66345bc2016-09-26 11:37:55 +0200809 INSERT_={'vim_net_id': net['vim_id'], 'created': net.get('created', False), 'instance_scenario_id':instance_uuid } #, 'type': net['type']
tiernobe41e222016-09-02 15:16:13 +0200810 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
tiernoa2793912016-10-04 08:15:08 +0000811 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +0100812 if net.get("uuid"):
813 INSERT_['net_id'] = net['uuid']
814 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200815 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
tiernobe41e222016-09-02 15:16:13 +0200816 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
tierno7edb6752016-03-21 17:37:52 +0100817 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200818
819 if 'ip_profile' in net:
820 net['ip_profile']['net_id'] = None
821 net['ip_profile']['sce_net_id'] = None
822 net['ip_profile']['instance_net_id'] = instance_net_uuid
823 created_time += 0.00001
824 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
825
tierno7edb6752016-03-21 17:37:52 +0100826 #instance_vms
827 for vm in vnf['vms']:
828 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
829 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200830 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100831 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
832
833 #instance_interfaces
834 for interface in vm['interfaces']:
835 net_id = interface.get('net_id', None)
836 if net_id is None:
837 #check if is connected to a inter VNFs net
838 for iface in vnf['interfaces']:
839 if iface['interface_id'] == interface['uuid']:
garciadeblas9f8456e2016-09-05 05:02:59 +0200840 if 'ip_address' in iface:
841 interface['ip_address'] = iface['ip_address']
tierno7edb6752016-03-21 17:37:52 +0100842 net_id = iface.get('sce_net_id', None)
843 break
844 if net_id is None:
845 continue
846 interface_type='external' if interface['external_name'] is not None else 'internal'
tiernobe41e222016-09-02 15:16:13 +0200847 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
garciadeblas9f8456e2016-09-05 05:02:59 +0200848 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
849 'ip_address': interface.get('ip_address') }
tierno7edb6752016-03-21 17:37:52 +0100850 #created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200851 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
tierno7edb6752016-03-21 17:37:52 +0100852 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
tiernof97fd272016-07-11 14:32:37 +0200853 return instance_uuid
854 except (mdb.Error, AttributeError) as e:
855 self._format_error(e, tries)
856 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100857
858 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
859 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
860 instance_id is the uuid or the name if it is not a valid uuid format
861 Only one instance must mutch the filtering or an error is returned
862 '''
tiernof97fd272016-07-11 14:32:37 +0200863 tries = 2
864 while tries:
tierno7edb6752016-03-21 17:37:52 +0100865 try:
866 with self.con:
867 self.cur = self.con.cursor(mdb.cursors.DictCursor)
868 #instance table
869 where_list=[]
870 if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200871 if db_base._check_valid_uuid(instance_id):
tierno7edb6752016-03-21 17:37:52 +0100872 where_list.append( "inst.uuid='" + instance_id +"'" )
873 else:
874 where_list.append( "inst.name='" + instance_id +"'" )
875 where_text = " AND ".join(where_list)
tiernof97fd272016-07-11 14:32:37 +0200876 cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
tierno7edb6752016-03-21 17:37:52 +0100877 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
878 " ,inst.description as description,inst.created_at as created_at" +\
tiernoa4e1a6e2016-08-31 14:19:40 +0200879 " ,inst.cloud_config as 'cloud_config'" +\
tierno7edb6752016-03-21 17:37:52 +0100880 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
881 " WHERE " + where_text
tiernof97fd272016-07-11 14:32:37 +0200882 self.logger.debug(cmd)
883 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100884 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +0200885
tierno7edb6752016-03-21 17:37:52 +0100886 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200887 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100888 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200889 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100890 instance_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200891 if instance_dict["cloud_config"]:
892 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
893 del instance_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100894
895 #instance_vnfs
896 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"\
897 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
tiernof97fd272016-07-11 14:32:37 +0200898 " WHERE iv.instance_scenario_id='{}'" \
899 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
900 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100901 self.cur.execute(cmd)
902 instance_dict['vnfs'] = self.cur.fetchall()
903 for vnf in instance_dict['vnfs']:
904 vnf_manage_iface_list=[]
905 #instance vms
906 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
907 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
tiernof97fd272016-07-11 14:32:37 +0200908 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
909 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100910 self.cur.execute(cmd)
911 vnf['vms'] = self.cur.fetchall()
912 for vm in vnf['vms']:
913 vm_manage_iface_list=[]
914 #instance_interfaces
garciadeblas0c317ee2016-08-29 12:33:06 +0200915 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 "\
tierno7edb6752016-03-21 17:37:52 +0100916 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid "\
tiernof97fd272016-07-11 14:32:37 +0200917 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
918 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100919 self.cur.execute(cmd )
920 vm['interfaces'] = self.cur.fetchall()
921 for iface in vm['interfaces']:
922 if iface["type"] == "mgmt" and iface["ip_address"]:
923 vnf_manage_iface_list.append(iface["ip_address"])
924 vm_manage_iface_list.append(iface["ip_address"])
925 if not verbose:
926 del iface["type"]
927 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
928 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
929
930 #instance_nets
931 #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"
932 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
933 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
934 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
tierno66345bc2016-09-26 11:37:55 +0200935 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"\
tierno7edb6752016-03-21 17:37:52 +0100936 " FROM instance_nets" \
tiernof97fd272016-07-11 14:32:37 +0200937 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
938 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100939 self.cur.execute(cmd)
940 instance_dict['nets'] = self.cur.fetchall()
941
tiernof97fd272016-07-11 14:32:37 +0200942 db_base._convert_datetime2str(instance_dict)
tierno66345bc2016-09-26 11:37:55 +0200943 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
tiernof97fd272016-07-11 14:32:37 +0200944 return instance_dict
945 except (mdb.Error, AttributeError) as e:
946 self._format_error(e, tries)
947 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100948
949 def delete_instance_scenario(self, instance_id, tenant_id=None):
950 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
951 instance_id is the uuid or the name if it is not a valid uuid format
952 Only one instance_scenario must mutch the filtering or an error is returned
953 '''
tiernof97fd272016-07-11 14:32:37 +0200954 tries = 2
955 while tries:
tierno7edb6752016-03-21 17:37:52 +0100956 try:
957 with self.con:
958 self.cur = self.con.cursor(mdb.cursors.DictCursor)
959
960 #instance table
961 where_list=[]
962 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200963 if db_base._check_valid_uuid(instance_id):
tierno7edb6752016-03-21 17:37:52 +0100964 where_list.append( "uuid='" + instance_id +"'" )
965 else:
966 where_list.append( "name='" + instance_id +"'" )
967 where_text = " AND ".join(where_list)
tiernof97fd272016-07-11 14:32:37 +0200968 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
969 self.logger.debug(cmd)
970 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100971 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +0200972
tierno7edb6752016-03-21 17:37:52 +0100973 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200974 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100975 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200976 raise db_base.db_base_Exception("More than one instance found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100977 instance_uuid = rows[0]["uuid"]
978 instance_name = rows[0]["name"]
979
980 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200981 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
982 self.logger.debug(cmd)
983 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100984
tiernof97fd272016-07-11 14:32:37 +0200985 return instance_uuid + " " + instance_name
986 except (mdb.Error, AttributeError) as e:
987 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
988 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100989
990 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
991 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
992 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
993
994 def update_instance_scenario(self, instance_scenario_dict):
995 #TODO:
996 return
997
998 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
999 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1000 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1001
1002 def update_instance_vnf(self, instance_vnf_dict):
1003 #TODO:
1004 return
1005
1006 def delete_instance_vnf(self, instance_vnf_id):
1007 #TODO:
1008 return
1009
1010 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1011 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1012 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1013
1014 def update_instance_vm(self, instance_vm_dict):
1015 #TODO:
1016 return
1017
1018 def delete_instance_vm(self, instance_vm_id):
1019 #TODO:
1020 return
1021
1022 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1023 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1024
1025 def update_instance_net(self, instance_net_dict):
1026 #TODO:
1027 return
1028
1029 def delete_instance_net(self, instance_net_id):
1030 #TODO:
1031 return
1032
1033 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1034 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1035
1036 def update_instance_interface(self, instance_interface_dict):
1037 #TODO:
1038 return
1039
1040 def delete_instance_interface(self, instance_interface_dict):
1041 #TODO:
1042 return
1043
1044 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1045 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1046 Attribute
1047 datacenter_id: uuid of the datacenter to act upon
1048 table: table where to insert
1049 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1050 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1051 '''
tiernof97fd272016-07-11 14:32:37 +02001052 tries = 2
1053 while tries:
tierno7edb6752016-03-21 17:37:52 +01001054 created_time = time.time()
1055 try:
1056 with self.con:
1057 self.cur = self.con.cursor()
tiernof97fd272016-07-11 14:32:37 +02001058 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1059 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +01001060 self.cur.execute(cmd)
1061 deleted = self.cur.rowcount
tiernof97fd272016-07-11 14:32:37 +02001062 inserted = 0
tierno7edb6752016-03-21 17:37:52 +01001063 for new_net in new_net_list:
1064 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +02001065 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1066 inserted += 1
1067 return inserted, deleted
1068 except (mdb.Error, AttributeError) as e:
1069 self._format_error(e, tries)
1070 tries -= 1
1071
tierno7edb6752016-03-21 17:37:52 +01001072