-
Notifications
You must be signed in to change notification settings - Fork 2
/
getquota.py
executable file
·831 lines (625 loc) · 28.3 KB
/
getquota.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
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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
#!/usr/bin/env python3
import fcntl
import getpass
import grp
import os
import pickle
import json
import pwd
import re
import shlex
import stat
import subprocess
import argparse
import sys
import time
from datetime import datetime
from threading import Timer
gpfs_device_names = {'/gpfs/ysm': 'ysm-gpfs',
'/gpfs/gibbs': 'gibbs',
'/gpfs/slayman': 'slayman',
'/gpfs/milgram': 'milgram',
'/gpfs/ycga': 'ycga',
'/gpfs/radev': 'radev',
}
common_filespaces = {'grace': ['home.grace', 'project', 'scratch'],
'mccleary': ['home.mccleary', 'project', 'scratch'],
'farnam': ['home', 'project', 'scratch60'],
'ruddle': ['home', 'project', 'scratch60'],
'milgram': ['home', 'project', 'scratch60'],
'misha': ['home','project','scratch'],
}
#### TO DO #####
""""
- refactor all general "fileset" logic to accomodate home, scratch not on GPFS
- refactor "this_filesystem" to be a dictionary that contains all filesets on that filesystem
"""
def get_args():
global debug
global active_users_only
is_me = False
parser = argparse.ArgumentParser(
prog = 'getquota',
description = 'Reports storage usage and quotas of YCRC HPCs. Use -u <user>, -g <group> or no argument for current user"',
epilog = 'For issues and questions, contact hpc@yale.edu')
parser.add_argument('-d', '--debug', action='store_true', help='debug mode')
parser.add_argument('-a', '--active-users', action='store_true',
help='only display usage for active users')
parser.add_argument('-u', '--user', help='usage and quotas for specific user')
parser.add_argument('-g', '--group', help='usage and quotas for specific group')
parser.add_argument('-c', '--cluster', default=get_cluster(),
help='usage and quotas on alternate cluster')
args = parser.parse_args()
debug = args.debug
active_users_only = args.active_users
group = {}
if args.group is None:
if args.user is None:
# get current user
user = getpass.getuser()
is_me = True
else:
user = args.user
# make sure user is valid, and if so get gid
try:
group['id'] = pwd.getpwnam(user).pw_gid
except:
sys.exit('Unknown user: '+user)
else:
# make sure group is valid, and if so get gid
try:
group['id'] = grp.getgrnam(args.group).gr_gid
except:
sys.exit('Unknown group: '+args.group)
# if group is set, no user is set
user = None
## REMOVE ME
print_format='cli'
return user, group, args.cluster, is_me, print_format
def get_cluster():
with open('/etc/yalehpc', 'r') as f:
cluster = f.readline().split('=')[1].replace('"', '').rstrip()
return cluster
def get_group_members(group, cluster):
global active_users_only
with open('/etc/yalehpc', 'r') as f:
f.readline()
mgt = f.readline().split('=')[1].replace('"', '').rstrip()
query = "LDAPTLS_REQCERT=never ldapsearch -xLLL -H ldaps://{0} -b o=hpc.yale.edu -D".format(mgt)
query += " cn=client,o=hpc.yale.edu -w hpc@Client"
if active_users_only:
query += " '(& ({0}HomeDirectory=*) (gidNumber={1}))'".format(cluster, group['id'])
else:
query += " '(gidNumber={0})'".format(group['id'])
query += " uid | grep '^uid'"
result = subprocess.check_output([query], shell=True, encoding='UTF-8')
group['members'] = result.replace('uid: ', '').split('\n')
# remove blank line
if group['members'][-1] == '':
group['members'].pop(-1)
## remove
# return group_membes
### ADAM'S CACHING ###
# try to end something cleanly, ..for whatever reason
def kill_cmd(cmd):
try:
cmd.stdout.close()
cmd.stderr.close()
cmd.kill()
except:
pass
# try to read something, ..but don't assume that you can
def nonblocking_read(output):
try:
fd = output.fileno()
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
out = output.read()
if out is not None:
return out
else:
return b''
except:
return b''
# run something, but discard any errors it may generate and give it a 4-second deadline to complete
def external_program_filter(cmd):
timeout = 4
result = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
timer = Timer(timeout, kill_cmd, [result])
timer.start()
command_output = ''
while result.poll() is None:
time.sleep(0.5)
command_output += str(nonblocking_read(result.stdout).decode("utf-8"))
timer.cancel()
return (command_output)
def localcache_quota_data(user):
output = ''
if os.path.isfile('/tmp/.'+user+'gqlc'):
lcmtime = time.time() - os.stat('/tmp/.'+user+'gqlc')[stat.ST_MTIME]
if lcmtime > 0 and lcmtime <= 300:
file = open('/tmp/.%s' % user+'gqlc', 'r')
output = pickle.load(file)
return output
### END ADAM'S CACHING ###
## PI FILESET CHECKS
def add_missing_pi_filesets(user_filesets, group, filesets_by_filesystems):
# fix for forcing pi filesets to show up for all primary group members
for fileset in sum(filesets_by_filesystems.values(), []):
#if group in fileset and fileset not in user_filesets:
if re.search(rf"[^:]+?:pi_{group['name']}$", fileset) and fileset not in user_filesets:
user_filesets.append(fileset)
def is_pi_fileset(fileset, section=None):
# only applicable for GPFS
if section is not None and 'FILESET' not in section:
return False
if 'pi' in fileset:
return True
elif 'scratch' in fileset or 'home' in fileset or 'project' in fileset or 'work' in fileset:
return False
elif 'apps' in fileset:
return False
else:
return True
### HELPER FUNCTIONS
def prefix_filesystem(filesystem, fileset):
if 'gpfs' in filesystem:
fileset = filesystem.replace('/gpfs/', '')+':'+fileset
elif 'vast' in filesystem:
if fileset == 'scratch':
fileset = 'palmer:'+fileset
else:
sys.exit('Unknown filesystem: ', filesystem)
return fileset
def place_output(output, section, fileset):
if 'home' in fileset:
output[0] = section
elif 'project' in fileset and 'pi' not in fileset:
output[1] = section
# scratch60
elif 'scratch' in fileset:
output[2] = section
elif fileset == 'ycga:work':
output.append(section)
### COLLECT USAGE DATA AND QUOTAS
##### GPFS
def parse_gpfs_mmrepquota_line(line, details, filesystem):
split = line.split(':')
# Fileset
quota_type = split[7]
if quota_type == 'FILESET':
# name
fileset = split[9]
name = ''
else:
# name
name = split[9]
fileset = split[-2]
fileset = prefix_filesystem(filesystem, fileset)
# blockUsage+blockInDoubt, blockQuota
# filesUsage+filesInDoubt, filesQuota
data = [fileset, name, quota_type, int(split[10])/1024/1024+int(split[13])/1024/1024, int(split[12])/1024/1024,
int(split[15])+int(split[18]), int(split[17])]
return fileset, name, data
def read_mmrepquota_gpfs(filesystem, this_user, cluster, group, usage_details, user_filesets, all_filesets):
filename = filesystem + '/.mmrepquota/current'
if not os.path.exists(filename):
print("%s is not available at the moment" % filesystem)
else:
with open(filename, 'r') as f:
f.readline()
for line in f:
if 'USR' not in line or 'root' in line or 'apps' in line:
continue
fileset, user, user_data = parse_gpfs_mmrepquota_line(line, True, filesystem)
if fileset == 'gibbs:project' and cluster in ['ruddle', 'farnam']:
continue
if fileset == 'milgram:globus':
continue
if fileset not in usage_details.keys():
usage_details[fileset] = {}
usage_details[fileset][user] = user_data
if user == this_user or (this_user is None and user in group['members']):
user_filesets.add(fileset)
if fileset not in all_filesets:
all_filesets.append(fileset)
def validate_gpfs_returned_values(result):
if not re.match("^mmlsq", result):
if debug:
print("Invalid results returned:", result)
return None
else:
return result
def live_quota_data_gpfs(filesets, filesystem, all_filesets, user, group, cluster, output):
global debug
quota_script = '/usr/lpp/mmfs/bin/mmlsquota'
# get group level usage
device = gpfs_device_names[filesystem]
query = '{0} -g {1} -Y --block-size auto {2}'.format(quota_script, group['name'], device)
if debug:
result = subprocess.check_output([query], shell=True, encoding='UTF-8')
else:
result = external_program_filter(query)
# user based home quotas
if device not in ['slayman', 'gibbs']:
query = '{0} -u {1} -Y --block-size auto {2} '.format(quota_script, user, device)
if debug:
result += subprocess.check_output([query], shell=True, encoding='UTF-8')
else:
result += external_program_filter(query)
# make sure that result thus far holds valid data
result = validate_gpfs_returned_values(result)
for quota in result.split('\n'):
if 'HEADER' in quota or 'root' in quota or 'apps' in quota or len(quota) < 10:
continue
if ('USR' in quota and 'home' not in quota):
continue
if (device == 'gibbs' and 'project' in quota and cluster in ['ruddle', 'farnam']):
continue
fileset, _, section = parse_gpfs_mmrepquota_line(quota, False, filesystem)
place_output(output, section, fileset)
# now add pi filesets previously identified in read_mmrepquota_gpfs and add_missing_pi_filesets
for fileset in filesets:
# check if this fileset is on this device
if is_pi_fileset(fileset):
# check if this fileset is on this device
if fileset in all_filesets:
# query the local pi filesets
fileset_name = re.search('[^:]+?:(.*):', fileset).group(1)
query = '{0} -j {1} -Y {2}'.format(quota_script, fileset_name, device)
if debug:
pi_quota = subprocess.check_output([query], shell=True, encoding='UTF-8')
else:
pi_quota = external_program_filter(query)
pi_quota = validate_gpfs_returned_values(pi_quota)
output.append(parse_gpfs_mmrepquota_line(pi_quota.split('\n')[1], False, filesystem)[-1])
return output
def cached_quota_data_gpfs(filesystem, filesets, user, group, cluster, output):
filename = filesystem + '/.mmrepquota/current'
if not os.path.exists(filename):
return output
with open(filename, 'r') as f:
f.readline()
for line in f:
if 'root' in line:
continue
fileset, name, section = parse_gpfs_mmrepquota_line(line, False, filesystem)
if fileset in filesets:
if 'home' in fileset:
if cluster == "grace":
continue
if 'USR' in line and name == user:
if filesystem == 'gibbs' and cluster in ['ruddle', 'farnam'] and fileset == 'project':
continue
place_output(output, section, fileset)
continue
if name == group['name']:
place_output(output, section, fileset)
elif is_pi_fileset(fileset, section=section):
output.append(section)
return output
### VAST
def cached_quota_data_vast(filesystem, user, group, cluster, output):
filenames = [filesystem + '/.quotas/current']
if cluster == 'mccleary':
filenames.append(filesystem + '/.quotas/mccleary_current')
if cluster == 'grace':
filenames.append(filesystem + '/.quotas/grace_current')
if user is not None:
uid = str(pwd.getpwnam(user).pw_uid)
else:
uid = ""
for filename in filenames:
if not os.path.exists(filename):
return output
with open(filename, 'r') as f:
all_quota_data = json.load(f)
for quota in all_quota_data:
if 'mccleary' in filename or 'grace' in filename:
### NOTE TO SELF: this used to be user in quota['entity_identifier'] but that was causing problems.
### not sure why i used in, but noting in case the fix introduces new/old issues.
if user is not None and (user == quota['entity_identifier'] or uid == quota['entity_identifier']):
fileset = 'palmer:home.'+cluster
### FIX: REPLACE used_effective_capacity instead of used_capacity
data = [fileset, quota['entity_identifier'], 'USR', quota['used_capacity']/1024/1024/1024,
quota['hard_limit']/1024/1024/1024, quota['used_inodes'], quota['hard_limit_inodes']]
place_output(output, data, fileset)
else:
if ':' in quota['name']:
fileset, name = quota['name'].split(':')
if group['name'] == name:
if 'scratch' in fileset:
fileset = prefix_filesystem(filesystem, fileset)
data = [fileset, group['name'], 'GRP', quota['used_effective_capacity']/1024/1024/1024,
quota['hard_limit']/1024/1024/1024, quota['used_inodes'], quota['hard_limit_inodes']]
place_output(output, data, 'scratch')
elif fileset == 'pi':
data = ['palmer:pi_'+group['name'], group['name'], 'FILESET', quota['used_effective_capacity']/1024/1024/1024,
quota['hard_limit']/1024/1024/1024, quota['used_inodes'], quota['hard_limit_inodes']]
output.append(data)
return output
# Outputs generated by cron on monitor1.grace that runs starfish_vast_usage.py
def read_vast_line(line):
data = {}
# group, username, filecount, usage (kb), usage (string)
split = line.split(',')
data['group'] = split[0]
data['user'] = split[1]
data['usage_TiB'] = int(split[3])/1024/1024/1024
data['usage_files'] = int(split[2])
return data
def read_user_details_vast(this_user, group, usage_details, user_filesets, all_filesets):
read_user_details_vast_scratch(group, usage_details, user_filesets, all_filesets)
read_user_details_vast_pi(this_user, group, usage_details, user_filesets, all_filesets)
def read_user_details_vast_scratch(group, usage_details, user_filesets, all_filesets):
# scratch
fileset = 'palmer:scratch'
usage_details[fileset] = {}
filename = '/vast/palmer/.quotas/scratch.details'
if not os.path.exists(filename):
return
with open(filename, 'r') as f:
f.readline()
for line in f:
# group, username, filecount, usage (kb), usage (string)
data = read_vast_line(line)
if data['group'] != group['name']:
continue
else:
usage_details[fileset][data['user']] = [fileset, data['user'], '', data['usage_TiB'], '', data['usage_files'], '']
user_filesets.add(fileset)
if fileset not in all_filesets:
all_filesets.append(fileset)
def read_user_details_vast_pi(this_user, group, usage_details, user_filesets, all_filesets):
# pi filesets
filename = '/vast/palmer/.quotas/pi.details'
if not os.path.exists(filename):
return
with open(filename, 'r') as f:
f.readline()
for line in f:
data = read_vast_line(line)
user = data['user']
fileset = 'palmer:pi_'+data['group']
if fileset not in usage_details.keys():
usage_details[fileset] = {}
usage_details[fileset][data['user']] = [fileset, data['user'], '', data['usage_TiB'], '', data['usage_files'], '']
if user == this_user or (this_user is None and user in group['members']):
user_filesets.add(fileset)
if fileset not in all_filesets:
all_filesets.append(fileset)
allocations = []
for fileset in user_filesets:
if 'palmer:pi_' in fileset:
allocations.append(fileset.replace('palmer:pi_', ''))
## OVERALL USAGE AND QUOTA COLLECTION
def collect_usage_details(filesystems, this_user, group, cluster):
# collects all usage details for gpfs systems
usage_details = {}
# collects list of all filesets and filesets where this_user has data
user_filesets = set()
filesets_by_filesystem = {filesystem: [] for filesystem in filesystems}
for filesystem in filesystems:
if 'gpfs' in filesystem:
read_mmrepquota_gpfs(filesystem, this_user, cluster, group,
usage_details, user_filesets, filesets_by_filesystem[filesystem])
elif 'vast' in filesystem:
if cluster in ['grace', 'mccleary']:
read_user_details_vast(this_user, group, usage_details, user_filesets, filesets_by_filesystem[filesystem])
else:
pass
return usage_details, list(user_filesets), filesets_by_filesystem
def collect_quota_data(filesets, filesets_by_filesystem, user, group, cluster, is_live):
global debug
if debug:
print("**Debug Output Enabled**")
output = ['', '', '']
for filesystem in filesets_by_filesystem.keys():
if 'gpfs' in filesystem:
if is_live:
if debug:
# if debug mode, force live query
live_quota_data_gpfs(filesets, filesystem, filesets_by_filesystem[filesystem],
user, group, cluster, output)
else:
#if not debug mode, fail over silently
try:
live_quota_data_gpfs(filesets, filesystem, filesets_by_filesystem[filesystem],
user, group, cluster, output)
except:
is_live = False
cached_quota_data_gpfs(filesystem, filesets, user, group, cluster, output)
else:
cached_quota_data_gpfs(filesystem, filesets, user, group, cluster, output)
elif 'vast' in filesystem:
# vast doesn't (yet?) return live data so just return cached data
cached_quota_data_vast(filesystem, user, group, cluster, output)
if is_live:
file = open('/tmp/.%sgqlc' % user, 'wb')
pickle.dump(output, file)
file.close()
return output
## USER BREAKDOWN ##
def compile_usage_details(filesets, group, data):
output = ['', '', '']
for fileset in sorted(filesets):
section = []
if is_pi_fileset(fileset):
for user in sorted(data[fileset].keys()):
section.append(format_for_details(data[fileset][user]))
output.append('\n'.join(section))
else:
for group_member in sorted(group['members']):
if group_member not in data[fileset].keys():
continue
else:
section.append(format_for_details(data[fileset][group_member]))
place_output(output, '\n'.join(section), fileset)
# don't show home data
output.pop(0)
for i in range(len(output)-1):
if len(output[i]) == 0:
output.pop(i)
return '\n----\n'.join(output)
### OUTPUT FORMATTING
def format_for_details(data):
# fileset, user, bytes, file count
return '{0:30.29}{1:14.13}{2:10.0f}{3:14,}'.format(data[0], data[1],
data[3], data[5])
def format_for_summary(data, cluster):
backup = 'No'
purge = 'No'
fileset = data[0]
if 'home' in fileset or cluster == 'milgram':
if 'scratch' not in fileset:
backup = 'Yes'
if 'scratch' in fileset:
purge = '60 days'
# fileset, userid, quota_type, bytes, byte quota, file count, file limit
return '{0:30.29}{1:8}{2:12.0f}{3:12.0f}{4:14,}{5:14,} {6:10}{7:10}'.format(data[0], data[2],
data[3], data[4],
data[5], data[6],
backup, purge)
### LIMIT CHECKS
def check_limits(summary_data):
at_limit = {'byte': 0,
'file': 0}
# if you can, avoid the possiblity of dividing by zero
if summary_data[4] == 0:
return at_limit
if summary_data[6] == 0:
return at_limit
if (summary_data[4]-summary_data[3])/float(summary_data[4]) <= 0.05:
at_limit['byte'] = True
if (summary_data[6]-summary_data[5])/float(summary_data[6]) <= 0.05:
at_limit['file'] = True
return at_limit
def limits_warnings(summary_data):
at_limit = check_limits(summary_data)
warnings = []
if at_limit['byte']:
warnings.append("Warning!!! You are at or near your storage limit in the %s fileset. "
"Reduce your storage usage to avoid issues." % summary_data[0])
# file limit
if at_limit['file']:
warnings.append("Warning!!! You are at or near your file count limit in the %s fileset. "
"Reduce the number of files to avoid issues." % summary_data[0])
return warnings
#### PRINT FORMATS
def get_quota_status(summary_data):
warnings = []
for summary in summary_data:
if summary:
at_limit = check_limits(summary)
if at_limit['byte']:
warnings.append([summary_data[0], summary_data[3], summary_data[4]])
if at_limit['file']:
warnings.append([summary_data[0], summary_data[5], summary_data[6]])
print(warnings)
def print_cli_output(details_data, summary_data, group, timestamp, is_live, cluster):
header = "This script shows information about your quotas on {0}.\n".format(cluster)
header += "If you plan to poll this sort of information extensively,\n"
header += "please contact us for help at hpc@yale.edu\n"
print(header)
details_header = '## Usage Details for {0} (as of {1})\n'.format(group['name'], timestamp)
details_header += '{0:30}{1:14}{2:10}{3:14}\n'.format('Fileset', 'User', 'Usage (GiB)', ' File Count')
details_header += '{0:30}{1:14}{2:10}{3:14}'.format('-'*29, '-'*13, '-'*10, ' '+'-'*13)
print(details_header)
print(details_data)
if is_live:
time = 'right now [*palmer stats are gathered once a day]'
else:
time = timestamp
summary_header = '\n## Quota Summary for {0} (as of {1})\n'.format(group['name'], time)
summary_header += '{0:30}{1:8}{2:12}{3:12}{4:14}{5:14}{6:10}{7:10}\n'.format('Fileset', 'Type', 'Usage (GiB)',
' Quota (GiB)', ' File Count',
' File Limit', ' Backup', ' Purged')
summary_header += '{0:30}{1:8}{2:12}{3:12}{4:14}{5:14}{6:10}{7:10}'.format('-'*29, '-'*7, '-'*12,
' '+'-'*11, ' '+'-'*13, ' '+'-'*13,
' '+'-'*9, ' '+'-'*9)
print(summary_header)
for summary in summary_data:
if summary:
print(format_for_summary(summary, cluster))
warnings = []
for summary in summary_data:
if summary:
warnings += limits_warnings(summary)
if len(warnings):
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!')
print('\n'.join(warnings))
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!')
def print_email_output(details_data, summary_data, group, timestamp, cluster):
header = "Our system has detected that you are approaching or have hit a \n"
header += "storage quota on {0}.\n".format(cluster)
header += "See below for details on your usage."
print(header)
warnings = []
for summary in summary_data:
if summary:
warnings += limits_warnings(summary)
if len(warnings):
print('\n'.join(warnings))
time = datetime.now().strftime("%b %d %Y, %H:%M:%S")
summary_header = '\n## Quota Summary for {0} (as of {1})\n'.format(group['name'], time)
summary_header += '{0:23}{1:8}{2:12}{3:12}{4:14}{5:14}{6:10}{7:10}\n'.format('Fileset', 'Type', 'Usage (GiB)',
' Quota (GiB)', ' File Count',
' File Limit', ' Backup', ' Purged')
summary_header += '{0:23}{1:8}{2:12}{3:12}{4:14}{5:14}{6:10}{7:10}'.format('-'*22, '-'*7, '-'*12,
' '+'-'*11, ' '+'-'*13, ' '+'-'*13,
' '+'-'*9, ' '+'-'*9)
print(summary_header)
for summary in summary_data:
if summary:
print(format_for_summary(summary, cluster))
print('\n')
details_header = '## Usage Details for {0} (as of {1})\n'.format(group['name'], timestamp)
details_header += '{0:23}{1:6}{2:10}{3:14}\n'.format('Fileset', 'User', 'Usage (GiB)', ' File Count')
details_header += '{0:23}{1:6}{2:10}{3:14}'.format('-'*22, '-'*5, '-'*10, ' '+'-'*13)
print(details_header)
print(details_data)
### MAIN ###
if (__name__ == '__main__'):
global debug
user, group, cluster, is_me, print_format = get_args()
group['name'] = grp.getgrgid(group['id']).gr_name
filesystems = {
'grace': ['/gpfs/gibbs', '/vast/palmer'],
'mccleary': ['/gpfs/gibbs', '/vast/palmer'],
'milgram': ['/gpfs/milgram'],
'misha': ['/gpfs/radev'],
'slayman': ['/gpfs/slayman'],
'gibbs': ['/gpfs/gibbs']
}
if cluster in ['mccleary'] and group_name == 'gerstein':
filesystems[cluster].append('/gpfs/slayman')
# check if user in ycga group
if cluster in ['mccleary'] and 10266 in os.getgroups():
filesystems[cluster].append('/gpfs/ycga')
# usage details
timestamp = time.strftime('%b %d %Y %H:%M', time.localtime(os.path.getmtime(filesystems[cluster][0]
+ '/.mmrepquota/current')))
get_group_members(group, cluster)
usage_data, user_filesets, filesets_by_filesystem = collect_usage_details(filesystems[cluster], user,
group, cluster)
add_missing_pi_filesets(user_filesets, group, filesets_by_filesystem)
details_data = compile_usage_details(user_filesets, group, usage_data)
is_live = False
if is_me:
is_live = True
# usage and quota summary
summary_data = None
# if is_me:
# summary_data = localcache_quota_data(user)
if summary_data is None or debug:
summary_data = collect_quota_data(user_filesets, filesets_by_filesystem,
user, group, cluster, is_live)
# print
if print_format == 'cli':
print_cli_output(details_data, summary_data, group, timestamp, is_live, cluster)
elif print_format == 'email':
print_email_output(details_data, summary_data, group, timestamp, cluster)
elif print_format == 'query':
get_quota_status(summary_data)
else:
sys.exit('unknown print format: ', print_format)