Skip to content

Commit 1ed4382

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

File tree

1 file changed

+29
-1
lines changed

1 file changed

+29
-1
lines changed

scripts/init-realm/init-realm.py

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,9 @@
2323
import logging
2424
import os
2525
from typing import Dict, List
26+
from urllib3.exceptions import NameResolutionError, SSLError
2627

28+
import requests
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,27 @@ def _check_and_create_user(keycloak_admin, new_user):
183186
logging.info("done")
184187

185188

189+
def _wait_for_tls(url: str, retries=10, 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)
196+
except (NameResolutionError, 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+
continue
204+
else:
205+
break
206+
finally:
207+
cur_retry += 1
208+
209+
186210
# The actual script
187211

188212
parser = argparse.ArgumentParser()
@@ -221,14 +245,18 @@ def _check_and_create_user(keycloak_admin, new_user):
221245
n_attempts = 0
222246
success = False
223247

248+
server_url = args.keycloak_url if args.keycloak_url.endswith("/") else args.keycloak_url + "/"
249+
250+
_wait_for_tls(server_url)
251+
224252
while not success and n_attempts < 31:
225253
try:
226254
logging.info("Getting an admin access token for Keycloak...")
227255
# NOTE: The keycloak python library does not follow redirect fully so passing in
228256
# "http://dev.renku.ch/auth" without the trailing "/" will fail with a 405 whereas
229257
# "http://dev.renku.ch/auth/" will work without a problem.
230258
keycloak_admin = KeycloakAdmin(
231-
server_url=args.keycloak_url if args.keycloak_url.endswith("/") else args.keycloak_url + "/",
259+
server_url=server_url,
232260
username=args.admin_user,
233261
password=keycloak_admin_password,
234262
verify=True,

0 commit comments

Comments
 (0)