-
Notifications
You must be signed in to change notification settings - Fork 499
/
MetastoreEvents.java
2894 lines (2661 loc) · 122 KB
/
MetastoreEvents.java
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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
package org.apache.impala.catalog.events;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.NotificationEvent;
import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.api.TxnToWriteId;
import org.apache.hadoop.hive.metastore.messaging.AbortTxnMessage;
import org.apache.hadoop.hive.metastore.messaging.AddPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.AllocWriteIdMessage;
import org.apache.hadoop.hive.metastore.messaging.AlterPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.CreateTableMessage;
import org.apache.hadoop.hive.metastore.messaging.DropPartitionMessage;
import org.apache.hadoop.hive.metastore.messaging.json.JSONAlterDatabaseMessage;
import org.apache.hadoop.hive.metastore.messaging.InsertMessage;
import org.apache.hadoop.hive.metastore.messaging.json.JSONAlterTableMessage;
import org.apache.hadoop.hive.metastore.messaging.json.JSONCreateDatabaseMessage;
import org.apache.hadoop.hive.metastore.messaging.json.JSONDropDatabaseMessage;
import org.apache.hadoop.hive.metastore.messaging.json.JSONDropTableMessage;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.impala.analysis.TableName;
import org.apache.impala.catalog.CatalogException;
import org.apache.impala.catalog.CatalogServiceCatalog;
import org.apache.impala.catalog.DatabaseNotFoundException;
import org.apache.impala.catalog.Db;
import org.apache.impala.catalog.FileMetadataLoadOpts;
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.catalog.IncompleteTable;
import org.apache.impala.catalog.TableLoadingException;
import org.apache.impala.catalog.TableNotFoundException;
import org.apache.impala.catalog.TableNotLoadedException;
import org.apache.impala.catalog.TableWriteId;
import org.apache.impala.common.Metrics;
import org.apache.impala.common.PrintUtils;
import org.apache.impala.common.Reference;
import org.apache.impala.compat.MetastoreShim;
import org.apache.impala.hive.common.MutableValidWriteIdList;
import org.apache.impala.service.BackendConfig;
import org.apache.impala.service.CatalogOpExecutor;
import org.apache.impala.thrift.TPartitionKeyValue;
import org.apache.impala.thrift.TTableName;
import org.apache.impala.util.AcidUtils;
import org.apache.impala.util.MetaStoreUtil;
import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
/**
* Main class which provides Metastore event objects for various event types. Also
* provides a MetastoreEventFactory to get or create the event instances for a given event
* type
*/
public class MetastoreEvents {
/**
* This enum contains keys for parameters added in Metastore entities, relevant for
* event processing. When eventProcessor is instantiated, we make sure during config
* validation that these parameters are not filtered out through the Metastore config
* EVENT_NOTIFICATION_PARAMETERS_EXCLUDE_PATTERNS.
*/
public enum MetastoreEventPropertyKey {
// key to be used for catalog version in table properties for detecting self-events
CATALOG_VERSION("impala.events.catalogVersion"),
// key to be used for catalog service id for detecting self-events
CATALOG_SERVICE_ID("impala.events.catalogServiceId"),
// flag to be set in the table/database parameters to disable event based metadata
// sync. Note the this is a user-facing property. Any changes to this key name
// will break backwards compatibility
DISABLE_EVENT_HMS_SYNC("impala.disableHmsSync");
private String key_;
MetastoreEventPropertyKey(String key) { this.key_ = key; }
public String getKey() { return key_; }
}
public enum MetastoreEventType {
CREATE_TABLE("CREATE_TABLE"),
DROP_TABLE("DROP_TABLE"),
ALTER_TABLE("ALTER_TABLE"),
CREATE_DATABASE("CREATE_DATABASE"),
DROP_DATABASE("DROP_DATABASE"),
ALTER_DATABASE("ALTER_DATABASE"),
ADD_PARTITION("ADD_PARTITION"),
ALTER_PARTITION("ALTER_PARTITION"),
ALTER_PARTITIONS("ALTER_PARTITIONS"),
DROP_PARTITION("DROP_PARTITION"),
INSERT("INSERT"),
INSERT_PARTITIONS("INSERT_PARTITIONS"),
RELOAD("RELOAD"),
ALLOC_WRITE_ID_EVENT("ALLOC_WRITE_ID_EVENT"),
COMMIT_TXN("COMMIT_TXN"),
ABORT_TXN("ABORT_TXN"),
COMMIT_COMPACTION("COMMIT_COMPACTION_EVENT"),
OTHER("OTHER");
private final String eventType_;
MetastoreEventType(String msEventType) {
this.eventType_ = msEventType;
}
@Override
public String toString() {
return eventType_;
}
/**
* Returns the MetastoreEventType from a given string value of event from Metastore's
* NotificationEvent.eventType. If none of the supported MetastoreEventTypes match,
* return OTHER
*
* @param eventType EventType value from the <code>NotificationEvent</code>
*/
public static MetastoreEventType from(String eventType) {
for (MetastoreEventType metastoreEventType : values()) {
if (metastoreEventType.eventType_.equalsIgnoreCase(eventType)) {
return metastoreEventType;
}
}
return OTHER;
}
}
/**
* Factory class to create various MetastoreEvents.
*/
public static class MetastoreEventFactory implements EventFactory {
private static final Logger LOG =
LoggerFactory.getLogger(MetastoreEventFactory.class);
// catalog service instance to be used for creating eventHandlers
protected final CatalogServiceCatalog catalog_;
// metrics registry to be made available for each events to publish metrics
//protected final Metrics metrics_;
// catalogOpExecutor needed for the create/drop events for table and database.
protected final CatalogOpExecutor catalogOpExecutor_;
private static MetastoreEventFactory INSTANCE = null;
public MetastoreEventFactory(CatalogOpExecutor catalogOpExecutor) {
this.catalogOpExecutor_ = Preconditions.checkNotNull(catalogOpExecutor);
this.catalog_ = Preconditions.checkNotNull(catalogOpExecutor.getCatalog());
}
/**
* creates instance of <code>MetastoreEvent</code> used to process a given event type.
* If the event type is unknown, returns a IgnoredEvent
*/
public MetastoreEvent get(NotificationEvent event, Metrics metrics)
throws MetastoreNotificationException {
Preconditions.checkNotNull(event.getEventType());
MetastoreEventType metastoreEventType =
MetastoreEventType.from(event.getEventType());
if (BackendConfig.INSTANCE.getHMSEventIncrementalRefreshTransactionalTable()) {
switch (metastoreEventType) {
case ALLOC_WRITE_ID_EVENT:
return new AllocWriteIdEvent(catalogOpExecutor_, metrics, event);
case COMMIT_TXN:
return new MetastoreShim.CommitTxnEvent(catalogOpExecutor_, metrics, event);
case ABORT_TXN:
return new AbortTxnEvent(catalogOpExecutor_, metrics, event);
}
}
switch (metastoreEventType) {
case CREATE_TABLE:
return new CreateTableEvent(catalogOpExecutor_, metrics, event);
case DROP_TABLE:
return new DropTableEvent(catalogOpExecutor_, metrics, event);
case ALTER_TABLE:
return new AlterTableEvent(catalogOpExecutor_, metrics, event);
case CREATE_DATABASE:
return new CreateDatabaseEvent(catalogOpExecutor_, metrics, event);
case DROP_DATABASE:
return new DropDatabaseEvent(catalogOpExecutor_, metrics, event);
case ALTER_DATABASE:
return new AlterDatabaseEvent(catalogOpExecutor_, metrics, event);
case ADD_PARTITION:
return new AddPartitionEvent(catalogOpExecutor_, metrics, event);
case DROP_PARTITION:
return new DropPartitionEvent(catalogOpExecutor_, metrics, event);
case ALTER_PARTITION:
return new AlterPartitionEvent(catalogOpExecutor_, metrics, event);
case RELOAD:
return new ReloadEvent(catalogOpExecutor_, metrics, event);
case INSERT:
return new InsertEvent(catalogOpExecutor_, metrics, event);
case COMMIT_COMPACTION:
return new CommitCompactionEvent(catalogOpExecutor_, metrics, event);
default:
// ignore all the unknown events by creating a IgnoredEvent
return new IgnoredEvent(catalogOpExecutor_, metrics, event);
}
}
/**
* Given a list of notification events, returns a list of <code>MetastoreEvent</code>
* In case there are create events which are followed by drop events for the same
* object, the create events are filtered out. The drop events do not need to be
* filtered out
*
* This is needed to avoid the replay problem. For example, if catalog created and
* removed a table, the create event received will try to add the object again. This
* table will be visible until the drop table event is processed. This can be avoided
* by "looking ahead" in the event stream to see if the table with the same name was
* dropped. In such a case, the create event can be ignored
*
* @param events NotificationEvents fetched from metastore
* @param metrics Metrics to update while filtering events
* @return A list of MetastoreEvents corresponding to the given the NotificationEvents
* @throws MetastoreNotificationException if a NotificationEvent could not be
* parsed into MetastoreEvent
*/
List<MetastoreEvent> getFilteredEvents(List<NotificationEvent> events,
Metrics metrics) throws MetastoreNotificationException {
Preconditions.checkNotNull(events);
if (events.isEmpty()) return Collections.emptyList();
List<MetastoreEvent> metastoreEvents = new ArrayList<>(events.size());
for (NotificationEvent event : events) {
metastoreEvents.add(get(event, metrics));
}
// filter out the create events which has a corresponding drop event later
int sizeBefore = metastoreEvents.size();
int numFilteredEvents = 0;
int i = 0;
while (i < metastoreEvents.size()) {
MetastoreEvent currentEvent = metastoreEvents.get(i);
String catalogName = currentEvent.getCatalogName();
String eventDb = currentEvent.getDbName();
String eventTbl = currentEvent.getTableName();
if (catalogName != null && !MetastoreShim.getDefaultCatalogName()
.equalsIgnoreCase(catalogName)) {
// currently Impala doesn't support custom hive catalogs and hence we should
// ignore all the events which are on non-default catalog namespaces.
LOG.debug(currentEvent.debugString(
"Filtering out this event since it is on a non-default hive catalog %s",
catalogName));
metastoreEvents.remove(i);
numFilteredEvents++;
} else if ((eventDb != null && catalog_.isBlacklistedDb(eventDb)) || (
eventTbl != null && catalog_.isBlacklistedTable(eventDb, eventTbl))) {
// if the event is on blacklisted db or table we should filter it out
String blacklistedObject = eventTbl != null ? new TableName(eventDb,
eventTbl).toString() : eventDb;
LOG.info(currentEvent.debugString("Filtering out this event since it is on a "
+ "blacklisted database or table %s", blacklistedObject));
metastoreEvents.remove(i);
numFilteredEvents++;
} else {
i++;
}
}
LOG.info(String.format("Total number of events received: %d Total number of events "
+ "filtered out: %d", sizeBefore, numFilteredEvents));
metrics.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC)
.inc(numFilteredEvents);
LOG.debug("Incremented skipped metric to " + metrics
.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC).getCount());
return createBatchEvents(metastoreEvents, metrics);
}
/**
* This method batches together any eligible consecutive elements from the given
* list of {@code MetastoreEvent}. The returned list may or may not contain batch
* events depending on whether it finds any events which could be batched together.
*/
@VisibleForTesting
List<MetastoreEvent> createBatchEvents(List<MetastoreEvent> events, Metrics metrics) {
if (events.size() < 2) return events;
int i = 0, j = 1;
List<MetastoreEvent> batchedEventList = new ArrayList<>();
MetastoreEvent current = events.get(i);
// startEventId points to the current event's or the start of the batch
// in case current is a batch event.
long startEventId = current.getEventId();
while (j < events.size()) {
MetastoreEvent next = events.get(j);
// check if the current metastore event and the next can be batched together
if (!current.canBeBatched(next)) {
// events cannot be batched, add the current event under consideration to the
// list and update current to the next
if (current.getNumberOfEvents() > 1) {
current.infoLog("Created a batch event for {} events from {} to {}",
current.getNumberOfEvents(), startEventId, current.getEventId());
metrics.getCounter(MetastoreEventsProcessor.NUMBER_OF_BATCH_EVENTS).inc();
}
batchedEventList.add(current);
current = next;
startEventId = next.getEventId();
} else {
// next can be batched into current event
current = Preconditions.checkNotNull(current.addToBatchEvents(next));
}
j++;
}
if (current.getNumberOfEvents() > 1) {
current.infoLog("Created a batch event for {} events from {} to {}",
current.getNumberOfEvents(), startEventId, current.getEventId());
metrics.getCounter(MetastoreEventsProcessor.NUMBER_OF_BATCH_EVENTS).inc();
}
batchedEventList.add(current);
return batchedEventList;
}
}
// A factory class for creating metastore events for syncing to latest event id
// We can't reuse existing event factory because of the following scenario:
// A ddl is executed from Impala shell. As a result of it, a self event generated
// for it should be ignored by event factory in MetastoreEventProcessor. If
// MetastoreEventProcessor also uses EventFactoryForSyncToLatestEvent then it would
// skip self event check and end up re processing the event which defeats the purpose
// of self event code. The reason for this behavior is - ddl ops from Impala shell
// i.e catalogOpExecutor don't sync db/table to latest event id. After
// IMPALA-10976 is merged, we can use one event factory and disable self event
// check in that.
public static class EventFactoryForSyncToLatestEvent extends
MetastoreEvents.MetastoreEventFactory {
private static final Logger LOG =
LoggerFactory.getLogger(MetastoreEventFactory.class);
public EventFactoryForSyncToLatestEvent(CatalogOpExecutor catalogOpExecutor) {
super(catalogOpExecutor);
}
public MetastoreEvent get(NotificationEvent event, Metrics metrics)
throws MetastoreNotificationException {
Preconditions.checkNotNull(event.getEventType());
MetastoreEventType metastoreEventType =
MetastoreEventType.from(event.getEventType());
switch (metastoreEventType) {
case ALTER_DATABASE:
return new AlterDatabaseEvent(catalogOpExecutor_, metrics, event) {
@Override
protected boolean isSelfEvent() {
return false;
}
};
case ALTER_TABLE:
return new AlterTableEvent(catalogOpExecutor_, metrics, event) {
@Override
protected boolean isSelfEvent() {
return false;
}
};
case ADD_PARTITION:
return new AddPartitionEvent(catalogOpExecutor_, metrics, event) {
@Override
public boolean isSelfEvent() {
return false;
}
};
case ALTER_PARTITION:
return new AlterPartitionEvent(catalogOpExecutor_, metrics, event) {
@Override
public boolean isSelfEvent() {
return false;
}
};
case DROP_PARTITION:
return new DropPartitionEvent(catalogOpExecutor_, metrics, event) {
@Override
public boolean isSelfEvent() {
return false;
}
};
case INSERT:
return new InsertEvent(catalogOpExecutor_, metrics, event) {
@Override
public boolean isSelfEvent() {
return false;
}
};
default:
return super.get(event, metrics);
}
}
}
/**
* Abstract base class for all MetastoreEvents. A MetastoreEvent is a object used to
* process a NotificationEvent received from metastore. It is self-contained with all
* the information needed to take action on catalog based on a the given
* NotificationEvent
*/
public static abstract class MetastoreEvent {
// String.format compatible string to prepend event id and type
private static final String STR_FORMAT_EVENT_ID_TYPE = "EventId: %d EventType: %s ";
// logger format compatible string to prepend to a log formatted message
private static final String LOG_FORMAT_EVENT_ID_TYPE = "EventId: {} EventType: {} ";
// CatalogServiceCatalog instance on which the event needs to be acted upon
protected final CatalogServiceCatalog catalog_;
protected final CatalogOpExecutor catalogOpExecutor_;
// the notification received from metastore which is processed by this
protected final NotificationEvent event_;
// Logger available for all the sub-classes
protected final Logger LOG = LoggerFactory.getLogger(this.getClass());
// catalog name from the event
protected final String catalogName_;
// dbName from the event
protected final String dbName_;
// tblName from the event
protected final String tblName_;
// eventId of the event. Used instead of calling getter on event_ everytime
private long eventId_;
// eventType from the NotificationEvent or in case of batch events set using
// the setter for this field
private MetastoreEventType eventType_;
// Actual notificationEvent object received from Metastore
protected final NotificationEvent metastoreNotificationEvent_;
// metrics registry so that events can add metrics
protected final Metrics metrics_;
protected MetastoreEvent(CatalogOpExecutor catalogOpExecutor, Metrics metrics,
NotificationEvent event) {
this.catalogOpExecutor_ = catalogOpExecutor;
this.catalog_ = catalogOpExecutor_.getCatalog();
this.event_ = event;
this.eventId_ = event_.getEventId();
this.eventType_ = MetastoreEventType.from(event.getEventType());
// certain event types in Hive-3 like COMMIT_TXN may not have dbName set
this.catalogName_ = event.getCatName();
this.dbName_ = event.getDbName();
this.tblName_ = event.getTableName();
this.metastoreNotificationEvent_ = event;
this.metrics_ = metrics;
}
public long getEventId() { return eventId_; }
public long getEventTime() { return event_.getEventTime(); }
public MetastoreEventType getEventType() { return eventType_; }
/**
* Certain events like {@link BatchPartitionEvent} batch a group of events
* to create a batch event type. This method is used to override the event type
* in such cases since the event type is not really derived from NotificationEvent.
*/
public void setEventType(MetastoreEventType type) {
this.eventType_ = type;
}
public String getCatalogName() { return catalogName_; }
public String getDbName() { return dbName_; }
public String getTableName() { return tblName_; }
/**
* Process this event if it is enabled based on the flags on this object
*
* @throws CatalogException If Catalog operations fail
* @throws MetastoreNotificationException If NotificationEvent parsing fails
*/
public void processIfEnabled()
throws CatalogException, MetastoreNotificationException {
if (isEventProcessingDisabled()) {
infoLog("Skipping this event because of flag evaluation");
metrics_.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC).inc();
debugLog("Incremented skipped metric to " + metrics_
.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC).getCount());
return;
}
if (BackendConfig.INSTANCE.enableSyncToLatestEventOnDdls()) {
if (shouldSkipWhenSyncingToLatestEventId()) {
metrics_.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC).inc();
return;
}
}
process();
}
/**
* Checks if the given event can be batched into this event. Default behavior is
* to return false which can be overridden by a sub-class.
*
* @param event The event under consideration to be batched into this event.
* @return false if event cannot be batched into this event; otherwise true.
*/
protected boolean canBeBatched(MetastoreEvent event) { return false; }
/**
* Adds the given event into the batch of events represented by this event. Default
* implementation is to return null. Sub-classes must override this method to
* implement batching.
*
* @param event The event which needs to be added to the batch.
* @return The batch event which represents all the events batched into this event
* until now including the given event.
*/
protected MetastoreEvent addToBatchEvents(MetastoreEvent event) { return null; }
/**
* Returns the number of events represented by this event. For most events this is
* 1. In case of batch events this could be more than 1.
*/
protected int getNumberOfEvents() { return 1; }
/**
* Certain events like ALTER_TABLE or ALTER_PARTITION implement logic to ignore
* some events because they are not interesting from catalogd's perspective.
* @return true if this event can be skipped.
*/
protected boolean canBeSkipped() { return false; }
/**
* In case of batch events, this method can be used override the {@code eventType_}
* field which is used for logging purposes.
*/
protected MetastoreEventType getBatchEventType() { return null; }
/**
* Evaluates whether processing of this event should be skipped
* if sync to latest event id is enabled. The event should
* be skipped if the db/table is already synced atleast till
* this event.
* @return true if the event should be skipped. False
* otherwise
* @throws CatalogException
*/
protected abstract boolean shouldSkipWhenSyncingToLatestEventId()
throws CatalogException;
/**
* Process the information available in the NotificationEvent to take appropriate
* action on Catalog
*
* @throws MetastoreNotificationException in case of event parsing errors out
* @throws CatalogException in case catalog operations could not be performed
*/
protected abstract void process()
throws MetastoreNotificationException, CatalogException;
/**
* Helper method to get debug string with helpful event information prepended to the
* message. This can be used to generate helpful exception messages
*
* @param msgFormatString String value to be used in String.format() for the given
* message
* @param args args to the <code>String.format()</code> for the given
* msgFormatString
*/
protected String debugString(String msgFormatString, Object... args) {
String formatString =
new StringBuilder(STR_FORMAT_EVENT_ID_TYPE).append(msgFormatString).toString();
Object[] formatArgs = getLogFormatArgs(args);
return String.format(formatString, formatArgs);
}
/**
* Helper method to generate the format args after prepending the event id and type
*/
private Object[] getLogFormatArgs(Object[] args) {
Object[] formatArgs = new Object[args.length + 2];
formatArgs[0] = getEventId();
formatArgs[1] = getEventType();
int i = 2;
for (Object arg : args) {
formatArgs[i] = arg;
i++;
}
return formatArgs;
}
/**
* Logs at info level the given log formatted string and its args. The log formatted
* string should have {} pair at the appropriate location in the string for each arg
* value provided. This method prepends the event id and event type before logging the
* message. No-op if the log level is not at INFO
*/
protected void infoLog(String logFormattedStr, Object... args) {
if (!LOG.isInfoEnabled()) return;
String formatString =
new StringBuilder(LOG_FORMAT_EVENT_ID_TYPE).append(logFormattedStr).toString();
Object[] formatArgs = getLogFormatArgs(args);
LOG.info(formatString, formatArgs);
}
/**
* Similar to infoLog excepts logs at debug level
*/
protected void debugLog(String logFormattedStr, Object... args) {
if (!LOG.isDebugEnabled()) return;
String formatString =
new StringBuilder(LOG_FORMAT_EVENT_ID_TYPE).append(logFormattedStr).toString();
Object[] formatArgs = getLogFormatArgs(args);
LOG.debug(formatString, formatArgs);
}
/**
* Similar to infoLog excepts logs at trace level
*/
protected void traceLog(String logFormattedStr, Object... args) {
if (!LOG.isTraceEnabled()) return;
String formatString =
new StringBuilder(LOG_FORMAT_EVENT_ID_TYPE).append(logFormattedStr).toString();
Object[] formatArgs = getLogFormatArgs(args);
LOG.trace(formatString, formatArgs);
}
/**
* Similar to infoLog excepts logs at warn level
*/
protected void warnLog(String logFormattedStr, Object... args) {
if (!LOG.isWarnEnabled()) return;
String formatString =
new StringBuilder(LOG_FORMAT_EVENT_ID_TYPE).append(logFormattedStr).toString();
Object[] formatArgs = getLogFormatArgs(args);
LOG.warn(formatString, formatArgs);
}
/**
* Search for a inverse event (for example drop_table is a inverse event for
* create_table) for this event from a given list of notificationEvents starting for
* the startIndex. This is useful for skipping certain events from processing
*
* @param events List of NotificationEvents to be searched
* @return true if the object is removed after this event, else false
*/
protected boolean isRemovedAfter(List<MetastoreEvent> events) {
return false;
}
/**
* Returns true if event based sync is disabled for this table/database associated
* with this event
*/
protected abstract boolean isEventProcessingDisabled();
protected abstract SelfEventContext getSelfEventContext();
/**
* This method detects if this event is self-generated or not (see class
* documentation of <code>MetastoreEventProcessor</code> to understand what a
* self-event is).
*
* In order to determine this, it compares the value of catalogVersion from the
* event with the list of pending version numbers stored in the catalog
* database/table. The event could be generated by another instance of CatalogService
* which can potentially have the same versionNumber. In order to resolve such
* conflict, it compares the CatalogService's serviceId before comparing the version
* number. If it is determined that this is indeed a self-event, this method also
* clears the version number from the catalog database/table's list of pending
* versions for in-flight events. This is needed so that a subsequent event with the
* same service id or version number is not incorrectly determined as a self-event. A
* subsequent event with the same serviceId and versionNumber is most likely generated
* by a non-Impala system because it cached the table object having those values of
* serviceId and version. More details on complete flow of self-event handling
* logic can be read in <code>MetastoreEventsProcessor</code> documentation.
*
* @return True if this event is a self-generated event. If the returned value is
* true, this method also clears the version number from the catalog database/table.
* Returns false if the version numbers or service id don't match
*/
protected boolean isSelfEvent() {
try {
if (catalog_.evaluateSelfEvent(getSelfEventContext())) {
metrics_.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC)
.inc(getNumberOfEvents());
infoLog("Incremented events skipped counter to {}",
metrics_.getCounter(MetastoreEventsProcessor.EVENTS_SKIPPED_METRIC)
.getCount());
return true;
}
} catch (CatalogException e) {
debugLog("Received exception {}. Ignoring self-event evaluation",
e.getMessage());
}
return false;
}
public final boolean isDropEvent() {
return (this instanceof DropTableEvent ||
this instanceof DropDatabaseEvent ||
this instanceof DropPartitionEvent);
}
@Override
public String toString() {
return String.format(STR_FORMAT_EVENT_ID_TYPE, eventId_, eventType_);
}
}
public static String getStringProperty(
Map<String, String> params, String key, String defaultVal) {
if (params == null) return defaultVal;
return params.getOrDefault(key, defaultVal);
}
/**
* Base class for all the table events
*/
public static abstract class MetastoreTableEvent extends MetastoreEvent {
// tblName from the event
protected final String tblName_;
// tbl object from the Notification event, corresponds to the before tableObj in
// case of alter events
protected org.apache.hadoop.hive.metastore.api.Table msTbl_;
// A boolean flag used in alter table event to record if the file metadata reload
// can be skipped for certain type of alter table statements
protected boolean skipFileMetadataReload_ = false;
// in case of partition batch events, this method can be overridden to return
// the partition object from the events which are batched together.
protected Partition getPartitionForBatching() { return null; }
private MetastoreTableEvent(CatalogOpExecutor catalogOpExecutor,
Metrics metrics, NotificationEvent event) {
super(catalogOpExecutor, metrics, event);
Preconditions.checkNotNull(dbName_, "Database name cannot be null");
tblName_ = Preconditions.checkNotNull(event.getTableName());
}
/**
* Util method to return the fully qualified table name which is of the format
* dbName.tblName for this event
*/
protected String getFullyQualifiedTblName() {
return new TableName(dbName_, tblName_).toString();
}
/**
* Checks if the table level property is set in the parameters of the table from the
* event. If it is available, it takes precedence over database level flag for this
* table. If the table level property is not set, returns the value from the database
* level property.f
*
* @return Boolean value of the table property with the key
* <code>MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC</code>. Else,
* returns the database property which is associated with this table. Returns
* false if neither of the properties are set.
*/
@Override
protected boolean isEventProcessingDisabled() {
Preconditions.checkNotNull(msTbl_);
Boolean tblProperty = getHmsSyncProperty(msTbl_);
if (tblProperty != null) {
infoLog("Found table level flag {} is set to {} for table {}",
MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC.getKey(),
tblProperty.toString(),
getFullyQualifiedTblName());
return tblProperty;
}
// if the tbl property is not set check at db level
String dbFlagVal = catalog_.getDbProperty(dbName_,
MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC.getKey());
if (dbFlagVal != null) {
// no need to spew unnecessary logs. Most tables/databases are expected to not
// have this flag set when event based HMS polling is enabled
debugLog("Table level flag is not set. Db level flag {} is {} for "
+ "database {}",
MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC.getKey(),
dbFlagVal, dbName_);
}
// flag value of null also returns false
return Boolean.valueOf(dbFlagVal);
}
/**
* Gets the value of the parameter with the key
* <code>MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC</code> from the given
* table
*
* @return the Boolean value of the property with the key
* <code>MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC</code> if it is
* available else returns null
*/
public static Boolean getHmsSyncProperty(
org.apache.hadoop.hive.metastore.api.Table tbl) {
if (!tbl.isSetParameters()) return null;
String val =
tbl.getParameters()
.get(MetastoreEventPropertyKey.DISABLE_EVENT_HMS_SYNC.getKey());
if (val == null || val.isEmpty()) return null;
return Boolean.valueOf(val);
}
/**
* Util method to create partition key-value map from HMS Partition objects.
*/
protected static List<TPartitionKeyValue> getTPartitionSpecFromHmsPartition(
org.apache.hadoop.hive.metastore.api.Table msTbl, Partition partition) {
List<TPartitionKeyValue> tPartSpec = new ArrayList<>();
List<org.apache.hadoop.hive.metastore.api.FieldSchema> fsList =
msTbl.getPartitionKeys();
List<String> partVals = partition.getValues();
Preconditions.checkNotNull(partVals);
Preconditions.checkState(fsList.size() == partVals.size());
for (int i = 0; i < fsList.size(); i++) {
tPartSpec.add(new TPartitionKeyValue(fsList.get(i).getName(), partVals.get(i)));
}
return tPartSpec;
}
/*
* Helper function to initiate a table reload on Catalog. Re-throws the exception if
* the catalog operation throws.
*/
protected boolean reloadTableFromCatalog(String operation, boolean isTransactional)
throws CatalogException {
try {
if (!catalog_.reloadTableIfExists(dbName_, tblName_,
"Processing " + operation + " event from HMS", getEventId(),
skipFileMetadataReload_)) {
debugLog("Automatic refresh on table {} failed as the table "
+ "either does not exist anymore or is not in loaded state.",
getFullyQualifiedTblName());
return false;
}
} catch (TableLoadingException | DatabaseNotFoundException e) {
// there could be many reasons for receiving a tableLoading exception,
// eg. table doesn't exist in HMS anymore or table schema is not supported
// or Kudu threw an exception due to some internal error. There is not much
// we can do here other than log it appropriately.
debugLog("Table {} was not refreshed due to error {}",
getFullyQualifiedTblName(), e.getMessage());
return false;
}
String tblStr = isTransactional ? "transactional table" : "table";
infoLog("Refreshed {} {}", tblStr, getFullyQualifiedTblName());
metrics_.getCounter(MetastoreEventsProcessor.NUMBER_OF_TABLE_REFRESHES).inc();
return true;
}
/**
* Reloads the partitions provided, only if the table is loaded and if the partitions
* exist in catalogd.
* @param partitions the list of Partition objects which need to be reloaded.
* @param fileMetadataLoadOpts: describes how to reload file metadata for partitions
* @param reason The reason for reload operation which is used for logging by
* catalogd.
*/
protected void reloadPartitions(List<Partition> partitions,
FileMetadataLoadOpts fileMetadataLoadOpts, String reason)
throws CatalogException {
try {
int numPartsRefreshed = catalogOpExecutor_.reloadPartitionsIfExist(getEventId(),
dbName_, tblName_, partitions, reason, fileMetadataLoadOpts);
if (numPartsRefreshed > 0) {
metrics_.getCounter(MetastoreEventsProcessor.NUMBER_OF_PARTITION_REFRESHES)
.inc(numPartsRefreshed);
}
} catch (TableNotLoadedException e) {
debugLog("Ignoring the event since table {} is not loaded",
getFullyQualifiedTblName());
} catch (DatabaseNotFoundException | TableNotFoundException e) {
debugLog("Ignoring the event since table {} is not found",
getFullyQualifiedTblName());
}
}
/**
* Reloads partitions from the event if they exist. Does not fetch those partitions
* from HMS. Does NOT reload file metadata
* @param partitions: Partitions to be reloaded
* @param reason: Reason for reloading. Mainly used for logging in catalogD
* @throws CatalogException
*/
protected void reloadPartitionsFromEvent(List<Partition> partitions, String reason)
throws CatalogException {
try {
int numPartsRefreshed = catalogOpExecutor_.reloadPartitionsFromEvent(getEventId(),
dbName_, tblName_, partitions, reason);
if (numPartsRefreshed > 0) {
metrics_.getCounter(MetastoreEventsProcessor.NUMBER_OF_PARTITION_REFRESHES)
.inc(numPartsRefreshed);
}
} catch (TableNotLoadedException e) {
debugLog("Ignoring the event since table {} is not loaded",
getFullyQualifiedTblName());
} catch (DatabaseNotFoundException | TableNotFoundException e) {
debugLog("Ignoring the event since table {} is not found",
getFullyQualifiedTblName());
}
}
protected void reloadPartitionsFromNames(List<String> partitionNames, String reason,
FileMetadataLoadOpts fileMetadataLoadOpts) throws CatalogException {
try {
int numPartsRefreshed = catalogOpExecutor_.reloadPartitionsFromNamesIfExists(
getEventId(), dbName_, tblName_, partitionNames, reason,
fileMetadataLoadOpts);
if (numPartsRefreshed > 0) {
metrics_.getCounter(MetastoreEventsProcessor.NUMBER_OF_PARTITION_REFRESHES)
.inc(numPartsRefreshed);
}
} catch (TableNotLoadedException e) {
debugLog("Ignoring the event since table {} is not loaded",
getFullyQualifiedTblName());
} catch (DatabaseNotFoundException | TableNotFoundException e) {
debugLog("Ignoring the event since table {} is not found",
getFullyQualifiedTblName());
}
}
/**
* To decide whether to skip processing this event, fetch table from cache
* and compare the last synced event id of cache table with this event id.
* Skip this event if the table is already synced till this event id. Otherwise,
* process this event.
* @return true if processing of this event should be skipped. False otherwise
* @throws CatalogException
*/
protected boolean shouldSkipWhenSyncingToLatestEventId() throws CatalogException {
Preconditions.checkState(
BackendConfig.INSTANCE.enableSyncToLatestEventOnDdls(),
"sync to latest event flag is not set to true");
long eventId = this.getEventId();
Preconditions.checkState(eventId > 0,
"Invalid event id %s. Should be greater than "
+ "0", eventId);
org.apache.impala.catalog.Table tbl = null;
try {
tbl = catalog_.getTable(dbName_, tblName_);
if (tbl == null) {
infoLog("Skipping on table {}.{} since it does not exist in cache", dbName_,
tblName_);
return true;
}
// During alter table rename, the renamed table is created as Incomplete table
// with create event id set to alter_table event id (i.e not -1) and therefore
// should *NOT* be skipped in event processing
if (tbl instanceof IncompleteTable && tbl.getLastSyncedEventId() == -1) {
infoLog("Skipping on an incomplete table {} since last synced event id is "
+ "set to {}", tbl.getFullName(), tbl.getLastSyncedEventId());
return true;
}
} catch (DatabaseNotFoundException e) {
infoLog("Skipping on table {} because db {} not found in cache", tblName_,
dbName_);
return true;
}
boolean shouldSkip = false;
// do not acquire read lock on tbl because lastSyncedEventId_ is volatile.
// It is fine if this method returns false because at the time of actual
// processing of the event, we would again check lastSyncedEventId_ after
// acquiring write lock on table and if the table was already synced till
// this event id, the event processing would be skipped.
if (tbl.getLastSyncedEventId() >= eventId) {
infoLog("Skipping on table {} since it is already synced till event id {}",
tbl.getFullName(), tbl.getLastSyncedEventId());
shouldSkip = true;
}
return shouldSkip;
}