leventov commented on a change in pull request #5556: Materialized view implementation URL: https://github.com/apache/incubator-druid/pull/5556#discussion_r268836038
########## File path: extensions-contrib/materialized-view-selection/src/main/java/io/druid/query/materializedview/DerivativeDataSourceManager.java ########## @@ -0,0 +1,265 @@ +/* + * Licensed to Metamarkets Group Inc. (Metamarkets) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. Metamarkets 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 io.druid.query.materializedview; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.google.common.base.Supplier; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Sets; +import com.google.common.util.concurrent.ListenableFuture; +import com.google.common.util.concurrent.ListeningScheduledExecutorService; +import com.google.common.util.concurrent.MoreExecutors; +import com.google.inject.Inject; +import io.druid.guice.ManageLifecycleLast; +import io.druid.indexing.overlord.DataSourceMetadata; +import io.druid.metadata.MetadataStorageTablesConfig; +import io.druid.metadata.SQLMetadataConnector; +import io.druid.indexing.materializedview.DerivativeDataSourceMetadata; +import io.druid.java.util.common.DateTimes; +import io.druid.java.util.common.Intervals; +import io.druid.java.util.common.Pair; +import io.druid.java.util.common.StringUtils; +import io.druid.java.util.common.concurrent.Execs; +import io.druid.java.util.common.lifecycle.LifecycleStart; +import io.druid.java.util.common.lifecycle.LifecycleStop; +import io.druid.java.util.emitter.EmittingLogger; +import io.druid.timeline.DataSegment; +import org.joda.time.Duration; +import org.joda.time.Interval; +import org.skife.jdbi.v2.Handle; +import org.skife.jdbi.v2.StatementContext; +import org.skife.jdbi.v2.tweak.HandleCallback; +import org.skife.jdbi.v2.tweak.ResultSetMapper; + +import java.io.IOException; +import java.sql.ResultSet; +import java.sql.SQLException; +import java.util.List; +import java.util.Set; +import java.util.SortedSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicReference; +import java.util.stream.Collectors; + +/** + * Read and store derivatives information from dataSource table frequently. + * When optimize query, DerivativesManager offers the information about derivatives. + */ +@ManageLifecycleLast +public class DerivativeDataSourceManager +{ + private static final EmittingLogger log = new EmittingLogger(DerivativeDataSourceManager.class); + private static final AtomicReference<ConcurrentHashMap<String, SortedSet<DerivativeDataSource>>> derivativesRef = + new AtomicReference<>(new ConcurrentHashMap<>()); + private final MaterializedViewConfig config; + private final Supplier<MetadataStorageTablesConfig> dbTables; + private final SQLMetadataConnector connector; + private final ObjectMapper objectMapper; + private final Object lock = new Object(); + + private boolean started = false; + private ListeningScheduledExecutorService exec = null; + private ListenableFuture<?> future = null; + + @Inject + public DerivativeDataSourceManager( + MaterializedViewConfig config, + Supplier<MetadataStorageTablesConfig> dbTables, + ObjectMapper objectMapper, + SQLMetadataConnector connector + ) + { + this.config = config; + this.dbTables = dbTables; + this.objectMapper = objectMapper; + this.connector = connector; + } + + @LifecycleStart + public void start() + { + log.info("starting derivatives manager."); + synchronized (lock) { + if (started) { + return; + } + exec = MoreExecutors.listeningDecorator(Execs.scheduledSingleThreaded("DerivativeDataSourceManager-Exec-%d")); + final Duration delay = config.getPollDuration().toStandardDuration(); + future = exec.scheduleWithFixedDelay( + new Runnable() { + @Override + public void run() + { + try { + updateDerivatives(); + } + catch (Exception e) { + log.makeAlert(e, "uncaught exception in derivatives manager updating thread").emit(); + } + } + }, + 0, + delay.getMillis(), + TimeUnit.MILLISECONDS + ); + started = true; + } + log.info("Derivatives manager started."); + } + + @LifecycleStop + public void stop() + { + synchronized (lock) { + if (!started) { + return; + } + started = false; + future.cancel(true); + future = null; + derivativesRef.set(new ConcurrentHashMap<>()); + exec.shutdownNow(); + exec = null; + } + } + + public static ImmutableSet<DerivativeDataSource> getDerivatives(String datasource) + { + return ImmutableSet.copyOf(derivativesRef.get().getOrDefault(datasource, Sets.newTreeSet())); + } + + public static ImmutableMap<String, Set<DerivativeDataSource>> getAllDerivatives() + { + return ImmutableMap.copyOf(derivativesRef.get()); + } + + private void updateDerivatives() + { + List<Pair<String, DerivativeDataSourceMetadata>> derivativesInDatabase = connector.retryWithHandle( + handle -> + handle.createQuery( + StringUtils.format("SELECT DISTINCT dataSource,commit_metadata_payload FROM %1$s", dbTables.get().getDataSourceTable()) + ) + .map(new ResultSetMapper<Pair<String, DerivativeDataSourceMetadata>>() + { + @Override + public Pair<String, DerivativeDataSourceMetadata> map(int index, ResultSet r, StatementContext ctx) throws SQLException + { + String datasourceName = r.getString("dataSource"); + try { + DataSourceMetadata payload = objectMapper.readValue( + r.getBytes("commit_metadata_payload"), + DataSourceMetadata.class); + if (!(payload instanceof DerivativeDataSourceMetadata)) { + return null; + } + DerivativeDataSourceMetadata metadata = (DerivativeDataSourceMetadata) payload; + return new Pair<>(datasourceName, metadata); + } + catch (IOException e) { + throw new RuntimeException(e); + } + } + }) + .list() + ); + + List<DerivativeDataSource> derivativeDataSources = derivativesInDatabase.parallelStream() Review comment: And here ---------------------------------------------------------------- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. For queries about this service, please contact Infrastructure at: [email protected] With regards, Apache Git Services --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
