generated from oracle/template-repo
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathusage2adw.py
2214 lines (1863 loc) · 102 KB
/
usage2adw.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
##########################################################################
# Copyright (c) 2024, Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
#
# DISCLAIMER This is not an official Oracle application, It does not supported by Oracle Support,
# It should NOT be used for utilization calculation purposes, and rather OCI official Cost Analysis
# https://docs.oracle.com/en-us/iaas/Content/Billing/Concepts/costanalysisoverview.htm
# or Usage Report
# https://docs.oracle.com/en-us/iaas/Content/Billing/Concepts/usagereportsoverview.htm
# features should be used instead.
#
# usage2adw.py
#
# @author: Adi Zohar
#
# Supports Python 3 and above
#
# coding: utf-8
##########################################################################
# OCI Usage to ADWC:
#
# Required OCI user part of UsageDownloadGroup with below permission:
# define tenancy usage-report as ocid1.tenancy.oc1..aaaaaaaaned4fkpkisbwjlr56u7cj63lf3wffbilvqknstgtvzub7vhqkggq
# endorse group UsageDownloadGroup to read objects in tenancy usage-report
# Allow group UsageDownloadGroup to inspect compartments in tenancy
# Allow group UsageDownloadGroup to inspect tenancies in tenancy
# Allow group UsageDownloadGroup to read autonomous-database in compartment {APPCOMP}
# Allow group UsageDownloadGroup to read secret-bundles in compartment {APPCOMP}
#
##########################################################################
# Database user:
# create user usage identified by applicable_password;
# grant connect, resource, dwrole, unlimited tablespace to usage;
##########################################################################
#
# Modules Included:
# - oci.object_storage.ObjectStorageClient
# - oci.identity.IdentityClient
# - oci.secrets.SecretsClient
#
# APIs Used:
# - IdentityClient.list_compartments - Policy COMPARTMENT_INSPECT
# - IdentityClient.get_tenancy - Policy TENANCY_INSPECT
# - IdentityClient.list_region_subscriptions - Policy TENANCY_INSPECT
# - ObjectStorageClient.list_objects - Policy OBJECT_INSPECT
# - ObjectStorageClient.get_object - Policy OBJECT_READ
# - SecretsClient.get_secret_bundle - Policy SECRET_BUNDLE_READ
#
# Meter API for Public Rate:
# - https://apexapps.oracle.com/pls/apex/cetools/api/v1/products/?currencyCode=USD
#
##########################################################################
# Tables used:
# - OCI_USAGE - Raw data of the usage reports
# - OCI_USAGE_STATS - Summary Stats of the Usage Report for quick query if only filtered by tenant and date
# - OCI_USAGE_TAG_KEYS - Tag keys of the usage reports
# - OCI_COST - Raw data of the cost reports
# - OCI_COST_STATS - Summary Stats of the Cost Report for quick query if only filtered by tenant and date
# - OCI_COST_TAG_KEYS - Tag keys of the cost reports
# - OCI_COST_REFERENCE - Reference table of the cost filter keys - SERVICE, REGION, COMPARTMENT, PRODUCT, SUBSCRIPTION
# - OCI_PRICE_LIST - Hold the price list and the cost per product
# - OCI_LOAD_STATUS - Load Statistics table
# - OCI_TENANT - tenant information
# - OCI_INTERNAL_COST - used for internal rate cards
##########################################################################
import sys
import argparse
import datetime
import oci
import gzip
import os
import csv
import oracledb
import requests
import time
import base64
version = "25.01.01"
work_report_dir = os.curdir + "/work_report_dir"
# Init the Oracle Thick Client Library in order to use sqlnet.ora and instant client
oracledb.init_oracle_client()
# create the work dir if not exist
if not os.path.exists(work_report_dir):
os.mkdir(work_report_dir)
##########################################################################
# Print header centered
##########################################################################
def print_header(name, category):
options = {0: 90, 1: 60, 2: 30}
chars = int(options[category])
print("")
print('#' * chars)
print("#" + name.center(chars - 2, " ") + "#")
print('#' * chars)
##########################################################################
# get command line and mask password
##########################################################################
def get_command_line():
str = ""
was_password = False
for var in sys.argv[1:]:
str += " " if str else ""
str += "xxxxxxx" if was_password else var
was_password = (var == "-dp")
return str
##########################################################################
# Get Column from Array
##########################################################################
def get_column_value_from_array(column, array):
if column in array:
return array[column]
else:
return ""
##########################################################################
# Get Currnet Date Time
##########################################################################
def get_current_date_time():
return str(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
##########################################################################
# print count result
##########################################################################
def get_time_elapsed(start_time):
et = time.time() - start_time
return ", Process Time " + str('{:02d}:{:02d}:{:02d}'.format(round(et // 3600), (round(et % 3600 // 60)), round(et % 60)))
##########################################################################
# Create signer
##########################################################################
def create_signer(cmd):
# assign default values
config_file = oci.config.DEFAULT_LOCATION
config_section = oci.config.DEFAULT_PROFILE
if cmd.config:
if cmd.config.name:
config_file = cmd.config.name
if cmd.profile:
config_section = cmd.profile
if cmd.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
else:
config = oci.config.from_file(config_file, config_section)
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
##########################################################################
# Load compartments
##########################################################################
def identity_read_compartments(identity, tenancy):
compartments = []
print("Loading Compartments...")
try:
# read all compartments to variable
all_compartments = []
try:
all_compartments = oci.pagination.list_call_get_all_results(
identity.list_compartments,
tenancy.id,
compartment_id_in_subtree=True
).data
except oci.exceptions.ServiceError:
raise
###################################################
# Build Compartments - return nested compartment list
###################################################
def build_compartments_nested(identity_client, cid, path):
try:
compartment_list = [item for item in all_compartments if str(item.compartment_id) == str(cid)]
if path != "":
path = path + " / "
for c in compartment_list:
if c.lifecycle_state == oci.identity.models.Compartment.LIFECYCLE_STATE_ACTIVE:
cvalue = {'id': str(c.id), 'name': str(c.name), 'path': path + str(c.name)}
compartments.append(cvalue)
build_compartments_nested(identity_client, c.id, cvalue['path'])
except Exception as error:
raise Exception("Error in build_compartments_nested: " + str(error.args))
###################################################
# Add root compartment
###################################################
value = {'id': str(tenancy.id), 'name': str(tenancy.name) + " (root)", 'path': "/ " + str(tenancy.name) + " (root)"}
compartments.append(value)
# Build the compartments
build_compartments_nested(identity, str(tenancy.id), "")
# sort the compartment
sorted_compartments = sorted(compartments, key=lambda k: k['path'])
print(" Total " + str(len(sorted_compartments)) + " compartments loaded.")
return sorted_compartments
except oci.exceptions.RequestException:
raise
except Exception as e:
raise Exception("Error in identity_read_compartments: " + str(e.args))
##########################################################################
# Create signer for Secret
##########################################################################
def create_secret_signer(cmd):
# assign default values
config_file = oci.config.DEFAULT_LOCATION
config_section = oci.config.DEFAULT_PROFILE
instant_principle = True
if cmd.config:
if cmd.config.name:
config_file = cmd.config.name
if cmd.dsecret_profile:
instant_principle = (cmd.dsecret_profile == 'local')
config_section = cmd.dsecret_profile
if instant_principle:
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, for secret, aborting", 0)
raise SystemExit
else:
config = oci.config.from_file(config_file, config_section)
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
##########################################################################
# get_secret_password
##########################################################################
def get_secret_password(config, signer, proxy, secret_id):
try:
print("\nConnecting to Secret Client Service...")
secret_client = oci.secrets.SecretsClient(config, signer=signer)
if proxy:
secret_client.base_client.session.proxies = {'https': proxy}
print("Connected.")
secret_data = secret_client.get_secret_bundle(secret_id).data
print("Secret Retrieved.")
secret_bundle_content = secret_data.secret_bundle_content
secret_base64 = secret_bundle_content.content
secret_text_bytes = base64.b64decode(secret_base64)
secret_text = secret_text_bytes.decode('ASCII')
return secret_text
except oci.exceptions.ServiceError as e:
print("\nServiceError retrieving secret at get_secret_password !")
print("\n" + str(e) + "\n")
raise SystemExit
except Exception as e:
print("\nException retrieving secret at get_secret_password !")
print("\n" + str(e) + "\n")
raise SystemExit
##########################################################################
# set parser
##########################################################################
def set_parser_arguments():
parser = argparse.ArgumentParser()
parser.add_argument('-c', type=argparse.FileType('r'), dest='config', help="Config File")
parser.add_argument('-t', default="", dest='profile', help='Config file section to use (tenancy profile)')
parser.add_argument('-f', default="", dest='fileid', help='File Id to load')
parser.add_argument('-ts', default="", dest='tagspecial', help='tag special key 1 to load the data to TAG_SPECIAL column')
parser.add_argument('-ts2', default="", dest='tagspecial2', help='tag special key 2 to load the data to TAG_SPECIAL2 column')
parser.add_argument('-d', default="", dest='filedate', help='Minimum File Date to load (i.e. yyyy-mm-dd)')
parser.add_argument('-p', default="", dest='proxy', help='Set Proxy (i.e. www-proxy-server.com:80) ')
parser.add_argument('-su', action='store_true', default=False, dest='skip_usage', help='Skip Load Usage Files')
parser.add_argument('-sc', action='store_true', default=False, dest='skip_cost', help='Skip Load Cost Files')
parser.add_argument('-sr', action='store_true', default=False, dest='skip_rate', help='Skip Public Rate API')
parser.add_argument('-ip', action='store_true', default=False, dest='instance_principals', help='Use Instance Principals for Authentication')
parser.add_argument('-bn', default="", dest='bucket_name', help='Override Bucket Name for Cost and Usage Files')
parser.add_argument('-ns', default="bling", dest='namespace_name', help='Override Namespace Name for Cost and Usage Files (default=bling)')
parser.add_argument('-du', default="", dest='duser', help='ADB User')
parser.add_argument('-dn', default="", dest='dname', help='ADB Name')
parser.add_argument('-ds', default="", dest='dsecret_id', help='ADB Secret Id')
parser.add_argument('-dst', default="", dest='dsecret_profile', help='ADB Secret tenancy profile (local or blank = instant principle)')
parser.add_argument('--force', action='store_true', default=False, dest='force', help='Force Update without updated file')
parser.add_argument('--version', action='version', version='%(prog)s ' + version)
result = parser.parse_args()
if not (result.duser and result.dsecret_id and result.dname):
parser.print_help()
print_header("You must specify database credentials!!", 0)
return None
return result
##########################################################################
# Check Table Structure for usage
##########################################################################
def check_database_table_structure_usage(connection, tenant_name):
try:
# open cursor
with connection.cursor() as cursor:
# check if OCI_TENANT table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_TENANT'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table not exist, create it
if val == 0:
print(" Table OCI_TENANT was not exist, creating")
sql = """create table OCI_TENANT (
TENANT_ID VARCHAR2(100),
TENANT_NAME VARCHAR2(100),
ADMIN_EMAIL VARCHAR2(100),
INFORMATION VARCHAR2(1000),
CONSTRAINT OCI_TENANT_PK PRIMARY KEY (TENANT_ID) USING INDEX
) """
cursor.execute(sql)
print(" Table OCI_TENANT created")
else:
print(" Table OCI_TENANT exist")
# check if OCI_INTERNAL_COST table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_INTERNAL_COST'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table not exist, create it
if val == 0:
print(" Table OCI_INTERNAL_COST was not exist, creating")
sql = """create table OCI_INTERNAL_COST (
RESOURCE_NAME VARCHAR2(100) NOT NULL,
SERVICE_NAME VARCHAR2(100),
BILLED_USAGE_UNIT VARCHAR2(100),
CONSUMED_MEASURE VARCHAR2(100),
RESOURCE_UNITS VARCHAR2(100),
UNIT_COST NUMBER,
CONVERSION_FACTOR NUMBER,
EXIST_IN_FINANCE CHAR(1),
CONVERSION_NOTES VARCHAR2(500),
CONSTRAINT OCI_INTERNAL_COST_PK PRIMARY KEY (RESOURCE_NAME,BILLED_USAGE_UNIT) USING INDEX ENABLE
)"""
cursor.execute(sql)
print(" Table OCI_INTERNAL_COST created")
else:
print(" Table OCI_INTERNAL_COST exist")
# check if OCI_USAGE table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_USAGE'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table not exist, create it
if val == 0:
print(" Table OCI_USAGE was not exist, creating")
sql = """create table OCI_USAGE (
TENANT_NAME VARCHAR2(100),
TENANT_ID VARCHAR2(100),
FILE_ID VARCHAR2(30),
USAGE_INTERVAL_START DATE,
USAGE_INTERVAL_END DATE,
PRD_SERVICE VARCHAR2(100),
PRD_RESOURCE VARCHAR2(100),
PRD_COMPARTMENT_ID VARCHAR2(100),
PRD_COMPARTMENT_NAME VARCHAR2(100),
PRD_COMPARTMENT_PATH VARCHAR2(1000),
PRD_REGION VARCHAR2(100),
PRD_AVAILABILITY_DOMAIN VARCHAR2(100),
USG_RESOURCE_ID VARCHAR2(1000),
USG_BILLED_QUANTITY NUMBER,
USG_CONSUMED_QUANTITY NUMBER,
USG_CONSUMED_UNITS VARCHAR2(100),
USG_CONSUMED_MEASURE VARCHAR2(100),
IS_CORRECTION VARCHAR2(10),
TAGS_DATA VARCHAR2(4000),
TAG_SPECIAL VARCHAR2(4000),
TAG_SPECIAL2 VARCHAR2(4000)
) COMPRESS"""
cursor.execute(sql)
print(" Table OCI_USAGE created")
else:
print(" Table OCI_USAGE exist")
# check if TAGS_DATA columns exist in OCI_USAGE table, if not create
sql = "select count(*) from user_tab_columns where table_name = 'OCI_USAGE' and column_name='TAGS_DATA'"
cursor.execute(sql)
val, = cursor.fetchone()
# if columns TAGS_DATA not exist, create it
if val == 0:
print(" Column TAGS_DATA does not exist in the table OCI_USAGE, adding...")
sql = "alter table OCI_USAGE add (TAGS_DATA VARCHAR2(4000))"
cursor.execute(sql)
# check if TENANT_ID columns exist in OCI_USAGE table, if not create
sql = "select count(*) from user_tab_columns where table_name = 'OCI_USAGE' and column_name='TENANT_ID'"
cursor.execute(sql)
val, = cursor.fetchone()
# if columns TENANT_ID not exist, create it
if val == 0:
print(" Column TENANT_ID does not exist in the table OCI_USAGE, adding...")
sql = "alter table OCI_USAGE add (TENANT_ID VARCHAR2(100))"
cursor.execute(sql)
# check if TAG_SPECIAL columns exist in OCI_USAGE table, if not create
sql = "select count(*) from user_tab_columns where table_name = 'OCI_USAGE' and column_name='TAG_SPECIAL'"
cursor.execute(sql)
val, = cursor.fetchone()
# if columns TAG_SPECIAL not exist, create it
if val == 0:
print(" Column TAG_SPECIAL does not exist in the table OCI_USAGE, adding...")
sql = "alter table OCI_USAGE add (TAG_SPECIAL VARCHAR2(4000))"
cursor.execute(sql)
# check if TAG_SPECIAL2 columns exist in OCI_USAGE table, if not create
sql = "select count(*) from user_tab_columns where table_name = 'OCI_USAGE' and column_name='TAG_SPECIAL2'"
cursor.execute(sql)
val, = cursor.fetchone()
# if columns TAG_SPECIAL2 not exist, create it
if val == 0:
print(" Column TAG_SPECIAL2 does not exist in the table OCI_USAGE, adding...")
sql = "alter table OCI_USAGE add (TAG_SPECIAL2 VARCHAR2(4000))"
cursor.execute(sql)
# check if OCI_USAGE_TAG_KEYS table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_USAGE_TAG_KEYS'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table OCI_USAGE_TAG_KEYS not exist, create it
if val == 0:
print(" Table OCI_USAGE_TAG_KEYS was not exist, creating")
sql = """CREATE TABLE OCI_USAGE_TAG_KEYS (TENANT_NAME VARCHAR2(100), TAG_KEY VARCHAR2(1000),
CONSTRAINT OCI_USAGE_TAG_KEYS_PK PRIMARY KEY(TENANT_NAME,TAG_KEY)
)"""
cursor.execute(sql)
print(" Table OCI_USAGE_TAG_KEYS created")
else:
print(" Table OCI_USAGE_TAG_KEYS exist")
# check if OCI_USAGE_STATS table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_USAGE_STATS'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table OCI_USAGE_STATS not exist, create it
if val == 0:
print(" Table OCI_USAGE_STATS was not exist, creating")
sql = """CREATE TABLE OCI_USAGE_STATS (
TENANT_NAME VARCHAR2(100),
FILE_ID VARCHAR2(30),
USAGE_INTERVAL_START DATE,
NUM_ROWS NUMBER,
UPDATE_DATE DATE,
AGENT_VERSION VARCHAR2(30),
CONSTRAINT OCI_USAGE_STATS_PK PRIMARY KEY (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START)
)"""
cursor.execute(sql)
print(" Table OCI_USAGE_STATS created")
update_usage_stats(connection, tenant_name)
else:
print(" Table OCI_USAGE_STATS exist")
except oracledb.DatabaseError as e:
print("\nError manipulating database at check_database_table_structure_usage() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at check_database_table_structure_usage() - " + str(e))
##########################################################################
# Check Resource Table Structure
##########################################################################
def check_database_table_structure_resource(connection):
try:
# open cursor
with connection.cursor() as cursor:
# check if OCI_USAGE table exist, if not create
sql = "select count(*) from user_tables where table_name = 'OCI_RESOURCES'"
cursor.execute(sql)
val, = cursor.fetchone()
# if table not exist, create it
if val == 0:
print(" Table OCI_RESOURCES was not exist, creating")
sql = """create table OCI_RESOURCES (
RESOURCE_ID VARCHAR2(200) NOT NULL,
RESOURCE_NAME VARCHAR2(1000),
SOURCE_TENANT VARCHAR2(100),
SOURCE_TABLE VARCHAR2(100),
LAST_LOADED DATE,
CONSTRAINT OCI_RESOURCES_PK PRIMARY KEY (RESOURCE_ID) USING INDEX)"""
cursor.execute(sql)
print(" Table OCI_RESOURCES created")
else:
print(" Table OCI_RESOURCES exist")
except oracledb.DatabaseError as e:
print("\nError manipulating database at check_database_table_structure_resource() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at check_database_table_structure_resource() - " + str(e))
##########################################################################
# Check Index Structure Usage to be created after the first load
##########################################################################
def check_database_index_structure_usage(connection):
try:
# open cursor
with connection.cursor() as cursor:
# check if index OCI_USAGE_1IX exist in OCI_USAGE table, if not create
sql = "select count(*) from user_indexes where table_name = 'OCI_USAGE' and index_name='OCI_USAGE_1IX'"
cursor.execute(sql)
val, = cursor.fetchone()
# if index not exist, create it
if val == 0:
print("\nChecking Index for OCI_USAGE")
print(" Index OCI_USAGE_1IX does not exist for table OCI_USAGE, adding...")
sql = "CREATE INDEX OCI_USAGE_1IX ON OCI_USAGE(TENANT_NAME,USAGE_INTERVAL_START)"
cursor.execute(sql)
print(" Index created.")
except oracledb.DatabaseError as e:
print("\nError manipulating database at check_database_index_structure_usage() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at check_database_index_structure_usage() - " + str(e))
##########################################################################
# Check Index Structure Usage to be created after the first load
##########################################################################
def check_database_index_structure_cost(connection):
try:
# open cursor
with connection.cursor() as cursor:
# check if index OCI_USAGE_1IX exist in OCI_USAGE table, if not create
sql = "select count(*) from user_indexes where table_name = 'OCI_COST' and index_name='OCI_COST_1IX'"
cursor.execute(sql)
val, = cursor.fetchone()
# if index not exist, create it
if val == 0:
print("\nChecking Index for OCI_COST")
print(" Index OCI_COST_1IX does not exist for table OCI_COST, adding...")
sql = "CREATE INDEX OCI_COST_1IX ON OCI_COST(TENANT_NAME,USAGE_INTERVAL_START)"
cursor.execute(sql)
print(" Index created.")
except oracledb.DatabaseError as e:
print("\nError manipulating database at check_database_index_structure_cost() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at check_database_index_structure_cost() - " + str(e))
#########################################################################
# insert load stats
##########################################################################
def insert_load_stats(connection, tenant_name, file_type, file_id, file_name_full, file_size_mb, file_time, num_rows, start_time_str, batch_id, batch_total):
try:
with connection.cursor() as cursor:
sql = """INSERT INTO OCI_LOAD_STATUS (TENANT_NAME, FILE_TYPE, FILE_ID, FILE_NAME, FILE_SIZE, FILE_DATE, NUM_ROWS, LOAD_START_TIME, LOAD_END_TIME, AGENT_VERSION, BATCH_ID, BATCH_TOTAL)
VALUES (
:tenant_name,
:file_type,
:file_id,
:file_name,
:file_size,
to_date(:file_date,'YYYY-MM-DD HH24:MI'),
:num_rows,
to_date(:load_start_time,'YYYY-MM-DD HH24:MI:SS'),
to_date(:load_end_time,'YYYY-MM-DD HH24:MI:SS'),
:agent_version,
:batch_id,
:batch_total
)"""
cursor.execute(
sql,
tenant_name=tenant_name,
file_type=file_type,
file_id=file_id,
file_name=file_name_full,
file_size=file_size_mb,
file_date=file_time,
num_rows=num_rows,
load_start_time=start_time_str,
load_end_time=get_current_date_time(),
agent_version=version,
batch_id=batch_id,
batch_total=batch_total)
connection.commit()
except oracledb.DatabaseError as e:
print("\ninsert_load_stats() - Error manipulating database - " + str(e) + "\n")
except Exception as e:
print("\ninsert_load_stats() - Error insert into load_stats table - " + str(e))
raise SystemExit
##########################################################################
# update_cost_stats
##########################################################################
def update_cost_stats(connection, tenant_name):
try:
start_time = time.time()
# open cursor
with connection.cursor() as cursor:
print("\nMerging statistics into OCI_COST_STATS...")
# run merge to oci_update_stats
sql = """merge into OCI_COST_STATS a
using
(
select /*+ parallel(oci_cost,8) full(oci_cost) */
tenant_name,
file_id,
USAGE_INTERVAL_START,
sum(COST_MY_COST) COST_MY_COST,
sum(COST_MY_COST_OVERAGE) COST_MY_COST_OVERAGE,
min(COST_CURRENCY_CODE) COST_CURRENCY_CODE,
count(*) NUM_ROWS
from
oci_cost
where
tenant_name = :tenant_name
group by
tenant_name,
file_id,
USAGE_INTERVAL_START
) b
on (a.tenant_name=b.tenant_name and a.file_id=b.file_id and a.USAGE_INTERVAL_START=b.USAGE_INTERVAL_START)
when matched then update set a.num_rows=b.num_rows, a.COST_MY_COST=b.COST_MY_COST, a.UPDATE_DATE=sysdate, a.AGENT_VERSION=:version,
a.COST_MY_COST_OVERAGE=b.COST_MY_COST_OVERAGE, a.COST_CURRENCY_CODE=b.COST_CURRENCY_CODE
where a.num_rows <> b.num_rows
when not matched then insert (TENANT_NAME,FILE_ID,USAGE_INTERVAL_START,NUM_ROWS,COST_MY_COST,UPDATE_DATE,AGENT_VERSION,COST_MY_COST_OVERAGE,COST_CURRENCY_CODE)
values (b.TENANT_NAME,b.FILE_ID,b.USAGE_INTERVAL_START,b.NUM_ROWS,b.COST_MY_COST,sysdate,:version,b.COST_MY_COST_OVERAGE,b.COST_CURRENCY_CODE)
"""
cursor.execute(sql, version=version, tenant_name=tenant_name)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
except oracledb.DatabaseError as e:
print("\nError manipulating database at update_cost_stats() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at update_cost_stats() - " + str(e))
##########################################################################
# update_price_list
##########################################################################
def update_price_list(connection, tenant_name):
try:
start_time = time.time()
# open cursor
with connection.cursor() as cursor:
print("\nMerging statistics into OCI_PRICE_LIST...")
# run merge to oci_update_stats
sql = """MERGE INTO OCI_PRICE_LIST A
USING
(
SELECT
TENANT_NAME,
TENANT_ID,
COST_PRODUCT_SKU,
PRD_DESCRIPTION,
COST_CURRENCY_CODE,
COST_UNIT_PRICE
FROM
(
SELECT /*+ parallel(a,8) full(a) */
TENANT_NAME,
TENANT_ID,
COST_PRODUCT_SKU,
PRD_DESCRIPTION,
COST_CURRENCY_CODE,
COST_UNIT_PRICE,
ROW_NUMBER() OVER (PARTITION BY TENANT_NAME, TENANT_ID, COST_PRODUCT_SKU ORDER BY USAGE_INTERVAL_START DESC, COST_UNIT_PRICE DESC) RN
FROM OCI_COST A where tenant_id is not null and tenant_name=:tenant_name
)
WHERE RN = 1
ORDER BY 1,2
) B
ON (A.TENANT_NAME = B.TENANT_NAME AND A.TENANT_ID = B.TENANT_ID AND A.COST_PRODUCT_SKU = B.COST_PRODUCT_SKU)
WHEN MATCHED THEN UPDATE SET A.PRD_DESCRIPTION=B.PRD_DESCRIPTION, A.COST_CURRENCY_CODE=B.COST_CURRENCY_CODE, A.COST_UNIT_PRICE=B.COST_UNIT_PRICE, COST_LAST_UPDATE = SYSDATE
WHEN NOT MATCHED THEN INSERT (TENANT_NAME,TENANT_ID,COST_PRODUCT_SKU,PRD_DESCRIPTION,COST_CURRENCY_CODE,COST_UNIT_PRICE,COST_LAST_UPDATE)
VALUES (B.TENANT_NAME,B.TENANT_ID, B.COST_PRODUCT_SKU,B.PRD_DESCRIPTION,B.COST_CURRENCY_CODE,B.COST_UNIT_PRICE,SYSDATE)
"""
cursor.execute(sql, tenant_name=tenant_name)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
start_time = time.time()
print("\nUpdate OCI_PRICE_LIST for empty currency...")
# update currency when currency is null
sql = """update OCI_PRICE_LIST
set COST_CURRENCY_CODE =
(
select COST_CURRENCY_CODE
from (SELECT /*+ parallel(a,8) full(a) */
COST_CURRENCY_CODE,
ROW_NUMBER() OVER (PARTITION BY TENANT_NAME ORDER BY USAGE_INTERVAL_START DESC) RN
FROM OCI_COST A where COST_CURRENCY_CODE is not null and tenant_name=:tenant_name
) where rn=1
)
where COST_CURRENCY_CODE is null and tenant_name=:tenant_name
"""
cursor.execute(sql, tenant_name=tenant_name)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
except oracledb.DatabaseError as e:
print("\nError manipulating database at update_price_list() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at update_price_list() - " + str(e))
##########################################################################
# update_cost_reference
##########################################################################
def update_cost_reference(connection, tag_special_key, tag_special_key2, tenant_name):
try:
start_time = time.time()
# open cursor
with connection.cursor() as cursor:
print("\nMerging statistics into OCI_COST_REFERENCE ...")
print(" Merging statistics from OCI_COST...")
#######################################################
# run merge to OCI_COST_REFERENCE
#######################################################
sql = """merge into OCI_COST_REFERENCE a
using
(
select TENANT_NAME, REF_TYPE, REF_NAME
from
(
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'PRD_SERVICE' as REF_TYPE, PRD_SERVICE as REF_NAME from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'PRD_COMPARTMENT_PATH' as REF_TYPE,
case when prd_compartment_path like '%/%' then substr(prd_compartment_path,1,instr(prd_compartment_path,' /')-1)
else prd_compartment_path end as REF_NAME
from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'TENANT_ID' as REF_TYPE, TENANT_ID as ref_name from OCI_COST where tenant_id is not null and :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'PRD_COMPARTMENT_NAME' as REF_TYPE, PRD_COMPARTMENT_NAME as ref_name from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'PRD_REGION' as REF_TYPE, PRD_REGION as ref_name from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'COST_SUBSCRIPTION_ID' as REF_TYPE, to_char(COST_SUBSCRIPTION_ID) as ref_name from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'TAG_SPECIAL' as REF_TYPE, TAG_SPECIAL as ref_name from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'TAG_SPECIAL2' as REF_TYPE, TAG_SPECIAL2 as ref_name from OCI_COST where :tenant_name = TENANT_NAME
union all
select /*+ parallel(oci_cost,8) full(oci_cost) */ distinct TENANT_NAME, 'COST_PRODUCT_SKU' as REF_TYPE, COST_PRODUCT_SKU || ' '||min(PRD_DESCRIPTION) as ref_name from OCI_COST where :tenant_name = TENANT_NAME
group by TENANT_NAME, COST_PRODUCT_SKU
) where ref_name is not null
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE and a.REF_NAME=b.REF_NAME)
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
if tag_special_key:
start_time = time.time()
# run merge to OCI_COST_REFERENCE for the tag special key
print(" Handling Tag Special Key '" + tag_special_key + "'")
sql = """merge into OCI_COST_REFERENCE a
using
(
select :tenant_name as TENANT_NAME, 'TAG_SPECIAL_KEY' as REF_TYPE, :tag_special_key as ref_name from DUAL
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE)
when matched then update set a.ref_name = b.ref_name
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name, tag_special_key=tag_special_key)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
if tag_special_key2:
start_time = time.time()
# run merge to OCI_COST_REFERENCE for the tag special key
print(" Handling Tag Special Key '" + tag_special_key2 + "'")
sql = """merge into OCI_COST_REFERENCE a
using
(
select :tenant_name as TENANT_NAME, 'TAG_SPECIAL_KEY2' as REF_TYPE, :tag_special_key2 as ref_name from DUAL
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE)
when matched then update set a.ref_name = b.ref_name
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name, tag_special_key2=tag_special_key2)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
except oracledb.DatabaseError as e:
print("\nError manipulating database at update_cost_reference() - " + str(e) + "\n")
raise SystemExit
except Exception as e:
raise Exception("\nError manipulating database at update_cost_reference() - " + str(e))
##########################################################################
# update_usage_reference
##########################################################################
def update_usage_reference(connection, tag_special_key, tag_special_key2, tenant_name):
try:
start_time = time.time()
# open cursor
with connection.cursor() as cursor:
print("\nMerging statistics into OCI_COST_REFERENCE ...")
print(" Merging statistics from OCI_USAGE...")
#######################################################
# run merge to OCI_COST_REFERENCE from OCI_USAGE
#######################################################
sql = """merge into OCI_COST_REFERENCE a
using
(
select TENANT_NAME, REF_TYPE, REF_NAME
from
(
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_PRD_SERVICE' as REF_TYPE, PRD_SERVICE as REF_NAME from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_PRD_COMPARTMENT_PATH' as REF_TYPE,
case when prd_compartment_path like '%/%' then substr(prd_compartment_path,1,instr(prd_compartment_path,' /')-1)
else prd_compartment_path end as REF_NAME
from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_TENANT_ID' as REF_TYPE, TENANT_ID as ref_name from OCI_USAGE where tenant_id is not null and :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_PRD_COMPARTMENT_NAME' as REF_TYPE, PRD_COMPARTMENT_NAME as ref_name from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_PRD_REGION' as REF_TYPE, PRD_REGION as ref_name from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_PRD_RESOURCE' as REF_TYPE, PRD_RESOURCE as ref_name from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_TAG_SPECIAL' as REF_TYPE, TAG_SPECIAL as ref_name from OCI_USAGE where :tenant_name = TENANT_NAME
union all
select /*+ parallel(OCI_USAGE,8) full(OCI_USAGE) */ distinct TENANT_NAME, 'USAGE_TAG_SPECIAL2' as REF_TYPE, TAG_SPECIAL2 as ref_name from OCI_USAGE where :tenant_name = TENANT_NAME
) where ref_name is not null
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE and a.REF_NAME=b.REF_NAME)
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
if tag_special_key:
start_time = time.time()
# run merge to OCI_COST_REFERENCE for the tag special key
print(" Handling Tag Special Key '" + tag_special_key + "'")
sql = """merge into OCI_COST_REFERENCE a
using
(
select :tenant_name as TENANT_NAME, 'TAG_SPECIAL_KEY' as REF_TYPE, :tag_special_key as ref_name from DUAL
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE)
when matched then update set a.ref_name = b.ref_name
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name, tag_special_key=tag_special_key)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
if tag_special_key2:
start_time = time.time()
# run merge to OCI_COST_REFERENCE for the tag special key
print(" Handling Tag Special Key '" + tag_special_key2 + "'")
sql = """merge into OCI_COST_REFERENCE a
using
(
select :tenant_name as TENANT_NAME, 'TAG_SPECIAL_KEY2' as REF_TYPE, :tag_special_key2 as ref_name from DUAL
) b
on (a.TENANT_NAME=b.TENANT_NAME and a.REF_TYPE=b.REF_TYPE)
when matched then update set a.ref_name = b.ref_name
when not matched then insert (TENANT_NAME,REF_TYPE,REF_NAME)
values (b.TENANT_NAME,b.REF_TYPE,b.REF_NAME)
"""
cursor.execute(sql, tenant_name=tenant_name, tag_special_key2=tag_special_key2)
connection.commit()
print(" Merge Completed, " + str(cursor.rowcount) + " rows merged" + get_time_elapsed(start_time))
except oracledb.DatabaseError as e:
print("\nError manipulating database at update_usage_reference() - " + str(e) + "\n")
raise SystemExit