This repository was archived by the owner on May 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathbase.py
More file actions
executable file
·4055 lines (3505 loc) · 149 KB
/
base.py
File metadata and controls
executable file
·4055 lines (3505 loc) · 149 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import abc
import base64
import collections
import json
import logging
import os
import warnings
import six
from six.moves import urllib
log = logging.getLogger(__name__)
class ConsulException(Exception):
pass
class ACLDisabled(ConsulException):
pass
class ACLPermissionDenied(ConsulException):
pass
class NotFound(ConsulException):
pass
class Timeout(ConsulException):
pass
class BadRequest(ConsulException):
pass
class ClientError(ConsulException):
"""Encapsulates 4xx Http error code"""
pass
#
# Convenience to define checks
class Check(object):
"""
There are three different kinds of checks: script, http and ttl
"""
@classmethod
def script(klass, args, interval):
"""
Run the script *args* every *interval* (e.g. "10s") to peform health
check
"""
if isinstance(args, six.string_types) \
or isinstance(args, six.binary_type):
warnings.warn(
"Check.script should take a list of arg", DeprecationWarning)
args = ["sh", "-c", args]
return {'args': args, 'interval': interval}
@classmethod
def http(klass, url, interval, timeout=None, deregister=None, header=None,
tls_skip_verify=None):
"""
Perform a HTTP GET against *url* every *interval* (e.g. "10s") to
perform health check with an optional *timeout* and optional
*deregister* after which a failing service will be automatically
deregistered. Optional parameter *header* specifies headers sent in
HTTP request. *header* parameter is in form of map of lists of
strings, e.g. {"x-foo": ["bar", "baz"]}. Optional parameter
*tls_skip_verify* allow to skip TLS certificate verification.
"""
ret = {'http': url, 'interval': interval}
if timeout:
ret['timeout'] = timeout
if deregister:
ret['DeregisterCriticalServiceAfter'] = deregister
if header:
ret['header'] = header
if tls_skip_verify:
ret['TLSSkipVerify'] = tls_skip_verify
return ret
@classmethod
def tcp(klass, host, port, interval, timeout=None, deregister=None):
"""
Attempt to establish a tcp connection to the specified *host* and
*port* at a specified *interval* with optional *timeout* and optional
*deregister* after which a failing service will be automatically
deregistered.
"""
ret = {
'tcp': '{host:s}:{port:d}'.format(host=host, port=port),
'interval': interval
}
if timeout:
ret['timeout'] = timeout
if deregister:
ret['DeregisterCriticalServiceAfter'] = deregister
return ret
@classmethod
def ttl(klass, ttl):
"""
Set check to be marked as critical after *ttl* (e.g. "10s") unless the
check is periodically marked as passing.
"""
return {'ttl': ttl}
@classmethod
def docker(klass, container_id, shell, script, interval, deregister=None):
"""
Invoke *script* packaged within a running docker container with
*container_id* at a specified *interval* on the configured
*shell* using the Docker Exec API. Optional *register* after which a
failing service will be automatically deregistered.
"""
ret = {
'docker_container_id': container_id,
'shell': shell,
'script': script,
'interval': interval
}
if deregister:
ret['DeregisterCriticalServiceAfter'] = deregister
return ret
@classmethod
def grpc(klass, grpc, interval, deregister=None):
"""
grpc (string: "") - Specifies a gRPC check's endpoint that
supports the standard gRPC health checking protocol.
The state of the check will be updated at the given
Interval by probing the configured endpoint. Add the
service identifier after the gRPC check's endpoint in the
following format to check for a specific service instead of
the whole gRPC server /:service_identifier.
"""
ret = {
'GRPC': grpc,
'Interval': interval
}
if deregister:
ret['DeregisterCriticalServiceAfter'] = deregister
return ret
@classmethod
def _compat(
self,
script=None,
interval=None,
ttl=None,
http=None,
timeout=None,
deregister=None):
if not script and not http and not ttl:
return {}
log.warning(
'DEPRECATED: use consul.Check.script/http/ttl to specify check')
ret = {'check': {}}
if script:
assert interval and not (ttl or http)
ret['check'] = {'script': script, 'ttl': interval}
if ttl:
assert not (interval or script or http)
ret['check'] = {'ttl': ttl}
if http:
assert interval and not (script or ttl)
ret['check'] = {'http': http, 'interval': interval}
if timeout:
assert http
ret['check']['timeout'] = timeout
# if deregister:
# ret['check']['DeregisterCriticalServiceAfter'] = deregister
return ret
Response = collections.namedtuple(
'Response', ['code', 'headers', 'body', 'content'])
#
# Conveniences to create consistent callback handlers for endpoints
class CB(object):
@classmethod
def _status(klass, response, allow_404=True):
# status checking
if 400 <= response.code < 500:
if response.code == 400:
raise BadRequest('%d %s' % (response.code, response.body))
elif response.code == 401:
raise ACLDisabled(response.body)
elif response.code == 403:
raise ACLPermissionDenied(response.body)
elif response.code == 404:
if not allow_404:
raise NotFound(response.body)
else:
raise ClientError("%d %s" % (response.code, response.body))
elif 500 <= response.code < 600:
raise ConsulException("%d %s" % (response.code, response.body))
@classmethod
def bool(klass):
# returns True on successful response
def cb(response):
CB._status(response)
return response.code == 200
return cb
@classmethod
def json(
klass,
map=None,
allow_404=True,
one=False,
decode=False,
is_id=False,
index=False):
"""
*map* is a function to apply to the final result.
*allow_404* if set, None will be returned on 404, instead of raising
NotFound.
*index* if set, a tuple of index, data will be returned.
*one* returns only the first item of the list of items. empty lists are
coerced to None.
*decode* if specified this key will be base64 decoded.
*is_id* only the 'ID' field of the json object will be returned.
"""
def cb(response):
CB._status(response, allow_404=allow_404)
if response.code == 404:
return response.headers.get('X-Consul-Index'), None
data = json.loads(response.body)
if decode:
for item in data:
if item.get(decode) is not None:
item[decode] = base64.b64decode(item[decode])
if is_id:
data = data['ID']
if one:
if not data:
data = None
if data is not None:
data = data[0]
if map:
data = map(data)
if index:
return response.headers['X-Consul-Index'], data
return data
return cb
@classmethod
def binary(klass):
"""
This method simply returns response body, usefull for snapshot
"""
def cb(response):
CB._status(response)
return response.content
return cb
#
# Convenience to define weight
class Weight(object):
"""
There object for set weights parameters like this
{'passing': 100, 'warning': 100}
"""
@classmethod
def weights(cls, passing, warning):
return {'passing': passing, 'warning': warning}
class HTTPClient(six.with_metaclass(abc.ABCMeta, object)):
def __init__(self, host='127.0.0.1', port=8500, scheme='http',
verify=True, cert=None, timeout=None):
self.host = host
self.port = port
self.scheme = scheme
self.verify = verify
self.base_uri = '%s://%s:%s' % (self.scheme, self.host, self.port)
self.cert = cert
self.timeout = timeout
def uri(self, path, params=None):
uri = self.base_uri + urllib.parse.quote(path, safe='/:')
if params:
uri = '%s?%s' % (uri, urllib.parse.urlencode(params))
return uri
@abc.abstractmethod
def get(self, callback, path, params=None, headers=None):
raise NotImplementedError
@abc.abstractmethod
def put(self, callback, path, params=None, data='', headers=None):
raise NotImplementedError
@abc.abstractmethod
def delete(self, callback, path, params=None, data='', headers=None):
raise NotImplementedError
@abc.abstractmethod
def post(self, callback, path, params=None, data='', headers=None):
raise NotImplementedError
class Consul(object):
def __init__(
self,
host='127.0.0.1',
port=8500,
token=None,
scheme='http',
consistency='default',
dc=None,
verify=True,
cert=None,
**kwargs):
"""
*token* is an optional `ACL token`_. If supplied it will be used by
default for all requests made with this client session. It's still
possible to override this token by passing a token explicitly for a
request.
*consistency* sets the consistency mode to use by default for all reads
that support the consistency option. It's still possible to override
this by passing explicitly for a given request. *consistency* can be
either 'default', 'consistent' or 'stale'.
*dc* is the datacenter that this agent will communicate with.
By default the datacenter of the host is used.
*verify* is whether to verify the SSL certificate for HTTPS requests
*cert* client side certificates for HTTPS requests
"""
# TODO: Status
if os.getenv('CONSUL_HTTP_ADDR'):
try:
host, port = os.getenv('CONSUL_HTTP_ADDR').split(':')
scheme = 'http'
except ValueError:
try:
scheme, host, port = \
os.getenv('CONSUL_HTTP_ADDR').split(':')
host = host.lstrip('//')
except ValueError:
raise ConsulException('CONSUL_HTTP_ADDR (%s) invalid, '
'does not match <host>:<port> or '
'<protocol>:<host>:<port>'
% os.getenv('CONSUL_HTTP_ADDR'))
use_ssl = os.getenv('CONSUL_HTTP_SSL')
if use_ssl == 'true':
scheme = 'https'
if os.getenv('CONSUL_HTTP_SSL_VERIFY') is not None:
verify = os.getenv('CONSUL_HTTP_SSL_VERIFY') == 'true'
self.acl = Consul.ACL(self)
self.agent = Consul.Agent(self)
self.catalog = Consul.Catalog(self)
self.config = Consul.Config(self)
self.connect = Consul.Connect(self)
assert consistency in ('default', 'consistent', 'stale'), \
'consistency must be either default, consistent or state'
self.consistency = consistency
self.coordinate = Consul.Coordinate(self)
self.dc = dc
self.discovery_chain = Consul.DiscoveryChain(self)
self.event = Consul.Event(self)
self.health = Consul.Health(self)
self.http = self.http_connect(host,
port,
scheme,
verify,
cert,
**kwargs)
self.kv = Consul.KV(self)
self.operator = Consul.Operator(self)
self.query = Consul.Query(self)
self.scheme = scheme
self.session = Consul.Session(self)
self.snapshot = Consul.Snapshot(self)
self.status = Consul.Status(self)
self.token = os.getenv('CONSUL_HTTP_TOKEN', token)
self.txn = Consul.Txn(self)
class ACL(object):
def __init__(self, agent):
self.agent = agent
self.tokens = Consul.ACL.Tokens(agent)
self.legacy_tokens = Consul.ACL.LegacyTokens(agent)
self.policy = Consul.ACL.Policy(agent)
self.roles = Consul.ACL.Roles(agent)
self.auth_method = Consul.ACL.AuthMethod(agent)
self.binding_rule = Consul.ACL.BindingRule(agent)
def self(self, token=None):
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(
CB.json(), path='/v1/acl/token/self', headers=headers)
def list(self, token=None):
"""
Lists all the active ACL tokens. This is a privileged endpoint, and
requires a management token. *token* will override this client's
default token. An *ACLPermissionDenied* exception will be raised
if a management token is not used.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(
CB.json(), path='/v1/acl/list', headers=headers)
def info(self, acl_id, token=None):
"""
Returns the token information for *acl_id*.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(
CB.json(one=True),
path='/v1/acl/info/%s' % acl_id,
headers=headers)
def create(self,
name=None,
type='client',
rules=None,
acl_id=None,
token=None):
"""
Creates a new ACL token. This is a privileged endpoint, and
requires a management token. *token* will override this client's
default token. An *ACLPermissionDenied* exception will be raised
if a management token is not used.
*name* is an optional name for this token.
*type* is either 'management' or 'client'. A management token is
effectively like a root user, and has the ability to perform any
action including creating, modifying, and deleting ACLs. A client
token can only perform actions as permitted by *rules*.
*rules* is an optional `HCL`_ string for this `ACL Token`_ Rule
Specification.
Rules look like this::
# Default all keys to read-only
key "" {
policy = "read"
}
key "foo/" {
policy = "write"
}
key "foo/private/" {
# Deny access to the private dir
policy = "deny"
}
Returns the string *acl_id* for the new token.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
payload = {}
if name:
payload['Name'] = name
if type:
assert type in ('client', 'management'), \
'type must be client or management'
payload['Type'] = type
if rules:
assert isinstance(rules, str), \
'Only HCL or JSON encoded strings supported for the moment'
payload['Rules'] = rules
if acl_id:
payload['ID'] = acl_id
if payload:
data = json.dumps(payload)
else:
data = ''
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/create',
headers=headers,
data=data)
def update(self, acl_id, name=None, type=None, rules=None, token=None):
"""
Updates the ACL token *acl_id*. This is a privileged endpoint, and
requires a management token. *token* will override this client's
default token. An *ACLPermissionDenied* exception will be raised if
a management token is not used.
*name* is an optional name for this token.
*type* is either 'management' or 'client'. A management token is
effectively like a root user, and has the ability to perform any
action including creating, modifying, and deleting ACLs. A client
token can only perform actions as permitted by *rules*.
*rules* is an optional `HCL`_ string for this `ACL Token`_ Rule
Specification.
Returns the string *acl_id* of this token on success.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
payload = {'ID': acl_id}
if name:
payload['Name'] = name
if type:
assert type in ('client', 'management'), \
'type must be client or management'
payload['Type'] = type
if rules:
assert isinstance(rules, str), \
'Only HCL or JSON encoded strings supported for the moment'
payload['Rules'] = rules
data = json.dumps(payload)
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/update',
headers=headers,
data=data)
def clone(self, acl_id, token=None):
"""
Clones the ACL token *acl_id*. This is a privileged endpoint, and
requires a management token. *token* will override this client's
default token. An *ACLPermissionDenied* exception will be raised if
a management token is not used.
Returns the string of the newly created *acl_id*.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/clone/%s' % acl_id,
headers=headers)
def destroy(self, acl_id, token=None):
"""
Destroys the ACL token *acl_id*. This is a privileged endpoint, and
requires a management token. *token* will override this client's
default token. An *ACLPermissionDenied* exception will be raised if
a management token is not used.
Returns *True* on success.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(
CB.json(),
path='/v1/acl/destroy/%s' % acl_id,
headers=headers)
def bootstrap(self, token=None):
"""
This endpoint does a special one-time bootstrap of the ACL system,
making the first management token if the acl.tokens.master
configuration entry is not specified in the Consul server
configuration and if the cluster has not been bootstrapped
previously. This is available in Consul 0.9.1 and later, and
requires all Consul servers to be upgraded in order to operate.
:param token:
:return:
"""
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),
path='/v1/acl/bootstrap',
headers=headers)
def replication(self, dc=None, token=None):
"""
This endpoint returns the status of the ACL replication
processes in the datacenter. This is intended to be used
by operators or by automation checking to discover the
health of ACL replication.
:param dc:
:header token:
:return:
"""
params = []
headers = {}
token = token or self.agent.token
dc = dc or self.agent.dc
if token:
headers['X-Consul-Token'] = token
if dc:
params.append(('dc', dc))
return self.agent.http.get(CB.json(),
path='/v1/acl/replication',
params=params,
headers=headers)
def create_translate(self, payload, token=None):
"""
This endpoint translates the legacy rule syntax into the latest
syntax. It is intended to be used by operators managing Consul's
ACLs and performing legacy token to new policy migrations.
*payload*
agent "" {
policy = "read"
}
:return:
"""
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.post(CB.binary(),
path='/v1/acl/rules/translate',
headers=headers,
data=payload)
def get_translate(self, accessor_id, token=None):
"""
This endpoint translates the legacy rules embedded within a legacy
ACL into the latest syntax.
:param accessor_id:
:param token:
:return:
"""
path = '/v1/acl/rules/translate/%s' % accessor_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(CB.json(),
path=path,
headers=headers)
def login(self, auth_method, bearer_token, meta=None, token=None):
payload = {
"AuthMethod": auth_method,
"BearerToken": bearer_token,
}
if meta:
payload['Meta'] = meta
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.post(CB.json(),
path='/v1/acl/login',
headers=headers,
data=json.dumps(payload))
def logout(self, token=None):
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.post(CB.json(),
path='/v1/acl/logout',
headers=headers)
class Tokens(object):
"""
The APIs are available in Consul versions 1.4.0 and later.
"""
def __init__(self, agent=None):
self.agent = agent
def create(self, payload, token=None):
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),
path='/v1/acl/token',
headers=headers,
data=json.dumps(payload))
def get(self, accessor_id, token=None):
path = '/v1/acl/token/%s' % accessor_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(CB.json(),
path=path,
headers=headers)
def self(self, token=None):
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(CB.json(),
path='/v1/acl/token/self',
headers=headers)
def update(self, payload, accessor_id, token=None):
path = '/v1/acl/token/%s' % accessor_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),
path=path,
headers=headers,
data=json.dumps(payload))
def clone(self,
description='',
token=None,
accessor_id=None):
payload = {
"Description": description,
}
path = '/v1/acl/token/%s/clone' % accessor_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),
path=path,
headers=headers,
data=json.dumps(payload))
def delete(self, accessor_id, token=None):
path = '/v1/acl/token/%s' % accessor_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.delete(CB.bool(),
path=path,
headers=headers)
def list(
self, policy=None, role=None, authmethod=None, token=None):
params = []
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
if policy:
params.append(('policy', policy))
if role:
params.append(('role', role))
if authmethod:
params.append(('authmethod', authmethod))
return self.agent.http.get(CB.json(),
path='/v1/acl/tokens',
params=params,
headers=headers)
class LegacyTokens(object):
def __init__(self, agent=None):
warnings.warn(
'Consul 1.4.0 deprecates the legacy ACL.',
DeprecationWarning)
self.agent = agent
def list(self, token=None):
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.get(
CB.json(), path='/v1/acl/list', params=params)
def info(self, acl_id, token=None):
"""
Returns the token information for *acl_id*.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.get(CB.json(one=True),
path='/v1/acl/info/%s' % acl_id,
params=params)
def create(self,
name=None,
type='client',
rules=None,
acl_id=None,
token=None):
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
payload = {}
if name:
payload['Name'] = name
if type:
assert type in ('client', 'management'), \
'type must be client or management'
payload['Type'] = type
if rules:
assert isinstance(rules, str), \
'Only HCL or JSON encoded strings' \
' supported for the moment'
payload['Rules'] = rules
if acl_id:
payload['ID'] = acl_id
if payload:
data = json.dumps(payload)
else:
data = ''
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/create',
params=params,
data=data)
def update(self, acl_id, name=None,
type=None, rules=None, token=None):
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
payload = {'ID': acl_id}
if name:
payload['Name'] = name
if type:
assert type in ('client', 'management'), \
'type must be client or management'
payload['Type'] = type
if rules:
assert isinstance(rules, str), \
'Only HCL or JSON encoded strings' \
' supported for the moment'
payload['Rules'] = rules
data = json.dumps(payload)
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/update',
params=params,
data=data)
def clone(self, acl_id, token=None):
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.put(
CB.json(is_id=True),
path='/v1/acl/clone/%s' % acl_id,
params=params)
def destroy(self, acl_id, token=None):
"""
Returns *True* on success.
"""
warnings.warn('Consul 1.4.0 deprecated',
DeprecationWarning)
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.put(
CB.bool(),
path='/v1/acl/destroy/%s' % acl_id,
params=params)
class Policy(object):
def __init__(self, agent=None):
self.agent = agent
def create(self, name, description=None,
rules=None, datacenters=None, token=None):
payload = {"Name": name}
if description:
payload['Description'] = description
if rules:
payload['Rules'] = rules
if datacenters:
payload['Datacenters'] = datacenters
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),
path='/v1/acl/policy',
headers=headers,
data=json.dumps(payload))
def get(self, policy_id=None, name=None, token=None):
path = '/v1/acl/policy/%s' % (policy_id or 'name/' + name)
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.get(CB.json(),
path=path,
headers=headers)
def update(self, policy_id, name, description=None,
rules=None, datacenters=None, token=None):
payload = {"Name": name}
if description:
payload['Description'] = description
if rules:
payload['Rules'] = rules
if datacenters:
payload['Datacenters'] = datacenters
path = '/v1/acl/policy/%s' % policy_id
headers = {}
token = token or self.agent.token
if token:
headers['X-Consul-Token'] = token
return self.agent.http.put(CB.json(),