Last active
July 1, 2021 16:37
-
-
Save epeters3/cb1147145e5b4b09e4b92ef0a56e4186 to your computer and use it in GitHub Desktop.
Error-handling middleware for the docker-compose CLI. Greps through the stdout of a docker-compose command, finding the highest exit code produced by any services that exited prematurely. After docker-compose exits, prints the message associated with that highest code then exits with that code. Useful when you want to exit with an error code if …
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
Error-handling middleware for the docker-compose CLI. Greps through the stdout of a docker-compose command, | |
finding the highest exit code produced by any services that exited prematurely. After docker-compose | |
exits, prints the message associated with that highest code then exits with that code. Useful | |
when you want to exit with an error code if *any* of your containers fail, and not just if the one | |
specified by `--exit-code-from` fails. | |
Example usage: | |
``` | |
docker-compose up --abort-on-container-exit | python3 <this-script>.py | |
``` | |
""" | |
import re | |
import sys | |
def watch_then_exit_with_highest(): | |
highest_exit_code = 0 | |
exit_msg = "Shield detected no errors. Docker Compose completed successfully." | |
for line in sys.stdin: | |
# Matches "<docker-container-name> exited with code <code>" | |
match = re.search(r"^\S+\sexited with code (\d+)$", line) | |
if match: | |
exit_code = int(match.group(1)) | |
if exit_code > highest_exit_code: | |
highest_exit_code = exit_code | |
exit_msg = line | |
sys.stdout.write(line) | |
return highest_exit_code, exit_msg.strip() | |
if __name__ == "__main__": | |
code, msg = watch_then_exit_with_highest() | |
if code > 0: | |
print( | |
f"Shield exiting with error code {code}, since this line was produced by docker compose:\n{msg}", | |
file=sys.stderr | |
) | |
else: | |
print(msg) | |
sys.exit(code) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment