/
vnc_cfg_ifmap.py
1812 lines (1544 loc) · 69 KB
/
vnc_cfg_ifmap.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) 2013 Juniper Networks, Inc. All rights reserved.
#
"""
Layer that transforms VNC config objects to ifmap representation
"""
from cfgm_common.zkclient import ZookeeperClient, IndexAllocator
from gevent import ssl, monkey
monkey.patch_all()
import gevent
import gevent.event
from gevent.queue import Queue, Empty
import sys
import time
import functools
from pprint import pformat
from lxml import etree, objectify
import cgitb
import StringIO
import re
import socket
from netaddr import IPNetwork
from cfgm_common import ignore_exceptions, utils
from cfgm_common.ifmap.client import client, namespaces
from cfgm_common.ifmap.request import NewSessionRequest, PublishRequest
from cfgm_common.ifmap.id import Identity
from cfgm_common.ifmap.operations import PublishUpdateOperation,\
PublishDeleteOperation
from cfgm_common.ifmap.response import Response, newSessionResult
from cfgm_common.ifmap.metadata import Metadata
from cfgm_common.exceptions import ResourceExhaustionError, ResourceExistsError
from cfgm_common.vnc_cassandra import VncCassandraClient
from cfgm_common.vnc_kombu import VncKombuClient
import copy
from cfgm_common import jsonutils as json
import uuid
import datetime
import pycassa
import pycassa.util
import pycassa.cassandra.ttypes
from pycassa.system_manager import *
from datetime import datetime
from pycassa.util import *
import signal, os
#from cfgm_common import vnc_type_conv
from provision_defaults import *
import cfgm_common.imid
from cfgm_common.exceptions import *
from vnc_quota import *
import gen
from gen.vnc_ifmap_client_gen import *
from gen.vnc_cassandra_client_gen import *
from pysandesh.connection_info import ConnectionState
from pysandesh.gen_py.process_info.ttypes import ConnectionStatus, \
ConnectionType
from pysandesh.gen_py.sandesh.ttypes import SandeshLevel
from sandesh.traces.ttypes import DBRequestTrace, MessageBusNotifyTrace, \
IfmapTrace
import logging
logger = logging.getLogger(__name__)
@ignore_exceptions
def get_trace_id():
try:
req_id = gevent.getcurrent().trace_request_id
except Exception:
req_id = 'req-%s' %(str(uuid.uuid4()))
gevent.getcurrent().trace_request_id = req_id
return req_id
# end get_trace_id
@ignore_exceptions
def trace_msg(trace_obj, trace_name, sandesh_hdl, error_msg=None):
if trace_obj:
if error_msg:
trace_obj.error = error_msg
trace_obj.trace_msg(name=trace_name, sandesh=sandesh_hdl)
# end trace_msg
class VncIfmapClient(object):
def handler(self, signum, frame):
file = open("/tmp/api-server-ifmap-cache.txt", "w")
file.write(pformat(self._id_to_metas))
file.close()
def __init__(self, db_client_mgr, ifmap_srv_ip, ifmap_srv_port,
uname, passwd, ssl_options):
for resource_type in gen.vnc_api_server_gen.all_resource_types:
obj_type = resource_type.replace('-', '_')
for oper in ('alloc', 'set', 'create', 'read_to_meta_index',
'update', 'delete'):
method = getattr(self, '_object_%s' %(oper))
bound_method = functools.partial(method, resource_type)
functools.update_wrapper(bound_method, method)
setattr(self, '_ifmap_%s_%s' %(obj_type, oper), bound_method)
self._ifmap_srv_ip = ifmap_srv_ip
self._ifmap_srv_port = ifmap_srv_port
self._username = uname
self._password = passwd
self._ssl_options = ssl_options
self._dequeue_greenlet = None
self._CONTRAIL_XSD = "http://www.contrailsystems.com/vnc_cfg.xsd"
self._IPERMS_NAME = "id-perms"
self._NAMESPACES = {
'env': "http://www.w3.org/2003/05/soap-envelope",
'ifmap': "http://www.trustedcomputinggroup.org/2010/IFMAP/2",
'meta':
"http://www.trustedcomputinggroup.org/2010/IFMAP-METADATA/2",
'contrail': self._CONTRAIL_XSD
}
self._db_client_mgr = db_client_mgr
self._sandesh = db_client_mgr._sandesh
ConnectionState.update(conn_type = ConnectionType.IFMAP,
name = 'IfMap', status = ConnectionStatus.INIT, message = '',
server_addrs = ["%s:%s" % (ifmap_srv_ip, ifmap_srv_port)])
self._conn_state = ConnectionStatus.INIT
self._reset()
# Set the signal handler
signal.signal(signal.SIGUSR2, self.handler)
# Initialize ifmap-id handler (alloc|convert|parse etc.)
self._imid_handler = ImidGen()
self._init_conn()
self._publish_config_root()
# end __init__
def _object_alloc(self, res_type, parent_type, fq_name):
imid = self._imid_handler
my_fqn = ':'.join(fq_name)
parent_fqn = ':'.join(fq_name[:-1])
my_imid = 'contrail:%s:%s' %(res_type, my_fqn)
if parent_fqn:
if parent_type is None:
return (None, None)
parent_imid = 'contrail:' + parent_type + ':' + parent_fqn
else: # parent is config-root
parent_imid = 'contrail:config-root:root'
# Normalize/escape special chars
my_imid = escape(my_imid)
parent_imid = escape(parent_imid)
return True, (my_imid, parent_imid)
# end _object_alloc
def _object_set(self, res_type, my_imid, existing_metas, obj_dict):
obj_type = res_type.replace('-', '_')
obj_class = self._db_client_mgr.get_resource_class(res_type)
update = {}
# Properties Meta
for prop_field in obj_class.prop_fields:
field = obj_dict.get(prop_field)
if field is None:
continue
# construct object of xsd-type and get its xml repr
field = obj_dict[prop_field]
# e.g. virtual_network_properties
is_simple, prop_type = obj_class.prop_field_types[prop_field]
# e.g. virtual-network-properties
prop_meta = obj_class.prop_field_metas[prop_field]
if is_simple:
norm_str = escape(str(field))
meta = Metadata(prop_meta, norm_str,
{'ifmap-cardinality':'singleValue'}, ns_prefix = 'contrail')
if (existing_metas and prop_meta in existing_metas and
str(existing_metas[prop_meta][0]['meta']) == str(meta)):
# no change
pass
else:
self._update_id_self_meta(update, meta)
else: # complex type
prop_cls = cfgm_common.utils.str_to_class(prop_type,
__name__)
buf = cStringIO.StringIO()
# perms might be inserted at server as obj.
# obj construction diff from dict construction.
if isinstance(field, dict):
prop_cls(**field).exportChildren(
buf, level=1, name_=prop_meta, pretty_print=False)
else: # object
field.exportChildren(
buf, level=1, name_=prop_meta, pretty_print=False)
prop_xml = buf.getvalue()
buf.close()
meta = Metadata(prop_meta, '',
{'ifmap-cardinality':'singleValue'}, ns_prefix='contrail',
elements=prop_xml)
if (existing_metas and prop_meta in existing_metas and
str(existing_metas[prop_meta][0]['meta']) == str(meta)):
# no change
pass
else:
self._update_id_self_meta(update, meta)
# end for all property types
# References Meta
for ref_field in obj_class.ref_fields:
refs = obj_dict.get(ref_field)
if not refs:
continue
for ref in refs:
ref_fq_name = ref['to']
ref_type, ref_link_type, _ = \
obj_class.ref_field_types[ref_field]
ref_meta = obj_class.ref_field_metas[ref_field]
ref_imid = cfgm_common.imid.get_ifmap_id_from_fq_name(
ref_type, ref_fq_name)
ref_data = ref.get('attr')
if ref_data:
buf = cStringIO.StringIO()
attr_cls = cfgm_common.utils.str_to_class(ref_link_type,
__name__)
attr_cls(**ref_data).exportChildren(
buf, level=1, name_=ref_meta, pretty_print=False)
ref_link_xml = buf.getvalue()
buf.close()
else:
ref_link_xml = ''
meta = Metadata(ref_meta, '',
{'ifmap-cardinality':'singleValue'}, ns_prefix = 'contrail',
elements=ref_link_xml)
self._update_id_pair_meta(update, ref_imid, meta)
# end for all ref types
self._publish_update(my_imid, update)
return (True, '')
# end _object_set
def _object_create(self, res_type, obj_ids, obj_dict):
obj_type = res_type.replace('-', '_')
if not 'parent_type' in obj_dict:
# parent is config-root
parent_type = 'config-root'
parent_imid = 'contrail:config-root:root'
else:
parent_type = obj_dict['parent_type']
parent_imid = obj_ids.get('parent_imid', None)
# Parent Link Meta
update = {}
parent_cls = self._db_client_mgr.get_resource_class(parent_type)
parent_link_meta = parent_cls.children_field_metas.get('%ss' %(obj_type))
if parent_link_meta:
meta = Metadata(parent_link_meta, '',
{'ifmap-cardinality':'singleValue'}, ns_prefix = 'contrail')
self._update_id_pair_meta(update, obj_ids['imid'], meta)
self._publish_update(parent_imid, update)
(ok, result) = self._object_set(res_type, obj_ids['imid'], None, obj_dict)
return (ok, result)
# end _object_create
def _object_read_to_meta_index(self, res_type, ifmap_id):
obj_type = res_type.replace('-', '_')
obj_cls = self._db_client_mgr.get_resource_class(res_type)
# metas is a dict where key is meta-name and val is list of dict
# of form [{'meta':meta}, {'id':id1, 'meta':meta}, {'id':id2, 'meta':meta}]
metas = {}
for meta_name, meta_val in self._id_to_metas[ifmap_id].items():
metas[meta_name] = meta_val
return metas
# end _object_read_to_meta_index
def _object_update(self, res_type, ifmap_id, new_obj_dict):
obj_type = res_type.replace('-', '_')
obj_cls = self._db_client_mgr.get_resource_class(res_type)
# read in refs from ifmap to determine which ones become inactive after update
existing_metas = self._object_read_to_meta_index(res_type, ifmap_id)
# remove properties that are no longer active
props = obj_cls.prop_field_metas
for prop in props:
prop_m = prop.replace('-', '_')
if prop in existing_metas and prop_m not in new_obj_dict:
self._delete_id_self_meta(ifmap_id, 'contrail:'+prop)
# remove refs that are no longer active
delete_list = []
refs = dict((obj_cls.ref_field_metas[rf],
obj_cls.ref_field_types[rf][0])
for rf in obj_cls.ref_fields)
#refs = {'virtual-network-qos-forwarding-class': 'qos-forwarding-class',
# 'virtual-network-network-ipam': 'network-ipam',
# 'virtual-network-network-policy': 'network-policy',
# 'virtual-network-route-table': 'route-table'}
for meta, to_name in refs.items():
old_set = set([m['id'] for m in existing_metas.get(meta, [])])
new_set = set()
to_name_m = to_name.replace('-', '_')
for ref in new_obj_dict.get(to_name_m+'_refs', []):
to_imid = self.fq_name_to_ifmap_id(to_name, ref['to'])
new_set.add(to_imid)
for inact_ref in old_set - new_set:
delete_list.append((inact_ref, 'contrail:'+meta))
if delete_list:
self._delete_id_pair_meta_list(ifmap_id, delete_list)
(ok, result) = self._object_set(res_type, ifmap_id, existing_metas, new_obj_dict)
return (ok, result)
# end _object_update
def _object_delete(self, res_type, obj_ids):
obj_type = res_type.replace('-', '_')
ifmap_id = obj_ids['imid']
parent_imid = obj_ids.get('parent_imid')
existing_metas = self._object_read_to_meta_index(res_type, ifmap_id)
meta_list = []
for meta_name, meta_infos in existing_metas.items():
for meta_info in meta_infos:
ref_imid = meta_info.get('id')
if ref_imid is None:
continue
meta_list.append((ref_imid, 'contrail:'+meta_name))
if parent_imid:
# Remove link from parent
meta_list.append((parent_imid, None))
if meta_list:
self._delete_id_pair_meta_list(ifmap_id, meta_list)
# Remove all property metadata associated with this ident
self._delete_id_self_meta(ifmap_id, None)
return (True, '')
# end _object_delete
def _init_conn(self):
mapclient = client(("%s" % (self._ifmap_srv_ip),
"%s" % (self._ifmap_srv_port)),
self._username, self._password,
self._NAMESPACES, self._ssl_options)
self._mapclient = mapclient
connected = False
while not connected:
try:
result = mapclient.call('newSession', NewSessionRequest())
connected = True
except socket.error as e:
time.sleep(3)
ConnectionState.update(conn_type = ConnectionType.IFMAP,
name = 'IfMap', status = ConnectionStatus.UP, message = '',
server_addrs = ["%s:%s" % (self._ifmap_srv_ip,
self._ifmap_srv_port)])
self._conn_state = ConnectionStatus.UP
msg = 'IFMAP connection ESTABLISHED'
self.config_log(msg, level=SandeshLevel.SYS_NOTICE)
mapclient.set_session_id(newSessionResult(result).get_session_id())
mapclient.set_publisher_id(newSessionResult(result).get_publisher_id())
# end _init_conn
def _get_api_server(self):
return self._db_client_mgr._api_svr_mgr
# end _get_api_server
def _reset(self):
# Cache of metas populated in ifmap server. Useful in update to find
# what things to remove in ifmap server
self._id_to_metas = {}
self._queue = Queue(self._get_api_server()._args.ifmap_queue_size)
if self._dequeue_greenlet is None:
self._dequeue_greenlet = gevent.spawn(self._ifmap_dequeue_task)
# end _reset
def _publish_config_root(self):
# config-root
buf = cStringIO.StringIO()
perms = Provision.defaults.perms
perms.exportChildren(buf, level=1, pretty_print=False)
id_perms_xml = buf.getvalue()
buf.close()
update = {}
meta = Metadata(self._IPERMS_NAME, '',
{'ifmap-cardinality': 'singleValue'},
ns_prefix='contrail', elements=id_perms_xml)
self._update_id_self_meta(update, meta)
self._publish_update("contrail:config-root:root", update)
# end _publish_config_root
def config_log(self, msg, level):
self._db_client_mgr.config_log(msg, level)
# end config_log
@ignore_exceptions
def _generate_ifmap_trace(self, oper, body):
req_id = get_trace_id()
ifmap_trace = IfmapTrace(request_id=req_id)
ifmap_trace.operation = oper
ifmap_trace.body = body
return ifmap_trace
# end _generate_ifmap_trace
def _publish_to_ifmap_enqueue(self, oper, oper_body, do_trace=True):
# safety check, if we proceed ifmap-server reports error
# asking for update|delete in publish
if not oper_body:
return
self._queue.put((oper, oper_body, do_trace))
# end _publish_to_ifmap_enqueue
def _ifmap_dequeue_task(self):
while True:
try:
self._publish_to_ifmap_dequeue()
except Exception as e:
tb = utils.detailed_traceback()
self.config_log(tb, level=SandeshLevel.SYS_ERR)
def _publish_to_ifmap_dequeue(self):
def _publish(requests, traces, publish_discovery=False):
ok = True
if requests:
ok, msg = self._publish_to_ifmap(''.join(requests))
for trace in traces:
if ok:
trace_msg(trace, 'IfmapTraceBuf', self._sandesh)
else:
trace_msg(trace, 'IfmapTraceBuf', self._sandesh,
error_msg=msg)
if publish_discovery and ok:
self._get_api_server().publish_ifmap_to_discovery()
# end _publish
while True:
# block until there is data in the queue
(oper, oper_body, do_trace) = self._queue.get()
requests = []
requests_len = 0
traces = []
while True:
# drain the queue till empty or max message size
# or change of oper because ifmap does not like
# different operations in same message
if oper == 'publish_discovery':
_publish(requests, traces, True)
break
if do_trace:
trace = self._generate_ifmap_trace(oper, oper_body)
traces.append(trace)
requests.append(oper_body)
requests_len += len(oper_body)
if (requests_len >
self._get_api_server()._args.ifmap_max_message_size):
_publish(requests, traces)
break
old_oper = oper
try:
(oper, oper_body, do_trace) = self._queue.get_nowait()
if oper != old_oper:
_publish(requests, traces)
requests = []
requests_len = 0
traces = []
continue
except Empty:
_publish(requests, traces)
break
# end _publish_to_ifmap_dequeue
def _publish_to_ifmap(self, oper_body):
try:
not_published = True
retry_count = 0
while not_published:
sess_id = self._mapclient.get_session_id()
req_xml = PublishRequest(sess_id, oper_body)
resp_xml = self._mapclient.call('publish', req_xml)
resp_doc = etree.parse(StringIO.StringIO(resp_xml))
err_codes = resp_doc.xpath(
'/env:Envelope/env:Body/ifmap:response/errorResult/@errorCode',
namespaces=self._NAMESPACES)
if err_codes:
if retry_count == 0:
log_str = 'Error publishing to ifmap, req: %s, resp: %s' \
%(req_xml, resp_xml)
self.config_log(log_str, level=SandeshLevel.SYS_ERR)
retry_count = retry_count + 1
result = self._mapclient.call('newSession',
NewSessionRequest())
sess_id = newSessionResult(result).get_session_id()
pub_id = newSessionResult(result).get_publisher_id()
self._mapclient.set_session_id(sess_id)
self._mapclient.set_publisher_id(pub_id)
else: # successful publish
not_published = False
break
# end while not_published
if retry_count:
log_str = 'Success publishing to ifmap after %d tries' \
%(retry_count)
self.config_log(log_str, level=SandeshLevel.SYS_ERR)
return True, resp_xml
except Exception as e:
if (isinstance(e, socket.error) and
self._conn_state != ConnectionStatus.DOWN):
log_str = 'Connection to IFMAP down. Failed to publish %s' %(
oper_body)
self.config_log(log_str, level=SandeshLevel.SYS_ERR)
self._conn_state = ConnectionStatus.DOWN
ConnectionState.update(
conn_type=ConnectionType.IFMAP,
name='IfMap', status=ConnectionStatus.DOWN, message='',
server_addrs=["%s:%s" % (self._ifmap_srv_ip,
self._ifmap_srv_port)])
self._reset()
self._get_api_server().un_publish_ifmap_to_discovery()
# this will block till connection is re-established
self._init_conn()
self._publish_config_root()
self._db_client_mgr.db_resync()
return False, log_str
else:
log_str = 'Failed to publish %s to ifmap: %s' %(oper_body,
str(e))
self.config_log(log_str, level=SandeshLevel.SYS_ERR)
return False, log_str
# end _publish_to_ifmap
def _build_request(self, id1_name, id2_name, meta_list, delete=False):
request = ''
id1 = unicode(Identity(name=id1_name, type="other",
other_type="extended"))
if id2_name != 'self':
id2 = unicode(Identity(name=id2_name, type="other",
other_type="extended"))
else:
id2 = None
for m in meta_list:
if delete:
filter = unicode(m) if m else None
op = PublishDeleteOperation(id1=id1, id2=id2,
filter=filter)
else:
op = PublishUpdateOperation(id1=id1, id2=id2,
metadata=unicode(m),
lifetime='forever')
request += unicode(op)
return request
def _delete_id_self_meta(self, self_imid, meta_name):
mapclient = self._mapclient
del_str = self._build_request(self_imid, 'self', [meta_name], True)
self._publish_to_ifmap_enqueue('delete', del_str)
# del meta from cache and del id if this was last meta
if meta_name:
prop_name = meta_name.replace('contrail:', '')
del self._id_to_metas[self_imid][prop_name]
if not self._id_to_metas[self_imid]:
del self._id_to_metas[self_imid]
else:
del self._id_to_metas[self_imid]
# end _delete_id_self_meta
def _delete_id_pair_meta_list(self, id1, meta_list):
mapclient = self._mapclient
del_str = ''
for id2, metadata in meta_list:
del_str += self._build_request(id1, id2, [metadata], True)
self._publish_to_ifmap_enqueue('delete', del_str)
# del meta,id2 from cache and del id if this was last meta
def _id_to_metas_delete(id1, id2, meta_name):
if id1 not in self._id_to_metas:
return
if meta_name not in self._id_to_metas[id1]:
return
if not self._id_to_metas[id1][meta_name]:
del self._id_to_metas[id1][meta_name]
if not self._id_to_metas[id1]:
del self._id_to_metas[id1]
return
# if meta is prop, noop
if 'id' not in self._id_to_metas[id1][meta_name][0]:
return
self._id_to_metas[id1][meta_name] = [
m for m in self._id_to_metas[id1][meta_name] if m['id'] != id2]
for id2, metadata in meta_list:
if metadata:
meta_name = metadata.replace('contrail:', '')
# replace with remaining refs
_id_to_metas_delete(id1, id2, meta_name)
_id_to_metas_delete(id2, id1, meta_name)
else: # no meta specified remove all links from id1 to id2
for meta_name in self._id_to_metas.get(id1, {}).keys():
_id_to_metas_delete(id1, id2, meta_name)
for meta_name in self._id_to_metas.get(id2, {}).keys():
_id_to_metas_delete(id2, id1, meta_name)
# end _delete_id_pair_meta_list
def _delete_id_pair_meta(self, id1, id2, metadata):
self._delete_id_pair_meta_list(id1, [(id2, metadata)])
# end _delete_id_pair_meta
def _update_id_self_meta(self, update, meta):
""" update: dictionary of the type
update[<id> | 'self'] = list(metadata)
"""
mlist = update.setdefault('self', [])
mlist.append(meta)
# end _update_id_self_meta
def _update_id_pair_meta(self, update, to_id, meta):
mlist = update.setdefault(to_id, [])
mlist.append(meta)
# end _update_id_pair_meta
def _publish_update(self, self_imid, update):
if self_imid not in self._id_to_metas:
self._id_to_metas[self_imid] = {}
mapclient = self._mapclient
requests = []
for id2 in update:
metalist = update[id2]
requests.append(self._build_request(self_imid, id2, metalist))
# remember what we wrote for diffing during next update
for m in metalist:
meta_name = m._Metadata__name.replace('contrail:', '')
if id2 == 'self':
self._id_to_metas[self_imid][meta_name] = [{'meta':m}]
continue
if meta_name in self._id_to_metas[self_imid]:
for id_meta in self._id_to_metas[self_imid][meta_name]:
if id_meta['id'] == id2:
id_meta['meta'] = m
break
else:
self._id_to_metas[self_imid][meta_name].append({'meta':m,
'id': id2})
else:
self._id_to_metas[self_imid][meta_name] = [{'meta':m,
'id': id2}]
if id2 not in self._id_to_metas:
self._id_to_metas[id2] = {}
if meta_name in self._id_to_metas[id2]:
for id_meta in self._id_to_metas[id2][meta_name]:
if id_meta['id'] == self_imid:
id_meta['meta'] = m
break
else:
self._id_to_metas[id2][meta_name].append({'meta':m,
'id': self_imid})
else:
self._id_to_metas[id2][meta_name] = [{'meta':m,
'id': self_imid}]
upd_str = ''.join(requests)
self._publish_to_ifmap_enqueue('update', upd_str)
# end _publish_update
def fq_name_to_ifmap_id(self, obj_type, fq_name):
return cfgm_common.imid.get_ifmap_id_from_fq_name(obj_type, fq_name)
# end fq_name_to_ifmap_id
def ifmap_id_to_fq_name(self, ifmap_id):
return cfgm_common.imid.get_fq_name_from_ifmap_id(ifmap_id)
# end ifmap_id_to_fq_name
# end class VncIfmapClient
class VncServerCassandraClient(VncCassandraClient):
# Useragent datastore keyspace + tables (used by neutron plugin currently)
_USERAGENT_KEYSPACE_NAME = 'useragent'
_USERAGENT_KV_CF_NAME = 'useragent_keyval_table'
@classmethod
def get_db_info(cls):
db_info = VncCassandraClient.get_db_info() + \
[(cls._USERAGENT_KEYSPACE_NAME, [cls._USERAGENT_KV_CF_NAME])]
return db_info
# end get_db_info
def __init__(self, db_client_mgr, cass_srv_list, reset_config, db_prefix):
self._db_client_mgr = db_client_mgr
keyspaces = {
self._USERAGENT_KEYSPACE_NAME: [(self._USERAGENT_KV_CF_NAME, None)]
}
if reset_config:
reset_config = [self._USERAGENT_KEYSPACE_NAME,
VncCassandraClient._UUID_KEYSPACE_NAME]
else:
reset_config = []
super(VncServerCassandraClient, self).__init__(
cass_srv_list, db_prefix, keyspaces, self.config_log,
generate_url=db_client_mgr.generate_url,
reset_config=reset_config)
self._useragent_kv_cf = self._cf_dict[self._USERAGENT_KV_CF_NAME]
# end __init__
def config_log(self, msg, level):
self._db_client_mgr.config_log(msg, level)
# end config_log
def create(self, method_name, *args, **kwargs):
method = getattr(self, '_cassandra_%s_create' % (method_name))
return method(*args, **kwargs)
# end create
def update(self, method_name, *args, **kwargs):
method = getattr(self, '_cassandra_%s_update' % (method_name))
return method(*args, **kwargs)
# end update
def delete(self, method_name, *args, **kwargs):
method = getattr(self, '_cassandra_%s_delete' % (method_name))
return method(*args, **kwargs)
# end delete
def ref_update(self, obj_type, obj_uuid, ref_type, ref_uuid, ref_data, operation):
bch = self._obj_uuid_cf.batch()
if operation == 'ADD':
self._create_ref(bch, obj_type, obj_uuid, ref_type, ref_uuid, ref_data)
elif operation == 'DELETE':
self._delete_ref(bch, obj_type, obj_uuid, ref_type, ref_uuid)
else:
pass
self.update_last_modified(bch, obj_uuid)
bch.send()
# end ref_update
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 _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_type,
ref_uuid, ref_data):
bch.insert(
obj_uuid, {'ref:%s:%s' %
(ref_type, ref_uuid): json.dumps(ref_data)})
if obj_type == ref_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_type,
old_ref_uuid, new_ref_infos):
if ref_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_type]:
# remove old ref
bch.remove(obj_uuid, columns=[
'ref:%s:%s' % (ref_type, old_ref_uuid)])
if obj_type == ref_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)])
self._db_client_mgr.dbe_cache_invalidate({'uuid':
old_ref_uuid})
else:
# retain old ref with new ref attr
new_ref_data = new_ref_infos[ref_type][old_ref_uuid]
bch.insert(
obj_uuid,
{'ref:%s:%s' %
(ref_type, old_ref_uuid): json.dumps(new_ref_data)})
if obj_type == ref_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)})
self._db_client_mgr.dbe_cache_invalidate({'uuid':
old_ref_uuid})
# uuid has been accounted for, remove so only new ones remain
del new_ref_infos[ref_type][old_ref_uuid]
# end _update_ref
def _delete_ref(self, bch, obj_type, obj_uuid, ref_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_type, ref_uuid)])
if obj_type == ref_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 is_latest(self, id, tstamp):
id_perms_json = self._obj_uuid_cf.get(
id, columns=['prop:id_perms'])['prop:id_perms']
id_perms = json.loads(id_perms_json)
if id_perms['last_modified'] == tstamp:
return True
else:
return False
# end is_latest
def update_last_modified(self, bch, obj_uuid, id_perms=None):
if id_perms is None:
id_perms = json.loads(
self._obj_uuid_cf.get(obj_uuid,
['prop:id_perms'])['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 uuid_to_obj_dict(self, id):
try:
obj_cols = self._obj_uuid_cf.get(id)
except pycassa.NotFoundException:
raise NoIdError(id)
return obj_cols
# end uuid_to_obj_dict
def uuid_to_obj_perms(self, id):
try:
id_perms_json = self._obj_uuid_cf.get(
id, columns=['prop:id_perms'])['prop:id_perms']
id_perms = json.loads(id_perms_json)
except pycassa.NotFoundException:
raise NoIdError(id)
return id_perms
# end uuid_to_obj_perms
def useragent_kv_store(self, key, value):
columns = {'value': value}
self._useragent_kv_cf.insert(key, columns)
# end useragent_kv_store
def useragent_kv_retrieve(self, key):
if key:
if isinstance(key, list):
rows = self._useragent_kv_cf.multiget(key)
return [rows[row].get('value') for row in rows]
else:
try:
columns = self._useragent_kv_cf.get(key)
except pycassa.NotFoundException:
raise NoUserAgentKey
return columns.get('value')
else: # no key specified, return entire contents
kv_list = []
for ua_key, ua_cols in self._useragent_kv_cf.get_range():
kv_list.append({'key': ua_key, 'value': ua_cols.get('value')})
return kv_list
# end useragent_kv_retrieve
def useragent_kv_delete(self, key):
self._useragent_kv_cf.remove(key)
# end useragent_kv_delete
def walk(self, fn):
walk_results = []
obj_infos = [x for x in self._obj_uuid_cf.get_range(
columns=['type', 'fq_name'],
column_count=self._MAX_COL)]
type_to_object = {}
for obj_uuid, obj_col in obj_infos:
try:
obj_type = json.loads(obj_col['type'])
obj_fq_name = json.loads(obj_col['fq_name'])
# prep cache to avoid n/w round-trip in db.read for ref
self.cache_uuid_to_fq_name_add(obj_uuid, obj_fq_name, obj_type)
try:
type_to_object[obj_type].append(obj_uuid)
except KeyError:
type_to_object[obj_type] = [obj_uuid]
except Exception as e:
self.config_log('Error in db walk read %s' %(str(e)),
level=SandeshLevel.SYS_ERR)
continue
for obj_type, uuid_list in type_to_object.items():
try:
self.config_log('Resync: obj_type %s len %s'
%(obj_type, len(uuid_list)),
level=SandeshLevel.SYS_INFO)
result = fn(obj_type, uuid_list)
if result:
walk_results.append(result)
except Exception as e:
self.config_log('Error in db walk invoke %s' %(str(e)),
level=SandeshLevel.SYS_ERR)
continue
return walk_results
# end walk
# end class VncCassandraClient
class VncServerKombuClient(VncKombuClient):
def __init__(self, db_client_mgr, rabbit_ip, rabbit_port, ifmap_db,
rabbit_user, rabbit_password, rabbit_vhost, rabbit_ha_mode):
self._db_client_mgr = db_client_mgr
self._sandesh = db_client_mgr._sandesh
self._ifmap_db = ifmap_db
listen_port = db_client_mgr.get_server_port()
q_name = 'vnc_config.%s-%s' %(socket.gethostname(), listen_port)
super(VncServerKombuClient, self).__init__(
rabbit_ip, rabbit_port, rabbit_user, rabbit_password, rabbit_vhost,
rabbit_ha_mode, q_name, self._dbe_subscribe_callback, self.config_log)
# end __init__
def prepare_to_consume(self):
self._db_client_mgr.wait_for_resync_done()
# prepare_to_consume
def config_log(self, msg, level):
self._db_client_mgr.config_log(msg, level)
# end config_log
def dbe_oper_publish_pending(self):
return self.num_pending_messages()
# end dbe_oper_publish_pending