-
Notifications
You must be signed in to change notification settings - Fork 1
/
gen_ilab_upload.py
executable file
·1414 lines (1056 loc) · 52.8 KB
/
gen_ilab_upload.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
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
#===============================================================================
#
# gen_ilab_upload.py - Generate billing data for upload into iLab.
#
# ARGS:
# 1st: the BillingConfig spreadsheet.
#
# SWITCHES:
# --billing_details_file: Location of the BillingDetails.xlsx file (default=look in BillingRoot/<year>/<month>)
# --billing_root: Location of BillingRoot directory (overrides BillingConfig.xlsx)
# [default if no BillingRoot in BillingConfig.xlsx or switch given: CWD]
# --year: Year of snapshot requested. [Default is this year]
# --month: Month of snapshot requested. [Default is last month]
#
# OUTPUT:
# CSV file with billing data suitable for uploading into iLab.
# Various messages about current processing status to STDOUT.
#
# ASSUMPTIONS:
#
# AUTHOR:
# Keith Bettinger
#
#==============================================================================
#=====
#
# IMPORTS
#
#=====
import argparse
import codecs
from collections import defaultdict
import csv
import locale # for converting strings with commas into floats
import os
import re
import sys
#import xlrd
import openpyxl
# =====
#
# IMPORTS
#
# =====
import argparse
import codecs
import csv
import locale # for converting strings with commas into floats
import os
import re
import sys
from collections import defaultdict
# import xlrd
import openpyxl
# Simulate an "include billing_common.py".
SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__))
exec(compile(open(os.path.join(SCRIPT_DIR, "billing_common.py"), "rb").read(), os.path.join(SCRIPT_DIR, "billing_common.py"), 'exec'))
#=====
#
# CONSTANTS
#
#=====
# From billing_common.py
global BILLING_NOTIFS_SHEET_COLUMNS
global BILLING_AGGREG_SHEET_COLUMNS
global BILLING_DETAILS_PREFIX
global BILLING_NOTIFS_PREFIX
global GOOGLE_INVOICE_PREFIX
global ILAB_EXPORT_PREFIX
global CONSULTING_HOURS_FREE
global CONSULTING_TRAVEL_RATE_DISCOUNT
global ACCOUNT_PREFIXES
global SUBDIR_RAWDATA
global SUBDIR_EXPORTS
global BASE_STORAGE_SIZE
# Default headers for the ilab Export CSV file (if not read in from iLab template file).
DEFAULT_CSV_HEADERS = ['service_id','note','service_quantity','purchased_on',
'service_request_id','owner_email','pi_email']
#=====
#
# GLOBALS
#
#=====
#
# These globals are data structures read in from BillingConfig workbook.
#
# List of pi_tags.
pi_tag_list = []
# Mapping from usernames to list of [date, pi_tag].
username_to_pi_tag_dates = defaultdict(list)
# Mapping from usernames to a list of [email, full_name].
username_to_user_details = defaultdict(list)
# Mapping from pi_tags to list of [first_name, last_name, email].
pi_tag_to_names_email = defaultdict(list)
# Mapping from pi_tags to iLab service request IDs (1-to-1 mapping).
pi_tag_to_ilab_service_req_id = dict()
# Mapping from accounts to list of [pi_tag, %age].
account_to_pi_tag_pctages = defaultdict(list)
# Mapping from folders to list of [pi_tag, %age].
folder_to_pi_tag_pctages = defaultdict(list)
#
# These globals are data structures used to write the BillingNotification workbooks.
#
# Mapping from pi_tag to list of [folder, size, %age].
pi_tag_to_folder_sizes = defaultdict(list)
# Mapping from pi_tag to list of [account, list of [username, cpu_core_hrs, %age]].
pi_tag_to_account_username_cpus = defaultdict(list)
# Mapping from pi_tag to list of [date, username, job_name, account, cpu_core_hrs, jobID, %age].
pi_tag_to_job_details = defaultdict(list)
# Mapping from pi_tag to list of [username, date_added, date_removed, %age].
pi_tag_to_user_details = defaultdict(list)
# Mapping from pi_tag to string for their cluster service level ('Full', 'Free', 'None').
pi_tag_to_service_level = dict()
# Mapping from pi_tag to string for their affiliate status ('Stanford', 'Affiliate', 'External').
pi_tag_to_affiliation = dict()
# Mapping from pi_tag to set of (cloud account, %age) tuples.
global pi_tag_to_cloud_account_pctages
pi_tag_to_cloud_account_pctages = defaultdict(set)
# Mapping from cloud account to set of cloud project IDs (several per project possible in this set).
cloud_account_to_cloud_projects = defaultdict(set)
# Mapping from cloud account to cloud account name
cloud_account_to_account_names = dict()
# Mapping from (cloud project ID, cloud account) to lists of (platform, account, description, dates, quantity, UOM, charge) tuples.
cloud_project_account_to_cloud_details = defaultdict(list)
# Mapping from (cloud project ID, cloud account) to total charge.
cloud_project_account_to_total_charges = defaultdict(float)
# Mapping from cloud project number to cloud project ID (1-to-1 mapping).
cloud_projnum_to_cloud_project = dict()
# Mapping from cloud project ID to cloud project name (1-to-1 mapping).
cloud_projid_to_cloud_projname = dict()
# Mapping from pi_tag to list of (date, summary, hours, cumul_hours)
consulting_details = defaultdict(list)
# Set locale to be US english for converting strings with commas into floats.
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
#=====
#
# FUNCTIONS
#
#=====
# From billing_common.py
global from_timestamp_to_excel_date
global from_excel_date_to_timestamp
global from_timestamp_to_date_string
global from_excel_date_to_date_string
global from_ymd_date_to_timestamp
global from_date_string_to_timestamp
global from_timestamp_to_datetime
global from_datetime_to_timestamp
global from_datetime_to_date_string
global sheet_get_named_column
global filter_by_dates
global argparse_get_parent_parser
global argparse_get_year_month
global argparse_get_billingroot_billingconfig
global get_subdirectory
global rowcol_to_a1_cell
# This function scans the username_to_pi_tag_dates dict to create a list of [pi_tag, %age]s
# for the PIs that the given user was working for on the given date.
def get_pi_tags_for_username_by_date(username, date_timestamp):
# Add PI Tag to the list if the given date is after date_added, but before date_removed.
pi_tag_list = []
pi_tag_dates = username_to_pi_tag_dates.get(username)
if pi_tag_dates is not None:
date_excel = from_timestamp_to_datetime(date_timestamp)
for (pi_tag, date_added, date_removed, pctage) in pi_tag_dates:
if date_added <= date_excel and (date_removed == '' or date_removed is None or date_removed >= date_excel):
pi_tag_list.append([pi_tag, pctage])
return pi_tag_list
#
# Reads a subtable from the CSVFile file-object, which is all the lines
# between blank lines.
#
def get_google_invoice_csv_subtable_lines(csvfile_obj):
subtable = []
line = csvfile_obj.readline()
while not line.startswith(',') and line != '' and line != '\n':
subtable.append(line)
line = csvfile_obj.readline()
return subtable
# Creates all the data structures used to write the BillingNotification workbook.
# The overall goal is to mimic the tables of the notification sheets so that
# to build the table, all that is needed is to print out one of these data structures.
def build_global_data(billing_config_wkbk, begin_month_timestamp, end_month_timestamp, read_cloud_data):
pis_sheet = billing_config_wkbk["PIs"]
folders_sheet = billing_config_wkbk["Folders"]
users_sheet = billing_config_wkbk["Users"]
accounts_sheet = billing_config_wkbk["Accounts"]
begin_month_exceldate = from_timestamp_to_excel_date(begin_month_timestamp)
end_month_exceldate = from_timestamp_to_excel_date(end_month_timestamp)
begin_month_datetime = from_timestamp_to_datetime(begin_month_timestamp)
end_month_datetime = from_timestamp_to_datetime(end_month_timestamp)
#
# Create list of pi_tags.
#
global pi_tag_list
pi_tag_list = list(sheet_get_named_column(pis_sheet, "PI Tag"))
# Remove all empty cells from the end of the pi_tag_list
while pi_tag_list[-1] is None:
pi_tag_list = pi_tag_list[:-1]
#
# Create mapping from pi_tag to a list of PI name and email.
#
global pi_tag_to_names_email
pi_first_names = sheet_get_named_column(pis_sheet, "PI First Name")
pi_last_names = sheet_get_named_column(pis_sheet, "PI Last Name")
pi_emails = sheet_get_named_column(pis_sheet, "PI Email")
owner_emails = sheet_get_named_column(pis_sheet, "iLab Service Request Owner")
pi_details_list = list(zip(pi_first_names, pi_last_names, pi_emails, owner_emails))
pi_tag_to_names_email = dict(list(zip(pi_tag_list, pi_details_list)))
#
# Create mapping from pi_tag to iLab Service Request ID.
#
global pi_tag_to_ilab_service_req_id
pi_ilab_ids = sheet_get_named_column(pis_sheet, "iLab Service Request ID")
pi_tag_to_ilab_service_req_id = dict(list(zip(pi_tag_list, pi_ilab_ids)))
# Organize data from the Cloud sheet, if present.
if read_cloud_data:
cloud_sheet = billing_config_wkbk["Cloud Accounts"]
#
# Create mapping from pi_tag to (cloud account, %age) tuples from the BillingConfig PIs sheet.
# Create mapping from cloud account to account names
#
global pi_tag_to_cloud_account_pctages
global cloud_account_to_account_names
cloud_platforms = sheet_get_named_column(cloud_sheet, "Platform")
cloud_pi_tags = sheet_get_named_column(cloud_sheet, "PI Tag")
cloud_accounts = sheet_get_named_column(cloud_sheet, "Billing Account Number")
cloud_account_names = sheet_get_named_column(cloud_sheet, "Billing Account Name")
cloud_pctages = sheet_get_named_column(cloud_sheet, "%age")
cloud_dates_added = sheet_get_named_column(cloud_sheet, "Date Added")
cloud_dates_remvd = sheet_get_named_column(cloud_sheet, "Date Removed")
cloud_rows = filter_by_dates(list(zip(cloud_platforms, cloud_pi_tags,
cloud_accounts, cloud_account_names, cloud_pctages)),
list(zip(cloud_dates_added, cloud_dates_remvd)),
begin_month_datetime, end_month_datetime)
# for (pi_tag, project, projnum, projid, account, pctage) in cloud_rows:
for (platform, pi_tag, account, acct_name, pctage) in cloud_rows:
# Only Google Cloud is supported by automated billing (for now)
if platform != "Google": continue
# Associate the project name and percentage to be charged with the pi_tag.
pi_tag_to_cloud_account_pctages[pi_tag].add((account, pctage))
# Associate the account name with the account
cloud_account_to_account_names[account] = acct_name
#
# Create mapping from pi_tags to a string denoting service level on cluster.
#
global pi_tag_to_service_level
levels_column = sheet_get_named_column(pis_sheet,"Cluster?")
pi_tag_to_service_level = dict(list(zip(pi_tag_list, levels_column)))
#
# Create mapping from pi_tags to a string denoting affiliation (Stanford/Affiliate/External).
#
global pi_tag_to_affiliation
affiliation_column = sheet_get_named_column(pis_sheet, "Affiliation")
pi_tag_to_affiliation = dict(list(zip(pi_tag_list, affiliation_column)))
#
# Filter pi_tag_list for PIs active in the current month.
#
pi_dates_added = sheet_get_named_column(pis_sheet, "Date Added")
pi_dates_removed = sheet_get_named_column(pis_sheet, "Date Removed")
pi_tags_and_dates_added = list(zip(pi_tag_list, pi_dates_added, pi_dates_removed))
for (pi_tag, date_added, date_removed) in pi_tags_and_dates_added:
# Convert the Excel dates to timestamps.
if date_added is None: continue
date_added_timestamp = from_datetime_to_timestamp(date_added)
if date_removed != '' and date_removed is not None:
date_removed_timestamp = from_datetime_to_timestamp(date_removed)
else:
date_removed_timestamp = end_month_timestamp + 1 # Not in this month.
# If the date added is AFTER the end of this month, or
# the date removed is BEFORE the beginning of this month,
# then remove the pi_tag from the list.
if date_added_timestamp >= end_month_timestamp:
print(" *** Ignoring PI %s: added after this month on %s" % (pi_tag_to_names_email[pi_tag][1], from_datetime_to_date_string(date_added)), file=sys.stderr)
pi_tag_list.remove(pi_tag)
elif date_removed_timestamp < begin_month_timestamp:
print(" *** Ignoring PI %s: removed before this month on %s" % (pi_tag_to_names_email[pi_tag][1], from_datetime_to_date_string(date_removed)), file=sys.stderr)
pi_tag_list.remove(pi_tag)
#
# Create mapping from usernames to a list of user details.
#
global username_to_user_details
usernames = sheet_get_named_column(users_sheet, "Username")
emails = sheet_get_named_column(users_sheet, "Email")
full_names = sheet_get_named_column(users_sheet, "Full Name")
username_details_rows = list(zip(usernames, emails, full_names))
for (username, email, full_name) in username_details_rows:
username_to_user_details[username] = [email, full_name]
#
# Create mapping from usernames to a list of pi_tag/dates.
#
global username_to_pi_tag_dates
pi_tags = sheet_get_named_column(users_sheet, "PI Tag")
dates_added = sheet_get_named_column(users_sheet, "Date Added")
dates_removed = sheet_get_named_column(users_sheet, "Date Removed")
pctages = sheet_get_named_column(users_sheet, "%age")
username_rows = list(zip(usernames, pi_tags, dates_added, dates_removed, pctages))
for (username, pi_tag, date_added, date_removed, pctage) in username_rows:
username_to_pi_tag_dates[username].append([pi_tag, date_added, date_removed, pctage])
#
# Create mapping from pi_tags to a list of [username, date_added, date_removed]
#
global pi_tag_to_user_details
for username in username_to_pi_tag_dates:
pi_tag_date_list = username_to_pi_tag_dates[username]
for (pi_tag, date_added, date_removed, pctage) in pi_tag_date_list:
pi_tag_to_user_details[pi_tag].append([username, date_added, date_removed, pctage])
#
# Create mapping from account to list of pi_tags and %ages.
#
global account_to_pi_tag_pctages
accounts = sheet_get_named_column(accounts_sheet, "Account")
pi_tags = sheet_get_named_column(accounts_sheet, "PI Tag")
pctages = sheet_get_named_column(accounts_sheet, "%age")
dates_added = sheet_get_named_column(accounts_sheet, "Date Added")
dates_removed = sheet_get_named_column(accounts_sheet, "Date Removed")
account_rows = filter_by_dates(list(zip(accounts, pi_tags, pctages)), list(zip(dates_added, dates_removed)),
#begin_month_exceldate, end_month_exceldate)
begin_month_datetime, end_month_datetime)
for (account, pi_tag, pctage) in account_rows:
account_to_pi_tag_pctages[account].append([pi_tag, pctage])
# Add pi_tags prefixed by ACCOUNT_PREFIXES to list of accounts for PI.
for pi_tag in pi_tag_list:
account_to_pi_tag_pctages[pi_tag].append([pi_tag, 1.0])
for prefix in ACCOUNT_PREFIXES:
account_to_pi_tag_pctages["%s_%s" % (prefix,pi_tag)].append([pi_tag, 1.0])
#
# Create mapping from folder to list of pi_tags and %ages.
#
global folder_to_pi_tag_pctages
# Get the Folders from PI Sheet
folders = sheet_get_named_column(pis_sheet, "PI Folder")
pi_tags = sheet_get_named_column(pis_sheet, "PI Tag")
pctages = [1.0] * len(folders)
dates_added = sheet_get_named_column(pis_sheet, "Date Added")
dates_removed = sheet_get_named_column(pis_sheet, "Date Removed")
# Add the Folders from Folder sheet
folders += sheet_get_named_column(folders_sheet, "Folder")
pi_tags += sheet_get_named_column(folders_sheet, "PI Tag")
pctages += sheet_get_named_column(folders_sheet, "%age")
dates_added += sheet_get_named_column(folders_sheet, "Date Added")
dates_removed += sheet_get_named_column(folders_sheet, "Date Removed")
folder_rows = filter_by_dates(list(zip(folders, pi_tags, pctages)), list(zip(dates_added, dates_removed)),
#begin_month_exceldate, end_month_exceldate)
begin_month_datetime, end_month_datetime)
for (folder, pi_tag, pctage) in folder_rows:
# Account for multiple folders separated by commas.
pi_folder_list = folder.split(',')
for pi_folder in pi_folder_list:
folder_to_pi_tag_pctages[pi_folder].append([pi_tag, pctage])
# Reads the particular rate requested from the Rates sheet of the BillingConfig workbook.
def get_rate(wkbk, rate_type):
rates_sheet = wkbk["Rates"]
types = sheet_get_named_column(rates_sheet, 'Type')
amounts = sheet_get_named_column(rates_sheet, 'Amount')
for (type, amount) in zip(types, amounts):
if type == rate_type:
return amount
else:
return None
def get_rate_a1_cell(wkbk, rate_string):
rates_sheet = wkbk["Rates"]
header_row = rates_sheet.iter_cols(min_row=1, max_row=1, values_only=True)
# Find the column numbers for 'Type' and 'Amount'.
type_col = -1
amt_col = -1
idx = 1
for col_name in header_row:
if col_name[0] == 'Type':
type_col = idx
if amt_col != -1: break # Leave loop if we have both
elif col_name[0] == 'Amount':
amt_col = idx
if type_col != -1: break # Leave loop if we have both
idx += 1
if type_col == -1 or amt_col == -1:
print("get_rate_a1_cell: Can't find Type/Amount headers (%d, %d)" % (type_col, amt_col), file=sys.stderr)
return None
# Get column of 'Types'.
types = rates_sheet.iter_rows(min_row=2, min_col=type_col, max_col=type_col, values_only=True)
# When you find the row with rate_string, return the Amount col and this row.
idx = 2
for row in types:
for col in row:
if col == rate_string:
return 'Rates!%s' % rowcol_to_a1_cell(idx + 1, amt_col, True, True)
idx += 1
else:
return 0.0
def get_rate_service_id(wkbk, rate_string):
rates_sheet = wkbk["Rates"]
types = sheet_get_named_column(rates_sheet, 'Type')
serv_ids = sheet_get_named_column(rates_sheet, 'iLab Service ID')
for (type, serv_id) in zip(types, serv_ids):
if type == rate_string:
return serv_id
else:
return None
def get_rate_data_from_string(billing_config_wkbk, service_str, tier_str, subservice_str, affiliation_str):
rate_string = service_str # To start, will be appended to below
if service_str == "Local HPC Storage" or service_str == "Local Computing":
# Add the tier string
rate_string += " (%s Tier)" % tier_str.capitalize()
# If there is a subservice string, add that to rate string
if subservice_str is not None and subservice_str != "":
rate_string += ": %s" % subservice_str
# Finish rate string with the affiliation string
rate_string += " - %s" % affiliation_str.capitalize()
# Look up rate amount, rate cell from rate_string
rate_amount = get_rate(billing_config_wkbk, rate_string)
rate_a1_cell = get_rate_a1_cell(billing_config_wkbk, rate_string)
rate_service_id = get_rate_service_id(billing_config_wkbk, rate_string)
return rate_amount, rate_a1_cell, rate_service_id
# Reads the Storage sheet of the BillingDetails workbook given, and populates
# the pi_tag_to_folder_sizes dict with the folder measurements for each PI.
def read_storage_sheet(wkbk):
global pi_tag_to_folder_sizes
storage_sheet = wkbk["Storage"]
for (date, timestamp, folder, size, used, inodes_quota, inodes_used) in storage_sheet.iter_rows(min_row=2, values_only=True):
# List of [pi_tag, %age] pairs.
pi_tag_pctages = folder_to_pi_tag_pctages[folder]
for (pi_tag, pctage) in pi_tag_pctages:
pi_tag_to_folder_sizes[pi_tag].append([folder, size, pctage])
# Reads the Computing sheet of the BillingDetails workbook given, and populates
# the account_to_pi_tag_cpus, pi_tag_to_account_username_cpus, and pi_tag_to_job_details dicts.
def read_computing_sheet(wkbk):
global pi_tag_to_job_details
computing_sheet = wkbk["Computing"]
if args.cpu_time_unit == 'cpu-hours':
cpu_time_denom = 3600.0
elif args.cpu_time_unit == 'cpu-days':
cpu_time_denom = 86400.0
else:
print("Arg 'cpu_time_unit' has unknown value {args.cpu_time_unit", file=sys.stderr)
sheet_number = 1
while True:
for (job_date, job_timestamp, job_username, job_name, account, node, cores, wallclock, jobID) in \
computing_sheet.iter_rows(min_row=2, values_only=True):
# Calculate CPU-core units for job.
cpu_core_time = cores * wallclock / cpu_time_denom # wallclock is in seconds.
# Rename this variable for easier understanding.
account = account.lower()
if account != '':
job_pi_tag_pctage_list = account_to_pi_tag_pctages[account]
else:
# No account means credit the job to the user's lab.
job_pi_tag_pctage_list = get_pi_tags_for_username_by_date(job_username, job_timestamp)
if len(job_pi_tag_pctage_list) == 0:
print(" *** No PI associated with job ID %d, pi_tag %s, account %s" % (jobID, pi_tag, account))
continue
# Distribute this job's CPU-units amongst pi_tags by %ages.
for (pi_tag, pctage) in job_pi_tag_pctage_list:
# This list is [account, list of [username, cpu_core_time, %age]].
account_username_cpu_list = pi_tag_to_account_username_cpus.get(pi_tag)
# If pi_tag has an existing list of account/username/CPUs:
if account_username_cpu_list is not None:
# Find if account for job is in list of account/CPUs for this pi_tag.
for pi_username_cpu_pctage_list in account_username_cpu_list:
(pi_account, pi_username_cpu_pctage_list) = pi_username_cpu_pctage_list
# If the account we are looking at is the one from the present job:
if pi_account == account:
# Find job username in list for account:
for username_cpu in pi_username_cpu_pctage_list:
if job_username == username_cpu[0]:
username_cpu[1] += cpu_core_time
break
else:
pi_username_cpu_pctage_list.append([job_username, cpu_core_time, pctage])
# Leave account_username_cpu_list loop.
break
else:
# No matching account in pi_tag list -- add a new one to the list.
account_username_cpu_list.append([account, [[job_username, cpu_core_time, pctage]]])
# Else start a new account/CPUs list for the pi_tag.
else:
pi_tag_to_account_username_cpus[pi_tag] = [[account, [[job_username, cpu_core_time, pctage]]]]
#
# Save job details for pi_tag.
#
new_job_details = [job_date, job_username, job_name, account, node, cpu_core_time, jobID, pctage]
pi_tag_to_job_details[pi_tag].append(new_job_details)
sheet_number += 1
try:
computing_sheet = wkbk["Computing %d" % sheet_number]
except:
break # No more computing sheets: exit the while True loop.
# Read the Cloud sheet from the BillingDetails workbook.
def read_cloud_sheet(wkbk):
cloud_sheet = wkbk["Cloud"]
for (platform, account, project, description, dates, quantity, uom, charge) in \
cloud_sheet.iter_rows(min_row=2, values_only=True):
# If project is of the form "<project name>(<project-id>)" or "<project name>[<project-id>]", get the "<project-id>".
if project is not None:
project_re = re.search("[(\[]([a-z0-9-:.]+)[\])]", project)
if project_re is not None:
project = project_re.group(1)
else:
pass # If no parens, use the original project name.
# Save the project that the account line item is for.
cloud_account_to_cloud_projects[account].add(project)
# Save the cloud item in a list of charges for that PI.
cloud_project_account_to_cloud_details[(project, account)].append((platform, description, dates, quantity, uom, charge))
# Accumulate the total cost of a project.
cloud_project_account_to_total_charges[(project, account)] += float(charge)
def read_google_invoice(google_invoice_csv_file):
###
# Read the Google Invoice CSV File
###
# Google Invoice CSV files are Unicode with BOM.
google_invoice_csv_file_obj = codecs.open(google_invoice_csv_file, 'rU', encoding='utf-8-sig')
# Read the header subtable
google_invoice_header_subtable = get_google_invoice_csv_subtable_lines(google_invoice_csv_file_obj)
google_invoice_header_csvreader = csv.DictReader(google_invoice_header_subtable, fieldnames=['key', 'value'])
for row in google_invoice_header_csvreader:
# Extract invoice date from "Issue Date".
if row['key'] == 'Issue date':
google_invoice_issue_date = row['value']
# Extract the "Amount Due" value.
elif row['key'] == 'Amount due':
google_invoice_amount_due = locale.atof(row['value'])
print(" Amount due: $%0.2f" % (google_invoice_amount_due), file=sys.stderr)
# Accumulate the total amount of charges while processing each line,
# to compare with total amount in header.
google_invoice_total_amount = 0.0
# While there are still more subtables...
while True:
# Read subtable.
google_invoice_subtable = get_google_invoice_csv_subtable_lines(google_invoice_csv_file_obj)
# No more subtables?! Let's get out of here!
if len(google_invoice_subtable) == 0:
break
# Create CSVReader from subtable
google_invoice_subtable_csvreader = csv.DictReader(google_invoice_subtable)
# Foreach row in CSVReader
for row_dict in google_invoice_subtable_csvreader:
# Accumulate total charges.
amount = locale.atof(row_dict['Amount'])
google_invoice_total_amount += amount
google_account = row_dict['Order']
# Construct note for ilab entry.
google_platform = 'Google Cloud Platform, Firebase, and APIs'
google_project = row_dict['Source']
google_item = row_dict['Description']
google_quantity = row_dict['Quantity']
google_uom = row_dict['UOM']
google_dates = row_dict['Interval']
# Save the cloud details with the appropriate PI.
cloud_project_account_to_cloud_details[(google_project, google_account)].append((google_platform, google_item, google_dates,
google_quantity, google_uom, amount))
# Compare total charges to "Amount Due".
if abs(google_invoice_total_amount - google_invoice_amount_due) >= 0.01: # Ignore differences less than a penny.
print(" WARNING: Accumulated amounts do not equal amount due: ($%.2f != $%.2f)" % (google_invoice_total_amount,
google_invoice_amount_due), file=sys.stderr)
else:
print(" VERIFIED: Sum of individual transactions equals Amount due.", file=sys.stderr)
#
# Read in the Consulting sheet.
#
# It fills in the dict consulting_details.
#
def read_consulting_sheet(wkbk):
#consulting_sheet = wkbk.sheet_by_name("Consulting")
consulting_sheet = wkbk["Consulting"]
#for row in range(1, consulting_sheet.nrows):
#(date, pi_tag, hours, travel_hours, participants, clients, summary, notes, cumul_hours) = consulting_sheet.row_values(row)
for (date, pi_tag, hours, travel_hours, participants, clients, summary, notes, cumul_hours) in \
consulting_sheet.iter_rows(min_row=2, values_only=True):
if travel_hours is None: travel_hours = 0
# Save the consulting item in a list of charges for that PI.
consulting_details[pi_tag].append((date, summary, clients, float(hours), float(travel_hours), float(cumul_hours)))
#
# Digest cluster data and output Cluster iLab file.
#
def process_cluster_data():
# Read in its Storage sheet.
print("Reading storage sheet.")
read_storage_sheet(billing_details_wkbk)
# Read in its Computing sheet.
print("Reading computing sheet.")
read_computing_sheet(billing_details_wkbk)
def open_ilab_output_dictwriter(subdir, suffix):
###
#
# Open an iLab CSV file for writing out.
#
###
ilab_export_csv_filename = "%s-%s.%s-%02d.csv" % (ILAB_EXPORT_PREFIX, suffix, year, month)
ilab_export_csv_pathname = os.path.join(subdir, ilab_export_csv_filename)
ilab_export_csv_file = open(ilab_export_csv_pathname, "w")
ilab_export_csv_dictwriter = csv.DictWriter(ilab_export_csv_file, fieldnames=ilab_csv_headers)
ilab_export_csv_dictwriter.writeheader()
return ilab_export_csv_dictwriter
#
# Digest cloud data and output Cloud iLab file.
#
def process_cloud_data():
# Read in Cloud data from Google Invoice, if given as argument.
if args.google_invoice_csv is not None:
###
# Read in Google Cloud Invoice data, ignoring data from BillingDetails.
###
print("Reading Google Invoice.")
read_google_invoice(google_invoice_csv)
# Read in the Cloud sheet from the BillingDetails file, if present.
elif "Cloud" in billing_details_wkbk.sheetnames:
print("Reading cloud sheet.")
read_cloud_sheet(billing_details_wkbk)
else:
print("No Cloud sheet in BillingDetails nor Google Invoice file...skipping")
return
#
# Digest Consulting data and output Consulting iLab file.
#
def process_consulting_data():
# Read in its Consulting sheet.
if "Consulting" in billing_details_wkbk.sheetnames:
print("Reading consulting sheet.")
read_consulting_sheet(billing_details_wkbk)
else:
print("No consulting sheet in BillingDetails: skipping")
return
#
# Generates the iLab Cluster Storage CSV entries for a particular pi_tag.
#
# It uses dict pi_tag_to_folder_sizes.
#
def output_ilab_csv_data_for_cluster_storage(csv_dictwriter, pi_tag, service_req_id, storage_base_service_id, storage_addl_service_id,
begin_month_timestamp, end_month_timestamp):
purchased_on_date = from_timestamp_to_date_string(end_month_timestamp-1) # Last date of billing period.
###
#
# STORAGE Subtable
#
###
output_storage_p = False # Did any lines get output?
total_storage_sizes = 0.0
if storage_base_service_id is not None:
for (folder, size, pctage) in pi_tag_to_folder_sizes[pi_tag]:
if folder == '/labs/%s' % pi_tag and size >= BASE_STORAGE_SIZE:
# Note format: <folder>
note = "%s" % (folder)
output_ilab_csv_data_row(csv_dictwriter, pi_tag, service_req_id, purchased_on_date, storage_base_service_id, note,1)
total_storage_sizes += BASE_STORAGE_SIZE
size -= BASE_STORAGE_SIZE
output_storage_p = True
if size > 0.0:
# Note format: <folder> [<pct>%, if not 0%]
note = "%s" % (folder)
if 0.0 < pctage < 1.0:
note += " [%d%%]" % (pctage * 100)
quantity = size * pctage
if quantity > 0.0:
output_ilab_csv_data_row(csv_dictwriter, pi_tag, service_req_id, purchased_on_date, storage_addl_service_id, note, quantity)
total_storage_sizes += size
output_storage_p = True
return output_storage_p
#
# Generates the iLab Cluster Computing CSV entries for a particular pi_tag.
#
# It uses dicts pi_tag_to_username_cpus, and pi_tag_to_account_cpus.
#
def output_ilab_csv_data_for_cluster_compute(csv_dictwriter, pi_tag, service_req_id, lab_computing_service_id, full_computing_service_id,
begin_month_timestamp, end_month_timestamp):
purchased_on_date = from_timestamp_to_date_string(end_month_timestamp-1) # Last date of billing period.
###
#
# COMPUTING Subtable
#
###
# Loop over pi_tag_to_account_username_cpus for account/username combos.
account_username_cpus_list = pi_tag_to_account_username_cpus.get(pi_tag)
output_compute_p = False # Were any lines written out?
if account_username_cpus_list is not None:
for (account, username_cpu_pctage_list) in account_username_cpus_list:
if len(username_cpu_pctage_list) > 0:
for (username, cpu_core_hrs, pctage) in username_cpu_pctage_list:
fullname = username_to_user_details[username][1]
# Note format: <user-name> (<user-ID>) [<pct>%, if not 0%]
note = "Account: %s - User: %s (%s)" % (account, fullname, username)
if 0.0 < pctage < 1.0:
note += " [%d%%]" % (pctage * 100)
quantity = cpu_core_hrs * pctage
if quantity > 0.0:
if lab_computing_service_id is not None:
output_ilab_csv_data_row(csv_dictwriter, pi_tag, service_req_id, purchased_on_date, lab_computing_service_id,
note, quantity)
output_compute_p = True
# Lab is in Free Tier, and we can charge them if someone outside the lab ran the job.
else:
pi_tags_for_username = get_pi_tags_for_username_by_date(username, begin_month_timestamp)
# If the user is not within the lab membership, then use the full tier service ID.
if pi_tag not in [pi_pct[0] for pi_pct in pi_tags_for_username]:
output_ilab_csv_data_row(csv_dictwriter, pi_tag, service_req_id, purchased_on_date, full_computing_service_id, note, quantity)
output_compute_p = True
else:
print(" *** In Free Tier Lab %s, lab member %s ran billable jobs (%f)." % (pi_tag, username, quantity), file=sys.stderr)
else:
# No users for this PI.
pass
return output_compute_p
#
# Generates the iLab Cloud CSV entries for a particular pi_tag.
#
# It uses dicts pi_tag_to_cloud_account_pctages and cloud_project_account_to_cloud_details.
#
def output_ilab_csv_data_for_cloud(csv_dictwriter, pi_tag, service_req_id, cloud_service_id,
begin_month_timestamp, end_month_timestamp):
purchased_on_date = from_timestamp_to_date_string(end_month_timestamp-1) # Last date of billing period.
# Get PI Last name for some situations below.
(_, pi_last_name, _, _) = pi_tag_to_names_email[pi_tag]
# Get list of (account, %ages) tuples for given PI.
output_cloud_p = False # Were any lines written out?
for (account, pctage) in pi_tag_to_cloud_account_pctages[pi_tag]:
if pctage == 0.0: continue
account_name = cloud_account_to_account_names[account]
if account_name is None or account_name == "":
account_name = account
for project_id in cloud_account_to_cloud_projects[account]:
# Get list of cloud items to charge PI for.
cloud_details = cloud_project_account_to_cloud_details[(project_id, account)]
# Get name for project ID.
project_name = cloud_projid_to_cloud_projname.get(project_id)
if project_name is None:
project_name = project_id
if not args.break_out_cloud and len(cloud_details) > 0:
# Generate a single transaction of all the transactions within the project.
total_amount_for_project = 0
# Add up all the charges for that project within the cloud details.
for (platform, description, dates, quantity, uom, amount) in cloud_details: