-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwait_for_services
executable file
·217 lines (189 loc) · 7.59 KB
/
wait_for_services
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
#!/usr/bin/env python3
import os
import sys
import time
import socket
import logging
import argparse
import requests
import docker
import docker.errors
SERVICES_URL = {
"v1": "http://127.0.0.1:8080/api/providers",
"v2": "http://127.0.0.1:8080/api/http/services",
}
def main():
start = int(time.time())
env = os.environ
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--timeout', type=int, default=20)
parser.add_argument('-d', '--retry-delay', type=int, default=2)
parser.add_argument('-v', '--verbose', action='store_true', default=False)
args = parser.parse_args()
logging.basicConfig(
stream=sys.stdout,
format='%(levelname)s: %(message)s',
level=100000,
)
log = logging.getLogger('wait_for_services')
log.setLevel(logging.DEBUG if args.verbose else logging.INFO)
breaks_at = time.time() + int(args.timeout)
my_id = socket.gethostname()
client = docker.from_env()
label = None
for container in client.containers.list(all=True):
if container.id.startswith(my_id):
if 'com.docker.compose.project' in container.labels:
label = (
'com.docker.compose.project=%s'
) % container.labels['com.docker.compose.project']
break
if label is None:
log.critical(
'Cant find my project! Are you using me inside compose ?!')
return 1
for i in range(2):
try:
containers = client.containers.list(
filters={'label': label}, all=True)
except docker.errors.NotFound:
time.sleep(args.retry_delay)
containers = {
c.labels['com.docker.compose.service']: c
for c in containers
}
not_found = set()
while time.time() < breaks_at and containers:
time.sleep(args.retry_delay)
for service in list(containers):
container = containers[service]
if container.id.startswith(my_id):
containers.pop(service)
continue
try:
container.reload()
except docker.errors.NotFound:
if service in not_found:
log.error('Container %s not found', service)
containers.pop(service)
else:
# give a chance to start
not_found.add(service)
continue
# check the restart policy first
config = container.attrs.get("HostConfig", {}) or {}
policy = config.get("RestartPolicy", {}) or {}
if policy.get("Name") == "no":
# ignore if the container is allowed to crash
log.debug('Ignoring %s. restart: no', service)
containers.pop(service)
continue
labels = container.labels
traefik_labels = {
k: v for k, v in labels.items() if k.startswith('traefik')
}
use_traefik = any(list(traefik_labels))
if service.startswith(('mysql', 'mariadb', 'postgresql')):
# handle databases
cmd = None
if service.startswith(('mysql', 'mariadb')):
password = env.get('MYSQL_ROOT_PASSWORD')
if password:
cmd = (
'mysql -u root --password=%s -e "SELECT 1+1;"'
) % password
else:
msg = 'No MYSQL_ROOT_PASSWORD'
elif service.startswith('postgresql'):
s = service.replace('postgresql', 'postgres')
user_key = '%s_USER' % s.upper()
u = env.get(user_key)
if u:
u = {'u': u}
cmd = r"psql -U %(u)s -w -c 'SELECT 1+1;' %(u)s" % u
else:
msg = 'No %s available' % user_key
if cmd:
rc = container.exec_run(cmd)
if rc.exit_code != 0:
msg = rc.output.decode('utf8', errors='replace')
log.debug('%s still failing: %s',
service, msg.strip())
else:
log.info('%s is accepting connections' % service)
containers.pop(service)
continue
else:
log.error('Cant check %s status. %s in environment.',
service, msg)
elif use_traefik:
try:
ip = socket.gethostbyname(service)
except Exception:
log.debug('%s does not resolve' % service)
continue
# check if traefik_rules are available in traefik providers
for service_url in SERVICES_URL.values():
resp = requests.get(service_url, timeout=2)
if resp.status_code == 200:
break
if ip not in resp.text:
log.debug('No traefik provider found for %s (%s)',
service, ip)
continue
config = container.attrs['Config']
ports = config.get('ExposedPorts') or []
for label, value in traefik_labels.items():
# check for traefik.port
if label == 'traefik.port':
ports = ['%s/tcp' % value]
if len(ports) > 1:
# handle http ports
if '80/tcp' in ports:
ports = ['80/tcp']
elif '8080/tcp' in ports:
ports = ['8080/tcp']
else:
# dont mess with multiple ports/non http
# services...
containers.pop(service)
continue
port = list(ports)[0]
port, proto = port.split('/')
if proto != 'tcp':
# dont mess with weird protos...
containers.pop(service)
continue
url = 'http://%s:%s' % (service, port)
try:
resp = requests.head(url, timeout=args.retry_delay)
log.debug(
'%s: %s/tcp (%s %s)',
service, port, resp.status_code, resp.reason)
except Exception as e:
log.debug('%s %s => %r',
service, url, e)
continue
else:
if str(resp.status_code)[0] in '12345':
log.info(
'%s is accepting connections on %s/tcp (%s %s)',
service, port, resp.status_code, resp.reason)
containers.pop(service)
continue
elif container.status == 'running':
log.debug(service + ' is ' + container.status)
containers.pop(service)
continue
# sleep a bit so traefik handle all connections
time.sleep(1)
duration = int(time.time()) - start
if containers:
log.info('Some services are still failing after %ss... (%s)',
duration, ', '.join(containers))
return 1
else:
log.info('All services are ready! Lets go! (%ss)', duration)
return 0
if __name__ == '__main__':
sys.exit(main())