Skip to content

Commit f3c5740

Browse files
committed
chore: wait for name resolution
1 parent 3433529 commit f3c5740

File tree

1 file changed

+28
-1
lines changed

1 file changed

+28
-1
lines changed

scripts/init-realm/init-realm.py

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@
2424
import os
2525
from typing import Dict, List
2626

27+
import requests
28+
from requests.exceptions import ConnectionError, SSLError
2729
from keycloak import KeycloakAdmin
2830
from keycloak.exceptions import (
2931
KeycloakConnectionError,
@@ -35,6 +37,7 @@
3537

3638
logging.basicConfig(level=logging.INFO)
3739

40+
3841
def _check_existing(existing_object: Dict, new_object: Dict, case, id_key) -> bool:
3942
"""
4043
Compare the new object to the existing one, warn about mismatches. Return True if there are mismatches.
@@ -183,6 +186,26 @@ def _check_and_create_user(keycloak_admin, new_user):
183186
logging.info("done")
184187

185188

189+
def _wait_for_tls(url: str, retries=60, wait_secs=2):
190+
"""Keeps calling the url and waits in between retries until the name resolution and TLS works."""
191+
logging.info("Waiting for name resolution and TLS.")
192+
cur_retry = 1
193+
while True:
194+
try:
195+
requests.get(url, allow_redirects=True)
196+
except (ConnectionError, SSLError) as err:
197+
if cur_retry >= retries:
198+
raise Exception(
199+
"Timed out trying to wait for name resolution or TLS"
200+
) from err
201+
logging.warning("Failed name resolution or TLS, will wait and retry.")
202+
time.sleep(wait_secs)
203+
else:
204+
break
205+
finally:
206+
cur_retry += 1
207+
208+
186209
# The actual script
187210

188211
parser = argparse.ArgumentParser()
@@ -221,14 +244,18 @@ def _check_and_create_user(keycloak_admin, new_user):
221244
n_attempts = 0
222245
success = False
223246

247+
server_url = args.keycloak_url if args.keycloak_url.endswith("/") else args.keycloak_url + "/"
248+
249+
_wait_for_tls(server_url)
250+
224251
while not success and n_attempts < 31:
225252
try:
226253
logging.info("Getting an admin access token for Keycloak...")
227254
# NOTE: The keycloak python library does not follow redirect fully so passing in
228255
# "http://dev.renku.ch/auth" without the trailing "/" will fail with a 405 whereas
229256
# "http://dev.renku.ch/auth/" will work without a problem.
230257
keycloak_admin = KeycloakAdmin(
231-
server_url=args.keycloak_url if args.keycloak_url.endswith("/") else args.keycloak_url + "/",
258+
server_url=server_url,
232259
username=args.admin_user,
233260
password=keycloak_admin_password,
234261
verify=True,

0 commit comments

Comments
 (0)