-
Notifications
You must be signed in to change notification settings - Fork 96
/
AbstractBinderFactory.java
1503 lines (1329 loc) · 62.3 KB
/
AbstractBinderFactory.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
// Copyright 2016 Yahoo Inc.
// Licensed under the terms of the Apache license. Please see LICENSE.md file distributed with this work for terms.
package com.yahoo.bard.webservice.application;
import static com.yahoo.bard.webservice.config.BardFeatureFlag.DRUID_COORDINATOR_METADATA;
import static com.yahoo.bard.webservice.config.BardFeatureFlag.DRUID_DIMENSIONS_LOADER;
import static com.yahoo.bard.webservice.config.BardFeatureFlag.DRUID_LOOKUP_METADATA;
import static com.yahoo.bard.webservice.web.handlers.CacheRequestHandler.CACHE_HITS;
import static com.yahoo.bard.webservice.web.handlers.CacheRequestHandler.CACHE_REQUESTS;
import static com.yahoo.bard.webservice.web.handlers.DefaultWebServiceHandlerSelector.QUERY_REQUEST_TOTAL;
import static com.yahoo.bard.webservice.web.handlers.SplitQueryRequestHandler.SPLITS;
import static com.yahoo.bard.webservice.web.handlers.SplitQueryRequestHandler.SPLIT_QUERIES;
import com.yahoo.bard.webservice.application.healthchecks.AllDimensionsLoadedHealthCheck;
import com.yahoo.bard.webservice.application.healthchecks.DataSourceMetadataLoaderHealthCheck;
import com.yahoo.bard.webservice.application.healthchecks.DruidDimensionsLoaderHealthCheck;
import com.yahoo.bard.webservice.application.healthchecks.LookupHealthCheck;
import com.yahoo.bard.webservice.application.healthchecks.VersionHealthCheck;
import com.yahoo.bard.webservice.async.broadcastchannels.BroadcastChannel;
import com.yahoo.bard.webservice.async.broadcastchannels.SimpleBroadcastChannel;
import com.yahoo.bard.webservice.async.jobs.jobrows.DefaultJobField;
import com.yahoo.bard.webservice.async.jobs.jobrows.DefaultJobRowBuilder;
import com.yahoo.bard.webservice.async.jobs.jobrows.JobRowBuilder;
import com.yahoo.bard.webservice.async.jobs.payloads.DefaultJobPayloadBuilder;
import com.yahoo.bard.webservice.async.jobs.payloads.JobPayloadBuilder;
import com.yahoo.bard.webservice.async.jobs.stores.ApiJobStore;
import com.yahoo.bard.webservice.async.jobs.stores.NoOpApiJobStore;
import com.yahoo.bard.webservice.async.preresponses.stores.NoOpPreResponseStore;
import com.yahoo.bard.webservice.async.preresponses.stores.PreResponseStore;
import com.yahoo.bard.webservice.async.workflows.AsynchronousWorkflowsBuilder;
import com.yahoo.bard.webservice.async.workflows.DefaultAsynchronousWorkflowsBuilder;
import com.yahoo.bard.webservice.config.BardFeatureFlag;
import com.yahoo.bard.webservice.config.CacheFeatureFlag;
import com.yahoo.bard.webservice.config.FeatureFlag;
import com.yahoo.bard.webservice.config.FeatureFlagRegistry;
import com.yahoo.bard.webservice.config.SystemConfig;
import com.yahoo.bard.webservice.config.SystemConfigProvider;
import com.yahoo.bard.webservice.data.DruidQueryBuilder;
import com.yahoo.bard.webservice.data.DruidResponseParser;
import com.yahoo.bard.webservice.data.HttpResponseMaker;
import com.yahoo.bard.webservice.data.PartialDataHandler;
import com.yahoo.bard.webservice.data.PreResponseDeserializer;
import com.yahoo.bard.webservice.data.cache.DataCache;
import com.yahoo.bard.webservice.data.cache.HashDataCache;
import com.yahoo.bard.webservice.data.cache.MemDataCache;
import com.yahoo.bard.webservice.data.cache.MemTupleDataCache;
import com.yahoo.bard.webservice.data.cache.StubDataCache;
import com.yahoo.bard.webservice.data.cache.StubTupleDataCache;
import com.yahoo.bard.webservice.data.cache.TupleDataCache;
import com.yahoo.bard.webservice.data.config.ConfigurationLoader;
import com.yahoo.bard.webservice.data.config.DefaultConfigurationLoader;
import com.yahoo.bard.webservice.data.config.ResourceDictionaries;
import com.yahoo.bard.webservice.data.config.dimension.DimensionConfig;
import com.yahoo.bard.webservice.data.config.dimension.DimensionLoader;
import com.yahoo.bard.webservice.data.config.dimension.TypeAwareDimensionLoader;
import com.yahoo.bard.webservice.data.config.metric.MetricLoader;
import com.yahoo.bard.webservice.data.config.table.TableLoader;
import com.yahoo.bard.webservice.data.dimension.DimensionDictionary;
import com.yahoo.bard.webservice.data.metric.LogicalMetric;
import com.yahoo.bard.webservice.data.metric.MetricDictionary;
import com.yahoo.bard.webservice.data.metric.TemplateDruidQueryMerger;
import com.yahoo.bard.webservice.data.time.GranularityDictionary;
import com.yahoo.bard.webservice.data.time.GranularityParser;
import com.yahoo.bard.webservice.data.time.StandardGranularityParser;
import com.yahoo.bard.webservice.data.volatility.DefaultingVolatileIntervalsService;
import com.yahoo.bard.webservice.data.volatility.VolatileIntervalsService;
import com.yahoo.bard.webservice.druid.client.DruidClientConfigHelper;
import com.yahoo.bard.webservice.druid.client.DruidServiceConfig;
import com.yahoo.bard.webservice.druid.client.DruidWebService;
import com.yahoo.bard.webservice.druid.client.impl.AsyncDruidWebServiceImpl;
import com.yahoo.bard.webservice.druid.client.impl.HeaderNestingJsonBuilderStrategy;
import com.yahoo.bard.webservice.druid.model.builders.DefaultDruidHavingBuilder;
import com.yahoo.bard.webservice.druid.model.builders.DruidFilterBuilder;
import com.yahoo.bard.webservice.druid.model.builders.DruidHavingBuilder;
import com.yahoo.bard.webservice.druid.model.builders.DruidInFilterBuilder;
import com.yahoo.bard.webservice.druid.model.builders.DruidOrFilterBuilder;
import com.yahoo.bard.webservice.druid.model.orderby.OrderByColumn;
import com.yahoo.bard.webservice.druid.model.query.LookbackQuery;
import com.yahoo.bard.webservice.druid.util.FieldConverterSupplier;
import com.yahoo.bard.webservice.druid.util.FieldConverters;
import com.yahoo.bard.webservice.druid.util.ThetaSketchFieldConverter;
import com.yahoo.bard.webservice.exception.DataExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliDataExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliDimensionExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliJobsExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliMetricExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliSlicesExceptionHandler;
import com.yahoo.bard.webservice.exception.FiliTablesExceptionHandler;
import com.yahoo.bard.webservice.exception.MetadataExceptionHandler;
import com.yahoo.bard.webservice.metadata.DataSourceMetadataLoadTask;
import com.yahoo.bard.webservice.metadata.DataSourceMetadataService;
import com.yahoo.bard.webservice.metadata.QuerySigningService;
import com.yahoo.bard.webservice.metadata.RegisteredLookupMetadataLoadTask;
import com.yahoo.bard.webservice.metadata.RequestedIntervalsFunction;
import com.yahoo.bard.webservice.metadata.SegmentIntervalsHashIdGenerator;
import com.yahoo.bard.webservice.table.LogicalTableDictionary;
import com.yahoo.bard.webservice.table.PhysicalTableDictionary;
import com.yahoo.bard.webservice.table.resolver.DefaultPhysicalTableResolver;
import com.yahoo.bard.webservice.table.resolver.PhysicalTableResolver;
import com.yahoo.bard.webservice.util.DefaultingDictionary;
import com.yahoo.bard.webservice.util.SimplifiedIntervalList;
import com.yahoo.bard.webservice.web.CsvResponseWriter;
import com.yahoo.bard.webservice.web.DefaultResponseFormatResolver;
import com.yahoo.bard.webservice.web.DimensionApiRequestMapper;
import com.yahoo.bard.webservice.web.FiliResponseWriter;
import com.yahoo.bard.webservice.web.FiliResponseWriterSelector;
import com.yahoo.bard.webservice.web.FilteredThetaSketchMetricsHelper;
import com.yahoo.bard.webservice.web.JsonApiResponseWriter;
import com.yahoo.bard.webservice.web.JsonResponseWriter;
import com.yahoo.bard.webservice.web.MetricsFilterSetBuilder;
import com.yahoo.bard.webservice.web.NoOpRequestMapper;
import com.yahoo.bard.webservice.web.RateLimiter;
import com.yahoo.bard.webservice.web.RequestMapper;
import com.yahoo.bard.webservice.web.ResponseFormatResolver;
import com.yahoo.bard.webservice.web.ResponseWriter;
import com.yahoo.bard.webservice.web.apirequest.DataApiRequest;
import com.yahoo.bard.webservice.web.apirequest.DataApiRequestFactory;
import com.yahoo.bard.webservice.web.apirequest.DefaultDataApiRequestFactory;
import com.yahoo.bard.webservice.web.apirequest.DimensionsApiRequest;
import com.yahoo.bard.webservice.web.apirequest.JobsApiRequest;
import com.yahoo.bard.webservice.web.apirequest.MetricsApiRequest;
import com.yahoo.bard.webservice.web.apirequest.SlicesApiRequest;
import com.yahoo.bard.webservice.web.apirequest.TablesApiRequest;
import com.yahoo.bard.webservice.web.apirequest.generator.Generator;
import com.yahoo.bard.webservice.web.apirequest.generator.LegacyGenerator;
import com.yahoo.bard.webservice.web.apirequest.generator.filter.ApiFilterParser;
import com.yahoo.bard.webservice.web.apirequest.generator.filter.RegexApiFilterParser;
import com.yahoo.bard.webservice.web.apirequest.generator.having.DefaultHavingApiGenerator;
import com.yahoo.bard.webservice.web.apirequest.generator.having.HavingGenerator;
import com.yahoo.bard.webservice.web.apirequest.generator.having.PerRequestDictionaryHavingGenerator;
import com.yahoo.bard.webservice.web.apirequest.generator.metric.ApiRequestLogicalMetricBinder;
import com.yahoo.bard.webservice.web.apirequest.generator.metric.ProtocolLogicalMetricGenerator;
import com.yahoo.bard.webservice.web.apirequest.generator.orderBy.DefaultOrderByGenerator;
import com.yahoo.bard.webservice.web.apirequest.metrics.ApiMetricAnnotater;
import com.yahoo.bard.webservice.web.handlers.workflow.DruidWorkflow;
import com.yahoo.bard.webservice.web.handlers.workflow.RequestWorkflowProvider;
import com.yahoo.bard.webservice.web.ratelimit.DefaultRateLimiter;
import com.yahoo.bard.webservice.web.responseprocessors.ResponseProcessorFactory;
import com.yahoo.bard.webservice.web.responseprocessors.ResultSetResponseProcessorFactory;
import com.yahoo.bard.webservice.web.util.CacheService;
import com.yahoo.bard.webservice.web.util.QuerySignedCacheService;
import com.yahoo.bard.webservice.web.util.QueryWeightUtil;
import com.yahoo.bard.webservice.web.util.ResponseUtils;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Metric;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.RatioGauge;
import com.codahale.metrics.health.HealthCheck;
import com.codahale.metrics.health.HealthCheckRegistry;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.glassfish.hk2.api.TypeLiteral;
import org.glassfish.hk2.utilities.Binder;
import org.glassfish.hk2.utilities.binding.AbstractBinder;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.DateTimeFormatterBuilder;
import org.joda.time.format.DateTimeParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rx.subjects.PublishSubject;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.time.Clock;
import java.time.ZoneId;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.validation.constraints.NotNull;
/**
* Abstract Binder factory implements the standard buildBinder functionality.
* It is left to individual projects to subclass, providing dimensions config,
* Metric and Table loading classes.
*/
public abstract class AbstractBinderFactory implements BinderFactory {
private static final Logger LOG = LoggerFactory.getLogger(AbstractBinderFactory.class);
private static final SystemConfig SYSTEM_CONFIG = SystemConfigProvider.getInstance();
public static final String HEALTH_CHECK_NAME_DATASOURCE_METADATA = "datasource metadata loader";
public static final String HEALTH_CHECK_NAME_LOOKUP_METADATA = "lookup metadata loader";
public static final String HEALTH_CHECK_NAME_DRUID_DIM_LOADER = "druid dimensions loader";
public static final String HEALTH_CHECK_VERSION = "version";
public static final String HEALTH_CHECK_NAME_DIMENSION = "dimension check";
private static final String METER_CACHE_HIT_RATIO = "queries.meter.cache.hit_ratio";
private static final String METER_SPLITS_TOTAL_RATIO = "queries.meter.split_queries.total_ratio";
private static final String METER_SPLITS_RATIO = "queries.meter.split_queries.ratio";
private static final String JVM_UPTIME = "jvm.uptime";
private static final String DRUID_HEADER_SUPPLIER_CLASS = "druid_header_supplier_class";
public static final String NAME_ACTIVE_PROTOCOLS = "active_protocols_name";
public static final String NAME_METRIC_GENERATOR = "metric_generator_name";
// Two minutes in milliseconds
public static final int HC_LAST_RUN_PERIOD_MILLIS_DEFAULT = (int) TimeUnit.MINUTES.toMillis(2);
public static final int LOADER_SCHEDULER_THREAD_POOL_SIZE_DEFAULT = 4;
public static final int SEG_LOADER_HC_LAST_RUN_PERIOD_MILLIS = SYSTEM_CONFIG.getIntProperty(
SYSTEM_CONFIG.getPackageVariableName("seg_loader_health_check_last_run_duration"),
HC_LAST_RUN_PERIOD_MILLIS_DEFAULT
);
public static final int DRUID_DIM_LOADER_HC_LAST_RUN_PERIOD_MILLIS = SYSTEM_CONFIG.getIntProperty(
SYSTEM_CONFIG.getPackageVariableName("druid_dim_loader_health_check_last_run_duration"),
HC_LAST_RUN_PERIOD_MILLIS_DEFAULT
);
public static final int LOADER_SCHEDULER_THREAD_POOL_SIZE = SYSTEM_CONFIG.getIntProperty(
SYSTEM_CONFIG.getPackageVariableName("loader_scheduler_thread_pool_size"),
LOADER_SCHEDULER_THREAD_POOL_SIZE_DEFAULT
);
public static final String DEPRECATED_PERMISSIVE_AVAILABILITY_FLAG = SYSTEM_CONFIG.getPackageVariableName(
"permissive_column_availability_enabled");
public static final int DRUID_UNCOVERED_INTERVAL_LIMIT = SYSTEM_CONFIG.getIntProperty(
SYSTEM_CONFIG.getPackageVariableName("druid_uncovered_interval_limit"),
0
);
public static final String SYSTEM_CONFIG_TIMEZONE_KEY = "timezone";
private ObjectMappersSuite objectMappers;
protected DataSourceMetadataService dataSourceMetadataService;
private ConfigurationLoader loader;
private final TaskScheduler loaderScheduler = new TaskScheduler(LOADER_SCHEDULER_THREAD_POOL_SIZE);
/**
* Constructor.
*/
public AbstractBinderFactory() {
super();
}
@Override
public final Binder buildBinder() {
return new AbstractBinder() {
@Override
protected void configure() {
HealthCheckRegistry healthCheckRegistry = HealthCheckRegistryFactory.getRegistry();
Stream.concat(
collectFeatureFlags(BardFeatureFlag.class).stream(),
collectFeatureFlags().stream()
).forEach(flag -> bind(flag).named(flag.name()).to(FeatureFlag.class));
bind(FeatureFlagRegistry.class).to(FeatureFlagRegistry.class);
// Bard currently expects there to be one web service
DruidWebService druidWebService = buildDruidWebService(getMappers().getMapper());
bind(druidWebService).to(DruidWebService.class);
// A separate web service for metadata
DruidWebService metadataDruidWebService = null;
if (DRUID_COORDINATOR_METADATA.isOn()) {
metadataDruidWebService = buildMetadataDruidWebService(getMappers().getMapper());
bind(metadataDruidWebService).named("metadataDruidWebService").to(DruidWebService.class);
}
// Bind the timeGrain
bind(getGranularityDictionary()).to(GranularityDictionary.class);
bind(getGranularityParser()).to(GranularityParser.class);
// Bind the request building action classes for druid
bind(buildDruidQueryBuilder()).to(DruidQueryBuilder.class);
bind(TemplateDruidQueryMerger.class).to(TemplateDruidQueryMerger.class);
bind(buildDruidResponseParser()).to(DruidResponseParser.class);
bind(buildDruidFilterBuilder()).to(DruidFilterBuilder.class);
bind(buildDruidHavingBuilder()).to(DruidHavingBuilder.class);
bind(buildDataApiRequestFactory()).to(DataApiRequestFactory.class);
//Initialize the field converter
FieldConverterSupplier.setSketchConverter(initializeSketchConverter());
//Initialize the metrics filter helper
FieldConverterSupplier.setMetricsFilterSetBuilder(initializeMetricsFilterSetBuilder());
// Build the datasource metadata service containing the data segments
bind(getDataSourceMetadataService()).to(DataSourceMetadataService.class);
// Protocol Stuff
bindMetricGenerator(this);
// Build the configuration loader and load configuration
loader = getConfigurationLoader();
loader.load();
bindDictionaries(this);
bind(buildHavingGenerator(loader)).to(HavingGenerator.class);
// Bind the request mappers
bindRequestMappers(this);
// Setup end points and back end services
setupHealthChecks(healthCheckRegistry, loader.getDimensionDictionary());
setupGauges();
bind(buildCache()).to(DataCache.class);
bind(QueryWeightUtil.class).to(QueryWeightUtil.class);
bind(getMappers()).to(ObjectMappersSuite.class);
bind(getMappers().getMapper()).to(ObjectMapper.class);
bind(getWorkflow()).to(RequestWorkflowProvider.class);
bind(getPhysicalTableResolver()).to(PhysicalTableResolver.class);
bind(PartialDataHandler.class).to(PartialDataHandler.class);
bind(getVolatileIntervalsService()).to(VolatileIntervalsService.class);
QuerySigningService<?> querySigningService = buildQuerySigningService(
loader.getPhysicalTableDictionary(),
dataSourceMetadataService
);
if (DRUID_COORDINATOR_METADATA.isOn()) {
DataSourceMetadataLoadTask dataSourceMetadataLoader = buildDataSourceMetadataLoader(
metadataDruidWebService,
loader.getPhysicalTableDictionary(),
dataSourceMetadataService,
getMappers().getMetadataMapper()
);
setupDataSourceMetaData(healthCheckRegistry, dataSourceMetadataLoader);
}
if (DRUID_LOOKUP_METADATA.isOn()) {
setupLookUpMetadataLoader(
healthCheckRegistry,
buildLookupMetaDataLoader(metadataDruidWebService, loader.getDimensionDictionary())
);
}
bind(querySigningService).to(QuerySigningService.class);
bind(buildQuerySignedCacheService(buildLocalSignatureCache(), querySigningService, getMapper()))
.to(CacheService.class);
bind(buildJobRowBuilder()).to(JobRowBuilder.class);
bind(buildPreResponseStore(loader.getDictionaries())).to(PreResponseStore.class);
bind(buildBroadcastChannel()).to(new TypeLiteral<BroadcastChannel<String>>() { });
bind(buildApiJobStore()).to(ApiJobStore.class);
bind(buildJobPayloadBuilder()).to(JobPayloadBuilder.class);
bind(getAsynchronousProcessBuilder()).to(AsynchronousWorkflowsBuilder.class);
bind(getClock()).to(Clock.class);
bind(getHttpResponseMaker()).to(HttpResponseMaker.class);
bind(buildResponseUtils()).to(ResponseUtils.class);
bind(buildResponseWriter(getMappers())).to(ResponseWriter.class);
bind(buildResponseFormatResolver()).to(ResponseFormatResolver.class);
bind(buildResponseProcessorFactory()).to(ResponseProcessorFactory.class);
bind(buildRateLimiter()).to(RateLimiter.class);
bind(getDataExceptionHandler()).to(DataExceptionHandler.class);
bindExceptionHandlers(this);
bind(buildDateTimeFormatter()).to(DateTimeFormatter.class);
bind(buildApiFilterParser()).to(ApiFilterParser.class);
if (DRUID_DIMENSIONS_LOADER.isOn()) {
DimensionValueLoadTask dimensionLoader = buildDruidDimensionsLoader(
druidWebService,
loader.getPhysicalTableDictionary(),
loader.getDimensionDictionary()
);
setupDruidDimensionsLoader(healthCheckRegistry, dimensionLoader);
}
if (SYSTEM_CONFIG.getBooleanProperty(DEPRECATED_PERMISSIVE_AVAILABILITY_FLAG, false)) {
LOG.warn(
"Permissive column availability feature flag is no longer supported, please use " +
"PermissivePhysicalTable to enable permissive column availability."
);
}
// Call post-binding hook to allow for additional binding
afterBinding(this);
}
};
}
/**
* Bind the components necessary to support protocol metrics.
*
* This method binds both the total ProtocolLogicalMetricGenerator and the arguments needed to create one
* in case users want to do their own implementation. The ProtocolLogicalMetricGenerator is on the
* BardConfigResources interface to support constructor level injection, but the DataApiRequestFactory takes its
* own injection and therefore can use the component fields as well.
*
* @param binder The binder to bind the generator to.
*/
protected void bindMetricGenerator(AbstractBinder binder) {
List<String> protocols = Collections.emptyList();
TypeLiteral<List<String>> stringListLiteral = new TypeLiteral<List<String>>() { };
// If you want to configure your system metrics, change the list of metrics
binder.bind(protocols).named(NAME_ACTIVE_PROTOCOLS).to(stringListLiteral);
// If you want to make your own business logic, you can change the Annotater implementation
binder.bind(ApiMetricAnnotater.NO_OP_ANNOTATER).to(ApiMetricAnnotater.class);
// This is the default binder used in ProtocolDataApiRequestImp
ProtocolLogicalMetricGenerator protocolLogicalMetricGenerator = new ProtocolLogicalMetricGenerator(
ApiMetricAnnotater.NO_OP_ANNOTATER,
protocols
);
// The binder used for factories
TypeLiteral<Generator<LinkedHashSet<LogicalMetric>>> metricGeneratorType =
new TypeLiteral<Generator<LinkedHashSet<LogicalMetric>>>() { };
binder.bind(protocolLogicalMetricGenerator).named(NAME_METRIC_GENERATOR).to(metricGeneratorType);
// The binding used for construction based ApiRequest objects
binder.bind(protocolLogicalMetricGenerator).to(ApiRequestLogicalMetricBinder.class);
TypeLiteral<LegacyGenerator<List<OrderByColumn>>> orderByGeneratorType =
new TypeLiteral<LegacyGenerator<List<OrderByColumn>>>() { };
binder.bind(DefaultOrderByGenerator.class)
.named(DataApiRequest.ORDER_BY_GENERATOR_NAMESPACE)
.to(orderByGeneratorType);
}
/**
* Binds all the resource dictionaries.
*
* @param binder The binder to bind the dictionaries to.
*/
private void bindDictionaries(AbstractBinder binder) {
// Bind the configuration dictionaries
binder.bind(loader.getDimensionDictionary()).to(DimensionDictionary.class);
binder.bind(loader.getMetricDictionary()).to(MetricDictionary.class);
binder.bind(loader.getLogicalTableDictionary()).to(LogicalTableDictionary.class);
binder.bind(loader.getPhysicalTableDictionary()).to(PhysicalTableDictionary.class);
binder.bind(loader.getDictionaries()).to(ResourceDictionaries.class);
}
/**
* Binds all the exception handlers to the specified binder.
*
* @param binder The binder to bind the exception handlers to
*/
protected void bindExceptionHandlers(AbstractBinder binder) {
binder.bind(getDimensionExceptionHandler())
.named(DimensionsApiRequest.EXCEPTION_HANDLER_NAMESPACE)
.to(MetadataExceptionHandler.class);
binder.bind(getMetricsExceptionHandler())
.named(MetricsApiRequest.EXCEPTION_HANDLER_NAMESPACE)
.to(MetadataExceptionHandler.class);
binder.bind(getTablesExceptionHandler())
.named(TablesApiRequest.EXCEPTION_HANDLER_NAMESPACE)
.to(MetadataExceptionHandler.class);
binder.bind(getSlicesExceptionHandler())
.named(SlicesApiRequest.EXCEPTION_HANDLER_NAMESPACE)
.to(MetadataExceptionHandler.class);
binder.bind(getJobsExceptionHandler())
.named(JobsApiRequest.EXCEPTION_HANDLER_NAMESPACE)
.to(MetadataExceptionHandler.class);
}
protected Class<? extends MetadataExceptionHandler> getDimensionExceptionHandler() {
return FiliDimensionExceptionHandler.class;
}
protected Class<? extends MetadataExceptionHandler> getMetricsExceptionHandler() {
return FiliMetricExceptionHandler.class;
}
protected Class<? extends MetadataExceptionHandler> getSlicesExceptionHandler() {
return FiliSlicesExceptionHandler.class;
}
protected Class<? extends MetadataExceptionHandler> getTablesExceptionHandler() {
return FiliTablesExceptionHandler.class;
}
protected Class<? extends MetadataExceptionHandler> getJobsExceptionHandler() {
return FiliJobsExceptionHandler.class;
}
protected Class<? extends DataExceptionHandler> getDataExceptionHandler() {
return FiliDataExceptionHandler.class;
}
/**
* Bind ApiRequest instances to resource scope names.
*
* @param binder The binder being used to bind the request mappers.
*/
@SuppressWarnings("rawtypes")
private void bindRequestMappers(AbstractBinder binder) {
Map<String, RequestMapper<?>> requestMappers = getRequestMappers(loader.getDictionaries());
binder.bind(requestMappers.getOrDefault(
DimensionsApiRequest.REQUEST_MAPPER_NAMESPACE,
new DimensionApiRequestMapper(loader.getDictionaries())
)).named(DimensionsApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
binder.bind(requestMappers.getOrDefault(
MetricsApiRequest.REQUEST_MAPPER_NAMESPACE,
new NoOpRequestMapper(loader.getDictionaries())
)).named(MetricsApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
binder.bind(requestMappers.getOrDefault(
SlicesApiRequest.REQUEST_MAPPER_NAMESPACE,
new NoOpRequestMapper(loader.getDictionaries())
)).named(SlicesApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
binder.bind(requestMappers.getOrDefault(
TablesApiRequest.REQUEST_MAPPER_NAMESPACE,
new NoOpRequestMapper(loader.getDictionaries())
)).named(TablesApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
binder.bind(requestMappers.getOrDefault(
DataApiRequest.REQUEST_MAPPER_NAMESPACE,
new NoOpRequestMapper(loader.getDictionaries())
)).named(DataApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
binder.bind(requestMappers.getOrDefault(
JobsApiRequest.REQUEST_MAPPER_NAMESPACE,
new NoOpRequestMapper(loader.getDictionaries())
)).named(JobsApiRequest.REQUEST_MAPPER_NAMESPACE).to(RequestMapper.class);
}
/**
* Initializes the factory that builds druid queries.
*
* @return An isntance of the {@link DruidQueryBuilder}
*/
protected Class<? extends DruidQueryBuilder> buildDruidQueryBuilder() {
return DruidQueryBuilder.class;
}
/**
* Initializes the class that parses responses from Druid.
*
* @return An instance of the {@link DruidResponseParser}
*/
protected Class<? extends DruidResponseParser> buildDruidResponseParser() {
return DruidResponseParser.class;
}
/**
* Returns a clock for generating instants for timestamps.
*
* @return The clock with which to generate instants for timestamps, by default uses the system clock with the
* system timezone
*/
protected Clock getClock() {
return Clock.system(
ZoneId.of(SYSTEM_CONFIG.getStringProperty(
SYSTEM_CONFIG.getPackageVariableName(SYSTEM_CONFIG_TIMEZONE_KEY),
"UTC"
))
);
}
/**
* Initializes the factory that builds the asynchronous PreResponse processing workflow.
*
* @return An instance of the {@link DefaultAsynchronousWorkflowsBuilder}
*/
protected Class<? extends AsynchronousWorkflowsBuilder> getAsynchronousProcessBuilder() {
return DefaultAsynchronousWorkflowsBuilder.class;
}
/**
* Initializes the service for building JobRows based on the information in a query.
*
* @return A factory for building JobRows, by default the factory builds a JobRow containing the fields
* enumerated in {@link DefaultJobField}, using ids that are the concatenation of the user id with a uuid generated
* by {@link UUID#randomUUID()}.
*/
protected JobRowBuilder buildJobRowBuilder() {
return new DefaultJobRowBuilder(
jobMetadata -> jobMetadata.get(DefaultJobField.USER_ID) + UUID.randomUUID().toString()
);
}
/**
* Builds an instance of the interface to the storage system to use to store PreResponses of asynchronous
* requests.
*
* @param resourceDictionaries Hold the resource dictionaries
*
* @return An instance of the interface that allows Bard to talk to an arbitrary key-value store system for storing
* PreResponses, by default this returns a {@code NoOpPreResponseStore}, which does nothing
*/
protected PreResponseStore buildPreResponseStore(ResourceDictionaries resourceDictionaries) {
return new NoOpPreResponseStore();
}
/**
* Builds an instance of the interface to the storage system to use to store metadata about asynchronous
* requests.
*
* @return An instance of the interface that allows Bard to talk to an arbitrary key-value store system for storing
* job metadata, by default this returns a {@code NoOpApiJobStore}, which does nothing
*/
protected ApiJobStore buildApiJobStore() {
return new NoOpApiJobStore();
}
/**
* Builds an instance of a BroadcastChannel that broadcasts the tickets of asynchronous jobs that have been
* successfully stored in the PreResponseStore .
*
* @return A BroadcastChannel that allows Bard to talk to other Bard processes, by default returns the
* {@link SimpleBroadcastChannel}, which uses a {@link PublishSubject} to allow cross-thread communication
*/
protected BroadcastChannel<String> buildBroadcastChannel() {
return new SimpleBroadcastChannel<>(PublishSubject.create());
}
/**
* Initialize the PreResponse deserializer to deserialize the custom serialized PreResponse.
*
* @param dimensionDictionary Contains all the dimension details
* @param nonResponseContextMapper ObjectMapper instance without any customization
* @param responseContextMapper ObjectMapper instance with customization to store/retrieve the value type
* @param granularityParser Granularity parser to get the time id
*
* @return instance of PreResponse deserializer
*/
protected PreResponseDeserializer initializePreResponseDeserializer(
DimensionDictionary dimensionDictionary,
ObjectMapper nonResponseContextMapper,
ObjectMapper responseContextMapper,
GranularityParser granularityParser
) {
return new PreResponseDeserializer(
dimensionDictionary,
nonResponseContextMapper,
responseContextMapper,
granularityParser
);
}
/**
* Initialize the service that decides which intervals in a request are volatile relative to a physical table.
* By default, returns a `VolatileIntervalsService` that assumes none of the physical tables have any volatile
* intervals.
*
* @return A service for determining which intervals in a request are volatile relative to a physical table
*/
protected VolatileIntervalsService getVolatileIntervalsService() {
return new DefaultingVolatileIntervalsService();
}
/**
* Initialize the field converter.
* By default it is SketchFieldConverter
*
* @return An instance of SketchFieldConverter
*/
protected FieldConverters initializeSketchConverter() {
return new ThetaSketchFieldConverter();
}
/**
* Initialize the MetricsFilterSetBuilder. By default it is MetricsFilterSetBuilder
*
* @return An instance of MetricsFilterSetBuilder
*/
protected MetricsFilterSetBuilder initializeMetricsFilterSetBuilder() {
return new FilteredThetaSketchMetricsHelper(buildDruidFilterBuilder());
}
/**
* Build an ObjectMappersSuite for everyone to use, since they are heavy-weight.
*
* @return The instance of ObjectMappersSuite
*/
protected final ObjectMappersSuite getMappers() {
if (objectMappers == null) {
objectMappers = new ObjectMappersSuite();
}
return objectMappers;
}
/**
* Return the instance of ObjectMapper defined in the current ObjectMappersSuite.
*
* @return The instance of ObjectMapper
*/
protected final ObjectMapper getMapper() {
return getMappers().getMapper();
}
/**
* Register required core health checks.
*
* @param healthCheckRegistry The health check registry
* @param dimensionDictionary The container with all dimensions
*/
protected final void setupHealthChecks(
HealthCheckRegistry healthCheckRegistry,
DimensionDictionary dimensionDictionary
) {
// Health checks are registered here since they should be configured at startup.
HealthCheck allDimsLoaded = new AllDimensionsLoadedHealthCheck(dimensionDictionary);
healthCheckRegistry.register(HEALTH_CHECK_NAME_DIMENSION, allDimsLoaded);
healthCheckRegistry.register(HEALTH_CHECK_VERSION, new VersionHealthCheck());
}
/**
* Register global gauges.
*/
protected final void setupGauges() {
// Gauges are registered here since they should be configured only once at startup.
MetricRegistry metricRegistry = MetricRegistryFactory.getRegistry();
Map<String, Metric> metrics = metricRegistry.getMetrics();
if (!metrics.containsKey(METER_CACHE_HIT_RATIO)) {
metricRegistry.register(
METER_CACHE_HIT_RATIO,
new RatioGauge() {
@Override
protected Ratio getRatio() {
return CACHE_REQUESTS.getCount() != 0
? Ratio.of(CACHE_HITS.getCount(), CACHE_REQUESTS.getCount())
: Ratio.of(0, 1);
}
}
);
}
if (!metrics.containsKey(METER_SPLITS_TOTAL_RATIO)) {
metricRegistry.register(
METER_SPLITS_TOTAL_RATIO,
new RatioGauge() {
@Override
protected Ratio getRatio() {
return QUERY_REQUEST_TOTAL.getCount() != 0
? Ratio.of(SPLIT_QUERIES.getCount(), QUERY_REQUEST_TOTAL.getCount())
: Ratio.of(0, 1);
}
}
);
}
if (!metrics.containsKey(METER_SPLITS_RATIO)) {
metricRegistry.register(
METER_SPLITS_RATIO,
new RatioGauge() {
@Override
protected Ratio getRatio() {
return SPLITS.getCount() != 0
? Ratio.of(SPLIT_QUERIES.getCount(), SPLITS.getCount())
: Ratio.of(0, 1);
}
}
);
}
if (!metrics.containsKey(JVM_UPTIME)) {
metricRegistry.register(
JVM_UPTIME,
(Gauge<Long>) () -> ManagementFactory.getRuntimeMXBean().getUptime()
);
}
}
/**
* Creates an object that constructs Druid dimension filters from Bard dimension filters.
* <p>
* Constructs a {@link DruidInFilterBuilder} by default.
*
* @return An object to build Druid filters from API filters
*/
protected DruidFilterBuilder buildDruidFilterBuilder() {
if (BardFeatureFlag.DEFAULT_IN_FILTER.isOn()) {
return new DruidInFilterBuilder();
} else {
return new DruidOrFilterBuilder();
}
}
/**
* Creates an object that constructs Druid dimension filters from Bard dimension filters.
* <p>
* Constructs a {@link DruidInFilterBuilder} by default.
*
* @return An object to build Druid filters from API filters
*/
protected DruidHavingBuilder buildDruidHavingBuilder() {
return new DefaultDruidHavingBuilder();
}
/**
* Creates an factory that constructs DataApiRequests
* .
* Constructs a {@link DefaultDataApiRequestFactory} by default.
*
* @return An object to build Druid filters from API filters
*/
protected DataApiRequestFactory buildDataApiRequestFactory() {
return new DefaultDataApiRequestFactory();
}
/**
* Creates an object that generates map of Api Having from having string.
* Constructs a {@link DefaultHavingApiGenerator} by default.
* @param loader Configuration loader that connects resource dictionaries with the loader.
*
* @return An object to generate having maps from having string.
*/
protected HavingGenerator buildHavingGenerator(ConfigurationLoader loader) {
return new PerRequestDictionaryHavingGenerator(new DefaultHavingApiGenerator(loader.getMetricDictionary()));
}
/**
* Get the stored metadata service, if not exist yet, create the service and store it.
*
* @return A datasource metadata service
*/
protected DataSourceMetadataService getDataSourceMetadataService() {
if (Objects.isNull(dataSourceMetadataService)) {
dataSourceMetadataService = new DataSourceMetadataService();
}
return dataSourceMetadataService;
}
/**
* Build a QuerySigningService.
*
* @param physicalTableDictionary the dictionary of physical tables
* @param dataSourceMetadataService A datasource metadata service
*
* @return A QuerySigningService
*/
protected QuerySigningService<?> buildQuerySigningService(
PhysicalTableDictionary physicalTableDictionary,
DataSourceMetadataService dataSourceMetadataService
) {
return new SegmentIntervalsHashIdGenerator(dataSourceMetadataService, buildSigningFunctions());
}
/**
* Build a QuerySignedCacheService.
*
* @param dataCache The cache instance
* @param querySigningService The service to generate query signatures
* @param objectMapper A JSON object mapper, used to parse JSON response
*
* @return A QuerySignedCacheService
*/
@SuppressWarnings("unchecked")
protected QuerySignedCacheService buildQuerySignedCacheService(
DataCache<?> dataCache,
QuerySigningService<?> querySigningService,
ObjectMapper objectMapper
) throws ClassCastException {
return new QuerySignedCacheService(
(TupleDataCache<String, Long, String>) dataCache,
(QuerySigningService<Long>) querySigningService,
objectMapper
);
}
/**
* Build a Map of Class to Function that should be used to get requestedIntervals from the DruidQuery.
*
* @return A Map that maps Class to a function that computes the requested intervals for a Druid query of
* that particular Class
*/
protected Map<Class<?>, RequestedIntervalsFunction> buildSigningFunctions() {
DefaultingDictionary<Class<?>, RequestedIntervalsFunction> signingFunctions = new DefaultingDictionary<>(
druidAggregationQuery -> new SimplifiedIntervalList(druidAggregationQuery.getIntervals())
);
signingFunctions.put(LookbackQuery.class, new LookbackQuery.LookbackQueryRequestedIntervalsFunction());
return signingFunctions;
}
/**
* Build a datasource metadata loader.
*
* @param webService The web service used by the loader to query druid for segments availability.
* @param physicalTableDictionary The table to get the dimensions from.
* @param metadataService The service to be used to store the datasource metadata.
* @param mapper The object mapper to process the metadata json.
*
* @return A datasource metadata loader.
*/
protected DataSourceMetadataLoadTask buildDataSourceMetadataLoader(
DruidWebService webService,
PhysicalTableDictionary physicalTableDictionary,
DataSourceMetadataService metadataService,
ObjectMapper mapper
) {
return new DataSourceMetadataLoadTask(
physicalTableDictionary,
metadataService,
webService,
mapper
);
}
/**
* Builds a lookup metadata loader.
*
* @param webService The web service used by the loader to query druid for lookup statuses.
* @param dimensionDictionary A {@link com.yahoo.bard.webservice.data.dimension.DimensionDictionary} that is used
* to obtain a list of lookups in Fili.
*
* @return a lookup metadata loader
*/
protected RegisteredLookupMetadataLoadTask buildLookupMetaDataLoader(
DruidWebService webService,
DimensionDictionary dimensionDictionary
) {
return new RegisteredLookupMetadataLoadTask(webService, dimensionDictionary);
}
/**
* Build a DimensionValueLoadTask.
*
* @param webService The web service used by the loader to query dimension values
* @param physicalTableDictionary The table to update dimensions on
* @param dimensionDictionary The dimensions to update
*
* @return A DimensionValueLoadTask
*/
protected DimensionValueLoadTask buildDruidDimensionsLoader(
DruidWebService webService,
PhysicalTableDictionary physicalTableDictionary,
DimensionDictionary dimensionDictionary
) {
DruidDimensionValueLoader druidDimensionRowProvider = new DruidDimensionValueLoader(
physicalTableDictionary,
dimensionDictionary,
webService
);
return new DimensionValueLoadTask(Collections.singletonList(druidDimensionRowProvider));
}
/**
* Schedule a datasource metadata loader and register its health check.
*
* @param healthCheckRegistry The health check registry to register partial data health checks.
* @param dataSourceMetadataLoader The datasource metadata loader to use.
*/
protected final void setupDataSourceMetaData(
HealthCheckRegistry healthCheckRegistry,
DataSourceMetadataLoadTask dataSourceMetadataLoader
) {
scheduleLoader(dataSourceMetadataLoader);
// Register Segment metadata loader health check
HealthCheck dataSourceMetadataLoaderHealthCheck = new DataSourceMetadataLoaderHealthCheck(
dataSourceMetadataLoader,
SEG_LOADER_HC_LAST_RUN_PERIOD_MILLIS
);
healthCheckRegistry.register(HEALTH_CHECK_NAME_DATASOURCE_METADATA, dataSourceMetadataLoaderHealthCheck);
}
/**
* Schedule a lookup metadata loader and register its health check.
*