-
Notifications
You must be signed in to change notification settings - Fork 390
/
vnc_cassandra.py
1377 lines (1192 loc) · 56.8 KB
/
vnc_cassandra.py
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
#
# Copyright (c) 2014 Juniper Networks, Inc. All rights reserved.
#
import pycassa
from pycassa import ColumnFamily
from pycassa.batch import Mutator
from pycassa.system_manager import SystemManager, SIMPLE_STRATEGY
from pycassa.pool import AllServersUnavailable, MaximumRetryException
import gevent
from vnc_api import vnc_api
from exceptions import NoIdError, DatabaseUnavailableError, VncError
from pysandesh.connection_info import ConnectionState
from pysandesh.gen_py.process_info.ttypes import ConnectionStatus
from pysandesh.gen_py.process_info.ttypes import ConnectionType as ConnType
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh_common.vns.constants import API_SERVER_KEYSPACE_NAME, \
CASSANDRA_DEFAULT_GC_GRACE_SECONDS
import time
from cfgm_common import jsonutils as json
import utils
import datetime
import re
from operator import itemgetter
import itertools
import sys
from collections import Mapping
def merge_dict(orig_dict, new_dict):
for key, value in new_dict.iteritems():
if key not in orig_dict:
orig_dict[key] = new_dict[key]
elif isinstance(value, Mapping):
orig_dict[key] = merge_dict(orig_dict.get(key, {}), value)
elif isinstance(value, list):
orig_dict[key] = orig_dict[key].append(value)
else:
orig_dict[key] = new_dict[key]
return orig_dict
class VncCassandraClient(object):
# Name to ID mapping keyspace + tables
_UUID_KEYSPACE_NAME = API_SERVER_KEYSPACE_NAME
# TODO describe layout
_OBJ_UUID_CF_NAME = 'obj_uuid_table'
# TODO describe layout
_OBJ_FQ_NAME_CF_NAME = 'obj_fq_name_table'
# key: object type, column ($type:$id, uuid)
# where type is entity object is being shared with. Project initially
_OBJ_SHARED_CF_NAME = 'obj_shared_table'
_UUID_KEYSPACE = {
_UUID_KEYSPACE_NAME: {
_OBJ_UUID_CF_NAME: {
'cf_args': {
'autopack_names': False,
'autopack_values': False,
},
},
_OBJ_FQ_NAME_CF_NAME: {
'cf_args': {
'autopack_values': False,
},
},
_OBJ_SHARED_CF_NAME: {}
}
}
_MAX_COL = 10000000
@classmethod
def get_db_info(cls):
db_info = [(cls._UUID_KEYSPACE_NAME, [cls._OBJ_UUID_CF_NAME,
cls._OBJ_FQ_NAME_CF_NAME,
cls._OBJ_SHARED_CF_NAME])]
return db_info
# end get_db_info
@staticmethod
def _is_parent(column_name):
return column_name[:7] == 'parent:'
@staticmethod
def _is_prop(column_name):
return column_name[:5] == 'prop:'
@staticmethod
def _is_prop_list(column_name):
return column_name[:6] == 'propl:'
@staticmethod
def _is_prop_map(column_name):
return column_name[:6] == 'propm:'
@staticmethod
def _is_ref(column_name):
return column_name[:4] == 'ref:'
@staticmethod
def _is_backref(column_name):
return column_name[:8] == 'backref:'
@staticmethod
def _is_children(column_name):
return column_name[:9] == 'children:'
def __init__(self, server_list, db_prefix, rw_keyspaces, ro_keyspaces,
logger, generate_url=None, reset_config=False, credential=None):
self._reset_config = reset_config
self._cache_uuid_to_fq_name = {}
if db_prefix:
self._db_prefix = '%s_' %(db_prefix)
else:
self._db_prefix = ''
self._server_list = server_list
self._num_dbnodes = len(self._server_list)
self._conn_state = ConnectionStatus.INIT
self._logger = logger
self._credential = credential
# if no generate_url is specified, use a dummy function that always
# returns an empty string
self._generate_url = generate_url or (lambda x,y: '')
self._cf_dict = {}
self._ro_keyspaces = ro_keyspaces or {}
self._rw_keyspaces = rw_keyspaces or {}
if ((self._UUID_KEYSPACE_NAME not in self._ro_keyspaces) and
(self._UUID_KEYSPACE_NAME not in self._rw_keyspaces)):
self._ro_keyspaces.update(self._UUID_KEYSPACE)
self._cassandra_init(server_list)
self._cache_uuid_to_fq_name = {}
self._obj_uuid_cf = self._cf_dict[self._OBJ_UUID_CF_NAME]
self._obj_fq_name_cf = self._cf_dict[self._OBJ_FQ_NAME_CF_NAME]
self._obj_shared_cf = self._cf_dict[self._OBJ_SHARED_CF_NAME]
# end __init__
def get_cf(self, cf_name):
return self._cf_dict.get(cf_name)
#end
def add(self, cf_name, key, value):
try:
self.get_cf(cf_name).insert(key, value)
return True
except:
return False
#end
def get(self, cf_name, key, columns=None, start='', finish=''):
result = self.multiget(cf_name,
[key],
columns=columns,
start=start,
finish=finish)
return result.get(key)
def multiget(self, cf_name, keys, columns=None, start='', finish='',
timestamp=False):
_thrift_limit_size = 10000
results = {}
cf = self.get_cf(cf_name)
if not columns or start or finish:
try:
results = cf.multiget(keys,
column_start=start,
column_finish=finish,
include_timestamp=timestamp,
column_count=self._MAX_COL)
except OverflowError:
for key in keys:
rows = dict(cf.xget(key,
column_start=start,
column_finish=finish,
include_timestamp=timestamp))
if rows:
results[key] = rows
if columns:
max_key_range, _ = divmod(_thrift_limit_size, len(columns))
if max_key_range > 1:
for key_chunk in [keys[x:x+max_key_range] for x in
xrange(0, len(keys), max_key_range)]:
rows = cf.multiget(key_chunk,
columns=columns,
include_timestamp=timestamp,
column_count=self._MAX_COL)
merge_dict(results, rows)
elif max_key_range == 0:
for column_chunk in [columns[x:x+(_thrift_limit_size - 1)] for x in
xrange(0, len(columns), _thrift_limit_size - 1)]:
rows = cf.multiget(keys,
columns=column_chunk,
include_timestamp=timestamp,
column_count=self._MAX_COL)
merge_dict(results, rows)
elif max_key_range == 1:
for key in keys:
try:
cols = cf.get(key,
columns=column_chunk,
include_timestamp=timestamp,
column_count=self._MAX_COL)
except pycassa.NotFoundException:
continue
results.setdefault(key, {}).update(cols)
for key in results:
for col, val in results[key].items():
try:
if timestamp:
results[key][col] = (json.loads(val[0]), val[1])
else:
results[key][col] = json.loads(val)
except ValueError as e:
msg = ("Cannot json load the value of cf: %s, key:%s "
"(error: %s). Use it as is: %s" %
(cf_name, key, str(e),
val if not timestamp else val[0]))
self._logger(msg, level=SandeshLevel.SYS_WARN)
results[key][col] = val
return results
def delete(self, cf_name, key):
try:
self.get_cf(cf_name).remove(key)
return True
except:
return False
#end
def get_range(self, cf_name):
try:
return self.get_cf(cf_name).get_range(column_count=100000)
except:
return None
#end
def get_one_col(self, cf_name, key, column):
col = self.multiget(cf_name, [key], columns=[column])
if key not in col:
raise NoIdError(key)
elif len(col[key]) > 1:
raise VncError('Multi match %s for %s' % (column, key))
return col[key][column]
def _create_prop(self, bch, obj_uuid, prop_name, prop_val):
bch.insert(obj_uuid, {'prop:%s' % (prop_name): json.dumps(prop_val)})
# end _create_prop
def _update_prop(self, bch, obj_uuid, prop_name, new_props):
if new_props[prop_name] is None:
bch.remove(obj_uuid, columns=['prop:' + prop_name])
else:
bch.insert(
obj_uuid,
{'prop:' + prop_name: json.dumps(new_props[prop_name])})
# prop has been accounted for, remove so only new ones remain
del new_props[prop_name]
# end _update_prop
def _add_to_prop_list(self, bch, obj_uuid, prop_name,
prop_elem_value, prop_elem_position):
bch.insert(obj_uuid,
{'propl:%s:%s' %(prop_name, prop_elem_position):
json.dumps(prop_elem_value)})
# end _add_to_prop_list
def _delete_from_prop_list(self, bch, obj_uuid, prop_name,
prop_elem_position):
bch.remove(obj_uuid,
columns=['propl:%s:%s' %(prop_name, prop_elem_position)])
# end _delete_from_prop_list
def _set_in_prop_map(self, bch, obj_uuid, prop_name,
prop_elem_value, prop_elem_position):
bch.insert(obj_uuid,
{'propm:%s:%s' %(prop_name, prop_elem_position):
json.dumps(prop_elem_value)})
# end _set_in_prop_map
def _delete_from_prop_map(self, bch, obj_uuid, prop_name,
prop_elem_position):
bch.remove(obj_uuid,
columns=['propm:%s:%s' %(prop_name, prop_elem_position)])
# end _delete_from_prop_map
def _create_child(self, bch, parent_type, parent_uuid,
child_type, child_uuid):
child_col = {'children:%s:%s' %
(child_type, child_uuid): json.dumps(None)}
bch.insert(parent_uuid, child_col)
parent_col = {'parent:%s:%s' %
(parent_type, parent_uuid): json.dumps(None)}
bch.insert(child_uuid, parent_col)
# end _create_child
def _delete_child(self, bch, parent_type, parent_uuid,
child_type, child_uuid):
child_col = {'children:%s:%s' %
(child_type, child_uuid): json.dumps(None)}
bch.remove(parent_uuid, columns=[
'children:%s:%s' % (child_type, child_uuid)])
# end _delete_child
def _create_ref(self, bch, obj_type, obj_uuid, ref_obj_type, ref_uuid,
ref_data):
bch.insert(
obj_uuid, {'ref:%s:%s' %
(ref_obj_type, ref_uuid): json.dumps(ref_data)})
if obj_type == ref_obj_type:
bch.insert(
ref_uuid, {'ref:%s:%s' %
(obj_type, obj_uuid): json.dumps(ref_data)})
else:
bch.insert(
ref_uuid, {'backref:%s:%s' %
(obj_type, obj_uuid): json.dumps(ref_data)})
# end _create_ref
def _update_ref(self, bch, obj_type, obj_uuid, ref_obj_type, old_ref_uuid,
new_ref_infos):
if ref_obj_type not in new_ref_infos:
# update body didn't touch this type, nop
return
if old_ref_uuid not in new_ref_infos[ref_obj_type]:
# remove old ref
bch.remove(obj_uuid, columns=[
'ref:%s:%s' % (ref_obj_type, old_ref_uuid)])
if obj_type == ref_obj_type:
bch.remove(old_ref_uuid, columns=[
'ref:%s:%s' % (obj_type, obj_uuid)])
else:
bch.remove(old_ref_uuid, columns=[
'backref:%s:%s' % (obj_type, obj_uuid)])
else:
# retain old ref with new ref attr
new_ref_data = new_ref_infos[ref_obj_type][old_ref_uuid]
bch.insert(
obj_uuid,
{'ref:%s:%s' %
(ref_obj_type, old_ref_uuid): json.dumps(new_ref_data)})
if obj_type == ref_obj_type:
bch.insert(
old_ref_uuid,
{'ref:%s:%s' %
(obj_type, obj_uuid): json.dumps(new_ref_data)})
else:
bch.insert(
old_ref_uuid,
{'backref:%s:%s' %
(obj_type, obj_uuid): json.dumps(new_ref_data)})
# uuid has been accounted for, remove so only new ones remain
del new_ref_infos[ref_obj_type][old_ref_uuid]
# end _update_ref
def _delete_ref(self, bch, obj_type, obj_uuid, ref_obj_type, ref_uuid):
send = False
if bch is None:
send = True
bch = self._cassandra_db._obj_uuid_cf.batch()
bch.remove(obj_uuid, columns=['ref:%s:%s' % (ref_obj_type, ref_uuid)])
if obj_type == ref_obj_type:
bch.remove(ref_uuid, columns=[
'ref:%s:%s' % (obj_type, obj_uuid)])
else:
bch.remove(ref_uuid, columns=[
'backref:%s:%s' % (obj_type, obj_uuid)])
if send:
bch.send()
# end _delete_ref
def _update_sandesh_status(self, status, msg=''):
ConnectionState.update(conn_type=ConnType.DATABASE,
name='Cassandra', status=status, message=msg,
server_addrs=self._server_list)
def _handle_exceptions(self, func):
def wrapper(*args, **kwargs):
if (sys._getframe(1).f_code.co_name != 'multiget' and
func.__name__ in ['get', 'multiget']):
msg = ("It is not recommended to use 'get' or 'multiget' "
"pycassa methods. It's better to use 'xget' or "
"'get_range' methods due to thrift limitations")
self._logger(msg, level=SandeshLevel.SYS_WARN)
try:
if self._conn_state != ConnectionStatus.UP:
# will set conn_state to UP if successful
self._cassandra_init_conn_pools()
return func(*args, **kwargs)
except (AllServersUnavailable, MaximumRetryException) as e:
if self._conn_state != ConnectionStatus.DOWN:
self._update_sandesh_status(ConnectionStatus.DOWN)
msg = 'Cassandra connection down. Exception in %s' %(
str(func))
self._logger(msg, level=SandeshLevel.SYS_ERR)
self._conn_state = ConnectionStatus.DOWN
raise DatabaseUnavailableError(
'Error, %s: %s' %(str(e), utils.detailed_traceback()))
return wrapper
# end _handle_exceptions
# Helper routines for cassandra
def _cassandra_init(self, server_list):
# 1. Ensure keyspace and schema/CFs exist
# 2. Read in persisted data and publish to ifmap server
self._update_sandesh_status(ConnectionStatus.INIT)
ColumnFamily.get = self._handle_exceptions(ColumnFamily.get)
ColumnFamily.multiget = self._handle_exceptions(ColumnFamily.multiget)
ColumnFamily.xget = self._handle_exceptions(ColumnFamily.xget)
ColumnFamily.get_range = self._handle_exceptions(ColumnFamily.get_range)
ColumnFamily.insert = self._handle_exceptions(ColumnFamily.insert)
ColumnFamily.remove = self._handle_exceptions(ColumnFamily.remove)
Mutator.send = self._handle_exceptions(Mutator.send)
self.sys_mgr = self._cassandra_system_manager()
self.existing_keyspaces = self.sys_mgr.list_keyspaces()
for ks,cf_dict in self._rw_keyspaces.items():
keyspace = '%s%s' %(self._db_prefix, ks)
self._cassandra_ensure_keyspace(keyspace, cf_dict)
for ks,_ in self._ro_keyspaces.items():
keyspace = '%s%s' %(self._db_prefix, ks)
self._cassandra_wait_for_keyspace(keyspace)
self._cassandra_init_conn_pools()
# end _cassandra_init
def _cassandra_system_manager(self):
# Retry till cassandra is up
server_idx = 0
connected = False
while not connected:
try:
cass_server = self._server_list[server_idx]
sys_mgr = SystemManager(cass_server,
credentials=self._credential)
connected = True
except Exception:
# TODO do only for
# thrift.transport.TTransport.TTransportException
server_idx = (server_idx + 1) % self._num_dbnodes
time.sleep(3)
return sys_mgr
# end _cassandra_system_manager
def _cassandra_wait_for_keyspace(self, keyspace):
# Wait for it to be created by another process
while keyspace not in self.existing_keyspaces:
gevent.sleep(1)
self._logger("Waiting for keyspace %s to be created" % keyspace,
level=SandeshLevel.SYS_NOTICE)
self.existing_keyspaces = self.sys_mgr.list_keyspaces()
# end _cassandra_wait_for_keyspace
def _cassandra_ensure_keyspace(self, keyspace_name, cf_dict):
if self._reset_config and keyspace_name in self.existing_keyspaces:
try:
self.sys_mgr.drop_keyspace(keyspace_name)
except pycassa.cassandra.ttypes.InvalidRequestException as e:
# TODO verify only EEXISTS
self._logger(str(e), level=SandeshLevel.SYS_NOTICE)
if (self._reset_config or keyspace_name not in self.existing_keyspaces):
try:
self.sys_mgr.create_keyspace(keyspace_name, SIMPLE_STRATEGY,
{'replication_factor': str(self._num_dbnodes)})
except pycassa.cassandra.ttypes.InvalidRequestException as e:
# TODO verify only EEXISTS
self._logger("Warning! " + str(e), level=SandeshLevel.SYS_WARN)
gc_grace_sec = CASSANDRA_DEFAULT_GC_GRACE_SECONDS
for cf_name in cf_dict:
create_cf_kwargs = cf_dict[cf_name].get('create_cf_args', {})
try:
self.sys_mgr.create_column_family(
keyspace_name, cf_name,
gc_grace_seconds=gc_grace_sec,
default_validation_class='UTF8Type',
**create_cf_kwargs)
except pycassa.cassandra.ttypes.InvalidRequestException as e:
# TODO verify only EEXISTS
self._logger("Warning! " + str(e), level=SandeshLevel.SYS_WARN)
self.sys_mgr.alter_column_family(keyspace_name, cf_name,
gc_grace_seconds=gc_grace_sec,
default_validation_class='UTF8Type',
**create_cf_kwargs)
# end _cassandra_ensure_keyspace
def _cassandra_init_conn_pools(self):
for ks,cf_dict in itertools.chain(self._rw_keyspaces.items(),
self._ro_keyspaces.items()):
keyspace = '%s%s' %(self._db_prefix, ks)
pool = pycassa.ConnectionPool(
keyspace, self._server_list, max_overflow=-1, use_threadlocal=True,
prefill=True, pool_size=20, pool_timeout=120,
max_retries=30, timeout=5, credentials=self._credential)
rd_consistency = pycassa.cassandra.ttypes.ConsistencyLevel.QUORUM
wr_consistency = pycassa.cassandra.ttypes.ConsistencyLevel.QUORUM
for cf_name in cf_dict:
cf_kwargs = cf_dict[cf_name].get('cf_args', {})
self._cf_dict[cf_name] = ColumnFamily(
pool, cf_name, read_consistency_level=rd_consistency,
write_consistency_level=wr_consistency,
dict_class=dict,
**cf_kwargs)
ConnectionState.update(conn_type = ConnType.DATABASE,
name = 'Cassandra', status = ConnectionStatus.UP, message = '',
server_addrs = self._server_list)
self._conn_state = ConnectionStatus.UP
msg = 'Cassandra connection ESTABLISHED'
self._logger(msg, level=SandeshLevel.SYS_NOTICE)
# end _cassandra_init_conn_pools
def _get_resource_class(self, obj_type):
if hasattr(self, '_db_client_mgr'):
return self._db_client_mgr.get_resource_class(obj_type)
cls_name = '%s' % (utils.CamelCase(obj_type))
return getattr(vnc_api, cls_name)
# end _get_resource_class
def _get_xsd_class(self, xsd_type):
return getattr(vnc_api, xsd_type)
# end _get_xsd_class
def object_create(self, obj_type, obj_id, obj_dict,
uuid_batch=None, fqname_batch=None):
obj_class = self._get_resource_class(obj_type)
if uuid_batch:
bch = uuid_batch
else:
# Gather column values for obj and updates to backrefs
# in a batch and write it at the end
bch = self._obj_uuid_cf.batch()
obj_cols = {}
obj_cols['fq_name'] = json.dumps(obj_dict['fq_name'])
obj_cols['type'] = json.dumps(obj_type)
if 'parent_type' in obj_dict:
# non config-root child
parent_type = obj_dict['parent_type']
if parent_type not in obj_class.parent_types:
return False, (400, 'Invalid parent type: %s' % parent_type)
parent_object_type = \
self._get_resource_class(parent_type).object_type
parent_fq_name = obj_dict['fq_name'][:-1]
obj_cols['parent_type'] = json.dumps(parent_type)
parent_uuid = self.fq_name_to_uuid(parent_object_type,
parent_fq_name)
self._create_child(bch, parent_object_type, parent_uuid, obj_type,
obj_id)
# Properties
for prop_field in obj_class.prop_fields:
field = obj_dict.get(prop_field)
# Specifically checking for None
if field is None:
continue
if prop_field == 'id_perms':
field['created'] = datetime.datetime.utcnow().isoformat()
field['last_modified'] = field['created']
if prop_field in obj_class.prop_list_fields:
# store list elements in list order
# iterate on wrapped element or directly or prop field
if obj_class.prop_list_field_has_wrappers[prop_field]:
wrapper_field = field.keys()[0]
list_coll = field[wrapper_field]
else:
list_coll = field
for i in range(len(list_coll)):
self._add_to_prop_list(
bch, obj_id, prop_field, list_coll[i], str(i))
elif prop_field in obj_class.prop_map_fields:
# iterate on wrapped element or directly or prop field
if obj_class.prop_map_field_has_wrappers[prop_field]:
wrapper_field = field.keys()[0]
map_coll = field[wrapper_field]
else:
map_coll = field
map_key_name = obj_class.prop_map_field_key_names[prop_field]
for map_elem in map_coll:
map_key = map_elem[map_key_name]
self._set_in_prop_map(
bch, obj_id, prop_field, map_elem, map_key)
else:
self._create_prop(bch, obj_id, prop_field, field)
# References
# e.g. ref_field = 'network_ipam_refs'
# ref_res_type = 'network-ipam'
# ref_link_type = 'VnSubnetsType'
# is_weakref = False
for ref_field in obj_class.ref_fields:
ref_fld_types_list = list(obj_class.ref_field_types[ref_field])
ref_res_type = ref_fld_types_list[0]
ref_link_type = ref_fld_types_list[1]
ref_obj_type = self._get_resource_class(ref_res_type).object_type
refs = obj_dict.get(ref_field, [])
for ref in refs:
ref_uuid = self.fq_name_to_uuid(ref_obj_type, ref['to'])
ref_attr = ref.get('attr')
ref_data = {'attr': ref_attr, 'is_weakref': False}
self._create_ref(bch, obj_type, obj_id, ref_obj_type, ref_uuid,
ref_data)
bch.insert(obj_id, obj_cols)
if not uuid_batch:
bch.send()
# Update fqname table
fq_name_str = ':'.join(obj_dict['fq_name'])
fq_name_cols = {utils.encode_string(fq_name_str) + ':' + obj_id:
json.dumps(None)}
if fqname_batch:
fqname_batch.insert(obj_type, fq_name_cols)
else:
self._obj_fq_name_cf.insert(obj_type, fq_name_cols)
return (True, '')
# end object_create
def object_read(self, obj_type, obj_uuids, field_names=None):
if not obj_uuids:
return (True, [])
# if field_names=None, all fields will be read/returned
obj_class = self._get_resource_class(obj_type)
ref_fields = obj_class.ref_fields
backref_fields = obj_class.backref_fields
children_fields = obj_class.children_fields
list_fields = obj_class.prop_list_fields
map_fields = obj_class.prop_map_fields
prop_fields = obj_class.prop_fields - (list_fields | map_fields)
# optimize for common case of reading non-backref, non-children fields
# ignoring columns starting from 'b' and 'c' - significant performance
# impact in scaled setting. e.g. read of project
obj_rows = {}
if (field_names is None or
set(field_names) & (backref_fields | children_fields)):
# atleast one backref/children field is needed
obj_rows = self.multiget(self._OBJ_UUID_CF_NAME,
obj_uuids,
timestamp=True)
elif not set(field_names) & ref_fields:
# specific props have been asked fetch exactly those
columns = set(['type', 'fq_name', 'parent_type'])
for fname in set(field_names) & prop_fields:
columns.add('prop:' + fname)
obj_rows = self.multiget(self._OBJ_UUID_CF_NAME,
obj_uuids,
columns=list(columns),
start='parent:',
finish='parent;',
timestamp=True)
for fname in set(field_names) & list_fields:
merge_dict(obj_rows,
self.multiget(self._OBJ_UUID_CF_NAME,
obj_uuids,
start='propl:%s:' % fname,
finish='propl:%s;' % fname,
timestamp=True))
for fname in set(field_names) & map_fields:
merge_dict(obj_rows,
self.multiget(self._OBJ_UUID_CF_NAME,
obj_uuids,
start='propm:%s:' % fname,
finish='propm:%s;' % fname,
timestamp=True))
else:
# ignore reading backref + children columns
obj_rows = self.multiget(self._OBJ_UUID_CF_NAME,
obj_uuids,
start='d',
timestamp=True)
if not obj_rows:
if len(obj_uuids) == 1:
raise NoIdError(obj_uuids[0])
else:
return (True, [])
results = []
for obj_uuid, obj_cols in obj_rows.items():
if obj_type != obj_cols.pop('type')[0]:
continue
result = {}
result['uuid'] = obj_uuid
result['fq_name'] = obj_cols.pop('fq_name')[0]
for col_name in obj_cols.keys():
if self._is_parent(col_name):
# non config-root child
(_, _, parent_uuid) = col_name.split(':')
parent_res_type = obj_cols['parent_type'][0]
result['parent_type'] = parent_res_type
try:
result['parent_uuid'] = parent_uuid
result['parent_href'] = self._generate_url(parent_res_type,
parent_uuid)
except NoIdError:
err_msg = 'Unknown uuid for parent ' + result['fq_name'][-2]
return (False, err_msg)
continue
if self._is_prop(col_name):
(_, prop_name) = col_name.split(':')
if ((prop_name not in prop_fields) or
(field_names and prop_name not in field_names)):
continue
result[prop_name] = obj_cols[col_name][0]
continue
if self._is_prop_list(col_name):
(_, prop_name, prop_elem_position) = col_name.split(':')
if field_names and prop_name not in field_names:
continue
if obj_class.prop_list_field_has_wrappers[prop_name]:
prop_field_types = obj_class.prop_field_types[prop_name]
wrapper_type = prop_field_types['xsd_type']
wrapper_cls = self._get_xsd_class(wrapper_type)
wrapper_field = wrapper_cls.attr_fields[0]
if prop_name not in result:
result[prop_name] = {wrapper_field: []}
result[prop_name][wrapper_field].append(
(obj_cols[col_name][0], prop_elem_position))
else:
if prop_name not in result:
result[prop_name] = []
result[prop_name].append((obj_cols[col_name][0],
prop_elem_position))
continue
if self._is_prop_map(col_name):
(_, prop_name, _) = col_name.split(':')
if field_names and prop_name not in field_names:
continue
if obj_class.prop_map_field_has_wrappers[prop_name]:
prop_field_types = obj_class.prop_field_types[prop_name]
wrapper_type = prop_field_types['xsd_type']
wrapper_cls = self._get_xsd_class(wrapper_type)
wrapper_field = wrapper_cls.attr_fields[0]
if prop_name not in result:
result[prop_name] = {wrapper_field: []}
result[prop_name][wrapper_field].append(
obj_cols[col_name][0])
else:
if prop_name not in result:
result[prop_name] = []
result[prop_name].append(obj_cols[col_name][0])
continue
if self._is_children(col_name):
(_, child_type, child_uuid) = col_name.split(':')
if field_names and '%ss' %(child_type) not in field_names:
continue
if child_type+'s' not in children_fields:
continue
child_tstamp = obj_cols[col_name][1]
try:
self._read_child(result, obj_uuid, child_type,
child_uuid, child_tstamp)
except NoIdError:
continue
continue
if self._is_ref(col_name):
(_, ref_type, ref_uuid) = col_name.split(':')
if ((ref_type+'_refs' not in ref_fields) or
(field_names and ref_type + '_refs' not in field_names)):
continue
self._read_ref(result, obj_uuid, ref_type, ref_uuid,
obj_cols[col_name][0])
continue
if self._is_backref(col_name):
(_, back_ref_type, back_ref_uuid) = col_name.split(':')
if back_ref_type+'_back_refs' not in backref_fields:
continue
if (field_names and
'%s_back_refs' %(back_ref_type) not in field_names):
continue
try:
self._read_back_ref(result, obj_uuid, back_ref_type,
back_ref_uuid, obj_cols[col_name][0])
except NoIdError:
continue
continue
# for all column names
# sort children by creation time
for child_field in obj_class.children_fields:
if child_field not in result:
continue
sorted_children = sorted(result[child_field],
key = itemgetter('tstamp'))
# re-write result's children without timestamp
result[child_field] = sorted_children
[child.pop('tstamp') for child in result[child_field]]
# for all children
# Ordering property lists by position attribute
for prop_name in (obj_class.prop_list_fields & set(result.keys())):
if isinstance(result[prop_name], list):
result[prop_name] = [el[0] for el in
sorted(result[prop_name],
key=itemgetter(1))]
elif isinstance(result[prop_name], dict):
wrapper, unsorted_list = result[prop_name].popitem()
result[prop_name][wrapper] = [el[0] for el in
sorted(unsorted_list,
key=itemgetter(1))]
results.append(result)
# end for all rows
return (True, results)
# end object_read
def object_count_children(self, obj_type, obj_uuid, child_type):
if child_type is None:
return (False, '')
obj_class = self._get_resource_class(obj_type)
obj_uuid_cf = self._obj_uuid_cf
if child_type not in obj_class.children_fields:
return (False,
'%s is not a child type of %s' %(child_type, obj_type))
col_start = 'children:'+child_type[:-1]+':'
col_finish = 'children:'+child_type[:-1]+';'
num_children = obj_uuid_cf.get_count(obj_uuid,
column_start=col_start,
column_finish=col_finish)
return (True, num_children)
# end object_count_children
def update_last_modified(self, bch, obj_uuid, id_perms=None):
if id_perms is None:
id_perms = self.get_one_col(self._OBJ_UUID_CF_NAME,
obj_uuid,
'prop:id_perms')
id_perms['last_modified'] = datetime.datetime.utcnow().isoformat()
self._update_prop(bch, obj_uuid, 'id_perms', {'id_perms': id_perms})
# end update_last_modified
def object_update(self, obj_type, obj_uuid, new_obj_dict,
uuid_batch=None):
obj_class = self._get_resource_class(obj_type)
# Grab ref-uuids and properties in new version
new_ref_infos = {}
# Properties
new_props = {}
for prop_field in obj_class.prop_fields:
if prop_field in new_obj_dict:
new_props[prop_field] = new_obj_dict[prop_field]
# References
# e.g. ref_field = 'network_ipam_refs'
# ref_type = 'network-ipam'
# ref_link_type = 'VnSubnetsType'
# is_weakref = False
for ref_field in obj_class.ref_fields:
ref_fld_types_list = list(obj_class.ref_field_types[ref_field])
ref_res_type = ref_fld_types_list[0]
ref_link_type = ref_fld_types_list[1]
is_weakref = ref_fld_types_list[2]
ref_obj_type = self._get_resource_class(ref_res_type).object_type
if ref_field in new_obj_dict:
new_refs = new_obj_dict[ref_field]
new_ref_infos[ref_obj_type] = {}
for new_ref in new_refs or []:
new_ref_uuid = self.fq_name_to_uuid(ref_obj_type,
new_ref['to'])
new_ref_attr = new_ref.get('attr')
new_ref_data = {'attr': new_ref_attr,
'is_weakref': is_weakref}
new_ref_infos[ref_obj_type][new_ref_uuid] = new_ref_data
# Gather column values for obj and updates to backrefs
# in a batch and write it at the end
obj_uuid_cf = self._obj_uuid_cf
if uuid_batch:
bch = uuid_batch
else:
bch = obj_uuid_cf.batch()
for col_name, col_value in obj_uuid_cf.xget(obj_uuid):
if self._is_prop(col_name):
(_, prop_name) = col_name.split(':')
if prop_name == 'id_perms':
# id-perms always has to be updated for last-mod timestamp
# get it from request dict(or from db if not in request dict)
new_id_perms = new_obj_dict.get(
prop_name, json.loads(col_value))
self.update_last_modified(bch, obj_uuid, new_id_perms)
elif prop_name in new_obj_dict:
self._update_prop(bch, obj_uuid, prop_name, new_props)
if self._is_prop_list(col_name):
(_, prop_name, prop_elem_position) = col_name.split(':')
if prop_name in new_props:
# delete all old values of prop list
self._delete_from_prop_list(
bch, obj_uuid, prop_name, prop_elem_position)
if self._is_prop_map(col_name):
(_, prop_name, prop_elem_position) = col_name.split(':')
if prop_name in new_props:
# delete all old values of prop list
self._delete_from_prop_map(
bch, obj_uuid, prop_name, prop_elem_position)
if self._is_ref(col_name):
(_, ref_type, ref_uuid) = col_name.split(':')
self._update_ref(bch, obj_type, obj_uuid, ref_type, ref_uuid,
new_ref_infos)
# for all column names
# create new refs
for ref_type in new_ref_infos.keys():
for ref_uuid in new_ref_infos[ref_type].keys():
ref_data = new_ref_infos[ref_type][ref_uuid]
self._create_ref(bch, obj_type, obj_uuid, ref_type, ref_uuid,
ref_data)
# create new props
for prop_name in new_props.keys():
if prop_name in obj_class.prop_list_fields:
# store list elements in list order
# iterate on wrapped element or directly on prop field
# for wrapped lists, store without the wrapper. regenerate
# wrapper on read
if (obj_class.prop_list_field_has_wrappers[prop_name] and
new_props[prop_name]):
wrapper_field = new_props[prop_name].keys()[0]
list_coll = new_props[prop_name][wrapper_field]
else:
list_coll = new_props[prop_name]
for i in range(len(list_coll)):
self._add_to_prop_list(bch, obj_uuid,
prop_name, list_coll[i], str(i))
elif prop_name in obj_class.prop_map_fields:
# store map elements in key order
# iterate on wrapped element or directly on prop field
# for wrapped lists, store without the wrapper. regenerate
# wrapper on read
if (obj_class.prop_map_field_has_wrappers[prop_name] and
new_props[prop_name]):
wrapper_field = new_props[prop_name].keys()[0]
map_coll = new_props[prop_name][wrapper_field]
else:
map_coll = new_props[prop_name]
map_key_name = obj_class.prop_map_field_key_names[prop_name]
for map_elem in map_coll:
map_key = map_elem[map_key_name]
self._set_in_prop_map(bch, obj_uuid,
prop_name, map_elem, map_key)
else:
self._create_prop(bch, obj_uuid, prop_name, new_props[prop_name])
if not uuid_batch:
bch.send()
return (True, '')
# end object_update
def object_list(self, obj_type, parent_uuids=None, back_ref_uuids=None,
obj_uuids=None, count=False, filters=None):