]> git.proxmox.com Git - ceph.git/blob - ceph/src/pybind/mgr/mgr_util.py
import 14.2.4 nautilus point release
[ceph.git] / ceph / src / pybind / mgr / mgr_util.py
1 import contextlib
2 import socket
3
4 (
5 BLACK,
6 RED,
7 GREEN,
8 YELLOW,
9 BLUE,
10 MAGENTA,
11 CYAN,
12 GRAY
13 ) = range(8)
14
15 RESET_SEQ = "\033[0m"
16 COLOR_SEQ = "\033[1;%dm"
17 COLOR_DARK_SEQ = "\033[0;%dm"
18 BOLD_SEQ = "\033[1m"
19 UNDERLINE_SEQ = "\033[4m"
20
21
22 def colorize(msg, color, dark=False):
23 """
24 Decorate `msg` with escape sequences to give the requested color
25 """
26 return (COLOR_DARK_SEQ if dark else COLOR_SEQ) % (30 + color) \
27 + msg + RESET_SEQ
28
29
30 def bold(msg):
31 """
32 Decorate `msg` with escape sequences to make it appear bold
33 """
34 return BOLD_SEQ + msg + RESET_SEQ
35
36
37 def format_units(n, width, colored, decimal):
38 """
39 Format a number without units, so as to fit into `width` characters, substituting
40 an appropriate unit suffix.
41
42 Use decimal for dimensionless things, use base 2 (decimal=False) for byte sizes/rates.
43 """
44
45 factor = 1000 if decimal else 1024
46 units = [' ', 'k', 'M', 'G', 'T', 'P', 'E']
47 unit = 0
48 while len("%s" % (int(n) // (factor**unit))) > width - 1:
49 unit += 1
50
51 if unit > 0:
52 truncated_float = ("%f" % (n / (float(factor) ** unit)))[0:width - 1]
53 if truncated_float[-1] == '.':
54 truncated_float = " " + truncated_float[0:-1]
55 else:
56 truncated_float = "%{wid}d".format(wid=width - 1) % n
57 formatted = "%s%s" % (truncated_float, units[unit])
58
59 if colored:
60 if n == 0:
61 color = BLACK, False
62 else:
63 color = YELLOW, False
64 return bold(colorize(formatted[0:-1], color[0], color[1])) \
65 + bold(colorize(formatted[-1], BLACK, False))
66 else:
67 return formatted
68
69
70 def format_dimless(n, width, colored=True):
71 return format_units(n, width, colored, decimal=True)
72
73
74 def format_bytes(n, width, colored=True):
75 return format_units(n, width, colored, decimal=False)
76
77
78 def merge_dicts(*args):
79 # type: (dict) -> dict
80 """
81 >>> assert merge_dicts({1:2}, {3:4}) == {1:2, 3:4}
82 You can also overwrite keys:
83 >>> assert merge_dicts({1:2}, {1:4}) == {1:4}
84 :rtype: dict[str, Any]
85 """
86 ret = {}
87 for arg in args:
88 ret.update(arg)
89 return ret
90
91
92 def get_default_addr():
93 def is_ipv6_enabled():
94 try:
95 sock = socket.socket(socket.AF_INET6)
96 with contextlib.closing(sock):
97 sock.bind(("::1", 0))
98 return True
99 except (AttributeError, socket.error) as e:
100 return False
101
102 try:
103 return get_default_addr.result
104 except AttributeError:
105 result = '::' if is_ipv6_enabled() else '0.0.0.0'
106 get_default_addr.result = result
107 return result
108