blob: 50f258c69bc9a80f5c268dc152e4675994fc700f [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
tierno7edb6752016-03-21 17:37:52 +010078 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
79 bridgeInterfacesDict = {}
80 for vm in vnf_descriptor['vnf']['VNFC']:
81 if 'bridge-ifaces' in vm:
82 bridgeInterfacesDict[vm['name']] = {}
83 for bridgeiface in vm['bridge-ifaces']:
tiernofa51c202017-01-27 14:58:17 +010084 created_time += 0.00001
montesmoreno2a1fc4e2017-01-09 16:46:04 +000085 if 'port-security' in bridgeiface:
86 bridgeiface['port_security'] = bridgeiface.pop('port-security')
87 if 'floating-ip' in bridgeiface:
88 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
tierno44528e42016-10-11 12:06:25 +000089 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
tierno7edb6752016-03-21 17:37:52 +010090 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = {}
91 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['vpci'] = bridgeiface.get('vpci',None)
92 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['mac'] = bridgeiface.get('mac_address',None)
93 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['bw'] = bridgeiface.get('bandwidth', None)
94 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['model'] = bridgeiface.get('model', None)
montesmoreno2a1fc4e2017-01-09 16:46:04 +000095 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['port_security'] = \
96 int(bridgeiface.get('port_security', True))
97 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['floating_ip'] = \
98 int(bridgeiface.get('floating_ip', False))
tiernofa51c202017-01-27 14:58:17 +010099 bridgeInterfacesDict[vm['name']][bridgeiface['name']]['created_time'] = created_time
100
101 # Collect the data interfaces of each VM/VNFC under the 'numas' field
102 dataifacesDict = {}
103 for vm in vnf_descriptor['vnf']['VNFC']:
104 dataifacesDict[vm['name']] = {}
105 for numa in vm.get('numas', []):
106 for dataiface in numa.get('interfaces', []):
107 created_time += 0.00001
108 db_base._convert_bandwidth(dataiface, logger=self.logger)
109 dataifacesDict[vm['name']][dataiface['name']] = {}
110 dataifacesDict[vm['name']][dataiface['name']]['vpci'] = dataiface['vpci']
111 dataifacesDict[vm['name']][dataiface['name']]['bw'] = dataiface['bandwidth']
112 dataifacesDict[vm['name']][dataiface['name']]['model'] = "PF" if dataiface[
113 'dedicated'] == "yes" else (
114 "VF" if dataiface['dedicated'] == "no" else "VFnotShared")
115 dataifacesDict[vm['name']][dataiface['name']]['created_time'] = created_time
116
tierno7edb6752016-03-21 17:37:52 +0100117 #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 +0200118 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100119 internalconnList = []
120 if 'internal-connections' in vnf_descriptor['vnf']:
121 for net in vnf_descriptor['vnf']['internal-connections']:
tiernof97fd272016-07-11 14:32:37 +0200122 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
tierno7edb6752016-03-21 17:37:52 +0100123
124 myNetDict = {}
125 myNetDict["name"] = net['name']
126 myNetDict["description"] = net['description']
127 myNetDict["type"] = net['type']
128 myNetDict["vnf_id"] = vnf_id
129
130 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200131 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 +0100132
133 for element in net['elements']:
134 ifaceItem = {}
135 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
136 ifaceItem["internal_name"] = element['local_iface_name']
137 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
138 ifaceItem["vm_id"] = vmDict[element['VNFC']]
139 ifaceItem["net_id"] = net_id
140 ifaceItem["type"] = net['type']
141 if ifaceItem ["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100142 dataiface = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
143 ifaceItem["vpci"] = dataiface['vpci']
144 ifaceItem["bw"] = dataiface['bw']
145 ifaceItem["model"] = dataiface['model']
146 created_time_iface = dataiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100147 else:
tiernofa51c202017-01-27 14:58:17 +0100148 bridgeiface = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
149 ifaceItem["vpci"] = bridgeiface['vpci']
150 ifaceItem["mac"] = bridgeiface['mac']
151 ifaceItem["bw"] = bridgeiface['bw']
152 ifaceItem["model"] = bridgeiface['model']
153 ifaceItem["port_security"] = bridgeiface['port_security']
154 ifaceItem["floating_ip"] = bridgeiface['floating_ip']
155 created_time_iface = bridgeiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100156 internalconnList.append(ifaceItem)
tiernof97fd272016-07-11 14:32:37 +0200157 #print "Internal net id in NFVO DB: %s" % net_id
tierno7edb6752016-03-21 17:37:52 +0100158
tiernof97fd272016-07-11 14:32:37 +0200159 #print "Adding internal interfaces to the NFVO database (if any)"
tierno7edb6752016-03-21 17:37:52 +0100160 for iface in internalconnList:
tiernofa51c202017-01-27 14:58:17 +0100161 #print "Iface name: %s" % iface['internal_name']
162 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 +0200163 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100164
tiernof97fd272016-07-11 14:32:37 +0200165 #print "Adding external interfaces to the NFVO database"
tierno7edb6752016-03-21 17:37:52 +0100166 for iface in vnf_descriptor['vnf']['external-connections']:
167 myIfaceDict = {}
168 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
169 myIfaceDict["internal_name"] = iface['local_iface_name']
170 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
171 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
172 myIfaceDict["external_name"] = iface['name']
173 myIfaceDict["type"] = iface['type']
174 if iface["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100175 dataiface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
176 myIfaceDict["vpci"] = dataiface['vpci']
177 myIfaceDict["bw"] = dataiface['bw']
178 myIfaceDict["model"] = dataiface['model']
179 created_time_iface = dataiface['created_time']
tierno7edb6752016-03-21 17:37:52 +0100180 else:
tiernofa51c202017-01-27 14:58:17 +0100181 bridgeiface = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]
182 myIfaceDict["vpci"] = bridgeiface['vpci']
183 myIfaceDict["bw"] = bridgeiface['bw']
184 myIfaceDict["model"] = bridgeiface['model']
185 myIfaceDict["mac"] = bridgeiface['mac']
186 myIfaceDict["port_security"]= bridgeiface['port_security']
187 myIfaceDict["floating_ip"] = bridgeiface['floating_ip']
188 created_time_iface = bridgeiface['created_time']
189 #print "Iface name: %s" % iface['name']
190 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 +0200191 #print "Iface id in NFVO DB: %s" % iface_id
tierno7edb6752016-03-21 17:37:52 +0100192
tiernof97fd272016-07-11 14:32:37 +0200193 return vnf_id
tierno7edb6752016-03-21 17:37:52 +0100194
tiernof97fd272016-07-11 14:32:37 +0200195 except (mdb.Error, AttributeError) as e:
196 self._format_error(e, tries)
197 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100198
garciadeblas9f8456e2016-09-05 05:02:59 +0200199 def new_vnf_as_a_whole2(self,nfvo_tenant,vnf_name,vnf_descriptor,VNFCDict):
200 self.logger.debug("Adding new vnf to the NFVO database")
201 tries = 2
202 while tries:
203 created_time = time.time()
204 try:
205 with self.con:
206
207 myVNFDict = {}
208 myVNFDict["name"] = vnf_name
209 myVNFDict["descriptor"] = vnf_descriptor['vnf'].get('descriptor')
210 myVNFDict["public"] = vnf_descriptor['vnf'].get('public', "false")
211 myVNFDict["description"] = vnf_descriptor['vnf']['description']
212 myVNFDict["class"] = vnf_descriptor['vnf'].get('class',"MISC")
213 myVNFDict["tenant_id"] = vnf_descriptor['vnf'].get("tenant_id")
214
215 vnf_id = self._new_row_internal('vnfs', myVNFDict, add_uuid=True, root_uuid=None, created_time=created_time)
216 #print "Adding new vms to the NFVO database"
217 #For each vm, we must create the appropriate vm in the NFVO database.
218 vmDict = {}
219 for _,vm in VNFCDict.iteritems():
220 #This code could make the name of the vms grow and grow.
221 #If we agree to follow this convention, we should check with a regex that the vnfc name is not including yet the vnf name
222 #vm['name'] = "%s-%s" % (vnf_name,vm['name'])
223 #print "VM name: %s. Description: %s" % (vm['name'], vm['description'])
224 vm["vnf_id"] = vnf_id
225 created_time += 0.00001
226 vm_id = self._new_row_internal('vms', vm, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
227 #print "Internal vm id in NFVO DB: %s" % vm_id
228 vmDict[vm['name']] = vm_id
229
garciadeblas9f8456e2016-09-05 05:02:59 +0200230 #Collect the bridge interfaces of each VM/VNFC under the 'bridge-ifaces' field
231 bridgeInterfacesDict = {}
232 for vm in vnf_descriptor['vnf']['VNFC']:
233 if 'bridge-ifaces' in vm:
234 bridgeInterfacesDict[vm['name']] = {}
235 for bridgeiface in vm['bridge-ifaces']:
tiernofa51c202017-01-27 14:58:17 +0100236 created_time += 0.00001
tierno44528e42016-10-11 12:06:25 +0000237 db_base._convert_bandwidth(bridgeiface, logger=self.logger)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000238 if 'port-security' in bridgeiface:
239 bridgeiface['port_security'] = bridgeiface.pop('port-security')
240 if 'floating-ip' in bridgeiface:
241 bridgeiface['floating_ip'] = bridgeiface.pop('floating-ip')
tiernofa51c202017-01-27 14:58:17 +0100242 ifaceDict = {}
243 ifaceDict['vpci'] = bridgeiface.get('vpci',None)
244 ifaceDict['mac'] = bridgeiface.get('mac_address',None)
245 ifaceDict['bw'] = bridgeiface.get('bandwidth', None)
246 ifaceDict['model'] = bridgeiface.get('model', None)
247 ifaceDict['port_security'] = int(bridgeiface.get('port_security', True))
248 ifaceDict['floating_ip'] = int(bridgeiface.get('floating_ip', False))
249 ifaceDict['created_time'] = created_time
250 bridgeInterfacesDict[vm['name']][bridgeiface['name']] = ifaceDict
251
252 # Collect the data interfaces of each VM/VNFC under the 'numas' field
253 dataifacesDict = {}
254 for vm in vnf_descriptor['vnf']['VNFC']:
255 dataifacesDict[vm['name']] = {}
256 for numa in vm.get('numas', []):
257 for dataiface in numa.get('interfaces', []):
258 created_time += 0.00001
259 db_base._convert_bandwidth(dataiface, logger=self.logger)
260 ifaceDict = {}
261 ifaceDict['vpci'] = dataiface['vpci']
262 ifaceDict['bw'] = dataiface['bandwidth']
263 ifaceDict['model'] = "PF" if dataiface['dedicated'] == "yes" else \
264 ("VF" if dataiface['dedicated'] == "no" else "VFnotShared")
265 ifaceDict['created_time'] = created_time
266 dataifacesDict[vm['name']][dataiface['name']] = ifaceDict
267
garciadeblas9f8456e2016-09-05 05:02:59 +0200268 #For each internal connection, we add it to the interfaceDict and we create the appropriate net in the NFVO database.
269 #print "Adding new nets (VNF internal nets) to the NFVO database (if any)"
garciadeblas9f8456e2016-09-05 05:02:59 +0200270 if 'internal-connections' in vnf_descriptor['vnf']:
271 for net in vnf_descriptor['vnf']['internal-connections']:
272 #print "Net name: %s. Description: %s" % (net['name'], net['description'])
273
274 myNetDict = {}
275 myNetDict["name"] = net['name']
276 myNetDict["description"] = net['description']
277 if (net["implementation"] == "overlay"):
278 net["type"] = "bridge"
279 #It should give an error if the type is e-line. For the moment, we consider it as a bridge
280 elif (net["implementation"] == "underlay"):
281 if (net["type"] == "e-line"):
282 net["type"] = "ptp"
283 elif (net["type"] == "e-lan"):
284 net["type"] = "data"
285 net.pop("implementation")
286 myNetDict["type"] = net['type']
287 myNetDict["vnf_id"] = vnf_id
288
289 created_time += 0.00001
290 net_id = self._new_row_internal('nets', myNetDict, add_uuid=True, root_uuid=vnf_id, created_time=created_time)
291
292 if "ip-profile" in net:
293 ip_profile = net["ip-profile"]
294 myIPProfileDict = {}
295 myIPProfileDict["net_id"] = net_id
296 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
297 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
298 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
299 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
300 if ("dhcp" in ip_profile):
301 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
302 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
303 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
304
305 created_time += 0.00001
306 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
307
308 for element in net['elements']:
309 ifaceItem = {}
310 #ifaceItem["internal_name"] = "%s-%s-%s" % (net['name'],element['VNFC'], element['local_iface_name'])
311 ifaceItem["internal_name"] = element['local_iface_name']
312 #ifaceItem["vm_id"] = vmDict["%s-%s" % (vnf_name,element['VNFC'])]
313 ifaceItem["vm_id"] = vmDict[element['VNFC']]
314 ifaceItem["net_id"] = net_id
315 ifaceItem["type"] = net['type']
316 ifaceItem["ip_address"] = element.get('ip_address',None)
317 if ifaceItem ["type"] == "data":
tiernofa51c202017-01-27 14:58:17 +0100318 ifaceDict = dataifacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
319 ifaceItem["vpci"] = ifaceDict['vpci']
320 ifaceItem["bw"] = ifaceDict['bw']
321 ifaceItem["model"] = ifaceDict['model']
garciadeblas9f8456e2016-09-05 05:02:59 +0200322 else:
tiernofa51c202017-01-27 14:58:17 +0100323 ifaceDict = bridgeInterfacesDict[ element['VNFC'] ][ element['local_iface_name'] ]
324 ifaceItem["vpci"] = ifaceDict['vpci']
325 ifaceItem["mac"] = ifaceDict['mac']
326 ifaceItem["bw"] = ifaceDict['bw']
327 ifaceItem["model"] = ifaceDict['model']
328 ifaceItem["port_security"] = ifaceDict['port_security']
329 ifaceItem["floating_ip"] = ifaceDict['floating_ip']
330 created_time_iface = ifaceDict["created_time"]
331 #print "Iface name: %s" % iface['internal_name']
332 iface_id = self._new_row_internal('interfaces', ifaceItem, add_uuid=True, root_uuid=vnf_id, created_time=created_time_iface)
333 #print "Iface id in NFVO DB: %s" % iface_id
garciadeblas9f8456e2016-09-05 05:02:59 +0200334
335 #print "Adding external interfaces to the NFVO database"
336 for iface in vnf_descriptor['vnf']['external-connections']:
337 myIfaceDict = {}
338 #myIfaceDict["internal_name"] = "%s-%s-%s" % (vnf_name,iface['VNFC'], iface['local_iface_name'])
339 myIfaceDict["internal_name"] = iface['local_iface_name']
340 #myIfaceDict["vm_id"] = vmDict["%s-%s" % (vnf_name,iface['VNFC'])]
341 myIfaceDict["vm_id"] = vmDict[iface['VNFC']]
342 myIfaceDict["external_name"] = iface['name']
343 myIfaceDict["type"] = iface['type']
344 if iface["type"] == "data":
345 myIfaceDict["vpci"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
346 myIfaceDict["bw"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
347 myIfaceDict["model"] = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
tiernofa51c202017-01-27 14:58:17 +0100348 created_time_iface = dataifacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['created_time']
garciadeblas9f8456e2016-09-05 05:02:59 +0200349 else:
350 myIfaceDict["vpci"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['vpci']
351 myIfaceDict["bw"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['bw']
352 myIfaceDict["model"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['model']
353 myIfaceDict["mac"] = bridgeInterfacesDict[ iface['VNFC'] ][ iface['local_iface_name'] ]['mac']
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000354 myIfaceDict["port_security"] = \
355 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['port_security']
356 myIfaceDict["floating_ip"] = \
357 bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['floating_ip']
tiernofa51c202017-01-27 14:58:17 +0100358 created_time_iface = bridgeInterfacesDict[iface['VNFC']][iface['local_iface_name']]['created_time']
359 #print "Iface name: %s" % iface['name']
360 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 +0200361 #print "Iface id in NFVO DB: %s" % iface_id
362
363 return vnf_id
364
365 except (mdb.Error, AttributeError) as e:
366 self._format_error(e, tries)
367# except KeyError as e2:
368# exc_type, exc_obj, exc_tb = sys.exc_info()
369# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
370# self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
371# raise KeyError
372 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100373
374 def new_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200375 tries = 2
376 while tries:
tierno7edb6752016-03-21 17:37:52 +0100377 created_time = time.time()
378 try:
379 with self.con:
380 self.cur = self.con.cursor()
381 tenant_id = scenario_dict.get('tenant_id')
382 #scenario
383 INSERT_={'tenant_id': tenant_id,
tiernof97fd272016-07-11 14:32:37 +0200384 'name': scenario_dict['name'],
385 'description': scenario_dict['description'],
386 'public': scenario_dict.get('public', "false")}
tierno7edb6752016-03-21 17:37:52 +0100387
tiernof97fd272016-07-11 14:32:37 +0200388 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
tierno7edb6752016-03-21 17:37:52 +0100389 #sce_nets
390 for net in scenario_dict['nets'].values():
391 net_dict={'scenario_id': scenario_uuid}
392 net_dict["name"] = net["name"]
393 net_dict["type"] = net["type"]
394 net_dict["description"] = net.get("description")
395 net_dict["external"] = net.get("external", False)
396 if "graph" in net:
397 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
398 #TODO, must be json because of the GUI, change to yaml
399 net_dict["graph"]=json.dumps(net["graph"])
400 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200401 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 +0100402 net['uuid']=net_uuid
403 #sce_vnfs
404 for k,vnf in scenario_dict['vnfs'].items():
405 INSERT_={'scenario_id': scenario_uuid,
406 'name': k,
407 'vnf_id': vnf['uuid'],
408 #'description': scenario_dict['name']
409 'description': vnf['description']
410 }
411 if "graph" in vnf:
412 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
413 #TODO, must be json because of the GUI, change to yaml
414 INSERT_["graph"]=json.dumps(vnf["graph"])
415 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200416 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 +0100417 vnf['scn_vnf_uuid']=scn_vnf_uuid
418 #sce_interfaces
419 for iface in vnf['ifaces'].values():
tiernof97fd272016-07-11 14:32:37 +0200420 #print 'iface', iface
tierno7edb6752016-03-21 17:37:52 +0100421 if 'net_key' not in iface:
422 continue
423 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
424 INSERT_={'sce_vnf_id': scn_vnf_uuid,
425 'sce_net_id': iface['net_id'],
426 'interface_id': iface[ 'uuid' ]
427 }
428 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200429 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 +0100430
tiernof97fd272016-07-11 14:32:37 +0200431 return scenario_uuid
tierno7edb6752016-03-21 17:37:52 +0100432
tiernof97fd272016-07-11 14:32:37 +0200433 except (mdb.Error, AttributeError) as e:
434 self._format_error(e, tries)
435 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100436
garciadeblas9f8456e2016-09-05 05:02:59 +0200437 def new_scenario2(self, scenario_dict):
438 tries = 2
439 while tries:
440 created_time = time.time()
441 try:
442 with self.con:
443 self.cur = self.con.cursor()
444 tenant_id = scenario_dict.get('tenant_id')
445 #scenario
446 INSERT_={'tenant_id': tenant_id,
447 'name': scenario_dict['name'],
448 'description': scenario_dict['description'],
449 'public': scenario_dict.get('public', "false")}
450
451 scenario_uuid = self._new_row_internal('scenarios', INSERT_, add_uuid=True, root_uuid=None, created_time=created_time)
452 #sce_nets
453 for net in scenario_dict['nets'].values():
454 net_dict={'scenario_id': scenario_uuid}
455 net_dict["name"] = net["name"]
456 net_dict["type"] = net["type"]
457 net_dict["description"] = net.get("description")
458 net_dict["external"] = net.get("external", False)
459 if "graph" in net:
460 #net["graph"]=yaml.safe_dump(net["graph"],default_flow_style=True,width=256)
461 #TODO, must be json because of the GUI, change to yaml
462 net_dict["graph"]=json.dumps(net["graph"])
463 created_time += 0.00001
464 net_uuid = self._new_row_internal('sce_nets', net_dict, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
465 net['uuid']=net_uuid
466
467 if "ip-profile" in net:
468 ip_profile = net["ip-profile"]
469 myIPProfileDict = {}
470 myIPProfileDict["sce_net_id"] = net_uuid
471 myIPProfileDict["ip_version"] = ip_profile.get('ip-version',"IPv4")
472 myIPProfileDict["subnet_address"] = ip_profile.get('subnet-address',None)
473 myIPProfileDict["gateway_address"] = ip_profile.get('gateway-address',None)
474 myIPProfileDict["dns_address"] = ip_profile.get('dns-address',None)
475 if ("dhcp" in ip_profile):
476 myIPProfileDict["dhcp_enabled"] = ip_profile["dhcp"].get('enabled',"true")
477 myIPProfileDict["dhcp_start_address"] = ip_profile["dhcp"].get('start-address',None)
478 myIPProfileDict["dhcp_count"] = ip_profile["dhcp"].get('count',None)
479
480 created_time += 0.00001
481 ip_profile_id = self._new_row_internal('ip_profiles', myIPProfileDict)
482
483 #sce_vnfs
484 for k,vnf in scenario_dict['vnfs'].items():
485 INSERT_={'scenario_id': scenario_uuid,
486 'name': k,
487 'vnf_id': vnf['uuid'],
488 #'description': scenario_dict['name']
489 'description': vnf['description']
490 }
491 if "graph" in vnf:
492 #INSERT_["graph"]=yaml.safe_dump(vnf["graph"],default_flow_style=True,width=256)
493 #TODO, must be json because of the GUI, change to yaml
494 INSERT_["graph"]=json.dumps(vnf["graph"])
495 created_time += 0.00001
496 scn_vnf_uuid = self._new_row_internal('sce_vnfs', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
497 vnf['scn_vnf_uuid']=scn_vnf_uuid
498 #sce_interfaces
499 for iface in vnf['ifaces'].values():
500 #print 'iface', iface
501 if 'net_key' not in iface:
502 continue
503 iface['net_id'] = scenario_dict['nets'][ iface['net_key'] ]['uuid']
504 INSERT_={'sce_vnf_id': scn_vnf_uuid,
505 'sce_net_id': iface['net_id'],
506 'interface_id': iface['uuid'],
507 'ip_address': iface['ip_address']
508 }
509 created_time += 0.00001
510 iface_uuid = self._new_row_internal('sce_interfaces', INSERT_, add_uuid=True, root_uuid=scenario_uuid, created_time=created_time)
511
512 return scenario_uuid
513
514 except (mdb.Error, AttributeError) as e:
515 self._format_error(e, tries)
516# except KeyError as e2:
517# exc_type, exc_obj, exc_tb = sys.exc_info()
518# fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
519# self.logger.debug("Exception type: %s; Filename: %s; Line number: %s", exc_type, fname, exc_tb.tb_lineno)
520# raise KeyError
521 tries -= 1
522
tierno7edb6752016-03-21 17:37:52 +0100523 def edit_scenario(self, scenario_dict):
tiernof97fd272016-07-11 14:32:37 +0200524 tries = 2
525 while tries:
tierno7edb6752016-03-21 17:37:52 +0100526 modified_time = time.time()
tiernof97fd272016-07-11 14:32:37 +0200527 item_changed=0
tierno7edb6752016-03-21 17:37:52 +0100528 try:
529 with self.con:
530 self.cur = self.con.cursor()
531 #check that scenario exist
532 tenant_id = scenario_dict.get('tenant_id')
533 scenario_uuid = scenario_dict['uuid']
534
tiernof97fd272016-07-11 14:32:37 +0200535 where_text = "uuid='{}'".format(scenario_uuid)
tierno7edb6752016-03-21 17:37:52 +0100536 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200537 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
538 cmd = "SELECT * FROM scenarios WHERE "+ where_text
539 self.logger.debug(cmd)
540 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100541 self.cur.fetchall()
542 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200543 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 +0100544 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200545 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 +0100546
547 #scenario
548 nodes = {}
549 topology = scenario_dict.pop("topology", None)
550 if topology != None and "nodes" in topology:
551 nodes = topology.get("nodes",{})
552 UPDATE_ = {}
553 if "name" in scenario_dict: UPDATE_["name"] = scenario_dict["name"]
554 if "description" in scenario_dict: UPDATE_["description"] = scenario_dict["description"]
555 if len(UPDATE_)>0:
556 WHERE_={'tenant_id': tenant_id, 'uuid': scenario_uuid}
tiernof97fd272016-07-11 14:32:37 +0200557 item_changed += self._update_rows('scenarios', UPDATE_, WHERE_, modified_time=modified_time)
tierno7edb6752016-03-21 17:37:52 +0100558 #sce_nets
559 for node_id, node in nodes.items():
560 if "graph" in node:
561 #node["graph"] = yaml.safe_dump(node["graph"],default_flow_style=True,width=256)
562 #TODO, must be json because of the GUI, change to yaml
563 node["graph"] = json.dumps(node["graph"])
564 WHERE_={'scenario_id': scenario_uuid, 'uuid': node_id}
tiernof97fd272016-07-11 14:32:37 +0200565 #Try to change at sce_nets(version 0 API backward compatibility and sce_vnfs)
566 item_changed += self._update_rows('sce_nets', node, WHERE_)
567 item_changed += self._update_rows('sce_vnfs', node, WHERE_, modified_time=modified_time)
568 return item_changed
tierno7edb6752016-03-21 17:37:52 +0100569
tiernof97fd272016-07-11 14:32:37 +0200570 except (mdb.Error, AttributeError) as e:
571 self._format_error(e, tries)
572 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100573
574# def get_instance_scenario(self, instance_scenario_id, tenant_id=None):
575# '''Obtain the scenario instance information, filtering by one or serveral of the tenant, uuid or name
576# instance_scenario_id is the uuid or the name if it is not a valid uuid format
577# Only one scenario isntance must mutch the filtering or an error is returned
578# '''
579# print "1******************************************************************"
580# try:
581# with self.con:
582# self.cur = self.con.cursor(mdb.cursors.DictCursor)
583# #scenario table
584# where_list=[]
585# if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200586# if db_base._check_valid_uuid(instance_scenario_id):
tierno7edb6752016-03-21 17:37:52 +0100587# where_list.append( "uuid='" + instance_scenario_id +"'" )
588# else:
589# where_list.append( "name='" + instance_scenario_id +"'" )
590# where_text = " AND ".join(where_list)
591# self.cur.execute("SELECT * FROM instance_scenarios WHERE "+ where_text)
592# rows = self.cur.fetchall()
593# if self.cur.rowcount==0:
594# return -HTTP_Bad_Request, "No scenario instance found with this criteria " + where_text
595# elif self.cur.rowcount>1:
596# return -HTTP_Bad_Request, "More than one scenario instance found with this criteria " + where_text
597# instance_scenario_dict = rows[0]
598#
599# #instance_vnfs
600# self.cur.execute("SELECT uuid,vnf_id FROM instance_vnfs WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
601# instance_scenario_dict['instance_vnfs'] = self.cur.fetchall()
602# for vnf in instance_scenario_dict['instance_vnfs']:
603# #instance_vms
604# self.cur.execute("SELECT uuid, vim_vm_id "+
605# "FROM instance_vms "+
606# "WHERE instance_vnf_id='" + vnf['uuid'] +"'"
607# )
608# vnf['instance_vms'] = self.cur.fetchall()
609# #instance_nets
610# self.cur.execute("SELECT uuid, vim_net_id FROM instance_nets WHERE instance_scenario_id='"+ instance_scenario_dict['uuid'] + "'")
611# instance_scenario_dict['instance_nets'] = self.cur.fetchall()
612#
613# #instance_interfaces
614# 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'] + "'")
615# instance_scenario_dict['instance_interfaces'] = self.cur.fetchall()
616#
tiernof97fd272016-07-11 14:32:37 +0200617# db_base._convert_datetime2str(instance_scenario_dict)
618# db_base._convert_str2boolean(instance_scenario_dict, ('public','shared','external') )
tierno7edb6752016-03-21 17:37:52 +0100619# print "2******************************************************************"
620# return 1, instance_scenario_dict
tiernof97fd272016-07-11 14:32:37 +0200621# except (mdb.Error, AttributeError) as e:
tierno7edb6752016-03-21 17:37:52 +0100622# print "nfvo_db.get_instance_scenario DB Exception %d: %s" % (e.args[0], e.args[1])
tiernof97fd272016-07-11 14:32:37 +0200623# return self._format_error(e)
tierno7edb6752016-03-21 17:37:52 +0100624
625 def get_scenario(self, scenario_id, tenant_id=None, datacenter_id=None):
626 '''Obtain the scenario information, filtering by one or serveral of the tenant, uuid or name
627 scenario_id is the uuid or the name if it is not a valid uuid format
628 if datacenter_id is provided, it supply aditional vim_id fields with the matching vim uuid
629 Only one scenario must mutch the filtering or an error is returned
630 '''
tiernof97fd272016-07-11 14:32:37 +0200631 tries = 2
632 while tries:
tierno7edb6752016-03-21 17:37:52 +0100633 try:
634 with self.con:
635 self.cur = self.con.cursor(mdb.cursors.DictCursor)
tiernof97fd272016-07-11 14:32:37 +0200636 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100637 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200638 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
639 cmd = "SELECT * FROM scenarios WHERE " + where_text
640 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100641 self.cur.execute(cmd)
642 rows = self.cur.fetchall()
643 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200644 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 +0100645 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200646 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 +0100647 scenario_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200648 if scenario_dict["cloud_config"]:
649 scenario_dict["cloud-config"] = yaml.load(scenario_dict["cloud_config"])
650 del scenario_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100651 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200652 cmd = "SELECT uuid,name,vnf_id,description FROM sce_vnfs WHERE scenario_id='{}' ORDER BY created_at".format(scenario_dict['uuid'])
653 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100654 self.cur.execute(cmd)
655 scenario_dict['vnfs'] = self.cur.fetchall()
656 for vnf in scenario_dict['vnfs']:
657 #sce_interfaces
garciadeblas9f8456e2016-09-05 05:02:59 +0200658 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 +0200659 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100660 self.cur.execute(cmd)
661 vnf['interfaces'] = self.cur.fetchall()
662 #vms
tierno36c0b172017-01-12 18:32:28 +0100663 cmd = "SELECT vms.uuid as uuid, flavor_id, image_id, vms.name as name, vms.description as description, vms.boot_data as boot_data " \
tierno7edb6752016-03-21 17:37:52 +0100664 " FROM vnfs join vms on vnfs.uuid=vms.vnf_id " \
665 " WHERE vnfs.uuid='" + vnf['vnf_id'] +"'" \
666 " ORDER BY vms.created_at"
tiernof97fd272016-07-11 14:32:37 +0200667 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100668 self.cur.execute(cmd)
669 vnf['vms'] = self.cur.fetchall()
670 for vm in vnf['vms']:
tierno36c0b172017-01-12 18:32:28 +0100671 if vm["boot_data"]:
672 vm["boot_data"] = yaml.safe_load(vm["boot_data"])
673 else:
674 del vm["boot_data"]
tierno7edb6752016-03-21 17:37:52 +0100675 if datacenter_id!=None:
tiernof97fd272016-07-11 14:32:37 +0200676 cmd = "SELECT vim_id FROM datacenters_images WHERE image_id='{}' AND datacenter_id='{}'".format(vm['image_id'],datacenter_id)
677 self.logger.debug(cmd)
678 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100679 if self.cur.rowcount==1:
680 vim_image_dict = self.cur.fetchone()
681 vm['vim_image_id']=vim_image_dict['vim_id']
tiernof97fd272016-07-11 14:32:37 +0200682 cmd = "SELECT vim_id FROM datacenters_flavors WHERE flavor_id='{}' AND datacenter_id='{}'".format(vm['flavor_id'],datacenter_id)
683 self.logger.debug(cmd)
684 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100685 if self.cur.rowcount==1:
686 vim_flavor_dict = self.cur.fetchone()
687 vm['vim_flavor_id']=vim_flavor_dict['vim_id']
688
689 #interfaces
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000690 cmd = "SELECT uuid,internal_name,external_name,net_id,type,vpci,mac,bw,model,ip_address," \
691 "floating_ip, port_security" \
tierno7edb6752016-03-21 17:37:52 +0100692 " FROM interfaces" \
tiernof97fd272016-07-11 14:32:37 +0200693 " WHERE vm_id='{}'" \
694 " ORDER BY created_at".format(vm['uuid'])
695 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100696 self.cur.execute(cmd)
697 vm['interfaces'] = self.cur.fetchall()
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000698 for index in range(0,len(vm['interfaces'])):
699 vm['interfaces'][index]['port-security'] = vm['interfaces'][index].pop("port_security")
700 vm['interfaces'][index]['floating-ip'] = vm['interfaces'][index].pop("floating_ip")
tierno7edb6752016-03-21 17:37:52 +0100701 #nets every net of a vms
tiernof97fd272016-07-11 14:32:37 +0200702 cmd = "SELECT uuid,name,type,description FROM nets WHERE vnf_id='{}'".format(vnf['vnf_id'])
703 self.logger.debug(cmd)
704 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100705 vnf['nets'] = self.cur.fetchall()
garciadeblas9f8456e2016-09-05 05:02:59 +0200706 for vnf_net in vnf['nets']:
707 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
708 cmd = "SELECT {} FROM ip_profiles WHERE net_id='{}'".format(SELECT_,vnf_net['uuid'])
709 self.logger.debug(cmd)
710 self.cur.execute(cmd)
711 ipprofiles = self.cur.fetchall()
712 if self.cur.rowcount==1:
713 vnf_net["ip_profile"] = ipprofiles[0]
714 elif self.cur.rowcount>1:
715 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)
716
tierno7edb6752016-03-21 17:37:52 +0100717 #sce_nets
718 cmd = "SELECT uuid,name,type,external,description" \
tiernof97fd272016-07-11 14:32:37 +0200719 " FROM sce_nets WHERE scenario_id='{}'" \
720 " ORDER BY created_at ".format(scenario_dict['uuid'])
721 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100722 self.cur.execute(cmd)
723 scenario_dict['nets'] = self.cur.fetchall()
724 #datacenter_nets
725 for net in scenario_dict['nets']:
726 if str(net['external']) == 'false':
garciadeblas9f8456e2016-09-05 05:02:59 +0200727 SELECT_ = "ip_version,subnet_address,gateway_address,dns_address,dhcp_enabled,dhcp_start_address,dhcp_count"
728 cmd = "SELECT {} FROM ip_profiles WHERE sce_net_id='{}'".format(SELECT_,net['uuid'])
729 self.logger.debug(cmd)
730 self.cur.execute(cmd)
731 ipprofiles = self.cur.fetchall()
732 if self.cur.rowcount==1:
733 net["ip_profile"] = ipprofiles[0]
734 elif self.cur.rowcount>1:
735 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 +0100736 continue
tiernof97fd272016-07-11 14:32:37 +0200737 WHERE_=" WHERE name='{}'".format(net['name'])
tierno7edb6752016-03-21 17:37:52 +0100738 if datacenter_id!=None:
tiernof97fd272016-07-11 14:32:37 +0200739 WHERE_ += " AND datacenter_id='{}'".format(datacenter_id)
740 cmd = "SELECT vim_net_id FROM datacenter_nets" + WHERE_
741 self.logger.debug(cmd)
742 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100743 d_net = self.cur.fetchone()
744 if d_net==None or datacenter_id==None:
745 #print "nfvo_db.get_scenario() WARNING external net %s not found" % net['name']
746 net['vim_id']=None
747 else:
748 net['vim_id']=d_net['vim_net_id']
749
tiernof97fd272016-07-11 14:32:37 +0200750 db_base._convert_datetime2str(scenario_dict)
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000751 db_base._convert_str2boolean(scenario_dict, ('public','shared','external','port-security','floating-ip') )
tiernof97fd272016-07-11 14:32:37 +0200752 return scenario_dict
753 except (mdb.Error, AttributeError) as e:
754 self._format_error(e, tries)
755 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100756
tierno7edb6752016-03-21 17:37:52 +0100757 def delete_scenario(self, scenario_id, tenant_id=None):
758 '''Deletes a scenario, filtering by one or several of the tenant, uuid or name
759 scenario_id is the uuid or the name if it is not a valid uuid format
760 Only one scenario must mutch the filtering or an error is returned
761 '''
tiernof97fd272016-07-11 14:32:37 +0200762 tries = 2
763 while tries:
tierno7edb6752016-03-21 17:37:52 +0100764 try:
765 with self.con:
766 self.cur = self.con.cursor(mdb.cursors.DictCursor)
767
768 #scenario table
tiernof97fd272016-07-11 14:32:37 +0200769 where_text = "uuid='{}'".format(scenario_id)
tierno7edb6752016-03-21 17:37:52 +0100770 if not tenant_id and tenant_id != "any":
tiernof97fd272016-07-11 14:32:37 +0200771 where_text += " AND (tenant_id='{}' OR public='True')".format(tenant_id)
772 cmd = "SELECT * FROM scenarios WHERE "+ where_text
773 self.logger.debug(cmd)
774 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100775 rows = self.cur.fetchall()
776 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200777 raise db_base.db_base_Exception("No scenario found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +0100778 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200779 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 +0100780 scenario_uuid = rows[0]["uuid"]
781 scenario_name = rows[0]["name"]
782
783 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +0200784 cmd = "DELETE FROM scenarios WHERE uuid='{}'".format(scenario_uuid)
785 self.logger.debug(cmd)
786 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100787
tiernof97fd272016-07-11 14:32:37 +0200788 return scenario_uuid + " " + scenario_name
789 except (mdb.Error, AttributeError) as e:
790 self._format_error(e, tries, "delete", "instances running")
791 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100792
793 def new_instance_scenario_as_a_whole(self,tenant_id,instance_scenario_name,instance_scenario_description,scenarioDict):
tiernof97fd272016-07-11 14:32:37 +0200794 tries = 2
795 while tries:
tierno7edb6752016-03-21 17:37:52 +0100796 created_time = time.time()
797 try:
798 with self.con:
799 self.cur = self.con.cursor()
800 #instance_scenarios
tierno7edb6752016-03-21 17:37:52 +0100801 datacenter_id = scenarioDict['datacenter_id']
802 INSERT_={'tenant_id': tenant_id,
tiernoa2793912016-10-04 08:15:08 +0000803 'datacenter_tenant_id': scenarioDict["datacenter2tenant"][datacenter_id],
tierno7edb6752016-03-21 17:37:52 +0100804 'name': instance_scenario_name,
805 'description': instance_scenario_description,
806 'scenario_id' : scenarioDict['uuid'],
807 'datacenter_id': datacenter_id
808 }
tiernoa4e1a6e2016-08-31 14:19:40 +0200809 if scenarioDict.get("cloud-config"):
810 INSERT_["cloud_config"] = yaml.safe_dump(scenarioDict["cloud-config"], default_flow_style=True, width=256)
811
tiernof97fd272016-07-11 14:32:37 +0200812 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 +0100813
814 net_scene2instance={}
815 #instance_nets #nets interVNF
816 for net in scenarioDict['nets']:
tiernobe41e222016-09-02 15:16:13 +0200817 net_scene2instance[ net['uuid'] ] ={}
818 datacenter_site_id = net.get('datacenter_id', datacenter_id)
819 if not "vim_id_sites" in net:
820 net["vim_id_sites"] ={datacenter_site_id: net['vim_id']}
tiernoa2793912016-10-04 08:15:08 +0000821 net["vim_id_sites"]["datacenter_site_id"] = {datacenter_site_id: net['vim_id']}
tiernobe41e222016-09-02 15:16:13 +0200822 sce_net_id = net.get("uuid")
823
824 for datacenter_site_id,vim_id in net["vim_id_sites"].iteritems():
tierno66345bc2016-09-26 11:37:55 +0200825 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 +0200826 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000827 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tiernobe41e222016-09-02 15:16:13 +0200828 if sce_net_id:
829 INSERT_['sce_net_id'] = sce_net_id
830 created_time += 0.00001
831 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
832 net_scene2instance[ sce_net_id ][datacenter_site_id] = instance_net_uuid
833 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200834
835 if 'ip_profile' in net:
836 net['ip_profile']['net_id'] = None
837 net['ip_profile']['sce_net_id'] = None
838 net['ip_profile']['instance_net_id'] = instance_net_uuid
839 created_time += 0.00001
840 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
tierno7edb6752016-03-21 17:37:52 +0100841
842 #instance_vnfs
843 for vnf in scenarioDict['vnfs']:
tiernobe41e222016-09-02 15:16:13 +0200844 datacenter_site_id = vnf.get('datacenter_id', datacenter_id)
tierno7edb6752016-03-21 17:37:52 +0100845 INSERT_={'instance_scenario_id': instance_uuid, 'vnf_id': vnf['vnf_id'] }
tiernobe41e222016-09-02 15:16:13 +0200846 INSERT_['datacenter_id'] = datacenter_site_id
tiernoa2793912016-10-04 08:15:08 +0000847 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_site_id]
tierno7edb6752016-03-21 17:37:52 +0100848 if vnf.get("uuid"):
849 INSERT_['sce_vnf_id'] = vnf['uuid']
850 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200851 instance_vnf_uuid = self._new_row_internal('instance_vnfs', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100852 vnf['uuid'] = instance_vnf_uuid #overwrite scnario uuid by instance uuid
853
854 #instance_nets #nets intraVNF
855 for net in vnf['nets']:
tiernobe41e222016-09-02 15:16:13 +0200856 net_scene2instance[ net['uuid'] ] = {}
tierno66345bc2016-09-26 11:37:55 +0200857 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 +0200858 INSERT_['datacenter_id'] = net.get('datacenter_id', datacenter_site_id)
tiernoa2793912016-10-04 08:15:08 +0000859 INSERT_['datacenter_tenant_id'] = scenarioDict["datacenter2tenant"][datacenter_id]
tierno7edb6752016-03-21 17:37:52 +0100860 if net.get("uuid"):
861 INSERT_['net_id'] = net['uuid']
862 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200863 instance_net_uuid = self._new_row_internal('instance_nets', INSERT_, True, instance_uuid, created_time)
tiernobe41e222016-09-02 15:16:13 +0200864 net_scene2instance[ net['uuid'] ][datacenter_site_id] = instance_net_uuid
tierno7edb6752016-03-21 17:37:52 +0100865 net['uuid'] = instance_net_uuid #overwrite scnario uuid by instance uuid
garciadeblas9f8456e2016-09-05 05:02:59 +0200866
867 if 'ip_profile' in net:
868 net['ip_profile']['net_id'] = None
869 net['ip_profile']['sce_net_id'] = None
870 net['ip_profile']['instance_net_id'] = instance_net_uuid
871 created_time += 0.00001
872 ip_profile_id = self._new_row_internal('ip_profiles', net['ip_profile'])
873
tierno7edb6752016-03-21 17:37:52 +0100874 #instance_vms
875 for vm in vnf['vms']:
876 INSERT_={'instance_vnf_id': instance_vnf_uuid, 'vm_id': vm['uuid'], 'vim_vm_id': vm['vim_id'] }
877 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200878 instance_vm_uuid = self._new_row_internal('instance_vms', INSERT_, True, instance_uuid, created_time)
tierno7edb6752016-03-21 17:37:52 +0100879 vm['uuid'] = instance_vm_uuid #overwrite scnario uuid by instance uuid
880
881 #instance_interfaces
882 for interface in vm['interfaces']:
883 net_id = interface.get('net_id', None)
884 if net_id is None:
885 #check if is connected to a inter VNFs net
886 for iface in vnf['interfaces']:
887 if iface['interface_id'] == interface['uuid']:
garciadeblas9f8456e2016-09-05 05:02:59 +0200888 if 'ip_address' in iface:
889 interface['ip_address'] = iface['ip_address']
tierno7edb6752016-03-21 17:37:52 +0100890 net_id = iface.get('sce_net_id', None)
891 break
892 if net_id is None:
893 continue
894 interface_type='external' if interface['external_name'] is not None else 'internal'
tiernobe41e222016-09-02 15:16:13 +0200895 INSERT_={'instance_vm_id': instance_vm_uuid, 'instance_net_id': net_scene2instance[net_id][datacenter_site_id],
garciadeblas9f8456e2016-09-05 05:02:59 +0200896 'interface_id': interface['uuid'], 'vim_interface_id': interface.get('vim_id'), 'type': interface_type,
montesmoreno2a1fc4e2017-01-09 16:46:04 +0000897 'ip_address': interface.get('ip_address'), 'floating_ip': int(interface.get('floating-ip',False)),
898 'port_security': int(interface.get('port-security',True))}
tierno7edb6752016-03-21 17:37:52 +0100899 #created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +0200900 interface_uuid = self._new_row_internal('instance_interfaces', INSERT_, True, instance_uuid) #, created_time)
tierno7edb6752016-03-21 17:37:52 +0100901 interface['uuid'] = interface_uuid #overwrite scnario uuid by instance uuid
tiernof97fd272016-07-11 14:32:37 +0200902 return instance_uuid
903 except (mdb.Error, AttributeError) as e:
904 self._format_error(e, tries)
905 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100906
907 def get_instance_scenario(self, instance_id, tenant_id=None, verbose=False):
908 '''Obtain the instance information, filtering by one or several of the tenant, uuid or name
909 instance_id is the uuid or the name if it is not a valid uuid format
910 Only one instance must mutch the filtering or an error is returned
911 '''
tiernof97fd272016-07-11 14:32:37 +0200912 tries = 2
913 while tries:
tierno7edb6752016-03-21 17:37:52 +0100914 try:
915 with self.con:
916 self.cur = self.con.cursor(mdb.cursors.DictCursor)
917 #instance table
918 where_list=[]
919 if tenant_id is not None: where_list.append( "inst.tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +0200920 if db_base._check_valid_uuid(instance_id):
tierno7edb6752016-03-21 17:37:52 +0100921 where_list.append( "inst.uuid='" + instance_id +"'" )
922 else:
923 where_list.append( "inst.name='" + instance_id +"'" )
924 where_text = " AND ".join(where_list)
tiernof97fd272016-07-11 14:32:37 +0200925 cmd = "SELECT inst.uuid as uuid,inst.name as name,inst.scenario_id as scenario_id, datacenter_id" +\
tierno7edb6752016-03-21 17:37:52 +0100926 " ,datacenter_tenant_id, s.name as scenario_name,inst.tenant_id as tenant_id" + \
927 " ,inst.description as description,inst.created_at as created_at" +\
tiernoa4e1a6e2016-08-31 14:19:40 +0200928 " ,inst.cloud_config as 'cloud_config'" +\
tierno7edb6752016-03-21 17:37:52 +0100929 " FROM instance_scenarios as inst join scenarios as s on inst.scenario_id=s.uuid"+\
930 " WHERE " + where_text
tiernof97fd272016-07-11 14:32:37 +0200931 self.logger.debug(cmd)
932 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +0100933 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +0200934
tierno7edb6752016-03-21 17:37:52 +0100935 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +0200936 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Not_Found)
tierno7edb6752016-03-21 17:37:52 +0100937 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +0200938 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 +0100939 instance_dict = rows[0]
tiernoa4e1a6e2016-08-31 14:19:40 +0200940 if instance_dict["cloud_config"]:
941 instance_dict["cloud-config"] = yaml.load(instance_dict["cloud_config"])
942 del instance_dict["cloud_config"]
tierno7edb6752016-03-21 17:37:52 +0100943
944 #instance_vnfs
945 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"\
946 " FROM instance_vnfs as iv join sce_vnfs as sv on iv.sce_vnf_id=sv.uuid" \
tiernof97fd272016-07-11 14:32:37 +0200947 " WHERE iv.instance_scenario_id='{}'" \
948 " ORDER BY iv.created_at ".format(instance_dict['uuid'])
949 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100950 self.cur.execute(cmd)
951 instance_dict['vnfs'] = self.cur.fetchall()
952 for vnf in instance_dict['vnfs']:
953 vnf_manage_iface_list=[]
954 #instance vms
955 cmd = "SELECT iv.uuid as uuid, vim_vm_id, status, error_msg, vim_info, iv.created_at as created_at, name "\
956 " FROM instance_vms as iv join vms on iv.vm_id=vms.uuid "\
tiernof97fd272016-07-11 14:32:37 +0200957 " WHERE instance_vnf_id='{}' ORDER BY iv.created_at".format(vnf['uuid'])
958 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100959 self.cur.execute(cmd)
960 vnf['vms'] = self.cur.fetchall()
961 for vm in vnf['vms']:
962 vm_manage_iface_list=[]
963 #instance_interfaces
tiernofa51c202017-01-27 14:58:17 +0100964 cmd = "SELECT vim_interface_id, instance_net_id, internal_name,external_name, mac_address,"\
965 " ii.ip_address as ip_address, vim_info, i.type as type"\
966 " FROM instance_interfaces as ii join interfaces as i on ii.interface_id=i.uuid"\
967 " WHERE instance_vm_id='{}' ORDER BY created_at".format(vm['uuid'])
tiernof97fd272016-07-11 14:32:37 +0200968 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100969 self.cur.execute(cmd )
970 vm['interfaces'] = self.cur.fetchall()
971 for iface in vm['interfaces']:
972 if iface["type"] == "mgmt" and iface["ip_address"]:
973 vnf_manage_iface_list.append(iface["ip_address"])
974 vm_manage_iface_list.append(iface["ip_address"])
975 if not verbose:
976 del iface["type"]
977 if vm_manage_iface_list: vm["ip_address"] = ",".join(vm_manage_iface_list)
978 if vnf_manage_iface_list: vnf["ip_address"] = ",".join(vnf_manage_iface_list)
979
980 #instance_nets
981 #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"
982 #from_text = "instance_nets join instance_scenarios on instance_nets.instance_scenario_id=instance_scenarios.uuid " + \
983 # "join sce_nets on instance_scenarios.scenario_id=sce_nets.scenario_id"
984 #where_text = "instance_nets.instance_scenario_id='"+ instance_dict['uuid'] + "'"
tierno66345bc2016-09-26 11:37:55 +0200985 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 +0100986 " FROM instance_nets" \
tiernof97fd272016-07-11 14:32:37 +0200987 " WHERE instance_scenario_id='{}' ORDER BY created_at".format(instance_dict['uuid'])
988 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +0100989 self.cur.execute(cmd)
990 instance_dict['nets'] = self.cur.fetchall()
991
tiernof97fd272016-07-11 14:32:37 +0200992 db_base._convert_datetime2str(instance_dict)
tierno66345bc2016-09-26 11:37:55 +0200993 db_base._convert_str2boolean(instance_dict, ('public','shared','created') )
tiernof97fd272016-07-11 14:32:37 +0200994 return instance_dict
995 except (mdb.Error, AttributeError) as e:
996 self._format_error(e, tries)
997 tries -= 1
tierno7edb6752016-03-21 17:37:52 +0100998
999 def delete_instance_scenario(self, instance_id, tenant_id=None):
1000 '''Deletes a instance_Scenario, filtering by one or serveral of the tenant, uuid or name
1001 instance_id is the uuid or the name if it is not a valid uuid format
1002 Only one instance_scenario must mutch the filtering or an error is returned
1003 '''
tiernof97fd272016-07-11 14:32:37 +02001004 tries = 2
1005 while tries:
tierno7edb6752016-03-21 17:37:52 +01001006 try:
1007 with self.con:
1008 self.cur = self.con.cursor(mdb.cursors.DictCursor)
1009
1010 #instance table
1011 where_list=[]
1012 if tenant_id is not None: where_list.append( "tenant_id='" + tenant_id +"'" )
tiernof97fd272016-07-11 14:32:37 +02001013 if db_base._check_valid_uuid(instance_id):
tierno7edb6752016-03-21 17:37:52 +01001014 where_list.append( "uuid='" + instance_id +"'" )
1015 else:
1016 where_list.append( "name='" + instance_id +"'" )
1017 where_text = " AND ".join(where_list)
tiernof97fd272016-07-11 14:32:37 +02001018 cmd = "SELECT * FROM instance_scenarios WHERE "+ where_text
1019 self.logger.debug(cmd)
1020 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +01001021 rows = self.cur.fetchall()
tiernof97fd272016-07-11 14:32:37 +02001022
tierno7edb6752016-03-21 17:37:52 +01001023 if self.cur.rowcount==0:
tiernof97fd272016-07-11 14:32:37 +02001024 raise db_base.db_base_Exception("No instance found where " + where_text, db_base.HTTP_Bad_Request)
tierno7edb6752016-03-21 17:37:52 +01001025 elif self.cur.rowcount>1:
tiernof97fd272016-07-11 14:32:37 +02001026 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 +01001027 instance_uuid = rows[0]["uuid"]
1028 instance_name = rows[0]["name"]
1029
1030 #sce_vnfs
tiernof97fd272016-07-11 14:32:37 +02001031 cmd = "DELETE FROM instance_scenarios WHERE uuid='{}'".format(instance_uuid)
1032 self.logger.debug(cmd)
1033 self.cur.execute(cmd)
tierno7edb6752016-03-21 17:37:52 +01001034
tiernof97fd272016-07-11 14:32:37 +02001035 return instance_uuid + " " + instance_name
1036 except (mdb.Error, AttributeError) as e:
1037 self._format_error(e, tries, "delete", "No dependences can avoid deleting!!!!")
1038 tries -= 1
tierno7edb6752016-03-21 17:37:52 +01001039
1040 def new_instance_scenario(self, instance_scenario_dict, tenant_id):
1041 #return self.new_row('vnfs', vnf_dict, None, tenant_id, True, True)
1042 return self._new_row_internal('instance_scenarios', instance_scenario_dict, tenant_id, add_uuid=True, root_uuid=None, log=True)
1043
1044 def update_instance_scenario(self, instance_scenario_dict):
1045 #TODO:
1046 return
1047
1048 def new_instance_vnf(self, instance_vnf_dict, tenant_id, instance_scenario_id = None):
1049 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1050 return self._new_row_internal('instance_vnfs', instance_vnf_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1051
1052 def update_instance_vnf(self, instance_vnf_dict):
1053 #TODO:
1054 return
1055
1056 def delete_instance_vnf(self, instance_vnf_id):
1057 #TODO:
1058 return
1059
1060 def new_instance_vm(self, instance_vm_dict, tenant_id, instance_scenario_id = None):
1061 #return self.new_row('vms', vm_dict, tenant_id, True, True)
1062 return self._new_row_internal('instance_vms', instance_vm_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1063
1064 def update_instance_vm(self, instance_vm_dict):
1065 #TODO:
1066 return
1067
1068 def delete_instance_vm(self, instance_vm_id):
1069 #TODO:
1070 return
1071
1072 def new_instance_net(self, instance_net_dict, tenant_id, instance_scenario_id = None):
1073 return self._new_row_internal('instance_nets', instance_net_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1074
1075 def update_instance_net(self, instance_net_dict):
1076 #TODO:
1077 return
1078
1079 def delete_instance_net(self, instance_net_id):
1080 #TODO:
1081 return
1082
1083 def new_instance_interface(self, instance_interface_dict, tenant_id, instance_scenario_id = None):
1084 return self._new_row_internal('instance_interfaces', instance_interface_dict, tenant_id, add_uuid=True, root_uuid=instance_scenario_id, log=True)
1085
1086 def update_instance_interface(self, instance_interface_dict):
1087 #TODO:
1088 return
1089
1090 def delete_instance_interface(self, instance_interface_dict):
1091 #TODO:
1092 return
1093
1094 def update_datacenter_nets(self, datacenter_id, new_net_list=[]):
1095 ''' Removes the old and adds the new net list at datacenter list for one datacenter.
1096 Attribute
1097 datacenter_id: uuid of the datacenter to act upon
1098 table: table where to insert
1099 new_net_list: the new values to be inserted. If empty it only deletes the existing nets
1100 Return: (Inserted items, Deleted items) if OK, (-Error, text) if error
1101 '''
tiernof97fd272016-07-11 14:32:37 +02001102 tries = 2
1103 while tries:
tierno7edb6752016-03-21 17:37:52 +01001104 created_time = time.time()
1105 try:
1106 with self.con:
1107 self.cur = self.con.cursor()
tiernof97fd272016-07-11 14:32:37 +02001108 cmd="DELETE FROM datacenter_nets WHERE datacenter_id='{}'".format(datacenter_id)
1109 self.logger.debug(cmd)
tierno7edb6752016-03-21 17:37:52 +01001110 self.cur.execute(cmd)
1111 deleted = self.cur.rowcount
tiernof97fd272016-07-11 14:32:37 +02001112 inserted = 0
tierno7edb6752016-03-21 17:37:52 +01001113 for new_net in new_net_list:
1114 created_time += 0.00001
tiernof97fd272016-07-11 14:32:37 +02001115 self._new_row_internal('datacenter_nets', new_net, add_uuid=True, created_time=created_time)
1116 inserted += 1
1117 return inserted, deleted
1118 except (mdb.Error, AttributeError) as e:
1119 self._format_error(e, tries)
1120 tries -= 1
1121
tierno7edb6752016-03-21 17:37:52 +01001122