Fix some bugs when testing opensds ansible
[stor4nfv.git] / src / ceph / src / ceph-volume / ceph_volume / decorators.py
1 import os
2 import sys
3 from ceph_volume import terminal, exceptions
4 from functools import wraps
5
6
7 def 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):
14         if not os.getuid() == 0:
15             raise exceptions.SuperUserError()
16         return func(*a, **kw)
17     return is_root
18
19
20 def 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()
32                 print "Success!"
33             except TypeError, exc:
34                 print "Error while handling some call: %s" % exc
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()
42             print "Success!"
43
44     If multiple exceptions need to be catched they need to be provided as a
45     tuple::
46
47         @catches((TypeError, AttributeError))
48         def bar():
49             some_call()
50             print "Success!"
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:
61                 import logging
62                 logger = logging.getLogger('ceph_volume')
63                 logger.exception('exception caught by decorator')
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
81 def 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__)