-
Notifications
You must be signed in to change notification settings - Fork 27
/
cass.py
1923 lines (1627 loc) · 72.4 KB
/
cass.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
"""
Cassandra implementation of the store for the front-end scaling groups engine
"""
import functools
import json
import time
import uuid
from datetime import datetime
from itertools import cycle, takewhile
from characteristic import attributes
from effect import Effect, TypeDispatcher, parallel
from effect.do import do, do_return
from jsonschema import ValidationError
from kazoo.protocol.states import KazooState
from pyrsistent import freeze
from silverberg.client import ConsistencyLevel
from toolz.curried import filter, map
from toolz.dicttoolz import assoc, keymap
from toolz.functoolz import compose
from twisted.internet import defer
from txeffect import deferred_performer
from zope.interface import implementer
from otter.log import log as otter_log
from otter.models.interface import (
GroupNotEmptyError,
GroupState,
IAdmin,
IScalingGroup,
IScalingGroupCollection,
IScalingGroupServersCache,
IScalingScheduleCollection,
NoSuchPolicyError,
NoSuchScalingGroupError,
NoSuchWebhookError,
PoliciesOverLimitError,
ScalingGroupOverLimitError,
ScalingGroupStatus,
UnrecognizedCapabilityError,
WebhooksOverLimitError,
next_cron_occurrence)
from otter.util import timestamp, zk
from otter.util.config import config_value
from otter.util.cqlbatch import Batch, batch
from otter.util.deferredutils import with_lock
from otter.util.hashkey import generate_capability, generate_key_str
from otter.util.retry import repeating_interval, retry, retry_times
from otter.util.weaklocks import WeakLocks
LOCK_PATH = '/locks'
DEFAULT_CONSISTENCY = ConsistencyLevel.QUORUM
QUERY_LIMIT = 10000
# Max number of seconds to wait to acquire group kazoo lock. This should
# not be held for more than 10-15ms in normal circumstances but we keep it high
# for safety sake. We don't want it to be < 30 since any request will be
# terminated by CLB by then.
ACQUIRE_TIMEOUT = 10
# Ideally release should not even timeout but keep this to capture any unwanted
# error
RELEASE_TIMEOUT = 10
@attributes(['query', 'params', 'consistency_level'])
class CQLQueryExecute(object):
"""
An intent to execute CQL query
"""
@deferred_performer
def perform_cql_query(conn, disp, intent):
"""
Perform CQLQueryExecute intent using given silverberg connection
"""
return conn.execute(
intent.query, intent.params, intent.consistency_level)
def get_cql_dispatcher(connection):
"""
Get dispatcher with `CQLQueryExecute`'s performer in it
:param connection: Silverberg connection
"""
return TypeDispatcher({
CQLQueryExecute: functools.partial(perform_cql_query, connection)
})
def cql_eff(query, params={}, consistency_level=DEFAULT_CONSISTENCY):
"""
Return Effect of CQLQueryExecute intent
"""
return Effect(
CQLQueryExecute(query=query, params=params,
consistency_level=consistency_level))
def serialize_json_data(data, ver):
"""
Serialize json data to cassandra by adding a version and dumping it to a
string
"""
dataOut = data.copy()
dataOut["_ver"] = ver
return json.dumps(dataOut)
# ACHTUNG LOOKENPEEPERS!
#
# Batch operations don't let you have semicolons between statements. Regular
# operations require you to end them with a semicolon.
#
# If you are doing a INSERT or UPDATE query, it's going to be part of a batch.
# Otherwise it won't.
#
# Thus, selects have a semicolon, everything else doesn't.
# NOTE about deleted groups: Make sure every query involving groups *either*
# filters out deleting=false, *or* includes the `deleting` query so that
# _unmarshal_state can parse the status correctly.
_cql_view = ('SELECT {column}, created_at FROM {cf} '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId '
'AND deleting=false;')
_cql_view_policy = (
'SELECT data, version FROM {cf} '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId '
'AND "policyId" = :policyId;')
_cql_view_webhook = (
'SELECT data, capability FROM {cf} '
'WHERE "tenantId" = :tenantId AND '
'"groupId" = :groupId AND "policyId" = :policyId AND '
'"webhookId" = :webhookId;')
_cql_create_group = (
'INSERT INTO {cf}("tenantId", "groupId", group_config, '
'launch_config, active, pending, "policyTouched", paused, '
'desired, created_at, deleting, suspended) '
'VALUES (:tenantId, :groupId, :group_config, '
':launch_config, :active, :pending, :policyTouched, '
':paused, :desired, :created_at, false, false) '
'USING TIMESTAMP :ts')
_cql_view_manifest = (
'SELECT "tenantId", "groupId", group_config, '
'launch_config, active, pending, "groupTouched", '
'"policyTouched", paused, desired, created_at, status, error_reasons, '
'deleting, suspended FROM {cf} '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId')
_cql_insert_policy = (
'INSERT INTO {cf}("tenantId", "groupId", "policyId", data, version) '
'VALUES (:tenantId, :groupId, :{name}policyId, :{name}data, '
':{name}version)')
_cql_insert_group_state = (
'INSERT INTO {cf}("tenantId", "groupId", active, pending, "groupTouched", '
'"policyTouched", paused, desired, suspended) '
'VALUES(:tenantId, :groupId, :active, :pending, :groupTouched, '
':policyTouched, :paused, :desired, :suspended) '
'USING TIMESTAMP :ts')
# --- Event related queries
_cql_insert_group_event = (
'INSERT INTO {cf}(bucket, "tenantId", "groupId", "policyId", trigger, '
'version) '
'VALUES (:{name}bucket, :tenantId, :groupId, :{name}policyId, '
':{name}trigger, :{name}version)')
_cql_insert_group_event_with_cron = (
'INSERT INTO {cf}(bucket, "tenantId", "groupId", "policyId", trigger, '
'cron, version) '
'VALUES (:{name}bucket, :tenantId, :groupId, :{name}policyId, '
':{name}trigger, :{name}cron, :{name}version)')
_cql_insert_cron_event = (
'INSERT INTO {cf}(bucket, "tenantId", "groupId", "policyId", trigger, '
'cron, version) '
'VALUES (:{name}bucket, :{name}tenantId, :{name}groupId, :{name}policyId, '
':{name}trigger, :{name}cron, :{name}version);')
_cql_fetch_batch_of_events = (
'SELECT "tenantId", "groupId", "policyId", "trigger", cron, version '
'FROM {cf} '
'WHERE bucket = :bucket AND trigger <= :now LIMIT :size;')
_cql_delete_bucket_event = (
'DELETE FROM {cf} WHERE bucket = :bucket '
'AND trigger = :{name}trigger AND "policyId" = :{name}policyId;')
_cql_oldest_event = 'SELECT * from {cf} WHERE bucket=:bucket LIMIT 1;'
_cql_insert_webhook = (
'INSERT INTO {cf}("tenantId", "groupId", "policyId", "webhookId", data, '
'capability, '
'"webhookKey") VALUES (:tenantId, :groupId, :policyId, :{name}Id, '
':{name}, :{name}Capability, :{name}Key)')
_cql_update = (
'INSERT INTO {cf}("tenantId", "groupId", {column}) '
'VALUES (:tenantId, :groupId, {name}) USING TIMESTAMP :ts')
_cql_update_webhook = (
'INSERT INTO {cf}("tenantId", "groupId", "policyId", "webhookId", data) '
'VALUES (:tenantId, :groupId, :policyId, :webhookId, :data);')
_cql_delete_group = (
'DELETE FROM {cf} USING TIMESTAMP :ts '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId')
_cql_delete_all_in_group = (
'DELETE FROM {cf} WHERE "tenantId" = :tenantId AND '
'"groupId" = :groupId{name}')
_cql_delete_all_in_policy = (
'DELETE FROM {cf} WHERE "tenantId" = :tenantId '
'AND "groupId" = :groupId AND "policyId" = :policyId')
_cql_delete_one_webhook = (
'DELETE FROM {cf} WHERE "tenantId" = :tenantId AND '
'"groupId" = :groupId AND "policyId" = :policyId AND '
'"webhookId" = :webhookId')
_cql_list_states = (
'SELECT "tenantId", "groupId", group_config, active, pending, '
'"groupTouched", "policyTouched", paused, desired, created_at, status, '
'error_reasons, suspended '
'FROM {cf} WHERE "tenantId"=:tenantId AND deleting=false;')
_cql_list_policy = (
'SELECT "policyId", data FROM {cf} WHERE '
'"tenantId" = :tenantId AND "groupId" = :groupId;')
_cql_list_webhook = (
'SELECT "webhookId", data, capability FROM {cf} '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId '
'AND "policyId" = :policyId;')
_cql_list_all_in_group = ('SELECT * FROM {cf} WHERE "tenantId" = :tenantId '
'AND "groupId" = :groupId {order_by};')
# Webhook keys table
_cql_insert_webhook_key = (
'INSERT INTO {cf}("webhookKey", "tenantId", "groupId", "policyId") '
'VALUES (:{name}Key, :tenantId, :groupId, :policyId)')
_cql_find_webhook_token = (
'SELECT "tenantId", "groupId", "policyId" FROM {cf} '
'WHERE "webhookKey" = :webhookKey;')
_cql_del_on_key = 'DELETE FROM {cf} WHERE "webhookKey"=:{name}webhookKey'
_cql_count_for_tenant = (
'SELECT COUNT(*) FROM {cf} '
'WHERE "tenantId"=:tenantId {deleting};')
_cql_count_for_policy = (
'SELECT COUNT(*) FROM {cf} '
'WHERE "tenantId" = :tenantId AND "groupId" = :groupId '
'AND "policyId" = :policyId;')
_cql_count_for_group = (
'SELECT COUNT(*) FROM {cf} WHERE "tenantId" = :tenantId '
'AND "groupId" = :groupId;')
_cql_count_all = ('SELECT COUNT(*) FROM {cf};')
# seems to be pretty quick no matter the consistency - unfortunately this only
# checks we can connect to Cassandra, and not whether the otter keyspace is
# correct, etc.
_cql_health_check = ('SELECT now() FROM system.local;')
def _paginated_list(tenant_id, group_id=None, policy_id=None, limit=100,
marker=None):
"""
:param tenant_id: the tenant ID - if this is all that is provided, this
function returns cql to list all groups
:param group_id: the group ID - if this and tenant ID are all that is
provided, this function returns cql to list all policies.
:param policy_id: the policyID - if this and gorupID and tenant ID are
provided, this function returns cql to list all webhooks. Note that
if this is provided and groupID is not provided, the policy ID will be
ignored and cql to list all groups will be returned.
:param marker: the ID of the last column of the provided keys. (e.g.
group_id, when listing groups, policy_id, when listing policies,
and webhook_id, when listing webhooks)
:param limit: is the number of items to fetch
:returns: a tuple of cql and a dict of the parameters to provide when
executing that CQL.
The CQL will look like:
SELECT "policyId", data FROM {cf} WHERE "tenantId" = :tenantId AND
"groupId" = :groupId AND "policyId" > :marker LIMIT 100;
Note that the column family name still has to be inserted.
Also, no ``ORDER BY`` is in the CQL, since for these are all primary keys
sorted by cluster order (e.g. if you get all scaling groups for a tenant,
the groups will be returned in ascending order of group ID, and if you get
all policies for a scaling group, they will be returned in ascending order
of policy ID)
See http://cassandra.apache.org/doc/cql3/CQL.html#createTableOptions
"""
params = {'tenantId': tenant_id, 'limit': limit}
marker_cql = ''
if marker is not None:
marker_cql = " AND {0} > :marker"
params['marker'] = marker
if group_id is not None:
params['groupId'] = group_id
if policy_id is not None:
params['policyId'] = policy_id
cql_parts = [_cql_list_webhook.rstrip(';'),
marker_cql.format('"webhookId"')]
else:
cql_parts = [_cql_list_policy.rstrip(';'),
marker_cql.format('"policyId"')]
else:
cql_parts = [_cql_list_states.rstrip(';'),
marker_cql.format('"groupId"')]
cql_parts.append(" LIMIT :limit;")
return (''.join(cql_parts), params)
def _build_policies(policies, policies_table, event_table, queries, data,
buckets):
"""
Because inserting many values into a table with compound keys with one
insert statement is hard. This builds a bunch of insert statements and a
dictionary matching different parameter names to different policies.
:param policies: a list of policy data without ID
:type policies: ``list`` of ``dict``
:param policies_table: the name of the policies table
:type policies_table: ``str``
:param queries: a list of existing CQL queries to add to
:type queries: ``list`` of ``str``
:param data: the dictionary of named parameters and values passed in
addition to the query to execute the query
:type data: ``dict``
:returns: a ``list`` of the created policies along with their generated IDs
"""
outpolicies = []
if policies is not None:
for i, policy in enumerate(policies):
polname = "policy{}".format(i)
polId = generate_key_str('policy')
queries.append(_cql_insert_policy.format(cf=policies_table,
name=polname))
data[polname + 'data'] = serialize_json_data(policy, 1)
data[polname + 'policyId'] = polId
data[polname + 'version'] = uuid.uuid1()
if policy.get("type") == 'schedule':
_build_schedule_policy(policy, event_table, queries,
data, polname, buckets)
outpolicies.append(policy.copy())
outpolicies[-1]['id'] = polId
return outpolicies
def _build_schedule_policy(policy, event_table, queries, data, polname,
buckets):
"""
Build schedule-type policy
"""
data[polname + 'bucket'] = buckets.next()
if 'at' in policy["args"]:
queries.append(_cql_insert_group_event
.format(cf=event_table, name=polname))
at_time = timestamp.from_timestamp(policy["args"]["at"])
data[polname + "trigger"] = at_time
elif 'cron' in policy["args"]:
queries.append(_cql_insert_group_event_with_cron
.format(cf=event_table, name=polname))
cron = policy["args"]["cron"]
data[polname + "trigger"] = next_cron_occurrence(cron)
data[polname + 'cron'] = cron
def _build_webhooks(bare_webhooks, webhooks_table, webhooks_keys_table,
queries, cql_parameters):
"""
Because inserting many values into a table with compound keys with one
insert statement is hard. This builds a bunch of insert statements and a
dictionary matching different parameter names to different policies.
:param bare_webhooks: a list of webhook data without ID or webhook keys,
or any generated capability hash info
:type bare_webhooks: ``list`` of ``dict``
:param webhooks_table: the name of the webhooks table
:type webhooks_table: ``str``
:param queries: a list of existing CQL queries to add to
:type queries: ``list`` of ``str``
:param cql_parameters: the dictionary of named parameters and values passed
in addition to the query to execute the query - additional parameters
will be added to this dictionary
:type cql_paramters: ``dict``
:returns: ``list`` of the created webhooks along with their IDs
"""
output = []
for i, webhook in enumerate(bare_webhooks):
name = "webhook{0}".format(i)
webhook_id = generate_key_str('webhook')
queries.append(_cql_insert_webhook.format(cf=webhooks_table,
name=name))
queries.append(_cql_insert_webhook_key.format(cf=webhooks_keys_table,
name=name))
# generate the real data that will be stored, which includes the
# webhook token, the capability stuff, and metadata by default
bare_webhooks[i].setdefault('metadata', {})
version, cap_hash = generate_capability()
cql_parameters[name] = serialize_json_data(webhook, 1)
cql_parameters['{0}Id'.format(name)] = webhook_id
cql_parameters['{0}Key'.format(name)] = cap_hash
cql_parameters['{0}Capability'.format(name)] = serialize_json_data(
{version: cap_hash}, 1)
output.append(dict(id=webhook_id,
capability={'hash': cap_hash, 'version': version},
**webhook))
return output
def _assemble_webhook_from_row(row, include_id=False):
"""
Builds a webhook as per :data:`otter.json_schema.model_schemas.webhook`
from the user-mutable user data (name and metadata) and the
non-user-mutable capability data.
:param dict row: a dictionary of cassandra data containing the key
``data`` (the user-mutable data) and the key ``capability`` (the
capability info, stored in cassandra as:
``{<version>: <capability hash>}``)
:return: the webhook, as per webhook schema
:rtype: ``dict``
"""
webhook_base = _jsonloads_data(row['data'])
capability_data = _jsonloads_data(row['capability'])
version, cap_hash = capability_data.iteritems().next()
webhook_base['capability'] = {'version': version, 'hash': cap_hash}
if include_id:
webhook_base['id'] = row['webhookId']
return webhook_base
def _check_empty_and_grab_data(results, exception_if_empty):
if len(results) == 0:
raise exception_if_empty
return _jsonloads_data(results[0]['data'])
def _jsonloads_data(raw_data):
data = json.loads(raw_data)
if "_ver" in data:
del data["_ver"]
return data
def _group_status(status, deleting):
if deleting:
return ScalingGroupStatus.DELETING
else:
# TODO: #1304
if status is None:
return ScalingGroupStatus.ACTIVE
elif status == 'DISABLED':
return ScalingGroupStatus.ERROR
else:
return ScalingGroupStatus.lookupByName(status)
def _unmarshal_state(state_dict):
desired_capacity = state_dict['desired']
if desired_capacity is None:
desired_capacity = 0
status = _group_status(state_dict['status'],
state_dict.get('deleting', False))
return GroupState(
state_dict["tenantId"], state_dict["groupId"],
_jsonloads_data(state_dict["group_config"])["name"],
_jsonloads_data(state_dict["active"]),
_jsonloads_data(state_dict["pending"]),
state_dict["groupTouched"],
_jsonloads_data(state_dict["policyTouched"]),
state_dict["paused"],
status,
desired=desired_capacity,
error_reasons=(state_dict["error_reasons"] or []),
suspended=bool(state_dict["suspended"])
)
def assemble_webhooks_in_policies(policies, webhooks):
"""
Assemble webhooks inside policies.
'webhooks' property will be added to each policy `dict` in `policies`. It
will be list of webhooks taken from `webhooks`.
:param policies: list of policy `dict` sorted based on 'id' based on
`group_schemas.policy`
:param webhooks: list of webhook `dict` sorted based on 'policyId' and
'webhookId' based on `model_schemas.webhook`
:return: policies with webhooks in them
"""
# Assuming policies and webhooks are sorted based on policyId and
# (policyId, webhookId) respectively
iwebhooks = iter(webhooks)
ipolicies = iter(policies)
try:
webhook = iwebhooks.next()
policy = ipolicies.next()
while True:
policy.setdefault('webhooks', [])
if policy['id'] == webhook['policyId']:
policy['webhooks'].append(
_assemble_webhook_from_row(webhook, include_id=True))
webhook = iwebhooks.next()
elif policy['id'] < webhook['policyId']:
policy = ipolicies.next()
else:
webhook = iwebhooks.next()
except StopIteration:
# Add empty webhooks for remaining policies
[p.update({'webhooks': []}) for p in ipolicies]
return policies
def verified_view(connection, view_query, del_query, data, consistency,
exception_if_empty, log):
"""
Ensures the view query on the group does not get resurrected row,
i.e. one that does not have "created_at" in it. Any resurrected entry is
deleted and `exception_if_empty` is raised. Also raises
`exception_if_empty` if group's status is DELETING
:return: Deferred that fires with result of executing view query
"""
def _check_resurrection(result):
if len(result) == 0:
raise exception_if_empty
group = result[0]
if group.get('created_at') is None:
# resurrected row, trigger its deletion and raise empty exception
log.msg('Resurrected row', row=result[0], row_params=data)
connection.execute(del_query, data, consistency)
raise exception_if_empty
return group
d = connection.execute(view_query, data, consistency)
return d.addCallback(_check_resurrection)
def _del_webhook_queries(table, webhooks):
"""
Return queries and params to delete webhooks from webhook_keys table
"""
queries, params = [], {}
for i, webhook in enumerate(webhooks):
name = 'key{}'.format(i)
queries.append(_cql_del_on_key.format(cf=table, name=name))
params[name + 'webhookKey'] = webhook['webhookKey']
return queries, params
def get_client_ts(reactor):
"""
Return EPOCH with microseconds precision synchronously
"""
return int(reactor.seconds() * 1000000)
def _check_deleting(group, get_deleting=False):
"""
Given a single group from reading the scaling group table, and whether
a deleting group should be returns, either returns the group or raises
a :class:`NoSuchScalingGroupError`.
"""
if not get_deleting and group['deleting']:
raise NoSuchScalingGroupError(group['tenantId'], group['groupId'])
return group
@implementer(IScalingGroup)
class CassScalingGroup(object):
"""
.. autointerface:: otter.models.interface.IScalingGroup
:ivar tenant_id: the tenant ID of the scaling group - once set, should not
be updated
:type tenant_id: ``str``
:ivar uuid: UUID of the scaling group - once set, cannot be updated
:type uuid: ``str``
:ivar connection: silverberg client used to connect to cassandra
:type connection: :class:`silverberg.client.CQLClient`
:ivar buckets: Scheduler buckets
:type buckets: iterator of buckets that does not end
:ivar kz_client: Kazoo client used for locking
:type kz_client: :class:`txkazoo.TxKazooClient`
:ivar reactor: Reactor used for time manipulations
:type reactor: :class:`twisted.internet.reactor.IReactorTime` provider
:ivar local_locks: Local locks used when modifying state
:type local_locks: :class:`WeakLocks`
IMPORTANT REMINDER: In CQL, update will create a new row if one doesn't
exist. Therefore, before doing an update, a read must be performed first
else an entry is created where none should have been.
Cassandra doesn't have atomic read-update. You can't be guaranteed that
the previous state (from the read) hasn't changed between when you got it
back from Cassandra and when you are sending your new update/insert
request.
Also, because deletes are done as tombstones rather than actually deleting,
deletes are also updates and hence a read must be performed before deletes.
"""
def __init__(self, log, tenant_id, uuid, connection, buckets, kz_client,
reactor, local_locks, dispatcher):
"""
Creates a CassScalingGroup object.
"""
self.log = log.bind(system=self.__class__.__name__,
tenant_id=tenant_id,
scaling_group_id=uuid)
self.tenant_id = tenant_id
self.uuid = uuid
self.connection = connection
self.buckets = buckets
self.kz_client = kz_client
self.reactor = reactor
self.local_locks = local_locks
self.dispatcher = dispatcher
self.group_table = "scaling_group"
self.launch_table = "launch_config"
self.policies_table = "scaling_policies"
self.state_table = "group_state"
self.webhooks_table = "policy_webhooks"
self.webhooks_keys_table = "webhook_keys"
self.event_table = "scaling_schedule_v2"
self.servers_cache_table = "servers_cache"
def with_timestamp(self, func):
"""
Decorator that calls the given function with timestamp
The timestamp returned is used when inserting/deleting/updating group.
This is required because state updates very close in time can be
corrupted (even if they are serial). This is because of small clock
drifts in cass nodes. This ensures that state updates from same node
is always serial. This however does not (yet) handle simultaneous
executions from multiple nodes.
"""
@functools.wraps(func)
def wrapper(*args):
return func(get_client_ts(self.reactor), *args)
return wrapper
def view_manifest(self, with_policies=True, with_webhooks=False,
get_deleting=False):
"""
see :meth:`otter.models.interface.IScalingGroup.view_manifest`
"""
def _set_policies_on_group(policies, group):
group['scalingPolicies'] = policies
return group
def _get_policies(group):
d = self._naive_list_policies()
return d.addCallback(_set_policies_on_group, group)
def _get_policies_and_webhooks(group):
d = defer.gatherResults(
[self._naive_list_policies(),
self._naive_list_all_webhooks()], consumeErrors=True)
return d.addCallback(lambda results: (group, results))
def _assemble_webhooks((group, results)):
policies, webhooks = results
return _set_policies_on_group(
assemble_webhooks_in_policies(policies, webhooks),
group)
def _generate_manifest_group_part(group):
m = {
'groupConfiguration': _jsonloads_data(group['group_config']),
'launchConfiguration': _jsonloads_data(group['launch_config']),
'id': self.uuid,
'state': _unmarshal_state(group),
}
return m
view_query = _cql_view_manifest.format(
cf=self.group_table)
del_query = _cql_delete_all_in_group.format(
cf=self.group_table, name='')
d = verified_view(self.connection, view_query, del_query,
{"tenantId": self.tenant_id,
"groupId": self.uuid},
DEFAULT_CONSISTENCY,
NoSuchScalingGroupError(self.tenant_id, self.uuid),
self.log)
d.addCallback(_check_deleting, get_deleting)
d.addCallback(_generate_manifest_group_part)
if with_policies:
if with_webhooks:
d.addCallback(_get_policies_and_webhooks)
d.addCallback(_assemble_webhooks)
else:
d.addCallback(_get_policies)
return d
def view_config(self):
"""
see :meth:`otter.models.interface.IScalingGroup.view_config`
"""
view_query = _cql_view.format(
cf=self.group_table, column='group_config')
del_query = _cql_delete_all_in_group.format(
cf=self.group_table, name='')
d = verified_view(self.connection, view_query, del_query,
{"tenantId": self.tenant_id,
"groupId": self.uuid},
DEFAULT_CONSISTENCY,
NoSuchScalingGroupError(self.tenant_id, self.uuid),
self.log)
return d.addCallback(lambda group:
_jsonloads_data(group['group_config']))
def view_launch_config(self):
"""
see :meth:`otter.models.interface.IScalingGroup.view_launch_config`
"""
view_query = _cql_view.format(
cf=self.group_table, column='launch_config')
del_query = _cql_delete_all_in_group.format(
cf=self.group_table, name='')
d = verified_view(self.connection, view_query, del_query,
{"tenantId": self.tenant_id,
"groupId": self.uuid},
DEFAULT_CONSISTENCY,
NoSuchScalingGroupError(self.tenant_id, self.uuid),
self.log)
return d.addCallback(lambda group:
_jsonloads_data(group['launch_config']))
def view_state(self, consistency=None, get_deleting=False):
"""
see :meth:`otter.models.interface.IScalingGroup.view_state`
"""
if consistency is None:
consistency = DEFAULT_CONSISTENCY
view_query = _cql_view_manifest.format(cf=self.group_table)
del_query = _cql_delete_all_in_group.format(
cf=self.group_table, name='')
d = verified_view(self.connection, view_query, del_query,
{"tenantId": self.tenant_id,
"groupId": self.uuid},
consistency,
NoSuchScalingGroupError(self.tenant_id, self.uuid),
self.log)
d.addCallback(_check_deleting, get_deleting)
return d.addCallback(_unmarshal_state)
def modify_state(self, modifier_callable, *args, **kwargs):
"""
see :meth:`otter.models.interface.IScalingGroup.modify_state`
"""
modify_state_reason = kwargs.pop('modify_state_reason', None)
log = self.log.bind(
system='CassScalingGroup.modify_state',
modify_state_reason=modify_state_reason)
consistency = DEFAULT_CONSISTENCY
@self.with_timestamp
def _write_state(timestamp, new_state):
assert (new_state.tenant_id == self.tenant_id and
new_state.group_id == self.uuid)
params = {
'tenantId': new_state.tenant_id,
'groupId': new_state.group_id,
'active': serialize_json_data(new_state.active, 1),
'pending': serialize_json_data(new_state.pending, 1),
'paused': new_state.paused,
'suspended': new_state.suspended,
'desired': new_state.desired,
'groupTouched': new_state.group_touched,
'policyTouched': serialize_json_data(new_state.policy_touched,
1),
'ts': timestamp
}
return self.connection.execute(
_cql_insert_group_state.format(cf=self.group_table),
params, consistency)
def _modify_state():
d = self.view_state(consistency)
d.addCallback(lambda state: modifier_callable(
self, state, *args, **kwargs))
return d.addCallback(_write_state)
lock = zk.PollingLock(self.dispatcher, LOCK_PATH + '/' + self.uuid)
lock.acquire = functools.partial(lock.acquire, timeout=ACQUIRE_TIMEOUT)
local_lock = self.local_locks.get_lock(self.uuid)
return local_lock.run(
with_lock, self.reactor, lock, _modify_state,
log.bind(category='locking', lock_reason='modify_state'),
acquire_timeout=ACQUIRE_TIMEOUT + 5,
release_timeout=RELEASE_TIMEOUT)
def update_status(self, status):
"""
see :meth:`otter.models.interface.IScalingGroup.update_status`
"""
self.log.bind(status=status).msg("Updating status")
@self.with_timestamp
def _do_update(ts, _):
return self.connection.execute(
_cql_update.format(cf=self.group_table,
column='status',
name=':status'),
{'tenantId': self.tenant_id,
'groupId': self.uuid,
'ts': ts,
'status': status.name},
DEFAULT_CONSISTENCY)
@self.with_timestamp
def set_deleting(ts, _):
return self.connection.execute(
_cql_update.format(cf=self.group_table,
column='deleting',
name=':deleting'),
{'tenantId': self.tenant_id,
'groupId': self.uuid,
'ts': ts,
'deleting': True},
DEFAULT_CONSISTENCY)
d = self.view_config()
if status == ScalingGroupStatus.DELETING:
d.addCallback(set_deleting)
else:
d.addCallback(_do_update)
return d
def update_error_reasons(self, reasons):
"""
see :meth:`otter.models.interface.IScalingGroup.update_error_reasons`
"""
self.log.msg("Updating error reasons {reasons}", reasons=reasons)
@self.with_timestamp
def _do_update(ts, lastRev):
query = _cql_update.format(
cf=self.group_table, column='error_reasons', name=":reasons")
return self.connection.execute(
query,
{"tenantId": self.tenant_id, "groupId": self.uuid,
"reasons": reasons, "ts": ts},
DEFAULT_CONSISTENCY)
d = self.view_config()
d.addCallback(_do_update)
return d
def update_config(self, data):
"""
see :meth:`otter.models.interface.IScalingGroup.update_config`
"""
self.log.bind(updated_config=data).msg("Updating config")
@self.with_timestamp
def _do_update_config(ts, lastRev):
queries = [_cql_update.format(
cf=self.group_table, column='group_config', name=":scaling")]
b = Batch(queries, {"tenantId": self.tenant_id,
"groupId": self.uuid,
"scaling": serialize_json_data(data, 1),
"ts": ts},
consistency=DEFAULT_CONSISTENCY)
return b.execute(self.connection)
d = self.view_config()
d.addCallback(_do_update_config)
return d
def update_launch_config(self, data):
"""
see :meth:`otter.models.interface.IScalingGroup.update_launch_config`
"""
self.log.bind(updated_launch_config=data).msg("Updating launch config")
@self.with_timestamp
def _do_update_launch(ts, lastRev):
queries = [_cql_update.format(
cf=self.group_table, column='launch_config', name=":launch")]
b = Batch(queries, {"tenantId": self.tenant_id,
"groupId": self.uuid,
"launch": serialize_json_data(data, 1),
"ts": ts},
consistency=DEFAULT_CONSISTENCY)
d = b.execute(self.connection)
return d
d = self.view_config()
d.addCallback(_do_update_launch)
return d
def _naive_list_policies(self, limit=None, marker=None):
"""
Like :meth:`otter.models.cass.CassScalingGroup.list_policies`, but gets
all the policies associated with particular scaling group
irregardless of whether the scaling group still exists.
"""
def insert_id(rows):
return [dict(id=row['policyId'], **_jsonloads_data(row['data']))
for row in rows]
# TODO: this is just in place so that pagination in the manifest can
# be handled elsewhere
if limit is not None:
cql, params = _paginated_list(self.tenant_id, self.uuid,
limit=limit, marker=marker)
else:
cql = _cql_list_policy
params = {"tenantId": self.tenant_id, "groupId": self.uuid}
d = self.connection.execute(cql.format(cf=self.policies_table), params,
DEFAULT_CONSISTENCY)
d.addCallback(insert_id)
return d
def list_policies(self, limit=100, marker=None):
"""
see :meth:`otter.models.interface.IScalingGroup.list_policies`
"""
# If there are no policies - make sure it's not because the group
# doesn't exist
def _check_if_empty(policies_dict):
if len(policies_dict) == 0:
return self.view_config().addCallback(lambda _: policies_dict)
return policies_dict
d = self._naive_list_policies(limit=limit, marker=marker)
return d.addCallback(_check_if_empty)
def get_policy(self, policy_id, version=None):
"""
see :meth:`otter.models.interface.IScalingGroup.get_policy`
"""
def fetch_policy(_):
query = _cql_view_policy.format(cf=self.policies_table)
d = self.connection.execute(query,
{"tenantId": self.tenant_id,
"groupId": self.uuid,
"policyId": policy_id},
DEFAULT_CONSISTENCY)
return d.addCallback(_extract_policy)