This repository has been archived by the owner on Dec 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 300
/
zdd.py
executable file
·806 lines (628 loc) · 27.9 KB
/
zdd.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
#!/usr/bin/env python3
from common import *
from datetime import datetime
from collections import namedtuple
import argparse
import json
import requests
import csv
import time
import math
import six.moves.urllib as urllib
import socket
import sys
import subprocess
from utils import *
from zdd_exceptions import *
import traceback
logger = logging.getLogger('zdd')
def query_yes_no(question, default="yes"):
# Thanks stackoverflow:
# https://stackoverflow.com/questions/3041986/python-command-line-yes-no-input
"""Ask a yes/no question via input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or None (meaning
an answer is required of the user).
The "answer" return value is True for "yes" or False for "no".
"""
valid = {"yes": True, "y": True, "ye": True,
"no": False, "n": False}
if default is None:
prompt = " [y/n] "
elif default == "yes":
prompt = " [Y/n] "
elif default == "no":
prompt = " [y/N] "
else:
raise ValueError("invalid default answer: '%s'" % default)
while True:
sys.stdout.write(question + prompt)
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
sys.stdout.write("Please respond with 'yes' or 'no' "
"(or 'y' or 'n').\n")
def marathon_get_request(args, path):
url = args.marathon + path
try:
response = requests.get(url, auth=get_marathon_auth_params(args))
response.raise_for_status()
except requests.exceptions.RequestException:
raise MarathonEndpointException(
"Error while querying marathon", url, traceback.format_exc())
return response
def list_marathon_apps(args):
response = marathon_get_request(args, "/v2/apps")
return response.json()['apps']
def fetch_marathon_app(args, app_id):
response = marathon_get_request(args, "/v2/apps" + app_id)
return response.json()['app']
def _get_alias_records(hostname):
"""Return all IPv4 A records for a given hostname
"""
return socket.gethostbyname_ex(hostname)[2]
def _unparse_url_alias(url, addr):
"""Reassemble a url object into a string but with a new address
"""
return urllib.parse.urlunparse((url[0],
addr + ":" + str(url.port),
url[2],
url[3],
url[4],
url[5]))
def get_marathon_lb_urls(args):
"""Return a list of urls for all Aliases of the
marathon_lb url passed in as an argument
"""
url = urllib.parse.urlparse(args.marathon_lb)
addrs = _get_alias_records(url.hostname)
return [_unparse_url_alias(url, addr) for addr in addrs]
def fetch_haproxy_pids(haproxy_url):
try:
response = requests.get(haproxy_url + "/_haproxy_getpids")
response.raise_for_status()
except requests.exceptions.RequestException:
logger.exception("Caught exception when retrieving HAProxy"
" pids from " + haproxy_url)
raise
return response.text.split()
def check_haproxy_reloading(haproxy_url):
"""Return False if haproxy has only one pid, it is not reloading.
Return True if we catch an exception while making a request to
haproxy or if more than one pid is returned
"""
try:
pids = fetch_haproxy_pids(haproxy_url)
except requests.exceptions.RequestException:
# Assume reloading on any error, this should be caught with a timeout
return True
if len(pids) > 1:
logger.info("Waiting for {} pids on {}".format(len(pids), haproxy_url))
return True
return False
def any_marathon_lb_reloading(marathon_lb_urls):
return any([check_haproxy_reloading(url) for url in marathon_lb_urls])
def fetch_haproxy_stats(haproxy_url):
try:
response = requests.get(haproxy_url + "/haproxy?stats;csv")
response.raise_for_status()
except requests.exceptions.RequestException:
logger.exception("Caught exception when retrieving HAProxy"
" stats from " + haproxy_url)
raise
return response.text
def fetch_combined_haproxy_stats(marathon_lb_urls):
raw = ''.join([fetch_haproxy_stats(url) for url in marathon_lb_urls])
return parse_haproxy_stats(raw)
def parse_haproxy_stats(csv_data):
rows = csv_data.splitlines()
headings = rows.pop(0).lstrip('# ').rstrip(',\n').split(',')
csv_reader = csv.reader(rows, delimiter=',', quotechar="'")
Row = namedtuple('Row', headings)
return [Row(*row[0:-1]) for row in csv_reader if row[0][0] != '#']
def get_deployment_label(app):
return get_deployment_group(app) + "_" + app['labels']['HAPROXY_0_PORT']
def _if_app_listener(app, listener):
return (listener.pxname == get_deployment_label(app) and
listener.svname not in ['BACKEND', 'FRONTEND'])
def fetch_app_listeners(app, marathon_lb_urls):
haproxy_stats = fetch_combined_haproxy_stats(marathon_lb_urls)
return [l for l in haproxy_stats if _if_app_listener(app, l)]
def waiting_for_listeners(new_app, old_app, listeners, haproxy_count):
listener_count = (len(listeners) / haproxy_count)
return listener_count != new_app['instances'] + old_app['instances']
def get_deployment_target(app):
return int(app['labels']['HAPROXY_DEPLOYMENT_TARGET_INSTANCES'])
def get_new_instance_count(app):
if 'HAPROXY_DEPLOYMENT_NEW_INSTANCES' in app['labels']:
return int(app['labels']['HAPROXY_DEPLOYMENT_NEW_INSTANCES'])
else:
return 0
def waiting_for_up_listeners(app, listeners, haproxy_count):
up_listeners = [l for l in listeners if l.status == 'UP']
up_listener_count = (len(up_listeners) / haproxy_count)
return up_listener_count < get_deployment_target(app)
def select_draining_listeners(listeners):
return [l for l in listeners if l.status == 'MAINT']
def select_drained_listeners(listeners):
draining_listeners = select_draining_listeners(listeners)
return [l for l in draining_listeners if not _has_pending_requests(l)]
def get_svnames_from_task(app, task):
prefix = task['host'].replace('.', '_')
task_ip, task_port = get_task_ip_and_ports(app, task)
if task['host'] == task_ip:
for port in task['ports']:
yield('{}_{}'.format(prefix, port))
else:
for port in task['ports']:
yield('{}_{}_{}'.format(prefix, task_ip.replace('.', '_'), port))
def get_svnames_from_tasks(app, tasks):
svnames = []
for task in tasks:
svnames += get_svnames_from_task(app, task)
return svnames
def _has_pending_requests(listener):
return int(listener.qcur or 0) > 0 or int(listener.scur or 0) > 0
def is_hybrid_deployment(args, app):
if (get_new_instance_count(app) != 0 and not args.complete_cur and
not args.complete_prev):
return True
else:
return False
def find_drained_task_ids(app, listeners, haproxy_count):
"""Return app tasks which have all haproxy listeners down and draining
of any pending sessions or connections
"""
tasks = zip(get_svnames_from_tasks(app, app['tasks']), app['tasks'])
drained_listeners = select_drained_listeners(listeners)
drained_task_ids = []
for svname, task in tasks:
task_listeners = [l for l in drained_listeners if l.svname == svname]
if len(task_listeners) == haproxy_count:
drained_task_ids.append(task['id'])
return drained_task_ids
def find_draining_task_ids(app, listeners, haproxy_count):
"""Return app tasks which have all haproxy listeners draining
"""
tasks = zip(get_svnames_from_tasks(app, app['tasks']), app['tasks'])
draining_listeners = select_draining_listeners(listeners)
draining_task_ids = []
for svname, task in tasks:
task_listeners = [l for l in draining_listeners if l.svname == svname]
if len(task_listeners) == haproxy_count:
draining_task_ids.append(task['id'])
return draining_task_ids
def max_wait_not_exceeded(max_wait, timestamp):
return (time.time() - timestamp < max_wait)
def find_tasks_to_kill(args, new_app, old_app, timestamp):
marathon_lb_urls = get_marathon_lb_urls(args)
haproxy_count = len(marathon_lb_urls)
try:
listeners = fetch_app_listeners(new_app, marathon_lb_urls)
except requests.exceptions.RequestException:
raise MarathonLbEndpointException(
"Error while querying Marathon-LB",
marathon_lb_urls,
traceback.format_exc())
while max_wait_not_exceeded(args.max_wait, timestamp):
time.sleep(args.step_delay)
logger.info("Existing app running {} instances, "
"new app running {} instances"
.format(old_app['instances'], new_app['instances']))
if any_marathon_lb_reloading(marathon_lb_urls):
continue
try:
listeners = fetch_app_listeners(new_app, marathon_lb_urls)
except requests.exceptions.RequestException:
# Restart loop if we hit an exception while loading listeners,
# this may be normal behaviour
continue
logger.info("Found {} app listeners across {} HAProxy instances"
.format(len(listeners), haproxy_count))
if waiting_for_listeners(new_app, old_app, listeners, haproxy_count):
continue
if waiting_for_up_listeners(new_app, listeners, haproxy_count):
continue
if waiting_for_drained_listeners(listeners):
continue
return find_drained_task_ids(old_app, listeners, haproxy_count)
logger.info('Timed out waiting for tasks to fully drain, find any draining'
' tasks and continue with deployment...')
return find_draining_task_ids(old_app, listeners, haproxy_count)
def deployment_in_progress(app):
return len(app['deployments']) > 0
def execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app):
if args.pre_kill_hook is not None:
logger.info("Calling pre-kill hook '{}'".format(args.pre_kill_hook))
subprocess.check_call([args.pre_kill_hook,
json.dumps(old_app),
json.dumps(tasks_to_kill),
json.dumps(new_app)])
def swap_zdd_apps(args, new_app, old_app):
old_app = fetch_marathon_app(args, old_app['id'])
new_app = fetch_marathon_app(args, new_app['id'])
if deployment_in_progress(new_app):
time.sleep(args.step_delay)
return swap_zdd_apps(args, new_app, old_app)
tasks_to_kill = find_tasks_to_kill(args, new_app, old_app, time.time())
if ready_to_delete_old_app(args, new_app, old_app, tasks_to_kill):
return safe_delete_app(args, old_app, new_app)
if len(tasks_to_kill) > 0:
execute_pre_kill_hook(args, old_app, tasks_to_kill, new_app)
logger.info("There are {} draining listeners, "
"about to kill the following tasks:\n - {}"
.format(len(tasks_to_kill),
"\n - ".join(tasks_to_kill)))
if args.force or query_yes_no("Continue?"):
logger.info("Scaling down old app by {} instances"
.format(len(tasks_to_kill)))
kill_marathon_tasks(args, tasks_to_kill)
else:
return False
if is_hybrid_deployment(args, new_app):
if new_app['instances'] < get_new_instance_count(new_app):
scale_new_app_instances(args, new_app, old_app)
else:
if new_app['instances'] < get_deployment_target(new_app):
scale_new_app_instances(args, new_app, old_app)
return swap_zdd_apps(args, new_app, old_app)
def ready_to_delete_old_app(args, new_app, old_app, draining_task_ids):
new_instances = get_new_instance_count(new_app)
if is_hybrid_deployment(args, new_app):
return (int(new_app['instances']) == new_instances and
int(old_app['instances']) == (
get_deployment_target(old_app) - new_instances))
else:
return (int(new_app['instances']) == get_deployment_target(new_app) and
len(draining_task_ids) == int(old_app['instances']))
def waiting_for_drained_listeners(listeners):
return len(select_drained_listeners(listeners)) < 1
def scale_new_app_instances(args, new_app, old_app):
"""Scale the app by 50% of its existing instances until we
meet or surpass instances deployed for old_app.
At which point go right to the new_app deployment target
"""
instances = (math.floor(new_app['instances'] +
(new_app['instances'] + 1) / 2))
if is_hybrid_deployment(args, new_app):
if instances > get_new_instance_count(new_app):
instances = get_new_instance_count(new_app)
else:
if instances >= old_app['instances']:
instances = get_deployment_target(new_app)
logger.info("Scaling new app up to {} instances".format(instances))
return scale_marathon_app_instances(args, new_app, instances)
def safe_delete_app(args, app, new_app):
if is_hybrid_deployment(args, new_app):
logger.info("Not deleting old app, as its hybrid configuration")
return True
else:
logger.info("About to delete old app {}".format(app['id']))
if args.force or query_yes_no("Continue?"):
delete_marathon_app(args, app)
return True
else:
return False
def delete_marathon_app(args, app):
url = args.marathon + '/v2/apps' + app['id']
try:
response = requests.delete(url,
auth=get_marathon_auth_params(args))
response.raise_for_status()
except requests.exceptions.RequestException:
raise AppDeleteException(
"Error while deleting the app", url, traceback.format_exc())
return response
def kill_marathon_tasks(args, ids):
data = json.dumps({'ids': ids})
url = args.marathon + "/v2/tasks/delete?scale=true"
headers = {'Content-Type': 'application/json'}
try:
response = requests.post(url, headers=headers, data=data,
auth=get_marathon_auth_params(args))
response.raise_for_status()
except requests.exceptions.RequestException:
# This is App Scale Down, so raising AppScale Exception
raise AppScaleException(
"Error while scaling the app", url, data, traceback.format_exc())
return response
def scale_marathon_app_instances(args, app, instances):
url = args.marathon + "/v2/apps" + app['id']
data = json.dumps({'instances': instances})
headers = {'Content-Type': 'application/json'}
try:
response = requests.put(url, headers=headers, data=data,
auth=get_marathon_auth_params(args))
response.raise_for_status()
except requests.exceptions.RequestException:
# This is App Scale Up, so raising AppScale Exception
raise AppScaleException(
"Error while scaling the app", url, data, traceback.format_exc())
return response
def deploy_marathon_app(args, app):
url = args.marathon + "/v2/apps"
data = json.dumps(app)
headers = {'Content-Type': 'application/json'}
try:
response = requests.post(url, headers=headers, data=data,
auth=get_marathon_auth_params(args))
response.raise_for_status()
except requests.exceptions.RequestException:
raise AppCreateException(
"Error while creating the app", url, data, traceback.format_exc())
return response
def get_service_port(app):
try:
return \
int(app['container']['docker']['portMappings'][0]['servicePort'])
except KeyError:
return int(app['ports'][0])
def set_service_port(app, servicePort):
try:
app['container']['docker']['portMappings'][0]['servicePort'] = \
int(servicePort)
except KeyError:
app['ports'][0] = int(servicePort)
return app
def validate_app(app):
if app['id'] is None:
raise MissingFieldException("App doesn't contain a valid App ID",
'id')
if 'labels' not in app:
raise MissingFieldException("No labels found. Please define the"
" HAPROXY_DEPLOYMENT_GROUP label",
'label')
if 'HAPROXY_DEPLOYMENT_GROUP' not in app['labels']:
raise MissingFieldException("Please define the "
"HAPROXY_DEPLOYMENT_GROUP label",
'HAPROXY_DEPLOYMENT_GROUP')
if 'HAPROXY_DEPLOYMENT_ALT_PORT' not in app['labels']:
raise MissingFieldException("Please define the "
"HAPROXY_DEPLOYMENT_ALT_PORT label",
'HAPROXY_DEPLOYMENT_ALT_PORT')
def set_app_ids(app, colour):
app['labels']['HAPROXY_APP_ID'] = app['id']
app['id'] = app['id'] + '-' + colour
if app['id'][0] != '/':
app['id'] = '/' + app['id']
return app
def set_service_ports(app, servicePort):
app['labels']['HAPROXY_0_PORT'] = str(get_service_port(app))
try:
app['container']['docker']['portMappings'][0]['servicePort'] = \
int(servicePort)
return app
except KeyError:
app['ports'][0] = int(servicePort)
return app
def select_next_port(app):
alt_port = int(app['labels']['HAPROXY_DEPLOYMENT_ALT_PORT'])
if int(app['ports'][0]) == alt_port:
return int(app['labels']['HAPROXY_0_PORT'])
else:
return alt_port
def select_next_colour(app):
if app['labels'].get('HAPROXY_DEPLOYMENT_COLOUR') == 'blue':
return 'green'
else:
return 'blue'
def sort_deploys(apps):
return sorted(apps, key=lambda a: a.get('labels', {})
.get('HAPROXY_DEPLOYMENT_STARTED_AT', '0'))
def select_last_deploy(apps):
return sort_deploys(apps).pop()
def select_last_two_deploys(apps):
return sort_deploys(apps)[:-3:-1]
def get_deployment_group(app):
return app.get('labels', {}).get('HAPROXY_DEPLOYMENT_GROUP')
def fetch_previous_deploys(args, app):
apps = list_marathon_apps(args)
app_deployment_group = get_deployment_group(app)
return [a for a in apps if get_deployment_group(a) == app_deployment_group]
def prepare_deploy(args, previous_deploys, app):
""" Return a blue or a green version of `app` based on prexisting deploys
"""
if len(previous_deploys) > 0:
last_deploy = select_last_deploy(previous_deploys)
next_colour = select_next_colour(last_deploy)
next_port = select_next_port(last_deploy)
deployment_target_instances = last_deploy['instances']
if args.new_instances > deployment_target_instances:
args.new_instances = deployment_target_instances
if args.new_instances and args.new_instances > 0:
if args.initial_instances > args.new_instances:
app['instances'] = args.new_instances
else:
app['instances'] = args.initial_instances
else:
if args.initial_instances > deployment_target_instances:
app['instances'] = deployment_target_instances
else:
app['instances'] = args.initial_instances
app['labels']['HAPROXY_DEPLOYMENT_NEW_INSTANCES'] = str(
args.new_instances)
else:
next_colour = 'blue'
next_port = get_service_port(app)
deployment_target_instances = app['instances']
app['labels']['HAPROXY_DEPLOYMENT_NEW_INSTANCES'] = "0"
app = set_app_ids(app, next_colour)
app = set_service_ports(app, next_port)
app['labels']['HAPROXY_DEPLOYMENT_TARGET_INSTANCES'] = \
str(deployment_target_instances)
app['labels']['HAPROXY_DEPLOYMENT_COLOUR'] = next_colour
app['labels']['HAPROXY_DEPLOYMENT_STARTED_AT'] = datetime.now().isoformat()
return app
def load_app_json(args):
with open(args.json) as content_file:
return json.load(content_file)
def safe_resume_deploy(args, previous_deploys):
if args.complete_cur:
logger.info("Coverting all instances to current config")
new_app, old_app = select_last_two_deploys(previous_deploys)
logger.info("Current config color is %s" % new_app[
'labels']['HAPROXY_DEPLOYMENT_COLOUR'])
logger.info("Considering %s color as existing app"
% old_app['labels']['HAPROXY_DEPLOYMENT_COLOUR'] +
" and %s color as new app"
% new_app['labels']['HAPROXY_DEPLOYMENT_COLOUR'])
return swap_zdd_apps(args, new_app, old_app)
elif args.complete_prev:
logger.info("Coverting all instances to previous config")
old_app, new_app = select_last_two_deploys(previous_deploys)
logger.info("Previous config color is %s" % new_app[
'labels']['HAPROXY_DEPLOYMENT_COLOUR'])
logger.info("Considering %s color as existing app"
% old_app['labels']['HAPROXY_DEPLOYMENT_COLOUR'] +
" and %s color as new app"
% new_app['labels']['HAPROXY_DEPLOYMENT_COLOUR'])
return swap_zdd_apps(args, new_app, old_app)
elif args.resume:
logger.info("Found previous deployment, resuming")
new_app, old_app = select_last_two_deploys(previous_deploys)
return swap_zdd_apps(args, new_app, old_app)
else:
raise Exception("There appears to be an"
" existing deployment in progress")
def do_zdd(args, out=sys.stdout):
app = load_app_json(args)
validate_app(app)
previous_deploys = fetch_previous_deploys(args, app)
if len(previous_deploys) > 1:
# There is a stuck deploy or hybrid deploy
return safe_resume_deploy(args, previous_deploys)
if args.complete_cur or args.complete_prev:
raise InvalidArgException("Cannot use --complete-cur, --complete-prev"
" flags when config is not hybrid")
new_app = prepare_deploy(args, previous_deploys, app)
logger.info('Final app definition:')
out.write(json.dumps(new_app, sort_keys=True, indent=2))
out.write("\n")
if args.dry_run:
return True
if args.force or query_yes_no("Continue with deployment?"):
deploy_marathon_app(args, new_app)
if len(previous_deploys) == 0:
# This was the first deploy, nothing to swap
return True
else:
# This is a standard blue/green deploy, swap new app with old
old_app = select_last_deploy(previous_deploys)
return swap_zdd_apps(args, new_app, old_app)
def get_arg_parser():
parser = argparse.ArgumentParser(
description="Zero-downtime deployment orchestrator for marathon-lb",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--longhelp",
help="Print out configuration details",
action="store_true"
)
parser.add_argument("--marathon", "-m",
help="[required] Marathon endpoint, eg. -m " +
"http://marathon1:8080"
)
parser.add_argument("--marathon-lb", "-l",
help="[required] Marathon-lb stats endpoint, eg. -l " +
"http://marathon-lb.marathon.mesos:9090"
)
parser.add_argument("--json", "-j",
help="[required] App JSON"
)
parser.add_argument("--dry-run", "-d",
help="Perform a dry run",
action="store_true"
)
parser.add_argument("--force", "-f",
help="Perform deployment un-prompted",
action="store_true"
)
parser.add_argument("--step-delay", "-s",
help="Delay (in seconds) between each successive"
" deployment step",
type=int, default=5
)
parser.add_argument("--initial-instances", "-i",
help="Initial number of app instances to launch."
" If this number is greater than total number of"
" existing instances, then this will be overridden"
" by the latter number",
type=int, default=1
)
parser.add_argument("--resume", "-r",
help="Resume from a previous deployment",
action="store_true"
)
parser.add_argument("--max-wait", "-w",
help="Maximum amount of time (in seconds) to wait"
" for HAProxy to drain connections",
type=int, default=300
)
parser.add_argument("--new-instances", "-n",
help="Number of new instances to replace the existing"
" instances. This is for having instances of both blue"
" and green at the same time",
type=int, default=0)
parser.add_argument("--complete-cur", "-c",
help="Change hybrid app entirely to"
" current (new) app's instances", action="store_true")
parser.add_argument("--complete-prev", "-p",
help="Change hybrid app entirely to"
" previous (old) app's instances", action="store_true")
parser.add_argument("--pre-kill-hook",
help="A path to an executable (such as a script) "
"which will be called before killing any tasks marked "
"for draining at each step. The script will be called "
"with 3 arguments (in JSON): the old app definition, "
"the list of tasks which will be killed, "
"and the new app definition. An exit "
"code of 0 indicates the deploy may continue. "
"If the hook returns a non-zero exit code, the deploy "
"will stop, and an operator must intervene."
)
parser = set_logging_args(parser)
parser = set_marathon_auth_args(parser)
return parser
def set_request_retries():
s = requests.Session()
a = requests.adapters.HTTPAdapter(max_retries=3)
s.mount('http://', a)
def process_arguments():
# Process arguments
arg_parser = get_arg_parser()
args = arg_parser.parse_args()
if args.longhelp:
print(__doc__)
sys.exit()
# otherwise make sure that a Marathon URL was specified
else:
if args.marathon is None:
arg_parser.error('argument --marathon/-m is required')
if args.marathon_lb is None:
arg_parser.error('argument --marathon-lb/-l is required')
if args.json is None:
arg_parser.error('argument --json/-j is required')
return args
if __name__ == '__main__':
args = process_arguments()
set_request_retries()
setup_logging(logger, args.syslog_socket, args.log_format, args.log_level)
try:
if do_zdd(args):
sys.exit(0)
else:
sys.exit(1)
except Exception as e:
if hasattr(e, 'zdd_exit_status'):
if hasattr(e, 'error'):
logger.exception(str(e.error))
else:
logger.exception(traceback.print_exc())
sys.exit(e.zdd_exit_status)
else:
# For Unknown Exceptions
logger.exception(traceback.print_exc())
sys.exit(2)