io.druid.server.lookup.namespace.cache.NamespaceExtractionCacheManager Maven / Gradle / Ivy
/*
* 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.server.lookup.namespace.cache;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.metamx.common.IAE;
import com.metamx.common.ISE;
import com.metamx.common.concurrent.ExecutorServices;
import com.metamx.common.lifecycle.Lifecycle;
import com.metamx.common.logger.Logger;
import com.metamx.emitter.service.ServiceEmitter;
import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.query.lookup.namespace.ExtractionNamespace;
import io.druid.query.lookup.namespace.ExtractionNamespaceCacheFactory;
import javax.annotation.concurrent.GuardedBy;
import java.util.Collection;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
/**
*
*/
public abstract class NamespaceExtractionCacheManager
{
protected static class NamespaceImplData
{
public NamespaceImplData(
final ListenableFuture> future,
final ExtractionNamespace namespace,
final String name
)
{
this.future = future;
this.namespace = namespace;
this.name = name;
}
final ListenableFuture> future;
final ExtractionNamespace namespace;
final String name;
final Object changeLock = new Object();
final AtomicBoolean enabled = new AtomicBoolean(false);
final CountDownLatch firstRun = new CountDownLatch(1);
volatile String latestVersion = null;
}
private static final Logger log = new Logger(NamespaceExtractionCacheManager.class);
private final ListeningScheduledExecutorService listeningScheduledExecutorService;
protected final ConcurrentMap implData = new ConcurrentHashMap<>();
protected final AtomicLong tasksStarted = new AtomicLong(0);
protected final ServiceEmitter serviceEmitter;
private final Map, ExtractionNamespaceCacheFactory>> namespaceFunctionFactoryMap;
public NamespaceExtractionCacheManager(
Lifecycle lifecycle,
final ServiceEmitter serviceEmitter,
final Map, ExtractionNamespaceCacheFactory>> namespaceFunctionFactoryMap
)
{
this.listeningScheduledExecutorService = MoreExecutors.listeningDecorator(
Executors.newScheduledThreadPool(
1,
new ThreadFactoryBuilder()
.setDaemon(true)
.setNameFormat("NamespaceExtractionCacheManager-%d")
.setPriority(Thread.MIN_PRIORITY)
.build()
)
);
ExecutorServices.manageLifecycle(lifecycle, listeningScheduledExecutorService);
this.serviceEmitter = serviceEmitter;
this.namespaceFunctionFactoryMap = namespaceFunctionFactoryMap;
listeningScheduledExecutorService.scheduleAtFixedRate(
new Runnable()
{
long priorTasksStarted = 0L;
@Override
public void run()
{
try {
final long tasks = tasksStarted.get();
serviceEmitter.emit(
ServiceMetricEvent.builder()
.build("namespace/deltaTasksStarted", tasks - priorTasksStarted)
);
priorTasksStarted = tasks;
monitor(serviceEmitter);
}
catch (Exception e) {
log.error(e, "Error emitting namespace stats");
if (Thread.currentThread().isInterrupted()) {
throw Throwables.propagate(e);
}
}
}
},
1,
10, TimeUnit.MINUTES
);
}
/**
* Optional monitoring for overriding classes. `super.monitor` does *NOT* need to be called by overriding methods
*
* @param serviceEmitter The emitter to emit to
*/
protected void monitor(ServiceEmitter serviceEmitter)
{
// Noop by default
}
protected boolean waitForServiceToEnd(long time, TimeUnit unit) throws InterruptedException
{
return listeningScheduledExecutorService.awaitTermination(time, unit);
}
protected void updateNamespace(final String id, final String cacheId, final String newVersion)
{
final NamespaceImplData namespaceDatum = implData.get(id);
if (namespaceDatum == null) {
// was removed
return;
}
try {
if (!namespaceDatum.enabled.get()) {
// skip because it was disabled
return;
}
synchronized (namespaceDatum.enabled) {
if (!namespaceDatum.enabled.get()) {
return;
}
swapAndClearCache(id, cacheId);
namespaceDatum.latestVersion = newVersion;
}
}
finally {
namespaceDatum.firstRun.countDown();
}
}
// return value means actually delete or not
public boolean checkedDelete(
String namespaceName
)
{
final NamespaceImplData implDatum = implData.get(namespaceName);
if (implDatum == null) {
// Delete but we don't have it?
log.wtf("Asked to delete something I just lost [%s]", namespaceName);
return false;
}
return delete(namespaceName);
}
// return value means actually schedule or not
public boolean scheduleOrUpdate(
final String id,
ExtractionNamespace namespace
)
{
final NamespaceImplData implDatum = implData.get(id);
if (implDatum == null) {
// New, probably
schedule(id, namespace);
return true;
}
if (!implDatum.enabled.get()) {
// Race condition. Someone else disabled it first, go ahead and reschedule
schedule(id, namespace);
return true;
}
// Live one. Check if it needs updated
if (implDatum.namespace.equals(namespace)) {
// skip if no update
return false;
}
if (log.isDebugEnabled()) {
log.debug("Namespace [%s] needs updated to [%s]", implDatum.namespace, namespace);
}
// Ensure it is not changing state right now.
synchronized (implDatum.changeLock) {
removeNamespaceLocalMetadata(implDatum);
}
schedule(id, namespace);
return true;
}
public boolean scheduleAndWait(
final String id,
ExtractionNamespace namespace,
long waitForFirstRun
)
{
if (scheduleOrUpdate(id, namespace)) {
log.debug("Scheduled new namespace [%s]: %s", id, namespace);
} else {
log.debug("Namespace [%s] already running: %s", id, namespace);
}
final NamespaceImplData namespaceImplData = implData.get(id);
if (namespaceImplData == null) {
log.warn("NamespaceLookupExtractorFactory[%s] - deleted during start", id);
return false;
}
boolean success = false;
try {
success = namespaceImplData.firstRun.await(waitForFirstRun, TimeUnit.MILLISECONDS);
}
catch (InterruptedException e) {
log.error(e, "NamespaceLookupExtractorFactory[%s] - interrupted during start", id);
}
if (!success) {
delete(id);
}
return success;
}
@GuardedBy("implDatum.changeLock")
private void cancelFuture(final NamespaceImplData implDatum)
{
final CountDownLatch latch = new CountDownLatch(1);
final ListenableFuture> future = implDatum.future;
Futures.addCallback(
future, new FutureCallback
© 2015 - 2024 Weber Informatics LLC | Privacy Policy