forked from GoogleCloudPlatform/datacatalog-tag-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataCatalogUtils.py
2143 lines (1625 loc) · 91.4 KB
/
DataCatalogUtils.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
# Copyright 2020-2021 Google, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests, configparser, time
from datetime import datetime, date
from datetime import time as dtime
import pytz
from operator import itemgetter
import pandas as pd
from pyarrow import parquet
import json
import os
from google.protobuf.timestamp_pb2 import Timestamp
from google.cloud import datacatalog
from google.cloud.datacatalog_v1 import types
from google.cloud.datacatalog import DataCatalogClient
from google.cloud import bigquery
from google.cloud import storage
import Resources as res
import TagEngineUtils as te
import BigQueryUtils as bq
import PubSubUtils as ps
import constants
config = configparser.ConfigParser()
config.read("tagengine.ini")
BIGQUERY_REGION = config['DEFAULT']['BIGQUERY_REGION']
class DataCatalogUtils:
def __init__(self, template_id=None, template_project=None, template_region=None):
self.template_id = template_id
self.template_project = template_project
self.template_region = template_region
self.client = DataCatalogClient()
if template_id is not None and template_project is not None and template_region is not None:
self.template_path = DataCatalogClient.tag_template_path(template_project, template_region, template_id)
def get_template(self, included_fields=None):
fields = []
tag_template = self.client.get_tag_template(name=self.template_path)
for field_id, field_value in tag_template.fields.items():
field_id = str(field_id)
if included_fields:
match_found = False
for included_field in included_fields:
if included_field['field_id'] == field_id:
match_found = True
if 'field_value' in included_field:
assigned_value = included_field['field_value']
else:
assigned_value = None
if 'query_expression' in included_field:
query_expression = included_field['query_expression']
else:
query_expression = None
break
if match_found == False:
continue
display_name = field_value.display_name
is_required = field_value.is_required
order = field_value.order
#print("field_id: " + str(field_id))
#print("field_value: " + str(field_value))
#print("display_name: " + display_name)
#print("primitive_type: " + str(FieldType.primitive_type))
#print("is_required: " + str(is_required))
enum_values = []
field_type = None
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.DOUBLE:
field_type = "double"
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.STRING:
field_type = "string"
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.BOOL:
field_type = "bool"
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.TIMESTAMP:
field_type = "datetime"
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.RICHTEXT:
field_type = "richtext"
if field_value.type_.primitive_type == datacatalog.FieldType.PrimitiveType.PRIMITIVE_TYPE_UNSPECIFIED:
field_type = "enum"
index = 0
enum_values_long = str(field_value.type_).split(":")
for long_value in enum_values_long:
if index > 0:
enum_value = long_value.split('"')[1]
#print("enum value: " + enum_value)
enum_values.append(enum_value)
index = index + 1
# populate dict
field = {}
field['field_id'] = field_id
field['display_name'] = display_name
field['field_type'] = field_type
field['is_required'] = is_required
field['order'] = order
if field_type == "enum":
field['enum_values'] = enum_values
if included_fields:
if assigned_value:
field['field_value'] = assigned_value
if query_expression:
field['query_expression'] = query_expression
fields.append(field)
return sorted(fields, key=itemgetter('order'), reverse=True)
def check_if_exists(self, parent, column=None):
#print('enter check_if_exists')
#print('input parent: ' + parent)
#print('input column: ' + column)
tag_exists = False
tag_id = ""
if column != None and column != "" and len(column) > 1:
column = column.lower() # column is stored in lower case in the tag object
tag_list = self.client.list_tags(parent=parent, timeout=120)
for tag_instance in tag_list:
#print('tag_instance: ' + str(tag_instance))
#print('tag name: ' + str(tag_instance.name))
tagged_column = tag_instance.column
#print('found tagged column: ' + tagged_column)
tagged_template_project = tag_instance.template.split('/')[1]
tagged_template_location = tag_instance.template.split('/')[3]
tagged_template_id = tag_instance.template.split('/')[5]
if column == '' or column == None:
# looking for a table-level tag
if tagged_template_id == self.template_id and tagged_template_project == self.template_project and \
tagged_template_location == self.template_region and tagged_column == "":
#print('DEBUG: table-level tag exists.')
tag_exists = True
tag_id = tag_instance.name
#print('DEBUG: tag_id: ' + tag_id)
break
else:
if column == tagged_column and tagged_template_id == self.template_id and tagged_template_project == self.template_project and \
tagged_template_location == self.template_region:
#print('DEBUG: column-level tag exists.')
tag_exists = True
tag_id = tag_instance.name
#print('DEBUG: tag_id: ' + tag_id)
break
#print('DEBUG: tag_exists: ' + str(tag_exists))
#print('DEBUG: tag_id: ' + str(tag_id))
return tag_exists, tag_id
def apply_static_asset_config(self, fields, uri, config_uuid, template_uuid, tag_history, tag_stream, overwrite=False):
print('*** apply_static_asset_config ***')
print('fields: ', fields)
print('uri: ', uri)
print('config_uuid: ', config_uuid)
print('template_uuid: ', template_uuid)
print('tag_history: ', tag_history)
# uri is either a BQ table/view path or GCS file path
store = te.TagEngineUtils()
creation_status = constants.SUCCESS
column = ''
is_gcs = False
is_bq = False
# look up the entry based on the resource type
if isinstance(uri, list):
is_gcs = True
bucket = uri[0].replace('-', '_')
filename = uri[1].split('.')[0].replace('/', '_') # extract the filename without extension, replace '/' with '_'
gcs_resource = '//datacatalog.googleapis.com/projects/' + self.template_project + '/locations/' + self.template_region + '/entryGroups/' + bucket + '/entries/' + filename
print('gcs_resource: ', gcs_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=gcs_resource
uri = '/'.join(uri)
#print('uri:', uri)
try:
entry = self.client.lookup_entry(request)
print('GCS entry:', entry.name)
except Exception as e:
print('Unable to find the entry in the catalog. Entry ' + gcs_resource + ' does not exist.')
creation_status = constants.ERROR
return creation_status
elif isinstance(uri, str):
is_bq = True
bigquery_resource = '//bigquery.googleapis.com/projects/' + uri
print("bigquery_resource: " + bigquery_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=bigquery_resource
entry = self.client.lookup_entry(request)
print('entry: ', entry.name)
try:
tag_exists, tag_id = self.check_if_exists(parent=entry.name)
print('tag exists: ', tag_exists)
except Exception as e:
print('Error during check_if_exists: ', e)
creation_status = constants.ERROR
return creation_status
if tag_exists and overwrite == False:
#print('Tag already exists and overwrite set to False')
creation_status = constants.SUCCESS
return creation_status
creation_status = self.create_update_tag(fields, tag_exists, tag_id, config_uuid, 'STATIC_ASSET_TAG', tag_history, tag_stream, entry, uri)
return creation_status
def apply_dynamic_table_config(self, fields, uri, config_uuid, template_uuid, tag_history, tag_stream, batch_mode=False):
print('*** apply_dynamic_table_config ***')
print('fields:', fields)
print('uri:', uri)
print('config_uuid:', config_uuid)
print('template_uuid:', template_uuid)
print('tag_history:', tag_history)
print('tag_stream:', tag_stream)
store = te.TagEngineUtils()
bq_client = bigquery.Client(location=BIGQUERY_REGION)
creation_status = constants.SUCCESS
error_exists = False
bigquery_resource = '//bigquery.googleapis.com/projects/' + uri
#print('bigquery_resource: ', bigquery_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=bigquery_resource
entry = self.client.lookup_entry(request)
tag_exists, tag_id = self.check_if_exists(parent=entry.name)
#print("tag_exists: " + str(tag_exists))
# create new tag
tag = datacatalog.Tag()
tag.template = self.template_path
verified_field_count = 0
for field in fields:
field_id = field['field_id']
field_type = field['field_type']
query_expression = field['query_expression']
# parse and run query in BQ
query_str = self.parse_query_expression(uri, query_expression)
#print('returned query_str: ' + query_str)
# note: field_values is of type list
field_values, error_exists = self.run_query(bq_client, query_str, field_type, batch_mode, store)
#print('field_values: ', field_values)
#print('error_exists: ', error_exists)
if error_exists or field_values == []:
continue
tag, error_exists = self.populate_tag_field(tag, field_id, field_type, field_values, store)
if error_exists:
continue
verified_field_count = verified_field_count + 1
#print('verified_field_count: ' + str(verified_field_count))
# store the value back in the dict, so that it can be accessed by the exporter
#print('field_value: ' + str(field_value))
if field_type == 'richtext':
formatted_value = ', '.join(str(v) for v in field_values)
else:
formatted_value = field_values[0]
field['field_value'] = formatted_value
# for loop ends here
if error_exists:
# error was encountered while running SQL expression
# proceed with tag creation / update, but return error to user
creation_status = constants.ERROR
if verified_field_count == 0:
# tag is empty due to errors, skip tag creation
return constants.ERROR
if tag_exists == True:
#print('updating tag')
#print('tag request: ' + str(tag))
tag.name = tag_id
try:
print('tag update request: ', tag)
response = self.client.update_tag(tag=tag)
#print('response: ', response)
except Exception as e:
print('Error occurred during tag update: ' + str(e))
msg = 'Error occurred during tag update: ' + str(e)
store.write_tag_op_error(constants.TAG_UPDATED, config_uuid, 'DYNAMIC_TABLE_TAG', msg)
creation_status = constants.ERROR
else:
try:
print('tag create request: ', tag)
response = self.client.create_tag(parent=entry.name, tag=tag)
#print('response: ', response)
except Exception as e:
print('Error occurred during tag create: ', e)
msg = 'Error occurred during tag create: ' + str(e)
store.write_tag_op_error(constants.TAG_CREATED, config_uuid, 'DYNAMIC_TABLE_TAG', msg)
creation_status = constants.ERROR
if creation_status == constants.SUCCESS and tag_history:
bqu = bq.BigQueryUtils()
template_fields = self.get_template()
bqu.copy_tag(self.template_id, template_fields, uri, None, fields)
if creation_status == constants.SUCCESS and tag_stream:
psu = ps.PubSubUtils()
psu.copy_tag(self.template_id, uri, None, fields)
return creation_status
def apply_dynamic_column_config(self, fields, columns_query, uri, config_uuid, template_uuid, tag_history, tag_stream, batch_mode=False):
print('*** apply_dynamic_column_config ***')
#print('fields:', fields)
#print('columns_query', columns_query)
#print('uri:', uri)
#print('config_uuid:', config_uuid)
#print('template_uuid:', template_uuid)
#print('tag_history:', tag_history)
#print('tag_stream:', tag_stream)
store = te.TagEngineUtils()
bq_client = bigquery.Client(location=BIGQUERY_REGION)
creation_status = constants.SUCCESS
error_exists = False
columns = [] # columns to be tagged
columns_query = self.parse_query_expression(uri, columns_query)
#print('columns_query:', columns_query)
rows = bq_client.query(columns_query).result()
num_rows = 0
for row in rows:
num_rows += 1
columns.append(row[0]) # DC stores all schema columns in lower case
if num_rows == 0:
# no columns to tag
return constants.SUCCESS
#print('columns to be tagged:', columns)
bigquery_resource = '//bigquery.googleapis.com/projects/' + uri
#print('bigquery_resource: ', bigquery_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=bigquery_resource
entry = self.client.lookup_entry(request)
schema_columns = [] # columns in the entry's schema
for column_schema in entry.schema.columns:
schema_columns.append(column_schema.column)
#print('schema_columns:', schema_columns)
for column in columns:
# skip columns not found in the entry's schema
if column not in schema_columns:
continue
# check to see if a tag has already been created on this column
tag_exists, tag_id = self.check_if_exists(entry.name, column)
print("tag_exists: ", tag_exists)
# initialize the new column-level tag
tag = datacatalog.Tag()
tag.template = self.template_path
tag.column = column
verified_field_count = 0
for field in fields:
field_id = field['field_id']
field_type = field['field_type']
query_expression = field['query_expression']
query_str = self.parse_query_expression(uri, query_expression, column)
#print('returned query_str: ' + query_str)
# note: field_values is of type list
field_values, error_exists = self.run_query(bq_client, query_str, field_type, batch_mode, store)
#print('field_values: ', field_values)
#print('error_exists: ', error_exists)
if error_exists or field_values == []:
continue
tag, error_exists = self.populate_tag_field(tag, field_id, field_type, field_values, store)
if error_exists:
continue
verified_field_count = verified_field_count + 1
#print('verified_field_count: ' + str(verified_field_count))
# store the value back in the dict, so that it can be accessed by the exporter
#print('field_value: ' + str(field_value))
if field_type == 'richtext':
formatted_value = ', '.join(str(v) for v in field_values)
else:
formatted_value = field_values[0]
field['field_value'] = formatted_value
# inner loop ends here
if error_exists:
# error was encountered while running SQL expression
# proceed with tag creation / update, but return error to user
creation_status = constants.ERROR
if verified_field_count == 0:
# tag is empty due to errors, skip tag creation
return constants.ERROR
# we are ready to create or update the tag
if tag_exists == True:
#print('updating tag')
#print('tag request: ' + str(tag))
tag.name = tag_id
try:
print('tag update request: ', tag)
response = self.client.update_tag(tag=tag)
#print('response: ', response)
except Exception as e:
print('Error occurred during tag update: ' + str(e))
msg = 'Error occurred during tag update: ' + str(e)
store.write_tag_op_error(constants.TAG_UPDATED, config_uuid, 'DYNAMIC_COLUMN_TAG', msg)
creation_status = constants.ERROR
else:
try:
print('tag create request: ', tag)
response = self.client.create_tag(parent=entry.name, tag=tag)
#print('response: ', response)
except Exception as e:
print('Error occurred during tag create: ', e)
msg = 'Error occurred during tag create: ' + str(e)
store.write_tag_op_error(constants.TAG_CREATED, config_uuid, 'DYNAMIC_COLUMN_TAG', msg)
creation_status = constants.ERROR
if creation_status == constants.SUCCESS and tag_history:
bqu = bq.BigQueryUtils()
template_fields = self.get_template()
bqu.copy_tag(self.template_id, template_fields, uri, column, fields)
if creation_status == constants.SUCCESS and tag_stream:
psu = ps.PubSubUtils()
psu.copy_tag(self.template_id, uri, column, fields)
# outer loop ends here
return creation_status
def apply_entry_config(self, fields, uri, config_uuid, template_uuid, tag_history, tag_stream):
print('** apply_entry_config **')
creation_status = constants.SUCCESS
store = te.TagEngineUtils()
gcs_client = storage.Client()
bucket_name, filename = uri
bucket = gcs_client.get_bucket(bucket_name)
blob = bucket.get_blob(filename)
entry_group_short_name = bucket_name.replace('-', '_')
entry_group_full_name = 'projects/' + self.template_project + '/locations/' + self.template_region + '/entryGroups/' + bucket_name.replace('-', '_')
# create the entry group
is_entry_group = self.entry_group_exists(entry_group_full_name)
print('is_entry_group: ', is_entry_group)
if is_entry_group != True:
self.create_entry_group(entry_group_short_name)
# generate the entry id, replace '/' with '_' and remove the file extension from the name
entry_id = filename.split('.')[0].replace('/', '_')
try:
entry_name = entry_group_full_name + '/entries/' + entry_id
print('Info: entry_name: ', entry_name)
entry = self.client.get_entry(name=entry_name)
print('Info: entry already exists: ', entry.name)
except Exception as e:
print('Info: entry does not exist')
# populate the entry
entry = datacatalog.Entry()
entry.name = filename
entry.display_name = entry_id
entry.type_ = 'FILESET'
entry.gcs_fileset_spec.file_patterns = ['gs://' + bucket_name + '/' + filename]
entry.fully_qualified_name = 'gs://' + bucket_name + '/' + filename
entry.source_system_timestamps.create_time = datetime.utcnow()
entry.source_system_timestamps.update_time = datetime.utcnow()
# get the file's schema
# download the file to App Engine's tmp directory
tmp_file = '/tmp/' + entry_id
blob.download_to_filename(filename=tmp_file)
# validate that it's a parquet file
try:
parquet.ParquetFile(tmp_file)
except Exception as e:
# not a parquet file, ignore it
print('The file ' + filename + ' is not a parquet file, ignoring it.')
creation_status = constants.ERROR
return creation_status
schema = parquet.read_schema(tmp_file, memory_map=True)
df = pd.DataFrame(({"column": name, "datatype": str(pa_dtype)} for name, pa_dtype in zip(schema.names, schema.types)))
df = df.reindex(columns=["column", "datatype"], fill_value=pd.NA)
#print('df: ', df)
for index, row in df.iterrows():
entry.schema.columns.append(
types.ColumnSchema(
column=row['column'],
type_=row['datatype'],
description=None,
mode=None
)
)
# create the entry
#print('entry request: ', entry)
created_entry = self.client.create_entry(parent=entry_group_full_name, entry_id=entry_id, entry=entry)
print('Info: created entry: ', created_entry.name)
# get the number of rows in the file
num_rows = parquet.ParquetFile(tmp_file).metadata.num_rows
#print('num_rows: ', num_rows)
# delete the tmp file ASAP to free up memory
os.remove(tmp_file)
# create the file metadata tag
template_path = self.client.tag_template_path(self.template_project, self.template_region, self.template_id)
tag = datacatalog.Tag()
tag.template = template_path
for field in fields:
if field['field_id'] == 'name':
string_field = datacatalog.TagField()
string_field.string_value = filename
tag.fields['name'] = string_field
field['field_value'] = filename # field_value is used by the BQ exporter
if field['field_id'] == 'bucket':
string_field = datacatalog.TagField()
string_field.string_value = bucket_name
tag.fields['bucket'] = string_field
field['field_value'] = bucket_name # field_value is used by the BQ exporter
if field['field_id'] == 'path':
string_field = datacatalog.TagField()
string_field.string_value = 'gs://' + bucket_name + '/' + filename
tag.fields['path'] = string_field
field['field_value'] = 'gs://' + bucket_name + '/' + filename # field_value is used by the BQ exporter
if field['field_id'] == 'type':
enum_field = datacatalog.TagField()
enum_field.enum_value.display_name = 'PARQUET' # hardcode file extension for now
tag.fields['type'] = enum_field
field['field_value'] = 'PARQUET' # field_value is used by the BQ exporter
if field['field_id'] == 'size':
double_field = datacatalog.TagField()
double_field.double_value = blob.size
tag.fields['size'] = double_field
field['field_value'] = blob.size # field_value is used by the BQ exporter
if field['field_id'] == 'num_rows':
double_field = datacatalog.TagField()
double_field.double_value = num_rows
tag.fields['num_rows'] = double_field
field['field_value'] = num_rows # field_value is used by the BQ exporter
if field['field_id'] == 'created_time':
datetime_field = datacatalog.TagField()
datetime_field.timestamp_value = blob.time_created
tag.fields['created_time'] = datetime_field
field['field_value'] = blob.time_created # field_value is used by the BQ exporter
if field['field_id'] == 'updated_time':
datetime_field = datacatalog.TagField()
datetime_field.timestamp_value = blob.time_created
tag.fields['updated_time'] = datetime_field
field['field_value'] = blob.time_created # field_value is used by the BQ exporter
if field['field_id'] == 'storage_class':
string_field = datacatalog.TagField()
string_field.string_value = blob.storage_class
tag.fields['storage_class'] = string_field
field['field_value'] = blob.storage_class # field_value is used by the BQ exporter
if field['field_id'] == 'content_encoding':
if blob.content_encoding:
string_field = datacatalog.TagField()
string_field.string_value = blob.content_encoding
tag.fields['content_encoding'] = string_field
field['field_value'] = blob.content_encoding # field_value is used by the BQ exporter
if field['field_id'] == 'content_language':
if blob.content_language:
string_field = datacatalog.TagField()
string_field.string_value = blob.content_language
tag.fields['content_language'] = string_field
field['field_value'] = blob.content_language # field_value is used by the BQ exporter
if field['field_id'] == 'media_link':
string_field = datacatalog.TagField()
string_field.string_value = blob.media_link
tag.fields['media_link'] = string_field
field['field_value'] = blob.media_link # field_value is used by the BQ exporter
#print('tag request: ', tag)
created_tag = self.client.create_tag(parent=entry_name, tag=tag)
#print('created_tag: ', created_tag)
if tag_history:
bqu = bq.BigQueryUtils()
template_fields = self.get_template()
bqu.copy_tag(self.template_id, template_fields, '/'.join(uri), None, fields)
if tag_stream:
psu = ps.PubSubUtils()
psu.copy_tag(self.template_id, uri, column, fields)
return creation_status
def entry_group_exists(self, entry_group_full_name):
request = datacatalog.GetEntryGroupRequest(name=entry_group_full_name)
try:
response = self.client.get_entry_group(request=request)
return True
except Exception as e:
return False
def create_entry_group(self, entry_group_short_name):
eg = datacatalog.EntryGroup()
eg.display_name = entry_group_short_name
entry_group = self.client.create_entry_group(
parent='projects/' + self.template_project + '/locations/' + self.template_region,
entry_group_id=entry_group_short_name,
entry_group=eg)
print('created entry_group: ', entry_group.name)
return entry_group.name
def apply_glossary_asset_config(self, fields, mapping_table, uri, config_uuid, template_uuid, tag_history, tag_stream, overwrite=False):
print('** enter apply_glossary_asset_config **')
#print('fields: ', fields)
print('mapping_table: ', mapping_table)
print('uri: ', uri)
#print('config_uuid: ', config_uuid)
#print('template_uuid: ', template_uuid)
#print('tag_history: ', tag_history)
#print('tag_stream: ', tag_stream)
# uri is either a BQ table/view path or GCS file path
store = te.TagEngineUtils()
creation_status = constants.SUCCESS
is_gcs = False
is_bq = False
# look up the entry based on the resource type
if isinstance(uri, list):
is_gcs = True
bucket = uri[0].replace('-', '_')
filename = uri[1].split('.')[0].replace('/', '_') # extract the filename without the extension, replace '/' with '_'
gcs_resource = '//datacatalog.googleapis.com/projects/' + self.template_project + '/locations/' + self.template_region + '/entryGroups/' + bucket + '/entries/' + filename
#print('gcs_resource: ', gcs_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=gcs_resource
try:
entry = self.client.lookup_entry(request)
print('entry: ', entry.name)
except Exception as e:
print('Unable to find entry in the catalog. Entry ' + gcs_resource + ' does not exist.')
creation_status = constants.ERROR
return creation_status
#print('entry found: ', entry)
elif isinstance(uri, str):
is_bq = True
bigquery_resource = '//bigquery.googleapis.com/projects/' + uri
print("bigquery_resource: " + bigquery_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=bigquery_resource
entry = self.client.lookup_entry(request)
print('entry: ', entry.name)
try:
tag_exists, tag_id = self.check_if_exists(parent=entry.name)
print('tag_exists: ', tag_exists)
except Exception as e:
print('Error during check_if_exists: ', e)
creation_status = constants.ERROR
return creation_status
if tag_exists and overwrite == False:
print('Info: tag already exists and overwrite set to False')
creation_status = constants.SUCCESS
return creation_status
if entry.schema == None:
print('Error: entry ' + entry.name + ' does not have a schema in the catalog.')
creation_status = constants.ERROR
return creation_status
# retrieve the schema columns from the entry
column_schema_str = ''
for column_schema in entry.schema.columns:
column_schema_str += "'" + column_schema.column + "',"
#print('column_schema_str: ', column_schema_str)
mapping_table_formatted = mapping_table.replace('bigquery/project/', '').replace('/dataset/', '.').replace('/', '.')
query_str = 'select canonical_name from `' + mapping_table_formatted + '` where source_name in (' + column_schema_str[0:-1] + ')'
#print('query_str: ', query_str)
# run query against mapping table
bq_client = bigquery.Client(location=BIGQUERY_REGION)
rows = bq_client.query(query_str).result()
tag = datacatalog.Tag()
tag.template = self.template_path
tag_is_empty = True
for row in rows:
canonical_name = row['canonical_name']
#print('canonical_name: ', canonical_name)
for field in fields:
if field['field_id'] == canonical_name:
#print('found match')
bool_field = datacatalog.TagField()
bool_field.bool_value = True
tag.fields[canonical_name] = bool_field
field['field_value'] = True
tag_is_empty = False
break
if tag_is_empty:
print("Error: can't create the tag because it's empty")
creation_status = constants.ERROR
return creation_status
if tag_exists:
# tag already exists and overwrite is True
tag.name = tag_id
try:
print('tag update: ', tag)
response = self.client.update_tag(tag=tag)
except Exception as e:
msg = 'Error occurred during tag update: ' + str(e)
store.write_tag_op_error(constants.TAG_UPDATED, config_uuid, 'GLOSSARY_ASSET_TAG', msg)
# sleep and retry the tag update
if 'Quota exceeded for quota metric' or '503 The service is currently unavailable' in str(e):
print('sleep for 3 minutes due to ' + str(e))
time.sleep(180)
try:
response = self.client.update_tag(tag=tag)
except Exception as e:
msg = 'Error occurred during tag update after sleep: ' + str(e)
store.write_tag_op_error(constants.TAG_UPDATED, config_uuid, 'GLOSSARY_ASSET_TAG', msg)
else:
try:
print('tag create: ', tag)
response = self.client.create_tag(parent=entry.name, tag=tag)
except Exception as e:
msg = 'Error occurred during tag create: ' + str(e) + '. Failed tag request = ' + str(tag)
store.write_tag_op_error(constants.TAG_CREATED, config_uuid, 'GLOSSARY_ASSET_TAG', msg)
# sleep and retry write
if 'Quota exceeded for quota metric' or '503 The service is currently unavailable' in str(e):
print('sleep for 3 minutes due to ' + str(e))
time.sleep(180)
try:
response = self.client.create_tag(parent=entry.name, tag=tag)
except Exception as e:
msg = 'Error occurred during tag create after sleep: ' + str(e)
store.write_tag_op_error(constants.TAG_CREATED, config_uuid, 'GLOSSARY_ASSET_TAG', msg)
if tag_history:
bqu = bq.BigQueryUtils()
template_fields = self.get_template()
if is_gcs:
bqu.copy_tag(self.template_id, template_fields, '/'.join(uri), None, fields)
if is_bq:
bqu.copy_tag(self.template_id, template_fields, uri, None, fields)
if tag_stream:
psu = ps.PubSubUtils()
if is_gcs:
bqu.copy_tag(self.template_id, '/'.join(uri), None, fields)
if is_bq:
psu.copy_tag(self.template_id, uri, None, fields)
return creation_status
def apply_sensitive_column_config(self, fields, dlp_dataset, infotype_selection_table, infotype_classification_table, \
uri, create_policy_tags, taxonomy_id, config_uuid, template_uuid, \
tag_history, tag_stream, overwrite=False):
print('** enter apply_sensitive_column_config **')
print('fields: ', fields)
print('dlp_dataset: ', dlp_dataset)
print('infotype_selection_table: ', infotype_selection_table)
print('infotype_classification_table: ', infotype_classification_table)
print('uri: ', uri)
print('create_policy_tags: ', create_policy_tags)
print('taxonomy_id: ', taxonomy_id)
print('config_uuid: ', config_uuid)
print('template_uuid: ', template_uuid)
if create_policy_tags:
ptm_client = datacatalog.PolicyTagManagerClient()
request = datacatalog.ListPolicyTagsRequest(
parent=taxonomy_id
)
try:
page_result = ptm_client.list_policy_tags(request=request)
except Exception as e:
print('Unable to retrieve the policy tag taxonomy for taxonomy_id ' + taxonomy_id + '. Error message: ', e)
creation_status = constants.ERROR
return creation_status
policy_tag_names = [] # list of fully qualified policy tag names and sensitive categories
for response in page_result:
policy_tag_names.append((response.name, response.display_name))
#print('policy_tag_names: ', policy_tag_names)
policy_tag_requests = [] # stores the list of fully qualified policy tag names and table column names,
# so that we can create the policy tags on the various sensitive fields
# uri is a BQ table path
store = te.TagEngineUtils()
creation_status = constants.SUCCESS
column = ''
if isinstance(uri, str) == False:
print('Error: url ' + str(url) + ' is not of type string.')
creation_status = constants.ERROR
return creation_status
bigquery_resource = '//bigquery.googleapis.com/projects/' + uri
#print("bigquery_resource: ", bigquery_resource)
request = datacatalog.LookupEntryRequest()
request.linked_resource=bigquery_resource
try:
entry = self.client.lookup_entry(request)
except Exception as e:
print('Error looking up entry ' + bigquery_resource + ' in the catalog. Error message: ', e)
creation_status = constants.ERROR
return creation_status
dlp_dataset = dlp_dataset.replace('bigquery/project/', '').replace('/dataset/', '.').replace('/', '.')
infotype_selection_table = infotype_selection_table.replace('bigquery/project/', '').replace('/dataset/', '.').replace('/', '.')
infotype_classification_table = infotype_classification_table.replace('bigquery/project/', '').replace('/dataset/', '.').replace('/', '.')
dlp_table = dlp_dataset + '.' + uri.split('/')[4]
#print('dlp_dataset: ', dlp_dataset)
#print('dlp_table: ', dlp_table)
infotype_fields = []
notable_infotypes = []
# get an array of infotypes associated with each field in the DLP findings table
dlp_sql = 'select field, array_agg(infotype) infotypes '
dlp_sql += 'from (select distinct cl.record_location.field_id.name as field, info_type.name as infotype '
dlp_sql += 'from ' + dlp_table + ', unnest(location.content_locations) as cl '
dlp_sql += 'order by cl.record_location.field_id.name) '
dlp_sql += 'group by field'
#print('dlp_sql: ', dlp_sql)
bq_client = bigquery.Client(location=BIGQUERY_REGION)
try:
dlp_rows = bq_client.query(dlp_sql).result()
except Exception as e:
print('Error querying DLP findings table. Error message: ', e)
creation_status = constants.ERROR
return creation_status
dlp_row_count = 0
for dlp_row in dlp_rows:
dlp_row_count += 1
field = dlp_row['field']
infotype_fields.append(field)
infotypes = dlp_row['infotypes']