-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmetadata.py
3416 lines (2792 loc) · 128 KB
/
metadata.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 DataStax, Inc.
#
# 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.
from binascii import unhexlify
from bisect import bisect_left
from collections import defaultdict
from functools import total_ordering
from hashlib import md5
import json
import logging
import re
import six
from six.moves import zip
import sys
from threading import RLock
import struct
import random
murmur3 = None
try:
from cassandra.murmur3 import murmur3
except ImportError as e:
pass
from cassandra import SignatureDescriptor, ConsistencyLevel, InvalidRequest, Unauthorized
import cassandra.cqltypes as types
from cassandra.encoder import Encoder
from cassandra.marshal import varint_unpack
from cassandra.protocol import QueryMessage
from cassandra.query import dict_factory, bind_params
from cassandra.util import OrderedDict, Version
from cassandra.pool import HostDistance
from cassandra.connection import EndPoint
from cassandra.compat import Mapping
log = logging.getLogger(__name__)
cql_keywords = set((
'add', 'aggregate', 'all', 'allow', 'alter', 'and', 'apply', 'as', 'asc', 'ascii', 'authorize', 'batch', 'begin',
'bigint', 'blob', 'boolean', 'by', 'called', 'clustering', 'columnfamily', 'compact', 'contains', 'count',
'counter', 'create', 'custom', 'date', 'decimal', 'default', 'delete', 'desc', 'describe', 'deterministic', 'distinct', 'double', 'drop',
'entries', 'execute', 'exists', 'filtering', 'finalfunc', 'float', 'from', 'frozen', 'full', 'function',
'functions', 'grant', 'if', 'in', 'index', 'inet', 'infinity', 'initcond', 'input', 'insert', 'int', 'into', 'is', 'json',
'key', 'keys', 'keyspace', 'keyspaces', 'language', 'limit', 'list', 'login', 'map', 'materialized', 'mbean', 'mbeans', 'modify', 'monotonic',
'nan', 'nologin', 'norecursive', 'nosuperuser', 'not', 'null', 'of', 'on', 'options', 'or', 'order', 'password', 'permission',
'permissions', 'primary', 'rename', 'replace', 'returns', 'revoke', 'role', 'roles', 'schema', 'select', 'set',
'sfunc', 'smallint', 'static', 'storage', 'stype', 'superuser', 'table', 'text', 'time', 'timestamp', 'timeuuid',
'tinyint', 'to', 'token', 'trigger', 'truncate', 'ttl', 'tuple', 'type', 'unlogged', 'unset', 'update', 'use', 'user',
'users', 'using', 'uuid', 'values', 'varchar', 'varint', 'view', 'where', 'with', 'writetime',
# DSE specifics
"node", "nodes", "plan", "active", "application", "applications", "java", "executor", "executors", "std_out", "std_err",
"renew", "delegation", "no", "redact", "token", "lowercasestring", "cluster", "authentication", "schemes", "scheme",
"internal", "ldap", "kerberos", "remote", "object", "method", "call", "calls", "search", "schema", "config", "rows",
"columns", "profiles", "commit", "reload", "rebuild", "field", "workpool", "any", "submission", "indices",
"restrict", "unrestrict"
))
"""
Set of keywords in CQL.
Derived from .../cassandra/src/java/org/apache/cassandra/cql3/Cql.g
"""
cql_keywords_unreserved = set((
'aggregate', 'all', 'as', 'ascii', 'bigint', 'blob', 'boolean', 'called', 'clustering', 'compact', 'contains',
'count', 'counter', 'custom', 'date', 'decimal', 'deterministic', 'distinct', 'double', 'exists', 'filtering', 'finalfunc', 'float',
'frozen', 'function', 'functions', 'inet', 'initcond', 'input', 'int', 'json', 'key', 'keys', 'keyspaces',
'language', 'list', 'login', 'map', 'monotonic', 'nologin', 'nosuperuser', 'options', 'password', 'permission', 'permissions',
'returns', 'role', 'roles', 'sfunc', 'smallint', 'static', 'storage', 'stype', 'superuser', 'text', 'time',
'timestamp', 'timeuuid', 'tinyint', 'trigger', 'ttl', 'tuple', 'type', 'user', 'users', 'uuid', 'values', 'varchar',
'varint', 'writetime'
))
"""
Set of unreserved keywords in CQL.
Derived from .../cassandra/src/java/org/apache/cassandra/cql3/Cql.g
"""
cql_keywords_reserved = cql_keywords - cql_keywords_unreserved
"""
Set of reserved keywords in CQL.
"""
_encoder = Encoder()
class Metadata(object):
"""
Holds a representation of the cluster schema and topology.
"""
cluster_name = None
""" The string name of the cluster. """
keyspaces = None
"""
A map from keyspace names to matching :class:`~.KeyspaceMetadata` instances.
"""
partitioner = None
"""
The string name of the partitioner for the cluster.
"""
token_map = None
""" A :class:`~.TokenMap` instance describing the ring topology. """
dbaas = False
""" A boolean indicating if connected to a DBaaS cluster """
def __init__(self):
self.keyspaces = {}
self.dbaas = False
self._hosts = {}
self._hosts_lock = RLock()
def export_schema_as_string(self):
"""
Returns a string that can be executed as a query in order to recreate
the entire schema. The string is formatted to be human readable.
"""
return "\n\n".join(ks.export_as_string() for ks in self.keyspaces.values())
def refresh(self, connection, timeout, target_type=None, change_type=None, **kwargs):
server_version = self.get_host(connection.endpoint).release_version
dse_version = self.get_host(connection.endpoint).dse_version
parser = get_schema_parser(connection, server_version, dse_version, timeout)
if not target_type:
self._rebuild_all(parser)
return
tt_lower = target_type.lower()
try:
parse_method = getattr(parser, 'get_' + tt_lower)
meta = parse_method(self.keyspaces, **kwargs)
if meta:
update_method = getattr(self, '_update_' + tt_lower)
if tt_lower == 'keyspace' and connection.protocol_version < 3:
# we didn't have 'type' target in legacy protocol versions, so we need to query those too
user_types = parser.get_types_map(self.keyspaces, **kwargs)
self._update_keyspace(meta, user_types)
else:
update_method(meta)
else:
drop_method = getattr(self, '_drop_' + tt_lower)
drop_method(**kwargs)
except AttributeError:
raise ValueError("Unknown schema target_type: '%s'" % target_type)
def _rebuild_all(self, parser):
current_keyspaces = set()
for keyspace_meta in parser.get_all_keyspaces():
current_keyspaces.add(keyspace_meta.name)
old_keyspace_meta = self.keyspaces.get(keyspace_meta.name, None)
self.keyspaces[keyspace_meta.name] = keyspace_meta
if old_keyspace_meta:
self._keyspace_updated(keyspace_meta.name)
else:
self._keyspace_added(keyspace_meta.name)
# remove not-just-added keyspaces
removed_keyspaces = [name for name in self.keyspaces.keys()
if name not in current_keyspaces]
self.keyspaces = dict((name, meta) for name, meta in self.keyspaces.items()
if name in current_keyspaces)
for ksname in removed_keyspaces:
self._keyspace_removed(ksname)
def _update_keyspace(self, keyspace_meta, new_user_types=None):
ks_name = keyspace_meta.name
old_keyspace_meta = self.keyspaces.get(ks_name, None)
self.keyspaces[ks_name] = keyspace_meta
if old_keyspace_meta:
keyspace_meta.tables = old_keyspace_meta.tables
keyspace_meta.user_types = new_user_types if new_user_types is not None else old_keyspace_meta.user_types
keyspace_meta.indexes = old_keyspace_meta.indexes
keyspace_meta.functions = old_keyspace_meta.functions
keyspace_meta.aggregates = old_keyspace_meta.aggregates
keyspace_meta.views = old_keyspace_meta.views
if (keyspace_meta.replication_strategy != old_keyspace_meta.replication_strategy):
self._keyspace_updated(ks_name)
else:
self._keyspace_added(ks_name)
def _drop_keyspace(self, keyspace):
if self.keyspaces.pop(keyspace, None):
self._keyspace_removed(keyspace)
def _update_table(self, meta):
try:
keyspace_meta = self.keyspaces[meta.keyspace_name]
# this is unfortunate, but protocol v4 does not differentiate
# between events for tables and views. <parser>.get_table will
# return one or the other based on the query results.
# Here we deal with that.
if isinstance(meta, TableMetadata):
keyspace_meta._add_table_metadata(meta)
else:
keyspace_meta._add_view_metadata(meta)
except KeyError:
# can happen if keyspace disappears while processing async event
pass
def _drop_table(self, keyspace, table):
try:
keyspace_meta = self.keyspaces[keyspace]
keyspace_meta._drop_table_metadata(table) # handles either table or view
except KeyError:
# can happen if keyspace disappears while processing async event
pass
def _update_type(self, type_meta):
try:
self.keyspaces[type_meta.keyspace].user_types[type_meta.name] = type_meta
except KeyError:
# can happen if keyspace disappears while processing async event
pass
def _drop_type(self, keyspace, type):
try:
self.keyspaces[keyspace].user_types.pop(type, None)
except KeyError:
# can happen if keyspace disappears while processing async event
pass
def _update_function(self, function_meta):
try:
self.keyspaces[function_meta.keyspace].functions[function_meta.signature] = function_meta
except KeyError:
# can happen if keyspace disappears while processing async event
pass
def _drop_function(self, keyspace, function):
try:
self.keyspaces[keyspace].functions.pop(function.signature, None)
except KeyError:
pass
def _update_aggregate(self, aggregate_meta):
try:
self.keyspaces[aggregate_meta.keyspace].aggregates[aggregate_meta.signature] = aggregate_meta
except KeyError:
pass
def _drop_aggregate(self, keyspace, aggregate):
try:
self.keyspaces[keyspace].aggregates.pop(aggregate.signature, None)
except KeyError:
pass
def _keyspace_added(self, ksname):
if self.token_map:
self.token_map.rebuild_keyspace(ksname, build_if_absent=False)
def _keyspace_updated(self, ksname):
if self.token_map:
self.token_map.rebuild_keyspace(ksname, build_if_absent=False)
def _keyspace_removed(self, ksname):
if self.token_map:
self.token_map.remove_keyspace(ksname)
def rebuild_token_map(self, partitioner, token_map):
"""
Rebuild our view of the topology from fresh rows from the
system topology tables.
For internal use only.
"""
self.partitioner = partitioner
if partitioner.endswith('RandomPartitioner'):
token_class = MD5Token
elif partitioner.endswith('Murmur3Partitioner'):
token_class = Murmur3Token
elif partitioner.endswith('ByteOrderedPartitioner'):
token_class = BytesToken
else:
self.token_map = None
return
token_to_host_owner = {}
ring = []
for host, token_strings in six.iteritems(token_map):
for token_string in token_strings:
token = token_class.from_string(token_string)
ring.append(token)
token_to_host_owner[token] = host
all_tokens = sorted(ring)
self.token_map = TokenMap(
token_class, token_to_host_owner, all_tokens, self)
def get_replicas(self, keyspace, key):
"""
Returns a list of :class:`.Host` instances that are replicas for a given
partition key.
"""
t = self.token_map
if not t:
return []
try:
return t.get_replicas(keyspace, t.token_class.from_key(key))
except NoMurmur3:
return []
def can_support_partitioner(self):
if self.partitioner.endswith('Murmur3Partitioner') and murmur3 is None:
return False
else:
return True
def add_or_return_host(self, host):
"""
Returns a tuple (host, new), where ``host`` is a Host
instance, and ``new`` is a bool indicating whether
the host was newly added.
"""
with self._hosts_lock:
try:
return self._hosts[host.endpoint], False
except KeyError:
self._hosts[host.endpoint] = host
return host, True
def remove_host(self, host):
with self._hosts_lock:
return bool(self._hosts.pop(host.endpoint, False))
def get_host(self, endpoint_or_address, port=None):
"""
Find a host in the metadata for a specific endpoint. If a string inet address and port are passed,
iterate all hosts to match the :attr:`~.pool.Host.broadcast_rpc_address` and
:attr:`~.pool.Host.broadcast_rpc_port`attributes.
"""
if not isinstance(endpoint_or_address, EndPoint):
return self._get_host_by_address(endpoint_or_address, port)
return self._hosts.get(endpoint_or_address)
def _get_host_by_address(self, address, port=None):
for host in six.itervalues(self._hosts):
if (host.broadcast_rpc_address == address and
(port is None or host.broadcast_rpc_port is None or host.broadcast_rpc_port == port)):
return host
return None
def all_hosts(self):
"""
Returns a list of all known :class:`.Host` instances in the cluster.
"""
with self._hosts_lock:
return list(self._hosts.values())
REPLICATION_STRATEGY_CLASS_PREFIX = "org.apache.cassandra.locator."
def trim_if_startswith(s, prefix):
if s.startswith(prefix):
return s[len(prefix):]
return s
_replication_strategies = {}
class ReplicationStrategyTypeType(type):
def __new__(metacls, name, bases, dct):
dct.setdefault('name', name)
cls = type.__new__(metacls, name, bases, dct)
if not name.startswith('_'):
_replication_strategies[name] = cls
return cls
@six.add_metaclass(ReplicationStrategyTypeType)
class _ReplicationStrategy(object):
options_map = None
@classmethod
def create(cls, strategy_class, options_map):
if not strategy_class:
return None
strategy_name = trim_if_startswith(strategy_class, REPLICATION_STRATEGY_CLASS_PREFIX)
rs_class = _replication_strategies.get(strategy_name, None)
if rs_class is None:
rs_class = _UnknownStrategyBuilder(strategy_name)
_replication_strategies[strategy_name] = rs_class
try:
rs_instance = rs_class(options_map)
except Exception as exc:
log.warning("Failed creating %s with options %s: %s", strategy_name, options_map, exc)
return None
return rs_instance
def make_token_replica_map(self, token_to_host_owner, ring):
raise NotImplementedError()
def export_for_schema(self):
raise NotImplementedError()
ReplicationStrategy = _ReplicationStrategy
class _UnknownStrategyBuilder(object):
def __init__(self, name):
self.name = name
def __call__(self, options_map):
strategy_instance = _UnknownStrategy(self.name, options_map)
return strategy_instance
class _UnknownStrategy(ReplicationStrategy):
def __init__(self, name, options_map):
self.name = name
self.options_map = options_map.copy() if options_map is not None else dict()
self.options_map['class'] = self.name
def __eq__(self, other):
return (isinstance(other, _UnknownStrategy) and
self.name == other.name and
self.options_map == other.options_map)
def export_for_schema(self):
"""
Returns a string version of these replication options which are
suitable for use in a CREATE KEYSPACE statement.
"""
if self.options_map:
return dict((str(key), str(value)) for key, value in self.options_map.items())
return "{'class': '%s'}" % (self.name, )
def make_token_replica_map(self, token_to_host_owner, ring):
return {}
class ReplicationFactor(object):
"""
Represent the replication factor of a keyspace.
"""
all_replicas = None
"""
The number of total replicas.
"""
full_replicas = None
"""
The number of replicas that own a full copy of the data. This is the same
than `all_replicas` when transient replication is not enabled.
"""
transient_replicas = None
"""
The number of transient replicas.
Only set if the keyspace has transient replication enabled.
"""
def __init__(self, all_replicas, transient_replicas=None):
self.all_replicas = all_replicas
self.transient_replicas = transient_replicas
self.full_replicas = (all_replicas - transient_replicas) if transient_replicas else all_replicas
@staticmethod
def create(rf):
"""
Given the inputted replication factor string, parse and return the ReplicationFactor instance.
"""
transient_replicas = None
try:
all_replicas = int(rf)
except ValueError:
try:
rf = rf.split('/')
all_replicas, transient_replicas = int(rf[0]), int(rf[1])
except Exception:
raise ValueError("Unable to determine replication factor from: {}".format(rf))
return ReplicationFactor(all_replicas, transient_replicas)
def __str__(self):
return ("%d/%d" % (self.all_replicas, self.transient_replicas) if self.transient_replicas
else "%d" % self.all_replicas)
def __eq__(self, other):
if not isinstance(other, ReplicationFactor):
return False
return self.all_replicas == other.all_replicas and self.full_replicas == other.full_replicas
class SimpleStrategy(ReplicationStrategy):
replication_factor_info = None
"""
A :class:`cassandra.metadata.ReplicationFactor` instance.
"""
@property
def replication_factor(self):
"""
The replication factor for this keyspace.
For backward compatibility, this returns the
:attr:`cassandra.metadata.ReplicationFactor.full_replicas` value of
:attr:`cassandra.metadata.SimpleStrategy.replication_factor_info`.
"""
return self.replication_factor_info.full_replicas
def __init__(self, options_map):
self.replication_factor_info = ReplicationFactor.create(options_map['replication_factor'])
def make_token_replica_map(self, token_to_host_owner, ring):
replica_map = {}
for i in range(len(ring)):
j, hosts = 0, list()
while len(hosts) < self.replication_factor and j < len(ring):
token = ring[(i + j) % len(ring)]
host = token_to_host_owner[token]
if host not in hosts:
hosts.append(host)
j += 1
replica_map[ring[i]] = hosts
return replica_map
def export_for_schema(self):
"""
Returns a string version of these replication options which are
suitable for use in a CREATE KEYSPACE statement.
"""
return "{'class': 'SimpleStrategy', 'replication_factor': '%s'}" \
% (str(self.replication_factor_info),)
def __eq__(self, other):
if not isinstance(other, SimpleStrategy):
return False
return str(self.replication_factor_info) == str(other.replication_factor_info)
class NetworkTopologyStrategy(ReplicationStrategy):
dc_replication_factors_info = None
"""
A map of datacenter names to the :class:`cassandra.metadata.ReplicationFactor` instance for that DC.
"""
dc_replication_factors = None
"""
A map of datacenter names to the replication factor for that DC.
For backward compatibility, this maps to the :attr:`cassandra.metadata.ReplicationFactor.full_replicas`
value of the :attr:`cassandra.metadata.NetworkTopologyStrategy.dc_replication_factors_info` dict.
"""
def __init__(self, dc_replication_factors):
self.dc_replication_factors_info = dict(
(str(k), ReplicationFactor.create(v)) for k, v in dc_replication_factors.items())
self.dc_replication_factors = dict(
(dc, rf.full_replicas) for dc, rf in self.dc_replication_factors_info.items())
def make_token_replica_map(self, token_to_host_owner, ring):
dc_rf_map = dict(
(dc, full_replicas) for dc, full_replicas in self.dc_replication_factors.items()
if full_replicas > 0)
# build a map of DCs to lists of indexes into `ring` for tokens that
# belong to that DC
dc_to_token_offset = defaultdict(list)
dc_racks = defaultdict(set)
hosts_per_dc = defaultdict(set)
for i, token in enumerate(ring):
host = token_to_host_owner[token]
dc_to_token_offset[host.datacenter].append(i)
if host.datacenter and host.rack:
dc_racks[host.datacenter].add(host.rack)
hosts_per_dc[host.datacenter].add(host)
# A map of DCs to an index into the dc_to_token_offset value for that dc.
# This is how we keep track of advancing around the ring for each DC.
dc_to_current_index = defaultdict(int)
replica_map = defaultdict(list)
for i in range(len(ring)):
replicas = replica_map[ring[i]]
# go through each DC and find the replicas in that DC
for dc in dc_to_token_offset.keys():
if dc not in dc_rf_map:
continue
# advance our per-DC index until we're up to at least the
# current token in the ring
token_offsets = dc_to_token_offset[dc]
index = dc_to_current_index[dc]
num_tokens = len(token_offsets)
while index < num_tokens and token_offsets[index] < i:
index += 1
dc_to_current_index[dc] = index
replicas_remaining = dc_rf_map[dc]
replicas_this_dc = 0
skipped_hosts = []
racks_placed = set()
racks_this_dc = dc_racks[dc]
hosts_this_dc = len(hosts_per_dc[dc])
for token_offset_index in six.moves.range(index, index+num_tokens):
if token_offset_index >= len(token_offsets):
token_offset_index = token_offset_index - len(token_offsets)
token_offset = token_offsets[token_offset_index]
host = token_to_host_owner[ring[token_offset]]
if replicas_remaining == 0 or replicas_this_dc == hosts_this_dc:
break
if host in replicas:
continue
if host.rack in racks_placed and len(racks_placed) < len(racks_this_dc):
skipped_hosts.append(host)
continue
replicas.append(host)
replicas_this_dc += 1
replicas_remaining -= 1
racks_placed.add(host.rack)
if len(racks_placed) == len(racks_this_dc):
for host in skipped_hosts:
if replicas_remaining == 0:
break
replicas.append(host)
replicas_remaining -= 1
del skipped_hosts[:]
return replica_map
def export_for_schema(self):
"""
Returns a string version of these replication options which are
suitable for use in a CREATE KEYSPACE statement.
"""
ret = "{'class': 'NetworkTopologyStrategy'"
for dc, rf in sorted(self.dc_replication_factors_info.items()):
ret += ", '%s': '%s'" % (dc, str(rf))
return ret + "}"
def __eq__(self, other):
if not isinstance(other, NetworkTopologyStrategy):
return False
return self.dc_replication_factors_info == other.dc_replication_factors_info
class LocalStrategy(ReplicationStrategy):
def __init__(self, options_map):
pass
def make_token_replica_map(self, token_to_host_owner, ring):
return {}
def export_for_schema(self):
"""
Returns a string version of these replication options which are
suitable for use in a CREATE KEYSPACE statement.
"""
return "{'class': 'LocalStrategy'}"
def __eq__(self, other):
return isinstance(other, LocalStrategy)
class KeyspaceMetadata(object):
"""
A representation of the schema for a single keyspace.
"""
name = None
""" The string name of the keyspace. """
durable_writes = True
"""
A boolean indicating whether durable writes are enabled for this keyspace
or not.
"""
replication_strategy = None
"""
A :class:`.ReplicationStrategy` subclass object.
"""
tables = None
"""
A map from table names to instances of :class:`~.TableMetadata`.
"""
indexes = None
"""
A dict mapping index names to :class:`.IndexMetadata` instances.
"""
user_types = None
"""
A map from user-defined type names to instances of :class:`~cassandra.metadata.UserType`.
.. versionadded:: 2.1.0
"""
functions = None
"""
A map from user-defined function signatures to instances of :class:`~cassandra.metadata.Function`.
.. versionadded:: 2.6.0
"""
aggregates = None
"""
A map from user-defined aggregate signatures to instances of :class:`~cassandra.metadata.Aggregate`.
.. versionadded:: 2.6.0
"""
views = None
"""
A dict mapping view names to :class:`.MaterializedViewMetadata` instances.
"""
virtual = False
"""
A boolean indicating if this is a virtual keyspace or not. Always ``False``
for clusters running Cassandra pre-4.0 and DSE pre-6.7 versions.
.. versionadded:: 3.15
"""
graph_engine = None
"""
A string indicating whether a graph engine is enabled for this keyspace (Core/Classic).
"""
_exc_info = None
""" set if metadata parsing failed """
def __init__(self, name, durable_writes, strategy_class, strategy_options, graph_engine=None):
self.name = name
self.durable_writes = durable_writes
self.replication_strategy = ReplicationStrategy.create(strategy_class, strategy_options)
self.tables = {}
self.indexes = {}
self.user_types = {}
self.functions = {}
self.aggregates = {}
self.views = {}
self.graph_engine = graph_engine
@property
def is_graph_enabled(self):
return self.graph_engine is not None
def export_as_string(self):
"""
Returns a CQL query string that can be used to recreate the entire keyspace,
including user-defined types and tables.
"""
# Make sure tables with vertex are exported before tables with edges
tables_with_vertex = [t for t in self.tables.values() if hasattr(t, 'vertex') and t.vertex]
other_tables = [t for t in self.tables.values() if t not in tables_with_vertex]
cql = "\n\n".join(
[self.as_cql_query() + ';'] +
self.user_type_strings() +
[f.export_as_string() for f in self.functions.values()] +
[a.export_as_string() for a in self.aggregates.values()] +
[t.export_as_string() for t in tables_with_vertex + other_tables])
if self._exc_info:
import traceback
ret = "/*\nWarning: Keyspace %s is incomplete because of an error processing metadata.\n" % \
(self.name)
for line in traceback.format_exception(*self._exc_info):
ret += line
ret += "\nApproximate structure, for reference:\n(this should not be used to reproduce this schema)\n\n%s\n*/" % cql
return ret
if self.virtual:
return ("/*\nWarning: Keyspace {ks} is a virtual keyspace and cannot be recreated with CQL.\n"
"Structure, for reference:*/\n"
"{cql}\n"
"").format(ks=self.name, cql=cql)
return cql
def as_cql_query(self):
"""
Returns a CQL query string that can be used to recreate just this keyspace,
not including user-defined types and tables.
"""
if self.virtual:
return "// VIRTUAL KEYSPACE {}".format(protect_name(self.name))
ret = "CREATE KEYSPACE %s WITH replication = %s " % (
protect_name(self.name),
self.replication_strategy.export_for_schema())
ret = ret + (' AND durable_writes = %s' % ("true" if self.durable_writes else "false"))
if self.graph_engine is not None:
ret = ret + (" AND graph_engine = '%s'" % self.graph_engine)
return ret
def user_type_strings(self):
user_type_strings = []
user_types = self.user_types.copy()
keys = sorted(user_types.keys())
for k in keys:
if k in user_types:
self.resolve_user_types(k, user_types, user_type_strings)
return user_type_strings
def resolve_user_types(self, key, user_types, user_type_strings):
user_type = user_types.pop(key)
for type_name in user_type.field_types:
for sub_type in types.cql_types_from_string(type_name):
if sub_type in user_types:
self.resolve_user_types(sub_type, user_types, user_type_strings)
user_type_strings.append(user_type.export_as_string())
def _add_table_metadata(self, table_metadata):
old_indexes = {}
old_meta = self.tables.get(table_metadata.name, None)
if old_meta:
# views are not queried with table, so they must be transferred to new
table_metadata.views = old_meta.views
# indexes will be updated with what is on the new metadata
old_indexes = old_meta.indexes
# note the intentional order of add before remove
# this makes sure the maps are never absent something that existed before this update
for index_name, index_metadata in six.iteritems(table_metadata.indexes):
self.indexes[index_name] = index_metadata
for index_name in (n for n in old_indexes if n not in table_metadata.indexes):
self.indexes.pop(index_name, None)
self.tables[table_metadata.name] = table_metadata
def _drop_table_metadata(self, table_name):
table_meta = self.tables.pop(table_name, None)
if table_meta:
for index_name in table_meta.indexes:
self.indexes.pop(index_name, None)
for view_name in table_meta.views:
self.views.pop(view_name, None)
return
# we can't tell table drops from views, so drop both
# (name is unique among them, within a keyspace)
view_meta = self.views.pop(table_name, None)
if view_meta:
try:
self.tables[view_meta.base_table_name].views.pop(table_name, None)
except KeyError:
pass
def _add_view_metadata(self, view_metadata):
try:
self.tables[view_metadata.base_table_name].views[view_metadata.name] = view_metadata
self.views[view_metadata.name] = view_metadata
except KeyError:
pass
class UserType(object):
"""
A user defined type, as created by ``CREATE TYPE`` statements.
User-defined types were introduced in Cassandra 2.1.
.. versionadded:: 2.1.0
"""
keyspace = None
"""
The string name of the keyspace in which this type is defined.
"""
name = None
"""
The name of this type.
"""
field_names = None
"""
An ordered list of the names for each field in this user-defined type.
"""
field_types = None
"""
An ordered list of the types for each field in this user-defined type.
"""
def __init__(self, keyspace, name, field_names, field_types):
self.keyspace = keyspace
self.name = name
# non-frozen collections can return None
self.field_names = field_names or []
self.field_types = field_types or []
def as_cql_query(self, formatted=False):
"""
Returns a CQL query that can be used to recreate this type.
If `formatted` is set to :const:`True`, extra whitespace will
be added to make the query more readable.
"""
ret = "CREATE TYPE %s.%s (%s" % (
protect_name(self.keyspace),
protect_name(self.name),
"\n" if formatted else "")
if formatted:
field_join = ",\n"
padding = " "
else:
field_join = ", "
padding = ""
fields = []
for field_name, field_type in zip(self.field_names, self.field_types):
fields.append("%s %s" % (protect_name(field_name), field_type))
ret += field_join.join("%s%s" % (padding, field) for field in fields)
ret += "\n)" if formatted else ")"
return ret
def export_as_string(self):
return self.as_cql_query(formatted=True) + ';'
class Aggregate(object):
"""
A user defined aggregate function, as created by ``CREATE AGGREGATE`` statements.
Aggregate functions were introduced in Cassandra 2.2
.. versionadded:: 2.6.0
"""
keyspace = None
"""
The string name of the keyspace in which this aggregate is defined
"""
name = None
"""
The name of this aggregate
"""
argument_types = None
"""
An ordered list of the types for each argument to the aggregate
"""
final_func = None
"""
Name of a final function
"""
initial_condition = None
"""
Initial condition of the aggregate
"""
return_type = None
"""
Return type of the aggregate
"""
state_func = None
"""
Name of a state function
"""
state_type = None