-
Notifications
You must be signed in to change notification settings - Fork 0
/
showusage.py
1842 lines (1608 loc) · 79.9 KB
/
showusage.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
# coding: utf-8
# Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license.
##########################################################################
# showusage.py
#
# @author: Adi Zohar, Oct 07 2021, Updated July 19th, 2024
# Added OSR Eligible for tenant grouping and CSV files
# Added new reports - Special and Compartment
# Added Monthly Reports - use -g MONTH
#
# Supports Python 3
##########################################################################
# Application Command line parameters
#
# -c config - OCI CLI Config
# -t profile - profile inside the config file
# -p proxy - Set Proxy (i.e. www-proxy-server.com:80)
# -ip - Use Instance Principals for Authentication
# -g grn - Granularity DAILY / MONTHLY (Default DAILY)
# -dt - Use Instance Principals with delegation token for cloud shell
# -ds date - Start Date in YYYY-MM-DD format
# -de date - End Date in YYYY-MM-DD format (Not Inclusive)
# -ld days - Add Days Combined with Start Date (de is ignored if specified)
# -ld days - Add Days Combined with Start Date (de is ignored if specified)
# -report type - Report Type = PRODUCT, DATE, REGION, SERVICE, RESOURCE, TENANT, SPECIAL, COMPARTMENT
# SPECIAL is group by Service, Region, Product Description
# -csv - Write to CSV files - usage_products.csv, usage_by_date.csv, usage_region.csvs,
# usage_resources.csv, usage_tenants.csv, usage_special.csv, usage_compartments.csv
#
##########################################################################
# Those are the valid options for GroupBy:
# "tagNamespace", "tagKey", "tagValue", "service", "skuName", "skuPartNumber", "unit", "compartmentName",
# "compartmentPath", "compartmentId", "platform", "region", "logicalAd", "resourceId", "tenantId", "tenantName"
##########################################################################
# Info:
# List Tenancy Usage
#
# Connectivity:
# Option 1 - User Authentication
# $HOME/.oci/config, please follow - https://docs.cloud.oracle.com/en-us/iaas/Content/API/Concepts/sdkconfig.htm
# OCI user part of ShowUsageGroup group with below Policy rules:
# Allow group ShowUsageGroup to inspect tenancies in tenancy
# Allow group ShowUsageGroup to read usage-report in tenancy
#
# Option 2 - Instance Principle
# Compute instance part of DynShowUsageGroup dynamic group with policy rules:
# Allow dynamic group DynShowUsageGroup to inspect tenancies in tenancy
# Allow dynamic group DynShowUsageGroup to read usage-report in tenancy
#
##########################################################################
# Modules Included:
# - oci.identity.IdentityClient
# - oci.usage_api.UsageapiClient
#
# APIs Used:
# - IdentityClient.get_tenancy - Policy TENANCY_INSPECT
# - IdentityClient.list_region_subscriptions - Policy TENANCY_INSPECT
# - UsageapiClient.request_summarized_usages - read usage-report
#
##########################################################################
import sys
import argparse
import datetime
import oci
import os
import platform
import csv
version = "2024.07.19"
csv_file_products = "usage_products.csv"
csv_file_by_date = "usage_by_date.csv"
csv_file_regions = "usage_regions.csv"
csv_file_resources = "usage_resources.csv"
csv_file_tenants = "usage_tenants.csv"
csv_file_service = "usage_service.csv"
csv_file_special = "usage_special.csv"
csv_file_compartment = "usage_compartments.csv"
##########################################################################
# Print header centered
##########################################################################
def print_header(name, category):
options = {0: 120, 1: 100, 2: 90, 3: 85}
chars = int(options[category])
print("")
print('#' * chars)
print("#" + name.center(chars - 2, " ") + "#")
print('#' * chars)
##########################################################################
# custom argparse *date* type for user dates
##########################################################################
def valid_date_type(arg_date_str):
try:
return datetime.datetime.strptime(arg_date_str, "%Y-%m-%d")
except ValueError:
msg = "Given Date ({0}) not valid! Expected format, YYYY-MM-DD!".format(arg_date_str)
raise argparse.ArgumentTypeError(msg)
##########################################################################
# check service error to warn instead of error
##########################################################################
def check_service_error(code):
return ('max retries exceeded' in str(code).lower() or
'auth' in str(code).lower() or
'notfound' in str(code).lower() or
code == 'Forbidden' or
code == 'TooManyRequests' or
code == 'IncorrectState' or
code == 'LimitExceeded'
)
##########################################################################
# Duration / days or months
##########################################################################
def duration(min_date, max_date, granularity):
if granularity == 'DAILY':
days = (max_date - min_date).days + 1
# print("Duration = " + str(days) + " days")
return days
else:
months = max_date.month - min_date.month + 12 * (max_date.year - min_date.year) + 1
# print("Duration = " + str(months) + " Months")
return months
##########################################################################
# Create signer for Authentication
# Input - config_profile and is_instance_principals and is_delegation_token
# Output - config and signer objects
##########################################################################
def create_signer(config_file, config_profile, is_instance_principals, is_delegation_token):
# if instance principals authentications
if is_instance_principals:
try:
signer = oci.auth.signers.InstancePrincipalsSecurityTokenSigner()
config = {'region': signer.region, 'tenancy': signer.tenancy_id}
return config, signer
except Exception:
print_header("Error obtaining instance principals certificate, aborting", 0)
raise SystemExit
# -----------------------------
# Delegation Token
# -----------------------------
elif is_delegation_token:
try:
# check if env variables OCI_CONFIG_FILE, OCI_CONFIG_PROFILE exist and use them
env_config_file = os.environ.get('OCI_CONFIG_FILE')
env_config_section = os.environ.get('OCI_CONFIG_PROFILE')
# check if file exist
if env_config_file is None or env_config_section is None:
print("*** OCI_CONFIG_FILE and OCI_CONFIG_PROFILE env variables not found, abort. ***")
print("")
raise SystemExit
config = oci.config.from_file(env_config_file, env_config_section)
delegation_token_location = config["delegation_token_file"]
with open(delegation_token_location, 'r') as delegation_token_file:
delegation_token = delegation_token_file.read().strip()
# get signer from delegation token
signer = oci.auth.signers.InstancePrincipalsDelegationTokenSigner(delegation_token=delegation_token)
return config, signer
except KeyError:
print("* Key Error obtaining delegation_token_file")
raise SystemExit
except Exception:
raise
# -----------------------------
# config file authentication
# -----------------------------
else:
config = oci.config.from_file(
(config_file if config_file else oci.config.DEFAULT_LOCATION),
(config_profile if config_profile else oci.config.DEFAULT_PROFILE)
)
signer = oci.signer.Signer(
tenancy=config["tenancy"],
user=config["user"],
fingerprint=config["fingerprint"],
private_key_file_location=config.get("key_file"),
pass_phrase=oci.config.get_config_value_or_default(config, "pass_phrase"),
private_key_content=config.get("key_content")
)
return config, signer
##########################################################################
# create csv file
##########################################################################
def export_to_csv_file(file_name, data):
try:
# if no data
if len(data) == 0:
return
# generate fields keys
fields = []
for dict_ in data:
for key in dict_:
if key not in fields:
fields.append(key)
with open(file_name, mode='w', newline='') as csv_file:
writer = csv.DictWriter(csv_file, fieldnames=fields)
# write header
writer.writeheader()
for row in data:
writer.writerow(row)
print("CSV: " + file_name + " created")
except Exception as e:
raise Exception("Error in export_to_csv_file: " + str(e.args))
##########################################################################
# Group Dictionaries by PK
##########################################################################
def group_dictionaries(data):
try:
gdata = {}
for item in data:
pk = item['pk']
if pk not in gdata:
gdata[pk] = item
else:
gdata[pk]['cost'] += item['cost']
gdata[pk]['quantity'] += item['quantity']
if item['currency'] and not gdata[pk]['currency']:
gdata[pk]['currency'] = item['currency']
if 'sku_part_number' in item and 'sku_name' in item and 'osr_eligible' in gdata[pk]:
gdata[pk]['osr_eligible'] += osr_eligible_cost(item['sku_part_number'], item['sku_name'], item['cost'])
return gdata
except Exception as e:
print("\nException Error at 'group_dictionaries' - " + str(e))
##########################################################################
# Usage Daily by Tenant
##########################################################################
def osr_eligible_cost(sku_part_number, sku_name, cost):
# IF Windows or VMWare
if 'windows' in sku_name.lower() or 'vmware' in sku_name.lower():
return 0
# if Market Image with MP
if str(sku_part_number).lower()[0:1] == 'mp':
return 0
return cost
##########################################################################
# Usage Product by Date
##########################################################################
def usage_product(usageClient, tenant_id, time_usage_started, time_usage_ended, is_csv, granularity):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity=granularity,
query_type='COST',
group_by=['skuPartNumber', 'skuName'],
time_usage_started=time_usage_started.strftime('%Y-%m-%dT%H:%M:%SZ'),
time_usage_ended=time_usage_ended.strftime('%Y-%m-%dT%H:%M:%SZ')
)
# usageClient.request_summarized_usages
request_summarized_usages = usageClient.request_summarized_usages(
requestSummarizedUsagesDetails,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
)
################################
# Add all data to array data
################################
data = []
min_date = None
max_date = None
date_format = '%Y-%m-%d' if granularity == 'DAILY' else '%Y-%m'
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'pk': item.sku_part_number,
'sku': item.sku_part_number,
'sku_name': item.sku_name if item.sku_part_number in item.sku_name else item.sku_part_number + " - " + item.sku_name,
'sku_part_number': item.sku_part_number,
'osr_eligible': osr_eligible_cost(item.sku_part_number, item.sku_name, item.computed_amount if item.computed_amount else 0),
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'currency': item.currency.lstrip(),
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency.lstrip():
currency = item.currency
if not min_date or item.time_usage_started < min_date:
min_date = item.time_usage_started
if not max_date or item.time_usage_started > max_date:
max_date = item.time_usage_started
days = duration(min_date, max_date, granularity)
################################
# Group Dictionaries by PK
################################
gdata = group_dictionaries(data)
################################
# if to generate to csv
################################
if is_csv:
csv_output = []
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
if granularity == 'DAILY':
csv_output.append({
'Product SKU': item['sku_part_number'],
'Product Name': item['sku_name'],
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Days': days,
'Currency': item['currency'],
'Quantity': "{:8.1f}".format(item['quantity']),
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost']),
'Month-31': "{:9.0f}".format(item['cost'] / days * 31),
'Year': "{:9.0f}".format(item['cost'] / days * 365),
})
else:
csv_output.append({
'Product SKU': item['sku_part_number'],
'Product Name': item['sku_name'],
'Granularity': 'Monthly',
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Months': days,
'Currency': item['currency'],
'Quantity': "{:8.1f}".format(item['quantity']),
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost'])
})
export_to_csv_file(csv_file_products, csv_output)
else:
################################
# Print to screen
################################
col = {
'product': 65,
'quantity': 14,
'days': 10,
'osr_eligible': 13,
'cost': 13,
'month': 13,
'year': 13
}
currency_print = (" in " + currency) if currency else ""
product_header = granularity + " Product Summary for " + min_date.strftime(date_format) + " - " + max_date.strftime(date_format) + currency_print
print_header(product_header, 3)
print("")
print(
"Product".ljust(col['product']) +
" Quantity".rjust(col['quantity']) +
" Duration".rjust(col['days']) +
" OSR Eligible".rjust(col['osr_eligible']) +
" Cost".rjust(col['cost']) +
(" Month-31".rjust(col['month']) if granularity == 'DAILY' else "") +
(" Year".rjust(col['year']) if granularity == 'DAILY' else "")
)
print(
"".ljust(col['product'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['osr_eligible'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
total = 0
osr_total = 0
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
total += item['cost']
osr_total += item['osr_eligible']
line = item['sku_name'].ljust(col['product'])[0:col['product']]
line += "{:8,.1f}".format(item['quantity']).rjust(col['quantity'])
line += "{:8,.0f}".format(days).rjust(col['days'])
line += "{:8,.1f}".format(item['osr_eligible']).rjust(col['osr_eligible'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
if granularity == 'DAILY':
line += "{:9,.0f}".format(item['cost'] / days * 31).rjust(col['month'])
line += "{:9,.0f}".format(item['cost'] / days * 365).rjust(col['year'])
print(line)
# Total
print(
"".ljust(col['product'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['osr_eligible'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
print(
"Total ".ljust(col['product'] + col['quantity'] + col['days']) +
" {:8,.1f}".format(osr_total).rjust(col['osr_eligible']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
(" {:9,.0f}".format(total / days * 31).rjust(col['month']) if granularity == 'DAILY' else "") +
(" {:9,.0f}".format(total / days * 31 * 12).rjust(col['year']) if granularity == 'DAILY' else "")
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_product' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_product' - " + str(e))
##########################################################################
# Usage Daily by Region
##########################################################################
def usage_region(usageClient, tenant_id, time_usage_started, time_usage_ended, is_csv, granularity):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity=granularity,
query_type='COST',
group_by=['region'],
time_usage_started=time_usage_started.strftime('%Y-%m-%dT%H:%M:%SZ'),
time_usage_ended=time_usage_ended.strftime('%Y-%m-%dT%H:%M:%SZ')
)
# usageClient.request_summarized_usages
request_summarized_usages = usageClient.request_summarized_usages(
requestSummarizedUsagesDetails,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
)
################################
# Add all data to array data
################################
data = []
min_date = None
max_date = None
date_format = '%Y-%m-%d' if granularity == 'DAILY' else '%Y-%m'
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'pk': item.region,
'region': item.region,
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'currency': item.currency.lstrip(),
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency.lstrip():
currency = item.currency
if not min_date or item.time_usage_started < min_date:
min_date = item.time_usage_started
if not max_date or item.time_usage_started > max_date:
max_date = item.time_usage_started
days = duration(min_date, max_date, granularity)
################################
# Group Dictionaries by PK
################################
gdata = group_dictionaries(data)
################################
# if to generate to csv
################################
if is_csv:
csv_output = []
for item_key in sorted(gdata, key=lambda x: gdata[x]['pk']):
item = gdata[item_key]
if item['cost'] == 0:
continue
if granularity == 'DAILY':
csv_output.append({
'Region': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Days': days,
'Currency': item['currency'],
'Cost': "{:8.1f}".format(item['cost']),
'Month-31': "{:9.0f}".format(item['cost'] / days * 31),
'Year': "{:9.0f}".format(item['cost'] / days * 365)
})
else:
csv_output.append({
'Region': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Months': days,
'Currency': item['currency'],
'Cost': "{:8.1f}".format(item['cost'])
})
export_to_csv_file(csv_file_regions, csv_output)
else:
################################
# Compact based on SKUs
################################
col = {
'region': 25,
'days': 10,
'cost': 13,
'month': 13,
'year': 13
}
currency_print = (" in " + currency) if currency else ""
product_header = granularity + " Region Summary for " + min_date.strftime(date_format) + " - " + max_date.strftime(date_format) + currency_print
print_header(product_header, 3)
print("")
print(
"Region".ljust(col['region']) +
" Duration".rjust(col['days']) +
" Cost".rjust(col['cost']) +
(" Month-31".rjust(col['month']) if granularity == 'DAILY' else "") +
(" Year".rjust(col['year']) if granularity == 'DAILY' else "")
)
print(
"".ljust(col['region'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
total = 0
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
total += item['cost']
line = item_key.ljust(col['region'])
line += "{:8,.0f}".format(days).rjust(col['days'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
if granularity == 'DAILY':
line += "{:9,.0f}".format(item['cost'] / days * 31).rjust(col['month'])
line += "{:9,.0f}".format(item['cost'] / days * 365).rjust(col['year'])
print(line)
# Total
print(
"".ljust(col['region'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
print(
"Total ".ljust(col['region'] + col['days']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
(" {:9,.0f}".format(total / days * 31).rjust(col['month']) if granularity == 'DAILY' else "") +
(" {:9,.0f}".format(total / days * 31 * 12).rjust(col['year']) if granularity == 'DAILY' else "")
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_region' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_region' - " + str(e))
##########################################################################
# Usage Daily by Tenant
##########################################################################
def usage_tenant(usageClient, tenant_id, time_usage_started, time_usage_ended, is_csv, granularity):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity=granularity,
query_type='COST',
group_by=['tenantName', 'skuPartNumber', 'skuName'],
time_usage_started=time_usage_started.strftime('%Y-%m-%dT%H:%M:%SZ'),
time_usage_ended=time_usage_ended.strftime('%Y-%m-%dT%H:%M:%SZ')
)
# usageClient.request_summarized_usages
request_summarized_usages = usageClient.request_summarized_usages(
requestSummarizedUsagesDetails,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
)
################################
# Add all data to array data
################################
data = []
min_date = None
max_date = None
date_format = '%Y-%m-%d' if granularity == 'DAILY' else '%Y-%m'
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'pk': item.tenant_name,
'tenant': item.tenant_name,
'sku_part_number': item.sku_part_number,
'sku_name': item.sku_name,
'osr_eligible': osr_eligible_cost(item.sku_part_number, item.sku_name, item.computed_amount if item.computed_amount else 0),
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'currency': item.currency.lstrip(),
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency.lstrip():
currency = item.currency
if not min_date or item.time_usage_started < min_date:
min_date = item.time_usage_started
if not max_date or item.time_usage_started > max_date:
max_date = item.time_usage_started
days = duration(min_date, max_date, granularity)
################################
# Group Dictionaries by PK
################################
gdata = group_dictionaries(data)
################################
# if to generate to csv
################################
if is_csv:
csv_output = []
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
if granularity == 'DAILY':
csv_output.append({
'Tenant': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Days': days,
'Currency': item['currency'],
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost']),
'Month-31': "{:9.0f}".format(item['cost'] / days * 31),
'Year': "{:9.0f}".format(item['cost'] / days * 365),
})
else:
csv_output.append({
'Tenant': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Months': days,
'Currency': item['currency'],
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost'])
})
export_to_csv_file(csv_file_tenants, csv_output)
else:
################################
# Print to screen
################################
col = {
'tenant': 30,
'days': 10,
'osr_eligible': 15,
'cost': 15,
'month': 13,
'year': 13
}
currency_print = (" in " + currency) if currency else ""
product_header = granularity + " Tenant Summary for " + min_date.strftime(date_format) + " - " + max_date.strftime(date_format) + currency_print
print_header(product_header, 3)
print("")
print(
"Tenant".ljust(col['tenant']) +
" Duration".rjust(col['days']) +
" OSR Eligible".rjust(col['osr_eligible']) +
" Cost".rjust(col['cost']) +
(" Month-31".rjust(col['month']) if granularity == 'DAILY' else "") +
(" Year".rjust(col['year']) if granularity == 'DAILY' else "")
)
print(
"".ljust(col['tenant'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['osr_eligible'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
total = 0
osr_total = 0
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
total += item['cost']
osr_total += item['osr_eligible']
line = item_key.ljust(col['tenant'])
line += "{:8,.0f}".format(days).rjust(col['days'])
line += "{:8,.1f}".format(item['osr_eligible']).rjust(col['osr_eligible'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
if granularity == 'DAILY':
line += "{:9,.0f}".format(item['cost'] / days * 31).rjust(col['month'])
line += "{:9,.0f}".format(item['cost'] / days * 365).rjust(col['year'])
print(line)
# Total
print(
"".ljust(col['tenant'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['osr_eligible'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
print(
"Total ".ljust(col['tenant'] + col['days']) +
" {:8,.1f}".format(osr_total).rjust(col['osr_eligible']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
(" {:9,.0f}".format(total / days * 31).rjust(col['month']) if granularity == 'DAILY' else "") +
(" {:9,.0f}".format(total / days * 31 * 12).rjust(col['year']) if granularity == 'DAILY' else "")
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_tenant' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_tenant' - " + str(e))
##########################################################################
# Usage Daily by Service
##########################################################################
def usage_service(usageClient, tenant_id, time_usage_started, time_usage_ended, is_csv, granularity):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity=granularity,
query_type='COST',
group_by=['service', 'skuPartNumber', 'skuName'],
time_usage_started=time_usage_started.strftime('%Y-%m-%dT%H:%M:%SZ'),
time_usage_ended=time_usage_ended.strftime('%Y-%m-%dT%H:%M:%SZ')
)
# usageClient.request_summarized_usages
request_summarized_usages = usageClient.request_summarized_usages(
requestSummarizedUsagesDetails,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
)
################################
# Add all data to array data
################################
data = []
min_date = None
max_date = None
date_format = '%Y-%m-%d' if granularity == 'DAILY' else '%Y-%m'
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'pk': item.service,
'service': item.service,
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'sku_part_number': item.sku_part_number,
'sku_name': item.sku_name,
'osr_eligible': osr_eligible_cost(item.sku_part_number, item.sku_name, item.computed_amount if item.computed_amount else 0),
'currency': item.currency.lstrip(),
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency.lstrip():
currency = item.currency
if not min_date or item.time_usage_started < min_date:
min_date = item.time_usage_started
if not max_date or item.time_usage_started > max_date:
max_date = item.time_usage_started
days = duration(min_date, max_date, granularity)
################################
# Group Dictionaries by PK
################################
gdata = group_dictionaries(data)
################################
# if to generate to csv
################################
if is_csv:
csv_output = []
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
if granularity == 'DAILY':
csv_output.append({
'Service': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Days': days,
'Currency': item['currency'],
'Quantity': "{:8.1f}".format(item['quantity']),
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost']),
'Month-31': "{:9.0f}".format(item['cost'] / days * 31),
'Year': "{:9.0f}".format(item['cost'] / days * 365),
})
else:
csv_output.append({
'Service': item_key,
'Start Date': min_date.strftime('%m/%d/%Y'),
'End Date': max_date.strftime('%m/%d/%Y'),
'Months': days,
'Currency': item['currency'],
'Quantity': "{:8.1f}".format(item['quantity']),
'Osr Eligible Cost': "{:8.1f}".format(item['osr_eligible']),
'Cost': "{:8.1f}".format(item['cost'])
})
export_to_csv_file(csv_file_service, csv_output)
else:
################################
# Print to screen
################################
col = {
'service': 45,
'quantity': 14,
'days': 10,
'osr_eligible': 15,
'cost': 13,
'month': 13,
'year': 13
}
currency_print = (" in " + currency) if currency else ""
product_header = granularity + " Service Summary for " + min_date.strftime(date_format) + " - " + max_date.strftime(date_format) + currency_print
print_header(product_header, 3)
print("")
print(
"Service".ljust(col['service']) +
" Duration".rjust(col['days']) +
" Quantity".rjust(col['quantity']) +
" OSR Eligible".rjust(col['osr_eligible']) +
" Cost".rjust(col['cost']) +
(" Month-31".rjust(col['month']) if granularity == 'DAILY' else "") +
(" Year".rjust(col['year']) if granularity == 'DAILY' else "")
)
print(
"".ljust(col['service'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['osr_eligible'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
total = 0
osr_total = 0
for item_key in sorted(gdata, key=lambda x: gdata[x]['cost']):
item = gdata[item_key]
if item['cost'] == 0:
continue
total += item['cost']
osr_total += item['osr_eligible']
line = item_key.ljust(col['service'])
line += "{:8,.0f}".format(days).rjust(col['days'])
line += "{:8,.1f}".format(item['quantity']).rjust(col['quantity'])
line += "{:8,.1f}".format(item['osr_eligible']).rjust(col['osr_eligible'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
if granularity == 'DAILY':
line += "{:9,.0f}".format(item['cost'] / days * 31).rjust(col['month'])
line += "{:9,.0f}".format(item['cost'] / days * 365).rjust(col['year'])
print(line)
# Total
print(
"".ljust(col['service'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['osr_eligible'], '=') +
" ".ljust(col['cost'], '=') +
(" ".ljust(col['month'], '=') if granularity == 'DAILY' else "") +
(" ".ljust(col['year'], '=') if granularity == 'DAILY' else "")
)
print(
"Total ".ljust(col['service'] + col['quantity'] + col['days']) +
" {:8,.1f}".format(osr_total).rjust(col['osr_eligible']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
(" {:9,.0f}".format(total / days * 31).rjust(col['month']) if granularity == 'DAILY' else "") +
(" {:9,.0f}".format(total / days * 31 * 12).rjust(col['year']) if granularity == 'DAILY' else "")
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_service' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_service' - " + str(e))
##########################################################################
# Usage Daily by Compartment and Service
##########################################################################
def usage_compartment(usageClient, tenant_id, time_usage_started, time_usage_ended, is_csv, granularity):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity=granularity,
query_type='COST',
compartment_depth=5,
group_by=['compartmentPath', 'service', 'skuPartNumber', 'skuName'],
time_usage_started=time_usage_started.strftime('%Y-%m-%dT%H:%M:%SZ'),
time_usage_ended=time_usage_ended.strftime('%Y-%m-%dT%H:%M:%SZ')
)
# usageClient.request_summarized_usages
request_summarized_usages = usageClient.request_summarized_usages(
requestSummarizedUsagesDetails,
retry_strategy=oci.retry.DEFAULT_RETRY_STRATEGY
)
################################
# Add all data to array data
################################
data = []
min_date = None
max_date = None
date_format = '%Y-%m-%d' if granularity == 'DAILY' else '%Y-%m'
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'pk': item.compartment_path + ":" + item.service,
'compartment': item.compartment_path,
'service': item.service,
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'sku_part_number': item.sku_part_number,
'sku_name': item.sku_name,