Repository navigation
Expand file tree
/
Copy pathvim_db.py
More file actions
1646 lines (1517 loc) · 88.1 KB
/
Copy pathvim_db.py
File metadata and controls
1646 lines (1517 loc) · 88.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# Copyright 2015 Telefónica Investigación y Desarrollo, S.A.U.
# This file is part of openmano
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
#
# For those usages not covered by the Apache License, Version 2.0 please
# contact with: nfvlabs@tid.es
##
'''
This module interact with the openvim database,
It implements general table management
and complex writings 'transactional' sures,
that is, or all is changed or nothing
'''
__author__="Alfonso Tierno"
__date__ ="$10-jul-2014 12:07:15$"
import MySQLdb as mdb
import uuid as myUuid
from utils import auxiliary_functions as af
import json
import logging
HTTP_Bad_Request = 400
HTTP_Unauthorized = 401
HTTP_Not_Found = 404
HTTP_Method_Not_Allowed = 405
HTTP_Request_Timeout = 408
HTTP_Conflict = 409
HTTP_Service_Unavailable = 503
HTTP_Internal_Server_Error = 500
class vim_db():
def __init__(self, vlan_range, debug="ERROR"):
'''vlan_range must be a tuple (vlan_ini, vlan_end) with available vlan values for networks
every dataplane network contain a unique value, regardless of it is used or not
'''
#initialization
self.net_vlan_range = vlan_range
self.net_vlan_usedlist = None
self.net_vlan_lastused = self.net_vlan_range[0] -1
self.debug=debug
self.logger = logging.getLogger('vim.db')
self.logger.setLevel( getattr(logging, debug) )
def connect(self, host=None, user=None, passwd=None, database=None):
'''Connect to the concrete data base.
The first time a valid host, user, passwd and database must be provided,
Following calls can skip this parameters
'''
try:
if host is not None: self.host = host
if user is not None: self.user = user
if passwd is not None: self.passwd = passwd
if database is not None: self.database = database
self.con = mdb.connect(self.host, self.user, self.passwd, self.database)
self.logger.debug("connected to DB %s at %s@%s", self.database,self.user, self.host)
return 0
except mdb.Error as e:
self.logger.error("Cannot connect to DB %s at %s@%s Error %d: %s", self.database, self.user, self.host, e.args[0], e.args[1])
return -1
def get_db_version(self):
''' Obtain the database schema version.
Return: (negative, text) if error or version 0.0 where schema_version table is missing
(version_int, version_text) if ok
'''
cmd = "SELECT version_int,version,openvim_ver FROM schema_version"
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor()
self.logger.debug(cmd)
self.cur.execute(cmd)
rows = self.cur.fetchall()
highest_version_int=0
highest_version=""
#print rows
for row in rows: #look for the latest version
if row[0]>highest_version_int:
highest_version_int, highest_version = row[0:2]
return highest_version_int, highest_version
except (mdb.Error, AttributeError) as e:
self.logger.error("get_db_version DB Exception %d: %s. Command %s",e.args[0], e.args[1], cmd)
r,c = self.format_error(e)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def disconnect(self):
'''disconnect from the data base'''
try:
self.con.close()
del self.con
except mdb.Error as e:
self.logger.error("while disconnecting from DB: Error %d: %s",e.args[0], e.args[1])
return -1
except AttributeError as e: #self.con not defined
if e[0][-5:] == "'con'": return -1, "Database internal error, no connection."
else: raise
def format_error(self, e, func, cmd, command=None, extra=None):
'''Creates a text error base on the produced exception
Params:
e: mdb exception
func: name of the function that makes the call, for logging purposes
cmd: database command that produce the exception
command: if the intention is update or delete
extra: extra information to add to some commands
Return
HTTP error in negative, formatted error text
'''
self.logger.error("%s DB Exception %s. Command %s",func, str(e), cmd)
if type(e[0]) is str:
if e[0][-5:] == "'con'": return -HTTP_Internal_Server_Error, "DB Exception, no connection."
else: raise
if e.args[0]==2006 or e.args[0]==2013 : #MySQL server has gone away (((or))) Exception 2013: Lost connection to MySQL server during query
#reconnect
self.connect()
return -HTTP_Request_Timeout,"Database reconnection. Try Again"
fk=e.args[1].find("foreign key constraint fails")
if fk>=0:
if command=="update": return -HTTP_Bad_Request, "tenant_id %s not found." % extra
elif command=="delete": return -HTTP_Bad_Request, "Resource is not free. There are %s that prevent its deletion." % extra
de = e.args[1].find("Duplicate entry")
fk = e.args[1].find("for key")
uk = e.args[1].find("Unknown column")
wc = e.args[1].find("in 'where clause'")
fl = e.args[1].find("in 'field list'")
#print de, fk, uk, wc,fl
if de>=0:
if fk>=0: #error 1062
return -HTTP_Conflict, "Value %s already in use for %s" % (e.args[1][de+15:fk], e.args[1][fk+7:])
if uk>=0:
if wc>=0:
return -HTTP_Bad_Request, "Field %s can not be used for filtering" % e.args[1][uk+14:wc]
if fl>=0:
return -HTTP_Bad_Request, "Field %s does not exist" % e.args[1][uk+14:wc]
return -HTTP_Internal_Server_Error, "Database internal Error %d: %s" % (e.args[0], e.args[1])
def __data2db_format(self, data):
'''convert data to database format. If data is None it return the 'Null' text,
otherwise it return the text surrounded by quotes ensuring internal quotes are escaped'''
if data==None:
return 'Null'
out=str(data)
if "'" not in out:
return "'" + out + "'"
elif '"' not in out:
return '"' + out + '"'
else:
return json.dumps(out)
def __get_used_net_vlan(self):
#get used from database if needed
try:
cmd = "SELECT vlan FROM nets WHERE vlan>='%s' and (type='ptp' or type='data') ORDER BY vlan LIMIT 25" % self.net_vlan_lastused
with self.con:
self.cur = self.con.cursor()
self.logger.debug(cmd)
self.cur.execute(cmd)
vlan_tuple = self.cur.fetchall()
#convert a tuple of tuples in a list of numbers
self.net_vlan_usedlist = []
for k in vlan_tuple:
self.net_vlan_usedlist.append(k[0])
return 0
except (mdb.Error, AttributeError) as e:
return self.format_error(e, "get_free_net_vlan", cmd)
def get_free_net_vlan(self):
'''obtain a vlan not used in any net'''
while True:
self.logger.debug("net_vlan_lastused:%d net_vlan_range:%d-%d net_vlan_usedlist:%s",
self.net_vlan_lastused, self.net_vlan_range[0], self.net_vlan_range[1], str(self.net_vlan_usedlist))
self.net_vlan_lastused += 1
if self.net_vlan_lastused == self.net_vlan_range[1]:
#start from the begining
self.net_vlan_lastused = self.net_vlan_range[0]
self.net_vlan_usedlist = None
if self.net_vlan_usedlist is None \
or (len(self.net_vlan_usedlist)>0 and self.net_vlan_lastused >= self.net_vlan_usedlist[-1] and len(self.net_vlan_usedlist)==25):
r = self.__get_used_net_vlan()
if r<0: return r
self.logger.debug("new net_vlan_usedlist %s", str(self.net_vlan_usedlist))
if self.net_vlan_lastused in self.net_vlan_usedlist:
continue
else:
return self.net_vlan_lastused
def get_table(self, **sql_dict):
''' Obtain rows from a table.
Atribure sql_dir: dictionary with the following key: value
'SELECT': [list of fields to retrieve] (by default all)
'FROM': string of table name (Mandatory)
'WHERE': dict of key:values, translated to key=value AND ... (Optional)
'WHERE_NOT': dict of key:values, translated to key!=value AND ... (Optional)
'WHERE_OR': dict of key:values, translated to key=value OR ... (Optional)
'LIMIT': limit of number of rows (Optional)
Return: a list with dictionarys at each row
'''
#print sql_dict
select_= "SELECT " + ("*" if 'SELECT' not in sql_dict else ",".join(map(str,sql_dict['SELECT'])) )
#print 'select_', select_
from_ = "FROM " + str(sql_dict['FROM'])
#print 'from_', from_
where_and = None
where_or = None
if 'WHERE' in sql_dict and len(sql_dict['WHERE']) > 0:
w=sql_dict['WHERE']
where_and = " AND ".join(map( lambda x: str(x) + (" is Null" if w[x] is None else "='"+str(w[x])+"'"), w.keys()) )
if 'WHERE_NOT' in sql_dict and len(sql_dict['WHERE_NOT']) > 0:
w=sql_dict['WHERE_NOT']
where_and_not = " AND ".join(map( lambda x: str(x) + (" is not Null" if w[x] is None else "!='"+str(w[x])+"'"), w.keys()) )
if where_and:
where_and += " AND " + where_and_not
else:
where_and = where_and_not
if 'WHERE_OR' in sql_dict and len(sql_dict['WHERE_OR']) > 0:
w=sql_dict['WHERE_OR']
where_or = " OR ".join(map( lambda x: str(x) + (" is Null" if w[x] is None else "='"+str(w[x])+"'"), w.keys()) )
if where_and!=None and where_or!=None:
where_ = "WHERE (" + where_and + ") OR " + where_or
elif where_and!=None and where_or==None:
where_ = "WHERE " + where_and
elif where_and==None and where_or!=None:
where_ = "WHERE " + where_or
else:
where_ = ""
#print 'where_', where_
limit_ = "LIMIT " + str(sql_dict['LIMIT']) if 'LIMIT' in sql_dict else ""
#print 'limit_', limit_
cmd = " ".join( (select_, from_, where_, limit_) )
for retry_ in range(0,2):
try:
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
self.logger.debug(cmd)
self.cur.execute(cmd)
rows = self.cur.fetchall()
return self.cur.rowcount, rows
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "get_table", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_tenant(self, tenant_dict):
''' Add one row into a table.
Attribure
tenant_dict: dictionary with the key: value to insert
It checks presence of uuid and add one automatically otherwise
Return: (result, uuid) where result can be 0 if error, or 1 if ok
'''
for retry_ in range(0,2):
cmd=""
inserted=-1
try:
#create uuid if not provided
if 'uuid' not in tenant_dict:
uuid = tenant_dict['uuid'] = str(myUuid.uuid1()) # create_uuid
else:
uuid = str(tenant_dict['uuid'])
#obtain tenant_id for logs
tenant_id = uuid
with self.con:
self.cur = self.con.cursor()
#inserting new uuid
cmd = "INSERT INTO uuids (uuid, used_at) VALUES ('%s','tenants')" % uuid
self.logger.debug(cmd)
self.cur.execute(cmd)
#insert tenant
cmd= "INSERT INTO tenants (" + \
",".join(map(str, tenant_dict.keys() )) + ") VALUES(" + \
",".join(map(lambda x: "Null" if x is None else "'"+str(x)+"'",tenant_dict.values() )) + ")"
self.logger.debug(cmd)
self.cur.execute(cmd)
inserted = self.cur.rowcount
##inserting new log
#del tenant_dict['uuid'] # not interested for the log
#cmd = "INSERT INTO logs (related,level,tenant_id,uuid,description) VALUES ('tenants','debug','%s','%s',\"new tenant %s\")" % (uuid, tenant_id, str(tenant_dict))
#self.logger.debug(cmd)
#self.cur.execute(cmd)
#commit transaction
self.cur.close()
if inserted == 0: return 0, uuid
with self.con:
self.cur = self.con.cursor()
#adding public flavors
cmd = "INSERT INTO tenants_flavors(flavor_id,tenant_id) SELECT uuid as flavor_id,'"+ tenant_id + "' FROM flavors WHERE public = 'yes'"
self.logger.debug(cmd)
self.cur.execute(cmd)
self.logger.debug("attached public flavors: %s", str(self.cur.rowcount))
#rows = self.cur.fetchall()
#for row in rows:
# cmd = "INSERT INTO tenants_flavors(flavor_id,tenant_id) VALUES('%s','%s')" % (row[0], tenant_id)
# self.cur.execute(cmd )
#adding public images
cmd = "INSERT INTO tenants_images(image_id,tenant_id) SELECT uuid as image_id,'"+ tenant_id + "' FROM images WHERE public = 'yes'"
self.logger.debug(cmd)
self.cur.execute(cmd)
self.logger.debug("attached public images: %s", str(self.cur.rowcount))
return 1, uuid
except (mdb.Error, AttributeError) as e:
if inserted==1:
self.logger.warning("new_tenant DB Exception %d: %s. Command %s",e.args[0], e.args[1], cmd)
return 1, uuid
else:
r,c = self.format_error(e, "new_tenant", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_row(self, table, INSERT, add_uuid=False, log=False):
''' Add one row into a table.
Atribure
INSERT: dictionary with the key: value to insert
table: table where to insert
add_uuid: if True, it will crated an uuid key entry at INSERT if not provided
It checks presence of uuid and add one automatically otherwise
Return: (result, uuid) where result can be 0 if error, or 1 if ok
'''
for retry_ in range(0,2):
cmd=""
try:
if add_uuid:
#create uuid if not provided
if 'uuid' not in INSERT:
uuid = INSERT['uuid'] = str(myUuid.uuid1()) # create_uuid
else:
uuid = str(INSERT['uuid'])
else:
uuid=None
with self.con:
self.cur = self.con.cursor()
if add_uuid:
#inserting new uuid
cmd = "INSERT INTO uuids (uuid, used_at) VALUES ('%s','%s')" % (uuid, table)
self.logger.debug(cmd)
self.cur.execute(cmd)
#insertion
cmd= "INSERT INTO " + table +" (" + \
",".join(map(str, INSERT.keys() )) + ") VALUES(" + \
",".join(map(lambda x: 'Null' if x is None else "'"+str(x)+"'", INSERT.values() )) + ")"
self.logger.debug(cmd)
self.cur.execute(cmd)
nb_rows = self.cur.rowcount
#inserting new log
#if nb_rows > 0 and log:
# if add_uuid: del INSERT['uuid']
# #obtain tenant_id for logs
# if 'tenant_id' in INSERT:
# tenant_id = INSERT['tenant_id']
# del INSERT['tenant_id']
# elif table == 'tenants':
# tenant_id = uuid
# else:
# tenant_id = None
# if uuid is None: uuid_k = uuid_v = ""
# else: uuid_k=",uuid"; uuid_v=",'" + str(uuid) + "'"
# if tenant_id is None: tenant_k = tenant_v = ""
# else: tenant_k=",tenant_id"; tenant_v=",'" + str(tenant_id) + "'"
# cmd = "INSERT INTO logs (related,level%s%s,description) VALUES ('%s','debug'%s%s,\"new %s %s\")" \
# % (uuid_k, tenant_k, table, uuid_v, tenant_v, table[:-1], str(INSERT))
# self.logger.debug(cmd)
# self.cur.execute(cmd)
return nb_rows, uuid
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "new_row", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def __remove_quotes(self, data):
'''remove single quotes ' of any string content of data dictionary'''
for k,v in data.items():
if type(v) == str:
if "'" in v:
data[k] = data[k].replace("'","_")
def _update_rows_internal(self, table, UPDATE, WHERE={}):
cmd= "UPDATE " + table +" SET " + \
",".join(map(lambda x: str(x)+'='+ self.__data2db_format(UPDATE[x]), UPDATE.keys() ));
if WHERE:
cmd += " WHERE " + " and ".join(map(lambda x: str(x)+ (' is Null' if WHERE[x] is None else"='"+str(WHERE[x])+"'" ), WHERE.keys() ))
self.logger.debug(cmd)
self.cur.execute(cmd)
nb_rows = self.cur.rowcount
return nb_rows, None
def update_rows(self, table, UPDATE, WHERE={}, log=False):
''' Update one or several rows into a table.
Atributes
UPDATE: dictionary with the key-new_value pairs to change
table: table to be modified
WHERE: dictionary to filter target rows, key-value
log: if true, a log entry is added at logs table
Return: (result, None) where result indicates the number of updated files
'''
for retry_ in range(0,2):
cmd=""
try:
#gettting uuid
uuid = WHERE.get('uuid')
with self.con:
self.cur = self.con.cursor()
cmd= "UPDATE " + table +" SET " + \
",".join(map(lambda x: str(x)+'='+ self.__data2db_format(UPDATE[x]), UPDATE.keys() ));
if WHERE:
cmd += " WHERE " + " and ".join(map(lambda x: str(x)+ (' is Null' if WHERE[x] is None else"='"+str(WHERE[x])+"'" ), WHERE.keys() ))
self.logger.debug(cmd)
self.cur.execute(cmd)
nb_rows = self.cur.rowcount
#if nb_rows > 0 and log:
# #inserting new log
# if uuid is None: uuid_k = uuid_v = ""
# else: uuid_k=",uuid"; uuid_v=",'" + str(uuid) + "'"
# cmd = "INSERT INTO logs (related,level%s,description) VALUES ('%s','debug'%s,\"updating %d entry %s\")" \
# % (uuid_k, table, uuid_v, nb_rows, (str(UPDATE)).replace('"','-') )
# self.logger.debug(cmd)
# self.cur.execute(cmd)
return nb_rows, uuid
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "update_rows", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def get_host(self, host_id):
if af.check_valid_uuid(host_id):
where_filter="uuid='" + host_id + "'"
else:
where_filter="name='" + host_id + "'"
for retry_ in range(0,2):
cmd=""
try:
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
#get HOST
cmd = "SELECT uuid, user, name, ip_name, description, ranking, admin_state_up, DATE_FORMAT(created_at,'%Y-%m-%dT%H:%i:%s') as created_at \
FROM hosts WHERE " + where_filter
self.logger.debug(cmd)
self.cur.execute(cmd)
if self.cur.rowcount == 0 :
return 0, "host '" + str(host_id) +"'not found."
elif self.cur.rowcount > 1 :
return 0, "host '" + str(host_id) +"' matches more than one result."
host = self.cur.fetchone()
host_id = host['uuid']
#get numa
cmd = "SELECT id, numa_socket, hugepages, memory, admin_state_up FROM numas WHERE host_id = '" + str(host_id) + "'"
self.logger.debug(cmd)
self.cur.execute(cmd)
host['numas'] = self.cur.fetchall()
for numa in host['numas']:
#print "SELECT core_id, instance_id, status, thread_id, v_thread_id FROM resources_core WHERE numa_id = '" + str(numa['id']) + "'"
#get cores
cmd = "SELECT core_id, instance_id, status, thread_id, v_thread_id FROM resources_core WHERE numa_id = '" + str(numa['id']) + "'"
self.logger.debug(cmd)
self.cur.execute(cmd)
numa['cores'] = self.cur.fetchall()
for core in numa['cores']:
if core['instance_id'] == None: del core['instance_id'], core['v_thread_id']
if core['status'] == 'ok': del core['status']
#get used memory
cmd = "SELECT sum(consumed) as hugepages_consumed FROM resources_mem WHERE numa_id = '" + str(numa['id']) + "' GROUP BY numa_id"
self.logger.debug(cmd)
self.cur.execute(cmd)
used = self.cur.fetchone()
used_= int(used['hugepages_consumed']) if used != None else 0
numa['hugepages_consumed'] = used_
#get ports
#cmd = "CALL GetPortsFromNuma(%s)'" % str(numa['id'])
#self.cur.callproc('GetPortsFromNuma', (numa['id'],) )
#every time a Procedure is launched you need to close and open the cursor
#under Error 2014: Commands out of sync; you can't run this command now
#self.cur.close()
#self.cur = self.con.cursor(mdb.cursors.DictCursor)
cmd="SELECT Mbps, pci, status, Mbps_used, instance_id, if(id=root_id,'PF','VF') as type_,\
switch_port, switch_dpid, mac, source_name\
FROM resources_port WHERE numa_id=%d ORDER BY root_id, type_ DESC" % (numa['id'])
self.logger.debug(cmd)
self.cur.execute(cmd)
ifaces = self.cur.fetchall()
#The SQL query will ensure to have SRIOV interfaces from a port first
sriovs=[]
Mpbs_consumed = 0
numa['interfaces'] = []
for iface in ifaces:
if not iface["instance_id"]:
del iface["instance_id"]
if iface['status'] == 'ok':
del iface['status']
Mpbs_consumed += int(iface["Mbps_used"])
del iface["Mbps_used"]
if iface["type_"]=='PF':
if not iface["switch_dpid"]:
del iface["switch_dpid"]
if not iface["switch_port"]:
del iface["switch_port"]
if sriovs:
iface["sriovs"] = sriovs
if Mpbs_consumed:
iface["Mpbs_consumed"] = Mpbs_consumed
del iface["type_"]
numa['interfaces'].append(iface)
sriovs=[]
Mpbs_consumed = 0
else: #VF, SRIOV
del iface["switch_port"]
del iface["switch_dpid"]
del iface["type_"]
del iface["Mbps"]
sriovs.append(iface)
#delete internal field
del numa['id']
return 1, host
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "get_host", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_uuid(self):
max_retries=10
while max_retries>0:
uuid = str( myUuid.uuid1() )
if self.check_uuid(uuid)[0] == 0:
return uuid
max_retries-=1
return uuid
def check_uuid(self, uuid):
'''check in the database if this uuid is already present'''
try:
cmd = "SELECT * FROM uuids where uuid='" + str(uuid) + "'"
with self.con:
self.cur = self.con.cursor(mdb.cursors.DictCursor)
self.logger.debug(cmd)
self.cur.execute(cmd)
rows = self.cur.fetchall()
return self.cur.rowcount, rows
except (mdb.Error, AttributeError) as e:
return self.format_error(e, "check_uuid", cmd)
def __get_next_ids(self):
'''get next auto increment index of all table in the database'''
self.cur.execute("SELECT table_name,AUTO_INCREMENT FROM information_schema.tables WHERE AUTO_INCREMENT IS NOT NULL AND table_schema = DATABASE()")
rows = self.cur.fetchall()
return self.cur.rowcount, dict(rows)
def edit_host(self, host_id, host_dict):
#get next port index
for retry_ in range(0,2):
cmd=""
try:
with self.con:
self.cur = self.con.cursor()
#update table host
numa_list = host_dict.pop('numas', () )
if host_dict:
self._update_rows_internal("hosts", host_dict, {"uuid": host_id})
where = {"host_id": host_id}
for numa_dict in numa_list:
where["numa_socket"] = str(numa_dict.pop('numa_socket'))
interface_list = numa_dict.pop('interfaces', () )
if numa_dict:
self._update_rows_internal("numas", numa_dict, where)
for interface in interface_list:
source_name = str(interface.pop("source_name") )
if interface:
#get interface id from resources_port
cmd= "SELECT rp.id as id FROM resources_port as rp join numas as n on n.id=rp.numa_id join hosts as h on h.uuid=n.host_id " +\
"WHERE host_id='%s' and rp.source_name='%s'" %(host_id, source_name)
self.logger.debug(cmd)
self.cur.execute(cmd)
row = self.cur.fetchone()
if self.cur.rowcount<=0:
return -HTTP_Bad_Request, "Interface source_name='%s' from numa_socket='%s' not found" % (source_name, str(where["numa_socket"]))
interface_id = row[0]
self._update_rows_internal("resources_port", interface, {"root_id": interface_id})
return self.get_host(host_id)
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "edit_host", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_host(self, host_dict):
#get next port index
for retry_ in range(0,2):
cmd=""
try:
with self.con:
self.cur = self.con.cursor()
result, next_ids = self.__get_next_ids()
#print "next_ids: " + str(next_ids)
if result <= 0: return result, "Internal DataBase error getting next id of tables"
#create uuid if not provided
if 'uuid' not in host_dict:
uuid = host_dict['uuid'] = str(myUuid.uuid1()) # create_uuid
else: #check uuid is valid
uuid = str(host_dict['uuid'])
# result, data = self.check_uuid(uuid)
# if (result == 1):
# return -1, "UUID '%s' already in use" % uuid
#inserting new uuid
cmd = "INSERT INTO uuids (uuid, used_at) VALUES ('%s','hosts')" % uuid
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#insert in table host
numa_list = host_dict.pop('numas', [])
#get nonhupages and nonisolated cpus
host_dict['RAM']=0
host_dict['cpus']=0
for numa in numa_list:
mem_numa = numa.get('memory', 0) - numa.get('hugepages',0)
if mem_numa>0:
host_dict['RAM'] += mem_numa
for core in numa.get("cores", []):
if "status" in core and core["status"]=="noteligible":
host_dict['cpus']+=1
host_dict['RAM']*=1024 # from GB to MB
keys = ",".join(host_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", host_dict.values() ) )
cmd = "INSERT INTO hosts (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#if result != 1: return -1, "Database Error while inserting at hosts table"
#insert numas
nb_numas = nb_cores = nb_ifaces = 0
for numa_dict in numa_list:
nb_numas += 1
interface_list = numa_dict.pop('interfaces', [])
core_list = numa_dict.pop('cores', [])
numa_dict['id'] = next_ids['numas']; next_ids['numas'] += 1
numa_dict['host_id'] = uuid
keys = ",".join(numa_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", numa_dict.values() ) )
cmd = "INSERT INTO numas (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#insert cores
for core_dict in core_list:
nb_cores += 1
core_dict['numa_id'] = numa_dict['id']
keys = ",".join(core_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", core_dict.values() ) )
cmd = "INSERT INTO resources_core (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#insert ports
for port_dict in interface_list:
nb_ifaces += 1
sriov_list = port_dict.pop('sriovs', [])
port_dict['numa_id'] = numa_dict['id']
port_dict['id'] = port_dict['root_id'] = next_ids['resources_port']
next_ids['resources_port'] += 1
switch_port = port_dict.get('switch_port', None)
switch_dpid = port_dict.get('switch_dpid', None)
keys = ",".join(port_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", port_dict.values() ) )
cmd = "INSERT INTO resources_port (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#insert sriovs into port table
for sriov_dict in sriov_list:
sriov_dict['switch_port'] = switch_port
sriov_dict['switch_dpid'] = switch_dpid
sriov_dict['numa_id'] = port_dict['numa_id']
sriov_dict['Mbps'] = port_dict['Mbps']
sriov_dict['root_id'] = port_dict['id']
sriov_dict['id'] = next_ids['resources_port']
if "vlan" in sriov_dict:
del sriov_dict["vlan"]
next_ids['resources_port'] += 1
keys = ",".join(sriov_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", sriov_dict.values() ) )
cmd = "INSERT INTO resources_port (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
result = self.cur.execute(cmd)
#inserting new log
#cmd = "INSERT INTO logs (related,level,uuid,description) VALUES ('hosts','debug','%s','new host: %d numas, %d theads, %d ifaces')" % (uuid, nb_numas, nb_cores, nb_ifaces)
#self.logger.debug(cmd)
#result = self.cur.execute(cmd)
#inseted ok
with self.con:
self.cur = self.con.cursor()
self.logger.debug("callproc('UpdateSwitchPort', () )")
self.cur.callproc('UpdateSwitchPort', () )
self.logger.debug("getting host '%s'",str(host_dict['uuid']))
return self.get_host(host_dict['uuid'])
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "new_host", cmd)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_flavor(self, flavor_dict, tenant_id ):
'''Add new flavor into the database. Create uuid if not provided
Atributes
flavor_dict: flavor dictionary with the key: value to insert. Must be valid flavors columns
tenant_id: if not 'any', it matches this flavor/tenant inserting at tenants_flavors table
Return: (result, data) where result can be
negative: error at inserting. data contain text
1, inserted, data contain inserted uuid flavor
'''
for retry_ in range(0,2):
cmd=""
try:
with self.con:
self.cur = self.con.cursor()
#create uuid if not provided
if 'uuid' not in flavor_dict:
uuid = flavor_dict['uuid'] = str(myUuid.uuid1()) # create_uuid
else: #check uuid is valid
uuid = str(flavor_dict['uuid'])
# result, data = self.check_uuid(uuid)
# if (result == 1):
# return -1, "UUID '%s' already in use" % uuid
#inserting new uuid
cmd = "INSERT INTO uuids (uuid, used_at) VALUES ('%s','flavors')" % uuid
self.logger.debug(cmd)
self.cur.execute(cmd)
#insert in table flavor
keys = ",".join(flavor_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", flavor_dict.values() ) )
cmd = "INSERT INTO flavors (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
self.cur.execute(cmd)
#if result != 1: return -1, "Database Error while inserting at flavors table"
#insert tenants_flavors
if tenant_id != 'any':
cmd = "INSERT INTO tenants_flavors (tenant_id,flavor_id) VALUES ('%s','%s')" % (tenant_id, uuid)
self.logger.debug(cmd)
self.cur.execute(cmd)
#inserting new log
#del flavor_dict['uuid']
#if 'extended' in flavor_dict: del flavor_dict['extended'] #remove two many information
#cmd = "INSERT INTO logs (related,level,uuid, tenant_id, description) VALUES ('flavors','debug','%s','%s',\"new flavor: %s\")" \
# % (uuid, tenant_id, str(flavor_dict))
#self.logger.debug(cmd)
#self.cur.execute(cmd)
#inseted ok
return 1, uuid
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "new_flavor", cmd, "update", tenant_id)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def new_image(self, image_dict, tenant_id):
'''Add new image into the database. Create uuid if not provided
Atributes
image_dict: image dictionary with the key: value to insert. Must be valid images columns
tenant_id: if not 'any', it matches this image/tenant inserting at tenants_images table
Return: (result, data) where result can be
negative: error at inserting. data contain text
1, inserted, data contain inserted uuid image
'''
for retry_ in range(0,2):
cmd=""
try:
with self.con:
self.cur = self.con.cursor()
#create uuid if not provided
if 'uuid' not in image_dict:
uuid = image_dict['uuid'] = str(myUuid.uuid1()) # create_uuid
else: #check uuid is valid
uuid = str(image_dict['uuid'])
# result, data = self.check_uuid(uuid)
# if (result == 1):
# return -1, "UUID '%s' already in use" % uuid
#inserting new uuid
cmd = "INSERT INTO uuids (uuid, used_at) VALUES ('%s','images')" % uuid
self.logger.debug(cmd)
self.cur.execute(cmd)
#insert in table image
keys = ",".join(image_dict.keys())
values = ",".join( map(lambda x: "Null" if x is None else "'"+str(x)+"'", image_dict.values() ) )
cmd = "INSERT INTO images (" + keys + ") VALUES (" + values + ")"
self.logger.debug(cmd)
self.cur.execute(cmd)
#if result != 1: return -1, "Database Error while inserting at images table"
#insert tenants_images
if tenant_id != 'any':
cmd = "INSERT INTO tenants_images (tenant_id,image_id) VALUES ('%s','%s')" % (tenant_id, uuid)
self.logger.debug(cmd)
self.cur.execute(cmd)
##inserting new log
#cmd = "INSERT INTO logs (related,level,uuid, tenant_id, description) VALUES ('images','debug','%s','%s',\"new image: %s path: %s\")" % (uuid, tenant_id, image_dict['name'], image_dict['path'])
#self.logger.debug(cmd)
#self.cur.execute(cmd)
#inseted ok
return 1, uuid
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "new_image", cmd, "update", tenant_id)
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def delete_image_flavor(self, item_type, item_id, tenant_id):
'''deletes an image or flavor from database
item_type must be a 'image' or 'flavor'
item_id is the uuid
tenant_id is the asociated tenant, can be 'any' with means all
If tenan_id is not any, it deletes from tenants_images/flavors,
which means this image/flavor is used by this tenant, and if success,
it tries to delete from images/flavors in case this is not public,
that only will success if image is private and not used by other tenants
If tenant_id is any, it tries to delete from both tables at the same transaction
so that image/flavor is completely deleted from all tenants or nothing
'''
for retry_ in range(0,2):
deleted = -1
deleted_item = -1
result = (-HTTP_Internal_Server_Error, "internal error")
cmd=""
try:
with self.con:
self.cur = self.con.cursor()
cmd = "DELETE FROM tenants_%ss WHERE %s_id = '%s'" % (item_type, item_type, item_id)
if tenant_id != 'any':
cmd += " AND tenant_id = '%s'" % tenant_id
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted = self.cur.rowcount
if tenant_id == 'any': #delete from images/flavors in the SAME transaction
cmd = "DELETE FROM %ss WHERE uuid = '%s'" % (item_type, item_id)
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted = self.cur.rowcount
if deleted>=1:
#delete uuid
cmd = "DELETE FROM uuids WHERE uuid = '%s'" % item_id
self.logger.debug(cmd)
self.cur.execute(cmd)
##inserting new log
#cmd = "INSERT INTO logs (related,level,uuid,tenant_id,description) \
# VALUES ('%ss','debug','%s','%s','delete %s completely')" % \
# (item_type, item_id, tenant_id, item_type)
#self.logger.debug(cmd)
#self.cur.execute(cmd)
return deleted, "%s '%s' completely deleted" % (item_type, item_id)
return 0, "%s '%s' not found" % (item_type, item_id)
if deleted == 1:
##inserting new log
#cmd = "INSERT INTO logs (related,level,uuid,tenant_id,description) \
# VALUES ('%ss','debug','%s','%s','delete %s reference for this tenant')" % \
# (item_type, item_id, tenant_id, item_type)
#self.logger.debug(cmd)
#self.cur.execute(cmd)
#commit transaction
self.cur.close()
#if tenant!=any delete from images/flavors in OTHER transaction. If fails is because dependencies so that not return error
if deleted==1:
with self.con:
self.cur = self.con.cursor()
#delete image/flavor if not public
cmd = "DELETE FROM %ss WHERE uuid = '%s' AND public = 'no'" % (item_type, item_id)
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted_item = self.cur.rowcount
if deleted_item == 1:
#delete uuid
cmd = "DELETE FROM uuids WHERE uuid = '%s'" % item_id
self.logger.debug(cmd)
self.cur.execute(cmd)
##inserting new log
#cmd = "INSERT INTO logs (related,level,uuid,tenant_id,description) \
# VALUES ('%ss','debug','%s','%s','delete %s completely')" % \
# (item_type, item_id, tenant_id, item_type)
#self.logger.debug(cmd)
#self.cur.execute(cmd)
except (mdb.Error, AttributeError) as e:
#print "delete_%s DB Exception %d: %s" % (item_type, e.args[0], e.args[1])
if deleted <0:
result = self.format_error(e, "delete_"+item_type, cmd, "delete", "servers")
finally:
if deleted==1:
return 1, "%s '%s' from tenant '%s' %sdeleted" % \
(item_type, item_id, tenant_id, "completely " if deleted_item==1 else "")
elif deleted==0:
return 0, "%s '%s' from tenant '%s' not found" % (item_type, item_id, tenant_id)
else:
if result[0]!=-HTTP_Request_Timeout or retry_==1: return result
def delete_row(self, table, uuid):
for retry_ in range(0,2):
cmd=""
try:
with self.con:
#delete host
self.cur = self.con.cursor()
cmd = "DELETE FROM %s WHERE uuid = '%s'" % (table, uuid)
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted = self.cur.rowcount
if deleted == 1:
#delete uuid
if table == 'tenants': tenant_str=uuid
else: tenant_str='Null'
self.cur = self.con.cursor()
cmd = "DELETE FROM uuids WHERE uuid = '%s'" % uuid
self.logger.debug(cmd)
self.cur.execute(cmd)
##inserting new log
#cmd = "INSERT INTO logs (related,level,uuid,tenant_id,description) VALUES ('%s','debug','%s','%s','delete %s')" % (table, uuid, tenant_str, table[:-1])
#self.logger.debug(cmd)
#self.cur.execute(cmd)
return deleted, table[:-1] + " '%s' %s" %(uuid, "deleted" if deleted==1 else "not found")
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "delete_row", cmd, "delete", 'instances' if table=='hosts' or table=='tenants' else 'dependencies')
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def delete_row_by_key(self, table, key, value):
for retry_ in range(0,2):
cmd=""
try:
with self.con:
#delete host
self.cur = self.con.cursor()
cmd = "DELETE FROM %s" % (table)
if key!=None:
if value!=None:
cmd += " WHERE %s = '%s'" % (key, value)
else:
cmd += " WHERE %s is null" % (key)
else: #delete all
pass
self.logger.debug(cmd)
self.cur.execute(cmd)
deleted = self.cur.rowcount
if deleted < 1:
return -1, 'Not found'
#delete uuid
return 0, deleted
except (mdb.Error, AttributeError) as e:
r,c = self.format_error(e, "delete_row_by_key", cmd, "delete", 'instances' if table=='hosts' or table=='tenants' else 'dependencies')
if r!=-HTTP_Request_Timeout or retry_==1: return r,c
def delete_row_by_dict(self, **sql_dict):
''' Deletes rows from a table.
Attribute sql_dir: dictionary with the following key: value
'FROM': string of table name (Mandatory)
'WHERE': dict of key:values, translated to key=value AND ... (Optional)
'WHERE_NOT': dict of key:values, translated to key<>value AND ... (Optional)
'WHERE_NOTNULL': (list or tuple of items that must not be null in a where ... (Optional)
'LIMIT': limit of number of rows (Optional)
Return: the (number of items deleted, descriptive test) if ok; (negative, descriptive text) if error
'''
#print sql_dict
from_ = "FROM " + str(sql_dict['FROM'])
#print 'from_', from_
if 'WHERE' in sql_dict and len(sql_dict['WHERE']) > 0:
w=sql_dict['WHERE']
where_ = "WHERE " + " AND ".join(map( lambda x: str(x) + (" is Null" if w[x] is None else "='"+str(w[x])+"'"), w.keys()) )
else: where_ = ""
if 'WHERE_NOT' in sql_dict and len(sql_dict['WHERE_NOT']) > 0:
w=sql_dict['WHERE_NOT']
where_2 = " AND ".join(map( lambda x: str(x) + (" is not Null" if w[x] is None else "<>'"+str(w[x])+"'"), w.keys()) )
if len(where_)==0: where_ = "WHERE " + where_2
else: where_ = where_ + " AND " + where_2
if 'WHERE_NOTNULL' in sql_dict and len(sql_dict['WHERE_NOTNULL']) > 0: