blob: 87e3f1e15da3c1162cf2959b84fbb272ee9d611c [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",
tierno868220c2017-09-26 00:11:05 +020039 "sce_vnfs","tenants_datacenters","datacenter_tenants","vms","vnfs", "datacenter_nets",
Igor D.Ccaadc442017-11-06 12:48:48 +000040 "instance_actions", "vim_actions", "sce_vnffgs", "sce_rsps", "sce_rsp_hops",
41 "sce_classifiers", "sce_classifier_matches", "instance_sfis", "instance_sfs",
42 "instance_classifications", "instance_sfps"]
tierno7edb6752016-03-21 17:37:52 +010043
tierno8e690322017-08-10 15:58:50 +020044
tiernof97fd272016-07-11 14:32:37 +020045class nfvo_db(db_base.db_base):
tiernob13f3cc2016-09-26 10:14:44 +020046 def __init__(self, host=None, user=None, passwd=None, database=None, log_name='openmano.db', log_level=None):
tiernof97fd272016-07-11 14:32:37 +020047 db_base.db_base.__init__(self, host, user, passwd, database, log_name, log_level)
48 db_base.db_base.tables_with_created_field=tables_with_createdat_field
tierno7edb6752016-03-21 17:37:52 +010049 return
50
tierno7edb6752016-03-21 17:37:52 +010051 def new_vnf_as_a_whole(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
tiernof97fd272016-07-11 14:32:37 +020052 self.logger.debug("Adding new vnf to the NFVO database")
53 tries = 2
54 while tries:
tierno7edb6752016-03-21 17:37:52 +010055 created_time = time.time()
56 try:
57 with self.con:
58
59 myVNFDict = {}
60 myVNFDict["name"] = vnf_name
61 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
62 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
63 myVNFDict["description"] = vnf_descriptor['vnf']['description']
64 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
65 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
66
tiernof97fd272016-07-11 14:32:37 +020067 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
68 #print "Adding new vms to the NFVO database"
tierno7edb6752016-03-21 17:37:52 +010069 #For each vm, we must create the appropriate vm in the NFVO database.
70 vmDict = {}
71 for _,vm in VNFCDict.iteritems():
72 #This code could make the name of the vms grow and grow.
73 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
74 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
tiernof97fd272016-07-11 14:32:37 +020075 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
tierno7edb6752016-03-21 17:37:52 +010076 vm["vnf_id"] = vnf_id
77 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +020078 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
79 #print "Internal vm id in NFVO DB: %s" % vm_id
tierno7edb6752016-03-21 17:37:52 +010080 vmDict[vm['name']] = vm_id
81
tierno7edb6752016-03-21 17:37:52 +010082 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
83 bridgeInterfacesDict = {}
84 for vm in vnf_descriptor['vnf']['VNFC']:
85 if 'bridge-ifaces' in vm:
86 bridgeInterfacesDict[vm['name']] = {}
87 for bridgeiface in vm['bridge-ifaces']:
tiernofa51c202017-01-27 14:58:17 +010088 created_time += 0.00001
montesmoreno2a1fc4e2017-01-09 16:46:04 +000089 if 'port-security' in bridgeiface:
90 bridgeiface['port_security'] = bridgeiface.pop('port-security')
91 if 'floating-ip' in bridgeiface:
92 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
tierno44528e42016-10-11 12:06:25 +000093 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
tierno7edb6752016-03-21 17:37:52 +010094 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = {}
95 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['vpci'] = bridgeiface.get('vpci',None)
96 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['mac'] = bridgeiface.get('mac_address',None)
97 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['bw'] = bridgeiface.get('bandwidth', None)
98 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['model'] = bridgeiface.get('model', None)
montesmoreno2a1fc4e2017-01-09 16:46:04 +000099 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['port_security'] = \
100 int(bridgeiface.get('port_security', True))
101 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['floating_ip'] = \
102 int(bridgeiface.get('floating_ip', False))
tiernofa51c202017-01-27 14:58:17 +0100103 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['created_time'] = created_time
104
105 # Collect the data interfaces of each VM/VNFC under the 'numas' field
106 dataifacesDict = {}
107 for vm in vnf_descriptor['vnf']['VNFC']:
108 dataifacesDict[vm['name']] = {}
109 for numa in vm.get('numas', []):
110 for dataiface in numa.get('interfaces', []):
111 created_time += 0.00001
112 db_base._convert_bandwidth(dataiface, logger=self.logger)
113 dataifacesDict[vm['name']][dataiface['name']] = {}
tiernoc3b6d372017-05-30 17:12:00 +0200114 dataifacesDict[vm['name']][dataiface['name']]['vpci'] = dataiface.get('vpci')
tiernofa51c202017-01-27 14:58:17 +0100115 dataifacesDict[vm['name']][dataiface['name']]['bw'] = dataiface['bandwidth']
116 dataifacesDict[vm['name']][dataiface['name']]['model'] = "PF" if dataiface[
117 'dedicated'] == "yes" else (
118 "VF" if dataiface['dedicated'] == "no" else "VFnotShared")
119 dataifacesDict[vm['name']][dataiface['name']]['created_time'] = created_time
120
tierno7edb6752016-03-21 17:37:52 +0100121 #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 +0200122 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100123 internalconnList = []
124 if 'internal-connections' in vnf_descriptor['vnf']:
125 for net in vnf_descriptor['vnf']['internal-connections']:
tiernof97fd272016-07-11 14:32:37 +0200126 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
tierno7edb6752016-03-21 17:37:52 +0100127
128 myNetDict = {}
129 myNetDict["name"] = net['name']
130 myNetDict["description"] = net['description']
131 myNetDict["type"] = net['type']
132 myNetDict["vnf_id"] = vnf_id
133
134 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200135 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 +0100136
137 for element in net['elements']:
138 ifaceItem = {}
139 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
140 ifaceItem["internal_name"] = element['local_iface_name']
141 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
142 ifaceItem["vm_id"] = vmDict[element['VNFC']]
143 ifaceItem["net_id"] = net_id
144 ifaceItem["type"] = net['type']
145 if ifaceItem ["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100146 dataiface = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
147 ifaceItem["vpci"] = dataiface['vpci']
148 ifaceItem["bw"] = dataiface['bw']
149 ifaceItem["model"] = dataiface['model']
150 created_time_iface = dataiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100151 else:
tiernofa51c202017-01-27 14:58:17 +0100152 bridgeiface = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
153 ifaceItem["vpci"] = bridgeiface['vpci']
154 ifaceItem["mac"] = bridgeiface['mac']
155 ifaceItem["bw"] = bridgeiface['bw']
156 ifaceItem["model"] = bridgeiface['model']
157 ifaceItem["port_security"] = bridgeiface['port_security']
158 ifaceItem["floating_ip"] = bridgeiface['floating_ip']
159 created_time_iface = bridgeiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100160 internalconnList.append(ifaceItem)
tiernof97fd272016-07-11 14:32:37 +0200161 #print "Internal net id in NFVO DB: %s" % net_id
tierno7edb6752016-03-21 17:37:52 +0100162
tiernof97fd272016-07-11 14:32:37 +0200163 #print "Adding internal interfaces to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100164 for iface in internalconnList:
tiernofa51c202017-01-27 14:58:17 +0100165 #print "Iface name: %s" % iface['internal_name']
166 iface_id = self._new_row_internal('interfaces', iface, add_uuid=True, root_uuid=vnf_id, created_time = created_time_iface)
tiernof97fd272016-07-11 14:32:37 +0200167 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100168
tiernof97fd272016-07-11 14:32:37 +0200169 #print "Adding external interfaces to the NFVO database"
tierno7edb6752016-03-21 17:37:52 +0100170 for iface in vnf_descriptor['vnf']['external-connections']:
171 myIfaceDict = {}
172 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
173 myIfaceDict["internal_name"] = iface['local_iface_name']
174 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
175 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
176 myIfaceDict["external_name"] = iface['name']
177 myIfaceDict["type"] = iface['type']
178 if iface["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100179 dataiface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
180 myIfaceDict["vpci"] = dataiface['vpci']
181 myIfaceDict["bw"] = dataiface['bw']
182 myIfaceDict["model"] = dataiface['model']
183 created_time_iface = dataiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100184 else:
tiernofa51c202017-01-27 14:58:17 +0100185 bridgeiface = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
186 myIfaceDict["vpci"] = bridgeiface['vpci']
187 myIfaceDict["bw"] = bridgeiface['bw']
188 myIfaceDict["model"] = bridgeiface['model']
189 myIfaceDict["mac"] = bridgeiface['mac']
190 myIfaceDict["port_security"]= bridgeiface['port_security']
191 myIfaceDict["floating_ip"] = bridgeiface['floating_ip']
192 created_time_iface = bridgeiface['created_time']
193 #print "Iface name: %s" % iface['name']
194 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time = created_time_iface)
tiernof97fd272016-07-11 14:32:37 +0200195 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100196
tiernof97fd272016-07-11 14:32:37 +0200197 return vnf_id
tierno7edb6752016-03-21 17:37:52 +0100198
tiernof97fd272016-07-11 14:32:37 +0200199 except (mdb.Error, AttributeError) as e:
200 self._format_error(e, tries)
201 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100202
garciadeblas9f8456e2016-09-05 05:02:59 +0200203 def new_vnf_as_a_whole2(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
204 self.logger.debug("Adding new vnf to the NFVO database")
205 tries = 2
206 while tries:
207 created_time = time.time()
208 try:
209 with self.con:
210
211 myVNFDict = {}
212 myVNFDict["name"] = vnf_name
213 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
214 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
215 myVNFDict["description"] = vnf_descriptor['vnf']['description']
216 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
217 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
gcalvinoe580c7d2017-09-22 14:09:51 +0200218
garciadeblas9f8456e2016-09-05 05:02:59 +0200219 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
220 #print "Adding new vms to the NFVO database"
221 #For each vm, we must create the appropriate vm in the NFVO database.
222 vmDict = {}
223 for _,vm in VNFCDict.iteritems():
224 #This code could make the name of the vms grow and grow.
225 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
226 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
227 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
228 vm["vnf_id"] = vnf_id
229 created_time += 0.00001
230 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
231 #print "Internal vm id in NFVO DB: %s" % vm_id
232 vmDict[vm['name']] = vm_id
233
garciadeblas9f8456e2016-09-05 05:02:59 +0200234 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
235 bridgeInterfacesDict = {}
236 for vm in vnf_descriptor['vnf']['VNFC']:
237 if 'bridge-ifaces' in vm:
238 bridgeInterfacesDict[vm['name']] = {}
239 for bridgeiface in vm['bridge-ifaces']:
tiernofa51c202017-01-27 14:58:17 +0100240 created_time += 0.00001
tierno44528e42016-10-11 12:06:25 +0000241 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000242 if 'port-security' in bridgeiface:
243 bridgeiface['port_security'] = bridgeiface.pop('port-security')
244 if 'floating-ip' in bridgeiface:
245 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
tiernofa51c202017-01-27 14:58:17 +0100246 ifaceDict = {}
247 ifaceDict['vpci'] = bridgeiface.get('vpci',None)
248 ifaceDict['mac'] = bridgeiface.get('mac_address',None)
249 ifaceDict['bw'] = bridgeiface.get('bandwidth', None)
250 ifaceDict['model'] = bridgeiface.get('model', None)
251 ifaceDict['port_security'] = int(bridgeiface.get('port_security', True))
252 ifaceDict['floating_ip'] = int(bridgeiface.get('floating_ip', False))
253 ifaceDict['created_time'] = created_time
254 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = ifaceDict
255
256 # Collect the data interfaces of each VM/VNFC under the 'numas' field
257 dataifacesDict = {}
258 for vm in vnf_descriptor['vnf']['VNFC']:
259 dataifacesDict[vm['name']] = {}
260 for numa in vm.get('numas', []):
261 for dataiface in numa.get('interfaces', []):
262 created_time += 0.00001
263 db_base._convert_bandwidth(dataiface, logger=self.logger)
264 ifaceDict = {}
tiernoc3b6d372017-05-30 17:12:00 +0200265 ifaceDict['vpci'] = dataiface.get('vpci')
tiernofa51c202017-01-27 14:58:17 +0100266 ifaceDict['bw'] = dataiface['bandwidth']
267 ifaceDict['model'] = "PF" if dataiface['dedicated'] == "yes" else \
268 ("VF" if dataiface['dedicated'] == "no" else "VFnotShared")
269 ifaceDict['created_time'] = created_time
270 dataifacesDict[vm['name']][dataiface['name']] = ifaceDict
271
garciadeblas9f8456e2016-09-05 05:02:59 +0200272 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
273 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
garciadeblas9f8456e2016-09-05 05:02:59 +0200274 if 'internal-connections' in vnf_descriptor['vnf']:
275 for net in vnf_descriptor['vnf']['internal-connections']:
276 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
277
278 myNetDict = {}
279 myNetDict["name"] = net['name']
280 myNetDict["description"] = net['description']
281 if (net["implementation"] == "overlay"):
282 net["type"] = "bridge"
283 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
284 elif (net["implementation"] == "underlay"):
285 if (net["type"] == "e-line"):
286 net["type"] = "ptp"
287 elif (net["type"] == "e-lan"):
288 net["type"] = "data"
289 net.pop("implementation")
290 myNetDict["type"] = net['type']
291 myNetDict["vnf_id"] = vnf_id
292
293 created_time += 0.00001
294 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
295
296 if "ip-profile" in net:
297 ip_profile = net["ip-profile"]
298 myIPProfileDict = {}
299 myIPProfileDict["net_id"] = net_id
300 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
301 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
302 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
303 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
304 if ("dhcp" in ip_profile):
305 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
306 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
307 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
308
309 created_time += 0.00001
310 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
311
312 for element in net['elements']:
313 ifaceItem = {}
314 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
315 ifaceItem["internal_name"] = element['local_iface_name']
316 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
317 ifaceItem["vm_id"] = vmDict[element['VNFC']]
318 ifaceItem["net_id"] = net_id
319 ifaceItem["type"] = net['type']
320 ifaceItem["ip_address"] = element.get('ip_address',None)
321 if ifaceItem ["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100322 ifaceDict = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
323 ifaceItem["vpci"] = ifaceDict['vpci']
324 ifaceItem["bw"] = ifaceDict['bw']
325 ifaceItem["model"] = ifaceDict['model']
garciadeblas9f8456e2016-09-05 05:02:59 +0200326 else:
tiernofa51c202017-01-27 14:58:17 +0100327 ifaceDict = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
328 ifaceItem["vpci"] = ifaceDict['vpci']
329 ifaceItem["mac"] = ifaceDict['mac']
330 ifaceItem["bw"] = ifaceDict['bw']
331 ifaceItem["model"] = ifaceDict['model']
332 ifaceItem["port_security"] = ifaceDict['port_security']
333 ifaceItem["floating_ip"] = ifaceDict['floating_ip']
334 created_time_iface = ifaceDict["created_time"]
335 #print "Iface name: %s" % iface['internal_name']
336 iface_id = self._new_row_internal('interfaces', ifaceItem, add_uuid=True, root_uuid=vnf_id, created_time=created_time_iface)
337 #print "Iface id in NFVO DB: %s" % iface_id
garciadeblas9f8456e2016-09-05 05:02:59 +0200338
339 #print "Adding external interfaces to the NFVO database"
340 for iface in vnf_descriptor['vnf']['external-connections']:
341 myIfaceDict = {}
342 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
343 myIfaceDict["internal_name"] = iface['local_iface_name']
344 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
345 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
346 myIfaceDict["external_name"] = iface['name']
347 myIfaceDict["type"] = iface['type']
348 if iface["type"] == "data":
349 myIfaceDict["vpci"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
350 myIfaceDict["bw"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
351 myIfaceDict["model"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
tiernofa51c202017-01-27 14:58:17 +0100352 created_time_iface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['created_time']
garciadeblas9f8456e2016-09-05 05:02:59 +0200353 else:
354 myIfaceDict["vpci"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
355 myIfaceDict["bw"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
356 myIfaceDict["model"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
357 myIfaceDict["mac"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000358 myIfaceDict["port_security"] = \
359 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['port_security']
360 myIfaceDict["floating_ip"] = \
361 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['floating_ip']
tiernofa51c202017-01-27 14:58:17 +0100362 created_time_iface = bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['created_time']
363 #print "Iface name: %s" % iface['name']
364 iface_id = self._new_row_internal('interfaces', myIfaceDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time_iface)
garciadeblas9f8456e2016-09-05 05:02:59 +0200365 #print "Iface id in NFVO DB: %s" % iface_id
366
367 return vnf_id
368
369 except (mdb.Error, AttributeError) as e:
370 self._format_error(e, tries)
371# except KeyError as e2:
372# exc_type, exc_obj, exc_tb = sys.exc_info()
373# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
374# self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
375# raise KeyError
376 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100377
378 def new_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200379 tries = 2
380 while tries:
tierno7edb6752016-03-21 17:37:52 +0100381 created_time = time.time()
382 try:
383 with self.con:
384 self.cur = self.con.cursor()
385 tenant_id = scenario_dict.get('tenant_id')
386 #scenario
387 INSERT_={'tenant_id': tenant_id,
tiernof97fd272016-07-11 14:32:37 +0200388 'name': scenario_dict['name'],
389 'description': scenario_dict['description'],
390 'public': scenario_dict.get('public', "false")}
tierno7edb6752016-03-21 17:37:52 +0100391
tiernof97fd272016-07-11 14:32:37 +0200392 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100393 #sce_nets
394 for net in scenario_dict['nets'].values():
395 net_dict={'scenario_id': scenario_uuid}
396 net_dict["name"] = net["name"]
397 net_dict["type"] = net["type"]
398 net_dict["description"] = net.get("description")
399 net_dict["external"] = net.get("external", False)
400 if "graph" in net:
401 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
402 #TODO, must be json because of the GUI, change to yaml
403 net_dict["graph"]=json.dumps(net["graph"])
404 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200405 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 +0100406 net['uuid']=net_uuid
tierno7edb6752016-03-21 17:37:52 +0100407
tierno5bb59dc2017-02-13 14:53:54 +0100408 if net.get("ip-profile"):
garciadeblas9f8456e2016-09-05 05:02:59 +0200409 ip_profile = net["ip-profile"]
tierno5bb59dc2017-02-13 14:53:54 +0100410 myIPProfileDict = {
411 "sce_net_id": net_uuid,
412 "ip_version": ip_profile.get('ip-version', "IPv4"),
413 "subnet_address": ip_profile.get('subnet-address'),
414 "gateway_address": ip_profile.get('gateway-address'),
415 "dns_address": ip_profile.get('dns-address')}
416 if "dhcp" in ip_profile:
417 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled', "true")
418 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address')
419 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count')
420 self._new_row_internal('ip_profiles', myIPProfileDict)
garciadeblas9f8456e2016-09-05 05:02:59 +0200421
tierno5bb59dc2017-02-13 14:53:54 +0100422 # sce_vnfs
423 for k, vnf in scenario_dict['vnfs'].items():
424 INSERT_ = {'scenario_id': scenario_uuid,
425 'name': k,
426 'vnf_id': vnf['uuid'],
427 # 'description': scenario_dict['name']
428 'description': vnf['description']}
garciadeblas9f8456e2016-09-05 05:02:59 +0200429 if "graph" in vnf:
tierno5bb59dc2017-02-13 14:53:54 +0100430 #I NSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
431 # TODO, must be json because of the GUI, change to yaml
432 INSERT_["graph"] = json.dumps(vnf["graph"])
garciadeblas9f8456e2016-09-05 05:02:59 +0200433 created_time += 0.00001
tierno5bb59dc2017-02-13 14:53:54 +0100434 scn_vnf_uuid = self._new_row_internal('sce_vnfs', INSERT_, add_uuid=True,
435 root_uuid=scenario_uuid, created_time=created_time)
garciadeblas9f8456e2016-09-05 05:02:59 +0200436 vnf['scn_vnf_uuid']=scn_vnf_uuid
tierno5bb59dc2017-02-13 14:53:54 +0100437 # sce_interfaces
garciadeblas9f8456e2016-09-05 05:02:59 +0200438 for iface in vnf['ifaces'].values():
tierno5bb59dc2017-02-13 14:53:54 +0100439 # print 'iface', iface
garciadeblas9f8456e2016-09-05 05:02:59 +0200440 if 'net_key' not in iface:
441 continue
442 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
443 INSERT_={'sce_vnf_id': scn_vnf_uuid,
tierno5bb59dc2017-02-13 14:53:54 +0100444 'sce_net_id': iface['net_id'],
445 'interface_id': iface['uuid'],
446 'ip_address': iface.get('ip_address')}
garciadeblas9f8456e2016-09-05 05:02:59 +0200447 created_time += 0.00001
tierno5bb59dc2017-02-13 14:53:54 +0100448 iface_uuid = self._new_row_internal('sce_interfaces', INSERT_, add_uuid=True,
449 root_uuid=scenario_uuid, created_time=created_time)
garciadeblas9f8456e2016-09-05 05:02:59 +0200450
451 return scenario_uuid
452
453 except (mdb.Error, AttributeError) as e:
454 self._format_error(e, tries)
garciadeblas9f8456e2016-09-05 05:02:59 +0200455 tries -= 1
456
tierno7edb6752016-03-21 17:37:52 +0100457 def edit_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200458 tries = 2
459 while tries:
tierno7edb6752016-03-21 17:37:52 +0100460 modified_time = time.time()
tiernof97fd272016-07-11 14:32:37 +0200461 item_changed=0
tierno7edb6752016-03-21 17:37:52 +0100462 try:
463 with self.con:
464 self.cur = self.con.cursor()
465 #check that scenario exist
466 tenant_id = scenario_dict.get('tenant_id')
467 scenario_uuid = scenario_dict['uuid']
468
tiernof97fd272016-07-11 14:32:37 +0200469 where_text = "uuid='{}'".format(scenario_uuid)
tierno7edb6752016-03-21 17:37:52 +0100470 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200471 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
472 cmd = "SELECT * FROM scenarios WHERE "+ where_text
473 self.logger.debug(cmd)
474 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100475 self.cur.fetchall()
476 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200477 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 +0100478 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200479 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 +0100480
481 #scenario
482 nodes = {}
483 topology = scenario_dict.pop("topology", None)
484 if topology != None and "nodes" in topology:
485 nodes = topology.get("nodes",{})
486 UPDATE_ = {}
487 if "name" in scenario_dict: UPDATE_["name"] = scenario_dict["name"]
488 if "description" in scenario_dict: UPDATE_["description"] = scenario_dict["description"]
489 if len(UPDATE_)>0:
490 WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
tiernof97fd272016-07-11 14:32:37 +0200491 item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
tierno7edb6752016-03-21 17:37:52 +0100492 #sce_nets
493 for node_id, node in nodes.items():
494 if "graph" in node:
495 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
496 #TODO, must be json because of the GUI, change to yaml
497 node["graph"] = json.dumps(node["graph"])
498 WHERE_={'scenario_id': scenario_uuid, 'uuid': node_id}
tiernof97fd272016-07-11 14:32:37 +0200499 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
500 item_changed += self._update_rows('sce_nets', node, WHERE_)
501 item_changed += self._update_rows('sce_vnfs', node, WHERE_, modified_time=modified_time)
502 return item_changed
tierno7edb6752016-03-21 17:37:52 +0100503
tiernof97fd272016-07-11 14:32:37 +0200504 except (mdb.Error, AttributeError) as e:
505 self._format_error(e, tries)
506 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100507
508# def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
509# '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
510# instance_scenario_id is the uuid or the name if it is not a valid uuid format
511# Only one scenario isntance must mutch the filtering or an error is returned
512# '''
513# print "1******************************************************************"
514# try:
515# with self.con:
516# self.cur = self.con.cursor(mdb.cursors.DictCursor)
517# #scenario table
518# where_list=[]
519# if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200520# if db_base._check_valid_uuid(instance_scenario_id):
tierno7edb6752016-03-21 17:37:52 +0100521# where_list.append( "uuid='" + instance_scenario_id +"'" )
522# else:
523# where_list.append( "name='" + instance_scenario_id +"'" )
524# where_text = " AND ".join(where_list)
525# self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
526# rows = self.cur.fetchall()
527# if self.cur.rowcount==0:
528# return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
529# elif self.cur.rowcount>1:
530# return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
531# instance_scenario_dict = rows[0]
532#
533# #instance_vnfs
534# self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
535# instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
536# for vnf in instance_scenario_dict['instance_vnfs']:
537# #instance_vms
538# self.cur.execute("SELECT uuid, vim_vm_id "+
539# "FROM instance_vms "+
540# "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
541# )
542# vnf['instance_vms'] = self.cur.fetchall()
543# #instance_nets
544# self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
545# instance_scenario_dict['instance_nets'] = self.cur.fetchall()
546#
547# #instance_interfaces
548# 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'] + "'")
549# instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
550#
tiernof97fd272016-07-11 14:32:37 +0200551# db_base._convert_datetime2str(instance_scenario_dict)
552# db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
tierno7edb6752016-03-21 17:37:52 +0100553# print "2******************************************************************"
554# return 1, instance_scenario_dict
tiernof97fd272016-07-11 14:32:37 +0200555# except (mdb.Error, AttributeError) as e:
tierno7edb6752016-03-21 17:37:52 +0100556# print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
tiernof97fd272016-07-11 14:32:37 +0200557# return self._format_error(e)
tierno7edb6752016-03-21 17:37:52 +0100558
tierno868220c2017-09-26 00:11:05 +0200559 def get_scenario(self, scenario_id, tenant_id=None, datacenter_vim_id=None, datacenter_id=None):
tierno7edb6752016-03-21 17:37:52 +0100560 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
561 scenario_id is the uuid or the name if it is not a valid uuid format
tierno868220c2017-09-26 00:11:05 +0200562 if datacenter_vim_id,d datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
tierno7edb6752016-03-21 17:37:52 +0100563 Only one scenario must mutch the filtering or an error is returned
564 '''
tiernof97fd272016-07-11 14:32:37 +0200565 tries = 2
566 while tries:
tierno7edb6752016-03-21 17:37:52 +0100567 try:
568 with self.con:
569 self.cur = self.con.cursor(mdb.cursors.DictCursor)
tiernof97fd272016-07-11 14:32:37 +0200570 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100571 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200572 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
573 cmd = "SELECT * FROM scenarios WHERE " + where_text
574 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100575 self.cur.execute(cmd)
576 rows = self.cur.fetchall()
577 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200578 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 +0100579 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200580 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 +0100581 scenario_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200582 if scenario_dict["cloud_config"]:
583 scenario_dict["cloud-config"] = yaml.load(scenario_dict["cloud_config"])
584 del scenario_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100585 #sce_vnfs
tiernof1ba57e2017-09-07 12:23:19 +0200586 cmd = "SELECT uuid,name,member_vnf_index,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' "\
587 "ORDER BY created_at".format(scenario_dict['uuid'])
tiernof97fd272016-07-11 14:32:37 +0200588 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100589 self.cur.execute(cmd)
590 scenario_dict['vnfs'] = self.cur.fetchall()
gcalvinoe580c7d2017-09-22 14:09:51 +0200591
tierno7edb6752016-03-21 17:37:52 +0100592 for vnf in scenario_dict['vnfs']:
gcalvinoe580c7d2017-09-22 14:09:51 +0200593 cmd = "SELECT mgmt_access FROM vnfs WHERE uuid='{}'".format(scenario_dict['vnfs'][0]['vnf_id'])
594 self.logger.debug(cmd)
595 self.cur.execute(cmd)
596 mgmt_access_dict = self.cur.fetchall()
597 if mgmt_access_dict[0].get('mgmt_access'):
598 vnf['mgmt_access'] = yaml.load(mgmt_access_dict[0]['mgmt_access'])
599 else:
600 vnf['mgmt_access'] = None
tierno7edb6752016-03-21 17:37:52 +0100601 #sce_interfaces
tierno8e690322017-08-10 15:58:50 +0200602 cmd = "SELECT scei.uuid,scei.sce_net_id,scei.interface_id,i.external_name,scei.ip_address"\
603 " FROM sce_interfaces as scei join interfaces as i on scei.interface_id=i.uuid"\
604 " WHERE scei.sce_vnf_id='{}' ORDER BY scei.created_at".format(vnf['uuid'])
tiernof97fd272016-07-11 14:32:37 +0200605 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100606 self.cur.execute(cmd)
607 vnf['interfaces'] = self.cur.fetchall()
608 #vms
mirabal29356312017-07-27 12:21:22 +0200609 cmd = "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name," \
tierno8e690322017-08-10 15:58:50 +0200610 " vms.description as description, vms.boot_data as boot_data, count," \
mirabal29356312017-07-27 12:21:22 +0200611 " vms.availability_zone as availability_zone" \
tierno8e690322017-08-10 15:58:50 +0200612 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id" \
613 " WHERE vnfs.uuid='" + vnf['vnf_id'] + "'" \
mirabal29356312017-07-27 12:21:22 +0200614 " ORDER BY vms.created_at"
tiernof97fd272016-07-11 14:32:37 +0200615 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100616 self.cur.execute(cmd)
617 vnf['vms'] = self.cur.fetchall()
618 for vm in vnf['vms']:
tierno36c0b172017-01-12 18:32:28 +0100619 if vm["boot_data"]:
620 vm["boot_data"] = yaml.safe_load(vm["boot_data"])
621 else:
622 del vm["boot_data"]
tierno868220c2017-09-26 00:11:05 +0200623 if datacenter_vim_id!=None:
624 cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_vim_id='{}'".format(vm['image_id'],datacenter_vim_id)
tiernof97fd272016-07-11 14:32:37 +0200625 self.logger.debug(cmd)
626 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100627 if self.cur.rowcount==1:
628 vim_image_dict = self.cur.fetchone()
629 vm['vim_image_id']=vim_image_dict['vim_id']
tierno868220c2017-09-26 00:11:05 +0200630 cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_vim_id='{}'".format(vm['flavor_id'],datacenter_vim_id)
tiernof97fd272016-07-11 14:32:37 +0200631 self.logger.debug(cmd)
632 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100633 if self.cur.rowcount==1:
634 vim_flavor_dict = self.cur.fetchone()
635 vm['vim_flavor_id']=vim_flavor_dict['vim_id']
636
637 #interfaces
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000638 cmd = "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
639 "floating_ip, port_security" \
tierno7edb6752016-03-21 17:37:52 +0100640 " FROM interfaces" \
tiernof97fd272016-07-11 14:32:37 +0200641 " WHERE vm_id='{}'" \
642 " ORDER BY created_at".format(vm['uuid'])
643 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100644 self.cur.execute(cmd)
645 vm['interfaces'] = self.cur.fetchall()
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000646 for index in range(0,len(vm['interfaces'])):
647 vm['interfaces'][index]['port-security'] = vm['interfaces'][index].pop("port_security")
648 vm['interfaces'][index]['floating-ip'] = vm['interfaces'][index].pop("floating_ip")
tierno7edb6752016-03-21 17:37:52 +0100649 #nets every net of a vms
tiernof97fd272016-07-11 14:32:37 +0200650 cmd = "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf['vnf_id'])
651 self.logger.debug(cmd)
652 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100653 vnf['nets'] = self.cur.fetchall()
garciadeblas9f8456e2016-09-05 05:02:59 +0200654 for vnf_net in vnf['nets']:
655 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
656 cmd = "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_,vnf_net['uuid'])
657 self.logger.debug(cmd)
658 self.cur.execute(cmd)
659 ipprofiles = self.cur.fetchall()
660 if self.cur.rowcount==1:
661 vnf_net["ip_profile"] = ipprofiles[0]
662 elif self.cur.rowcount>1:
663 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)
664
tierno7edb6752016-03-21 17:37:52 +0100665 #sce_nets
666 cmd = "SELECT uuid,name,type,external,description" \
tiernof97fd272016-07-11 14:32:37 +0200667 " FROM sce_nets WHERE scenario_id='{}'" \
668 " ORDER BY created_at ".format(scenario_dict['uuid'])
669 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100670 self.cur.execute(cmd)
671 scenario_dict['nets'] = self.cur.fetchall()
672 #datacenter_nets
673 for net in scenario_dict['nets']:
674 if str(net['external']) == 'false':
garciadeblas9f8456e2016-09-05 05:02:59 +0200675 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
676 cmd = "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_,net['uuid'])
677 self.logger.debug(cmd)
678 self.cur.execute(cmd)
679 ipprofiles = self.cur.fetchall()
680 if self.cur.rowcount==1:
681 net["ip_profile"] = ipprofiles[0]
682 elif self.cur.rowcount>1:
683 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 +0100684 continue
tiernof97fd272016-07-11 14:32:37 +0200685 WHERE_=" WHERE name='{}'".format(net['name'])
tierno7edb6752016-03-21 17:37:52 +0100686 if datacenter_id!=None:
tiernof97fd272016-07-11 14:32:37 +0200687 WHERE_ += " AND datacenter_id='{}'".format(datacenter_id)
688 cmd = "SELECT vim_net_id FROM datacenter_nets" + WHERE_
689 self.logger.debug(cmd)
690 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100691 d_net = self.cur.fetchone()
tierno868220c2017-09-26 00:11:05 +0200692 if d_net==None or datacenter_vim_id==None:
tierno7edb6752016-03-21 17:37:52 +0100693 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
694 net['vim_id']=None
695 else:
696 net['vim_id']=d_net['vim_net_id']
697
tiernof97fd272016-07-11 14:32:37 +0200698 db_base._convert_datetime2str(scenario_dict)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000699 db_base._convert_str2boolean(scenario_dict, ('public','shared','external','port-security','floating-ip') )
Igor D.Ccaadc442017-11-06 12:48:48 +0000700
701 #forwarding graphs
702 cmd = "SELECT uuid,name,description,vendor FROM sce_vnffgs WHERE scenario_id='{}' "\
703 "ORDER BY created_at".format(scenario_dict['uuid'])
704 self.logger.debug(cmd)
705 self.cur.execute(cmd)
706 scenario_dict['vnffgs'] = self.cur.fetchall()
707 for vnffg in scenario_dict['vnffgs']:
708 cmd = "SELECT uuid,name FROM sce_rsps WHERE sce_vnffg_id='{}' "\
709 "ORDER BY created_at".format(vnffg['uuid'])
710 self.logger.debug(cmd)
711 self.cur.execute(cmd)
712 vnffg['rsps'] = self.cur.fetchall()
713 for rsp in vnffg['rsps']:
714 cmd = "SELECT uuid,if_order,interface_id,sce_vnf_id FROM sce_rsp_hops WHERE sce_rsp_id='{}' "\
715 "ORDER BY created_at".format(rsp['uuid'])
716 self.logger.debug(cmd)
717 self.cur.execute(cmd)
718 rsp['connection_points'] = self.cur.fetchall();
719 cmd = "SELECT uuid,name,sce_vnf_id,interface_id FROM sce_classifiers WHERE sce_vnffg_id='{}' "\
720 "AND sce_rsp_id='{}' ORDER BY created_at".format(vnffg['uuid'], rsp['uuid'])
721 self.logger.debug(cmd)
722 self.cur.execute(cmd)
723 rsp['classifier'] = self.cur.fetchone();
724 cmd = "SELECT uuid,ip_proto,source_ip,destination_ip,source_port,destination_port FROM sce_classifier_matches "\
725 "WHERE sce_classifier_id='{}' ORDER BY created_at".format(rsp['classifier']['uuid'])
726 self.logger.debug(cmd)
727 self.cur.execute(cmd)
728 rsp['classifier']['matches'] = self.cur.fetchall()
729
tiernof97fd272016-07-11 14:32:37 +0200730 return scenario_dict
731 except (mdb.Error, AttributeError) as e:
732 self._format_error(e, tries)
733 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100734
tierno7edb6752016-03-21 17:37:52 +0100735 def delete_scenario(self, scenario_id, tenant_id=None):
736 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
737 scenario_id is the uuid or the name if it is not a valid uuid format
738 Only one scenario must mutch the filtering or an error is returned
739 '''
tiernof97fd272016-07-11 14:32:37 +0200740 tries = 2
741 while tries:
tierno7edb6752016-03-21 17:37:52 +0100742 try:
743 with self.con:
744 self.cur = self.con.cursor(mdb.cursors.DictCursor)
745
746 #scenario table
tiernof97fd272016-07-11 14:32:37 +0200747 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100748 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200749 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
750 cmd = "SELECT * FROM scenarios WHERE "+ where_text
751 self.logger.debug(cmd)
752 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100753 rows = self.cur.fetchall()
754 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200755 raise db_base.db_base_Exception("No scenario found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100756 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200757 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 +0100758 scenario_uuid = rows[0]["uuid"]
759 scenario_name = rows[0]["name"]
760
761 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200762 cmd = "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid)
763 self.logger.debug(cmd)
764 self.cur.execute(cmd)
gcalvinoe580c7d2017-09-22 14:09:51 +0200765
tiernof97fd272016-07-11 14:32:37 +0200766 return scenario_uuid + " " + scenario_name
767 except (mdb.Error, AttributeError) as e:
768 self._format_error(e, tries, "delete", "instances running")
769 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100770
tierno8e690322017-08-10 15:58:50 +0200771 def new_rows(self, tables, uuid_list=None):
772 """
773 Make a transactional insertion of rows at several tables
774 :param tables: list with dictionary where the keys are the table names and the values are a row or row list
775 with the values to be inserted at the table. Each row is a dictionary with the key values. E.g.:
776 tables = [
777 {"table1": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
778 {"table2": [ {"column1": value, "column2: value, ... }, {"column1": value, "column2: value, ... }, ...],
779 {"table3": {"column1": value, "column2: value, ... }
780 }
tiernoa9550202017-09-22 13:31:35 +0200781 If tables does not contain the 'created_at', it is generated incrementally with the order of tables. You can
782 provide a integer value, that it is an index multiply by 0.00001 to add to the created time to manually set
783 up and order
tierno8e690322017-08-10 15:58:50 +0200784 :param uuid_list: list of created uuids, first one is the root (#TODO to store at uuid table)
785 :return: None if success, raise exception otherwise
786 """
787 tries = 2
788 while tries:
789 created_time = time.time()
790 try:
791 with self.con:
792 self.cur = self.con.cursor()
793 for table in tables:
794 for table_name, row_list in table.items():
795 index = 0
796 if isinstance(row_list, dict):
797 row_list = (row_list, ) #create a list with the single value
798 for row in row_list:
799 if table_name in self.tables_with_created_field:
tiernoa9550202017-09-22 13:31:35 +0200800 if "created_at" in row:
801 created_time_param = created_time + row.pop("created_at")*0.00001
802 else:
803 created_time_param = created_time + index*0.00001
804 index += 1
tierno8e690322017-08-10 15:58:50 +0200805 else:
tiernoa9550202017-09-22 13:31:35 +0200806 created_time_param = 0
tierno8e690322017-08-10 15:58:50 +0200807 self._new_row_internal(table_name, row, add_uuid=False, root_uuid=None,
808 created_time=created_time_param)
tierno8e690322017-08-10 15:58:50 +0200809 return
810 except (mdb.Error, AttributeError) as e:
811 self._format_error(e, tries)
812 tries -= 1
813
tierno7edb6752016-03-21 17:37:52 +0100814 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
tiernof97fd272016-07-11 14:32:37 +0200815 tries = 2
816 while tries:
tierno7edb6752016-03-21 17:37:52 +0100817 created_time = time.time()
818 try:
819 with self.con:
820 self.cur = self.con.cursor()
821 #instance_scenarios
tierno7edb6752016-03-21 17:37:52 +0100822 datacenter_id = scenarioDict['datacenter_id']
823 INSERT_={'tenant_id': tenant_id,
tiernoa2793912016-10-04 08:15:08 +0000824 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
tierno7edb6752016-03-21 17:37:52 +0100825 'name': instance_scenario_name,
826 'description': instance_scenario_description,
827 'scenario_id' : scenarioDict['uuid'],
828 'datacenter_id': datacenter_id
829 }
tiernoa4e1a6e2016-08-31 14:19:40 +0200830 if scenarioDict.get("cloud-config"):
831 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
832
tiernof97fd272016-07-11 14:32:37 +0200833 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 +0100834
835 net_scene2instance={}
836 #instance_nets #nets interVNF
837 for net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +0200838 net_scene2instance[ net['uuid'] ] ={}
839 datacenter_site_id = net.get('datacenter_id', datacenter_id)
840 if not "vim_id_sites" in net:
841 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
tiernoa2793912016-10-04 08:15:08 +0000842 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
tiernobe41e222016-09-02 15:16:13 +0200843 sce_net_id = net.get("uuid")
844
845 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
tierno66345bc2016-09-26 11:37:55 +0200846 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 +0200847 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000848 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tierno91baf982017-03-30 19:37:57 +0200849 if not net.get('created', False):
850 INSERT_['status'] = "ACTIVE"
tiernobe41e222016-09-02 15:16:13 +0200851 if sce_net_id:
852 INSERT_['sce_net_id'] = sce_net_id
853 created_time += 0.00001
854 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
855 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
856 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200857
858 if 'ip_profile' in net:
859 net['ip_profile']['net_id'] = None
860 net['ip_profile']['sce_net_id'] = None
861 net['ip_profile']['instance_net_id'] = instance_net_uuid
862 created_time += 0.00001
863 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
tierno7edb6752016-03-21 17:37:52 +0100864
865 #instance_vnfs
866 for vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +0200867 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
tierno7edb6752016-03-21 17:37:52 +0100868 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
tiernobe41e222016-09-02 15:16:13 +0200869 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000870 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tierno7edb6752016-03-21 17:37:52 +0100871 if vnf.get("uuid"):
872 INSERT_['sce_vnf_id'] = vnf['uuid']
873 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200874 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100875 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
876
877 #instance_nets #nets intraVNF
878 for net in vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +0200879 net_scene2instance[ net['uuid'] ] = {}
tierno66345bc2016-09-26 11:37:55 +0200880 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 +0200881 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
tiernoa2793912016-10-04 08:15:08 +0000882 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +0100883 if net.get("uuid"):
884 INSERT_['net_id'] = net['uuid']
885 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200886 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
tiernobe41e222016-09-02 15:16:13 +0200887 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
tierno7edb6752016-03-21 17:37:52 +0100888 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200889
890 if 'ip_profile' in net:
891 net['ip_profile']['net_id'] = None
892 net['ip_profile']['sce_net_id'] = None
893 net['ip_profile']['instance_net_id'] = instance_net_uuid
894 created_time += 0.00001
895 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
896
tierno7edb6752016-03-21 17:37:52 +0100897 #instance_vms
898 for vm in vnf['vms']:
899 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
900 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200901 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100902 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
903
904 #instance_interfaces
905 for interface in vm['interfaces']:
906 net_id = interface.get('net_id', None)
907 if net_id is None:
908 #check if is connected to a inter VNFs net
909 for iface in vnf['interfaces']:
910 if iface['interface_id'] == interface['uuid']:
garciadeblas9f8456e2016-09-05 05:02:59 +0200911 if 'ip_address' in iface:
912 interface['ip_address'] = iface['ip_address']
tierno7edb6752016-03-21 17:37:52 +0100913 net_id = iface.get('sce_net_id', None)
914 break
915 if net_id is None:
916 continue
917 interface_type='external' if interface['external_name'] is not None else 'internal'
tiernobe41e222016-09-02 15:16:13 +0200918 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
garciadeblas9f8456e2016-09-05 05:02:59 +0200919 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000920 'ip_address': interface.get('ip_address'), 'floating_ip': int(interface.get('floating-ip',False)),
921 'port_security': int(interface.get('port-security',True))}
tierno7edb6752016-03-21 17:37:52 +0100922 #created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200923 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
tierno7edb6752016-03-21 17:37:52 +0100924 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
tiernof97fd272016-07-11 14:32:37 +0200925 return instance_uuid
926 except (mdb.Error, AttributeError) as e:
927 self._format_error(e, tries)
928 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100929
930 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
931 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
932 instance_id is the uuid or the name if it is not a valid uuid format
933 Only one instance must mutch the filtering or an error is returned
934 '''
tiernof97fd272016-07-11 14:32:37 +0200935 tries = 2
936 while tries:
tierno7edb6752016-03-21 17:37:52 +0100937 try:
938 with self.con:
939 self.cur = self.con.cursor(mdb.cursors.DictCursor)
tierno868220c2017-09-26 00:11:05 +0200940 # instance table
tiernoa15c4b92017-10-05 12:41:44 +0200941 where_list = []
942 if tenant_id:
943 where_list.append("inst.tenant_id='{}'".format(tenant_id))
tiernof97fd272016-07-11 14:32:37 +0200944 if db_base._check_valid_uuid(instance_id):
tiernoa15c4b92017-10-05 12:41:44 +0200945 where_list.append("inst.uuid='{}'".format(instance_id))
tierno7edb6752016-03-21 17:37:52 +0100946 else:
tiernoa15c4b92017-10-05 12:41:44 +0200947 where_list.append("inst.name='{}'".format(instance_id))
tierno7edb6752016-03-21 17:37:52 +0100948 where_text = " AND ".join(where_list)
tiernoa15c4b92017-10-05 12:41:44 +0200949 cmd = "SELECT inst.uuid as uuid, inst.name as name, inst.scenario_id as scenario_id, datacenter_id"\
950 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" \
951 " ,inst.description as description, inst.created_at as created_at" \
952 " ,inst.cloud_config as cloud_config" \
953 " FROM instance_scenarios as inst left join scenarios as s on inst.scenario_id=s.uuid" \
tierno7edb6752016-03-21 17:37:52 +0100954 " WHERE " + where_text
tiernof97fd272016-07-11 14:32:37 +0200955 self.logger.debug(cmd)
956 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100957 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +0200958
tiernoa15c4b92017-10-05 12:41:44 +0200959 if self.cur.rowcount == 0:
tiernof97fd272016-07-11 14:32:37 +0200960 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
tiernoa15c4b92017-10-05 12:41:44 +0200961 elif self.cur.rowcount > 1:
962 raise db_base.db_base_Exception("More than one instance found where " + where_text,
963 db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100964 instance_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200965 if instance_dict["cloud_config"]:
966 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
967 del instance_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100968
tiernoa15c4b92017-10-05 12:41:44 +0200969 # instance_vnfs
970 cmd = "SELECT iv.uuid as uuid, iv.vnf_id as vnf_id, sv.name as vnf_name, sce_vnf_id, datacenter_id"\
tiernoce62cc42018-01-25 10:37:16 +0100971 " ,datacenter_tenant_id, v.mgmt_access, sv.member_vnf_index "\
tiernoa15c4b92017-10-05 12:41:44 +0200972 " FROM instance_vnfs as iv left join sce_vnfs as sv "\
973 "on iv.sce_vnf_id=sv.uuid join vnfs as v on iv.vnf_id=v.uuid" \
tiernof97fd272016-07-11 14:32:37 +0200974 " WHERE iv.instance_scenario_id='{}'" \
975 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
976 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100977 self.cur.execute(cmd)
978 instance_dict['vnfs'] = self.cur.fetchall()
979 for vnf in instance_dict['vnfs']:
980 vnf_manage_iface_list=[]
981 #instance vms
gcalvinoe580c7d2017-09-22 14:09:51 +0200982 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name"\
tierno7edb6752016-03-21 17:37:52 +0100983 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
tiernof97fd272016-07-11 14:32:37 +0200984 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
985 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100986 self.cur.execute(cmd)
987 vnf['vms'] = self.cur.fetchall()
988 for vm in vnf['vms']:
989 vm_manage_iface_list=[]
tiernoa15c4b92017-10-05 12:41:44 +0200990 # instance_interfaces
tiernofa51c202017-01-27 14:58:17 +0100991 cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
tierno867ffe92017-03-27 12:50:34 +0200992 " ii.ip_address as ip_address, vim_info, i.type as type, sdn_port_id"\
tiernofa51c202017-01-27 14:58:17 +0100993 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
994 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
tiernof97fd272016-07-11 14:32:37 +0200995 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100996 self.cur.execute(cmd )
997 vm['interfaces'] = self.cur.fetchall()
998 for iface in vm['interfaces']:
999 if iface["type"] == "mgmt" and iface["ip_address"]:
1000 vnf_manage_iface_list.append(iface["ip_address"])
1001 vm_manage_iface_list.append(iface["ip_address"])
1002 if not verbose:
1003 del iface["type"]
1004 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
1005 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
1006
1007 #instance_nets
1008 #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"
1009 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
1010 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
1011 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
Pablo Montes Moreno3fbff9b2017-03-08 11:28:15 +01001012 cmd = "SELECT uuid,vim_net_id,status,error_msg,vim_info,created, sce_net_id, net_id as vnf_net_id, datacenter_id, datacenter_tenant_id, sdn_net_id"\
tierno7edb6752016-03-21 17:37:52 +01001013 " FROM instance_nets" \
tiernof97fd272016-07-11 14:32:37 +02001014 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
1015 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +01001016 self.cur.execute(cmd)
1017 instance_dict['nets'] = self.cur.fetchall()
Igor D.Ccaadc442017-11-06 12:48:48 +00001018
1019 #instance_sfps
1020 cmd = "SELECT uuid,vim_sfp_id,sce_rsp_id,datacenter_id,"\
1021 "datacenter_tenant_id,status,error_msg,vim_info"\
1022 " FROM instance_sfps" \
1023 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
1024 self.logger.debug(cmd)
1025 self.cur.execute(cmd)
1026 instance_dict['sfps'] = self.cur.fetchall()
1027
tierno69b590e2018-03-13 18:52:23 +01001028 # for sfp in instance_dict['sfps']:
1029 #instance_sfs
1030 cmd = "SELECT uuid,vim_sf_id,sce_rsp_hop_id,datacenter_id,"\
1031 "datacenter_tenant_id,status,error_msg,vim_info"\
1032 " FROM instance_sfs" \
1033 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid']) # TODO: replace instance_scenario_id with instance_sfp_id
1034 self.logger.debug(cmd)
1035 self.cur.execute(cmd)
1036 instance_dict['sfs'] = self.cur.fetchall()
Igor D.Ccaadc442017-11-06 12:48:48 +00001037
tierno69b590e2018-03-13 18:52:23 +01001038 #for sf in instance_dict['sfs']:
1039 #instance_sfis
1040 cmd = "SELECT uuid,vim_sfi_id,sce_rsp_hop_id,datacenter_id,"\
1041 "datacenter_tenant_id,status,error_msg,vim_info"\
1042 " FROM instance_sfis" \
1043 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid']) # TODO: replace instance_scenario_id with instance_sf_id
1044 self.logger.debug(cmd)
1045 self.cur.execute(cmd)
1046 instance_dict['sfis'] = self.cur.fetchall()
Igor D.Ccaadc442017-11-06 12:48:48 +00001047# for sfi in instance_dict['sfi']:
1048
1049 #instance_classifications
1050 cmd = "SELECT uuid,vim_classification_id,sce_classifier_match_id,datacenter_id,"\
1051 "datacenter_tenant_id,status,error_msg,vim_info"\
1052 " FROM instance_classifications" \
1053 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
1054 self.logger.debug(cmd)
1055 self.cur.execute(cmd)
1056 instance_dict['classifications'] = self.cur.fetchall()
1057# for classification in instance_dict['classifications']
1058
tiernof97fd272016-07-11 14:32:37 +02001059 db_base._convert_datetime2str(instance_dict)
tierno66345bc2016-09-26 11:37:55 +02001060 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
tiernof97fd272016-07-11 14:32:37 +02001061 return instance_dict
1062 except (mdb.Error, AttributeError) as e:
1063 self._format_error(e, tries)
1064 tries -= 1
tierno7edb6752016-03-21 17:37:52 +01001065
1066 def delete_instance_scenario(self, instance_id, tenant_id=None):
1067 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
1068 instance_id is the uuid or the name if it is not a valid uuid format
1069 Only one instance_scenario must mutch the filtering or an error is returned
1070 '''
tiernof97fd272016-07-11 14:32:37 +02001071 tries = 2
1072 while tries:
tierno7edb6752016-03-21 17:37:52 +01001073 try:
1074 with self.con:
1075 self.cur = self.con.cursor(mdb.cursors.DictCursor)
1076
1077 #instance table
1078 where_list=[]
1079 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +02001080 if db_base._check_valid_uuid(instance_id):
tierno7edb6752016-03-21 17:37:52 +01001081 where_list.append( "uuid='" + instance_id +"'" )
1082 else:
1083 where_list.append( "name='" + instance_id +"'" )
1084 where_text = " AND ".join(where_list)
tiernof97fd272016-07-11 14:32:37 +02001085 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
1086 self.logger.debug(cmd)
1087 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +01001088 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +02001089
tierno7edb6752016-03-21 17:37:52 +01001090 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +02001091 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001092 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +02001093 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 +01001094 instance_uuid = rows[0]["uuid"]
1095 instance_name = rows[0]["name"]
1096
1097 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +02001098 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
1099 self.logger.debug(cmd)
1100 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +01001101
tiernof97fd272016-07-11 14:32:37 +02001102 return instance_uuid + " " + instance_name
1103 except (mdb.Error, AttributeError) as e:
1104 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
1105 tries -= 1
tierno7edb6752016-03-21 17:37:52 +01001106
1107 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
1108 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1109 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
1110
1111 def update_instance_scenario(self, instance_scenario_dict):
1112 #TODO:
1113 return
1114
1115 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
1116 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1117 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1118
1119 def update_instance_vnf(self, instance_vnf_dict):
1120 #TODO:
1121 return
1122
1123 def delete_instance_vnf(self, instance_vnf_id):
1124 #TODO:
1125 return
1126
1127 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1128 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1129 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1130
1131 def update_instance_vm(self, instance_vm_dict):
1132 #TODO:
1133 return
1134
1135 def delete_instance_vm(self, instance_vm_id):
1136 #TODO:
1137 return
1138
1139 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1140 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1141
1142 def update_instance_net(self, instance_net_dict):
1143 #TODO:
1144 return
1145
1146 def delete_instance_net(self, instance_net_id):
1147 #TODO:
1148 return
1149
1150 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1151 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1152
1153 def update_instance_interface(self, instance_interface_dict):
1154 #TODO:
1155 return
1156
1157 def delete_instance_interface(self, instance_interface_dict):
1158 #TODO:
1159 return
1160
1161 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1162 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1163 Attribute
1164 datacenter_id: uuid of the datacenter to act upon
1165 table: table where to insert
1166 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1167 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1168 '''
tiernof97fd272016-07-11 14:32:37 +02001169 tries = 2
1170 while tries:
tierno7edb6752016-03-21 17:37:52 +01001171 created_time = time.time()
1172 try:
1173 with self.con:
1174 self.cur = self.con.cursor()
tiernof97fd272016-07-11 14:32:37 +02001175 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1176 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +01001177 self.cur.execute(cmd)
1178 deleted = self.cur.rowcount
tiernof97fd272016-07-11 14:32:37 +02001179 inserted = 0
tierno7edb6752016-03-21 17:37:52 +01001180 for new_net in new_net_list:
1181 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +02001182 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1183 inserted += 1
1184 return inserted, deleted
1185 except (mdb.Error, AttributeError) as e:
1186 self._format_error(e, tries)
1187 tries -= 1
1188
tierno7edb6752016-03-21 17:37:52 +01001189