This repository was archived by the owner on Apr 15, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 217
Expand file tree
/
Copy pathbase.py
More file actions
executable file
·2419 lines (2039 loc) · 87.3 KB
/
base.py
File metadata and controls
executable file
·2419 lines (2039 loc) · 87.3 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 collections
import warnings
import logging
import base64
import json
import os
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 args", DeprecationWarning)
args = ["sh", "-c", args]
return {'args': args, 'interval': interval}
@classmethod
def http(klass, url, interval, timeout=None, deregister=None, header=None):
"""
Peform a HTTP GET against *url* every *interval* (e.g. "10s") to peform
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*
paramater is in form of map of lists of strings,
e.g. {"x-foo": ["bar", "baz"]}.
"""
ret = {'http': url, 'interval': interval}
if timeout:
ret['timeout'] = timeout
if deregister:
ret['DeregisterCriticalServiceAfter'] = deregister
if header:
ret['header'] = header
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 _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.warn(
'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, 'interval': 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'])
#
# 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['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 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
class HTTPClient(six.with_metaclass(abc.ABCMeta, object)):
def __init__(self, host='127.0.0.1', port=8500, scheme='http',
verify=True, cert=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
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):
raise NotImplementedError
@abc.abstractmethod
def put(self, callback, path, params=None, data=''):
raise NotImplementedError
@abc.abstractmethod
def delete(self, callback, path, params=None):
raise NotImplementedError
@abc.abstractmethod
def post(self, callback, path, params=None, data=''):
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):
"""
*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(':')
except ValueError:
raise ConsulException('CONSUL_HTTP_ADDR (%s) invalid, '
'does not match <host>:<port>'
% os.getenv('CONSUL_HTTP_ADDR'))
use_ssl = os.getenv('CONSUL_HTTP_SSL')
if use_ssl is not None:
scheme = 'https' if use_ssl == 'true' else 'http'
if os.getenv('CONSUL_HTTP_SSL_VERIFY') is not None:
verify = os.getenv('CONSUL_HTTP_SSL_VERIFY') == 'true'
self.http = self.connect(host, port, scheme, verify, cert)
self.token = os.getenv('CONSUL_HTTP_TOKEN', token)
self.scheme = scheme
self.dc = dc
assert consistency in ('default', 'consistent', 'stale'), \
'consistency must be either default, consistent or state'
self.consistency = consistency
self.event = Consul.Event(self)
self.kv = Consul.KV(self)
self.txn = Consul.Txn(self)
self.agent = Consul.Agent(self)
self.catalog = Consul.Catalog(self)
self.health = Consul.Health(self)
self.session = Consul.Session(self)
self.acl = Consul.ACL(self)
self.status = Consul.Status(self)
self.query = Consul.Query(self)
self.coordinate = Consul.Coordinate(self)
self.operator = Consul.Operator(self)
class Event(object):
"""
The event command provides a mechanism to fire a custom user event to
an entire datacenter. These events are opaque to Consul, but they can
be used to build scripting infrastructure to do automated deploys,
restart services, or perform any other orchestration action.
Unlike most Consul data, which is replicated using consensus, event
data is purely peer-to-peer over gossip.
This means it is not persisted and does not have a total ordering. In
practice, this means you cannot rely on the order of message delivery.
An advantage however is that events can still be used even in the
absence of server nodes or during an outage."""
def __init__(self, agent):
self.agent = agent
def fire(
self,
name,
body="",
node=None,
service=None,
tag=None,
token=None):
"""
Sends an event to Consul's gossip protocol.
*name* is the Consul-opaque name of the event. This can be filtered
on in calls to list, below
*body* is the Consul-opaque body to be delivered with the event.
From the Consul documentation:
The underlying gossip also sets limits on the size of a user
event message. It is hard to give an exact number, as it
depends on various parameters of the event, but the payload
should be kept very small (< 100 bytes). Specifying too large
of an event will return an error.
*node*, *service*, and *tag* are regular expressions which remote
agents will filter against to determine if they should store the
event
*token* is an optional `ACL token`_ to apply to this request. If
the token's policy is not allowed to fire an event of this *name*
an *ACLPermissionDenied* exception will be raised.
"""
assert not name.startswith('/'), \
'keys should not start with a forward slash'
params = []
if node is not None:
params.append(('node', node))
if service is not None:
params.append(('service', service))
if tag is not None:
params.append(('tag', tag))
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.put(
CB.json(),
'/v1/event/fire/%s' % name, params=params, data=body)
def list(
self,
name=None,
index=None,
wait=None):
"""
Returns a tuple of (*index*, *events*)
Note: Since Consul's event protocol uses gossip, there is no
ordering, and instead index maps to the newest event that
matches the query.
*name* is the type of events to list, if None, lists all available.
*index* is the current event Consul index, suitable for making
subsequent calls to wait for changes since this query was last run.
Check https://consul.io/docs/agent/http/event.html#event_list for
more infos about indexes on events.
*wait* the maximum duration to wait (e.g. '10s') to retrieve
a given index. This parameter is only applied if *index* is also
specified. the wait time by default is 5 minutes.
Consul agents only buffer the most recent entries. The current
buffer size is 256, but this value could change in the future.
Each *event* looks like this::
{
{
"ID": "b54fe110-7af5-cafc-d1fb-afc8ba432b1c",
"Name": "deploy",
"Payload": "1609030",
"NodeFilter": "",
"ServiceFilter": "",
"TagFilter": "",
"Version": 1,
"LTime": 19
},
}
"""
params = []
if name is not None:
params.append(('name', name))
if index:
params.append(('index', index))
if wait:
params['wait'] = wait
return self.agent.http.get(
CB.json(index=True, decode='Payload'),
'/v1/event/list', params=params)
class KV(object):
"""
The KV endpoint is used to expose a simple key/value store. This can be
used to store service configurations or other meta data in a simple
way.
"""
def __init__(self, agent):
self.agent = agent
def get(
self,
key,
index=None,
recurse=False,
wait=None,
token=None,
consistency=None,
keys=False,
separator=None,
dc=None):
"""
Returns a tuple of (*index*, *value[s]*)
*index* is the current Consul index, suitable for making subsequent
calls to wait for changes since this query was last run.
*wait* the maximum duration to wait (e.g. '10s') to retrieve
a given index. this parameter is only applied if *index* is also
specified. the wait time by default is 5 minutes.
*token* is an optional `ACL token`_ to apply to this request.
*keys* is a boolean which, if True, says to return a flat list of
keys without values or other metadata. *separator* can be used
with *keys* to list keys only up to a given separator character.
*dc* is the optional datacenter that you wish to communicate with.
If None is provided, defaults to the agent's datacenter.
The *value* returned is for the specified key, or if *recurse* is
True a list of *values* for all keys with the given prefix is
returned.
Each *value* looks like this::
{
"CreateIndex": 100,
"ModifyIndex": 200,
"LockIndex": 200,
"Key": "foo",
"Flags": 0,
"Value": "bar",
"Session": "adf4238a-882b-9ddc-4a9d-5b6758e4159e"
}
Note, if the requested key does not exists *(index, None)* is
returned. It's then possible to long poll on the index for when the
key is created.
"""
assert not key.startswith('/'), \
'keys should not start with a forward slash'
params = []
if index:
params.append(('index', index))
if wait:
params.append(('wait', wait))
if recurse:
params.append(('recurse', '1'))
token = token or self.agent.token
if token:
params.append(('token', token))
dc = dc or self.agent.dc
if dc:
params.append(('dc', dc))
if keys:
params.append(('keys', True))
if separator:
params.append(('separator', separator))
consistency = consistency or self.agent.consistency
if consistency in ('consistent', 'stale'):
params.append((consistency, '1'))
one = False
decode = False
if not keys:
decode = 'Value'
if not recurse and not keys:
one = True
return self.agent.http.get(
CB.json(index=True, decode=decode, one=one),
'/v1/kv/%s' % key,
params=params)
def put(
self,
key,
value,
cas=None,
flags=None,
acquire=None,
release=None,
token=None,
dc=None):
"""
Sets *key* to the given *value*.
*value* can either be None (useful for marking a key as a
directory) or any string type, including binary data (e.g. a
msgpack'd data structure)
The optional *cas* parameter is used to turn the PUT into a
Check-And-Set operation. This is very useful as it allows clients
to build more complex syncronization primitives on top. If the
index is 0, then Consul will only put the key if it does not
already exist. If the index is non-zero, then the key is only set
if the index matches the ModifyIndex of that key.
An optional *flags* can be set. This can be used to specify an
unsigned value between 0 and 2^64-1.
*acquire* is an optional session_id. if supplied a lock acquisition
will be attempted.
*release* is an optional session_id. if supplied a lock release
will be attempted.
*token* is an optional `ACL token`_ to apply to this request. If
the token's policy is not allowed to write to this key an
*ACLPermissionDenied* exception will be raised.
*dc* is the optional datacenter that you wish to communicate with.
If None is provided, defaults to the agent's datacenter.
The return value is simply either True or False. If False is
returned, then the update has not taken place.
"""
assert not key.startswith('/'), \
'keys should not start with a forward slash'
assert value is None or \
isinstance(value, (six.string_types, six.binary_type)), \
"value should be None or a string / binary data"
params = []
if cas is not None:
params.append(('cas', cas))
if flags is not None:
params.append(('flags', flags))
if acquire:
params.append(('acquire', acquire))
if release:
params.append(('release', release))
token = token or self.agent.token
if token:
params.append(('token', token))
dc = dc or self.agent.dc
if dc:
params.append(('dc', dc))
return self.agent.http.put(
CB.json(), '/v1/kv/%s' % key, params=params, data=value)
def delete(self, key, recurse=None, cas=None, token=None, dc=None):
"""
Deletes a single key or if *recurse* is True, all keys sharing a
prefix.
*cas* is an optional flag is used to turn the DELETE into a
Check-And-Set operation. This is very useful as a building block
for more complex synchronization primitives. Unlike PUT, the index
must be greater than 0 for Consul to take any action: a 0 index
will not delete the key. If the index is non-zero, the key is only
deleted if the index matches the ModifyIndex of that key.
*token* is an optional `ACL token`_ to apply to this request. If
the token's policy is not allowed to delete to this key an
*ACLPermissionDenied* exception will be raised.
*dc* is the optional datacenter that you wish to communicate with.
If None is provided, defaults to the agent's datacenter.
"""
assert not key.startswith('/'), \
'keys should not start with a forward slash'
params = []
if recurse:
params.append(('recurse', '1'))
if cas is not None:
params.append(('cas', cas))
token = token or self.agent.token
if token:
params.append(('token', token))
dc = dc or self.agent.dc
if dc:
params.append(('dc', dc))
return self.agent.http.delete(
CB.json(), '/v1/kv/%s' % key, params=params)
class Txn(object):
"""
The Transactions endpoints manage updates or fetches of multiple keys
inside a single, atomic transaction.
"""
def __init__(self, agent):
self.agent = agent
def put(self, payload):
"""
Create a transaction by submitting a list of operations to apply to
the KV store inside of a transaction. If any operation fails, the
transaction is rolled back and none of the changes are applied.
*payload* is a list of operations where each operation is a `dict`
with a single key value pair, with the key specifying operation the
type. An example payload of operation type "KV" is
dict::
{
"KV": {
"Verb": "<verb>",
"Key": "<key>",
"Value": "<Base64-encoded blob of data>",
"Flags": 0,
"Index": 0,
"Session": "<session id>"
}
}
"""
return self.agent.http.put(CB.json(), "/v1/txn",
data=json.dumps(payload))
class Agent(object):
"""
The Agent endpoints are used to interact with a local Consul agent.
Usually, services and checks are registered with an agent, which then
takes on the burden of registering with the Catalog and performing
anti-entropy to recover from outages.
"""
def __init__(self, agent):
self.agent = agent
self.service = Consul.Agent.Service(agent)
self.check = Consul.Agent.Check(agent)
def self(self):
"""
Returns configuration of the local agent and member information.
"""
return self.agent.http.get(CB.json(), '/v1/agent/self')
def services(self):
"""
Returns all the services that are registered with the local agent.
These services were either provided through configuration files, or
added dynamically using the HTTP API. It is important to note that
the services known by the agent may be different than those
reported by the Catalog. This is usually due to changes being made
while there is no leader elected. The agent performs active
anti-entropy, so in most situations everything will be in sync
within a few seconds.
"""
return self.agent.http.get(CB.json(), '/v1/agent/services')
def checks(self):
"""
Returns all the checks that are registered with the local agent.
These checks were either provided through configuration files, or
added dynamically using the HTTP API. Similar to services,
the checks known by the agent may be different than those
reported by the Catalog. This is usually due to changes being made
while there is no leader elected. The agent performs active
anti-entropy, so in most situations everything will be in sync
within a few seconds.
"""
return self.agent.http.get(CB.json(), '/v1/agent/checks')
def members(self, wan=False):
"""
Returns all the members that this agent currently sees. This may
vary by agent, use the nodes api of Catalog to retrieve a cluster
wide consistent view of members.
For agents running in server mode, setting *wan* to *True* returns
the list of WAN members instead of the LAN members which is
default.
"""
params = []
if wan:
params.append(('wan', 1))
return self.agent.http.get(
CB.json(), '/v1/agent/members', params=params)
def maintenance(self, enable, reason=None):
"""
The node maintenance endpoint can place the agent into
"maintenance mode".
*enable* is either 'true' or 'false'. 'true' enables maintenance
mode, 'false' disables maintenance mode.
*reason* is an optional string. This is simply to aid human
operators.
"""
params = []
params.append(('enable', enable))
if reason:
params.append(('reason', reason))
return self.agent.http.put(
CB.bool(), '/v1/agent/maintenance', params=params)
def join(self, address, wan=False):
"""
This endpoint instructs the agent to attempt to connect to a
given address.
*address* is the ip to connect to.
*wan* is either 'true' or 'false'. For agents running in server
mode, 'true' causes the agent to attempt to join using the WAN
pool. Default is 'false'.
"""
params = []
if wan:
params.append(('wan', 1))
return self.agent.http.get(
CB.bool(), '/v1/agent/join/%s' % address, params=params)
def force_leave(self, node):
"""
This endpoint instructs the agent to force a node into the left
state. If a node fails unexpectedly, then it will be in a failed
state. Once in the failed state, Consul will attempt to reconnect,
and the services and checks belonging to that node will not be
cleaned up. Forcing a node into the left state allows its old
entries to be removed.
*node* is the node to change state for.
"""
return self.agent.http.get(
CB.bool(), '/v1/agent/force-leave/%s' % node)
class Service(object):
def __init__(self, agent):
self.agent = agent
def register(
self,
name,
service_id=None,
address=None,
port=None,
tags=None,
check=None,
token=None,
# *deprecated* use check parameter
script=None,
interval=None,
ttl=None,
http=None,
timeout=None,
enable_tag_override=False):
"""
Add a new service to the local agent. There is more
documentation on services
`here <http://www.consul.io/docs/agent/services.html>`_.
*name* is the name of the service.
If the optional *service_id* is not provided it is set to
*name*. You cannot have duplicate *service_id* entries per
agent, so it may be necessary to provide one.
*address* will default to the address of the agent if not
provided.
An optional health *check* can be created for this service is
one of `Check.script`_, `Check.http`_, `Check.tcp`_,
`Check.ttl`_ or `Check.docker`_.
*token* is an optional `ACL token`_ to apply to this request.
Note this call will return successful even if the token doesn't
have permissions to register this service.
*script*, *interval*, *ttl*, *http*, and *timeout* arguments
are deprecated. use *check* instead.
*enable_tag_override* is an optional bool that enable you
to modify a service tags from servers(consul agent role server)
Default is set to False.
This option is only for >=v0.6.0 version on both agent and
servers.
for more information
https://www.consul.io/docs/agent/services.html
"""
payload = {}
payload['name'] = name
if enable_tag_override:
payload['enabletagoverride'] = enable_tag_override
if service_id:
payload['id'] = service_id
if address:
payload['address'] = address
if port:
payload['port'] = port
if tags:
payload['tags'] = tags
if check:
payload['check'] = check
else:
payload.update(Check._compat(
script=script,
interval=interval,
ttl=ttl,
http=http,
timeout=timeout))
params = []
token = token or self.agent.token
if token:
params.append(('token', token))
return self.agent.http.put(
CB.bool(),
'/v1/agent/service/register',
params=params,
data=json.dumps(payload))
def deregister(self, service_id):
"""
Used to remove a service from the local agent. The agent will
take care of deregistering the service with the Catalog. If
there is an associated check, that is also deregistered.
"""
return self.agent.http.put(
CB.bool(), '/v1/agent/service/deregister/%s' % service_id)
def maintenance(self, service_id, enable, reason=None):
"""
The service maintenance endpoint allows placing a given service
into "maintenance mode".
*service_id* is the id of the service that is to be targeted
for maintenance.
*enable* is either 'true' or 'false'. 'true' enables
maintenance mode, 'false' disables maintenance mode.
*reason* is an optional string. This is simply to aid human
operators.
"""
params = []
params.append(('enable', enable))
if reason:
params.append(('reason', reason))
return self.agent.http.put(
CB.bool(),
'/v1/agent/service/maintenance/{0}'.format(service_id),
params=params)
class Check(object):
def __init__(self, agent):
self.agent = agent
def register(
self,
name,
check=None,
check_id=None,
notes=None,
service_id=None,
token=None,
# *deprecated* use check parameter
script=None,
interval=None,
ttl=None,
http=None,
timeout=None):
"""
Register a new check with the local agent. More documentation
on checks can be found `here
<http://www.consul.io/docs/agent/checks.html>`_.
*name* is the name of the check.
*check* is one of `Check.script`_, `Check.http`_, `Check.tcp`_
`Check.ttl`_ or `Check.docker`_ and is required.
If the optional *check_id* is not provided it is set to *name*.
*check_id* must be unique for this agent.
*notes* is not used by Consul, and is meant to be human
readable.
Optionally, a *service_id* can be specified to associate a
registered check with an existing service.
*token* is an optional `ACL token`_ to apply to this request.
Note this call will return successful even if the token doesn't
have permissions to register this check.
*script*, *interval*, *ttl*, *http*, and *timeout* arguments
are deprecated. use *check* instead.
Returns *True* on success.
"""
payload = {'name': name}
assert check or script or ttl or http, \
'check is required'
if check:
payload.update(check)
else:
payload.update(Check._compat(
script=script,
interval=interval,
ttl=ttl,
http=http,
timeout=timeout)['check'])
if check_id:
payload['id'] = check_id
if notes:
payload['notes'] = notes
if service_id: