This repository has been archived by the owner on Aug 22, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
error_handling.py
75 lines (60 loc) · 2.61 KB
/
error_handling.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
import functools
import sys
from tempfile import NamedTemporaryFile
from traceback import format_exception
from botocore.exceptions import ClientError, NoCredentialsError
def store_exception(exception: Exception) -> str:
"""
Stores the exception in a temporary file and returns its filename
"""
tracebacks = format_exception(etype=type(exception), value=exception, tb=exception.__traceback__) # type: [str]
content = "".join(tracebacks)
with NamedTemporaryFile(prefix="piu-traceback-", delete=False) as error_file:
file_name = error_file.name
error_file.write(content.encode())
return file_name
def is_credentials_expired_error(e: ClientError) -> bool:
return e.response["Error"]["Code"] in ["ExpiredToken", "RequestExpired"]
def is_permissions_error(e: ClientError) -> bool:
return (
e.response["Error"]["Code"] == "AccessDeniedException"
and "ec2-instance-connect" in e.response["Error"]["Message"]
)
def handle_exceptions(func):
@functools.wraps(func)
def wrapper():
try:
func()
except NoCredentialsError as e:
print(
'No AWS credentials found. Use the "zaws" command-line tool to get a temporary access key\n'
"or manually configure either ~/.aws/credentials or AWS_ACCESS_KEY_ID/AWS_SECRET_ACCESS_KEY.",
file=sys.stderr,
)
sys.exit(1)
except ClientError as e:
sys.stdout.flush()
if is_credentials_expired_error(e):
print(
"AWS credentials have expired.\n"
'Use the "zaws" command line tool to get a new temporary access key.',
file=sys.stderr,
)
sys.exit(1)
elif is_permissions_error(e):
print(
"Are you allowed to use SSH access in this account. If this is a Kubernetes account"
" please consider using alternate access methods as described in the documentation "
"https://cloud.docs.zalando.net/howtos/access-private-resources/"
)
sys.exit(1)
else:
file_name = store_exception(e)
print("Unknown Error.\n" "Please create an issue with the content of {fn}".format(fn=file_name))
sys.exit(1)
except Exception as e:
# Catch All
file_name = store_exception(e)
print("Unknown Error.\n" "Please create an issue with the content of {fn}".format(fn=file_name))
sys.exit(1)
return wrapper