This repository has been archived by the owner on Jul 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
/
marathon-bigip-ctlr.py
executable file
·1215 lines (1004 loc) · 42.1 KB
/
marathon-bigip-ctlr.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 python
#
# Copyright (c) 2017,2018, F5 Networks, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""marathon-bigip-ctlr.
marathon-bigip-ctlr is a service discovery and load balancing tool
for Marathon to configure an F5 BIG-IP. It reads the Marathon task information
and dynamically generates BIG-IP configuration details.
To gather the task information, marathon-bigip-ctlr 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-bigip-ctlr just needs to know where to find Marathon.
"""
from __future__ import print_function
import json
import logging
from operator import attrgetter
import os
import os.path
import re
import sys
import time
import threading
from itertools import cycle
from urlparse import urlparse
import configargparse
import requests
from requests.exceptions import ConnectionError
from sseclient import SSEClient
from common import (set_logging_args, set_marathon_auth_args,
setup_logging, get_marathon_auth_params, resolve_ip,
validate_bigip_address)
from f5_cccl.api import F5CloudServiceManager
from f5_cccl.exceptions import F5CcclError
from f5_cccl.utils.mgmt import mgmt_root
class InvalidServiceDefinitionError(ValueError):
"""Parser or validator encountered error in user's service definition.
Raising this error will cause the service to not be defined on BIG-IP.
For example, if while parsing F5_2_MODE the parser decides the mode is
invalid, it can raise this error and the 2nd service port (F5_2_*) won't
be defined.
A helpful error is logged to the user at loglevel warning.
"""
# Setter function callbacks that correspond to specific labels: they will
# handle validating the value (v) and setting attributes on the object (x).
# These functions are used for exact matches (resp. prefix matches below).
def set_bindAddr(x, v):
"""App label callback.
Set the Virtual Server address from label F5_n_BIND_ADDR
"""
x.bindAddr = v
def set_port(x, v):
"""App label callback.
Set the service port from label F5_n_PORT
"""
x.servicePort = int(v)
def set_mode(x, v):
"""App label callback.
Set the mode from label F5_n_MODE
"""
x.mode = v
def set_balance(x, v):
"""App label callback.
Set the load-balancing method from label F5_n_BALANCE
"""
x.balance = v
def set_profile(x, v):
"""App label callback.
Set the SSL Profile from label F5_n_SSL_PROFILE
"""
x.profile = v
def set_iapp(x, v):
"""App label callback.
Set the iApp template from label F5_n_IAPP_TEMPLATE
"""
x.iapp = v
loggedIappPoolMemberTableNameDeprecated = False
def set_iapp_pool_member_table_name(x, v):
"""App label callback.
Set the pool-member table name in the iApp from label
F5_n_IAPP_POOL_MEMBER_TABLE_NAME
"""
global loggedIappPoolMemberTableNameDeprecated
if hasattr(x, 'iappPoolMemberTable'):
raise InvalidServiceDefinitionError(
("You can only specify one of IAPP_POOL_MEMBER_TABLE_NAME or "
"IAPP_POOL_MEMBER_TABLE, not both")
)
if not loggedIappPoolMemberTableNameDeprecated:
logger.info(
("Using IAPP_POOL_MEMBER_TABLE_NAME is deprecated; see "
"IAPP_POOL_MEMBER_TABLE")
)
loggedIappPoolMemberTableNameDeprecated = True
x.iappPoolMemberTableName = v
def set_iapp_pool_member_table(x, v):
"""App label callback.
Take the user's description for how to fill out the iApp's pool member
table. Every iApp may have a different layout for this table. We need to
provide the pool member IPs and ports, so we'll need to know what those
columns are named. If there are other columns, we need to let the user
specify what we should fill in.
"""
if hasattr(x, 'iappPoolMemberTableName'):
raise InvalidServiceDefinitionError(
("You can only specify one of IAPP_POOL_MEMBER_TABLE_NAME or "
"IAPP_POOL_MEMBER_TABLE, not both")
)
table = None
try:
table = json.loads(v)
except ValueError:
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE is not valid JSON")
# FIXME(andrew): This should be done by jsonschema.
for mandatoryProp in ['name', 'columns']:
if mandatoryProp not in table:
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE must have a '%s' field" %
mandatoryProp)
if not isinstance(table['name'], basestring):
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE's 'name' property must be a string")
if not isinstance(table['columns'], list):
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE's 'columns' property must be an array")
for i, col in enumerate(table['columns']):
# Each column must be either
# columnWithKind: { "name": "foo", "kind": "IPAddress" } or
# columnWithValue: { "name": "foo", "value": "42" }
# Both column styles need "name"
if 'name' not in col:
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE column %d must have a 'name' field" %
i)
# Need either 'kind' or 'value'
if 'kind' in col:
if col['kind'] not in ['IPAddress', 'Port']:
raise InvalidServiceDefinitionError(
"IAPP_POOL_MEMBER_TABLE column %d kind '%s' unknown" %
(i, col['kind']))
elif 'value' in col:
# We pass the value opaquely.
pass
else:
raise InvalidServiceDefinitionError(
("IAPP_POOL_MEMBER_TABLE column %d must specify either 'kind'"
" or 'value'") % i)
x.iappPoolMemberTable = table
# Dictionary of labels and setter functions, where the labels must match the
# key exactly (after template substitution)
exact_label_keys = {
'F5_{0}_BIND_ADDR': set_bindAddr,
'F5_{0}_PORT': set_port,
'F5_{0}_MODE': set_mode,
'F5_{0}_BALANCE': set_balance,
'F5_{0}_SSL_PROFILE': set_profile,
'F5_{0}_IAPP_TEMPLATE': set_iapp,
'F5_{0}_IAPP_POOL_MEMBER_TABLE_NAME': set_iapp_pool_member_table_name,
'F5_{0}_IAPP_POOL_MEMBER_TABLE': set_iapp_pool_member_table,
}
# Setter function callbacks that correspond to specific labels (k) and their
# values (v) to set an attribute on the object (x). These functions are
# associated with the 'label_keys' dictionary that follows.
# The 'k' arg is the actual label key used, because these functions will handle
# any label that prefix-matches a string (e.g. k may be
# F5_0_IAPP_VARIABLE_net__server_mode which prefix-matches
# F5_0_IAPP_VARIABLE_).
def set_iapp_variable(x, k, v):
"""App label callback.
Set an element in the iApp Variables from label F5_n_IAPP_VARIABLE_*
"""
x.iappVariables[k] = v
def set_iapp_table(x, k, v):
"""App label callback.
Set an element in the iApp Tables from label F5_n_IAPP_TABLE_*
"""
x.iappTables[k] = v
def set_iapp_option(x, k, v):
"""App label callback.
Set an optional parameter in the iApp from label F5_n_IAPP_OPTION_*
"""
x.iappOptions[k] = v
# Dictionary of labels and setter functions, where the labels must start with
# the key (after template substitution)
prefix_label_keys = {
'F5_{0}_IAPP_TABLE_': set_iapp_table,
'F5_{0}_IAPP_VARIABLE_': set_iapp_variable,
'F5_{0}_IAPP_OPTION_': set_iapp_option,
}
logger = logging.getLogger('controller')
def healthcheck_timeout_calculate(data):
"""Calculate a BIG-IP Health Monitor timeout.
Args:
data: BIG-IP config dict
"""
# Calculate timeout
# See the f5 monitor docs for explanation of settings:
# https://goo.gl/JJWUIg
# Formula to match up the cloud settings with f5 settings:
# (( maxConsecutiveFailures - 1) * intervalSeconds )
# + timeoutSeconds + 1
timeout = (
((data['maxConsecutiveFailures'] - 1) * data['intervalSeconds']) +
data['timeoutSeconds'] + 1
)
return timeout
def get_protocol(protocol):
"""Return the protocol (tcp or udp).
This converts from the marathon protocol (udp, tcp, or http) to the BIG-IP
protocol (udp or tcp); http is handled at a different layer on top of tcp
in BIG-IP config
"""
if str(protocol).lower() == 'tcp':
return 'tcp'
if str(protocol).lower() == 'http':
return 'tcp'
if str(protocol).lower() == 'udp':
return 'udp'
return None
def is_label_data_valid(app):
"""Validate the Marathon app's label data.
Args:
app: The app to be validated
"""
is_valid = True
msg = 'Application label {0} for {1} contains an invalid value: {2}'
# Validate mode
if get_protocol(app.mode) is None:
logger.error(msg.format('F5_MODE', app.appId, app.mode))
is_valid = False
# Validate port
if app.servicePort < 1 or app.servicePort > 65535:
logger.error(msg.format('F5_PORT', app.appId, app.servicePort))
is_valid = False
# Validate address
if app.bindAddr is not None:
if not validate_bigip_address(app.bindAddr):
logger.error(msg.format('F5_BIND_ADDR', app.appId, app.bindAddr))
is_valid = False
return is_valid
def healthcheck_sendstring(data):
"""Return the 'send' string for a health monitor.
Args:
data: Health Monitor dict
"""
if 'type' in data and data['type'] == "http":
send_string = 'GET / HTTP/1.0\\r\\n\\r\\n'
if 'path' in data:
send_string = 'GET %s HTTP/1.0\\r\\n\\r\\n' % data['path']
return send_string
else:
return None
class MarathonBackend(object):
"""MarathonBackend class.
Represents a backend server (host and port) that requires
load balancing
"""
def __init__(self, host, port, draining):
"""Initialize the backend object."""
self.host = host
self.port = port
self.draining = draining
def __hash__(self):
"""Host and port for a backend are unique."""
return hash((self.host, self.port))
def __repr__(self):
"""String representation of object."""
return "MarathonBackend(%r, %r)" % (self.host, self.port)
class MarathonService(object):
"""MarathonService class.
Represents a service in Marathon that requires
load balancing
"""
def __init__(self, appId, servicePort, healthCheck):
"""Initialize MarathonService with defaults."""
self.appId = appId
self.servicePort = servicePort
self.backends = set()
self.hostname = None
self.sticky = False
self.redirectHttpToHttps = False
self.sslCert = None
self.bindOptions = None
self.bindAddr = None
self.partition = None
self.iapp = None
self.iappTableName = None
self.iappTables = {}
self.iappVariables = {}
self.iappOptions = {}
self.mode = 'tcp'
self.balance = 'round-robin'
self.profile = None
self.healthCheck = healthCheck
self.labels = {}
if healthCheck:
for hc in healthCheck:
if hc['protocol'] == 'HTTP':
self.mode = 'http'
def add_backend(self, host, port, draining):
"""Add a backend to the service."""
self.backends.add(MarathonBackend(host, port, draining))
def __hash__(self):
"""Object is identified by servicePort."""
return hash(self.servicePort)
def __eq__(self, other):
"""Object is identified by servicePort."""
return self.servicePort == other.servicePort
def __repr__(self):
"""String representation of object."""
return "MarathonService(%r, %r)" % (self.appId, self.servicePort)
class MarathonApp(object):
"""MarathonApp class.
Represents an application in Marathon
"""
def __init__(self, appId, app):
"""Initialize MarathonApp."""
self.app = app
self.partition = None
self.appId = appId
# port -> MarathonService
self.services = dict()
def __hash__(self):
"""Object is identified by appId."""
return hash(self.appId)
def __eq__(self, other):
"""Object is identified by appId."""
return self.appId == other.appId
class Marathon(object):
"""Marathon class.
Manages access to Marathon
* Subscribe for events
* Processes event
* Retrieves Marathon application state
"""
def __init__(self, hosts, health_check, auth, ca_cert=None):
"""Initialize the Marathon object."""
self.__hosts = hosts
self.__health_check = health_check
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, **kwargs):
"""Send an API request to Marathon and return the response."""
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'
},
**kwargs
)
logger.debug("%s %s", method, response.url)
if response.status_code == 200:
break
response.raise_for_status()
if 'message' in response.json():
response.reason = "%s (%s)" % (
response.reason,
response.json()['message'])
return response
def api_req(self, method, path, **kwargs):
"""Send an API request to Marathon and return the JSON response."""
return self.api_req_raw(method, path, self.__auth,
verify=self.__verify, **kwargs).json()
# Lists all running apps.
def list(self):
"""Get the app list from Marathon."""
logger.info('fetching apps')
return self.api_req('GET', ['apps'],
params={'embed': 'apps.tasks'})["apps"]
def health_check(self):
"""Get health check."""
return self.__health_check
def get_event_stream(self, timeout):
"""Get the Server Side Event (SSE) event stream."""
url = self.host+"/v2/events"
logger.info(
"SSE Active, trying fetch events from from {0}".format(url))
return SSEClient(url, auth=self.__auth, verify=self.__verify,
timeout=timeout)
@property
def host(self):
"""Cycle the the configured set of Marathon hosts."""
return next(self.__cycle_hosts)
def get_health_check(app, portIndex):
"""Get the healthcheck for the app."""
checks = []
for check in app.get('healthChecks', []):
if check.get('port') or check.get('portIndex') == portIndex:
checks.append(check)
if len(checks) > 0:
return checks
return None
def get_apps(apps, health_check):
"""Create a list of app services from the Marathon state."""
marathon_apps = []
logger.debug("Marathon apps: %s", [app["id"] for app in apps])
for app in apps:
logger.info("Working on app %s", app['id'])
appId = app['id']
if appId[1:] == os.environ.get("FRAMEWORK_NAME"):
continue
marathon_app = MarathonApp(appId, app)
if 'F5_PARTITION' in marathon_app.app['labels']:
marathon_app.partition = \
marathon_app.app['labels']['F5_PARTITION']
marathon_apps.append(marathon_app)
# 'ports' does not exist in Marathon v1.5.2 and when DC/OS Virtual
# Networking is used.
service_ports = app.get('ports', [])
if len(service_ports) == 0:
# If 'ports' doesn't exist, check 'portMappings'
portMappings = app.get('container', {}).get('portMappings', [])
for port in portMappings:
if 'servicePort' in port:
service_ports.append(port['servicePort'])
logger.debug("Application service ports = %s", (repr(service_ports)))
logger.debug("Labels for app %s: %s", app['id'],
marathon_app.app['labels'])
if len(service_ports) == 0:
logger.warning("Warning, no service ports found for %s", appId)
for i, servicePort in enumerate(service_ports):
try:
service = MarathonService(
appId, servicePort, get_health_check(app, i))
service.partition = marathon_app.partition
# Parse the app labels that must match the template exactly
for key_unformatted in exact_label_keys:
key = key_unformatted.format(i)
if key in marathon_app.app['labels']:
func = exact_label_keys[key_unformatted]
func(service, marathon_app.app['labels'][key])
# Parse the app labels that must start with a template entry
for key_unformatted in prefix_label_keys:
key = key_unformatted.format(i)
for label in marathon_app.app['labels']:
# Labels can be a combination of predicate +
# a variable name
if label.startswith(key):
func = prefix_label_keys[key_unformatted]
func(service,
label[len(key):],
marathon_app.app['labels'][label])
marathon_app.services[servicePort] = service
except InvalidServiceDefinitionError as e:
logger.warning(
"App %s, service %d has an invalid config, skipping: %s",
appId, i, e)
for task in app['tasks']:
# Marathon 0.7.6 bug workaround
if len(task['host']) == 0:
logger.warning("Ignoring Marathon task without host %s",
task['id'])
continue
if health_check and 'healthChecks' in app and \
len(app['healthChecks']) > 0:
if 'healthCheckResults' not in task:
continue
alive = True
for result in task['healthCheckResults']:
if not result['alive']:
alive = False
if not alive:
continue
task_ports = task['ports']
draining = False
if 'draining' in task:
draining = task['draining']
# if different versions of app have different number of ports,
# try to match as many ports as possible
number_of_defined_ports = min(len(task_ports), len(service_ports))
for i in range(number_of_defined_ports):
task_port = task_ports[i]
service_port = service_ports[i]
service = marathon_app.services.get(service_port, None)
if service:
service.add_backend(task['host'],
task_port,
draining)
# Convert into a list for easier consumption
apps_list = []
for marathon_app in marathon_apps:
for service in list(marathon_app.services.values()):
apps_list.append(service)
logger.debug("Marathon app list: %s", repr(apps_list))
return apps_list
def get_source_addr_translation(snat_pool_name):
"""Get the source address translation based on SNAT pool presence.
Args:
snat_pool_name: SNAT pool name string
"""
if snat_pool_name == "":
return {'type': 'automap'}
return {
'type': 'snat',
'pool': snat_pool_name
}
def create_config_marathon(cccl, apps, snat_pool_name):
"""Create a BIG-IP configuration from the Marathon app list.
Args:
apps: Marathon app list
"""
logger.debug(apps)
for app in apps:
logger.debug(app.__hash__())
logger.info("Generating config for BIG-IP")
services = {
'virtualServers': [],
'l7Policies': [],
'pools': [],
'monitors': [],
'iapps': []
}
for app in apps:
# Only handle application if it's partition is one that this script
# is responsible for
if cccl.get_partition() != app.partition:
continue
# Validate data from the app's labels
if not app.iapp and not is_label_data_valid(app):
continue
# No address or iApp for this port (pool-only config)
if not app.bindAddr and not app.iapp:
logger.debug("Creating pool only for %s", app.appId)
logger.info("Configuring app %s, partition %s", app.appId,
app.partition)
backend = app.appId[1:].replace('/', '_') + '_' + \
str(app.servicePort)
frontend_name = "%s_%d" % ((app.appId).lstrip('/'), app.servicePort)
# The Marathon appId contains the full path, replace all '/' in
# the name with '_'
frontend_name = frontend_name.replace('/', '_')
if app.bindAddr:
logger.debug("Frontend at %s:%d with backend %s", app.bindAddr,
app.servicePort, backend)
# pool members
members = []
key_func = attrgetter('host', 'port')
for backendServer in sorted(app.backends, key=key_func):
logger.debug("Found backend server at %s:%d for app %s",
backendServer.host, backendServer.port, app.appId)
# Resolve backendServer hostname to IP address
ip = resolve_ip(backendServer.host)
if ip is not None:
member = {
'address': ip,
'port': backendServer.port,
'session': 'user-enabled'
}
members.append(member)
else:
logger.warning("Could not resolve ip for host %s, "
"ignoring this backend", backendServer.host)
if app.iapp:
# Translate from the internal properties we set on app to the
# naming expected by the iapp.
# Only set properties that are actually present.
cfg = {
'variables': {},
'tables': {},
'options': {}
}
for k, v in {'template': 'iapp',
'tableName': 'iappPoolMemberTableName',
'poolMemberTable': 'iappPoolMemberTable',
'tables': 'iappTables',
'variables': 'iappVariables',
'options': 'iappOptions'}.iteritems():
if hasattr(app, v):
cfg[k] = getattr(app, v)
try:
# Decode the tables
for key in app.iappTables:
cfg['tables'][key] = json.loads(app.iappTables[key])
except ValueError:
logger.error("IAPP TABLE data is not valid JSON")
continue
iapp = {
'name': frontend_name,
'template': cfg['template'],
'variables': cfg['variables'],
'tables': cfg['tables'],
'options': cfg['options']
}
for member in members:
# iApp will manage member state
del member['session']
# Add the poolMemberTable
if 'poolMemberTable' in cfg:
cfg['poolMemberTable']['members'] = members
iapp['poolMemberTable'] = cfg['poolMemberTable']
elif 'tableName' in cfg:
# Before adding the flexible poolMemberTable mode, we only
# supported three fixed columns in order, and connection_limit
# was hardcoded to 0 ("no limit")
poolMemberTable = {
"name": cfg['tableName'],
"columns": [
{"name": "addr", "kind": "IPAddress"},
{"name": "port", "kind": "Port"},
{"name": "connection_limit", "value": "0"}
]
}
poolMemberTable['members'] = members
iapp['poolMemberTable'] = poolMemberTable
services['iapps'].append(iapp)
else:
monitors = []
if app.healthCheck:
for counter, hc in enumerate(app.healthCheck):
logger.debug("Healthcheck for app '%s': %s",
app.appId, hc)
# normalize healthcheck protocol name to lowercase
if 'protocol' in hc:
hc['type'] = (hc['protocol']).lower()
if 'http' in hc['type']:
hc['type'] = 'http'
if 'tcp' in hc['type']:
hc['type'] = 'tcp'
hc.update({
'interval': hc['intervalSeconds'],
'timeout': healthcheck_timeout_calculate(hc)
})
# Append the index and protocol to the monitor name to
# keep them unique
hc['name'] = frontend_name + '_' + str(counter) + '_' + \
hc['type']
send = healthcheck_sendstring(hc)
if send is not None:
hc['send'] = send
monitors.append(hc)
services['monitors'] += monitors
# Parse the SSL profile into partition and name
profiles = []
if app.profile:
profile = app.profile.split('/')
if len(profile) != 2:
logger.error("Could not parse partition and name from"
" SSL profile: %s", app.profile)
else:
profiles.append({'partition': profile[0],
'name': profile[1]})
# Add appropriate profiles
if str(app.mode).lower() == 'http':
# BIG-IP will automatically add the tcp profile for http
# because it is an inherited profile. Explictly add the tcp
# profile so that we don't fail comparison matches later.
profiles.append({'partition': 'Common',
'name': 'http',
'context': 'all'})
profiles.append({'partition': 'Common',
'name': 'tcp',
'context': 'all'})
elif get_protocol(app.mode) == 'tcp':
profiles.append({'partition': 'Common',
'name': 'tcp',
'context': 'all'})
if app.bindAddr:
virtual = {
'name': frontend_name,
'enabled': True,
'ipProtocol': get_protocol(app.mode),
'destination':
"/%s/%s:%d" % (app.partition, app.bindAddr,
app.servicePort),
'pool': "/%s/%s" % (app.partition, frontend_name),
'sourceAddressTranslation': get_source_addr_translation(
snat_pool_name),
'profiles': profiles
}
services['virtualServers'].append(virtual)
pool = {
'name': frontend_name,
'monitors': ["/%s/%s" %
(app.partition, m['name']) for m in monitors],
'loadBalancingMode': app.balance,
'members': members
}
services['pools'].append(pool)
logger.debug("Service Config: %s", json.dumps(services))
return services
class MarathonEventProcessor(object):
"""MarathonEventProcessor class.
Processes Marathon events, fetches the Marathon state, and
reconfigures the BIG-IP
"""
def __init__(self, marathon, verify_interval, cccls, snat_pool_name):
"""Class init.
Starts a thread that waits for Marathon events,
then configures BIG-IP based on the Marathon state
"""
self.__marathon = marathon
# appId -> MarathonApp
self.__apps = dict()
self.__cccls = cccls
self.__verify_interval = verify_interval
self.__snat_pool_name = snat_pool_name
self.__condition = threading.Condition()
self.__thread = threading.Thread(target=self.do_reset)
self.__pending_reset = False
self.__thread.daemon = True
self.__thread.start()
self.__timer = None
self._backoff_timer = 1
self._max_backoff_time = 128
# Fetch the base data
self.reset_from_tasks()
def do_reset(self):
"""Process the Marathon state and reconfigure the BIG-IP."""
with self.__condition:
while True: # pylint: disable=too-many-nested-blocks
self.__condition.acquire()
if not self.__pending_reset:
self.__condition.wait()
self.__pending_reset = False
self.__condition.release()
try:
start_time = time.time()
if self.__timer is not None:
# Stop timer
self.__timer.cancel()
self.__timer = None
self.__apps = \
sorted(get_apps(self.__marathon.list(),
self.__marathon.health_check()),
key=attrgetter('appId', 'servicePort'))
incomplete = 0
for cccl in self.__cccls:
cfg = create_config_marathon(
cccl, self.__apps, self.__snat_pool_name)
try:
incomplete += cccl.apply_ltm_config(cfg)
except F5CcclError as e:
logger.error("CCCL Error: %s", e.msg)
if incomplete:
# Some retryable error occurred),
# do a reset so that we try again
self.retry_backoff(self.reset_from_tasks)
else:
# Reconfig was successful
self.start_checkpoint_timer()
self._backoff_timer = 1
perf_enable = os.environ.get('SCALE_PERF_ENABLE')
if perf_enable: # pragma: no cover
test_data = {}
app_count = 0
backend_count = 0
for app in self.__apps:
if app.partition == 'test':
app_count += 1
backends = len(app.backends)
test_data[app.appId[1:]] = backends
backend_count += backends
test_data['Total_Services'] = app_count
test_data['Total_Backends'] = backend_count
test_data['Time'] = time.time()
json_data = json.dumps(test_data)
logger.info('SCALE_PERF: Test data: %s',
json_data)
logger.debug("updating tasks finished, took %s seconds",
time.time() - start_time)
except ConnectionError:
logger.error("Could not connect to Marathon")
self.start_checkpoint_timer()
except Exception:
logger.exception("Unexpected error!")
self.start_checkpoint_timer()
def retry_backoff(self, func):
"""Tight loop backoff in case of error response."""
e = threading.Event()
logger.error("Error applying config, will try again in %s seconds",
self._backoff_timer)
e.wait(self._backoff_timer)
if self._backoff_timer < self._max_backoff_time:
self._backoff_timer *= 2
func()
def start_checkpoint_timer(self):
"""Start timer to checkpoint the BIG-IP config."""
# Start a timer that will force a reconfig in the absence of Marathon
# events to ensure that the BIG-IP config remains sane
self.__timer = threading.Timer(self.__verify_interval,
self.reset_from_tasks)
self.__timer.start()
def reset_from_tasks(self):
"""Indicate that we need to process the Marathon state."""
self.__condition.acquire()
self.__pending_reset = True
self.__condition.notify()
self.__condition.release()
def handle_event(self, event):
"""Check Marathon event.