/
hive_metastore_migration.py
1544 lines (1279 loc) · 68.1 KB
/
hive_metastore_migration.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 2016-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
# This script avoids adding any external dependencies
# except for python 2.7 standard library and Spark 2.1
import sys
import argparse
import re
import logging
from time import localtime, strftime
from types import MethodType
from datetime import tzinfo, datetime, timedelta
from pyspark.context import SparkContext, SparkConf
from pyspark.sql import SQLContext, DataFrame, Row
from pyspark.sql.functions import lit, struct, array, col, UserDefinedFunction, concat, monotonically_increasing_id, explode
from pyspark.sql.types import StringType, StructField, StructType, LongType, ArrayType, MapType, IntegerType, \
FloatType, BooleanType
PYTHON_VERSION = sys.version_info[0]
MYSQL_DRIVER_CLASS = 'com.mysql.jdbc.Driver'
# flags for migration direction
FROM_METASTORE = 'from-metastore'
TO_METASTORE = 'to-metastore'
DATACATALOG_STORAGE_DESCRIPTOR_SCHEMA = \
StructType([
StructField('inputFormat', StringType(), True),
StructField('compressed', BooleanType(), False),
StructField('storedAsSubDirectories', BooleanType(), False),
StructField('location', StringType(), True),
StructField('numberOfBuckets', IntegerType(), False),
StructField('outputFormat', StringType(), True),
StructField('bucketColumns', ArrayType(StringType(), True), True),
StructField('columns', ArrayType(StructType([
StructField('name', StringType(), True),
StructField('type', StringType(), True),
StructField('comment', StringType(), True)
]), True), True),
StructField('parameters', MapType(StringType(), StringType(), True), True),
StructField('serdeInfo', StructType([
StructField('name', StringType(), True),
StructField('serializationLibrary', StringType(), True),
StructField('parameters', MapType(StringType(), StringType(), True), True)
]), True),
StructField('skewedInfo', StructType([
StructField('skewedColumnNames', ArrayType(StringType(), True), True),
StructField('skewedColumnValueLocationMaps', MapType(StringType(), StringType(), True), True),
StructField('skewedColumnValues', ArrayType(StringType(), True), True)
]), True),
StructField('sortColumns', ArrayType(StructType([
StructField('column', StringType(), True),
StructField('order', IntegerType(), True)
]), True), True)
])
DATACATALOG_DATABASE_ITEM_SCHEMA = \
StructType([
StructField('description', StringType(), True),
StructField('locationUri', StringType(), True),
StructField('name', StringType(), False),
StructField('parameters', MapType(StringType(), StringType(), True), True)
])
DATACATALOG_TABLE_ITEM_SCHEMA = \
StructType([
StructField('createTime', StringType(), True),
StructField('lastAccessTime', StringType(), True),
StructField('owner', StringType(), True),
StructField('retention', IntegerType(), True),
StructField('name', StringType(), False),
StructField('tableType', StringType(), True),
StructField('viewExpandedText', StringType(), True),
StructField('viewOriginalText', StringType(), True),
StructField('parameters', MapType(StringType(), StringType(), True), True),
StructField('partitionKeys', ArrayType(StructType([
StructField('name', StringType(), True),
StructField('type', StringType(), True),
StructField('comment', StringType(), True)
]), True), True),
StructField('storageDescriptor', DATACATALOG_STORAGE_DESCRIPTOR_SCHEMA, True)
])
DATACATALOG_PARTITION_ITEM_SCHEMA = \
StructType([
StructField('creationTime', StringType(), True),
StructField('lastAccessTime', StringType(), True),
StructField('namespaceName', StringType(), True),
StructField('tableName', StringType(), True),
StructField('parameters', MapType(StringType(), StringType(), True), True),
StructField('storageDescriptor', DATACATALOG_STORAGE_DESCRIPTOR_SCHEMA, True),
StructField('values', ArrayType(StringType(), False), False)
])
DATACATALOG_DATABASE_SCHEMA = \
StructType([
StructField('items', ArrayType(
DATACATALOG_DATABASE_ITEM_SCHEMA, False),
True),
StructField('type', StringType(), False)
])
DATACATALOG_TABLE_SCHEMA = \
StructType([
StructField('database', StringType(), False),
StructField('type', StringType(), False),
StructField('items', ArrayType(DATACATALOG_TABLE_ITEM_SCHEMA, False), True)
])
DATACATALOG_PARTITION_SCHEMA = \
StructType([
StructField('database', StringType(), False),
StructField('table', StringType(), False),
StructField('items', ArrayType(DATACATALOG_PARTITION_ITEM_SCHEMA, False), True),
StructField('type', StringType(), False)
])
METASTORE_PARTITION_SCHEMA = \
StructType([
StructField('database', StringType(), False),
StructField('table', StringType(), False),
StructField('item', DATACATALOG_PARTITION_ITEM_SCHEMA, True),
StructField('type', StringType(), False)
])
METASTORE_DATABASE_SCHEMA = \
StructType([
StructField('item', DATACATALOG_DATABASE_ITEM_SCHEMA, True),
StructField('type', StringType(), False)
])
METASTORE_TABLE_SCHEMA = \
StructType([
StructField('database', StringType(), False),
StructField('type', StringType(), False),
StructField('item', DATACATALOG_TABLE_ITEM_SCHEMA, True)
])
def append(l, elem):
"""Append list with element and return the list modified"""
if elem is not None:
l.append(elem)
return l
def extend(l1, l2):
"""Extend l1 with l2 and return l1 modified"""
l1.extend(l2)
return l1
def remove(l, elem):
l.remove(elem)
return l
def remove_all(l1, l2):
return [elem for elem in l1 if elem not in l2]
def construct_struct_schema(schema_tuples_list):
struct_fields = []
atomic_types_dict = {
'int': IntegerType(),
'long': LongType(),
'string': StringType()
}
for (col_name, col_type, nullable) in schema_tuples_list:
field_type = atomic_types_dict[col_type]
struct_fields.append(StructField(name=col_name, dataType=field_type, nullable=nullable))
return StructType(struct_fields)
def empty(self):
return self.rdd.isEmpty()
def drop_columns(self, columns_to_drop):
for col in columns_to_drop:
self = self.drop(col)
return self
def rename_columns(df, rename_tuples=None):
"""
Rename columns, for each key in rename_map, rename column from key to value
:param self: dataframe
:param rename_map: map for columns to be renamed
:return: new dataframe with columns renamed
"""
for old, new in rename_tuples:
df = df.withColumnRenamed(old, new)
return df
def rename_columns_for_class(self, rename_tuples=None):
"""
Rename columns, for each key in rename_map, rename column from key to value
:param self: dataframe
:param rename_map: map for columns to be renamed
:return: new dataframe with columns renamed
"""
for old, new in rename_tuples:
self = self.withColumnRenamed(old, new)
return self
def get_schema_type(df, column_name):
return df.select(column_name).schema.fields[0].dataType
def get_schema_type_for_class(self, column_name):
return self.select(column_name).schema.fields[0].dataType
def join_other_to_single_column(self, other, on, how, new_column_name):
"""
:param df: this dataframe
:param other: other dataframe
:param on: the column to join on
:param how: :param how: str, default 'inner'. One of `inner`, `outer`, `left_outer`, `right_outer`, `leftsemi`.
:param new_column_name: the column name for all fields from the other dataframe
:return: this dataframe, with a single new column containing all fields of the other dataframe
:type df: DataFrame
:type other: DataFrame
:type new_column_name: str
"""
other_cols = remove(other.columns, on)
other_combined = other.select([on, struct(other_cols).alias(new_column_name)])
return self.join(other=other_combined, on=on, how=how)
def batch_items_within_partition(sql_context, df, key_col, value_col, values_col):
"""
Group a DataFrame of key, value pairs, create a list of values for the same key in each spark partition, but there
is no cross-partition data interaction, so the same key may be shown multiple times in the output dataframe
:param sql_context: spark sqlContext
:param df: DataFrame with only two columns, a key_col and a value_col
:param key_col: name of key column
:param value_col: name of value column
:param values_col: name of values column, which is an array of value_col
:type df: DataFrame
:type key_col: str
:type value_col: str
:return: DataFrame of values grouped by key within each partition
"""
def group_by_key(it):
grouped = dict()
for row in it:
(k, v) = (row[key_col], row[value_col])
if k in grouped:
grouped[k].append(v)
else:
grouped[k] = [v]
row = Row(key_col, values_col)
for k in grouped:
yield row(k, grouped[k])
return sql_context.createDataFrame(data=df.rdd.mapPartitions(group_by_key), schema=StructType([
StructField(key_col, get_schema_type(df, key_col), True),
StructField(values_col, ArrayType(get_schema_type(df, value_col)), True)
]))
def batch_metastore_partitions(sql_context, df_parts):
"""
:param sql_context: the spark SqlContext
:param df_parts: the dataframe of partitions with the schema of DATACATALOG_PARTITION_SCHEMA
:type df_parts: DataFrame
:return: a dataframe partition in which each row contains a list of catalog partitions
belonging to the same database and table.
"""
df_kv = df_parts.select(struct(['database', 'table', 'type']).alias('key'), 'item')
batched_kv = batch_items_within_partition(sql_context, df_kv, key_col='key', value_col='item', values_col='items')
batched_parts = batched_kv.select(
batched_kv.key.database.alias('database'),
batched_kv.key.table.alias('table'),
batched_kv.key.type.alias('type'), batched_kv.items)
return batched_parts
def register_methods_to_dataframe():
"""
Register self-defined helper methods to dataframe
"""
if PYTHON_VERSION==3:
DataFrame.empty = empty
DataFrame.drop_columns = drop_columns
DataFrame.rename_columns = rename_columns_for_class
DataFrame.get_schema_type = get_schema_type_for_class
DataFrame.join_other_to_single_column = join_other_to_single_column
else:
DataFrame.empty = MethodType(empty, None, DataFrame)
DataFrame.drop_columns = MethodType(drop_columns, None, DataFrame)
DataFrame.rename_columns = MethodType(rename_columns, None, DataFrame)
DataFrame.get_schema_type = MethodType(get_schema_type, None, DataFrame)
DataFrame.join_other_to_single_column = MethodType(join_other_to_single_column, None, DataFrame)
register_methods_to_dataframe()
class UTC(tzinfo):
"""
Have to implement timezone class myself because python standard library doesn't have one, and I want to avoid adding
external libraries, to make it simpler for people new to Spark to run the script
"""
def utcoffset(self, dt):
return timedelta(0)
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return timedelta(0)
class HiveMetastoreTransformer:
def transform_params(self, params_df, id_col, key='PARAM_KEY', value='PARAM_VALUE'):
"""
Transform a PARAMS table dataframe to dataframe of 2 columns: (id, Map<key, value>)
:param params_df: dataframe of PARAMS table
:param id_col: column name for id field
:param key: column name for key
:param value: column name for value
:return: dataframe of params in map
"""
return self.kv_pair_to_map(params_df, id_col, key, value, 'parameters')
def kv_pair_to_map(self, df, id_col, key, value, map_col_name):
def merge_dict(dict1, dict2):
dict1.update(dict2)
return dict1
def remove_none_key(dictionary):
if None in dictionary:
del dictionary[None]
return dictionary
id_type = df.get_schema_type(id_col)
map_type = MapType(keyType=df.get_schema_type(key), valueType=df.get_schema_type(value))
output_schema = StructType([StructField(name=id_col, dataType=id_type, nullable=False),
StructField(name=map_col_name, dataType=map_type)])
return self.sql_context.createDataFrame(
df.rdd.map(lambda row: (row[id_col], {row[key]: row[value]})).reduceByKey(merge_dict).map(
lambda rec: (rec[0], remove_none_key(rec[1]))), output_schema)
def join_with_params(self, df, df_params, id_col):
df_params_map = self.transform_params(params_df=df_params, id_col=id_col)
df_with_params = df.join(other=df_params_map, on=id_col, how='left_outer')
return df_with_params
def transform_df_with_idx(self, df, id_col, idx, payloads_column_name, payload_type, payload_func):
"""
Aggregate dataframe by ID, create a single PAYLOAD column where each row is a list of data sorted by IDX, and
each element is a payload created by payload_func. Example:
Input:
df =
+---+---+----+----+
| ID|IDX|COL1|COL2|
+---+---+----+----+
| 1| 2| 1| 1|
| 1| 1| 2| 2|
| 2| 1| 3| 3|
+---+---+----+----+
id = 'ID'
idx = 'IDX'
payload_list_name = 'PAYLOADS'
payload_func = row.COL1 + row.COL2
Output:
+------+--------+
| ID|PAYLOADS|
+------+--------+
| 1| [4, 2] |
| 2| [6] |
+------+--------+
The method assumes (ID, IDX) is input table primary key. ID and IDX values cannot be None
:param df: dataframe with id and idx columns
:param id_col: name of column for id
:param idx: name of column for sort index
:param payloads_column_name: the column name for payloads column in the output dataframe
:param payload_func: the function to transform an input row to a payload object
:param payload_type: the schema type for a single payload object
:return: output dataframe with data grouped by id and sorted by idx
"""
rdd_result = df.rdd.map(lambda row: (row[id_col], (row[idx], payload_func(row)))) \
.aggregateByKey([], append, extend) \
.map(lambda rec: (rec[0], sorted(rec[1], key=lambda t: t[0]))) \
.map(lambda rec: (rec[0], [payload for index, payload in rec[1]]))
schema = StructType([StructField(name=id_col, dataType=LongType(), nullable=False),
StructField(name=payloads_column_name, dataType=ArrayType(elementType=payload_type))])
return self.sql_context.createDataFrame(rdd_result, schema)
def transform_ms_partition_keys(self, ms_partition_keys):
return self.transform_df_with_idx(df=ms_partition_keys,
id_col='TBL_ID',
idx='INTEGER_IDX',
payloads_column_name='partitionKeys',
payload_type=StructType([
StructField(name='name', dataType=StringType()),
StructField(name='type', dataType=StringType()),
StructField(name='comment', dataType=StringType())]),
payload_func=lambda row: (
row['PKEY_NAME'], row['PKEY_TYPE'], row['PKEY_COMMENT']))
def transform_ms_partition_key_vals(self, ms_partition_key_vals):
return self.transform_df_with_idx(df=ms_partition_key_vals,
id_col='PART_ID',
idx='INTEGER_IDX',
payloads_column_name='values',
payload_type=StringType(),
payload_func=lambda row: row['PART_KEY_VAL'])
def transform_ms_bucketing_cols(self, ms_bucketing_cols):
return self.transform_df_with_idx(df=ms_bucketing_cols,
id_col='SD_ID',
idx='INTEGER_IDX',
payloads_column_name='bucketColumns',
payload_type=StringType(),
payload_func=lambda row: row['BUCKET_COL_NAME'])
def transform_ms_columns(self, ms_columns):
return self.transform_df_with_idx(df=ms_columns,
id_col='CD_ID',
idx='INTEGER_IDX',
payloads_column_name='columns',
payload_type=StructType([
StructField(name='name', dataType=StringType()),
StructField(name='type', dataType=StringType()),
StructField(name='comment', dataType=StringType())]),
payload_func=lambda row: (
row['COLUMN_NAME'], row['TYPE_NAME'], row['COMMENT']))
def transform_ms_skewed_col_names(self, ms_skewed_col_names):
return self.transform_df_with_idx(df=ms_skewed_col_names,
id_col='SD_ID',
idx='INTEGER_IDX',
payloads_column_name='skewedColumnNames',
payload_type=StringType(),
payload_func=lambda row: row['SKEWED_COL_NAME'])
def transform_ms_skewed_string_list_values(self, ms_skewed_string_list_values):
return self.transform_df_with_idx(df=ms_skewed_string_list_values,
id_col='STRING_LIST_ID',
idx='INTEGER_IDX',
payloads_column_name='skewedColumnValuesList',
payload_type=StringType(),
payload_func=lambda row: row['STRING_LIST_VALUE'])
def transform_ms_sort_cols(self, sort_cols):
return self.transform_df_with_idx(df=sort_cols,
id_col='SD_ID',
idx='INTEGER_IDX',
payloads_column_name='sortColumns',
payload_type=StructType([
StructField(name='column', dataType=StringType()),
StructField(name='order', dataType=IntegerType())]),
payload_func=lambda row: (row['COLUMN_NAME'], row['ORDER']))
@staticmethod
def udf_escape_chars(param_value):
ret_param_value = param_value.replace('\\', '\\\\')\
.replace('|', '\\|')\
.replace('"', '\\"')\
.replace('{', '\\{')\
.replace(':', '\\:')\
.replace('}', '\\}')
return ret_param_value
@staticmethod
def udf_skewed_values_to_str():
return UserDefinedFunction(lambda values: ''.join(
map(lambda v: '' if v is None else '%d%%%s' % (len(v), v), values)
), StringType())
@staticmethod
def modify_column_by_udf(df, udf, column_to_modify, new_column_name=None):
"""
transform a column of the dataframe with the user-defined function, keeping all other columns unchanged.
:param new_column_name: new column name. If None, old column name will be used
:param df: dataframe
:param udf: user-defined function
:param column_to_modify: the name of the column to modify.
:type column_to_modify: str
:return: the dataframe with single column modified
"""
if new_column_name is None:
new_column_name = column_to_modify
return df.select(
*[udf(column).alias(new_column_name) if column == column_to_modify else column for column in df.columns])
@staticmethod
def s3a_or_s3n_to_s3_in_location(df, location_col_name):
"""
For a dataframe with a column containing location strings, for any location "s3a://..." or "s3n://...", replace
them with "s3://...".
:param df: dataframe
:param location_col_name: the name of the column containing location, must be string type
:return: dataframe with location columns where all "s3a" or "s3n" protocols are replaced by "s3"
"""
udf = UserDefinedFunction(
lambda location: None if location is None else re.sub(r'^s3[a|n]:\/\/', 's3://', location),
StringType())
return HiveMetastoreTransformer.modify_column_by_udf(df=df, udf=udf, column_to_modify=location_col_name)
@staticmethod
def add_prefix_to_column(df, column_to_modify, prefix):
if prefix is None or prefix == '':
return df
udf = UserDefinedFunction(lambda col: prefix + col, StringType())
return HiveMetastoreTransformer.modify_column_by_udf(df=df, udf=udf, column_to_modify=column_to_modify)
@staticmethod
def utc_timestamp_to_iso8601_time(df, date_col_name, new_date_col_name):
"""
Tape DataCatalog writer uses Gson to parse Date column. According to Gson deserializer, (https://goo.gl/mQdXuK)
it uses either java DateFormat or ISO-8601 format. I convert Date to be compatible with java DateFormat
:param df: dataframe with a column of unix timestamp in seconds of number type
:param date_col_name: timestamp column
:param new_date_col_name: new column with converted timestamp, if None, old column name is used
:type df: DataFrame
:type date_col_name: str
:type new_date_col_name: str
:return: dataframe with timestamp column converted to string representation of time
"""
def convert_time(timestamp):
if timestamp is None:
return None
return datetime.fromtimestamp(timestamp=float(timestamp), tz=UTC()).strftime("%b %d, %Y %I:%M:%S %p")
udf_time_int_to_date = UserDefinedFunction(convert_time, StringType())
return HiveMetastoreTransformer.modify_column_by_udf(df, udf_time_int_to_date, date_col_name, new_date_col_name)
@staticmethod
def transform_timestamp_cols(df, date_cols_map):
"""
Call timestamp_int_to_iso8601_time in batch, rename all time columns in date_cols_map keys.
:param df: dataframe with columns of unix timestamp
:param date_cols_map: map from old column name to new column name
:type date_cols_map: dict
:return: dataframe
"""
for k, v in date_cols_map.items():
df = HiveMetastoreTransformer.utc_timestamp_to_iso8601_time(df, k, v)
return df
@staticmethod
def fill_none_with_empty_list(df, column):
"""
Given a column of array type, fill each None value with empty list.
This is not doable by df.na.fill(), Spark will throw Unsupported value type java.util.ArrayList ([]).
:param df: dataframe with array type
:param column: column name string, the column must be array type
:return: dataframe that fills None with empty list for the given column
"""
return HiveMetastoreTransformer.modify_column_by_udf(
df=df,
udf=UserDefinedFunction(
lambda lst: [] if lst is None else lst,
get_schema_type(df, column)
),
column_to_modify=column,
new_column_name=column
)
@staticmethod
def join_dbs_tbls(ms_dbs, ms_tbls):
return ms_dbs.select('DB_ID', 'NAME').join(other=ms_tbls, on='DB_ID', how='inner')
def transform_skewed_values_and_loc_map(self, ms_skewed_string_list_values, ms_skewed_col_value_loc_map):
# columns: (STRING_LIST_ID:BigInt, skewedColumnValuesList:List[String])
skewed_values_list = self.transform_ms_skewed_string_list_values(ms_skewed_string_list_values)
# columns: (STRING_LIST_ID:BigInt, skewedColumnValuesStr:String)
skewed_value_str = self.modify_column_by_udf(df=skewed_values_list,
udf=HiveMetastoreTransformer.udf_skewed_values_to_str(),
column_to_modify='skewedColumnValuesList',
new_column_name='skewedColumnValuesStr')
# columns: (SD_ID: BigInt, STRING_LIST_ID_KID: BigInt, STRING_LIST_ID: BigInt,
# LOCATION: String, skewedColumnValuesStr: String)
skewed_value_str_with_loc = ms_skewed_col_value_loc_map \
.join(other=skewed_value_str,
on=[ms_skewed_col_value_loc_map['STRING_LIST_ID_KID'] == skewed_value_str['STRING_LIST_ID']],
how='inner')
# columns: (SD_ID: BigInt, skewedColumnValueLocationMaps: Map[String, String])
skewed_column_value_location_maps = self.kv_pair_to_map(df=skewed_value_str_with_loc,
id_col='SD_ID',
key='skewedColumnValuesStr',
value='LOCATION',
map_col_name='skewedColumnValueLocationMaps')
# columns: (SD_ID: BigInt, skewedColumnValues: List[String])
skewed_column_values = self.sql_context.createDataFrame(
data=skewed_value_str_with_loc.rdd.map(
lambda row: (row['SD_ID'], row['skewedColumnValues'])
).aggregateByKey([], append, extend),
schema=StructType([
StructField(name='SD_ID', dataType=LongType()),
StructField(name='skewedColumnValues', dataType=ArrayType(elementType=StringType()))
]))
return skewed_column_values, skewed_column_value_location_maps
def transform_skewed_info(self, ms_skewed_col_names, ms_skewed_string_list_values, ms_skewed_col_value_loc_map):
(skewed_column_values, skewed_column_value_location_maps) = self.transform_skewed_values_and_loc_map(
ms_skewed_string_list_values, ms_skewed_col_value_loc_map)
# columns: (SD_ID: BigInt, skewedColumnNames: List[String])
skewed_column_names = self.transform_ms_skewed_col_names(ms_skewed_col_names)
# columns: (SD_ID: BigInt, skewedColumnNames: List[String], skewedColumnValues: List[String],
# skewedColumnValueLocationMaps: Map[String, String])
skewed_info = skewed_column_names \
.join(other=skewed_column_value_location_maps, on='SD_ID', how='outer') \
.join(other=skewed_column_values, on='SD_ID', how='outer')
return skewed_info
# TODO: remove when escape special characters fix in DatacatalogWriter is pushed to production.
def transform_param_value(self, df):
udf_escape_chars = UserDefinedFunction(HiveMetastoreTransformer.udf_escape_chars, StringType())
return df.select('*', udf_escape_chars('PARAM_VALUE').alias('PARAM_VALUE_ESCAPED'))\
.drop('PARAM_VALUE')\
.withColumnRenamed('PARAM_VALUE_ESCAPED', 'PARAM_VALUE')
def transform_ms_serde_info(self, ms_serdes, ms_serde_params):
escaped_serde_params = self.transform_param_value(ms_serde_params)
serde_with_params = self.join_with_params(df=ms_serdes, df_params=escaped_serde_params, id_col='SERDE_ID')
serde_info = serde_with_params.rename_columns(rename_tuples=[
('NAME', 'name'),
('SLIB', 'serializationLibrary')
])
return serde_info
def transform_storage_descriptors(self, ms_sds, ms_sd_params, ms_columns, ms_bucketing_cols, ms_serdes,
ms_serde_params, ms_skewed_col_names, ms_skewed_string_list_values,
ms_skewed_col_value_loc_map, ms_sort_cols):
bucket_columns = self.transform_ms_bucketing_cols(ms_bucketing_cols)
columns = self.transform_ms_columns(ms_columns)
parameters = self.transform_params(params_df=ms_sd_params, id_col='SD_ID')
serde_info = self.transform_ms_serde_info(ms_serdes=ms_serdes, ms_serde_params=ms_serde_params)
skewed_info = self.transform_skewed_info(ms_skewed_col_names=ms_skewed_col_names,
ms_skewed_string_list_values=ms_skewed_string_list_values,
ms_skewed_col_value_loc_map=ms_skewed_col_value_loc_map)
sort_columns = self.transform_ms_sort_cols(ms_sort_cols)
storage_descriptors_joined = ms_sds \
.join(other=bucket_columns, on='SD_ID', how='left_outer') \
.join(other=columns, on='CD_ID', how='left_outer') \
.join(other=parameters, on='SD_ID', how='left_outer') \
.join_other_to_single_column(other=serde_info, on='SERDE_ID', how='left_outer',
new_column_name='serdeInfo') \
.join_other_to_single_column(other=skewed_info, on='SD_ID', how='left_outer',
new_column_name='skewedInfo') \
.join(other=sort_columns, on='SD_ID', how='left_outer')
storage_descriptors_s3_location_fixed = \
HiveMetastoreTransformer.s3a_or_s3n_to_s3_in_location(storage_descriptors_joined, 'LOCATION')
storage_descriptors_renamed = storage_descriptors_s3_location_fixed.rename_columns(rename_tuples=[
('INPUT_FORMAT', 'inputFormat'),
('OUTPUT_FORMAT', 'outputFormat'),
('LOCATION', 'location'),
('NUM_BUCKETS', 'numberOfBuckets'),
('IS_COMPRESSED', 'compressed'),
('IS_STOREDASSUBDIRECTORIES', 'storedAsSubDirectories')
])
storage_descriptors_with_empty_sorted_cols = HiveMetastoreTransformer.fill_none_with_empty_list(
storage_descriptors_renamed, 'sortColumns')
storage_descriptors_final = storage_descriptors_with_empty_sorted_cols.drop_columns(['SERDE_ID', 'CD_ID'])
return storage_descriptors_final
def transform_tables(self, db_tbl_joined, ms_table_params, storage_descriptors, ms_partition_keys):
tbls_date_transformed = self.transform_timestamp_cols(db_tbl_joined, date_cols_map={
'CREATE_TIME': 'createTime',
'LAST_ACCESS_TIME': 'lastAccessTime'
})
tbls_with_params = self.join_with_params(df=tbls_date_transformed, df_params=self.transform_param_value(ms_table_params), id_col='TBL_ID')
partition_keys = self.transform_ms_partition_keys(ms_partition_keys)
tbls_joined = tbls_with_params\
.join(other=partition_keys, on='TBL_ID', how='left_outer')\
.join_other_to_single_column(other=storage_descriptors, on='SD_ID', how='left_outer',
new_column_name='storageDescriptor')
tbls_renamed = rename_columns(df=tbls_joined, rename_tuples=[
('NAME', 'database'),
('TBL_NAME', 'name'),
('TBL_TYPE', 'tableType'),
('CREATE_TIME', 'createTime'),
('LAST_ACCESS_TIME', 'lastAccessTime'),
('OWNER', 'owner'),
('RETENTION', 'retention'),
('VIEW_EXPANDED_TEXT', 'viewExpandedText'),
('VIEW_ORIGINAL_TEXT', 'viewOriginalText'),
])
tbls_dropped_cols = tbls_renamed.drop_columns(['DB_ID', 'TBL_ID', 'SD_ID', 'LINK_TARGET_ID'])
tbls_drop_invalid = tbls_dropped_cols.na.drop(how='any', subset=['name', 'database'])
tbls_with_empty_part_cols = HiveMetastoreTransformer.fill_none_with_empty_list(
tbls_drop_invalid, 'partitionKeys')
tbls_final = tbls_with_empty_part_cols.select(
'database', struct(remove(tbls_dropped_cols.columns, 'database')).alias('item')
).withColumn('type', lit('table'))
return tbls_final
def transform_partitions(self, db_tbl_joined, ms_partitions, storage_descriptors, ms_partition_params,
ms_partition_key_vals):
parts_date_transformed = self.transform_timestamp_cols(df=ms_partitions, date_cols_map={
'CREATE_TIME': 'creationTime',
'LAST_ACCESS_TIME': 'lastAccessTime'
})
db_tbl_names = db_tbl_joined.select(db_tbl_joined['NAME'].alias('namespaceName'),
db_tbl_joined['TBL_NAME'].alias('tableName'), 'DB_ID', 'TBL_ID')
parts_with_db_tbl = parts_date_transformed.join(other=db_tbl_names, on='TBL_ID', how='inner')
parts_with_params = self.join_with_params(df=parts_with_db_tbl, df_params=self.transform_param_value(ms_partition_params), id_col='PART_ID')
parts_with_sd = parts_with_params.join_other_to_single_column(
other=storage_descriptors, on='SD_ID', how='left_outer', new_column_name='storageDescriptor')
part_values = self.transform_ms_partition_key_vals(ms_partition_key_vals)
parts_with_values = parts_with_sd.join(other=part_values, on='PART_ID', how='left_outer')
parts_renamed = rename_columns(df=parts_with_values, rename_tuples=[
('CREATE_TIME', 'createTime'),
('LAST_ACCESS_TIME', 'lastAccessTime')
])
parts_dropped_cols = parts_renamed.drop_columns([
'DB_ID', 'TBL_ID', 'PART_ID', 'SD_ID', 'PART_NAME', 'LINK_TARGET_ID'
])
parts_drop_invalid = parts_dropped_cols.na.drop(how='any', subset=['values', 'namespaceName', 'tableName'])
parts_final = parts_drop_invalid.select(
parts_drop_invalid['namespaceName'].alias('database'),
parts_drop_invalid['tableName'].alias('table'),
struct(parts_drop_invalid.columns).alias('item')
).withColumn('type', lit('partition'))
return parts_final
def transform_databases(self, ms_dbs, ms_database_params):
dbs_with_params = self.join_with_params(df=ms_dbs, df_params=ms_database_params, id_col='DB_ID')
dbs_renamed = rename_columns(df=dbs_with_params, rename_tuples=[
('NAME', 'name'),
('DESC', 'description'),
('DB_LOCATION_URI', 'locationUri')
])
dbs_dropped_cols = dbs_renamed.drop_columns(['DB_ID', 'OWNER_NAME', 'OWNER_TYPE'])
dbs_drop_invalid = dbs_dropped_cols.na.drop(how='any', subset=['name'])
dbs_final = dbs_drop_invalid.select(struct(dbs_dropped_cols.columns).alias('item')) \
.withColumn('type', lit('database'))
return dbs_final
def transform(self, hive_metastore):
dbs_prefixed = HiveMetastoreTransformer.add_prefix_to_column(hive_metastore.ms_dbs, 'NAME', self.db_prefix)
tbls_prefixed = HiveMetastoreTransformer.add_prefix_to_column(
hive_metastore.ms_tbls, 'TBL_NAME', self.table_prefix)
databases = self.transform_databases(
ms_dbs=dbs_prefixed,
ms_database_params=hive_metastore.ms_database_params)
db_tbl_joined = HiveMetastoreTransformer.join_dbs_tbls(ms_dbs=dbs_prefixed, ms_tbls=tbls_prefixed)
storage_descriptors = self.transform_storage_descriptors(
ms_sds=hive_metastore.ms_sds,
ms_sd_params=hive_metastore.ms_sd_params,
ms_columns=hive_metastore.ms_columns,
ms_bucketing_cols=hive_metastore.ms_bucketing_cols,
ms_serdes=hive_metastore.ms_serdes,
ms_serde_params=hive_metastore.ms_serde_params,
ms_skewed_col_names=hive_metastore.ms_skewed_col_names,
ms_skewed_string_list_values=hive_metastore.ms_skewed_string_list_values,
ms_skewed_col_value_loc_map=hive_metastore.ms_skewed_col_value_loc_map,
ms_sort_cols=hive_metastore.ms_sort_cols)
tables = self.transform_tables(
db_tbl_joined=db_tbl_joined,
ms_table_params=hive_metastore.ms_table_params,
storage_descriptors=storage_descriptors,
ms_partition_keys=hive_metastore.ms_partition_keys)
partitions = self.transform_partitions(
db_tbl_joined=db_tbl_joined,
ms_partitions=hive_metastore.ms_partitions,
storage_descriptors=storage_descriptors,
ms_partition_params=hive_metastore.ms_partition_params,
ms_partition_key_vals=hive_metastore.ms_partition_key_vals)
return databases, tables, partitions
def __init__(self, sc, sql_context, db_prefix, table_prefix):
self.sc = sc
self.sql_context = sql_context
self.db_prefix = db_prefix
self.table_prefix = table_prefix
class DataCatalogTransformer:
"""
The class to extract data from DataCatalog entities into Hive metastore tables.
"""
@staticmethod
def udf_array_to_map(array):
if array is None:
return array
return dict((i, v) for i, v in enumerate(array))
@staticmethod
def udf_partition_name_from_keys_vals(keys, vals):
"""
udf_partition_name_from_keys_vals, create name string from array of keys and vals
:param keys: array of partition keys from a datacatalog table
:param vals: array of partition vals from a datacatalog partition
:return: partition name, a string in the form 'key1(type),key2(type)=val1,val2'
"""
if not keys or not vals:
return ""
s_keys = []
for k in keys:
s_keys.append("%s(%s)" % (k['name'], k['type']))
return ','.join(s_keys) + '=' + ','.join(vals)
@staticmethod
def udf_milliseconds_str_to_timestamp(milliseconds_str):
return 0 if milliseconds_str is None else int(milliseconds_str) / 1000
@staticmethod
def udf_string_list_str_to_list(str):
"""
udf_string_list_str_to_list, transform string of a specific format into an array
:param str: array represented as a string, format should be '<len>%['ele1', 'ele2', 'ele3']'
:return: array, in this case would be [ele1, ele2, ele3]
"""
try:
r = re.compile("\d%\[('\w+',?\s?)+\]")
if r.match(str) is None:
return []
return [s.strip()[1:-1] for s in str.split('%')[1][1:-1].split(',')]
except (IndexError, AssertionError):
return []
@staticmethod
def udf_parameters_to_map(parameters):
return parameters.asDict()
@staticmethod
def udf_with_non_null_locationuri(locationUri):
if locationUri is None:
return ""
return locationUri
@staticmethod
def generate_idx_for_df(df, id_name, col_name, col_schema):
"""
generate_idx_for_df, explodes rows with array as a column into a new row for each element in
the array, with 'INTEGER_IDX' indicating its index in the original array.
:param df: dataframe with array columns
:param id_name: the id field of df
:param col_name: the col of df to explode
:param col_schema: the schema of each element in col_name array
:return: new df with exploded rows.
"""
idx_udf = UserDefinedFunction(
DataCatalogTransformer.udf_array_to_map,
MapType(IntegerType(), col_schema, True))
return df.withColumn('idx_columns', idx_udf(col(col_name)))\
.select(id_name, explode('idx_columns').alias("INTEGER_IDX", "col"))
@staticmethod
def column_date_to_timestamp(df, column):
date_to_udf_time_int = UserDefinedFunction(
DataCatalogTransformer.udf_milliseconds_str_to_timestamp,
IntegerType())
return df.withColumn(column + '_new', date_to_udf_time_int(col(column)))\
.drop(column)\
.withColumnRenamed(column + '_new', column)
@staticmethod
def params_to_df(df, id_name):
return df.select(col(id_name), explode(df['parameters'])
.alias('PARAM_KEY', 'PARAM_VALUE'))
def generate_id_df(self, df, id_name):
"""
generate_id_df, creates a new column <id_name>, with unique id for each row in df
:param df: dataframe to be given id column
:param id_name: the id name
:return: new df with generated id
"""
initial_id = self.start_id_map[id_name] if id_name in self.start_id_map else 0
row_with_index = Row(*(["id"] + df.columns))
df_columns = df.columns
# using zipWithIndex to generate consecutive ids, rather than monotonically_increasing_ids
# consecutive ids are desired because ids unnecessarily large will complicate future
# appending to the same metastore (generated ids have to be bigger than the max of ids
# already in the database
def make_row_with_uid(columns, row, uid):
row_dict = row.asDict()
return row_with_index(*([uid] + [row_dict.get(c) for c in columns]))
df_with_pk = (df.rdd
.zipWithIndex()
.map(lambda row_uid: make_row_with_uid(df_columns, *row_uid))
.toDF(StructType([StructField("zip_id", LongType(), False)] + df.schema.fields)))
return df_with_pk.withColumn(id_name, df_with_pk.zip_id + initial_id).drop("zip_id")
def extract_dbs(self, databases):
ms_dbs_no_id = databases.select('item.*')
ms_dbs = self.generate_id_df(ms_dbs_no_id, 'DB_ID')
# if locationUri is null, fill with empty string value
udf_fill_location_uri = UserDefinedFunction(DataCatalogTransformer
.udf_with_non_null_locationuri, StringType())
ms_dbs = ms_dbs.select('*',
udf_fill_location_uri('locationUri')
.alias('locationUriNew'))\
.drop('locationUri')\
.withColumnRenamed('locationUriNew', 'locationUri')
return ms_dbs
def reformat_dbs(self, ms_dbs):
ms_dbs = rename_columns(df=ms_dbs, rename_tuples=[
('locationUri', 'DB_LOCATION_URI'),
('name', 'NAME')
])
return ms_dbs
def extract_tbls(self, tables, ms_dbs):
ms_tbls_no_id = tables\
.join(ms_dbs, tables.database == ms_dbs.NAME, 'inner')\
.select(tables.database, tables.item, ms_dbs.DB_ID)\
.select('DB_ID', 'database', 'item.*')# database col needed for later
ms_tbls = self.generate_id_df(ms_tbls_no_id, 'TBL_ID')
return ms_tbls
def reformat_tbls(self, ms_tbls):
# reformat CREATE_TIME and LAST_ACCESS_TIME
ms_tbls = DataCatalogTransformer.column_date_to_timestamp(ms_tbls, 'createTime')
import time
create_timestamp = int(time.time() * 1.0)
ms_tbls = ms_tbls.withColumn("createTime",lit(create_timestamp))
ms_tbls = DataCatalogTransformer.column_date_to_timestamp(ms_tbls, 'lastAccessTime')
ms_tbls = rename_columns(df=ms_tbls, rename_tuples=[
('database', 'DB_NAME'),
('createTime', 'CREATE_TIME'),
('lastAccessTime', 'LAST_ACCESS_TIME'),
('owner', 'OWNER'),
('retention', 'RETENTION'),
('name', 'TBL_NAME'),
('tableType', 'TBL_TYPE'),
('viewExpandedText', 'VIEW_EXPANDED_TEXT'),
('viewOriginalText', 'VIEW_ORIGINAL_TEXT')
])
return ms_tbls
def get_name_for_partitions(self, ms_partitions, ms_tbls):
tbls_for_join = ms_tbls.select('TBL_ID', 'partitionKeys')
combine_part_key_and_vals = \
UserDefinedFunction(DataCatalogTransformer.udf_partition_name_from_keys_vals,
StringType())
ms_partitions = ms_partitions.join(tbls_for_join, ms_partitions.TBL_ID == tbls_for_join.TBL_ID, 'inner')\
.drop(tbls_for_join.TBL_ID)\
.withColumn('PART_NAME', combine_part_key_and_vals(col('partitionKeys'), col('values')))\
.drop('partitionKeys')
return ms_partitions
def extract_partitions(self, partitions, ms_dbs, ms_tbls):
ms_partitions = partitions.join(ms_dbs, partitions.database == ms_dbs.NAME, 'inner')\
.select(partitions.item, ms_dbs.DB_ID, partitions.table)
cond = [ms_partitions.table == ms_tbls.TBL_NAME, ms_partitions.DB_ID == ms_tbls.DB_ID]
ms_partitions = ms_partitions.join(ms_tbls, cond, 'inner')\
.select(ms_partitions.item, ms_tbls.TBL_ID)\
.select('TBL_ID', 'item.*')
# generate PART_ID
ms_partitions = self.generate_id_df(ms_partitions, 'PART_ID')