forked from tonymarkel/oci-usage-to-data-dog-metrics
-
Notifications
You must be signed in to change notification settings - Fork 0
/
showusage.py
700 lines (605 loc) · 27.8 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
# coding: utf-8
# Copyright (c) 2016, 2023, 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
#
# @authors:
# Adi Zohar, Oct 07 2021
# Tony Markel, Oct 31 2021
#
# 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
# -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)
# -report type - Report Type = PRODUCT, DAILY, REGION
#
#
##########################################################################
# 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
version = "2023.05.16"
##########################################################################
# 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'
)
##########################################################################
# 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
##########################################################################
# Usage Daily by Product
##########################################################################
def usage_daily_product(usageClient, tenant_id, time_usage_started, time_usage_ended):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity='DAILY',
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
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'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,
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'currency': item.currency,
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency:
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
################################
# Grouped Dict
################################
gdata = {}
for item in data:
sku = item['sku']
if sku not in gdata:
gdata[sku] = {'cost': item['cost'], 'quantity': item['quantity'], 'sku_name': item['sku_name'], 'currency': item['currency']}
else:
gdata[sku]['cost'] += item['cost']
gdata[sku]['quantity'] += item['quantity']
################################
# Compact based on SKUs
################################
col = {
'product': 65,
'quantity': 14,
'days': 10,
'cost': 13,
'month': 13,
'year': 13
}
days = (max_date - min_date).days + 1
product_header = "Product Summary for " + min_date.strftime('%m/%d/%Y') + " - " + max_date.strftime('%m/%d/%Y') + " in " + currency
print_header(product_header, 3)
print("")
print(
"Product".ljust(col['product']) +
" Days".rjust(col['days']) +
" Quantity".rjust(col['quantity']) +
" Cost".rjust(col['cost']) +
" Month-31".rjust(col['month']) +
" Year".rjust(col['year'])
)
print(
"".ljust(col['product'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
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['sku_name'].ljust(col['product'])[0:col['product']]
line += "{:8,.0f}".format(days).rjust(col['days'])
line += "{:8,.1f}".format(item['quantity']).rjust(col['quantity'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
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['days'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
print(
"Total ".ljust(col['product'] + col['days'] + col['quantity']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
" {:9,.0f}".format(total / days * 31).rjust(col['month']) +
" {:9,.0f}".format(total / days * 365).rjust(col['year'])
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_daily_product' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_daily_product' - " + str(e))
##########################################################################
# Usage Daily by Region
##########################################################################
def usage_daily_region(usageClient, tenant_id, time_usage_started, time_usage_ended):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity='DAILY',
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
currency = ""
for item in request_summarized_usages.data.items:
data.append({
'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,
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
if item.currency:
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
################################
# Grouped Dict
################################
gdata = {}
for item in data:
region = item['region']
if region not in gdata:
gdata[region] = {'cost': item['cost'], 'quantity': item['quantity'], 'currency': item['currency']}
else:
gdata[region]['cost'] += item['cost']
gdata[region]['quantity'] += item['quantity']
################################
# Compact based on SKUs
################################
col = {
'region': 15,
'quantity': 14,
'days': 10,
'cost': 13,
'month': 13,
'year': 13
}
days = (max_date - min_date).days + 1
product_header = "Region Summary for " + min_date.strftime('%m/%d/%Y') + " - " + max_date.strftime('%m/%d/%Y') + " in " + currency
print_header(product_header, 3)
print("")
print(
"Region".ljust(col['region']) +
" Days".rjust(col['days']) +
" Quantity".rjust(col['quantity']) +
" Cost".rjust(col['cost']) +
" Month-31".rjust(col['month']) +
" Year".rjust(col['year'])
)
print(
"".ljust(col['region'], '=') +
" ".ljust(col['days'], '=') +
" ".ljust(col['quantity'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
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['quantity']).rjust(col['quantity'])
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
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['quantity'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
print(
"Total ".ljust(col['region'] + col['days'] + col['quantity']) +
" {:8,.1f}".format(total).rjust(col['cost']) +
" {:9,.0f}".format(total / days * 31).rjust(col['month']) +
" {:9,.0f}".format(total / days * 365).rjust(col['year'])
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_daily_region' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_daily_region' - " + str(e))
##########################################################################
# Usage Daily Summary
##########################################################################
def usage_daily_summary(usageClient, tenant_id, time_usage_started, time_usage_ended):
try:
# oci.usage_api.models.RequestSummarizedUsagesDetails
requestSummarizedUsagesDetails = oci.usage_api.models.RequestSummarizedUsagesDetails(
tenant_id=tenant_id,
granularity='DAILY',
query_type='COST',
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
for item in request_summarized_usages.data.items:
data.append({
'day': item.time_usage_started.strftime('%Y-%m-%d'),
'cost': item.computed_amount if item.computed_amount else 0,
'quantity': item.computed_quantity if item.computed_quantity else 0,
'currency': item.currency,
'time_usage_started': item.time_usage_started,
'time_usage_ended': item.time_usage_ended
})
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
################################
# Grouped Dict
################################
gdata = {}
for item in data:
day = item['day']
if day not in gdata:
gdata[day] = {'cost': item['cost'], 'quantity': item['quantity'], 'currency': item['currency']}
else:
gdata[day]['cost'] += item['cost']
gdata[day]['quantity'] += item['quantity']
################################
# Compact based on SKUs
################################
col = {
'day': 15,
'cost': 15,
'month': 15,
'year': 15
}
product_header = "Daily Summary for " + min_date.strftime('%m/%d/%Y') + " - " + max_date.strftime('%m/%d/%Y')
print_header(product_header, 3)
print("")
print(
"Day".ljust(col['day']) +
" Cost".rjust(col['cost']) +
" Month-31".rjust(col['month']) +
" Year".rjust(col['year'])
)
print(
"".ljust(col['day'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
total = 0
for item_key in sorted(gdata, key=lambda x: x):
item = gdata[item_key]
if item['cost'] == 0:
continue
total += item['cost']
line = item_key.ljust(col['day'])[0:col['day']]
line += "{:8,.1f}".format(item['cost']).rjust(col['cost'])
line += "{:9,.0f}".format(item['cost'] * 31).rjust(col['month'])
line += "{:9,.0f}".format(item['cost'] * 365).rjust(col['year'])
print(line)
# Total
print(
"".ljust(col['day'], '=') +
" ".ljust(col['cost'], '=') +
" ".ljust(col['month'], '=') +
" ".ljust(col['year'], '=')
)
print(
"Total ".ljust(col['day']) +
" {:8,.1f}".format(total).rjust(col['cost'])
)
except oci.exceptions.ServiceError as e:
print("\nService Error at 'usage_daily_summary' - " + str(e))
except Exception as e:
print("\nException Error at 'usage_daily_summary' - " + str(e))
##########################################################################
# Main Process
##########################################################################
def main():
# Get Command Line Parser
# parser = argparse.ArgumentParser()
parser = argparse.ArgumentParser(usage=argparse.SUPPRESS, formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=80, width=130))
parser.add_argument('-c', default="", dest='config_file', help='OCI CLI Config file')
parser.add_argument('-t', default="", dest='config_profile', help='Config Profile inside the config file')
parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ')
parser.add_argument('-ip', action='store_true', default=False, dest='is_instance_principals', help='Use Instance Principals for Authentication')
parser.add_argument('-dt', action='store_true', default=False, dest='is_delegation_token', help='Use Delegation Token for Authentication')
parser.add_argument("-ds", default=None, dest='date_start', help="Start Date - format YYYY-MM-DD", type=valid_date_type)
parser.add_argument("-de", default=None, dest='date_end', help="End Date - format YYYY-MM-DD, (Not Inclusive)", type=valid_date_type)
parser.add_argument("-days", default=None, dest='days', help="Add Days Combined with Start Date (de is ignored if specified)", type=int)
parser.add_argument("-report", default="ALL", dest='report', help="Report Type = PRODUCT / DAILY / REGION / ALL ( Default = ALL )")
cmd = parser.parse_args()
if len(sys.argv) < 2:
parser.print_help()
return
if not cmd.report or not (cmd.report == "DAILY" or cmd.report == "PRODUCT" or cmd.report == "REGION" or cmd.report == "ALL"):
parser.print_help()
print("")
print("**********************************************************")
print("*** You must specify report type ! ***")
print("*** DAILY = Daily cost ***")
print("*** PRODUCT = Product Summary Cost ***")
print("*** ALL = All Reports ***")
print("**********************************************************")
return None
if not (cmd.date_start):
parser.print_help()
print("")
print("**********************************************************")
print("*** You must specify date range!! ***")
print("*** Either DATE_START+DAYS or DATE_START+DATE_END ***")
print("**********************************************************")
return None
# Start print time info
print_header("Running Show Usage", 0)
print("Author : Adi Zohar")
print("Disclaimer : This is not an official Oracle application, It does not supported by Oracle, It should NOT be used for utilization calculation purposes !")
print(" : Last 2 days may not be filled and should not be used")
print("Machine : " + platform.node() + " (" + platform.machine() + ")")
print("App Version : " + version)
print("OCI SDK Version : " + oci.version.__version__)
print("Python Version : " + platform.python_version())
if cmd.is_instance_principals:
print("Authentication : Instance Principals")
elif cmd.is_delegation_token:
print("Authentication : Instance Principals With Delegation Token")
else:
print("Authentication : Config File")
print("Date/Time : " + str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
print("Command Line : " + ' '.join(x for x in sys.argv[1:]))
############################################
# Date Validation
############################################
time_usage_started = None
time_usage_ended = None
report_type = cmd.report
if cmd.date_start and cmd.date_start > datetime.datetime.now():
print("\n!!! Error, Start date cannot be in the future !!!")
sys.exit()
if cmd.date_start and cmd.date_end and cmd.date_start > cmd.date_end:
print("\n!!! Error, Start date cannot be greater than End date !!!")
sys.exit()
if cmd.date_start:
time_usage_started = cmd.date_start
if cmd.days:
time_usage_ended = time_usage_started + datetime.timedelta(days=cmd.days)
elif cmd.date_end:
time_usage_ended = cmd.date_end
else:
time_usage_ended = time_usage_started + datetime.timedelta(days=1)
print("Start Date : " + time_usage_started.strftime('%m/%d/%Y'))
print("End Date : " + time_usage_ended.strftime('%m/%d/%Y') + " Not Included")
############################################
# Days check
############################################
days = (time_usage_ended - time_usage_started).days
if days > 93:
print("\n!!! Error, Max 93 days period allowed, input is " + str(days) + " days, !!!")
sys.exit()
############################################
# create signer
############################################
config, signer = create_signer(cmd.config_file, cmd.config_profile, cmd.is_instance_principals, cmd.is_delegation_token)
tenant_id = ""
print_header("Fetching data", 0)
try:
print("\nConnecting to Identity Service...\n")
identity = oci.identity.IdentityClient(config, signer=signer)
if cmd.proxy:
identity.base_client.session.proxies = {'https': cmd.proxy}
tenancy = identity.get_tenancy(config["tenancy"]).data
regions = identity.list_region_subscriptions(tenancy.id).data
tenant_id = tenancy.id
# Set home region for connection
for reg in regions:
if reg.is_home_region:
tenancy_home_region = str(reg.region_name)
config['region'] = tenancy_home_region
signer.region = tenancy_home_region
print("Tenant Name : " + str(tenancy.name))
print("Tenant Id : " + tenancy.id)
print("Home Region : " + tenancy_home_region)
except Exception as e:
raise RuntimeError("\nError fetching tenant information - " + str(e))
############################################
# Connection to UsageAPI
############################################
try:
print("\nConnecting to UsageAPI Service...")
usage_client = oci.usage_api.UsageapiClient(config, signer=signer)
if cmd.proxy:
usage_client.base_client.session.proxies = {'https': cmd.proxy}
if report_type == 'DAILY' or report_type == 'ALL':
usage_daily_summary(usage_client, tenant_id, time_usage_started, time_usage_ended)
if report_type == 'PRODUCT' or report_type == 'ALL':
usage_daily_product(usage_client, tenant_id, time_usage_started, time_usage_ended)
if report_type == 'REGION' or report_type == 'ALL':
usage_daily_region(usage_client, tenant_id, time_usage_started, time_usage_ended)
except Exception as e:
raise RuntimeError("\nError at main function - " + str(e))
##########################################################################
# Main Process
##########################################################################
main()