forked from mesosphere/marathon-lb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
marathon_lb.py
executable file
·2239 lines (1986 loc) · 91.9 KB
/
marathon_lb.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
#!/usr/bin/env python3
"""# marathon-lb
### Overview
The marathon-lb is a service discovery and load balancing tool
for Marathon based on HAProxy. It reads the Marathon task information
and dynamically generates HAProxy configuration details.
To gather the task information, marathon-lb needs to know where
to find Marathon. The service configuration details are stored in labels.
Every service port in Marathon can be configured independently.
### Configuration
Service configuration lives in Marathon via labels.
Marathon-lb just needs to know where to find Marathon.
### Command Line Usage
"""
import argparse
import hashlib
import json
import logging
import os
import os.path
import random
import re
import shlex
import signal
import stat
import subprocess
import sys
import threading
import time
import datetime
from itertools import cycle
from collections import defaultdict
from operator import attrgetter
from shutil import move, copy
from tempfile import mkstemp
import dateutil.parser
import requests
import pycurl
from common import (get_marathon_auth_params, set_logging_args,
set_marathon_auth_args, setup_logging, cleanup_json)
from config import ConfigTemplater, label_keys
from lrucache import LRUCache
from utils import (CurlHttpEventStream, get_task_ip_and_ports, ip_cache,
ServicePortAssigner)
logger = logging.getLogger('marathon_lb')
SERVICE_PORT_ASSIGNER = ServicePortAssigner()
class MarathonBackend(object):
def __init__(self, host, ip, port, draining):
self.host = host
"""
The host that is running this task.
"""
self.ip = ip
"""
The IP address used to access the task. For tasks using IP-per-task,
this is the actual IP address of the task; otherwise, it is the IP
address resolved from the hostname.
"""
self.port = port
"""
The port used to access a particular service on a task. For tasks
using IP-per-task, this is the actual port exposed by the task;
otherwise, it is the port exposed on the host.
"""
self.draining = draining
"""
Whether we should be draining access to this task in the LB.
"""
def __hash__(self):
return hash((self.host, self.port))
def __repr__(self):
return "MarathonBackend(%r, %r, %r)" % (self.host, self.ip, self.port)
class MarathonService(object):
def __init__(self, appId, servicePort, healthCheck, strictMode):
self.appId = appId
self.servicePort = servicePort
self.backends = set()
self.hostname = None
self.proxypath = None
self.revproxypath = None
self.redirpath = None
self.haproxy_groups = frozenset()
self.path = None
self.authRealm = None
self.authUser = None
self.authPasswd = None
self.sticky = False
self.enabled = not strictMode
self.redirectHttpToHttps = False
self.useHsts = False
self.sslCert = None
self.bindOptions = None
self.bindAddr = '*'
self.groups = frozenset()
self.mode = None
self.balance = 'roundrobin'
self.healthCheck = healthCheck
self.labels = {}
self.backend_weight = 0
self.network_allowed = None
self.healthcheck_port_index = None
if healthCheck:
if healthCheck['protocol'] == 'HTTP':
self.mode = 'http'
def add_backend(self, host, ip, port, draining):
self.backends.add(MarathonBackend(host, ip, port, draining))
def __hash__(self):
return hash(self.servicePort)
def __eq__(self, other):
return self.servicePort == other.servicePort
def __repr__(self):
return "MarathonService(%r, %r)" % (self.appId, self.servicePort)
class MarathonApp(object):
def __init__(self, marathon, appId, app):
self.app = app
self.groups = frozenset()
self.appId = appId
# port -> MarathonService
self.services = dict()
def __hash__(self):
return hash(self.appId)
def __eq__(self, other):
return self.appId == other.appId
class Marathon(object):
def __init__(self, hosts, health_check, strict_mode, auth, ca_cert=None):
# TODO(cmaloney): Support getting master list from zookeeper
self.__hosts = hosts
self.__health_check = health_check
self.__strict_mode = strict_mode
self.__auth = auth
self.__cycle_hosts = cycle(self.__hosts)
self.__verify = False
if ca_cert:
self.__verify = ca_cert
def api_req_raw(self, method, path, auth, body=None, **kwargs):
for host in self.__hosts:
path_str = os.path.join(host, 'v2')
for path_elem in path:
path_str = path_str + "/" + path_elem
response = requests.request(
method,
path_str,
auth=auth,
headers={
'Accept': 'application/json',
'Content-Type': 'application/json'
},
timeout=(3.05, 46),
**kwargs
)
logger.debug("%s %s", method, response.url)
if response.status_code == 200:
break
response.raise_for_status()
resp_json = cleanup_json(response.json())
if 'message' in resp_json:
response.reason = "%s (%s)" % (
response.reason,
resp_json['message'])
return response
def api_req(self, method, path, **kwargs):
data = self.api_req_raw(method, path, self.__auth,
verify=self.__verify, **kwargs).json()
return cleanup_json(data)
def create(self, app_json):
return self.api_req('POST', ['apps'], app_json)
def get_app(self, appid):
logger.info('fetching app %s', appid)
return self.api_req('GET', ['apps', appid])["app"]
# Lists all running apps.
def list(self):
logger.info('fetching apps')
return self.api_req('GET', ['apps'],
params={'embed': 'apps.tasks'})["apps"]
def health_check(self):
return self.__health_check
def strict_mode(self):
return self.__strict_mode
def tasks(self):
logger.info('fetching tasks')
return self.api_req('GET', ['tasks'])["tasks"]
def get_event_stream(self):
url = self.host + "/v2/events?plan-format=light&" + \
"event_type=status_update_event&" + \
"event_type=health_status_changed_event&" + \
"event_type=api_post_event"
return CurlHttpEventStream(url, self.__auth, self.__verify)
def iter_events(self, stream):
logger.info(
"SSE Active, trying fetch events from {0}".format(stream.url))
class Event(object):
def __init__(self, data):
self.data = data
for line in stream.iter_lines():
if line.strip() != '':
for real_event_data in re.split(r'\r\n',
line.decode('utf-8')):
if real_event_data[:6] == "data: ":
event = Event(data=real_event_data[6:])
yield event
@property
def host(self):
return next(self.__cycle_hosts)
def has_group(groups, app_groups):
# All groups / wildcard match
if '*' in groups:
return True
# empty group only
if len(groups) == 0 and len(app_groups) == 0:
raise Exception("No groups specified")
# Contains matching groups
if (len(frozenset(app_groups) & groups)):
return True
return False
def get_backend_port(apps, app, idx):
"""
Return the port of the idx-th backend of the app which index in apps
is defined by app.healthcheck_port_index.
Example case:
We define an app mapping two ports: 9000 and 9001, that we
scaled to 3 instances.
The port 9000 is used for the app itself, and the port 9001
is used for the app healthchecks. Hence, we have 2 apps
at the marathon level, each with 3 backends (one for each
container).
If app.healthcheck_port_index is set to 1 (via the
HAPROXY_0_BACKEND_HEALTHCHECK_PORT_INDEX label), then
get_backend_port(apps, app, 3) will return the port of the 3rd
backend of the second app.
See https://github.com/mesosphere/marathon-lb/issues/198 for the
actual use case.
Note: if app.healthcheck_port_index has a out of bounds value,
then the app idx-th backend is returned instead.
"""
def get_backends(app):
key_func = attrgetter('host', 'port')
return sorted(list(app.backends), key=key_func)
apps = [_app for _app in apps if _app.appId == app.appId]
# If no healthcheck port index is defined, or if its value is nonsense
# simply return the app port
if app.healthcheck_port_index is None \
or abs(app.healthcheck_port_index) > len(apps):
return get_backends(app)[idx].port
# If a healthcheck port index is defined, fetch the app corresponding
# to the argument app healthcheck port index,
# and return its idx-th backend port
apps = sorted(apps, key=attrgetter('appId', 'servicePort'))
backends = get_backends(apps[app.healthcheck_port_index])
return backends[idx].port
def _get_health_check_options(template, health_check, health_check_port):
return template.format(
healthCheck=health_check,
healthCheckPortIndex=health_check.get('portIndex'),
healthCheckPort=health_check_port,
healthCheckProtocol=health_check['protocol'],
healthCheckPath=health_check.get('path', '/'),
healthCheckTimeoutSeconds=health_check['timeoutSeconds'],
healthCheckIntervalSeconds=health_check['intervalSeconds'],
healthCheckGracePeriodSeconds=health_check['gracePeriodSeconds'],
healthCheckMaxConsecutiveFailures=health_check[
'maxConsecutiveFailures'],
healthCheckFalls=health_check['maxConsecutiveFailures'] + 1,
healthCheckPortOptions=' port ' + str(
health_check_port) if health_check_port else ''
)
def mergeVhostTable(left, right):
result = left.copy()
for key in right:
if key in result:
result[key][0].extend(right[key][0])
result[key][1].update(right[key][1])
result[key][2].update(right[key][2])
else:
result[key] = right[key]
return result
def calculate_server_id(server_name, taken_server_ids):
"""Calculate a stable server id given server name
Calculates stable server id [1] for the given server name [2]
which has following properties:
* is unique/has not been assigned yet
* is an integer from the range 1-32767
* is stable - i.e. calling this function repeatably with the same
server name must yield the same server id.
THE STABILITY OF SERVER_ID IS GUARANTEED IF THE ORDER OF CALLS OF THIS
FUNCTION IS PRESERVED, I.E. THE BACKEND LIST IS SORTED BEFORE
PROCESSING
[1] http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#5.2-id
[2] http://cbonte.github.io/haproxy-dconv/1.8/configuration.html#5.2
Args:
server_name(str): the name of the given backend server
taken_server_ids(set): list of allready assigned server ids
Returns:
An integer depicting the server ID
"""
if server_name == '' or server_name is None:
raise ValueError("Malformed server name: {}".format(server_name))
server_name_encoded = server_name.encode('utf-8')
server_name_shasum = hashlib.sha256(server_name_encoded).hexdigest()
# The number 32767 is not coincidental. It is very important to notice
# in [1] that:
# * due to the use of atol() call [2], server id must not exceed the length
# of 'long int' on a given platform. According to [3] it is at
# least 32bits long so 32bits is a safe limit.
# * the atol() call returns `long int` which is assigned to puid var which
# int turn is `int`. As per [4]:
#
# ```
# On a system where long is wider than int, if the value won't fit in an
# int, then the result of the conversion is implementation-defined. (Or,
# starting in C99, it can raise an implementation-defined signal, but I
# don't know of any compilers that actually do that.) What typically
# happens is that the high-order bits are discarded, but you shouldn't
# depend on that. (The rules are different for unsigned types; the result
# of converting a signed or unsigned integer to an unsigned type is well
# defined.)
# ```
#
# So we need to assume that server id is 16 bit signed integer. Server id
# must be a positive number so this gives us at most 2**15-1 = 32767
# possible server IDs. Beyond that there are dragons and the undefined
# behaviour of the C compiler ;)
#
# [1] https://github.com/haproxy/haproxy/blob/c55b88ece616afe0b28dc81eb39bad37b5f9c33f/src/server.c#L359-L388 # noqa: E501
# [2] https://github.com/haproxy/haproxy/blob/c55b88ece616afe0b28dc81eb39bad37b5f9c33f/src/server.c#L368 # noqa: E501
# [3] https://en.wikipedia.org/wiki/C_data_types
# [4] https://stackoverflow.com/a/13652624
server_id = int(server_name_shasum, 16) % 32767
if server_id not in taken_server_ids and server_id > 0:
taken_server_ids.add(server_id)
return server_id
# We try to solve the collisions by recursively calling
# calculate_backend_id() with the server name argument set to the initial
# server name plus the calculated `server_name_shasum` appended to it.
# This way we should get stable IDs during the next haproxy
# reconfiguration. The more backends there are the more likely the
# collisions will get. Initially the probability is 1/(2**15-1) * 100 =
# 0.003%. As the new_server_id gets longer the sha sum calculation will be
# getting more CPU-heavy and the number of SHA sum calculations per backend
# server will increase. Still - it is unlikely that we will hit the number
# backend server that will this approach a problem - the number of backend
# servers would need to be in the order of thousands.
new_server_name = "{0} {1}".format(server_name, server_name_shasum)
if server_id == 0:
msg_fmt = ("server id == 0 for `%s`, retrying with `%s`")
logger.info(msg_fmt, server_name, new_server_name)
else:
msg_fmt = ("server id collision for `%s`: `%d` was already assigned, "
"retrying with `%s`")
logger.info(msg_fmt, server_name, server_id, new_server_name)
return calculate_server_id(new_server_name, taken_server_ids)
def config(apps, groups, bind_http_https, ssl_certs, templater,
haproxy_map=False, domain_map_array=[], app_map_array=[],
config_file="/etc/haproxy/haproxy.cfg",
group_https_by_vhosts=False):
logger.info("generating config")
config = templater.haproxy_head
groups = frozenset(groups)
duplicate_map = {}
# do not repeat use backend multiple times since map file is same.
_ssl_certs = ssl_certs or "/etc/ssl/cert.pem"
_ssl_certs = _ssl_certs.split(",")
if bind_http_https:
http_frontends = templater.haproxy_http_frontend_head
if group_https_by_vhosts:
https_frontends = templater.haproxy_https_grouped_frontend_head
else:
https_frontends = templater.haproxy_https_frontend_head.format(
sslCerts=" ".join(map(lambda cert: "crt " + cert, _ssl_certs))
)
# This should handle situations where customers have a custom HAPROXY_HEAD
# that includes the 'daemon' flag or does not expose listener fds:
if 'daemon' in config or "expose-fd listeners" not in config:
upgrade_warning = '''\
Error in custom HAPROXY_HEAD template: \
In Marathon-LB 1.12, the default HAPROXY_HEAD section changed, please \
make the following changes to your custom template: Remove "daemon", \
Add "stats socket /var/run/haproxy/socket expose-fd listeners". \
More information can be found here: \
https://docs.mesosphere.com/services/marathon-lb/advanced/#global-template.\
'''
raise Exception(upgrade_warning)
userlists = str()
frontends = str()
backends = str()
http_appid_frontends = templater.haproxy_http_frontend_appid_head
apps_with_http_appid_backend = []
http_frontend_list = []
https_frontend_list = []
https_grouped_frontend_list = defaultdict(lambda: ([], set(), set()))
haproxy_dir = os.path.dirname(config_file)
logger.debug("HAProxy dir is %s", haproxy_dir)
for app in sorted(apps, key=attrgetter('appId', 'servicePort')):
# App only applies if we have it's group
# Check if there is a haproxy group associated with service group
# if not fallback to original HAPROXY group.
# This is added for backward compatability with HAPROXY_GROUP
if app.haproxy_groups:
if not has_group(groups, app.haproxy_groups):
continue
else:
if not has_group(groups, app.groups):
continue
# Skip if it's not actually enabled
if not app.enabled:
continue
logger.debug("configuring app %s", app.appId)
if len(app.backends) < 1:
logger.error("skipping app %s as it is not valid to generate" +
" backend without any server entries!", app.appId)
continue
backend = app.appId[1:].replace('/', '_') + '_' + str(app.servicePort)
logger.debug("frontend at %s:%d with backend %s",
app.bindAddr, app.servicePort, backend)
# If app has HAPROXY_{n}_MODE set, use that setting.
# Otherwise use 'http' if HAPROXY_{N}_VHOST is set, and 'tcp' if not.
if app.mode is None:
if app.hostname:
app.mode = 'http'
else:
app.mode = 'tcp'
if app.authUser:
userlist_head = templater.haproxy_userlist_head(app)
userlists += userlist_head.format(
backend=backend,
user=app.authUser,
passwd=app.authPasswd
)
frontend_head = templater.haproxy_frontend_head(app)
frontends += frontend_head.format(
bindAddr=app.bindAddr,
backend=backend,
servicePort=app.servicePort,
mode=app.mode,
sslCert=' ssl crt ' + app.sslCert if app.sslCert else '',
bindOptions=' ' + app.bindOptions if app.bindOptions else ''
)
backend_head = templater.haproxy_backend_head(app)
backends += backend_head.format(
backend=backend,
balance=app.balance,
mode=app.mode
)
# if a hostname is set we add the app to the vhost section
# of our haproxy config
# TODO(lloesche): Check if the hostname is already defined by another
# service
if bind_http_https and app.hostname:
backend_weight, p_fe, s_fe, g_fe = \
generateHttpVhostAcl(templater,
app,
backend,
haproxy_map,
domain_map_array,
haproxy_dir,
duplicate_map)
http_frontend_list.append((backend_weight, p_fe))
https_frontend_list.append((backend_weight, s_fe))
if group_https_by_vhosts:
https_grouped_frontend_list = mergeVhostTable(
https_grouped_frontend_list, g_fe)
# if app mode is http, we add the app to the second http frontend
# selecting apps by http header X-Marathon-App-Id
if app.mode == 'http' and \
app.appId not in apps_with_http_appid_backend:
logger.debug("adding virtual host for app with id %s", app.appId)
# remember appids to prevent multiple entries for the same app
apps_with_http_appid_backend += [app.appId]
cleanedUpAppId = re.sub(r'[^a-zA-Z0-9\-]', '_', app.appId)
if haproxy_map:
if 'map_http_frontend_appid_acl' not in duplicate_map:
http_appid_frontend_acl = templater \
.haproxy_map_http_frontend_appid_acl(app)
http_appid_frontends += http_appid_frontend_acl.format(
haproxy_dir=haproxy_dir
)
duplicate_map['map_http_frontend_appid_acl'] = 1
map_element = {}
map_element[app.appId] = backend
if map_element not in app_map_array:
app_map_array.append(map_element)
else:
http_appid_frontend_acl = templater \
.haproxy_http_frontend_appid_acl(app)
http_appid_frontends += http_appid_frontend_acl.format(
cleanedUpAppId=cleanedUpAppId,
hostname=app.hostname,
appId=app.appId,
backend=backend
)
if app.mode == 'http':
if app.useHsts:
backends += templater.haproxy_backend_hsts_options(app)
backends += templater.haproxy_backend_http_options(app)
backend_http_backend_proxypass = templater \
.haproxy_http_backend_proxypass_glue(app)
if app.proxypath:
backends += backend_http_backend_proxypass.format(
hostname=app.hostname,
proxypath=app.proxypath
)
backend_http_backend_revproxy = templater \
.haproxy_http_backend_revproxy_glue(app)
if app.revproxypath:
backends += backend_http_backend_revproxy.format(
hostname=app.hostname,
rootpath=app.revproxypath
)
backend_http_backend_redir = templater \
.haproxy_http_backend_redir(app)
if app.redirpath:
backends += backend_http_backend_redir.format(
hostname=app.hostname,
redirpath=app.redirpath
)
# Set network allowed ACLs
if app.mode == 'http' and app.network_allowed:
for network in app.network_allowed.split():
backends += templater.\
haproxy_http_backend_network_allowed_acl(app).\
format(network_allowed=network)
backends += templater.haproxy_http_backend_acl_allow_deny
elif app.mode == 'tcp' and app.network_allowed:
for network in app.network_allowed.split():
backends += templater.\
haproxy_tcp_backend_network_allowed_acl(app).\
format(network_allowed=network)
backends += templater.haproxy_tcp_backend_acl_allow_deny
if app.sticky:
logger.debug("turning on sticky sessions")
backends += templater.haproxy_backend_sticky_options(app)
frontend_backend_glue = templater.haproxy_frontend_backend_glue(app)
frontends += frontend_backend_glue.format(backend=backend)
do_backend_healthcheck_options_once = True
key_func = attrgetter('host', 'port')
taken_server_ids = set()
for backend_service_idx, backendServer\
in enumerate(sorted(app.backends, key=key_func)):
if do_backend_healthcheck_options_once:
if app.healthCheck:
template_backend_health_check = None
if app.mode == 'tcp' \
or app.healthCheck['protocol'] == 'TCP' \
or app.healthCheck['protocol'] == 'MESOS_TCP':
template_backend_health_check = templater \
.haproxy_backend_tcp_healthcheck_options(app)
elif app.mode == 'http':
template_backend_health_check = templater \
.haproxy_backend_http_healthcheck_options(app)
if template_backend_health_check:
health_check_port = get_backend_port(
apps,
app,
backend_service_idx)
backends += _get_health_check_options(
template_backend_health_check,
app.healthCheck,
health_check_port)
do_backend_healthcheck_options_once = False
logger.debug(
"backend server %s:%d on %s",
backendServer.ip,
backendServer.port,
backendServer.host)
# Create a unique, friendly name for the backend server. We concat
# the host, task IP and task port together. If the host and task
# IP are actually the same then omit one for clarity.
if backendServer.host != backendServer.ip:
serverName = re.sub(
r'[^a-zA-Z0-9\-]', '_',
(backendServer.host + '_' +
backendServer.ip + '_' +
str(backendServer.port)))
else:
serverName = re.sub(
r'[^a-zA-Z0-9\-]', '_',
(backendServer.ip + '_' +
str(backendServer.port)))
shortHashedServerName = hashlib.sha1(serverName.encode()) \
.hexdigest()[:10]
# In order to keep the state of backend servers consistent between
# reloads, server IDs need to be stable. See
# calculate_backend_id()'s docstring to learn how it is achieved.
server_id = calculate_server_id(serverName, taken_server_ids)
server_health_check_options = None
if app.healthCheck:
template_server_healthcheck_options = None
if app.mode == 'tcp' \
or app.healthCheck['protocol'] == 'TCP' \
or app.healthCheck['protocol'] == 'MESOS_TCP':
template_server_healthcheck_options = templater \
.haproxy_backend_server_tcp_healthcheck_options(app)
elif app.mode == 'http':
template_server_healthcheck_options = templater \
.haproxy_backend_server_http_healthcheck_options(app)
if template_server_healthcheck_options:
if app.healthcheck_port_index is not None:
health_check_port = \
get_backend_port(apps, app, backend_service_idx)
else:
health_check_port = app.healthCheck.get('port')
server_health_check_options = _get_health_check_options(
template_server_healthcheck_options,
app.healthCheck,
health_check_port)
backend_server_options = templater \
.haproxy_backend_server_options(app)
backends += backend_server_options.format(
host=backendServer.host,
host_ipv4=backendServer.ip,
port=backendServer.port,
serverName=serverName,
serverId=server_id,
cookieOptions=' check cookie ' + shortHashedServerName
if app.sticky else '',
healthCheckOptions=server_health_check_options
if server_health_check_options else '',
otherOptions=' disabled' if backendServer.draining else ''
)
http_frontend_list.sort(key=lambda x: x[0], reverse=True)
https_frontend_list.sort(key=lambda x: x[0], reverse=True)
for backend in http_frontend_list:
http_frontends += backend[1]
if group_https_by_vhosts:
for backend in sorted(https_grouped_frontend_list.keys()):
https_frontends +=\
templater.haproxy_https_grouped_vhost_frontend_acl.format(
backend=re.sub(r'[^a-zA-Z0-9\-]', '_', backend),
host=backend)
else:
for backend in https_frontend_list:
https_frontends += backend[1]
config += userlists
if bind_http_https:
config += http_frontends
config += http_appid_frontends
if bind_http_https:
config += https_frontends
if group_https_by_vhosts:
for vhost in sorted(https_grouped_frontend_list.keys()):
config +=\
templater\
.haproxy_https_grouped_vhost_backend_head\
.format(
name=re.sub(r'[^a-zA-Z0-9\-]', '_', vhost))
frontend = templater \
.haproxy_https_grouped_vhost_frontend_head \
.format(name=re.sub(r'[^a-zA-Z0-9\-]', '_', vhost),
sslCerts=" ".join(
map(lambda cert: "crt " + cert,
defaultValue(
https_grouped_frontend_list[vhost][1],
set(_ssl_certs)))),
bindOpts=" ".join(
map(lambda opts: " " + opts,
https_grouped_frontend_list[vhost][2]))
)
for v in sorted(
https_grouped_frontend_list[vhost][0],
key=lambda x: x[0],
reverse=True):
frontend += v[1]
config += frontend
config += frontends
config += backends
return config
def defaultValue(col, default):
if len(col) == 0:
return default
else:
return col
def get_haproxy_pids():
try:
return set(map(lambda i: int(i), subprocess.check_output(
"pidof haproxy",
stderr=subprocess.STDOUT,
shell=True).split()))
except subprocess.CalledProcessError as ex:
logger.debug("Unable to get haproxy pids: %s", ex)
return set()
def reloadConfig():
reloadCommand = []
if args.command:
reloadCommand = shlex.split(args.command)
else:
logger.debug("No reload command provided, trying to find out how to" +
" reload the configuration")
if os.path.isfile('/etc/init/haproxy.conf'):
logger.debug("we seem to be running on an Upstart based system")
reloadCommand = ['reload', 'haproxy']
elif (os.path.isfile('/usr/lib/systemd/system/haproxy.service') or
os.path.isfile('/lib/systemd/system/haproxy.service') or
os.path.isfile('/etc/systemd/system/haproxy.service')):
logger.debug("we seem to be running on systemd based system")
reloadCommand = ['systemctl', 'reload', 'haproxy']
elif os.path.isfile('/etc/init.d/haproxy'):
logger.debug("we seem to be running on a sysvinit based system")
reloadCommand = ['/etc/init.d/haproxy', 'reload']
else:
# if no haproxy exists (maybe running in a container)
logger.debug("no haproxy detected. won't reload.")
reloadCommand = None
if reloadCommand:
logger.info("reloading using %s", " ".join(reloadCommand))
try:
start_time = time.time()
checkpoint_time = start_time
# Retry or log the reload every 10 seconds
reload_frequency = args.reload_interval
reload_retries = args.max_reload_retries
enable_retries = True
infinite_retries = False
if reload_retries == 0:
enable_retries = False
elif reload_retries < 0:
infinite_retries = True
old_pids = get_haproxy_pids()
subprocess.check_call(reloadCommand, close_fds=True)
new_pids = get_haproxy_pids()
logger.debug("Waiting for new haproxy pid (old pids: [%s], " +
"new_pids: [%s])...", old_pids, new_pids)
# Wait until the reload actually occurs and there's a new PID
while True:
if len(new_pids - old_pids) >= 1:
logger.debug("new pids: [%s]", new_pids)
logger.debug("reload finished, took %s seconds",
time.time() - start_time)
break
timeSinceCheckpoint = time.time() - checkpoint_time
if (timeSinceCheckpoint >= reload_frequency):
logger.debug("Still waiting for new haproxy pid after " +
"%s seconds (old pids: [%s], " +
"new_pids: [%s]).",
time.time() - start_time, old_pids, new_pids)
checkpoint_time = time.time()
if enable_retries:
if not infinite_retries:
reload_retries -= 1
if reload_retries == 0:
logger.debug("reload failed after %s seconds",
time.time() - start_time)
break
logger.debug("Attempting reload again...")
subprocess.check_call(reloadCommand, close_fds=True)
time.sleep(0.1)
new_pids = get_haproxy_pids()
except OSError as ex:
logger.error("unable to reload config using command %s",
" ".join(reloadCommand))
logger.error("OSError: %s", ex)
except subprocess.CalledProcessError as ex:
logger.error("unable to reload config using command %s",
" ".join(reloadCommand))
logger.error("reload returned non-zero: %s", ex)
def generateHttpVhostAcl(
templater, app, backend, haproxy_map, map_array,
haproxy_dir, duplicate_map):
# If the hostname contains the delimiter ',', then the marathon app is
# requesting multiple hostname matches for the same backend, and we need
# to use alternate templates from the default one-acl/one-use_backend.
staging_http_frontends = ""
staging_https_frontends = ""
https_grouped_frontend_list = defaultdict(lambda: ([], set(), set()))
if "," in app.hostname:
logger.debug(
"vhost label specifies multiple hosts: %s", app.hostname)
vhosts = app.hostname.split(',')
acl_name = re.sub(r'[^a-zA-Z0-9\-]', '_', vhosts[0]) + \
'_' + app.appId[1:].replace('/', '_')
if app.path:
if app.authRealm:
# Set the path ACL if it exists
logger.debug("adding path acl, path=%s", app.path)
http_frontend_acl = \
templater.\
haproxy_http_frontend_acl_only_with_path_and_auth(app)
staging_http_frontends += http_frontend_acl.format(
path=app.path,
cleanedUpHostname=acl_name,
hostname=vhosts[0],
realm=app.authRealm,
backend=backend
)
https_frontend_acl = \
templater.\
haproxy_https_frontend_acl_only_with_path(app)
staging_https_frontends += https_frontend_acl.format(
path=app.path,
cleanedUpHostname=acl_name,
hostname=vhosts[0],
realm=app.authRealm,
backend=backend
)
else:
# Set the path ACL if it exists
logger.debug("adding path acl, path=%s", app.path)
http_frontend_acl = \
templater.haproxy_http_frontend_acl_only_with_path(app)
staging_http_frontends += http_frontend_acl.format(
path=app.path,
backend=backend
)
https_frontend_acl = \
templater.haproxy_https_frontend_acl_only_with_path(app)
staging_https_frontends += https_frontend_acl.format(
path=app.path,
backend=backend
)
temp_frontend_head = staging_https_frontends
for vhost_hostname in vhosts:
https_grouped_frontend_list[vhost_hostname][0].append(
(app.backend_weight, temp_frontend_head))
if app.sslCert is not None:
https_grouped_frontend_list[vhost_hostname][1].add(app.sslCert)
if app.bindOptions is not None:
https_grouped_frontend_list[vhost_hostname][2].add(
app.bindOptions)
logger.debug("processing vhost %s", vhost_hostname)
if haproxy_map and not app.path and not app.authRealm and \
not app.redirectHttpToHttps:
if 'map_http_frontend_acl' not in duplicate_map:
app.backend_weight = -1
http_frontend_acl = templater.\
haproxy_map_http_frontend_acl_only(app)
staging_http_frontends += http_frontend_acl.format(
haproxy_dir=haproxy_dir
)
duplicate_map['map_http_frontend_acl'] = 1
map_element = {}
map_element[vhost_hostname] = backend
if map_element not in map_array:
map_array.append(map_element)
else:
http_frontend_acl = templater.\
haproxy_http_frontend_acl_only(app)
staging_http_frontends += http_frontend_acl.format(
cleanedUpHostname=acl_name,
hostname=vhost_hostname
)
# Tack on the SSL ACL as well
if app.path:
if app.authRealm:
https_frontend_acl = templater.\
haproxy_https_frontend_acl_with_auth_and_path(app)
staging_https_frontend = https_frontend_acl.format(
cleanedUpHostname=acl_name,
hostname=vhost_hostname,
appId=app.appId,
realm=app.authRealm,
backend=backend
)
staging_https_frontends += staging_https_frontend
https_grouped_frontend_list[vhost_hostname][0].append(
(app.backend_weight, staging_https_frontend))
else:
https_frontend_acl = \
templater.haproxy_https_frontend_acl_with_path(app)
staging_https_frontend = https_frontend_acl.format(
cleanedUpHostname=acl_name,
hostname=vhost_hostname,
appId=app.appId,
backend=backend
)
staging_https_frontends += staging_https_frontend
https_grouped_frontend_list[vhost_hostname][0].append(
(app.backend_weight, staging_https_frontend))
else:
if app.authRealm:
https_frontend_acl = \
templater.haproxy_https_frontend_acl_with_auth(app)
staging_https_frontend = https_frontend_acl.format(
cleanedUpHostname=acl_name,
hostname=vhost_hostname,