-
Notifications
You must be signed in to change notification settings - Fork 0
/
cephfs-quota
309 lines (256 loc) · 9.43 KB
/
cephfs-quota
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
#!/usr/bin/env python3
import os
import pwd
import sys
import glob
import math
import re
import psutil
import argparse
from configparser import SafeConfigParser
from tabulate import tabulate
from enum import Enum
config_file = '/etc/ceph-quota.ini'
if not os.path.isfile(config_file):
print('Cannot find ' + config_file + ' file')
exit(1)
class Types(str, Enum):
files = 'files'
space = 'space'
used = 'used'
usage = 'usage'
limit = 'limit'
path = 'path'
def __str__(self):
return self.value
class Shorts(str, Enum):
space = 'Used Space'
files = 'Used Files'
space_usage = 'Space Usage'
files_usage = 'Files Usage'
space_limit = 'Space Limit'
files_limit = 'Files Limit'
def __str__(self):
return self.name
@staticmethod
def from_string(s):
try:
return Shorts[s]
except KeyError:
raise ValueError()
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
config = SafeConfigParser(allow_no_value=True)
config.read(config_file)
parser = MyParser(
description='CephFS quota utility',
prog='cephfs-quota',
usage='%(prog)s [options]')
parser.add_argument('user',
metavar='USERNAME', type=str,
help='The user name for which the quota is to be checked')
parser.add_argument('-b', '--blame',
help='Show list of subdirectories sorted by utilization',
default=False, required=False,
action='store_true')
parser.add_argument('-R', '--raw',
help='Show quota info in raw (bytes) data',
default=False, required=False,
action='store_true')
parser.add_argument('--short',
type=Shorts.from_string, choices=list(Shorts),
help='Show only requested value',
default=None, required=False, nargs='+')
parser.add_argument('-s', '--select',
type=Types, choices=list(Types),
help='Show only requested quota info',
default=None, required=False, nargs='+')
parser.add_argument('-d', '--depth',
metavar='N',
type=int, default=1,
help='Depth of subdirectories to check by BLAME option',
required=False)
parser.add_argument('-r', '--results',
metavar='N',
type=int, default=5,
help='Number of results returned by BLAME option',
required=False)
parser.add_argument('-f', '--files',
help='Sort Blame result by files instead of space',
default=False, required=False,
action='store_true')
args = parser.parse_args()
def progress(count, total=100):
if count <= 20.0:
color = '\33[92m'
elif count <= 40.0:
color = '\33[94m'
elif count <= 70.0:
color = '\33[93m'
else:
color = '\33[91m'
c_end = '\33[0m'
bar_len = 10
if count > total:
filled_len = bar_len
else:
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = color + '█' * filled_len + c_end + '-' * (bar_len - filled_len)
return '[%s] %s%s' % (bar, percents, '%')
def iec(size, is_bytes=True):
if size == 0:
if is_bytes:
return "0B"
else:
return "0"
if is_bytes:
size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
else:
size_name = ("", "K", "M", "G", "T", "P", "E", "Z", "Y")
if is_bytes:
i = int(math.floor(math.log(size, 1024)))
p = math.pow(1024, i)
else:
i = int(math.floor(math.log(size, 1000)))
p = math.pow(1000, i)
s = round(size / p, 2)
return '%s%s' % ('{0:g}'.format(s), size_name[i])
def get_cur_quota(path, limit):
try:
_quota = int(os.getxattr(path, limit))
except IOError:
_quota = 0
return _quota
def subdirs_usage(user, depth):
_sdir_data = []
for path in get_quota_dirs():
_u_path = path + '/' + user
if os.path.isdir(_u_path):
_rbytes = 'ceph.dir.rbytes'
_files = 'ceph.dir.rentries'
_s_list = glob.glob(_u_path + depth * '/*')
_s_list += glob.glob(_u_path + depth * '/.*')
_exclude = config['main']['blame_exclude']
_f_list = filter(lambda x: not re.search(_exclude, x), _s_list)
for sdir in _f_list:
try:
if os.path.isdir(sdir) and not os.path.islink(sdir):
_sdata = {}
_sdata['Largest subdirectories'] = sdir
_sdir_bytes = get_cur_quota(sdir, _rbytes)
_sdir_files = get_cur_quota(sdir, _files)
_sdata['Space'] = _sdir_bytes
_sdata['Files'] = _sdir_files
_sdir_data.append(_sdata)
except IOError:
pass
if args.files:
_sorted = sorted(_sdir_data, key=lambda d: d['Files'],
reverse=True)[:args.results]
else:
_sorted = sorted(_sdir_data, key=lambda d: d['Space'],
reverse=True)[:args.results]
if not args.raw:
for _subdir in _sorted:
_subdir['Space'] = iec(_subdir['Space'])
_subdir['Files'] = iec(_subdir['Files'], False)
if args.select:
pattern = re.compile('|'.join(args.select), re.IGNORECASE)
keys = {key for key, value in _sorted.items() if not pattern.findall(key)}
for key in keys:
_sorted.pop(key, None)
return _sorted
def get_quota_dirs():
_dirs = []
for section in config.sections():
if '/' in section:
if os.path.ismount(section):
if get_fstype(section) == 'ceph':
_dirs.append(section)
else:
print('Skipped: ' + section + ' is not a CephFS!')
else:
print('Skipped: ' + section + ' is not a mount point!')
if _dirs:
return _dirs
else:
print('No valid CephFS share was found!')
print('Check config file and mount points in system!')
exit(1)
def get_fstype(path):
for part in psutil.disk_partitions(all=True):
if part.mountpoint == path:
return part.fstype
def user_exist(user):
try:
pwd.getpwnam(user)
except KeyError:
print('User ' + user + ' does not exist.')
return False
return True
def tab_print(data):
print(tabulate(data, headers="keys",
tablefmt="fancy_grid", floatfmt=(".1f")))
def percent(x, y):
try:
return (x / y) * 100
except ZeroDivisionError:
return 0
def get_user_utilization(user):
_rbytes = 'ceph.dir.rbytes'
_files = 'ceph.dir.rentries'
_max_bytes = 'ceph.quota.max_bytes'
_max_files = 'ceph.quota.max_files'
_user_data = []
if user_exist(user):
for path in get_quota_dirs():
_u_path = path + '/' + user
if os.path.isdir(_u_path):
_data = {}
_data['Path'] = _u_path
_d_bytes = get_cur_quota(_u_path, _rbytes)
_d_files = get_cur_quota(_u_path, _files)
_m_bytes = get_cur_quota(_u_path, _max_bytes)
_m_files = get_cur_quota(_u_path, _max_files)
if args.raw:
_data['Used Space'] = _d_bytes
_data['Used Files'] = _d_files
_data['Space Limit'] = _m_bytes
_data['Files Limit'] = _m_files
else:
_data['Used Space'] = iec(_d_bytes)
_data['Used Files'] = iec(_d_files, False)
_data['Space Limit'] = iec(_m_bytes)
_data['Files Limit'] = iec(_m_files, False)
_data['Space Usage'] = progress(percent(_d_bytes, _m_bytes))
_data['Files Usage'] = progress(percent(_d_files, _m_files))
if args.select:
pattern = re.compile('|'.join(args.select), re.IGNORECASE)
keys = {key for key, value in _data.items() if not pattern.findall(key)}
for key in keys:
_data.pop(key, None)
_user_data.append(_data)
return _user_data
if os.geteuid() != 0:
print("Script not started as root. Running sudo..")
args = ['sudo', sys.executable] + sys.argv + [os.environ]
os.execlpe('sudo', *args)
if args.short:
for item in args.short:
print(get_user_utilization(args.user)[0][item.value])
else:
tab_print(get_user_utilization(args.user))
if args.blame:
if args.short:
for item in args.short:
for _sdir in subdirs_usage(args.user, args.depth):
if re.findall('Space', item):
print("%s %s" % (_sdir['Largest subdirectories'],_sdir[re.findall('Space', item)[0]]))
else:
print("%s %s" % (_sdir['Largest subdirectories'],_sdir[re.findall('Files', item)[0]]))
else:
tab_print(subdirs_usage(args.user, args.depth))