]> git.proxmox.com Git - ceph.git/blame - ceph/src/ceph-volume/ceph_volume/decorators.py
update ceph source to reef 18.2.0
[ceph.git] / ceph / src / ceph-volume / ceph_volume / decorators.py
CommitLineData
d2e6a577
FG
1import os
2import sys
3from ceph_volume import terminal, exceptions
4from functools import wraps
5
6
7def needs_root(func):
8 """
9 Check for super user privileges on functions/methods. Raise
10 ``SuperUserError`` with a nice message.
11 """
12 @wraps(func)
13 def is_root(*a, **kw):
20effc67 14 if not os.getuid() == 0 and not os.environ.get('CEPH_VOLUME_SKIP_NEEDS_ROOT', False):
d2e6a577
FG
15 raise exceptions.SuperUserError()
16 return func(*a, **kw)
17 return is_root
18
19
20def catches(catch=None, handler=None, exit=True):
21 """
22 Very simple decorator that tries any of the exception(s) passed in as
23 a single exception class or tuple (containing multiple ones) returning the
24 exception message and optionally handling the problem if it rises with the
25 handler if it is provided.
26
27 So instead of douing something like this::
28
29 def bar():
30 try:
31 some_call()
9f95a23c 32 print("Success!")
d2e6a577 33 except TypeError, exc:
9f95a23c 34 print("Error while handling some call: %s" % exc)
d2e6a577
FG
35 sys.exit(1)
36
37 You would need to decorate it like this to have the same effect::
38
39 @catches(TypeError)
40 def bar():
41 some_call()
9f95a23c 42 print("Success!")
d2e6a577 43
11fdf7f2 44 If multiple exceptions need to be caught they need to be provided as a
d2e6a577
FG
45 tuple::
46
47 @catches((TypeError, AttributeError))
48 def bar():
49 some_call()
9f95a23c 50 print("Success!")
d2e6a577
FG
51 """
52 catch = catch or Exception
53
54 def decorate(f):
55
56 @wraps(f)
57 def newfunc(*a, **kw):
58 try:
59 return f(*a, **kw)
60 except catch as e:
3efd9988
FG
61 import logging
62 logger = logging.getLogger('ceph_volume')
63 logger.exception('exception caught by decorator')
d2e6a577
FG
64 if os.environ.get('CEPH_VOLUME_DEBUG'):
65 raise
66 if handler:
67 return handler(e)
68 else:
69 sys.stderr.write(make_exception_message(e))
70 if exit:
71 sys.exit(1)
72 return newfunc
73
74 return decorate
75
76#
77# Decorator helpers
78#
79
80
81def make_exception_message(exc):
82 """
83 An exception is passed in and this function
84 returns the proper string depending on the result
85 so it is readable enough.
86 """
87 if str(exc):
88 return '%s %s: %s\n' % (terminal.red_arrow, exc.__class__.__name__, exc)
89 else:
90 return '%s %s\n' % (terminal.red_arrow, exc.__class__.__name__)