You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@druid.apache.org by GitBox <gi...@apache.org> on 2018/08/10 02:29:31 UTC
[GitHub] jon-wei closed pull request #6147: [Backport] New quickstart and
tutorials
jon-wei closed pull request #6147: [Backport] New quickstart and tutorials
URL: https://github.com/apache/incubator-druid/pull/6147
This is a PR merged from a forked repository.
As GitHub hides the original diff on merge, it is displayed below for
the sake of provenance:
As this is a foreign pull request (from a fork), the diff is supplied
below (as it won't show otherwise due to GitHub magic):
diff --git a/api/pom.xml b/api/pom.xml
index d4bcddd4370..40ba14d0337 100644
--- a/api/pom.xml
+++ b/api/pom.xml
@@ -28,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/api/src/main/java/io/druid/guice/JsonConfigurator.java b/api/src/main/java/io/druid/guice/JsonConfigurator.java
index f6d766dd955..09721a932d5 100644
--- a/api/src/main/java/io/druid/guice/JsonConfigurator.java
+++ b/api/src/main/java/io/druid/guice/JsonConfigurator.java
@@ -93,7 +93,6 @@ public JsonConfigurator(
log.info(e, "Unable to parse [%s]=[%s] as a json object, using as is.", prop, propValue);
value = propValue;
}
-
hieraricalPutValue(propertyPrefix, prop, prop.substring(propertyBase.length()), value, jsonMap);
}
}
@@ -175,8 +174,11 @@ private static void hieraricalPutValue(
)
{
int dotIndex = property.indexOf('.');
+ // Always put property with name even if it is of form a.b. This will make sure the property is available for classes
+ // where JsonProperty names are of the form a.b
+ // Note:- this will cause more than required properties to be present in the jsonMap.
+ targetMap.put(property, value);
if (dotIndex < 0) {
- targetMap.put(property, value);
return;
}
if (dotIndex == 0) {
diff --git a/api/src/main/java/io/druid/indexer/TaskStatusPlus.java b/api/src/main/java/io/druid/indexer/TaskStatusPlus.java
index a45a9a7865a..0560206f213 100644
--- a/api/src/main/java/io/druid/indexer/TaskStatusPlus.java
+++ b/api/src/main/java/io/druid/indexer/TaskStatusPlus.java
@@ -25,6 +25,7 @@
import org.joda.time.DateTime;
import javax.annotation.Nullable;
+import java.util.Objects;
public class TaskStatusPlus
{
@@ -40,7 +41,7 @@ public TaskStatusPlus(
@JsonProperty("id") String id,
@JsonProperty("createdTime") DateTime createdTime,
@JsonProperty("queueInsertionTime") DateTime queueInsertionTime,
- @JsonProperty("state") @Nullable TaskState state,
+ @JsonProperty("statusCode") @Nullable TaskState state,
@JsonProperty("duration") @Nullable Long duration,
@JsonProperty("location") TaskLocation location
)
@@ -74,7 +75,8 @@ public DateTime getQueueInsertionTime()
return queueInsertionTime;
}
- @JsonProperty
+ @Nullable
+ @JsonProperty("statusCode")
public TaskState getState()
{
return state;
@@ -91,4 +93,40 @@ public TaskLocation getLocation()
{
return location;
}
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) {
+ return true;
+ }
+
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+
+ final TaskStatusPlus that = (TaskStatusPlus) o;
+ if (!id.equals(that.id)) {
+ return false;
+ }
+ if (!createdTime.equals(that.createdTime)) {
+ return false;
+ }
+ if (!queueInsertionTime.equals(that.queueInsertionTime)) {
+ return false;
+ }
+ if (!Objects.equals(state, that.state)) {
+ return false;
+ }
+ if (!Objects.equals(duration, that.duration)) {
+ return false;
+ }
+ return location.equals(that.location);
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return Objects.hash(id, createdTime, queueInsertionTime, state, duration, location);
+ }
}
diff --git a/api/src/main/java/io/druid/segment/loading/DataSegmentFinder.java b/api/src/main/java/io/druid/segment/loading/DataSegmentFinder.java
index 937a42e72c2..66af8353daf 100644
--- a/api/src/main/java/io/druid/segment/loading/DataSegmentFinder.java
+++ b/api/src/main/java/io/druid/segment/loading/DataSegmentFinder.java
@@ -20,8 +20,11 @@
package io.druid.segment.loading;
import io.druid.guice.annotations.ExtensionPoint;
+import io.druid.java.util.common.Pair;
+import io.druid.java.util.common.logger.Logger;
import io.druid.timeline.DataSegment;
+import java.util.Map;
import java.util.Set;
/**
@@ -31,6 +34,8 @@
@ExtensionPoint
public interface DataSegmentFinder
{
+ Logger log = new Logger(DataSegmentFinder.class);
+
/**
* This method should first recursively look for descriptor.json (partitionNum_descriptor.json for HDFS data storage) underneath
* workingDirPath and then verify that index.zip (partitionNum_index.zip for HDFS data storage) exists in the same folder.
@@ -46,4 +51,26 @@
* @return a set of segments that were found underneath workingDirPath
*/
Set<DataSegment> findSegments(String workingDirPath, boolean updateDescriptor) throws SegmentLoadingException;
+
+ /**
+ * Adds dataSegment if it does not exist in timestampedSegments. If it exists, replaces entry if segmentModifiedAt is
+ * newer than stored timestamp.
+ *
+ * @param timestampedSegments map of <segmentID, Pair<segment, modifiedAt>> containing segments with modified time
+ * @param dataSegment segment to add
+ * @param segmentModifiedAt segment modified timestamp
+ */
+ static void putInMapRetainingNewest(
+ Map<String, Pair<DataSegment, Long>> timestampedSegments, DataSegment dataSegment, long segmentModifiedAt
+ )
+ {
+ timestampedSegments.merge(
+ dataSegment.getIdentifier(),
+ Pair.of(dataSegment, segmentModifiedAt),
+ (previous, current) -> {
+ log.warn("Multiple copies of segmentId [%s] found, using newest version", current.lhs.getIdentifier());
+ return previous.rhs > current.rhs ? previous : current;
+ }
+ );
+ }
}
diff --git a/api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java b/api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java
index c26a73daeb1..96bbeb9362d 100644
--- a/api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java
+++ b/api/src/main/java/io/druid/segment/loading/DataSegmentKiller.java
@@ -20,16 +20,41 @@
package io.druid.segment.loading;
import io.druid.guice.annotations.ExtensionPoint;
+import io.druid.java.util.common.logger.Logger;
import io.druid.timeline.DataSegment;
import java.io.IOException;
-/**
- */
@ExtensionPoint
public interface DataSegmentKiller
{
- void kill(DataSegment segments) throws SegmentLoadingException;
- void killAll() throws IOException;
+ Logger log = new Logger(DataSegmentKiller.class);
+
+ /**
+ * Removes segment files (index and metadata) from deep storage.
+ * @param segment the segment to kill
+ * @throws SegmentLoadingException if the segment could not be completely removed
+ */
+ void kill(DataSegment segment) throws SegmentLoadingException;
+ /**
+ * A more stoic killer who doesn't throw a tantrum if things get messy. Use when killing segments for best-effort
+ * cleanup.
+ * @param segment the segment to kill
+ */
+ default void killQuietly(DataSegment segment)
+ {
+ try {
+ kill(segment);
+ }
+ catch (Exception e) {
+ log.debug(e, "Failed to kill segment %s", segment);
+ }
+ }
+
+ /**
+ * Like a nuke. Use wisely. Used by the 'reset-cluster' command, and of the built-in deep storage implementations, it
+ * is only implemented by local and HDFS.
+ */
+ void killAll() throws IOException;
}
diff --git a/api/src/main/java/io/druid/segment/loading/DataSegmentPusher.java b/api/src/main/java/io/druid/segment/loading/DataSegmentPusher.java
index b9bf810f72c..7c4cead40cb 100644
--- a/api/src/main/java/io/druid/segment/loading/DataSegmentPusher.java
+++ b/api/src/main/java/io/druid/segment/loading/DataSegmentPusher.java
@@ -30,6 +30,7 @@
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.UUID;
@ExtensionPoint
public interface DataSegmentPusher
@@ -39,18 +40,53 @@
@Deprecated
String getPathForHadoop(String dataSource);
String getPathForHadoop();
- DataSegment push(File file, DataSegment segment) throws IOException;
+
+ /**
+ * Pushes index files and segment descriptor to deep storage.
+ * @param file directory containing index files
+ * @param segment segment descriptor
+ * @param useUniquePath if true, pushes to a unique file path. This prevents situations where task failures or replica
+ * tasks can either overwrite or fail to overwrite existing segments leading to the possibility
+ * of different versions of the same segment ID containing different data. As an example, a Kafka
+ * indexing task starting at offset A and ending at offset B may push a segment to deep storage
+ * and then fail before writing the loadSpec to the metadata table, resulting in a replacement
+ * task being spawned. This replacement will also start at offset A but will read to offset C and
+ * will then push a segment to deep storage and write the loadSpec metadata. Without unique file
+ * paths, this can only work correctly if new segments overwrite existing segments. Suppose that
+ * at this point the task then fails so that the supervisor retries again from offset A. This 3rd
+ * attempt will overwrite the segments in deep storage before failing to write the loadSpec
+ * metadata, resulting in inconsistencies in the segment data now in deep storage and copies of
+ * the segment already loaded by historicals.
+ *
+ * If unique paths are used, caller is responsible for cleaning up segments that were pushed but
+ * were not written to the metadata table (for example when using replica tasks).
+ * @return segment descriptor
+ * @throws IOException
+ */
+ DataSegment push(File file, DataSegment segment, boolean useUniquePath) throws IOException;
+
//use map instead of LoadSpec class to avoid dependency pollution.
Map<String, Object> makeLoadSpec(URI finalIndexZipFilePath);
+ /**
+ * @deprecated backward-compatibiliy shim that should be removed on next major release;
+ * use {@link #getStorageDir(DataSegment, boolean)} instead.
+ */
+ @Deprecated
default String getStorageDir(DataSegment dataSegment)
{
- return getDefaultStorageDir(dataSegment);
+ return getStorageDir(dataSegment, false);
+ }
+
+ default String getStorageDir(DataSegment dataSegment, boolean useUniquePath)
+ {
+ return getDefaultStorageDir(dataSegment, useUniquePath);
}
default String makeIndexPathName(DataSegment dataSegment, String indexName)
{
- return StringUtils.format("./%s/%s", getStorageDir(dataSegment), indexName);
+ // This is only called from Hadoop batch which doesn't require unique segment paths so set useUniquePath=false
+ return StringUtils.format("./%s/%s", getStorageDir(dataSegment, false), indexName);
}
/**
@@ -66,13 +102,19 @@ default String makeIndexPathName(DataSegment dataSegment, String indexName)
// If above format is ever changed, make sure to change it appropriately in other places
// e.g. HDFSDataSegmentKiller uses this information to clean the version, interval and dataSource directories
// on segment deletion if segment being deleted was the only segment
- static String getDefaultStorageDir(DataSegment segment)
+ static String getDefaultStorageDir(DataSegment segment, boolean useUniquePath)
{
return JOINER.join(
segment.getDataSource(),
StringUtils.format("%s_%s", segment.getInterval().getStart(), segment.getInterval().getEnd()),
segment.getVersion(),
- segment.getShardSpec().getPartitionNum()
+ segment.getShardSpec().getPartitionNum(),
+ useUniquePath ? generateUniquePath() : null
);
}
+
+ static String generateUniquePath()
+ {
+ return UUID.randomUUID().toString();
+ }
}
diff --git a/api/src/main/java/io/druid/utils/CompressionUtils.java b/api/src/main/java/io/druid/utils/CompressionUtils.java
index 6a551e319e0..2b25186b25f 100644
--- a/api/src/main/java/io/druid/utils/CompressionUtils.java
+++ b/api/src/main/java/io/druid/utils/CompressionUtils.java
@@ -36,26 +36,26 @@
private static final Logger log = new Logger(CompressionUtils.class);
- @Deprecated // Use com.metamx.common.CompressionUtils.zip
+ @Deprecated // Use io.druid.java.util.common.CompressionUtils.zip
public static long zip(File directory, File outputZipFile) throws IOException
{
return io.druid.java.util.common.CompressionUtils.zip(directory, outputZipFile);
}
- @Deprecated // Use com.metamx.common.CompressionUtils.zip
+ @Deprecated // Use io.druid.java.util.common.CompressionUtils.zip
public static long zip(File directory, OutputStream out) throws IOException
{
return io.druid.java.util.common.CompressionUtils.zip(directory, out);
}
- @Deprecated // Use com.metamx.common.CompressionUtils.unzip
+ @Deprecated // Use io.druid.java.util.common.CompressionUtils.unzip
public static void unzip(File pulledFile, File outDir) throws IOException
{
io.druid.java.util.common.CompressionUtils.unzip(pulledFile, outDir);
}
- @Deprecated // Use com.metamx.common.CompressionUtils.unzip
+ @Deprecated // Use io.druid.java.util.common.CompressionUtils.unzip
public static void unzip(InputStream in, File outDir) throws IOException
{
io.druid.java.util.common.CompressionUtils.unzip(in, outDir);
@@ -63,8 +63,8 @@ public static void unzip(InputStream in, File outDir) throws IOException
/**
* Uncompress using a gzip uncompress algorithm from the `pulledFile` to the `outDir`.
- * Unlike `com.metamx.common.CompressionUtils.gunzip`, this function takes an output *DIRECTORY* and tries to guess the file name.
- * It is recommended that the caller use `com.metamx.common.CompressionUtils.gunzip` and specify the output file themselves to ensure names are as expected
+ * Unlike `io.druid.java.util.common.CompressionUtils.gunzip`, this function takes an output *DIRECTORY* and tries to guess the file name.
+ * It is recommended that the caller use `io.druid.java.util.common.CompressionUtils.gunzip` and specify the output file themselves to ensure names are as expected
*
* @param pulledFile The source file
* @param outDir The destination directory to put the resulting file
diff --git a/api/src/test/java/io/druid/guice/JsonConfiguratorTest.java b/api/src/test/java/io/druid/guice/JsonConfiguratorTest.java
index 0ce4f77a79a..acfadf57131 100644
--- a/api/src/test/java/io/druid/guice/JsonConfiguratorTest.java
+++ b/api/src/test/java/io/druid/guice/JsonConfiguratorTest.java
@@ -94,10 +94,13 @@ public ExecutableValidator forExecutables()
public void testTest()
{
Assert.assertEquals(
- new MappableObject("p1", ImmutableList.<String>of("p2")),
- new MappableObject("p1", ImmutableList.<String>of("p2"))
+ new MappableObject("p1", ImmutableList.<String>of("p2"), "p2"),
+ new MappableObject("p1", ImmutableList.<String>of("p2"), "p2")
+ );
+ Assert.assertEquals(
+ new MappableObject("p1", null, null),
+ new MappableObject("p1", ImmutableList.<String>of(), null)
);
- Assert.assertEquals(new MappableObject("p1", null), new MappableObject("p1", ImmutableList.<String>of()));
}
@Test
@@ -140,6 +143,19 @@ public void testQuotedConfig()
Assert.assertEquals("testing \"prop1\"", obj.prop1);
Assert.assertEquals(ImmutableList.of(), obj.prop1List);
}
+
+ @Test
+ public void testPropertyWithDot()
+ {
+ final JsonConfigurator configurator = new JsonConfigurator(mapper, validator);
+ properties.setProperty(PROP_PREFIX + "prop2.prop.2", "testing");
+ properties.setProperty(PROP_PREFIX + "prop1", "prop1");
+ final MappableObject obj = configurator.configurate(properties, PROP_PREFIX, MappableObject.class);
+ Assert.assertEquals("testing", obj.prop2);
+ Assert.assertEquals(ImmutableList.of(), obj.prop1List);
+ Assert.assertEquals("prop1", obj.prop1);
+
+ }
}
class MappableObject
@@ -148,15 +164,19 @@ public void testQuotedConfig()
final String prop1;
@JsonProperty("prop1List")
final List<String> prop1List;
+ @JsonProperty("prop2.prop.2")
+ final String prop2;
@JsonCreator
protected MappableObject(
@JsonProperty("prop1") final String prop1,
- @JsonProperty("prop1List") final List<String> prop1List
+ @JsonProperty("prop1List") final List<String> prop1List,
+ @JsonProperty("prop2.prop.2") final String prop2
)
{
this.prop1 = prop1;
this.prop1List = prop1List == null ? ImmutableList.<String>of() : prop1List;
+ this.prop2 = prop2;
}
@@ -172,6 +192,12 @@ public String getProp1()
return prop1;
}
+ @JsonProperty
+ public String getProp2()
+ {
+ return prop2;
+ }
+
@Override
public boolean equals(Object o)
{
diff --git a/api/src/test/java/io/druid/indexer/TaskStatusPlusTest.java b/api/src/test/java/io/druid/indexer/TaskStatusPlusTest.java
new file mode 100644
index 00000000000..a4f3460e65a
--- /dev/null
+++ b/api/src/test/java/io/druid/indexer/TaskStatusPlusTest.java
@@ -0,0 +1,87 @@
+/*
+ * 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.indexer;
+
+import com.fasterxml.jackson.core.JsonParser;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.core.JsonToken;
+import com.fasterxml.jackson.databind.DeserializationContext;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.fasterxml.jackson.databind.deser.std.StdDeserializer;
+import com.fasterxml.jackson.databind.module.SimpleModule;
+import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
+import io.druid.java.util.common.DateTimes;
+import org.joda.time.DateTime;
+import org.junit.Assert;
+import org.junit.Test;
+
+import java.io.IOException;
+
+public class TaskStatusPlusTest
+{
+ @Test
+ public void testSerde() throws IOException
+ {
+ final ObjectMapper mapper = new ObjectMapper();
+ mapper.registerModule(
+ new SimpleModule()
+ .addDeserializer(DateTime.class, new DateTimeDeserializer())
+ .addSerializer(DateTime.class, ToStringSerializer.instance)
+ );
+ final TaskStatusPlus status = new TaskStatusPlus(
+ "testId",
+ DateTimes.nowUtc(),
+ DateTimes.nowUtc(),
+ TaskState.RUNNING,
+ 1000L,
+ TaskLocation.create("testHost", 1010, -1)
+ );
+ final String json = mapper.writeValueAsString(status);
+ Assert.assertEquals(status, mapper.readValue(json, TaskStatusPlus.class));
+ }
+
+ // Copied from io.druid.jackson.JodaStuff
+ private static class DateTimeDeserializer extends StdDeserializer<DateTime>
+ {
+ public DateTimeDeserializer()
+ {
+ super(DateTime.class);
+ }
+
+ @Override
+ public DateTime deserialize(JsonParser jp, DeserializationContext ctxt)
+ throws IOException, JsonProcessingException
+ {
+ JsonToken t = jp.getCurrentToken();
+ if (t == JsonToken.VALUE_NUMBER_INT) {
+ return DateTimes.utc(jp.getLongValue());
+ }
+ if (t == JsonToken.VALUE_STRING) {
+ String str = jp.getText().trim();
+ if (str.length() == 0) { // [JACKSON-360]
+ return null;
+ }
+ // make sure to preserve time zone information when parsing timestamps
+ return DateTimes.ISO_DATE_OR_TIME_WITH_OFFSET.parse(str);
+ }
+ throw ctxt.mappingException(getValueClass());
+ }
+ }
+}
diff --git a/aws-common/pom.xml b/aws-common/pom.xml
index 608552f98f5..cc16f8ceb0d 100644
--- a/aws-common/pom.xml
+++ b/aws-common/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/benchmarks/pom.xml b/benchmarks/pom.xml
index 596931c1439..9af8f37928a 100644
--- a/benchmarks/pom.xml
+++ b/benchmarks/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<prerequisites>
diff --git a/benchmarks/src/main/java/io/druid/benchmark/LoadStatusBenchmark.java b/benchmarks/src/main/java/io/druid/benchmark/LoadStatusBenchmark.java
new file mode 100644
index 00000000000..e1b877d481d
--- /dev/null
+++ b/benchmarks/src/main/java/io/druid/benchmark/LoadStatusBenchmark.java
@@ -0,0 +1,121 @@
+/*
+ * 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.benchmark;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
+import com.google.common.collect.Sets;
+import io.druid.java.util.common.Intervals;
+import io.druid.java.util.common.StringUtils;
+import io.druid.timeline.DataSegment;
+import io.druid.timeline.partition.NoneShardSpec;
+import org.openjdk.jmh.annotations.Benchmark;
+import org.openjdk.jmh.annotations.BenchmarkMode;
+import org.openjdk.jmh.annotations.Fork;
+import org.openjdk.jmh.annotations.Level;
+import org.openjdk.jmh.annotations.Measurement;
+import org.openjdk.jmh.annotations.Mode;
+import org.openjdk.jmh.annotations.OutputTimeUnit;
+import org.openjdk.jmh.annotations.Param;
+import org.openjdk.jmh.annotations.Scope;
+import org.openjdk.jmh.annotations.Setup;
+import org.openjdk.jmh.annotations.State;
+import org.openjdk.jmh.annotations.Warmup;
+import org.openjdk.jmh.infra.Blackhole;
+
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
+
+@State(Scope.Benchmark)
+@Fork(value = 1)
+@Warmup(iterations = 15)
+@Measurement(iterations = 30)
+public class LoadStatusBenchmark
+{
+ // Number of total data segments
+ @Param({"10000"})
+ int totalSegmentsCount;
+
+ @Param({"true", "false"})
+ private boolean serverHasAllSegments;
+
+ private Set<DataSegment> datasourceSegments;
+ private Collection<DataSegment> serverSegments;
+
+ @Setup(Level.Invocation)
+ public void setup()
+ {
+ Map<String, DataSegment> immutableDatasourceSegmentsMap;
+ ConcurrentHashMap<String, DataSegment> serverSegmentsMap;
+
+ HashMap<String, DataSegment> datasourceSegmentsMap = Maps.newHashMap();
+ serverSegmentsMap = new ConcurrentHashMap<>();
+
+ for (int i = 0; i < totalSegmentsCount; i++) {
+ DataSegment segment = new DataSegment(
+ "benchmarkDatasource",
+ Intervals.of(StringUtils.format("%s-01-01/%s-12-31", i + 1970, i + 1970)),
+ "1",
+ null,
+ null,
+ null,
+ NoneShardSpec.instance(),
+ 1,
+ 1
+ );
+
+ datasourceSegmentsMap.put(segment.getIdentifier(), segment);
+
+ if (serverHasAllSegments || i % 2 == 0) {
+ serverSegmentsMap.put(segment.getIdentifier(), segment);
+ }
+ }
+
+ immutableDatasourceSegmentsMap = ImmutableMap.copyOf(datasourceSegmentsMap);
+
+ datasourceSegments = Sets.newHashSet(immutableDatasourceSegmentsMap.values());
+ serverSegments = Collections.unmodifiableCollection(serverSegmentsMap.values());
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.MICROSECONDS)
+ public void oldVersion(Blackhole blackhole)
+ {
+ datasourceSegments.removeAll(serverSegments);
+ blackhole.consume(datasourceSegments);
+ }
+
+ @Benchmark
+ @BenchmarkMode(Mode.AverageTime)
+ @OutputTimeUnit(TimeUnit.MICROSECONDS)
+ public void newVersion(Blackhole blackhole)
+ {
+ for (DataSegment segment : serverSegments) {
+ datasourceSegments.remove(segment);
+ }
+ blackhole.consume(datasourceSegments);
+ }
+}
diff --git a/bytebuffer-collections/pom.xml b/bytebuffer-collections/pom.xml
deleted file mode 100755
index 4b8b231d5ea..00000000000
--- a/bytebuffer-collections/pom.xml
+++ /dev/null
@@ -1,138 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- ~ 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.
- -->
-
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
-
- <parent>
- <groupId>io.druid</groupId>
- <artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
- </parent>
-
- <artifactId>bytebuffer-collections</artifactId>
- <name>bytebuffer-collections</name>
- <description>ByteBuffer Collections</description>
-
- <dependencies>
- <dependency>
- <groupId>io.druid</groupId>
- <artifactId>extendedset</artifactId>
- <version>${project.parent.version}</version>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- <version>16.0.1</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-annotations</artifactId>
- <version>2.4.6</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-core</artifactId>
- <version>2.4.6</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.4.6</version>
- </dependency>
- <dependency>
- <groupId>org.roaringbitmap</groupId>
- <artifactId>RoaringBitmap</artifactId>
- </dependency>
-
- <!-- Tests -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.easymock</groupId>
- <artifactId>easymock</artifactId>
- <version>3.0</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.carrotsearch</groupId>
- <artifactId>junit-benchmarks</artifactId>
- <version>0.7.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.h2database</groupId>
- <artifactId>h2</artifactId>
- <version>1.4.182</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava-testlib</artifactId>
- <scope>test</scope>
- </dependency>
- </dependencies>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.4</version>
- <executions>
- <execution>
- <goals>
- <goal>test-jar</goal>
- </goals>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <excludedGroups>io.druid.test.annotation.Benchmark</excludedGroups>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <profiles>
- <profile>
- <id>benchmark</id>
- <build>
- <plugins>
- <plugin>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <argLine>-server -Xms3G -Xmx3G -Djub.consumers=CONSOLE,H2 -Djub.db.file=benchmarks/benchmarks</argLine>
- <groups>io.druid.test.annotation.Benchmark</groups>
- <excludedGroups>io.druid.test.annotation.Dummy</excludedGroups>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-</project>
diff --git a/common/pom.xml b/common/pom.xml
index 58379d33864..1e3cad51e69 100644
--- a/common/pom.xml
+++ b/common/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/common/src/main/java/io/druid/common/guava/ThreadRenamingCallable.java b/common/src/main/java/io/druid/common/guava/ThreadRenamingCallable.java
index 2fd6877a965..811fe59ce01 100644
--- a/common/src/main/java/io/druid/common/guava/ThreadRenamingCallable.java
+++ b/common/src/main/java/io/druid/common/guava/ThreadRenamingCallable.java
@@ -35,7 +35,7 @@ public ThreadRenamingCallable(
}
@Override
- public final T call()
+ public final T call() throws Exception
{
final Thread currThread = Thread.currentThread();
String currName = currThread.getName();
@@ -48,5 +48,5 @@ public final T call()
}
}
- public abstract T doCall();
+ public abstract T doCall() throws Exception;
}
diff --git a/common/src/main/java/io/druid/concurrent/LifecycleLock.java b/common/src/main/java/io/druid/concurrent/LifecycleLock.java
index a94e3cd31a3..7cc8e64a113 100644
--- a/common/src/main/java/io/druid/concurrent/LifecycleLock.java
+++ b/common/src/main/java/io/druid/concurrent/LifecycleLock.java
@@ -175,9 +175,9 @@ void exitStop()
}
}
- void reset()
+ void exitStopAndReset()
{
- if (!compareAndSetState(STOPPED, NOT_STARTED)) {
+ if (!compareAndSetState(STOPPING, NOT_STARTED)) {
throw new IllegalMonitorStateException("Not called exitStop() before reset()");
}
}
@@ -187,7 +187,7 @@ void reset()
/**
* Start latch, only one canStart() call in any thread on this LifecycleLock object could return true, if {@link
- * #reset()} is not called in between.
+ * #exitStopAndReset()} is not called in between.
*/
public boolean canStart()
{
@@ -257,8 +257,8 @@ public boolean canStop()
}
/**
- * If this LifecycleLock is used in a restartable object, which uses {@link #reset()}, exitStop() must be called
- * before exit from stop() on this object, usually in a finally block.
+ * Finalizes stopping the the LifecycleLock. This method must be called before exit from stop() on this object,
+ * usually in a finally block. If you're using a restartable object, use {@link #exitStopAndReset()} instead.
*
* @throws IllegalMonitorStateException if {@link #canStop()} is not yet called on this LifecycleLock
*/
@@ -268,12 +268,14 @@ public void exitStop()
}
/**
- * Resets the LifecycleLock after {@link #exitStop()}, so that {@link #canStart()} could be called again.
+ * Finalizes stopping the LifecycleLock and resets it, so that {@link #canStart()} could be called again. If this
+ * LifecycleLock is used in a restartable object, this method must be called before exit from stop() on this object,
+ * usually in a finally block.
*
- * @throws IllegalMonitorStateException if {@link #exitStop()} is not yet called on this LifecycleLock
+ * @throws IllegalMonitorStateException if {@link #canStop()} is not yet called on this LifecycleLock
*/
- public void reset()
+ public void exitStopAndReset()
{
- sync.reset();
+ sync.exitStopAndReset();
}
}
diff --git a/common/src/test/java/io/druid/collections/BlockingPoolTest.java b/common/src/test/java/io/druid/collections/BlockingPoolTest.java
index f76339ca99c..8e13cb56b27 100644
--- a/common/src/test/java/io/druid/collections/BlockingPoolTest.java
+++ b/common/src/test/java/io/druid/collections/BlockingPoolTest.java
@@ -21,7 +21,9 @@
import com.google.common.base.Suppliers;
import com.google.common.collect.Lists;
-import org.junit.AfterClass;
+import io.druid.java.util.common.concurrent.Execs;
+import org.junit.After;
+import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
@@ -30,7 +32,6 @@
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static org.junit.Assert.assertEquals;
@@ -40,26 +41,34 @@
public class BlockingPoolTest
{
- private static final ExecutorService SERVICE = Executors.newFixedThreadPool(2);
+ private ExecutorService service;
- private static final DefaultBlockingPool<Integer> POOL = new DefaultBlockingPool<>(Suppliers.ofInstance(1), 10);
- private static final BlockingPool<Integer> EMPTY_POOL = new DefaultBlockingPool<>(Suppliers.ofInstance(1), 0);
+ private DefaultBlockingPool<Integer> pool;
+ private BlockingPool<Integer> emptyPool;
- @AfterClass
- public static void teardown()
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
+ @Before
+ public void setup()
{
- SERVICE.shutdown();
+ service = Execs.multiThreaded(2, "blocking-pool-test");
+ pool = new DefaultBlockingPool<>(Suppliers.ofInstance(1), 10);
+ emptyPool = new DefaultBlockingPool<>(Suppliers.ofInstance(1), 0);
}
- @Rule
- public ExpectedException expectedException = ExpectedException.none();
+ @After
+ public void teardown()
+ {
+ service.shutdownNow();
+ }
@Test
public void testTakeFromEmptyPool()
{
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Pool was initialized with limit = 0, there are no objects to take.");
- EMPTY_POOL.take(0);
+ emptyPool.take(0);
}
@Test
@@ -67,54 +76,54 @@ public void testDrainFromEmptyPool()
{
expectedException.expect(IllegalStateException.class);
expectedException.expectMessage("Pool was initialized with limit = 0, there are no objects to take.");
- EMPTY_POOL.takeBatch(1, 0);
+ emptyPool.takeBatch(1, 0);
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testTake()
{
- final ReferenceCountingResourceHolder<Integer> holder = POOL.take(100);
+ final ReferenceCountingResourceHolder<Integer> holder = pool.take(100);
assertNotNull(holder);
- assertEquals(9, POOL.getPoolSize());
+ assertEquals(9, pool.getPoolSize());
holder.close();
- assertEquals(10, POOL.getPoolSize());
+ assertEquals(10, pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testTakeTimeout()
{
- final ReferenceCountingResourceHolder<List<Integer>> batchHolder = POOL.takeBatch(10, 100L);
- final ReferenceCountingResourceHolder<Integer> holder = POOL.take(100);
+ final ReferenceCountingResourceHolder<List<Integer>> batchHolder = pool.takeBatch(10, 100L);
+ final ReferenceCountingResourceHolder<Integer> holder = pool.take(100);
assertNull(holder);
batchHolder.close();
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testTakeBatch()
{
- final ReferenceCountingResourceHolder<List<Integer>> holder = POOL.takeBatch(6, 100L);
+ final ReferenceCountingResourceHolder<List<Integer>> holder = pool.takeBatch(6, 100L);
assertNotNull(holder);
assertEquals(6, holder.get().size());
- assertEquals(4, POOL.getPoolSize());
+ assertEquals(4, pool.getPoolSize());
holder.close();
- assertEquals(10, POOL.getPoolSize());
+ assertEquals(10, pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testWaitAndTakeBatch() throws InterruptedException, ExecutionException
{
- ReferenceCountingResourceHolder<List<Integer>> batchHolder = POOL.takeBatch(10, 10);
+ ReferenceCountingResourceHolder<List<Integer>> batchHolder = pool.takeBatch(10, 10);
assertNotNull(batchHolder);
assertEquals(10, batchHolder.get().size());
- assertEquals(0, POOL.getPoolSize());
+ assertEquals(0, pool.getPoolSize());
- final Future<ReferenceCountingResourceHolder<List<Integer>>> future = SERVICE.submit(
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> future = service.submit(
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
{
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(8, 100);
+ return pool.takeBatch(8, 100);
}
}
);
@@ -124,26 +133,26 @@ public void testWaitAndTakeBatch() throws InterruptedException, ExecutionExcepti
batchHolder = future.get();
assertNotNull(batchHolder);
assertEquals(8, batchHolder.get().size());
- assertEquals(2, POOL.getPoolSize());
+ assertEquals(2, pool.getPoolSize());
batchHolder.close();
- assertEquals(10, POOL.getPoolSize());
+ assertEquals(10, pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testTakeBatchTooManyObjects()
{
- final ReferenceCountingResourceHolder<List<Integer>> holder = POOL.takeBatch(100, 100L);
+ final ReferenceCountingResourceHolder<List<Integer>> holder = pool.takeBatch(100, 100L);
assertNull(holder);
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testConcurrentTake() throws ExecutionException, InterruptedException
{
- final int limit1 = POOL.maxSize() / 2;
- final int limit2 = POOL.maxSize() - limit1 + 1;
+ final int limit1 = pool.maxSize() / 2;
+ final int limit2 = pool.maxSize() - limit1 + 1;
- final Future<List<ReferenceCountingResourceHolder<Integer>>> f1 = SERVICE.submit(
+ final Future<List<ReferenceCountingResourceHolder<Integer>>> f1 = service.submit(
new Callable<List<ReferenceCountingResourceHolder<Integer>>>()
{
@Override
@@ -151,13 +160,13 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException
{
List<ReferenceCountingResourceHolder<Integer>> result = Lists.newArrayList();
for (int i = 0; i < limit1; i++) {
- result.add(POOL.take(10));
+ result.add(pool.take(10));
}
return result;
}
}
);
- final Future<List<ReferenceCountingResourceHolder<Integer>>> f2 = SERVICE.submit(
+ final Future<List<ReferenceCountingResourceHolder<Integer>>> f2 = service.submit(
new Callable<List<ReferenceCountingResourceHolder<Integer>>>()
{
@Override
@@ -165,7 +174,7 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException
{
List<ReferenceCountingResourceHolder<Integer>> result = Lists.newArrayList();
for (int i = 0; i < limit2; i++) {
- result.add(POOL.take(10));
+ result.add(pool.take(10));
}
return result;
}
@@ -175,7 +184,7 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException
final List<ReferenceCountingResourceHolder<Integer>> r1 = f1.get();
final List<ReferenceCountingResourceHolder<Integer>> r2 = f2.get();
- assertEquals(0, POOL.getPoolSize());
+ assertEquals(0, pool.getPoolSize());
assertTrue(r1.contains(null) || r2.contains(null));
int nonNullCount = 0;
@@ -190,9 +199,9 @@ public void testConcurrentTake() throws ExecutionException, InterruptedException
nonNullCount++;
}
}
- assertEquals(POOL.maxSize(), nonNullCount);
+ assertEquals(pool.maxSize(), nonNullCount);
- final Future future1 = SERVICE.submit(new Runnable()
+ final Future future1 = service.submit(new Runnable()
{
@Override
public void run()
@@ -204,7 +213,7 @@ public void run()
}
}
});
- final Future future2 = SERVICE.submit(new Runnable()
+ final Future future2 = service.submit(new Runnable()
{
@Override
public void run()
@@ -220,82 +229,82 @@ public void run()
future1.get();
future2.get();
- assertEquals(POOL.maxSize(), POOL.getPoolSize());
+ assertEquals(pool.maxSize(), pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testConcurrentTakeBatch() throws ExecutionException, InterruptedException
{
- final int batch1 = POOL.maxSize() / 2;
+ final int batch1 = pool.maxSize() / 2;
final Callable<ReferenceCountingResourceHolder<List<Integer>>> c1 =
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
{
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(batch1, 10);
+ return pool.takeBatch(batch1, 10);
}
};
- final int batch2 = POOL.maxSize() - batch1 + 1;
+ final int batch2 = pool.maxSize() - batch1 + 1;
final Callable<ReferenceCountingResourceHolder<List<Integer>>> c2 =
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
{
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(batch2, 10);
+ return pool.takeBatch(batch2, 10);
}
};
- final Future<ReferenceCountingResourceHolder<List<Integer>>> f1 = SERVICE.submit(c1);
- final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = SERVICE.submit(c2);
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> f1 = service.submit(c1);
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = service.submit(c2);
final ReferenceCountingResourceHolder<List<Integer>> r1 = f1.get();
final ReferenceCountingResourceHolder<List<Integer>> r2 = f2.get();
if (r1 != null) {
assertNull(r2);
- assertEquals(POOL.maxSize() - batch1, POOL.getPoolSize());
+ assertEquals(pool.maxSize() - batch1, pool.getPoolSize());
assertEquals(batch1, r1.get().size());
r1.close();
} else {
assertNotNull(r2);
- assertEquals(POOL.maxSize() - batch2, POOL.getPoolSize());
+ assertEquals(pool.maxSize() - batch2, pool.getPoolSize());
assertEquals(batch2, r2.get().size());
r2.close();
}
- assertEquals(POOL.maxSize(), POOL.getPoolSize());
+ assertEquals(pool.maxSize(), pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testConcurrentBatchClose() throws ExecutionException, InterruptedException
{
- final int batch1 = POOL.maxSize() / 2;
+ final int batch1 = pool.maxSize() / 2;
final Callable<ReferenceCountingResourceHolder<List<Integer>>> c1 =
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
{
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(batch1, 10);
+ return pool.takeBatch(batch1, 10);
}
};
- final int batch2 = POOL.maxSize() - batch1;
+ final int batch2 = pool.maxSize() - batch1;
final Callable<ReferenceCountingResourceHolder<List<Integer>>> c2 =
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
{
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(batch2, 10);
+ return pool.takeBatch(batch2, 10);
}
};
- final Future<ReferenceCountingResourceHolder<List<Integer>>> f1 = SERVICE.submit(c1);
- final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = SERVICE.submit(c2);
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> f1 = service.submit(c1);
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = service.submit(c2);
final ReferenceCountingResourceHolder<List<Integer>> r1 = f1.get();
final ReferenceCountingResourceHolder<List<Integer>> r2 = f2.get();
@@ -304,9 +313,9 @@ public void testConcurrentBatchClose() throws ExecutionException, InterruptedExc
assertNotNull(r2);
assertEquals(batch1, r1.get().size());
assertEquals(batch2, r2.get().size());
- assertEquals(0, POOL.getPoolSize());
+ assertEquals(0, pool.getPoolSize());
- final Future future1 = SERVICE.submit(new Runnable()
+ final Future future1 = service.submit(new Runnable()
{
@Override
public void run()
@@ -314,7 +323,7 @@ public void run()
r1.close();
}
});
- final Future future2 = SERVICE.submit(new Runnable()
+ final Future future2 = service.submit(new Runnable()
{
@Override
public void run()
@@ -326,13 +335,13 @@ public void run()
future1.get();
future2.get();
- assertEquals(POOL.maxSize(), POOL.getPoolSize());
+ assertEquals(pool.maxSize(), pool.getPoolSize());
}
- @Test(timeout = 1000)
+ @Test(timeout = 5000)
public void testConcurrentTakeBatchClose() throws ExecutionException, InterruptedException
{
- final ReferenceCountingResourceHolder<List<Integer>> r1 = POOL.takeBatch(1, 10);
+ final ReferenceCountingResourceHolder<List<Integer>> r1 = pool.takeBatch(1, 10);
final Callable<ReferenceCountingResourceHolder<List<Integer>>> c2 =
new Callable<ReferenceCountingResourceHolder<List<Integer>>>()
@@ -340,12 +349,12 @@ public void testConcurrentTakeBatchClose() throws ExecutionException, Interrupte
@Override
public ReferenceCountingResourceHolder<List<Integer>> call() throws Exception
{
- return POOL.takeBatch(10, 100);
+ return pool.takeBatch(10, 100);
}
};
- final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = SERVICE.submit(c2);
- final Future f1 = SERVICE.submit(new Runnable()
+ final Future<ReferenceCountingResourceHolder<List<Integer>>> f2 = service.submit(c2);
+ final Future f1 = service.submit(new Runnable()
{
@Override
public void run()
@@ -364,9 +373,9 @@ public void run()
f1.get();
assertNotNull(r2);
assertEquals(10, r2.get().size());
- assertEquals(0, POOL.getPoolSize());
+ assertEquals(0, pool.getPoolSize());
r2.close();
- assertEquals(POOL.maxSize(), POOL.getPoolSize());
+ assertEquals(pool.maxSize(), pool.getPoolSize());
}
}
diff --git a/common/src/test/java/io/druid/concurrent/LifecycleLockTest.java b/common/src/test/java/io/druid/concurrent/LifecycleLockTest.java
index e1d9f8adbbf..afb55bf2c2c 100644
--- a/common/src/test/java/io/druid/concurrent/LifecycleLockTest.java
+++ b/common/src/test/java/io/druid/concurrent/LifecycleLockTest.java
@@ -138,8 +138,7 @@ public void testRestart()
lifecycleLock.started();
lifecycleLock.exitStart();
Assert.assertTrue(lifecycleLock.canStop());
- lifecycleLock.exitStop();
- lifecycleLock.reset();
+ lifecycleLock.exitStopAndReset();
Assert.assertTrue(lifecycleLock.canStart());
}
diff --git a/distribution/pom.xml b/distribution/pom.xml
index 365ee356c46..5f25f29ec9d 100644
--- a/distribution/pom.xml
+++ b/distribution/pom.xml
@@ -16,8 +16,7 @@
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
@@ -29,7 +28,7 @@
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
@@ -60,7 +59,7 @@
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
- <classpath/>
+ <classpath />
<argument>-Ddruid.extensions.loadList=[]</argument>
<argument>-Ddruid.extensions.directory=${project.build.directory}/extensions</argument>
<argument>
@@ -190,7 +189,7 @@
<executable>java</executable>
<arguments>
<argument>-classpath</argument>
- <classpath/>
+ <classpath />
<argument>-Ddruid.extensions.loadList=[]</argument>
<argument>-Ddruid.extensions.directory=${project.build.directory}/extensions
</argument>
diff --git a/docs/content/configuration/auth.md b/docs/content/configuration/auth.md
index 358a54431b8..2fecfc1a86c 100644
--- a/docs/content/configuration/auth.md
+++ b/docs/content/configuration/auth.md
@@ -9,6 +9,7 @@ layout: doc_page
|`druid.auth.authenticationChain`|JSON List of Strings|List of Authenticator type names|["allowAll"]|no|
|`druid.escalator.type`|String|Type of the Escalator that should be used for internal Druid communications. This Escalator must use an authentication scheme that is supported by an Authenticator in `druid.auth.authenticationChain`.|"noop"|no|
|`druid.auth.authorizers`|JSON List of Strings|List of Authorizer type names |["allowAll"]|no|
+|`druid.auth.allowUnauthenticatedHttpOptions`|Boolean|If true, skip authentication checks for HTTP OPTIONS requests. This is needed for certain use cases, such as supporting CORS pre-flight requests. Note that disabling authentication checks for OPTIONS requests will allow unauthenticated users to determine what Druid endpoints are valid (by checking if the OPTIONS request returns a 200 instead of 404), so enabling this option may reveal information about server configuration, including information about what extensions are loaded (if those extensions add endpoints).|false|no|
## Enabling Authentication/Authorization
diff --git a/docs/content/configuration/coordinator.md b/docs/content/configuration/coordinator.md
index 2dfd97098df..867a3043ac2 100644
--- a/docs/content/configuration/coordinator.md
+++ b/docs/content/configuration/coordinator.md
@@ -29,6 +29,7 @@ The coordinator node uses several of the global configs in [Configuration](../co
|`druid.coordinator.merge.on`|Boolean flag for whether or not the coordinator should try and merge small segments into a more optimal segment size.|false|
|`druid.coordinator.conversion.on`|Boolean flag for converting old segment indexing versions to the latest segment indexing version.|false|
|`druid.coordinator.load.timeout`|The timeout duration for when the coordinator assigns a segment to a historical node.|PT15M|
+|`druid.coordinator.kill.pendingSegments.on`|Boolean flag for whether or not the coordinator clean up old entries in the `pendingSegments` table of metadata store. If set to true, coordinator will check the created time of most recently complete task. If it doesn't exist, it finds the created time of the earlist running/pending/waiting tasks. Once the created time is found, then for all dataSources not in the `killPendingSegmentsSkipList` (see [Dynamic configuration](#dynamic-configuration)), coordinator will ask the overlord to clean up the entries 1 day or more older than the found created time in the `pendingSegments` table. This will be done periodically based on `druid.coordinator.period` specified.|false|
|`druid.coordinator.kill.on`|Boolean flag for whether or not the coordinator should submit kill task for unused segments, that is, hard delete them from metadata store and deep storage. If set to true, then for all whitelisted dataSources (or optionally all), coordinator will submit tasks periodically based on `period` specified. These kill tasks will delete all segments except for the last `durationToRetain` period. Whitelist or All can be set via dynamic configuration `killAllDataSources` and `killDataSourceWhitelist` described later.|false|
|`druid.coordinator.kill.period`|How often to send kill tasks to the indexing service. Value must be greater than `druid.coordinator.period.indexingPeriod`. Only applies if kill is turned on.|P1D (1 Day)|
|`druid.coordinator.kill.durationToRetain`| Do not kill segments in last `durationToRetain`, must be greater or equal to 0. Only applies and MUST be specified if kill is turned on. Note that default value is invalid.|PT-1S (-1 seconds)|
@@ -103,8 +104,9 @@ Issuing a GET request at the same URL will return the spec that is currently in
|`replicantLifetime`|The maximum number of coordinator runs for a segment to be replicated before we start alerting.|15|
|`replicationThrottleLimit`|The maximum number of segments that can be replicated at one time.|10|
|`emitBalancingStats`|Boolean flag for whether or not we should emit balancing stats. This is an expensive operation.|false|
-|`killDataSourceWhitelist`|List of dataSources for which kill tasks are sent if property `druid.coordinator.kill.on` is true.|none|
+|`killDataSourceWhitelist`|List of dataSources for which kill tasks are sent if property `druid.coordinator.kill.on` is true. This can be a list of comma-separated dataSources or a JSON array.|none|
|`killAllDataSources`|Send kill tasks for ALL dataSources if property `druid.coordinator.kill.on` is true. If this is set to true then `killDataSourceWhitelist` must not be specified or be empty list.|false|
+|`killPendingSegmentsSkipList`|List of dataSources for which pendingSegments are _NOT_ cleaned up if property `druid.coordinator.kill.pendingSegments.on` is true. This can be a list of comma-separated dataSources or a JSON array.|none|
|`maxSegmentsInNodeLoadingQueue`|The maximum number of segments that could be queued for loading to any given server. This parameter could be used to speed up segments loading process, especially if there are "slow" nodes in the cluster (with low loading speed) or if too much segments scheduled to be replicated to some particular node (faster loading could be preferred to better segments distribution). Desired value depends on segments loading speed, acceptable replication time and number of nodes. Value 1000 could be a start point for a rather big cluster. Default value is 0 (loading queue is unbounded) |0|
To view the audit history of coordinator dynamic config issue a GET request to the URL -
diff --git a/docs/content/configuration/historical.md b/docs/content/configuration/historical.md
index 9290e265d27..b0e34339635 100644
--- a/docs/content/configuration/historical.md
+++ b/docs/content/configuration/historical.md
@@ -31,7 +31,7 @@ The historical node uses several of the global configs in [Configuration](../con
|Property|Description|Default|
|--------|-----------|-------|
-|`druid.segmentCache.locations`|Segments assigned to a Historical node are first stored on the local file system (in a disk cache) and then served by the Historical node. These locations define where that local cache resides. This value cannot be NULL or EMPTY. Here is an example `druid.segmentCache.locations=[{"path": "/mnt/druidSegments", "maxSize": 10000}, "freeSpacePercent": 1.0]`. "freeSpacePercent" is optional, if provided then enforces that much of free disk partition space while storing segments. But, it depends on File.getTotalSpace() and File.getFreeSpace() methods, so enable if only if they work for your File System.| none |
+|`druid.segmentCache.locations`|Segments assigned to a Historical node are first stored on the local file system (in a disk cache) and then served by the Historical node. These locations define where that local cache resides. This value cannot be NULL or EMPTY. Here is an example `druid.segmentCache.locations=[{"path": "/mnt/druidSegments", "maxSize": 10000, "freeSpacePercent": 1.0}]`. "freeSpacePercent" is optional, if provided then enforces that much of free disk partition space while storing segments. But, it depends on File.getTotalSpace() and File.getFreeSpace() methods, so enable if only if they work for your File System.| none |
|`druid.segmentCache.deleteOnRemove`|Delete segment files from cache once a node is no longer serving a segment.|true|
|`druid.segmentCache.dropSegmentDelayMillis`|How long a node delays before completely dropping segment.|30000 (30 seconds)|
|`druid.segmentCache.infoDir`|Historical nodes keep track of the segments they are serving so that when the process is restarted they can reload the same segments without waiting for the Coordinator to reassign. This path defines where this metadata is kept. Directory will be created if needed.|${first_location}/info_dir|
diff --git a/docs/content/configuration/index.md b/docs/content/configuration/index.md
index 66b8ca41f76..02a0d20e9de 100644
--- a/docs/content/configuration/index.md
+++ b/docs/content/configuration/index.md
@@ -180,19 +180,19 @@ Druid nodes periodically emit metrics and different metrics monitors can be incl
|Property|Description|Default|
|--------|-----------|-------|
|`druid.monitoring.emissionPeriod`|How often metrics are emitted.|PT1m|
-|`druid.monitoring.monitors`|Sets list of Druid monitors used by a node. See below for names and more information. For example, you can specify monitors for a Broker with `druid.monitoring.monitors=["com.metamx.metrics.SysMonitor","com.metamx.metrics.JvmMonitor"]`.|none (no monitors)|
+|`druid.monitoring.monitors`|Sets list of Druid monitors used by a node. See below for names and more information. For example, you can specify monitors for a Broker with `druid.monitoring.monitors=["io.druid.java.util.metrics.SysMonitor","io.druid.java.util.metrics.JvmMonitor"]`.|none (no monitors)|
The following monitors are available:
|Name|Description|
|----|-----------|
|`io.druid.client.cache.CacheMonitor`|Emits metrics (to logs) about the segment results cache for Historical and Broker nodes. Reports typical cache statistics include hits, misses, rates, and size (bytes and number of entries), as well as timeouts and and errors.|
-|`com.metamx.metrics.SysMonitor`|This uses the [SIGAR library](http://www.hyperic.com/products/sigar) to report on various system activities and statuses.|
+|`io.druid.java.util.metrics.SysMonitor`|This uses the [SIGAR library](http://www.hyperic.com/products/sigar) to report on various system activities and statuses.|
|`io.druid.server.metrics.HistoricalMetricsMonitor`|Reports statistics on Historical nodes.|
-|`com.metamx.metrics.JvmMonitor`|Reports various JVM-related statistics.|
-|`com.metamx.metrics.JvmCpuMonitor`|Reports statistics of CPU consumption by the JVM.|
-|`com.metamx.metrics.CpuAcctDeltaMonitor`|Reports consumed CPU as per the cpuacct cgroup.|
-|`com.metamx.metrics.JvmThreadsMonitor`|Reports Thread statistics in the JVM, like numbers of total, daemon, started, died threads.|
+|`io.druid.java.util.metrics.JvmMonitor`|Reports various JVM-related statistics.|
+|`io.druid.java.util.metrics.JvmCpuMonitor`|Reports statistics of CPU consumption by the JVM.|
+|`io.druid.java.util.metrics.CpuAcctDeltaMonitor`|Reports consumed CPU as per the cpuacct cgroup.|
+|`io.druid.java.util.metrics.JvmThreadsMonitor`|Reports Thread statistics in the JVM, like numbers of total, daemon, started, died threads.|
|`io.druid.segment.realtime.RealtimeMetricsMonitor`|Reports statistics on Realtime nodes.|
|`io.druid.server.metrics.EventReceiverFirehoseMonitor`|Reports how many events have been queued in the EventReceiverFirehose.|
|`io.druid.server.metrics.QueryCountStatsMonitor`|Reports how many queries have been successful/failed/interrupted.|
@@ -222,8 +222,8 @@ The Druid servers [emit various metrics](../operations/metrics.html) and alerts
|`druid.emitter.http.basicAuthentication`|Login and password for authentification in "login:password" form, e. g. `druid.emitter.http.basicAuthentication=admin:adminpassword`|not specified = no authentification|
|`druid.emitter.http.flushTimeOut|The timeout after which an event should be sent to the endpoint, even if internal buffers are not filled, in milliseconds.|not specified = no timeout|
|`druid.emitter.http.batchingStrategy`|The strategy of how the batch is formatted. "ARRAY" means `[event1,event2]`, "NEWLINES" means `event1\nevent2`, ONLY_EVENTS means `event1event2`.|ARRAY|
-|`druid.emitter.http.maxBatchSize`|The maximum batch size, in bytes.|5191680 (i. e. 5 MB)|
-|`druid.emitter.http.batchQueueSizeLimit`|The maximum number of batches in emitter queue, if there are problems with emitting.|50|
+|`druid.emitter.http.maxBatchSize`|The maximum batch size, in bytes.|the minimum of (10% of JVM heap size divided by 2) or (5191680 (i. e. 5 MB))|
+|`druid.emitter.http.batchQueueSizeLimit`|The maximum number of batches in emitter queue, if there are problems with emitting.|the maximum of (2) or (10% of the JVM heap size divided by 5MB)|
|`druid.emitter.http.minHttpTimeoutMillis`|If the speed of filling batches imposes timeout smaller than that, not even trying to send batch to endpoint, because it will likely fail, not being able to send the data that fast. Configure this depending based on emitter/successfulSending/minTimeMs metric. Reasonable values are 10ms..100ms.|0|
|`druid.emitter.http.recipientBaseUrl`|The base URL to emit messages to. Druid will POST JSON to be consumed at the HTTP endpoint specified by this property.|none, required config|
diff --git a/docs/content/development/extensions-core/druid-kerberos.md b/docs/content/development/extensions-core/druid-kerberos.md
index 1ded0e0f5a5..dc0d38a7b5a 100644
--- a/docs/content/development/extensions-core/druid-kerberos.md
+++ b/docs/content/development/extensions-core/druid-kerberos.md
@@ -31,8 +31,6 @@ The configuration examples in the rest of this document will use "kerberos" as t
### Properties
|Property|Possible Values|Description|Default|required|
|--------|---------------|-----------|-------|--------|
-|`druid.auth.authenticator.kerberos.internalClientPrincipal`|`druid@EXAMPLE.COM`| Principal user name, used for internal node communication|empty|Yes|
-|`druid.auth.authenticator.kerberos.internalClientKeytab`|`/etc/security/keytabs/druid.keytab`|Path to keytab file used for internal node communication|empty|Yes|
|`druid.auth.authenticator.kerberos.serverPrincipal`|`HTTP/_HOST@EXAMPLE.COM`| SPNego service principal used by druid nodes|empty|Yes|
|`druid.auth.authenticator.kerberos.serverKeytab`|`/etc/security/keytabs/spnego.service.keytab`|SPNego service keytab used by druid nodes|empty|Yes|
|`druid.auth.authenticator.kerberos.authToLocal`|`RULE:[1:$1@$0](druid@EXAMPLE.COM)s/.*/druid DEFAULT`|It allows you to set a general rule for mapping principal names to local user names. It will be used if there is not an explicit mapping for the principal name that is being translated.|DEFAULT|No|
@@ -54,6 +52,17 @@ In Active Directory environment, SPNEGO token in the Authorization header includ
which includes all security groups for the user. In some cases when the user belongs to many security groups the header to grow beyond what druid can handle by default.
In such cases, max request header size that druid can handle can be increased by setting `druid.server.http.maxRequestHeaderSize` (default 8Kb) and `druid.router.http.maxRequestBufferSize` (default 8Kb).
+## Configuring Kerberos Escalated Client
+
+Druid internal nodes communicate with each other using an escalated http Client. A Kerberos enabled escalated HTTP Client can be configured by following properties -
+
+
+|Property|Example Values|Description|Default|required|
+|--------|---------------|-----------|-------|--------|
+|`druid.escalator.type`|`kerberos`| Type of Escalator client used for internal node communication.|n/a|Yes|
+|`druid.escalator.internalClientPrincipal`|`druid@EXAMPLE.COM`| Principal user name, used for internal node communication|n/a|Yes|
+|`druid.escalator.internalClientKeytab`|`/etc/security/keytabs/druid.keytab`|Path to keytab file used for internal node communication|n/a|Yes|
+|`druid.escalator.authorizerName`|`MyBasicAuthorizer`|Authorizer that requests should be directed to.|n/a|Yes|
## Accessing Druid HTTP end points when kerberos security is enabled
1. To access druid HTTP endpoints via curl user will need to first login using `kinit` command as follows -
diff --git a/docs/content/development/extensions-core/kafka-ingestion.md b/docs/content/development/extensions-core/kafka-ingestion.md
index b32c479fe7b..c254aad114e 100644
--- a/docs/content/development/extensions-core/kafka-ingestion.md
+++ b/docs/content/development/extensions-core/kafka-ingestion.md
@@ -311,40 +311,17 @@ In this way, configuration changes can be applied without requiring any pause in
### On the Subject of Segments
-The Kafka indexing service may generate a significantly large number of segments which over time will cause query
-performance issues if not properly managed. One important characteristic to understand is that the Kafka indexing task
-will generate a Druid partition in each segment granularity interval for each partition in the Kafka topic. As an
-example, if you are ingesting realtime data and your segment granularity is 15 minutes with 10 partitions in the Kafka
-topic, you would generate a minimum of 40 segments an hour. This is a limitation imposed by the Kafka architecture which
-guarantees delivery order within a partition but not across partitions. Therefore as a consumer of Kafka, in order to
-generate segments deterministically (and be able to provide exactly-once ingestion semantics) partitions need to be
-handled separately.
-
-Compounding this, if your taskDuration was also set to 15 minutes, you would actually generate 80 segments an hour since
-any given 15 minute interval would be handled by two tasks. For an example of this behavior, let's say we started the
-supervisor at 9:05 with a 15 minute segment granularity. The first task would create a segment for 9:00-9:15 and a
-segment for 9:15-9:30 before stopping at 9:20. A second task would be created at 9:20 which would create another segment
-for 9:15-9:30 and a segment for 9:30-9:45 before stopping at 9:35. Hence, if taskDuration and segmentGranularity are the
-same duration, you will get two tasks generating a segment for each segment granularity interval.
-
-Understanding this behavior is the first step to managing the number of segments produced. Some recommendations for
-keeping the number of segments low are:
-
- * Keep the number of Kafka partitions to the minimum required to sustain the required throughput for your event streams.
- * Increase segment granularity and task duration so that more events are written into the same segment. One
- consideration here is that segments are only handed off to historical nodes after the task duration has elapsed.
- Since workers tend to be configured with less query-serving resources than historical nodes, query performance may
- suffer if tasks run excessively long without handing off segments.
-
-In many production installations which have been ingesting events for a long period of time, these suggestions alone
-will not be sufficient to keep the number of segments at an optimal level. It is recommended that scheduled re-indexing
-tasks be run to merge segments together into new segments of an ideal size (in the range of ~500-700 MB per segment).
-Currently, the recommended way of doing this is by running periodic Hadoop batch ingestion jobs and using a `dataSource`
-inputSpec to read from the segments generated by the Kafka indexing tasks. Details on how to do this can be found under
-['Updating Existing Data'](../../ingestion/update-existing-data.html). Note that the Merge Task and Append Task described
-[here](../../ingestion/tasks.html) will not work as they require unsharded segments while Kafka indexing tasks always
-generated sharded segments.
-
-There is ongoing work to support automatic segment compaction of sharded segments as well as compaction not requiring
-Hadoop (see [here](https://github.com/druid-io/druid/pull/1998) and [here](https://github.com/druid-io/druid/pull/3611)
-for related PRs).
+Each Kafka Indexing Task puts events consumed from Kafka partitions assigned to it in a single segment for each segment
+granular interval until maxRowsPerSegment limit is reached, at this point a new partition for this segment granularity is
+created for further events. Kafka Indexing Task also does incremental hand-offs which means that all the segments created by a
+task will not be held up till the task duration is over. As soon as maxRowsPerSegment limit is hit, all the segments held
+by the task at that point in time will be handed-off and new set of segments will be created for further events.
+This means that the task can run for longer durations of time without accumulating old segments locally on Middle Manager
+nodes and it is encouraged to do so.
+
+Kafka Indexing Service may still produce some small segments. Lets say the task duration is 4 hours, segment granularity
+is set to an HOUR and Supervisor was started at 9:10 then after 4 hours at 13:10, new set of tasks will be started and
+events for the interval 13:00 - 14:00 may be split across previous and new set of tasks. If you see it becoming a problem then
+one can schedule re-indexing tasks be run to merge segments together into new segments of an ideal size (in the range of ~500-700 MB per segment).
+There is also ongoing work to support automatic segment compaction of sharded segments as well as compaction not requiring
+Hadoop (see [here](https://github.com/druid-io/druid/pull/5102)).
diff --git a/docs/content/development/extensions-core/lookups-cached-global.md b/docs/content/development/extensions-core/lookups-cached-global.md
index 7e4b11af843..a5e7d5eb04f 100644
--- a/docs/content/development/extensions-core/lookups-cached-global.md
+++ b/docs/content/development/extensions-core/lookups-cached-global.md
@@ -71,7 +71,7 @@ The parameters are as follows
|--------|-----------|--------|-------|
|`extractionNamespace`|Specifies how to populate the local cache. See below|Yes|-|
|`firstCacheTimeout`|How long to wait (in ms) for the first run of the cache to populate. 0 indicates to not wait|No|`0` (do not wait)|
-|`injective`|If the underlying map is injective (keys and values are unique) then optimizations can occur internally by setting this to `true`|No|`false`|
+|`injective`|If the underlying map is [injective](../../querying/lookups.html#query-execution) (keys and values are unique) then optimizations can occur internally by setting this to `true`|No|`false`|
If `firstCacheTimeout` is set to a non-zero value, it should be less than `druid.manager.lookups.hostUpdateTimeout`. If `firstCacheTimeout` is NOT set, then management is essentially asynchronous and does not know if a lookup succeeded or failed in starting. In such a case logs from the lookup nodes should be monitored for repeated failures.
diff --git a/docs/content/development/extensions-core/mysql.md b/docs/content/development/extensions-core/mysql.md
index eb03af6af86..5314c07eef5 100644
--- a/docs/content/development/extensions-core/mysql.md
+++ b/docs/content/development/extensions-core/mysql.md
@@ -53,3 +53,23 @@ Make sure to [include](../../operations/including-extensions.html) `mysql-metada
packaged in a separate tarball that can be downloaded from [here](http://druid.io/downloads.html).
You can also get it using [pull-deps](../../operations/pull-deps.html), or you can build
it from source code; see [Build from Source](../build.html).
+
+
+## Encrypting MySQL connections
+ This extension provides support for encrypting MySQL connections. To get more information about encrypting MySQL connections using TLS/SSL in general, please refer to this [guide](https://dev.mysql.com/doc/refman/5.7/en/using-encrypted-connections.html).
+
+## Configuration
+
+|Property|Description|Default|Required|
+|--------|-----------|-------|--------|
+|`druid.metadata.mysql.ssl.useSSL`|Enable SSL|`false`|no|
+|`druid.metadata.mysql.ssl.clientCertificateKeyStoreUrl`|The file path URL to the client certificate key store.|none|no|
+|`druid.metadata.mysql.ssl.clientCertificateKeyStoreType`|The type of the key store where the client certificate is stored.|none|no|
+|`druid.metadata.mysql.ssl.clientCertificateKeyStorePassword`|The [Password Provider](../operations/password-provider.html) or String password for the client key store.|none|no|
+|`druid.metadata.mysql.ssl.verifyServerCertificate`|Enables server certificate verification.|false|no|
+|`druid.metadata.mysql.ssl.trustCertificateKeyStoreUrl`|The file path to the trusted root certificate key store.|Default trust store provided by MySQL|yes if `verifyServerCertificate` is set to true and a custom trust store is used|
+|`druid.metadata.mysql.ssl.trustCertificateKeyStoreType`|The type of the key store where trusted root certificates are stored.|JKS|yes if `verifyServerCertificate` is set to true and keystore type is not JKS|
+|`druid.metadata.mysql.ssl.trustCertificateKeyStorePassword`|The [Password Provider](../operations/password-provider.html) or String password for the trust store.|none|yes if `verifyServerCertificate` is set to true and password is not null|
+|`druid.metadata.mysql.ssl.enabledSSLCipherSuites`|Overrides the existing cipher suites with these cipher suites.|none|no|
+|`druid.metadata.mysql.ssl.enabledTLSProtocols`|Overrides the TLS protocols with these protocols.|none|no|
+
diff --git a/docs/content/development/extensions.md b/docs/content/development/extensions.md
index bc728306042..a9e1d1ee2f0 100644
--- a/docs/content/development/extensions.md
+++ b/docs/content/development/extensions.md
@@ -22,6 +22,7 @@ Core extensions are maintained by Druid committers.
|Name|Description|Docs|
|----|-----------|----|
|druid-avro-extensions|Support for data in Apache Avro data format.|[link](../development/extensions-core/avro.html)|
+|druid-basic-security|Support for Basic HTTP authentication and role-based access control.|[link](../development/extensions-core/druid-basic-security.html)|
|druid-caffeine-cache|A local cache implementation backed by Caffeine.|[link](../development/extensions-core/caffeine-cache.html)|
|druid-datasketches|Support for approximate counts and set operations with [DataSketches](http://datasketches.github.io/).|[link](../development/extensions-core/datasketches-aggregators.html)|
|druid-hdfs-storage|HDFS deep storage.|[link](../development/extensions-core/hdfs.html)|
diff --git a/docs/content/development/modules.md b/docs/content/development/modules.md
index be3773bfaf1..db529f3029a 100644
--- a/docs/content/development/modules.md
+++ b/docs/content/development/modules.md
@@ -110,7 +110,7 @@ The following example was retrieved from a historical node configured to use Azu
00Z_2015-04-14T02:41:09.484Z
2015-04-14T02:42:33,463 INFO [ZkCoordinator-0] io.druid.guice.JsonConfigurator - Loaded class[class io.druid.storage.azure.AzureAccountConfig] from props[drui
d.azure.] as [io.druid.storage.azure.AzureAccountConfig@759c9ad9]
-2015-04-14T02:49:08,275 INFO [ZkCoordinator-0] com.metamx.common.CompressionUtils - Unzipping file[/opt/druid/tmp/compressionUtilZipCache1263964429587449785.z
+2015-04-14T02:49:08,275 INFO [ZkCoordinator-0] io.druid.java.util.common.CompressionUtils - Unzipping file[/opt/druid/tmp/compressionUtilZipCache1263964429587449785.z
ip] to [/opt/druid/zk_druid/dde/2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z/2015-04-14T02:41:09.484Z/0]
2015-04-14T02:49:08,276 INFO [ZkCoordinator-0] io.druid.storage.azure.AzureDataSegmentPuller - Loaded 1196 bytes from [dde/2015-01-02T00:00:00.000Z_2015-01-03
T00:00:00.000Z/2015-04-14T02:41:09.484Z/0/index.zip] to [/opt/druid/zk_druid/dde/2015-01-02T00:00:00.000Z_2015-01-03T00:00:00.000Z/2015-04-14T02:41:09.484Z/0]
diff --git a/docs/content/ingestion/tasks.md b/docs/content/ingestion/tasks.md
index b5b1bc1c543..4d424efcadb 100644
--- a/docs/content/ingestion/tasks.md
+++ b/docs/content/ingestion/tasks.md
@@ -276,8 +276,10 @@ An example of compaction task is
}
```
-This compaction task merges _all segments_ of the interval `2017-01-01/2018-01-01` into a _single segment_.
-To merge each day's worth of data into a separate segment, you can submit multiple `compact` tasks, one for each day. They will run in parallel.
+This compaction task reads _all segments_ of the interval `2017-01-01/2018-01-01` and results in new segments.
+Note that intervals of the input segments are merged into a single interval of `2017-01-01/2018-01-01` no matter what the segmentGranularity was.
+To controll the number of result segments, you can set `targetPartitionSize` or `numShards`. See [indexTuningConfig](#tuningconfig) for more details.
+To merge each day's worth of data into separate segments, you can submit multiple `compact` tasks, one for each day. They will run in parallel.
A compaction task internally generates an `index` task spec for performing compaction work with some fixed parameters.
For example, its `firehose` is always the [ingestSegmentSpec](./firehose.html), and `dimensionsSpec` and `metricsSpec`
diff --git a/docs/content/misc/math-expr.md b/docs/content/misc/math-expr.md
index 07dcc501808..abcebdd3b5e 100644
--- a/docs/content/misc/math-expr.md
+++ b/docs/content/misc/math-expr.md
@@ -62,7 +62,7 @@ The following built-in functions are available.
|timestamp_ceil|timestamp_ceil(expr, period, \[origin, \[timezone\]\]) rounds up a timestamp, returning it as a new timestamp. Period can be any ISO8601 period, like P3M (quarters) or PT12H (half-days). The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00".|
|timestamp_floor|timestamp_floor(expr, period, \[origin, [timezone\]\]) rounds down a timestamp, returning it as a new timestamp. Period can be any ISO8601 period, like P3M (quarters) or PT12H (half-days). The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00".|
|timestamp_shift|timestamp_shift(expr, period, step, \[timezone\]) shifts a timestamp by a period (step times), returning it as a new timestamp. Period can be any ISO8601 period. Step may be negative. The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00".|
-|timestamp_extract|timestamp_extract(expr, unit, \[timezone\]) extracts a time part from expr, returning it as a number. Unit can be EPOCH, SECOND, MINUTE, HOUR, DAY (day of month), DOW (day of week), DOY (day of year), WEEK (week of [week year](https://en.wikipedia.org/wiki/ISO_week_date)), MONTH (1 through 12), QUARTER (1 through 4), or YEAR. The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00"|
+|timestamp_extract|timestamp_extract(expr, unit, \[timezone\]) extracts a time part from expr, returning it as a number. Unit can be EPOCH (number of seconds since 1970-01-01 00:00:00 UTC), SECOND, MINUTE, HOUR, DAY (day of month), DOW (day of week), DOY (day of year), WEEK (week of [week year](https://en.wikipedia.org/wiki/ISO_week_date)), MONTH (1 through 12), QUARTER (1 through 4), or YEAR. The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00"|
|timestamp_parse|timestamp_parse(string expr, \[pattern, [timezone\]\]) parses a string into a timestamp using a given [Joda DateTimeFormat pattern](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html). If the pattern is not provided, this parses time strings in either ISO8601 or SQL format. The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00", and will be used as the time zone for strings that do not include a time zone offset. Pattern and time zone must be literals. Strings that cannot be parsed as timestamps will be returned as nulls.|
|timestamp_format|timestamp_format(expr, \[pattern, \[timezone\]\]) formats a timestamp as a string with a given [Joda DateTimeFormat pattern](http://www.joda.org/joda-time/apidocs/org/joda/time/format/DateTimeFormat.html), or ISO8601 if the pattern is not provided. The time zone, if provided, should be a time zone name like "America/Los_Angeles" or offset like "-08:00". Pattern and time zone must be literals.|
diff --git a/docs/content/operations/insert-segment-to-db.md b/docs/content/operations/insert-segment-to-db.md
index 60549e69d6c..cd5ba2264ae 100644
--- a/docs/content/operations/insert-segment-to-db.md
+++ b/docs/content/operations/insert-segment-to-db.md
@@ -5,24 +5,43 @@ layout: doc_page
`insert-segment-to-db` is a tool that can insert segments into Druid metadata storage. It is intended to be used
to update the segment table in metadata storage after people manually migrate segments from one place to another.
-It can also be used to insert missing segment into Druid, or even recover metadata storage by telling it where the
+It can also be used to insert missing segments into Druid, or even recover metadata storage by telling it where the
segments are stored.
-Note: This tool expects users to have Druid cluster running in a "safe" mode, where there are no active tasks to interfere
-the segments being inserted. Users can optionally bring down the cluster to make 100% sure nothing is interfering.
+**Note:** This tool simply scans the deep storage directory to reconstruct the metadata entries used to locate and
+identify each segment. It does not have any understanding about whether those segments _should actually_ be written to
+the metadata storage. In certain cases, this can lead to undesired or inconsistent results. Some examples of things to
+watch out for:
+ - Dropped datasources will be re-enabled.
+ - The latest version of each segment set will be loaded by Druid, which in some cases may not be the version you
+ actually want. An example of this is a bad compaction job that generates segments which need to be manually rolled
+ back by removing that version from the metadata table. If these segments are not also removed from deep storage,
+ they will be imported back into the metadata table and overshadow the correct version.
+ - Some indexers such as the Kafka indexing service have the potential to generate more than one set of segments that
+ have the same segment ID but different contents. When the metadata is first written, the correct set of segments is
+ referenced and the other set is normally deleted from deep storage. It is possible however that an unhandled
+ exception could result in multiple sets of segments with the same segment ID remaining in deep storage. Since this
+ tool does not know which one is the 'correct' one to use, it will simply select the newest segment set and ignore
+ the other versions. If the wrong segment set is picked, the exactly-once semantics of the Kafka indexing service
+ will no longer hold true and you may get duplicated or dropped events.
+
+With these considerations in mind, it is recommended that data migrations be done by exporting the original metadata
+storage directly, since that is the definitive cluster state. This tool should be used as a last resort when a direct
+export is not possible.
+
+**Note:** This tool expects users to have Druid cluster running in a "safe" mode, where there are no active tasks to interfere
+with the segments being inserted. Users can optionally bring down the cluster to make 100% sure nothing is interfering.
In order to make it work, user will have to provide metadata storage credentials and deep storage type through Java JVM argument
-or runtime.properties file. Specifically, this tool needs to know
+or runtime.properties file. Specifically, this tool needs to know:
-`druid.metadata.storage.type`
-
-`druid.metadata.storage.connector.connectURI`
-
-`druid.metadata.storage.connector.user`
-
-`druid.metadata.storage.connector.password`
-
-`druid.storage.type`
+```
+druid.metadata.storage.type
+druid.metadata.storage.connector.connectURI
+druid.metadata.storage.connector.user
+druid.metadata.storage.connector.password
+druid.storage.type
+```
Besides the properties above, you also need to specify the location where the segments are stored and whether you want to
update descriptor.json (`partitionNum_descriptor.json` for HDFS data storage). These two can be provided through command line arguments.
diff --git a/docs/content/operations/performance-faq.md b/docs/content/operations/performance-faq.md
index edeaf77d8ae..1c27c0d3eb9 100644
--- a/docs/content/operations/performance-faq.md
+++ b/docs/content/operations/performance-faq.md
@@ -64,7 +64,7 @@ Yes, using a `log4j2.xml` similar to the following causes some of the more chatt
<AsyncLogger name="io.druid.client.ServerInventoryView" level="debug" additivity="false">
<AppenderRef ref="Console"/>
</AsyncLogger>
- <AsyncLogger name ="com.metamx.http.client.pool.ChannelResourceFactory" level="info" additivity="false">
+ <AsyncLogger name ="io.druid.java.util.http.client.pool.ChannelResourceFactory" level="info" additivity="false">
<AppenderRef ref="Console"/>
</AsyncLogger>
<Root level="info">
diff --git a/docs/content/querying/dimensionspecs.md b/docs/content/querying/dimensionspecs.md
index 236e13b5a7a..19d080493fe 100644
--- a/docs/content/querying/dimensionspecs.md
+++ b/docs/content/querying/dimensionspecs.md
@@ -95,8 +95,6 @@ The default values are `replaceMissingValueWith = null` and `retainMissingValue
It is illegal to set `retainMissingValue = true` and also specify a `replaceMissingValueWith`.
-A property of `injective` specifies if optimizations can be used which assume there is no combining of multiple names into one. For example: If ABC123 is the only key that maps to SomeCompany, that can be optimized since it is a unique lookup. But if both ABC123 and DEF456 BOTH map to SomeCompany, then that is NOT a unique lookup. Setting this value to true and setting `retainMissingValue` to FALSE (the default) may cause undesired behavior.
-
A property `optimize` can be supplied to allow optimization of lookup based extraction filter (by default `optimize = true`).
The second kind where it is not possible to pass at query time due to their size, will be based on an external lookup table or resource that is already registered via configuration file or/and coordinator.
@@ -316,67 +314,38 @@ Example for the `__time` dimension:
JavaScript-based functionality is disabled by default. Please refer to the Druid <a href="../development/javascript.html">JavaScript programming guide</a> for guidelines about using Druid's JavaScript functionality, including instructions on how to enable it.
</div>
-### Lookup extraction function
+### Registered lookup extraction function
-Lookups are a concept in Druid where dimension values are (optionally) replaced with new values.
-For more documentation on using lookups, please see [here](../querying/lookups.html).
-Explicit lookups allow you to specify a set of keys and values to use when performing the extraction.
+Lookups are a concept in Druid where dimension values are (optionally) replaced with new values.
+For more documentation on using lookups, please see [Lookups](../querying/lookups.html).
+The "registeredLookup" extraction function lets you refer to a lookup that has been registered in the cluster-wide
+configuration.
-```json
-{
- "type":"lookup",
- "lookup":{
- "type":"map",
- "map":{"foo":"bar", "baz":"bat"}
- },
- "retainMissingValue":true,
- "injective":true
-}
-```
-
-```json
-{
- "type":"lookup",
- "lookup":{
- "type":"map",
- "map":{"foo":"bar", "baz":"bat"}
- },
- "retainMissingValue":false,
- "injective":false,
- "replaceMissingValueWith":"MISSING"
-}
-```
-
-```json
-{
- "type":"lookup",
- "lookup":{"type":"namespace","namespace":"some_lookup"},
- "replaceMissingValueWith":"Unknown",
- "injective":false
-}
-```
+An example:
```json
{
- "type":"lookup",
- "lookup":{"type":"namespace","namespace":"some_lookup"},
- "retainMissingValue":true,
- "injective":false
+ "type":"registeredLookup",
+ "lookup":"some_lookup_name",
+ "retainMissingValue":true
}
```
-A lookup can be of type `namespace` or `map`. A `map` lookup is passed as part of the query.
-A `namespace` lookup is populated on all the nodes which handle queries as per [lookups](../querying/lookups.html)
+A property of `retainMissingValue` and `replaceMissingValueWith` can be specified at query time to hint how to handle
+missing values. Setting `replaceMissingValueWith` to `""` has the same effect as setting it to `null` or omitting the
+property. Setting `retainMissingValue` to true will use the dimension's original value if it is not found in the lookup.
+The default values are `replaceMissingValueWith = null` and `retainMissingValue = false` which causes missing values to
+be treated as missing.
-A property of `retainMissingValue` and `replaceMissingValueWith` can be specified at query time to hint how to handle missing values. Setting `replaceMissingValueWith` to `""` has the same effect as setting it to `null` or omitting the property. Setting `retainMissingValue` to true will use the dimension's original value if it is not found in the lookup. The default values are `replaceMissingValueWith = null` and `retainMissingValue = false` which causes missing values to be treated as missing.
-
It is illegal to set `retainMissingValue = true` and also specify a `replaceMissingValueWith`.
-A property of `injective` specifies if optimizations can be used which assume there is no combining of multiple names into one. For example: If ABC123 is the only key that maps to SomeCompany, that can be optimized since it is a unique lookup. But if both ABC123 and DEF456 BOTH map to SomeCompany, then that is NOT a unique lookup. Setting this value to true and setting `retainMissingValue` to FALSE (the default) may cause undesired behavior.
+A property of `injective` can override the lookup's own sense of whether or not it is
+[injective](lookups.html#query-execution). If left unspecified, Druid will use the registered cluster-wide lookup
+configuration.
-A property `optimize` can be supplied to allow optimization of lookup based extraction filter (by default `optimize = true`).
+A property `optimize` can be supplied to allow optimization of lookup based extraction filter (by default `optimize = true`).
The optimization layer will run on the broker and it will rewrite the extraction filter as clause of selector filters.
-For instance the following filter
+For instance the following filter
```json
{
@@ -385,21 +354,16 @@ For instance the following filter
"dimension": "product",
"value": "bar_1",
"extractionFn": {
- "type": "lookup",
+ "type": "registeredLookup",
"optimize": true,
- "lookup": {
- "type": "map",
- "map": {
- "product_1": "bar_1",
- "product_3": "bar_1"
- }
- }
+ "lookup": "some_lookup_name"
}
}
}
```
-will be rewritten as
+will be rewritten as the following simpler query, assuming a lookup that maps "product_1" and "product_3" to the value
+"bar_1":
```json
{
@@ -425,30 +389,49 @@ will be rewritten as
}
```
-A null dimension value can be mapped to a specific value by specifying the empty string as the key.
+A null dimension value can be mapped to a specific value by specifying the empty string as the key in your lookup file.
This allows distinguishing between a null dimension and a lookup resulting in a null.
For example, specifying `{"":"bar","bat":"baz"}` with dimension values `[null, "foo", "bat"]` and replacing missing values with `"oof"` will yield results of `["bar", "oof", "baz"]`.
Omitting the empty string key will cause the missing value to take over. For example, specifying `{"bat":"baz"}` with dimension values `[null, "foo", "bat"]` and replacing missing values with `"oof"` will yield results of `["oof", "oof", "baz"]`.
-### Registered Lookup Extraction Function
+### Inline lookup extraction function
-While it is recommended that the [lookup dimension spec](#lookup-dimensionspecs) be used whenever possible, any lookup that is registered for use as a lookup dimension spec can be used as a dimension extraction.
+Lookups are a concept in Druid where dimension values are (optionally) replaced with new values.
+For more documentation on using lookups, please see [Lookups](../querying/lookups.html).
+The "lookup" extraction function lets you specify an inline lookup map without registering one in the cluster-wide
+configuration.
-The specification for dimension extraction using dimension specification named lookups is formatted as per the following example:
+Examples:
```json
{
- "type":"registeredLookup",
- "lookup":"some_lookup_name",
+ "type":"lookup",
+ "lookup":{
+ "type":"map",
+ "map":{"foo":"bar", "baz":"bat"}
+ },
"retainMissingValue":true,
- "injective":false
+ "injective":true
+}
+```
+
+```json
+{
+ "type":"lookup",
+ "lookup":{
+ "type":"map",
+ "map":{"foo":"bar", "baz":"bat"}
+ },
+ "retainMissingValue":false,
+ "injective":false,
+ "replaceMissingValueWith":"MISSING"
}
```
-All the flags for [lookup extraction function](#lookup-extraction-function) apply here as well.
+The inline lookup should be of type `map`.
-In general, the dimension specification should be used. This dimension **extraction** implementation is made available for testing, validation, and transitioning from dimension extraction to the dimension specification style lookups.
-There is also a chance that a feature uses dimension extraction in such a way that it is not applied to dimension specification lookups. Such a scenario should be brought to the attention of the development mailing list.
+The properties `retainMissingValue`, `replaceMissingValueWith`, `injective`, and `optimize` behave similarly to the
+[registered lookup extraction function](#registered-lookup-extraction-function).
### Cascade Extraction Function
diff --git a/docs/content/querying/lookups.md b/docs/content/querying/lookups.md
index 616b602eb3b..771c9adfb74 100644
--- a/docs/content/querying/lookups.md
+++ b/docs/content/querying/lookups.md
@@ -8,15 +8,17 @@ layout: doc_page
Lookups are an <a href="../development/experimental.html">experimental</a> feature.
</div>
-Lookups are a concept in Druid where dimension values are (optionally) replaced with new values.
-See [dimension specs](../querying/dimensionspecs.html) for more information. For the purpose of these documents,
-a "key" refers to a dimension value to match, and a "value" refers to its replacement.
-So if you wanted to rename `appid-12345` to `Super Mega Awesome App` then the key would be `appid-12345` and the value
-would be `Super Mega Awesome App`.
-
-It is worth noting that lookups support use cases where keys map to unique values (injective) such as a country code and
-a country name, and also supports use cases where multiple IDs map to the same value, e.g. multiple app-ids belonging to
-a single account manager.
+Lookups are a concept in Druid where dimension values are (optionally) replaced with new values, allowing join-like
+functionality. Applying lookups in Druid is similar to joining a dimension table in a data warehouse. See
+[dimension specs](../querying/dimensionspecs.html) for more information. For the purpose of these documents, a "key"
+refers to a dimension value to match, and a "value" refers to its replacement. So if you wanted to map
+`appid-12345` to `Super Mega Awesome App` then the key would be `appid-12345` and the value would be
+`Super Mega Awesome App`.
+
+It is worth noting that lookups support not just use cases where keys map one-to-one to unique values, such as country
+code and country name, but also support use cases where multiple IDs map to the same value, e.g. multiple app-ids
+mapping to a single account manager. When lookups are one-to-one, Druid is able to apply additional optimizations at
+query time; see [Query execution](#query-execution) below for more details.
Lookups do not have history. They always use the current data. This means that if the chief account manager for a
particular app-id changes, and you issue a query with a lookup to store the app-id to account manager relationship,
@@ -33,6 +35,38 @@ Other lookup types are available as extensions, including:
- Globally cached lookups from local files, remote URIs, or JDBC through [lookups-cached-global](../development/extensions-core/lookups-cached-global.html).
- Globally cached lookups from a Kafka topic through [kafka-extraction-namespace](../development/extensions-core/kafka-extraction-namespace.html).
+Query Execution
+---------------
+When executing an aggregation query involving lookups, Druid can decide to apply lookups either while scanning and
+aggregating rows, or to apply them after aggregation is complete. It is more efficient to apply lookups after
+aggregation is complete, so Druid will do this if it can. Druid decides this by checking if the lookup is marked
+as "injective" or not. In general, you should set this property for any lookup that is naturally one-to-one, to allow
+Druid to run your queries as fast as possible.
+
+Injective lookups should include _all_ possible keys that may show up in your dataset, and should also map all keys to
+_unique values_. This matters because non-injective lookups may map different keys to the same value, which must be
+accounted for during aggregation, lest query results contain two result values that should have been aggregated into
+one.
+
+This lookup is injective (assuming it contains all possible keys from your data):
+
+```
+1 -> Foo
+2 -> Bar
+3 -> Billy
+```
+
+But this one is not, since both "2" and "3" map to the same key:
+
+```
+1 -> Foo
+2 -> Bar
+3 -> Bar
+```
+
+To tell Druid that your lookup is injective, you must specify `"injective" : true` in the lookup configuration. Druid
+will not detect this automatically.
+
Dynamic Configuration
---------------------
<div class="note caution">
diff --git a/docs/content/toc.md b/docs/content/toc.md
index d18de0e7c73..b272be61d73 100644
--- a/docs/content/toc.md
+++ b/docs/content/toc.md
@@ -3,12 +3,20 @@ layout: toc
---
## Getting Started
- * [Concepts](/docs/VERSION/design/)
- * [Quickstart](/docs/VERSION/tutorials/quickstart.html)
- * [Loading Data](/docs/VERSION/tutorials/ingestion.html)
- * [Loading from Files](/docs/VERSION/tutorials/tutorial-batch.html)
- * [Loading from Streams](/docs/VERSION/tutorials/tutorial-streams.html)
- * [Loading from Kafka](/docs/VERSION/tutorials/tutorial-kafka.html)
+ * [Concepts](/docs/VERSION/design/)
+ * [Quickstart](/docs/VERSION/tutorials/index.html)
+ * [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html)
+ * [Tutorial: Loading stream data from Kafka](/docs/VERSION/tutorials/tutorial-kafka.html)
+ * [Tutorial: Loading a file using Hadoop](/docs/VERSION/tutorials/tutorial-batch-hadoop.html)
+ * [Tutorial: Loading stream data using HTTP push](/docs/VERSION/tutorials/tutorial-tranquility.html)
+ * [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html)
+ * [Further tutorials](/docs/VERSION/tutorials/advanced.html)
+ * [Tutorial: Rollup](/docs/VERSION/tutorials/rollup.html)
+ * [Tutorial: Configuring retention](/docs/VERSION/tutorials/tutorial-retention.html)
+ * [Tutorial: Updating existing data](/docs/VERSION/tutorials/tutorial-update-data.html)
+ * [Tutorial: Compacting segments](/docs/VERSION/tutorials/tutorial-compaction.html)
+ * [Tutorial: Deleting data](/docs/VERSION/tutorials/tutorial-delete-data.html)
+ * [Tutorial: Writing your own ingestion specs](/docs/VERSION/tutorials/tutorial-ingestion-spec.html)
* [Clustering](/docs/VERSION/tutorials/cluster.html)
## Data Ingestion
@@ -90,6 +98,7 @@ layout: toc
* [Broker](/docs/VERSION/configuration/broker.html)
* [Realtime](/docs/VERSION/configuration/realtime.html)
* [Configuring Logging](/docs/VERSION/configuration/logging.html)
+ * [Configuring Authentication and Authorization](/docs/VERSION/configuration/auth.html)
## Development
* [Overview](/docs/VERSION/development/overview.html)
diff --git a/docs/content/tutorials/cluster.md b/docs/content/tutorials/cluster.md
index ac13b594dae..68037d400ac 100644
--- a/docs/content/tutorials/cluster.md
+++ b/docs/content/tutorials/cluster.md
@@ -46,7 +46,7 @@ Very large clusters should consider selecting larger servers.
We recommend running your favorite Linux distribution. You will also need:
- * Java 8 or better
+ * Java 8
Your OS package manager should be able to help for both Java. If your Ubuntu-based OS
does not have a recent enough version of Java, WebUpd8 offers [packages for those
@@ -291,9 +291,9 @@ rsync -az druid-#{DRUIDVERSION}/ COORDINATION_SERVER:druid-#{DRUIDVERSION}/
Log on to your coordination server and install Zookeeper:
```bash
-curl http://www.gtlib.gatech.edu/pub/apache/zookeeper/zookeeper-3.4.10/zookeeper-3.4.10.tar.gz -o zookeeper-3.4.10.tar.gz
-tar -xzf zookeeper-3.4.10.tar.gz
-cd zookeeper-3.4.10
+curl http://www.gtlib.gatech.edu/pub/apache/zookeeper/zookeeper-3.4.11/zookeeper-3.4.11.tar.gz -o zookeeper-3.4.11.tar.gz
+tar -xzf zookeeper-3.4.11.tar.gz
+cd zookeeper-3.4.11
cp conf/zoo_sample.cfg conf/zoo.cfg
./bin/zkServer.sh start
```
diff --git a/docs/content/tutorials/img/tutorial-batch-01.png b/docs/content/tutorials/img/tutorial-batch-01.png
new file mode 100644
index 00000000000..6c2fdaa804d
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-batch-01.png differ
diff --git a/docs/content/tutorials/img/tutorial-compaction-01.png b/docs/content/tutorials/img/tutorial-compaction-01.png
new file mode 100644
index 00000000000..1be9d00dbe0
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-compaction-01.png differ
diff --git a/docs/content/tutorials/img/tutorial-compaction-02.png b/docs/content/tutorials/img/tutorial-compaction-02.png
new file mode 100644
index 00000000000..5467635b8b0
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-compaction-02.png differ
diff --git a/docs/content/tutorials/img/tutorial-deletion-01.png b/docs/content/tutorials/img/tutorial-deletion-01.png
new file mode 100644
index 00000000000..d209b8c753c
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-deletion-01.png differ
diff --git a/docs/content/tutorials/img/tutorial-deletion-02.png b/docs/content/tutorials/img/tutorial-deletion-02.png
new file mode 100644
index 00000000000..60959ed1330
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-deletion-02.png differ
diff --git a/docs/content/tutorials/img/tutorial-retention-00.png b/docs/content/tutorials/img/tutorial-retention-00.png
new file mode 100644
index 00000000000..99c4ca8f68e
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-retention-00.png differ
diff --git a/docs/content/tutorials/img/tutorial-retention-01.png b/docs/content/tutorials/img/tutorial-retention-01.png
new file mode 100644
index 00000000000..49589753d4b
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-retention-01.png differ
diff --git a/docs/content/tutorials/img/tutorial-retention-02.png b/docs/content/tutorials/img/tutorial-retention-02.png
new file mode 100644
index 00000000000..a317116b933
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-retention-02.png differ
diff --git a/docs/content/tutorials/img/tutorial-retention-03.png b/docs/content/tutorials/img/tutorial-retention-03.png
new file mode 100644
index 00000000000..614f872a505
Binary files /dev/null and b/docs/content/tutorials/img/tutorial-retention-03.png differ
diff --git a/docs/content/tutorials/index.md b/docs/content/tutorials/index.md
new file mode 100644
index 00000000000..3b9b43d6fca
--- /dev/null
+++ b/docs/content/tutorials/index.md
@@ -0,0 +1,181 @@
+---
+layout: doc_page
+---
+
+# Druid Quickstart
+
+In this quickstart, we will download Druid, set it up on a single machine, load some data, and query the data.
+
+## Prerequisites
+
+You will need:
+
+ * Java 8 or higher
+ * Linux, Mac OS X, or other Unix-like OS (Windows is not supported)
+ * 8G of RAM
+ * 2 vCPUs
+
+On Mac OS X, you can use [Oracle's JDK
+8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) to install
+Java.
+
+On Linux, your OS package manager should be able to help for Java. If your Ubuntu-
+based OS does not have a recent enough version of Java, WebUpd8 offers [packages for those
+OSes](http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html).
+
+## Getting started
+
+To install Druid, issue the following commands in your terminal:
+
+```bash
+curl -O http://static.druid.io/artifacts/releases/druid-#{DRUIDVERSION}-bin.tar.gz
+tar -xzf druid-#{DRUIDVERSION}-bin.tar.gz
+cd druid-#{DRUIDVERSION}
+```
+
+In the package, you should find:
+
+* `LICENSE` - the license files.
+* `bin/` - scripts useful for this quickstart.
+* `conf/*` - template configurations for a clustered setup.
+* `conf-quickstart/*` - configurations for this quickstart.
+* `extensions/*` - all Druid extensions.
+* `hadoop-dependencies/*` - Druid Hadoop dependencies.
+* `lib/*` - all included software packages for core Druid.
+* `quickstart/*` - files useful for this quickstart.
+
+## Download tutorial example files
+
+Before proceeding, please download the [tutorial examples package](../tutorials/tutorial-examples.tar.gz).
+
+This tarball contains sample data and ingestion specs that will be used in the tutorials.
+
+```
+curl -O http://druid.io/docs/#{DRUIDVERSION}/tutorials/tutorial-examples.tar.gz
+tar zxvf tutorial-examples.tar.gz
+```
+
+## Start up Zookeeper
+
+Druid currently has a dependency on [Apache ZooKeeper](http://zookeeper.apache.org/) for distributed coordination. You'll
+need to download and run Zookeeper.
+
+```bash
+curl http://www.gtlib.gatech.edu/pub/apache/zookeeper/zookeeper-3.4.10/zookeeper-3.4.10.tar.gz -o zookeeper-3.4.10.tar.gz
+tar -xzf zookeeper-3.4.10.tar.gz
+cd zookeeper-3.4.10
+cp conf/zoo_sample.cfg conf/zoo.cfg
+./bin/zkServer.sh start
+```
+
+## Start up Druid services
+
+With Zookeeper running, return to the druid-#{DRUIDVERSION} directory. In that directory, issue the command:
+
+```bash
+bin/init
+```
+
+This will setup up some directories for you. Next, you can start up the Druid processes in different terminal windows.
+This tutorial runs every Druid process on the same system. In a large distributed production cluster,
+many of these Druid processes can still be co-located together.
+
+```bash
+java `cat examples/conf/druid/coordinator/jvm.config | xargs` -cp "examples/conf/druid/_common:examples/conf/druid/_common/hadoop-xml:examples/conf/druid/coordinator:lib/*" io.druid.cli.Main server coordinator
+java `cat examples/conf/druid/overlord/jvm.config | xargs` -cp "examples/conf/druid/_common:examples/conf/druid/_common/hadoop-xml:examples/conf/druid/overlord:lib/*" io.druid.cli.Main server overlord
+java `cat examples/conf/druid/historical/jvm.config | xargs` -cp "examples/conf/druid/_common:examples/conf/druid/_common/hadoop-xml:examples/conf/druid/historical:lib/*" io.druid.cli.Main server historical
+java `cat examples/conf/druid/middleManager/jvm.config | xargs` -cp "examples/conf/druid/_common:examples/conf/druid/_common/hadoop-xml:examples/conf/druid/middleManager:lib/*" io.druid.cli.Main server middleManager
+java `cat examples/conf/druid/broker/jvm.config | xargs` -cp "examples/conf/druid/_common:examples/conf/druid/_common/hadoop-xml:examples/conf/druid/broker:lib/*" io.druid.cli.Main server broker
+```
+
+Once every service has started, you are now ready to load data.
+
+### Resetting cluster state
+
+All persistent state such as the cluster metadata store and segments for the services will be kept in the `var` directory under the druid-#{DRUIDVERSION} package root.
+
+Later on, if you'd like to stop the services, CTRL-C to exit from the running java processes. If you
+want a clean start after stopping the services, delete the `log` and `var` directory and run the `init` script again.
+
+From the druid-#{DRUIDVERSION} directory:
+```
+rm -rf log
+rm -rf var
+bin/init
+```
+
+## Loading Data
+
+### Tutorial Dataset
+
+For the following data loading tutorials, we have included a sample data file containing Wikipedia page edit events that occurred on 2015-09-12.
+
+This sample data is located at `quickstart/wikipedia-2015-09-12-sampled.json.gz` from the Druid package root. The page edit events are stored as JSON objects in a text file.
+
+The sample data has the following columns, and an example event is shown below:
+
+ * added
+ * channel
+ * cityName
+ * comment
+ * countryIsoCode
+ * countryName
+ * deleted
+ * delta
+ * isAnonymous
+ * isMinor
+ * isNew
+ * isRobot
+ * isUnpatrolled
+ * metroCode
+ * namespace
+ * page
+ * regionIsoCode
+ * regionName
+ * user
+
+```
+{
+ "timestamp":"2015-09-12T20:03:45.018Z",
+ "channel":"#en.wikipedia",
+ "namespace":"Main"
+ "page":"Spider-Man's powers and equipment",
+ "user":"foobar",
+ "comment":"/* Artificial web-shooters */",
+ "cityName":"New York",
+ "regionName":"New York",
+ "regionIsoCode":"NY",
+ "countryName":"United States",
+ "countryIsoCode":"US",
+ "isAnonymous":false,
+ "isNew":false,
+ "isMinor":false,
+ "isRobot":false,
+ "isUnpatrolled":false,
+ "added":99,
+ "delta":99,
+ "deleted":0,
+}
+```
+
+The following tutorials demonstrate various methods of loading data into Druid, including both batch and streaming use cases.
+
+### [Tutorial: Loading a file](./tutorial-batch.html)
+
+This tutorial demonstrates how to perform a batch file load, using Druid's native batch ingestion.
+
+### [Tutorial: Loading stream data from Kafka](../tutorial-kafka.html)
+
+This tutorial demonstrates how to load streaming data from a Kafka topic.
+
+### [Tutorial: Loading a file using Hadoop](../tutorial-batch-hadoop.html)
+
+This tutorial demonstrates how to perform a batch file load, using a remote Hadoop cluster.
+
+### [Tutorial: Loading data using Tranquility](../tutorial-tranquility.html)
+
+This tutorial demonstrates how to load streaming data by pushing events to Druid using the Tranquility service.
+
+### [Tutorial: Writing your own ingestion spec](../tutorial-ingestion-spec.html)
+
+This tutorial demonstrates how to write a new ingestion spec and use it to load data.
\ No newline at end of file
diff --git a/docs/content/tutorials/ingestion.md b/docs/content/tutorials/ingestion.md
deleted file mode 100644
index ab2844fe269..00000000000
--- a/docs/content/tutorials/ingestion.md
+++ /dev/null
@@ -1,42 +0,0 @@
----
-layout: doc_page
----
-
-# Loading Data
-
-## Choosing an ingestion method
-
-Druid supports streaming (real-time) and file-based (batch) ingestion methods. The most
-popular configurations are:
-
-- [Files](../ingestion/batch-ingestion.html) - Load data from HDFS, S3, local files, or any supported Hadoop
-filesystem in batches. We recommend this method if your dataset is already in flat files.
-
-- [Stream push](../ingestion/stream-ingestion.html#stream-push) - Push a data stream into Druid in real-time
-using [Tranquility](http://github.com/druid-io/tranquility), a client library for sending streams
-to Druid. We recommend this method if your dataset originates in a streaming system like Kafka,
-Storm, Spark Streaming, or your own system.
-
-- [Stream pull](../ingestion/stream-ingestion.html#stream-pull) - Pull a data stream directly from an external
-data source into Druid using Realtime Nodes.
-
-## Getting started
-
-The easiest ways to get started with loading your own data are the three included tutorials.
-
-- [Files-based tutorial](tutorial-batch.html) showing you how to load files from your local disk.
-- [Streams-based tutorial](tutorial-streams.html) showing you how to push data over HTTP.
-- [Kafka-based tutorial](tutorial-kafka.html) showing you how to load data from Kafka.
-
-## Hybrid batch/streaming
-
-You can combine batch and streaming methods in a hybrid batch/streaming architecture. In a hybrid architecture,
-you use a streaming method to do initial ingestion, and then periodically re-ingest older data in batch mode
-(typically every few hours, or nightly). When Druid re-ingests data for a time range, the new data automatically
-replaces the data from the earlier ingestion.
-
-All streaming ingestion methods currently supported by Druid do introduce the possibility of dropped or duplicated
-messages in certain failure scenarios, and batch re-ingestion eliminates this potential source of error for
-historical data.
-
-Batch re-ingestion also gives you the option to re-ingest your data if you needed to revise it for any reason.
diff --git a/docs/content/tutorials/quickstart.md b/docs/content/tutorials/quickstart.md
deleted file mode 100644
index 4d35b392cc1..00000000000
--- a/docs/content/tutorials/quickstart.md
+++ /dev/null
@@ -1,243 +0,0 @@
----
-layout: doc_page
----
-
-# Druid Quickstart
-
-In this quickstart, we will download Druid, set up it up on a single machine, load some data, and query the data.
-
-## Prerequisites
-
-You will need:
-
- * Java 8 or higher
- * Linux, Mac OS X, or other Unix-like OS (Windows is not supported)
- * 8G of RAM
- * 2 vCPUs
-
-On Mac OS X, you can use [Oracle's JDK
-8](http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html) to install
-Java.
-
-On Linux, your OS package manager should be able to help for Java. If your Ubuntu-
-based OS does not have a recent enough version of Java, WebUpd8 offers [packages for those
-OSes](http://www.webupd8.org/2012/09/install-oracle-java-8-in-ubuntu-via-ppa.html).
-
-## Getting started
-
-To install Druid, issue the following commands in your terminal:
-
-```bash
-curl -O http://static.druid.io/artifacts/releases/druid-#{DRUIDVERSION}-bin.tar.gz
-tar -xzf druid-#{DRUIDVERSION}-bin.tar.gz
-cd druid-#{DRUIDVERSION}
-```
-
-In the package, you should find:
-
-* `LICENSE` - the license files.
-* `bin/` - scripts useful for this quickstart.
-* `conf/*` - template configurations for a clustered setup.
-* `conf-quickstart/*` - configurations for this quickstart.
-* `extensions/*` - all Druid extensions.
-* `hadoop-dependencies/*` - Druid Hadoop dependencies.
-* `lib/*` - all included software packages for core Druid.
-* `quickstart/*` - files useful for this quickstart.
-
-## Start up Zookeeper
-
-Druid currently has a dependency on [Apache ZooKeeper](http://zookeeper.apache.org/) for distributed coordination. You'll
-need to download and run Zookeeper.
-
-```bash
-curl http://www.gtlib.gatech.edu/pub/apache/zookeeper/zookeeper-3.4.10/zookeeper-3.4.10.tar.gz -o zookeeper-3.4.10.tar.gz
-tar -xzf zookeeper-3.4.10.tar.gz
-cd zookeeper-3.4.10
-cp conf/zoo_sample.cfg conf/zoo.cfg
-./bin/zkServer.sh start
-```
-
-## Start up Druid services
-
-With Zookeeper running, return to the druid-#{DRUIDVERSION} directory. In that directory, issue the command:
-
-```bash
-bin/init
-```
-
-This will setup up some directories for you. Next, you can start up the Druid processes in different terminal windows.
-This tutorial runs every Druid process on the same system. In a large distributed production cluster,
-many of these Druid processes can still be co-located together.
-
-```bash
-java `cat conf-quickstart/druid/historical/jvm.config | xargs` -cp "conf-quickstart/druid/_common:conf-quickstart/druid/historical:lib/*" io.druid.cli.Main server historical
-java `cat conf-quickstart/druid/broker/jvm.config | xargs` -cp "conf-quickstart/druid/_common:conf-quickstart/druid/broker:lib/*" io.druid.cli.Main server broker
-java `cat conf-quickstart/druid/coordinator/jvm.config | xargs` -cp "conf-quickstart/druid/_common:conf-quickstart/druid/coordinator:lib/*" io.druid.cli.Main server coordinator
-java `cat conf-quickstart/druid/overlord/jvm.config | xargs` -cp "conf-quickstart/druid/_common:conf-quickstart/druid/overlord:lib/*" io.druid.cli.Main server overlord
-java `cat conf-quickstart/druid/middleManager/jvm.config | xargs` -cp "conf-quickstart/druid/_common:conf-quickstart/druid/middleManager:lib/*" io.druid.cli.Main server middleManager
-```
-
-You should see a log message printed out for each service that starts up.
-
-Later on, if you'd like to stop the services, CTRL-C to exit from the running java processes. If you
-want a clean start after stopping the services, delete the `var` directory and run the `init` script again.
-
-Once every service has started, you are now ready to load data.
-
-## Load batch data
-
-We've included a sample of Wikipedia edits from September 12, 2015 to get you started.
-
-<div class="note info">
-This section shows you how to load data in batches, but you can skip ahead to learn how to <a href="quickstart.html#load-streaming-data">load
-streams in real-time</a>. Druid's streaming ingestion can load data
-with virtually no delay between events occurring and being available for queries.
-</div>
-
-The [dimensions](https://en.wikipedia.org/wiki/Dimension_%28data_warehouse%29) (attributes you can
-filter and split on) in the Wikipedia dataset, other than time, are:
-
- * channel
- * cityName
- * comment
- * countryIsoCode
- * countryName
- * isAnonymous
- * isMinor
- * isNew
- * isRobot
- * isUnpatrolled
- * metroCode
- * namespace
- * page
- * regionIsoCode
- * regionName
- * user
-
-The [measures](https://en.wikipedia.org/wiki/Measure_%28data_warehouse%29), or *metrics* as they are known in Druid (values you can aggregate)
-in the Wikipedia dataset are:
-
- * count
- * added
- * deleted
- * delta
- * user_unique
-
-To load this data into Druid, you can submit an *ingestion task* pointing to the file. We've included
-a task that loads the `wikiticker-2015-09-12-sampled.json` file included in the archive. To submit
-this task, POST it to Druid in a new terminal window from the druid-#{DRUIDVERSION} directory:
-
-```bash
-curl -X 'POST' -H 'Content-Type:application/json' -d @quickstart/wikiticker-index.json localhost:8090/druid/indexer/v1/task
-```
-
-Which will print the ID of the task if the submission was successful:
-
-```bash
-{"task":"index_hadoop_wikipedia_2013-10-09T21:30:32.802Z"}
-```
-
-To view the status of your ingestion task, go to your overlord console:
-[http://localhost:8090/console.html](http://localhost:8090/console.html). You can refresh the console periodically, and after
-the task is successful, you should see a "SUCCESS" status for the task.
-
-After your ingestion task finishes, the data will be loaded by historical nodes and available for
-querying within a minute or two. You can monitor the progress of loading your data in the
-coordinator console, by checking whether there is a datasource "wikiticker" with a blue circle
-indicating "fully available": [http://localhost:8081/#/](http://localhost:8081/#/).
-
-Once the data is fully available, you can immediately query it— to see how, skip to the [Query
-data](#query-data) section below. Or, continue to the [Load your own data](#load-your-own-data)
-section if you'd like to load a different dataset.
-
-## Load streaming data
-
-To load streaming data, we are going to push events into Druid
-over a simple HTTP API. To do this we will use [Tranquility], a high level data producer
-library for Druid.
-
-To download Tranquility, issue the following commands in your terminal:
-
-```bash
-curl -O http://static.druid.io/tranquility/releases/tranquility-distribution-0.8.0.tgz
-tar -xzf tranquility-distribution-0.8.0.tgz
-cd tranquility-distribution-0.8.0
-```
-
-We've included a configuration file in `conf-quickstart/tranquility/server.json` as part of the Druid distribution
-for a *metrics* datasource. We're going to start the Tranquility server process, which can be used to push events
-directly to Druid.
-
-``` bash
-bin/tranquility server -configFile <path_to_druid_distro>/conf-quickstart/tranquility/server.json
-```
-
-<div class="note info">
-This section shows you how to load data using Tranquility Server, but Druid also supports a wide
-variety of <a href="../ingestion/stream-ingestion.html#stream-push">other streaming ingestion options</a>, including from
-popular streaming systems like Kafka, Storm, Samza, and Spark Streaming.
-</div>
-
-The [dimensions](https://en.wikipedia.org/wiki/Dimension_%28data_warehouse%29) (attributes you can
-filter and split on) for this datasource are flexible. It's configured for *schemaless dimensions*,
-meaning it will accept any field in your JSON input as a dimension.
-
-The metrics (also called
-[measures](https://en.wikipedia.org/wiki/Measure_%28data_warehouse%29); values
-you can aggregate) in this datasource are:
-
- * count
- * value_sum (derived from `value` in the input)
- * value_min (derived from `value` in the input)
- * value_max (derived from `value` in the input)
-
-We've included a script that can generate some random sample metrics to load into this datasource.
-To use it, simply run in your Druid distribution repository:
-
-```bash
-bin/generate-example-metrics | curl -XPOST -H'Content-Type: application/json' --data-binary @- http://localhost:8200/v1/post/metrics
-```
-
-Which will print something like:
-
-```
-{"result":{"received":25,"sent":25}}
-```
-
-This indicates that the HTTP server received 25 events from you, and sent 25 to Druid. Note that
-this may take a few seconds to finish the first time you run it, as Druid resources must be
-allocated to the ingestion task. Subsequent POSTs should complete quickly.
-
-Once the data is sent to Druid, you can immediately [query it](#query-data).
-
-## Query data
-
-### Direct Druid queries
-
-Druid supports a rich [family of JSON-based
-queries](../querying/querying.html). We've included an example topN query
-in `quickstart/wikiticker-top-pages.json` that will find the most-edited articles in this dataset:
-
-```bash
-curl -L -H'Content-Type: application/json' -XPOST --data-binary @quickstart/wikiticker-top-pages.json http://localhost:8082/druid/v2/?pretty
-```
-
-## Visualizing data
-
-Druid is ideal for power user-facing analytic applications. There are a number of different open source applications to
-visualize and explore data in Druid. We recommend trying [Pivot](https://github.com/implydata/pivot),
-[Superset](https://github.com/airbnb/superset), or [Metabase](https://github.com/metabase/metabase) to start
-visualizing the data you just ingested.
-
-If you installed Pivot for example, you should be able to view your data in your browser at [localhost:9090](http://localhost:9090/).
-
-### SQL and other query libraries
-
-There are many more query tools for Druid than we've included here, including SQL
-engines, and libraries for various languages like Python and Ruby. Please see [the list of
-libraries](../development/libraries.html) for more information.
-
-## Clustered setup
-
-This quickstart sets you up with all services running on a single machine. The next step is to [load
-your own data](ingestion.html). Or, you can skip ahead to [running a distributed cluster](cluster.html).
diff --git a/docs/content/tutorials/tutorial-batch-hadoop.md b/docs/content/tutorials/tutorial-batch-hadoop.md
new file mode 100644
index 00000000000..821f6eac18f
--- /dev/null
+++ b/docs/content/tutorials/tutorial-batch-hadoop.md
@@ -0,0 +1,250 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Load batch data using Hadoop
+
+This tutorial shows you how to load data files into Druid using a remote Hadoop cluster.
+
+For this tutorial, we'll assume that you've already completed the previous [batch ingestion tutorial](tutorial-batch.html) using Druid's native batch ingestion system.
+
+## Install Docker
+
+This tutorial requires [Docker](https://docs.docker.com/install/) to be installed on the tutorial machine.
+
+Once the Docker install is complete, please proceed to the next steps in the tutorial.
+
+## Build the Hadoop docker image
+
+For this tutorial, we've provided a Dockerfile for a Hadoop 2.7.3 cluster, which we'll use to run the batch indexing task.
+
+This Dockerfile and related files are located at `examples/hadoop/docker`.
+
+From the druid-${DRUIDVERSION} package root, run the following commands to build a Docker image named "druid-hadoop-demo" with version tag "2.7.3":
+
+```
+cd examples/hadoop/docker
+docker build -t druid-hadoop-demo:2.7.3 .
+```
+
+This will start building the Hadoop image. Once the image build is done, you should see the message `Successfully tagged druid-hadoop-demo:2.7.3` printed to the console.
+
+## Setup the Hadoop docker cluster
+
+### Create temporary shared directory
+
+We'll need a shared folder between the host and the Hadoop container for transferring some files.
+
+Let's create some folders under `/tmp`, we will use these later when starting the Hadoop container:
+
+```
+mkdir -p /tmp/shared
+mkdir -p /tmp/shared/hadoop-xml
+```
+
+### Configure /etc/hosts
+
+On the host machine, add the following entry to `/etc/hosts`:
+
+```
+127.0.0.1 druid-hadoop-demo
+```
+
+### Start the Hadoop container
+
+Once the `/tmp/shared` folder has been created and the `etc/hosts` entry has been added, run the following command to start the Hadoop container.
+
+```
+docker run -it -h druid-hadoop-demo -p 50010:50010 -p 50020:50020 -p 50075:50075 -p 50090:50090 -p 8020:8020 -p 10020:10020 -p 19888:19888 -p 8030:8030 -p 8031:8031 -p 8032:8032 -p 8033:8033 -p 8040:8040 -p 8042:8042 -p 8088:8088 -p 8443:8443 -p 2049:2049 -p 9000:9000 -p 49707:49707 -p 2122:2122 -p 34455:34455 -v /tmp/shared:/shared druid-hadoop-demo:2.7.3 /etc/bootstrap.sh -bash
+```
+
+Once the container is started, your terminal will attach to a bash shell running inside the container:
+
+```
+Starting sshd: [ OK ]
+18/07/26 17:27:15 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
+Starting namenodes on [druid-hadoop-demo]
+druid-hadoop-demo: starting namenode, logging to /usr/local/hadoop/logs/hadoop-root-namenode-druid-hadoop-demo.out
+localhost: starting datanode, logging to /usr/local/hadoop/logs/hadoop-root-datanode-druid-hadoop-demo.out
+Starting secondary namenodes [0.0.0.0]
+0.0.0.0: starting secondarynamenode, logging to /usr/local/hadoop/logs/hadoop-root-secondarynamenode-druid-hadoop-demo.out
+18/07/26 17:27:31 WARN util.NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
+starting yarn daemons
+starting resourcemanager, logging to /usr/local/hadoop/logs/yarn--resourcemanager-druid-hadoop-demo.out
+localhost: starting nodemanager, logging to /usr/local/hadoop/logs/yarn-root-nodemanager-druid-hadoop-demo.out
+starting historyserver, logging to /usr/local/hadoop/logs/mapred--historyserver-druid-hadoop-demo.out
+bash-4.1#
+```
+
+The `Unable to load native-hadoop library for your platform... using builtin-java classes where applicable` warning messages can be safely ignored.
+
+### Copy input data to the Hadoop container
+
+From the druid-${DRUIDVERSION} package root on the host, copy the `quickstart/wikiticker-2015-09-12-sampled.json.gz` sample data to the shared folder:
+
+```
+cp quickstart/wikiticker-2015-09-12-sampled.json.gz /tmp/shared/wikiticker-2015-09-12-sampled.json.gz
+```
+
+### Setup HDFS directories
+
+In the Hadoop container's shell, run the following commands to setup the HDFS directories needed by this tutorial and copy the input data to HDFS.
+
+```
+cd /usr/local/hadoop/bin
+./hadoop fs -mkdir /druid
+./hadoop fs -mkdir /druid/segments
+./hadoop fs -mkdir /quickstart
+./hadoop fs -chmod 777 /druid
+./hadoop fs -chmod 777 /druid/segments
+./hadoop fs -chmod 777 /quickstart
+./hadoop fs -chmod -R 777 /tmp
+./hadoop fs -chmod -R 777 /user
+./hadoop fs -put /shared/wikiticker-2015-09-12-sampled.json.gz /quickstart/wikiticker-2015-09-12-sampled.json.gz
+```
+
+If you encounter namenode errors such as `mkdir: Cannot create directory /druid. Name node is in safe mode.` when running this command, the Hadoop container is not finished initializing. When this occurs, wait a couple of minutes and retry the commands.
+
+## Configure Druid to use Hadoop
+
+Some additional steps are needed to configure the Druid cluster for Hadoop batch indexing.
+
+### Copy Hadoop configuration to Druid classpath
+
+From the Hadoop container's shell, run the following command to copy the Hadoop .xml configuration files to the shared folder:
+
+```
+cp /usr/local/hadoop/etc/hadoop/*.xml /shared/hadoop-xml
+```
+
+From the host machine, run the following, where {PATH_TO_DRUID} is replaced by the path to the Druid package.
+
+```
+cp /tmp/shared/hadoop-xml/*.xml {PATH_TO_DRUID}/examples/conf/druid/_common/hadoop-xml/
+```
+
+### Update Druid segment and log storage
+
+In your favorite text editor, open `examples/conf/druid/_common/common.runtime.properties`, and make the following edits:
+
+#### Disable local deep storage and enable HDFS deep stroage
+
+```
+#
+# Deep storage
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+#druid.storage.type=local
+#druid.storage.storageDirectory=var/druid/segments
+
+# For HDFS:
+druid.storage.type=hdfs
+druid.storage.storageDirectory=/druid/segments
+```
+
+
+#### Disable local log storage and enable HDFS log storage
+
+```
+#
+# Indexing service logs
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+#druid.indexer.logs.type=file
+#druid.indexer.logs.directory=var/druid/indexing-logs
+
+# For HDFS:
+druid.indexer.logs.type=hdfs
+druid.indexer.logs.directory=/druid/indexing-logs
+
+```
+
+### Restart Druid cluster
+
+Once the Hadoop .xml files have been copied to the Druid cluster and the segment/log storage configuration has been updated to use HDFS, the Druid cluster needs to be restarted for the new configurations to take effect.
+
+If the cluster is still running, CTRL-C to terminate each Druid service, and re-run them.
+
+## Load batch data
+
+We've included a sample of Wikipedia edits from September 12, 2015 to get you started.
+
+To load this data into Druid, you can submit an *ingestion task* pointing to the file. We've included
+a task that loads the `wikiticker-2015-09-12-sampled.json.gz` file included in the archive. To submit
+this task, POST it to Druid in a new terminal window from the druid-#{DRUIDVERSION} directory:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-index-hadoop.json http://localhost:8090/druid/indexer/v1/task
+```
+
+Which will print the ID of the task if the submission was successful:
+
+```bash
+{"task":"index_hadoop_wikipedia-hadoop_2018-06-09T21:30:32.802Z"}
+```
+
+To view the status of your ingestion task, go to your overlord console:
+[http://localhost:8090/console.html](http://localhost:8090/console.html). You can refresh the console periodically, and after
+the task is successful, you should see a "SUCCESS" status for the task.
+
+After your ingestion task finishes, the data will be loaded by historical nodes and be available for
+querying within a minute or two. You can monitor the progress of loading your data in the
+coordinator console, by checking whether there is a datasource "wikipedia" with a blue circle
+indicating "fully available": [http://localhost:8081/#/](http://localhost:8081/#/).
+
+
+
+## Querying your data
+
+Your data should become fully available within a minute or two after the task completes. You can monitor this process on
+your Coordinator console at [http://localhost:8081/#/](http://localhost:8081/#/).
+
+Please follow the [query tutorial](../tutorial/tutorial-query.html) to run some example queries on the newly loaded data.
+
+## Cleanup
+
+This tutorial is only meant to be used together with the [query tutorial](../tutorial/tutorial-query.html).
+
+If you wish to go through any of the other tutorials, you will need to:
+* Shut down the cluster and reset the cluster state by following the [reset instructions](index.html#resetting-the-cluster).
+* Revert the deep storage and task storage config back to local types in `examples/conf/druid/_common/common.runtime.properties`
+* Restart the cluster
+
+This is necessary because the other ingestion tutorials will write to the same "wikipedia" datasource, and later tutorials expect the cluster to use local deep storage.
+
+Example reverted config:
+
+```
+#
+# Deep storage
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+druid.storage.type=local
+druid.storage.storageDirectory=var/druid/segments
+
+# For HDFS:
+#druid.storage.type=hdfs
+#druid.storage.storageDirectory=/druid/segments
+
+#
+# Indexing service logs
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+druid.indexer.logs.type=file
+druid.indexer.logs.directory=var/druid/indexing-logs
+
+# For HDFS:
+#druid.indexer.logs.type=hdfs
+#druid.indexer.logs.directory=/druid/indexing-logs
+
+```
+
+
+## Further reading
+
+For more information on loading batch data with Hadoop, please see [the Hadoop batch ingestion documentation](../ingestion/hadoop.html).
+
diff --git a/docs/content/tutorials/tutorial-batch.md b/docs/content/tutorials/tutorial-batch.md
index 3d14a9a8449..2aaf058924a 100644
--- a/docs/content/tutorials/tutorial-batch.md
+++ b/docs/content/tutorials/tutorial-batch.md
@@ -2,137 +2,130 @@
layout: doc_page
---
-# Tutorial: Load your own batch data
+# Tutorial: Loading a file
## Getting started
-This tutorial shows you how to load your own data files into Druid.
+This tutorial demonstrates how to perform a batch file load, using Druid's native batch ingestion.
For this tutorial, we'll assume you've already downloaded Druid as described in
-the [single-machine quickstart](quickstart.html) and have it running on your local machine. You
+the [single-machine quickstart](index.html) and have it running on your local machine. You
don't need to have loaded any data yet.
-Once that's complete, you can load your own dataset by writing a custom ingestion spec.
+## Preparing the data and the ingestion task spec
-## Writing an ingestion spec
+A data load is initiated by submitting an *ingestion task* spec to the Druid overlord. For this tutorial, we'll be loading the sample Wikipedia page edits data.
-When loading files into Druid, you will use Druid's [batch loading](../ingestion/batch-ingestion.html) process.
-There's an example batch ingestion spec in `quickstart/wikiticker-index.json` that you can modify
-for your own needs.
+We have provided an ingestion spec at `examples/wikipedia-index.json`, shown here for convenience,
+which has been configured to read the `quickstart/wikiticker-2015-09-12-sampled.json.gz` input file:
-The most important questions are:
-
- * What should the dataset be called? This is the "dataSource" field of the "dataSchema".
- * Where is the dataset located? The file paths belong in the "paths" of the "inputSpec". If you
-want to load multiple files, you can provide them as a comma-separated string.
- * Which field should be treated as a timestamp? This belongs in the "column" of the "timestampSpec".
- * Which fields should be treated as dimensions? This belongs in the "dimensions" of the "dimensionsSpec".
- * Which fields should be treated as metrics? This belongs in the "metricsSpec".
- * What time ranges (intervals) are being loaded? This belongs in the "intervals" of the "granularitySpec".
-
-If your data does not have a natural sense of time, you can tag each row with the current time.
-You can also tag all rows with a fixed timestamp, like "2000-01-01T00:00:00.000Z".
-
-Let's use this pageviews dataset as an example. Druid supports TSV, CSV, and JSON out of the box.
-Note that nested JSON objects are not supported, so if you do use JSON, you should provide a file
-containing flattened objects.
-
-```json
-{"time": "2015-09-01T00:00:00Z", "url": "/foo/bar", "user": "alice", "latencyMs": 32}
-{"time": "2015-09-01T01:00:00Z", "url": "/", "user": "bob", "latencyMs": 11}
-{"time": "2015-09-01T01:30:00Z", "url": "/foo/bar", "user": "bob", "latencyMs": 45}
```
-
-Make sure the file has no newline at the end. If you save this to a file called "pageviews.json", then for this dataset:
-
- * Let's call the dataset "pageviews".
- * The data is located in "pageviews.json".
- * The timestamp is the "time" field.
- * Good choices for dimensions are the string fields "url" and "user".
- * Good choices for metrics are a count of pageviews, and the sum of "latencyMs". Collecting that
-sum when we load the data will allow us to compute an average at query time as well.
- * The data covers the time range 2015-09-01 (inclusive) through 2015-09-02 (exclusive).
-
-You can copy the existing `quickstart/wikiticker-index.json` indexing task to a new file:
-
-```bash
-cp quickstart/wikiticker-index.json my-index-task.json
-```
-
-And modify it by altering these sections:
-
-```json
-"dataSource": "pageviews"
-```
-
-```json
-"inputSpec": {
- "type": "static",
- "paths": "pageviews.json"
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "wikipedia",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "day",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "quickstart/",
+ "filter" : "wikiticker-2015-09-12-sampled.json.gz"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
}
```
-```json
-"timestampSpec": {
- "format": "auto",
- "column": "time"
-}
-```
-
-```json
-"dimensionsSpec": {
- "dimensions": ["url", "user"]
-}
-```
-
-```json
-"metricsSpec": [
- {"name": "views", "type": "count"},
- {"name": "latencyMs", "type": "doubleSum", "fieldName": "latencyMs"}
-]
-```
-
-```json
-"granularitySpec": {
- "type": "uniform",
- "segmentGranularity": "day",
- "queryGranularity": "none",
- "intervals": ["2015-09-01/2015-09-02"]
-}
-```
+This spec will create a datasource named "wikipedia".
-## Running the task
+## Load batch data
-To actually run this task, first make sure that the indexing task can read *pageviews.json*:
+We've included a sample of Wikipedia edits from September 12, 2015 to get you started.
-- If you're running locally (no configuration for connecting to Hadoop; this is the default) then
-place it in the root of the Druid distribution.
-- If you configured Druid to connect to a Hadoop cluster, upload
-the pageviews.json file to HDFS. You may need to adjust the `paths` in the ingestion spec.
-
-To kick off the indexing process, POST your indexing task to the Druid Overlord. In a standard Druid
-install, the URL is `http://OVERLORD_IP:8090/druid/indexer/v1/task`.
+To load this data into Druid, you can submit an *ingestion task* pointing to the file. To submit
+this task, POST it to Druid in a new terminal window from the druid-#{DRUIDVERSION} directory:
```bash
-curl -X 'POST' -H 'Content-Type:application/json' -d @my-index-task.json OVERLORD_IP:8090/druid/indexer/v1/task
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-index.json http://localhost:8090/druid/indexer/v1/task
```
-If you're running everything on a single machine, you can use localhost:
+Which will print the ID of the task if the submission was successful:
```bash
-curl -X 'POST' -H 'Content-Type:application/json' -d @my-index-task.json localhost:8090/druid/indexer/v1/task
+{"task":"index_wikipedia_2018-06-09T21:30:32.802Z"}
```
-If anything goes wrong with this task (e.g. it finishes with status FAILED), you can troubleshoot
-by visiting the "Task log" on the [overlord console](http://localhost:8090/console.html).
+To view the status of your ingestion task, go to your overlord console:
+[http://localhost:8090/console.html](http://localhost:8090/console.html). You can refresh the console periodically, and after
+the task is successful, you should see a "SUCCESS" status for the task.
+
+After your ingestion task finishes, the data will be loaded by historical nodes and available for
+querying within a minute or two. You can monitor the progress of loading your data in the
+coordinator console, by checking whether there is a datasource "wikipedia" with a blue circle
+indicating "fully available": [http://localhost:8081/#/](http://localhost:8081/#/).
+
+
## Querying your data
Your data should become fully available within a minute or two. You can monitor this process on
your Coordinator console at [http://localhost:8081/#/](http://localhost:8081/#/).
-Once your data is fully available, you can query it using any of the
-[supported query methods](../querying/querying.html).
+Once the data is loaded, please follow the [query tutorial](../tutorial/tutorial-query.html) to run some example queries on the newly loaded data.
+
+## Cleanup
+
+If you wish to go through any of the other ingestion tutorials, you will need to reset the cluster and follow these [reset instructions](index.html#resetting-the-cluster), as the other tutorials will write to the same "wikipedia" datasource.
## Further reading
diff --git a/docs/content/tutorials/tutorial-compaction.md b/docs/content/tutorials/tutorial-compaction.md
new file mode 100644
index 00000000000..73c182a73e0
--- /dev/null
+++ b/docs/content/tutorials/tutorial-compaction.md
@@ -0,0 +1,103 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Compacting segments
+
+This tutorial demonstrates how to compact existing segments into fewer but larger segments.
+
+Because there is some per-segment memory and processing overhead, it can sometimes be beneficial to reduce the total number of segments.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html) and [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html).
+
+## Load the initial data
+
+For this tutorial, we'll be using the Wikipedia edits sample data, with an ingestion task spec that will create a separate segment for each hour in the input data.
+
+The ingestion spec can be found at `examples/compaction-init-index.json`. Let's submit that spec, which will create a datasource called `compaction-tutorial`:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/compaction-init-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After the ingestion completes, go to http://localhost:8081/#/datasources/compaction-tutorial in a browser to view information about the new datasource in the Coordinator console.
+
+There will be 24 segments for this datasource, one segment per hour in the input data:
+
+
+
+Running a COUNT(*) query on this datasource shows that there are 39,244 rows:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/compaction-count-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[{"EXPR$0":39244}]
+```
+
+## Compact the data
+
+Let's now combine these 24 segments into one segment.
+
+We have included a compaction task spec for this tutorial datasource at `examples/compaction-final-index.json`:
+
+```
+{
+ "type": "compact",
+ "dataSource": "compaction-tutorial",
+ "interval": "2015-09-12/2015-09-13",
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+}
+```
+
+This will compact all segments for the interval `2015-09-12/2015-09-13` in the `compaction-tutorial` datasource.
+
+The parameters in the `tuningConfig` control how many segments will be present in the compacted set of segments.
+
+In this tutorial example, only one compacted segment will be created, as the 39244 rows in the input is less than the 5000000 `targetPartitionSize`.
+
+Let's submit this task now:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/compaction-final-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After the task finishes, refresh the http://localhost:8081/#/datasources/compaction-tutorial page.
+
+The original 24 segments will eventually be marked as "unused" by the Coordinator and removed, with the new compacted segment remaining.
+
+By default, the Druid coordinator will not mark segments as unused until the coordinator process has been up for at least 15 minutes, so you may see the old segment set and the new compacted set at the same time in the coordinator, e.g.:
+
+
+
+The new compacted segment has a more recent version than the original segments, so even when both sets of segments are shown by the coordinator, queries will only read from the new compacted segment.
+
+Let's try running a COUNT(*) on `compaction-tutorial` again, where the row count should still be 39,244:
+
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/compaction-count-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[{"EXPR$0":39244}]
+```
+
+After the coordinator has been running for at least 15 minutes, the http://localhost:8081/#/datasources/compaction-tutorial page should show there is only 1 segment:
+
+
+
+## Further reading
+
+[Task documentation](../ingestion/tasks.html)
+
+[Segment optimization](../operations/segment-optimization.html)
diff --git a/docs/content/tutorials/tutorial-delete-data.md b/docs/content/tutorials/tutorial-delete-data.md
new file mode 100644
index 00000000000..19f0b57ded6
--- /dev/null
+++ b/docs/content/tutorials/tutorial-delete-data.md
@@ -0,0 +1,156 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Deleting data
+
+This tutorial demonstrates how to delete existing data.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+Completing [Tutorial: Configuring retention](/docs/VERSION/tutorials/tutorial-retention.html) first is highly recommended, as we will be using retention rules in this tutorial.
+
+## Load initial data
+
+In this tutorial, we will use the Wikipedia edits data, with an indexing spec that creates hourly segments. This spec is located at `examples/deletion-index.json`, and it creates a datasource called `deletion-tutorial`.
+
+Let's load this initial data:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/deletion-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+When the load finishes, open http://localhost:8081/#/datasources/deletion-tutorial in a browser.
+
+## How to permanently delete data
+
+Permanent deletion of a Druid segment has two steps:
+
+1. The segment must first be marked as "unused". This occurs when a segment is dropped by retention rules, and when a user manually disables a segment through the Coordinator API. This tutorial will cover both cases.
+2. After segments have been marked as "unused", a Kill Task will delete any "unused" segments from Druid's metadata store as well as deep storage.
+
+Let's drop some segments now, first with load rules, then manually.
+
+## Drop some data with load rules
+
+As with the previous retention tutorial, there are currently 24 segments in the `deletion-tutorial` datasource.
+
+Click the `edit rules` button with a pencil icon at the upper left corner of the page.
+
+A rule configuration window will appear. Enter `tutorial` for both the user and changelog comment field.
+
+Now click the `+ Add a rule` button twice.
+
+In the `rule #1` box at the top, click `Load`, `Interval`, enter `2015-09-12T12:00:00.000Z/2015-09-13T00:00:00.000Z` in the interval box, and click `+ _default_tier replicant`.
+
+In the `rule #2` box at the bottom, click `Drop` and `Forever`.
+
+This will cause the first 12 segments of `deletion-tutorial` to be dropped. However, these dropped segments are not removed from deep storage.
+
+You can see that all 24 segments are still present in deep storage by listing the contents of `druid-{DRUIDVERSION}/var/druid/segments/deletion-tutorial`:
+
+```
+$ ls -l1 var/druid/segments/deletion-tutorial/
+2015-09-12T00:00:00.000Z_2015-09-12T01:00:00.000Z
+2015-09-12T01:00:00.000Z_2015-09-12T02:00:00.000Z
+2015-09-12T02:00:00.000Z_2015-09-12T03:00:00.000Z
+2015-09-12T03:00:00.000Z_2015-09-12T04:00:00.000Z
+2015-09-12T04:00:00.000Z_2015-09-12T05:00:00.000Z
+2015-09-12T05:00:00.000Z_2015-09-12T06:00:00.000Z
+2015-09-12T06:00:00.000Z_2015-09-12T07:00:00.000Z
+2015-09-12T07:00:00.000Z_2015-09-12T08:00:00.000Z
+2015-09-12T08:00:00.000Z_2015-09-12T09:00:00.000Z
+2015-09-12T09:00:00.000Z_2015-09-12T10:00:00.000Z
+2015-09-12T10:00:00.000Z_2015-09-12T11:00:00.000Z
+2015-09-12T11:00:00.000Z_2015-09-12T12:00:00.000Z
+2015-09-12T12:00:00.000Z_2015-09-12T13:00:00.000Z
+2015-09-12T13:00:00.000Z_2015-09-12T14:00:00.000Z
+2015-09-12T14:00:00.000Z_2015-09-12T15:00:00.000Z
+2015-09-12T15:00:00.000Z_2015-09-12T16:00:00.000Z
+2015-09-12T16:00:00.000Z_2015-09-12T17:00:00.000Z
+2015-09-12T17:00:00.000Z_2015-09-12T18:00:00.000Z
+2015-09-12T18:00:00.000Z_2015-09-12T19:00:00.000Z
+2015-09-12T19:00:00.000Z_2015-09-12T20:00:00.000Z
+2015-09-12T20:00:00.000Z_2015-09-12T21:00:00.000Z
+2015-09-12T21:00:00.000Z_2015-09-12T22:00:00.000Z
+2015-09-12T22:00:00.000Z_2015-09-12T23:00:00.000Z
+2015-09-12T23:00:00.000Z_2015-09-13T00:00:00.000Z
+```
+
+## Manually disable a segment
+
+Let's manually disable a segment now. This will mark a segment as "unused", but not remove it from deep storage.
+
+On http://localhost:8081/#/datasources/deletion-tutorial, click one of the remaining segments on the left for full details about the segment:
+
+
+
+The top of the info box shows the full segment ID, e.g. `deletion-tutorial_2016-06-27T14:00:00.000Z_2016-06-27T15:00:00.000Z_2018-07-27T22:57:00.110Z` for the segment of hour 14.
+
+Let's disable the hour 14 segment by sending the following DELETE request to the coordinator, where {SEGMENT-ID} is the full segment ID shown in the info box:
+
+```
+curl -XDELETE http://localhost:8081/druid/coordinator/v1/datasources/deletion-tutorial/segments/{SEGMENT-ID}
+```
+
+After that command completes, you should see that the segment for hour 14 has been disabled:
+
+
+
+Note that the hour 14 segment is still in deep storage:
+
+```
+$ ls -l1 var/druid/segments/deletion-tutorial/
+2015-09-12T00:00:00.000Z_2015-09-12T01:00:00.000Z
+2015-09-12T01:00:00.000Z_2015-09-12T02:00:00.000Z
+2015-09-12T02:00:00.000Z_2015-09-12T03:00:00.000Z
+2015-09-12T03:00:00.000Z_2015-09-12T04:00:00.000Z
+2015-09-12T04:00:00.000Z_2015-09-12T05:00:00.000Z
+2015-09-12T05:00:00.000Z_2015-09-12T06:00:00.000Z
+2015-09-12T06:00:00.000Z_2015-09-12T07:00:00.000Z
+2015-09-12T07:00:00.000Z_2015-09-12T08:00:00.000Z
+2015-09-12T08:00:00.000Z_2015-09-12T09:00:00.000Z
+2015-09-12T09:00:00.000Z_2015-09-12T10:00:00.000Z
+2015-09-12T10:00:00.000Z_2015-09-12T11:00:00.000Z
+2015-09-12T11:00:00.000Z_2015-09-12T12:00:00.000Z
+2015-09-12T12:00:00.000Z_2015-09-12T13:00:00.000Z
+2015-09-12T13:00:00.000Z_2015-09-12T14:00:00.000Z
+2015-09-12T14:00:00.000Z_2015-09-12T15:00:00.000Z
+2015-09-12T15:00:00.000Z_2015-09-12T16:00:00.000Z
+2015-09-12T16:00:00.000Z_2015-09-12T17:00:00.000Z
+2015-09-12T17:00:00.000Z_2015-09-12T18:00:00.000Z
+2015-09-12T18:00:00.000Z_2015-09-12T19:00:00.000Z
+2015-09-12T19:00:00.000Z_2015-09-12T20:00:00.000Z
+2015-09-12T20:00:00.000Z_2015-09-12T21:00:00.000Z
+2015-09-12T21:00:00.000Z_2015-09-12T22:00:00.000Z
+2015-09-12T22:00:00.000Z_2015-09-12T23:00:00.000Z
+2015-09-12T23:00:00.000Z_2015-09-13T00:00:00.000Z
+```
+
+## Run a kill task
+
+Now that we have disabled some segments, we can submit a Kill Task, which will delete the disabled segments from metadata and deep storage.
+
+A Kill Task spec has been provided at `examples/deletion-kill.json`. Submit this task to the Overlord with the following command:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/deletion-kill.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After this task completes, you can see that the disabled segments have now been removed from deep storage:
+
+```
+$ ls -l1 var/druid/segments/deletion-tutorial/
+2015-09-12T12:00:00.000Z_2015-09-12T13:00:00.000Z
+2015-09-12T13:00:00.000Z_2015-09-12T14:00:00.000Z
+2015-09-12T15:00:00.000Z_2015-09-12T16:00:00.000Z
+2015-09-12T16:00:00.000Z_2015-09-12T17:00:00.000Z
+2015-09-12T17:00:00.000Z_2015-09-12T18:00:00.000Z
+2015-09-12T18:00:00.000Z_2015-09-12T19:00:00.000Z
+2015-09-12T19:00:00.000Z_2015-09-12T20:00:00.000Z
+2015-09-12T20:00:00.000Z_2015-09-12T21:00:00.000Z
+2015-09-12T21:00:00.000Z_2015-09-12T22:00:00.000Z
+2015-09-12T22:00:00.000Z_2015-09-12T23:00:00.000Z
+2015-09-12T23:00:00.000Z_2015-09-13T00:00:00.000Z
+```
\ No newline at end of file
diff --git a/docs/content/tutorials/tutorial-examples.tar.gz b/docs/content/tutorials/tutorial-examples.tar.gz
new file mode 100644
index 00000000000..cdd20c1abf6
Binary files /dev/null and b/docs/content/tutorials/tutorial-examples.tar.gz differ
diff --git a/docs/content/tutorials/tutorial-ingestion-spec.md b/docs/content/tutorials/tutorial-ingestion-spec.md
new file mode 100644
index 00000000000..65a028291bb
--- /dev/null
+++ b/docs/content/tutorials/tutorial-ingestion-spec.md
@@ -0,0 +1,691 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Writing an ingestion spec
+
+This tutorial will guide the reader through the process of defining an ingestion spec, pointing out key considerations and guidelines.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html), [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html), and [Tutorial: Rollup](/docs/VERSION/tutorials/tutorial-rollup.html).
+
+## Example data
+
+Suppose we have the following network flow data:
+
+* `srcIP`: IP address of sender
+* `srcPort`: Port of sender
+* `dstIP`: IP address of receiver
+* `dstPort`: Port of receiver
+* `protocol`: IP protocol number
+* `packets`: number of packets transmitted
+* `bytes`: number of bytes transmitted
+* `cost`: the cost of sending the traffic
+
+```
+{"ts":"2018-01-01T01:01:35Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":10, "bytes":1000, "cost": 1.4}
+{"ts":"2018-01-01T01:01:51Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":20, "bytes":2000, "cost": 3.1}
+{"ts":"2018-01-01T01:01:59Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":2000, "dstPort":3000, "protocol": 6, "packets":30, "bytes":3000, "cost": 0.4}
+{"ts":"2018-01-01T01:02:14Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":40, "bytes":4000, "cost": 7.9}
+{"ts":"2018-01-01T01:02:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":50, "bytes":5000, "cost": 10.2}
+{"ts":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3}
+{"ts":"2018-01-01T02:33:14Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":100, "bytes":10000, "cost": 22.4}
+{"ts":"2018-01-01T02:33:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":200, "bytes":20000, "cost": 34.5}
+{"ts":"2018-01-01T02:35:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8", "srcPort":4000, "dstPort":5000, "protocol": 17, "packets":300, "bytes":30000, "cost": 46.3}
+```
+
+Save the JSON contents above into a file called `ingestion-tutorial-data.json` under `examples`.
+
+Let's walk through the process of defining an ingestion spec that can load this data.
+
+For this tutorial, we will be using the native batch indexing task. When using other task types, some aspects of the ingestion spec will differ, and this tutorial will point out such areas.
+
+## Defining the schema
+
+The core element of a Druid ingestion spec is the `dataSchema`. The `dataSchema` defines how to parse input data into a set of columns that will be stored in Druid.
+
+Let's start with an empty `dataSchema` and add fields to it as we progress through the tutorial.
+
+Create a new file called `ingestion-tutorial-index.json` under `examples` with the following contents:
+
+```json
+"dataSchema" : {}
+```
+
+We will be making successive edits to this ingestion spec as we progress through the tutorial.
+
+### Datasource name
+
+The datasource name is specified by the `dataSource` parameter in the `dataSchema`.
+
+```json
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+}
+```
+
+Let's call the tutorial datasource `ingestion-tutorial`.
+
+### Choose a parser
+
+A `dataSchema` has a `parser` field, which defines the parser that Druid will use to interpret the input data.
+
+Since our input data is represented as JSON strings, we'll use a `string` parser with `json` format:
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json"
+ }
+ }
+}
+```
+
+### Time column
+
+The `parser` needs to know how to extract the main timestamp field from the input data. When using a `json` type `parseSpec`, the timestamp is defined in a `timestampSpec`.
+
+The timestamp column in our input data is named "ts", containing ISO 8601 timestamps, so let's add a `timestampSpec` with that information to the `parseSpec`:
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ }
+ }
+ }
+}
+```
+
+### Column types
+
+Now that we've defined the time column, let's look at definitions for other columns.
+
+Druid supports the following column types: String, Long, Float, Double. We will see how these are used in the following sections.
+
+Before we move on to how we define our other non-time columns, let's discuss `rollup` first.
+
+### Rollup
+
+When ingesting data, we must consider whether we wish to use rollup or not.
+
+* If rollup is enabled, we will need to separate the input columns into two categories, "dimensions" and "metrics". "Dimensions" are the grouping columns for rollup, while "metrics" are the columns that will be aggregated.
+
+* If rollup is disabled, then all columns are treated as "dimensions" and no pre-aggregation occurs.
+
+For this tutorial, let's enable rollup. This is specified with a `granularitySpec` on the `dataSchema`.
+
+Note that the `granularitySpec` lies outside of the `parser`. We will revist the `parser` soon when we define our dimensions and metrics.
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ }
+ }
+ },
+ "granularitySpec" : {
+ "rollup" : true
+ }
+}
+
+```
+
+#### Choosing dimensions and metrics
+
+For this example dataset, the following is a sensible split for "dimensions" and "metrics":
+
+* Dimensions: srcIP, srcPort, dstIP, dstPort, protocol
+* Metrics: packets, bytes, cost
+
+The dimensions here are a group of properties that identify a unidirectional flow of IP traffic, while the metrics represent facts about the IP traffic flow specified by a dimension grouping.
+
+Let's look at how to define these dimensions and metrics within the ingestion spec.
+
+#### Dimensions
+
+Dimensions are specified with a `dimensionsSpec` inside the `parseSpec`.
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "granularitySpec" : {
+ "rollup" : true
+ }
+}
+```
+
+Each dimension has a `name` and a `type`, where `type` can be "long", "float", "double", or "string".
+
+Note that `srcIP` is a "string" dimension; for string dimensions, it is enough to specify just a dimension name, since "string" is the default dimension type.
+
+Also note that `protocol` is a numeric value in the input data, but we are ingesting it as a "string" column; Druid will coerce the input longs to strings during ingestion.
+
+##### Strings vs. Numerics
+
+Should a numeric input be ingested as a numeric dimension or as a string dimension?
+
+Numeric dimensions have the following pros/cons relative to String dimensions:
+* Pros: Numeric representation can result in smaller column sizes on disk and lower processing overhead when reading values from the column
+* Cons: Numeric dimensions do not have indices, so filtering on them will often be slower than filtering on an equivalent String dimension (which has bitmap indices)
+
+#### Metrics
+
+Metrics are specified with a `metricsSpec` inside the `dataSchema`:
+
+```json
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "rollup" : true
+ }
+}
+```
+
+When defining a metric, it is necessary to specify what type of aggregation should be performed on that column during rollup.
+
+Here we have defined long sum aggregations on the two long metric columns, `packets` and `bytes`, and a double sum aggregation for the `cost` column.
+
+Note that the `metricsSpec` is on a different nesting level than `dimensionSpec` or `parseSpec`; it belongs on the same nesting level as `parser` within the `dataSchema`.
+
+Note that we have also defined a `count` aggregator. The count aggregator will track how many rows in the original input data contributed to a "rolled up" row in the final ingested data.
+
+### No rollup
+
+If we were not using rollup, all columns would be specified in the `dimensionsSpec`, e.g.:
+
+```
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" },
+ { "name" : "packets", "type" : "long" },
+ { "name" : "bytes", "type" : "long" },
+ { "name" : "srcPort", "type" : "double" }
+ ]
+ },
+```
+
+
+### Define granularities
+
+At this point, we are done defining the `parser` and `metricsSpec` within the `dataSchema` and we are almost done writing the ingestion spec.
+
+There are some additional properties we need to set in the `granularitySpec`:
+* Type of granularitySpec: `uniform` and `arbitrary` are the two supported types. For this tutorial, we will use a `uniform` granularity spec, where all segments have uniform interval sizes (for example, all segments cover an hour's worth of data).
+* The segment granularity: what size of time interval should a single segment contain data for? e.g., `DAY`, `WEEK`
+* The bucketing granularity of the timestamps in the time column (referred to as `queryGranularity`)
+
+#### Segment granularity
+
+Segment granularity is configured by the `segmentGranularity` property in the `granularitySpec`. For this tutorial, we'll create hourly segments:
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "rollup" : true
+ }
+}
+```
+
+Our input data has events from two separate hours, so this task will generate two segments.
+
+#### Query granularity
+
+The query granularity is configured by the `queryGranularity` property in the `granularitySpec`. For this tutorial, let's use minute granularity:
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "queryGranularity" : "MINUTE"
+ "rollup" : true
+ }
+}
+```
+
+To see the effect of the query granularity, let's look at this row from the raw input data:
+
+```
+{"ts":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3}
+```
+
+When this row is ingested with minute queryGranularity, Druid will floor the row's timestamp to minute buckets:
+
+```
+{"ts":"2018-01-01T01:03:00Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2", "srcPort":5000, "dstPort":7000, "protocol": 6, "packets":60, "bytes":6000, "cost": 4.3}
+```
+
+#### Define an interval (batch only)
+
+For batch tasks, it is necessary to define a time interval. Input rows with timestamps outside of the time interval will not be ingested.
+
+The interval is also specified in the `granularitySpec`:
+
+```
+"dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "queryGranularity" : "MINUTE",
+ "intervals" : ["2018-01-01/2018-01-02"],
+ "rollup" : true
+ }
+}
+```
+
+## Define the task type
+
+We've now finished defining our `dataSchema`. The remaining steps are to place the `dataSchema` we created into an ingestion task spec, and specify the input source.
+
+The `dataSchema` is shared across all task types, but each task type has its own specification format. For this tutorial, we will use the native batch ingestion task:
+
+```
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "queryGranularity" : "MINUTE",
+ "intervals" : ["2018-01-01/2018-01-02"],
+ "rollup" : true
+ }
+ }
+ }
+}
+```
+
+## Define the input source
+
+Now let's define our input source, which is specified in an `ioConfig` object. Each task type has its own type of `ioConfig`. The native batch task uses "firehoses" to read input data, so let's configure a "local" firehose to read the example netflow data we saved earlier:
+
+
+```
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "ingestion-tutorial-data.json"
+ }
+ }
+```
+
+```
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "queryGranularity" : "MINUTE",
+ "intervals" : ["2018-01-01/2018-01-02"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "ingestion-tutorial-data.json"
+ }
+ }
+ }
+}
+```
+
+## Additional tuning
+
+Each ingestion task has a `tuningConfig` section that allows users to tune various ingestion parameters.
+
+As an example, let's add a `tuningConfig` that sets a target segment size for the native batch ingestion task:
+
+```
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000
+ }
+```
+
+Note that each ingestion task has its own type of `tuningConfig`.
+
+## Final spec
+
+We've finished defining the ingestion spec, it should now look like the following:
+
+```
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "ingestion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "timestampSpec" : {
+ "format" : "iso",
+ "column" : "ts"
+ },
+ "dimensionsSpec" : {
+ "dimensions": [
+ "srcIP",
+ { "name" : "srcPort", "type" : "long" },
+ { "name" : "dstIP", "type" : "string" },
+ { "name" : "dstPort", "type" : "long" },
+ { "name" : "protocol", "type" : "string" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" },
+ { "type" : "doubleSum", "name" : "cost", "fieldName" : "cost" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "HOUR",
+ "queryGranularity" : "MINUTE",
+ "intervals" : ["2018-01-01/2018-01-02"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "ingestion-tutorial-data.json"
+ }
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000
+ }
+ }
+}
+```
+
+## Submit the task and query the data
+
+From the druid-${DRUIDVERSION} package root, run the following command:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/ingestion-tutorial-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After the script completes, we will query the data.
+
+Let's issue a `select * from "ingestion-tutorial";` query to see what data was ingested.
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/ingestion-tutorial-select-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "bytes": 6000,
+ "cost": 4.9,
+ "count": 3,
+ "dstIP": "2.2.2.2",
+ "dstPort": 3000,
+ "packets": 60,
+ "protocol": "6",
+ "srcIP": "1.1.1.1",
+ "srcPort": 2000
+ },
+ {
+ "__time": "2018-01-01T01:02:00.000Z",
+ "bytes": 9000,
+ "cost": 18.1,
+ "count": 2,
+ "dstIP": "2.2.2.2",
+ "dstPort": 7000,
+ "packets": 90,
+ "protocol": "6",
+ "srcIP": "1.1.1.1",
+ "srcPort": 5000
+ },
+ {
+ "__time": "2018-01-01T01:03:00.000Z",
+ "bytes": 6000,
+ "cost": 4.3,
+ "count": 1,
+ "dstIP": "2.2.2.2",
+ "dstPort": 7000,
+ "packets": 60,
+ "protocol": "6",
+ "srcIP": "1.1.1.1",
+ "srcPort": 5000
+ },
+ {
+ "__time": "2018-01-01T02:33:00.000Z",
+ "bytes": 30000,
+ "cost": 56.9,
+ "count": 2,
+ "dstIP": "8.8.8.8",
+ "dstPort": 5000,
+ "packets": 300,
+ "protocol": "17",
+ "srcIP": "7.7.7.7",
+ "srcPort": 4000
+ },
+ {
+ "__time": "2018-01-01T02:35:00.000Z",
+ "bytes": 30000,
+ "cost": 46.3,
+ "count": 1,
+ "dstIP": "8.8.8.8",
+ "dstPort": 5000,
+ "packets": 300,
+ "protocol": "17",
+ "srcIP": "7.7.7.7",
+ "srcPort": 4000
+ }
+]
+```
diff --git a/docs/content/tutorials/tutorial-kafka.md b/docs/content/tutorials/tutorial-kafka.md
index 5242df76f9f..77b83e7bcbd 100644
--- a/docs/content/tutorials/tutorial-kafka.md
+++ b/docs/content/tutorials/tutorial-kafka.md
@@ -2,33 +2,26 @@
layout: doc_page
---
-# Tutorial: Load from Kafka
+# Tutorial: Load streaming data from Kafka
## Getting started
-This tutorial shows you how to load data from Kafka into Druid.
+This tutorial demonstrates how to load data from a Kafka stream, using the Druid Kafka indexing service.
-For this tutorial, we'll assume you've already downloaded Druid and Tranquility as described in
-the [single-machine quickstart](quickstart.html) and have it running on your local machine. You
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine. You
don't need to have loaded any data yet.
-<div class="note info">
-This tutorial will show you how to load data from Kafka into Druid, but Druid additionally supports
-a wide variety of batch and streaming loading methods. See the <a href="../ingestion/batch-ingestion.html">Loading files</a>
-and <a href="../ingestion/stream-ingestion.html">Loading streams</a> pages for more information about other options,
-including from Hadoop, HTTP, Storm, Samza, Spark Streaming, and your own JVM apps.
-</div>
-
-## Start Kafka
+## Download and start Kafka
[Apache Kafka](http://kafka.apache.org/) is a high throughput message bus that works well with
-Druid. For this tutorial, we will use Kafka 0.9.0.0. To download Kafka, issue the following
+Druid. For this tutorial, we will use Kafka 0.10.2.0. To download Kafka, issue the following
commands in your terminal:
```bash
-curl -O http://www.us.apache.org/dist/kafka/0.9.0.0/kafka_2.11-0.9.0.0.tgz
-tar -xzf kafka_2.11-0.9.0.0.tgz
-cd kafka_2.11-0.9.0.0
+curl -O https://archive.apache.org/dist/kafka/0.10.2.0/kafka_2.11-0.10.2.0.tgz
+tar -xzf kafka_2.11-0.10.2.0.tgz
+cd kafka_2.11-0.10.2.0
```
Start a Kafka broker by running the following command in a new terminal:
@@ -37,149 +30,49 @@ Start a Kafka broker by running the following command in a new terminal:
./bin/kafka-server-start.sh config/server.properties
```
-Run this command to create a Kafka topic called *metrics*, to which we'll send data:
+Run this command to create a Kafka topic called *wikipedia*, to which we'll send data:
```bash
-./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic metrics
+./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic wikipedia
```
-## Send example data
-
-Let's launch a console producer for our topic and send some data!
-
-In your Druid directory, generate some metrics by running:
+## Enable Druid Kafka ingestion
-```bash
-bin/generate-example-metrics
-```
-
-In your Kafka directory, run:
+We will use Druid's Kafka indexing service to ingest messages from our newly created *wikipedia* topic. To start the
+service, we will need to submit a supervisor spec to the Druid overlord by running the following from the Druid package root:
```bash
-./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic metrics
+curl -XPOST -H'Content-Type: application/json' -d @examples/wikipedia-kafka-supervisor.json http://localhost:8090/druid/indexer/v1/supervisor
```
-The *kafka-console-producer* command is now awaiting input. Copy the generated example metrics,
-paste them into the *kafka-console-producer* terminal, and press enter. If you like, you can also
-paste more messages into the producer, or you can press CTRL-D to exit the console producer.
-
-You can immediately query this data, or you can skip ahead to the
-[Loading your own data](#loading-your-own-data) section if you'd like to load your own dataset.
-
-## Querying your data
-
-After sending data, you can immediately query it using any of the
-[supported query methods](../querying/querying.html).
-
-## Loading your own data
-
-So far, you've loaded data into Druid from Kafka using an ingestion spec that we've included in the
-distribution. Each ingestion spec is designed to work with a particular dataset. You load your own
-data types into Imply by writing a custom ingestion spec.
-
-You can write a custom ingestion spec by starting from the bundled configuration in
-`conf-quickstart/tranquility/kafka.json` and modifying it for your own needs.
-
-The most important questions are:
+If the supervisor was successfully created, you will get a response containing the ID of the supervisor; in our case we should see `{"id":"wikipedia-kafka"}`.
- * What should the dataset be called? This is the "dataSource" field of the "dataSchema".
- * Which field should be treated as a timestamp? This belongs in the "column" of the "timestampSpec".
- * Which fields should be treated as dimensions? This belongs in the "dimensions" of the "dimensionsSpec".
- * Which fields should be treated as measures? This belongs in the "metricsSpec".
+For more details about what's going on here, check out the
+[Druid Kafka indexing service documentation](http://druid.io/docs/{{druidVersion}}/development/extensions-core/kafka-ingestion.html).
-Let's use a small JSON pageviews dataset in the topic *pageviews* as an example, with records like:
+## Load data
-```json
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "alice", "latencyMs": 32}
-```
-
-First, create the topic:
-
-```bash
-./bin/kafka-topics.sh --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic pageviews
-```
+Let's launch a console producer for our topic and send some data!
-Next, edit `conf-quickstart/tranquility/kafka.json`:
-
- * Let's call the dataset "pageviews-kafka".
- * The timestamp is the "time" field.
- * Good choices for dimensions are the string fields "url" and "user".
- * Good choices for measures are a count of pageviews, and the sum of "latencyMs". Collecting that
-sum when we load the data will allow us to compute an average at query time as well.
-
-You can edit the existing `conf-quickstart/tranquility/kafka.json` file by altering these
-sections:
-
- 1. Change the key `"metrics-kafka"` under `"dataSources"` to `"pageviews-kafka"`
- 2. Alter these sections under the new `"pageviews-kafka"` key:
- ```json
- "dataSource": "pageviews-kafka"
- ```
-
- ```json
- "timestampSpec": {
- "format": "auto",
- "column": "time"
- }
- ```
-
- ```json
- "dimensionsSpec": {
- "dimensions": ["url", "user"]
- }
- ```
-
- ```json
- "metricsSpec": [
- {"name": "views", "type": "count"},
- {"name": "latencyMs", "type": "doubleSum", "fieldName": "latencyMs"}
- ]
- ```
-
- ```json
- "properties" : {
- "task.partitions" : "1",
- "task.replicants" : "1",
- "topicPattern" : "pageviews"
- }
- ```
-
-Next, start Druid Kafka ingestion:
+In your Kafka directory, run the following command, where {PATH_TO_DRUID} is replaced by the path to the Druid directory:
```bash
-bin/tranquility kafka -configFile ../druid-#{DRUIDVERSION}/conf-quickstart/tranquility/kafka.json
+export KAFKA_OPTS="-Dfile.encoding=UTF-8"
+./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic wikipedia < {PATH_TO_DRUID}/quickstart/wikiticker-2015-09-12-sampled.json
```
-- If your Tranquility server or Kafka is already running, stop it (CTRL-C) and
-start it up again.
-
-Finally, send some data to the Kafka topic. Let's start with these messages:
+The previous command posted sample events to the *wikipedia* Kafka topic which were then ingested into Druid by the Kafka indexing service. You're now ready to run some queries!
-```json
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "alice", "latencyMs": 32}
-{"time": "2000-01-01T00:00:00Z", "url": "/", "user": "bob", "latencyMs": 11}
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "bob", "latencyMs": 45}
-```
+## Querying your data
-Druid streaming ingestion requires relatively current messages (relative to a slack time controlled by the
-[windowPeriod](../ingestion/stream-ingestion.html#segmentgranularity-and-windowperiod) value), so you should
-replace `2000-01-01T00:00:00Z` in these messages with the current time in ISO8601 format. You can
-get this by running:
+After data is sent to the Kafka stream, it is immediately available for querying.
-```bash
-python -c 'import datetime; print(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"))'
-```
+Please follow the [query tutorial](../tutorial/tutorial-query.html) to run some example queries on the newly loaded data.
-Update the timestamps in the JSON above, then copy and paste these messages into this console
-producer and press enter:
-
-```bash
-./bin/kafka-console-producer.sh --broker-list localhost:9092 --topic pageviews
-```
+## Cleanup
-That's it, your data should now be in Druid. You can immediately query it using any of the
-[supported query methods](../querying/querying.html).
+If you wish to go through any of the other ingestion tutorials, you will need to reset the cluster and follow these [reset instructions](index.html#resetting-the-cluster), as the other tutorials will write to the same "wikipedia" datasource.
## Further reading
-To read more about loading streams, see our [streaming ingestion documentation](../ingestion/stream-ingestion.html).
+For more information on loading data from Kafka streams, please see the [Druid Kafka indexing service documentation](http://druid.io/docs/{{druidVersion}}/development/extensions-core/kafka-ingestion.html).
diff --git a/docs/content/tutorials/tutorial-query.md b/docs/content/tutorials/tutorial-query.md
new file mode 100644
index 00000000000..3744df0c9a2
--- /dev/null
+++ b/docs/content/tutorials/tutorial-query.md
@@ -0,0 +1,362 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Querying data
+
+This tutorial will demonstrate how to query data in Druid, with examples for Druid's native query format and Druid SQL.
+
+The tutorial assumes that you've already completed one of the 4 ingestion tutorials, as we will be querying the sample Wikipedia edits data.
+
+* [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html)
+* [Tutorial: Loading stream data from Kafka](/docs/VERSION/tutorials/tutorial-kafka.html)
+* [Tutorial: Loading a file using Hadoop](/docs/VERSION/tutorials/tutorial-batch-hadoop.html)
+* [Tutorial: Loading stream data using Tranquility](/docs/VERSION/tutorials/tutorial-tranquility.html)
+
+## Native JSON queries
+
+Druid's native query format is expressed in JSON. We have included a sample native TopN query under `examples/wikipedia-top-pages.json`:
+
+```json
+{
+ "queryType" : "topN",
+ "dataSource" : "wikipedia",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "granularity" : "all",
+ "dimension" : "page",
+ "metric" : "count",
+ "threshold" : 10,
+ "aggregations" : [
+ {
+ "type" : "count",
+ "name" : "count"
+ }
+ ]
+}
+```
+
+This query retrieves the 10 Wikipedia pages with the most page edits on 2015-09-12.
+
+Let's submit this query to the Druid broker:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-top-pages.json http://localhost:8082/druid/v2?pretty
+```
+
+You should see the following query results:
+
+```json
+[ {
+ "timestamp" : "2015-09-12T00:46:58.771Z",
+ "result" : [ {
+ "count" : 33,
+ "page" : "Wikipedia:Vandalismusmeldung"
+ }, {
+ "count" : 28,
+ "page" : "User:Cyde/List of candidates for speedy deletion/Subpage"
+ }, {
+ "count" : 27,
+ "page" : "Jeremy Corbyn"
+ }, {
+ "count" : 21,
+ "page" : "Wikipedia:Administrators' noticeboard/Incidents"
+ }, {
+ "count" : 20,
+ "page" : "Flavia Pennetta"
+ }, {
+ "count" : 18,
+ "page" : "Total Drama Presents: The Ridonculous Race"
+ }, {
+ "count" : 18,
+ "page" : "User talk:Dudeperson176123"
+ }, {
+ "count" : 18,
+ "page" : "Wikipédia:Le Bistro/12 septembre 2015"
+ }, {
+ "count" : 17,
+ "page" : "Wikipedia:In the news/Candidates"
+ }, {
+ "count" : 17,
+ "page" : "Wikipedia:Requests for page protection"
+ } ]
+} ]
+```
+
+## Druid SQL queries
+
+Druid also supports a dialect of SQL for querying. Let's run a SQL query that is equivalent to the native JSON query shown above:
+
+```
+SELECT page, COUNT(*) AS Edits FROM wikipedia WHERE "__time" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00' GROUP BY page ORDER BY Edits DESC LIMIT 10;
+```
+
+The SQL queries are submitted as JSON over HTTP.
+
+### TopN query example
+
+The tutorial package includes an example file that contains the SQL query shown above at `examples/wikipedia-top-pages-sql.json`. Let's submit that query to the Druid broker:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-top-pages-sql.json http://localhost:8082/druid/v2/sql
+```
+
+The following results should be returned:
+
+```
+[
+ {
+ "page": "Wikipedia:Vandalismusmeldung",
+ "Edits": 33
+ },
+ {
+ "page": "User:Cyde/List of candidates for speedy deletion/Subpage",
+ "Edits": 28
+ },
+ {
+ "page": "Jeremy Corbyn",
+ "Edits": 27
+ },
+ {
+ "page": "Wikipedia:Administrators' noticeboard/Incidents",
+ "Edits": 21
+ },
+ {
+ "page": "Flavia Pennetta",
+ "Edits": 20
+ },
+ {
+ "page": "Total Drama Presents: The Ridonculous Race",
+ "Edits": 18
+ },
+ {
+ "page": "User talk:Dudeperson176123",
+ "Edits": 18
+ },
+ {
+ "page": "Wikipédia:Le Bistro/12 septembre 2015",
+ "Edits": 18
+ },
+ {
+ "page": "Wikipedia:In the news/Candidates",
+ "Edits": 17
+ },
+ {
+ "page": "Wikipedia:Requests for page protection",
+ "Edits": 17
+ }
+]
+```
+
+### Pretty Printing
+
+Note that Druid SQL does not support pretty printing of results. The output above was formatted using the [jq](https://stedolan.github.io/jq/) JSON processing tool. Other instances of SQL queries in these tutorials will also use `jq` formatting.
+
+### Additional Druid SQL queries
+
+The following section provides additional SQL examples that plan to various types of native Druid queries.
+
+#### Timeseries
+
+An example SQL timeseries query is available at `examples/wikipedia-timeseries-sql.json`. This query retrieves the total number of lines deleted from pages for each hour of 2015-09-12.
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-timeseries-sql.json http://localhost:8082/druid/v2/sql
+```
+
+The following results should be returned:
+
+```
+[
+ {
+ "HourTime": "2015-09-12T00:00:00.000Z",
+ "LinesDeleted": 1761
+ },
+ {
+ "HourTime": "2015-09-12T01:00:00.000Z",
+ "LinesDeleted": 16208
+ },
+ {
+ "HourTime": "2015-09-12T02:00:00.000Z",
+ "LinesDeleted": 14543
+ },
+ {
+ "HourTime": "2015-09-12T03:00:00.000Z",
+ "LinesDeleted": 13101
+ },
+ {
+ "HourTime": "2015-09-12T04:00:00.000Z",
+ "LinesDeleted": 12040
+ },
+ {
+ "HourTime": "2015-09-12T05:00:00.000Z",
+ "LinesDeleted": 6399
+ },
+ {
+ "HourTime": "2015-09-12T06:00:00.000Z",
+ "LinesDeleted": 9036
+ },
+ {
+ "HourTime": "2015-09-12T07:00:00.000Z",
+ "LinesDeleted": 11409
+ },
+ {
+ "HourTime": "2015-09-12T08:00:00.000Z",
+ "LinesDeleted": 11616
+ },
+ {
+ "HourTime": "2015-09-12T09:00:00.000Z",
+ "LinesDeleted": 17509
+ },
+ {
+ "HourTime": "2015-09-12T10:00:00.000Z",
+ "LinesDeleted": 19406
+ },
+ {
+ "HourTime": "2015-09-12T11:00:00.000Z",
+ "LinesDeleted": 16284
+ },
+ {
+ "HourTime": "2015-09-12T12:00:00.000Z",
+ "LinesDeleted": 18672
+ },
+ {
+ "HourTime": "2015-09-12T13:00:00.000Z",
+ "LinesDeleted": 30520
+ },
+ {
+ "HourTime": "2015-09-12T14:00:00.000Z",
+ "LinesDeleted": 18025
+ },
+ {
+ "HourTime": "2015-09-12T15:00:00.000Z",
+ "LinesDeleted": 26399
+ },
+ {
+ "HourTime": "2015-09-12T16:00:00.000Z",
+ "LinesDeleted": 24759
+ },
+ {
+ "HourTime": "2015-09-12T17:00:00.000Z",
+ "LinesDeleted": 19634
+ },
+ {
+ "HourTime": "2015-09-12T18:00:00.000Z",
+ "LinesDeleted": 17345
+ },
+ {
+ "HourTime": "2015-09-12T19:00:00.000Z",
+ "LinesDeleted": 19305
+ },
+ {
+ "HourTime": "2015-09-12T20:00:00.000Z",
+ "LinesDeleted": 22265
+ },
+ {
+ "HourTime": "2015-09-12T21:00:00.000Z",
+ "LinesDeleted": 16394
+ },
+ {
+ "HourTime": "2015-09-12T22:00:00.000Z",
+ "LinesDeleted": 16379
+ },
+ {
+ "HourTime": "2015-09-12T23:00:00.000Z",
+ "LinesDeleted": 15289
+ }
+]
+```
+#### GroupBy
+
+An example SQL GroupBy query is available at `examples/wikipedia-groupby-sql.json`. This query retrieves the total number of lines added for each Wikipedia language category (the channel) on 2015-09-12.
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-groupby-sql.json http://localhost:8082/druid/v2/sql
+```
+
+The following results should be returned:
+
+```
+[
+ {
+ "channel": "#en.wikipedia",
+ "EXPR$1": 3045299
+ },
+ {
+ "channel": "#it.wikipedia",
+ "EXPR$1": 711011
+ },
+ {
+ "channel": "#fr.wikipedia",
+ "EXPR$1": 642555
+ },
+ {
+ "channel": "#ru.wikipedia",
+ "EXPR$1": 640698
+ },
+ {
+ "channel": "#es.wikipedia",
+ "EXPR$1": 634670
+ }
+]
+```
+
+#### Scan
+
+An example SQL scan query is available at `examples/wikipedia-scan-sql.json`. This query retrieves 5 user-page pairs from the datasource.
+
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-scan-sql.json http://localhost:8082/druid/v2/sql
+```
+
+The following results should be returned:
+
+```
+[
+ {
+ "user": "Thiago89",
+ "page": "Campeonato Mundial de Voleibol Femenino Sub-20 de 2015"
+ },
+ {
+ "user": "91.34.200.249",
+ "page": "Friede von Schönbrunn"
+ },
+ {
+ "user": "TuHan-Bot",
+ "page": "Trĩ và ng"
+ },
+ {
+ "user": "Lowercase sigmabot III",
+ "page": "User talk:ErrantX"
+ },
+ {
+ "user": "BattyBot",
+ "page": "Hans W. Jung"
+ }
+]
+```
+
+#### EXPLAIN PLAN FOR
+
+By prepending `EXPLAIN PLAN FOR ` to a Druid SQL query, it is possible to see what native Druid queries a SQL query will plan into.
+
+An example query that explains the top pages query shown earlier has been provided at `examples/wikipedia-explain-sql.json`:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/wikipedia-explain-top-pages-sql.json http://localhost:8082/druid/v2/sql
+```
+
+This will return the following plan:
+```
+[
+ {
+ "PLAN": "DruidQueryRel(query=[{\"queryType\":\"topN\",\"dataSource\":{\"type\":\"table\",\"name\":\"wikipedia\"},\"virtualColumns\":[],\"dimension\":{\"type\":\"default\",\"dimension\":\"page\",\"outputName\":\"d0\",\"outputType\":\"STRING\"},\"metric\":{\"type\":\"numeric\",\"metric\":\"a0\"},\"threshold\":10,\"intervals\":{\"type\":\"intervals\",\"intervals\":[\"2015-09-12T00:00:00.000Z/2015-09-13T00:00:00.001Z\"]},\"filter\":null,\"granularity\":{\"type\":\"all\"},\"aggregations\":[{\"type\":\"count\",\"name\":\"a0\"}],\"postAggregations\":[],\"context\":{},\"descending\":false}], signature=[{d0:STRING, a0:LONG}])\n"
+ }
+]
+```
+
+## Further reading
+
+The [Queries documentation](/docs/VERSION/querying/querying.html) has more information on Druid's native JSON queries.
+
+The [Druid SQL documentation](/docs/VERSION/querying/sql.html) has more information on using Druid SQL queries.
\ No newline at end of file
diff --git a/docs/content/tutorials/tutorial-retention.md b/docs/content/tutorials/tutorial-retention.md
new file mode 100644
index 00000000000..afea21893bc
--- /dev/null
+++ b/docs/content/tutorials/tutorial-retention.md
@@ -0,0 +1,92 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Configuring data retention
+
+This tutorial demonstrates how to configure retention rules on a datasource to set the time intervals of data that will be retained or dropped.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html) and [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html).
+
+## Load the example data
+
+For this tutorial, we'll be using the Wikipedia edits sample data, with an ingestion task spec that will create a separate segment for each hour in the input data.
+
+The ingestion spec can be found at `examples/retention-index.json`. Let's submit that spec, which will create a datasource called `retention-tutorial`:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/retention-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After the ingestion completes, go to http://localhost:8081 in a browser to access the Coordinator console.
+
+In the Coordinator console, go to the `datasources` tab at the top of the page.
+
+This tab shows the available datasources and a summary of the retention rules for each datasource:
+
+
+
+Currently there are no rules set for the `retention-tutorial` datasource. Note that there are default rules, currently set to `load Forever 2 in _default_tier`.
+
+This means that all data will be loaded regardless of timestamp, and each segment will be replicated to two nodes in the default tier.
+
+In this tutorial, we will ignore the tiering and redundancy concepts for now.
+
+Let's click the `retention-tutorial` datasource on the left.
+
+The next page (http://localhost:8081/#/datasources/retention-tutorial) provides information about what segments a datasource contains. On the left, the page shows that there are 24 segments, each one containing data for a specific hour of 2015-09-12:
+
+
+
+## Set retention rules
+
+Suppose we want to drop data for the first 12 hours of 2015-09-12 and keep data for the later 12 hours of 2015-09-12.
+
+Click the `edit rules` button with a pencil icon at the upper left corner of the page.
+
+A rule configuration window will appear. Enter `tutorial` for both the user and changelog comment field.
+
+Now click the `+ Add a rule` button twice.
+
+In the `rule #1` box at the top, click `Load`, `Interval`, enter `2015-09-12T12:00:00.000Z/2015-09-13T00:00:00.000Z` in the interval box, and click `+ _default_tier replicant`.
+
+In the `rule #2` box at the bottom, click `Drop` and `Forever`.
+
+The rules should look like this:
+
+
+
+Now click `Save all rules`, wait for a few seconds, and refresh the page.
+
+The segments for the first 12 hours of 2015-09-12 are now gone:
+
+
+
+The resulting retention rule chain is the following:
+
+```
+loadByInterval 2015-09-12T12/2015-09-13 (12 hours)
+
+dropForever
+
+loadForever (default rule)
+```
+
+The rule chain is evaluated from top to bottom, with the default rule chain always added at the bottom.
+
+The tutorial rule chain we just created loads data if it is within the specified 12 hour interval.
+
+If data is not within the 12 hour interval, the rule chain evaluates `dropForever` next, which will drop any data.
+
+The `dropForever` terminates the rule chain, effectively overriding the default `loadForever` rule, which will never be reached in this rule chain.
+
+Note that in this tutorial we defined a load rule on a specific interval.
+
+If instead you want to retain data based on how old it is (e.g., retain data that ranges from 3 months in the past to the present time), you would define a Period load rule instead.
+
+## Further reading
+
+* [Load rules](/docs/VERSION/operations/rule-configuration.html)
diff --git a/docs/content/tutorials/tutorial-rollup.md b/docs/content/tutorials/tutorial-rollup.md
new file mode 100644
index 00000000000..8fe45849944
--- /dev/null
+++ b/docs/content/tutorials/tutorial-rollup.md
@@ -0,0 +1,221 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Roll-up
+
+Druid can summarize raw data at ingestion time using a process we refer to as "roll-up". Roll-up is a first-level aggregation operation over a selected set of columns that reduces the size of stored segments.
+
+This tutorial will demonstrate the effects of roll-up on an example dataset.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html) and [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html).
+
+## Example data
+
+For this tutorial, we'll use a small sample of network flow event data, representing packet and byte counts for traffic from a source to a destination IP address that occurred within a particular second.
+
+```
+{"timestamp":"2018-01-01T01:01:35Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":20,"bytes":9024}
+{"timestamp":"2018-01-01T01:01:51Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":255,"bytes":21133}
+{"timestamp":"2018-01-01T01:01:59Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":11,"bytes":5780}
+{"timestamp":"2018-01-01T01:02:14Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":38,"bytes":6289}
+{"timestamp":"2018-01-01T01:02:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":377,"bytes":359971}
+{"timestamp":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":49,"bytes":10204}
+{"timestamp":"2018-01-02T21:33:14Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":38,"bytes":6289}
+{"timestamp":"2018-01-02T21:33:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":123,"bytes":93999}
+{"timestamp":"2018-01-02T21:35:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":12,"bytes":2818}
+```
+
+A file containing this sample input data is located at `examples/rollup-data.json`.
+
+We'll ingest this data using the following ingestion task spec, located at `examples/rollup-index.json`.
+
+```
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "rollup-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "srcIP",
+ "dstIP"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples",
+ "filter" : "rollup-data.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
+```
+
+Roll-up has been enabled by setting `"rollup" : true` in the `granularitySpec`.
+
+Note that we have `srcIP` and `dstIP` defined as dimensions, a longSum metric is defined for the `packets` and `bytes` columns, and the `queryGranularity` has been defined as `minute`.
+
+We will see how these definitions are used after we load this data.
+
+## Load the example data
+
+From the druid-${DRUIDVERSION} package root, run the following command:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/rollup-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+After the data is loaded, we will query the data.
+
+## Query the example data
+
+Let's issue a `select * from "rollup-tutorial";` query to see what data was ingested.
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/rollup-select-sql.json http://localhost:8082/druid/v2/sql
+```
+
+The following results will be returned:
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "bytes": 35937,
+ "count": 3,
+ "dstIP": "2.2.2.2",
+ "packets": 286,
+ "srcIP": "1.1.1.1"
+ },
+ {
+ "__time": "2018-01-01T01:02:00.000Z",
+ "bytes": 366260,
+ "count": 2,
+ "dstIP": "2.2.2.2",
+ "packets": 415,
+ "srcIP": "1.1.1.1"
+ },
+ {
+ "__time": "2018-01-01T01:03:00.000Z",
+ "bytes": 10204,
+ "count": 1,
+ "dstIP": "2.2.2.2",
+ "packets": 49,
+ "srcIP": "1.1.1.1"
+ },
+ {
+ "__time": "2018-01-02T21:33:00.000Z",
+ "bytes": 100288,
+ "count": 2,
+ "dstIP": "8.8.8.8",
+ "packets": 161,
+ "srcIP": "7.7.7.7"
+ },
+ {
+ "__time": "2018-01-02T21:35:00.000Z",
+ "bytes": 2818,
+ "count": 1,
+ "dstIP": "8.8.8.8",
+ "packets": 12,
+ "srcIP": "7.7.7.7"
+ }
+]
+```
+
+Let's look at the three events in the original input data that occurred during `2018-01-01T01:01`:
+
+```
+{"timestamp":"2018-01-01T01:01:35Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":20,"bytes":9024}
+{"timestamp":"2018-01-01T01:01:51Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":255,"bytes":21133}
+{"timestamp":"2018-01-01T01:01:59Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":11,"bytes":5780}
+```
+
+These three rows have been "rolled up" into the following row:
+
+```
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "bytes": 35937,
+ "count": 3,
+ "dstIP": "2.2.2.2",
+ "packets": 286,
+ "srcIP": "1.1.1.1"
+ },
+```
+
+The input rows have been grouped by the timestamp and dimension columns `{timestamp, srcIP, dstIP}` with sum aggregations on the metric columns `packets` and `bytes`.
+
+Before the grouping occurs, the timestamps of the original input data are bucketed/floored by minute, due to the `"queryGranularity":"minute"` setting in the ingestion spec.
+
+Likewise, these two events that occurred during `2018-01-01T01:02` have been rolled up:
+
+```
+{"timestamp":"2018-01-01T01:02:14Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":38,"bytes":6289}
+{"timestamp":"2018-01-01T01:02:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":377,"bytes":359971}
+```
+
+```
+ {
+ "__time": "2018-01-01T01:02:00.000Z",
+ "bytes": 366260,
+ "count": 2,
+ "dstIP": "2.2.2.2",
+ "packets": 415,
+ "srcIP": "1.1.1.1"
+ },
+```
+
+For the last event recording traffic between 1.1.1.1 and 2.2.2.2, no roll-up took place, because this was the only event that occurred during `2018-01-01T01:03`:
+
+```
+{"timestamp":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":49,"bytes":10204}
+```
+
+```
+ {
+ "__time": "2018-01-01T01:03:00.000Z",
+ "bytes": 10204,
+ "count": 1,
+ "dstIP": "2.2.2.2",
+ "packets": 49,
+ "srcIP": "1.1.1.1"
+ },
+```
+
+Note that the `count` metric shows how many rows in the original input data contributed to the final "rolled up" row.
\ No newline at end of file
diff --git a/docs/content/tutorials/tutorial-streams.md b/docs/content/tutorials/tutorial-streams.md
deleted file mode 100644
index c20fb23a6c7..00000000000
--- a/docs/content/tutorials/tutorial-streams.md
+++ /dev/null
@@ -1,134 +0,0 @@
----
-layout: doc_page
----
-
-# Tutorial: Load your own streaming data
-
-## Getting started
-
-This tutorial shows you how to load your own streams into Druid.
-
-For this tutorial, we'll assume you've already downloaded Druid and Tranquility as described in
-the [single-machine quickstart](quickstart.html) and have it running on your local machine. You
-don't need to have loaded any data yet.
-
-Once that's complete, you can load your own dataset by writing a custom ingestion spec.
-
-## Writing an ingestion spec
-
-When loading streams into Druid, we recommend using the [stream push](../ingestion/stream-push.html)
-process. In this tutorial we'll be using [Tranquility Server](../ingestion/stream-ingestion.html#server) to push
-data into Druid over HTTP.
-
-<div class="note info">
-This tutorial will show you how to push streams to Druid using HTTP, but Druid additionally supports
-a wide variety of batch and streaming loading methods. See the <a href="../ingestion/batch-ingestion.html">Loading files</a>
-and <a href="../ingestion/stream-ingestion.html">Loading streams</a> pages for more information about other options,
-including from Hadoop, Kafka, Storm, Samza, Spark Streaming, and your own JVM apps.
-</div>
-
-You can prepare for loading a new dataset over HTTP by writing a custom Tranquility Server
-configuration. The bundled configuration is in `conf-quickstart/tranquility/server.json`, which
-you can modify for your own needs.
-
-The most important questions are:
-
- * What should the dataset be called? This is the "dataSource" field of the "dataSchema".
- * Which field should be treated as a timestamp? This belongs in the "column" field of the "timestampSpec".
- * Which fields should be treated as dimensions? This belongs in the "dimensions" field of the "dimensionsSpec".
- * Which fields should be treated as measures? This belongs in the "metricsSpec" field.
-
-Let's use a small JSON pageviews dataset as an example, with records like:
-
-```json
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "alice", "latencyMs": 32}
-```
-
-So the answers to the questions above are:
-
- * Let's call the dataset "pageviews".
- * The timestamp is the "time" field.
- * Good choices for dimensions are the string fields "url" and "user".
- * Good choices for measures are a count of pageviews, and the sum of "latencyMs". Collecting that
-sum when we load the data will allow us to compute an average at query time as well.
-
-Now, edit the existing `conf-quickstart/tranquility/server.json` file by altering these
-sections:
-
- 1. Change the key `"metrics"` under `"dataSources"` to `"pageviews"`
- 2. Alter these sections under the new `"pageviews"` key:
- ```json
- "dataSource": "pageviews"
- ```
-
- ```json
- "timestampSpec": {
- "format": "auto",
- "column": "time"
- }
- ```
-
- ```json
- "dimensionsSpec": {
- "dimensions": ["url", "user"]
- }
- ```
-
- ```json
- "metricsSpec": [
- {"name": "views", "type": "count"},
- {"name": "latencyMs", "type": "doubleSum", "fieldName": "latencyMs"}
- ]
- ```
-
-## Restarting the server
-
-Restart the server to pick up the new configuration file by stopping Tranquility (CTRL-C) and starting it up again.
-
-## Sending data
-
-Let's send some data! We'll start with these three records:
-
-```json
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "alice", "latencyMs": 32}
-{"time": "2000-01-01T00:00:00Z", "url": "/", "user": "bob", "latencyMs": 11}
-{"time": "2000-01-01T00:00:00Z", "url": "/foo/bar", "user": "bob", "latencyMs": 45}
-```
-
-Druid streaming ingestion requires relatively current messages (relative to a slack time controlled by the
-[windowPeriod](../ingestion/stream-push.html#segmentgranularity-and-windowperiod) value), so you should
-replace `2000-01-01T00:00:00Z` in these messages with the current time in ISO8601 format. You can
-get this by running:
-
-```bash
-python -c 'import datetime; print(datetime.datetime.utcnow().strftime("%Y-%m-%dT%H:%M:%SZ"))'
-```
-
-Update the timestamps in the JSON above, and save it to a file named `pageviews.json`. Then send
-it to Druid by running:
-
-```bash
-curl -XPOST -H'Content-Type: application/json' --data-binary @pageviews.json http://localhost:8200/v1/post/pageviews
-```
-
-This will print something like:
-
-```
-{"result":{"received":3,"sent":3}}
-```
-
-This indicates that the HTTP server received 3 events from you, and sent 3 to Druid. Note that
-this may take a few seconds to finish the first time you run it, as Druid resources must be
-allocated to the ingestion task. Subsequent POSTs should complete quickly.
-
-If you see `"sent":0` this likely means that your timestamps are not recent enough. Try adjusting
-your timestamps and re-sending your data.
-
-## Querying your data
-
-After sending data, you can immediately query it using any of the
-[supported query methods](../querying/querying.html).
-
-## Further reading
-
-To read more about loading streams, see our [streaming ingestion documentation](../ingestion/stream-ingestion.html).
diff --git a/docs/content/tutorials/tutorial-tranquility.md b/docs/content/tutorials/tutorial-tranquility.md
new file mode 100644
index 00000000000..773355c13ee
--- /dev/null
+++ b/docs/content/tutorials/tutorial-tranquility.md
@@ -0,0 +1,76 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Load streaming data with HTTP push
+
+## Getting started
+
+This tutorial shows you how to load streaming data into Druid using HTTP push via Tranquility Server.
+
+[Tranquility Server](https://github.com/druid-io/tranquility/blob/master/docs/server.md) allows a stream of data to be pushed into Druid using HTTP POSTs.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](quickstart.html) and have it running on your local machine. You
+don't need to have loaded any data yet.
+
+## Download Tranquility
+
+In the Druid package root, run the following commands:
+
+```
+curl http://static.druid.io/tranquility/releases/tranquility-distribution-0.8.2.tgz -o tranquility-distribution-0.8.2.tgz
+tar -xzf tranquility-distribution-0.8.2.tgz
+cd tranquility-distribution-0.8.2
+```
+
+## Run Tranquility server
+
+Run the following command:
+
+```
+bin/tranquility server -configFile ../examples/conf/tranquility/wikipedia-server.json -Ddruid.extensions.loadList=[]
+```
+
+## Send data
+
+Let's send the sample Wikipedia edits data to Tranquility:
+
+```
+curl -XPOST -H'Content-Type: application/json' --data-binary @quickstart/wikiticker-2015-09-12-sampled.json http://localhost:8200/v1/post/wikipedia
+```
+
+Which will print something like:
+
+```
+{"result":{"received":39244,"sent":39244}}
+```
+
+This indicates that the HTTP server received 39,244 events from you, and sent 39,244 to Druid. This
+command may generate a "connection refused" error if you run it too quickly after enabling Tranquility
+Server, which means the server has not yet started up. It should start up within a few seconds. The command
+may also take a few seconds to finish the first time you run it, during which time Druid resources are being
+allocated to the ingestion task. Subsequent POSTs will complete quickly once this is done.
+
+Once the data is sent to Druid, you can immediately query it.
+
+If you see a `sent` count of 0, retry the send command until the `sent` count also shows 39244:
+
+```
+{"result":{"received":39244,"sent":0}}
+```
+
+## Querying your data
+
+Please follow the [query tutorial](../tutorial/tutorial-query.html) to run some example queries on the newly loaded data.
+
+## Cleanup
+
+If you wish to go through any of the other ingestion tutorials, you will need to reset the cluster and follow these [reset instructions](index.html#resetting-the-cluster), as the other tutorials will write to the same "wikipedia" datasource.
+
+When cleaning up after running this Tranquility tutorial, it is also necessary to recomment the `tranquility-server` line in `quickstart/tutorial/conf/tutorial-cluster.conf` before restarting the cluster.
+
+
+## Further reading
+
+For more information on Tranquility, please see [the Tranquility documentation](https://github.com/druid-io/tranquility).
diff --git a/docs/content/tutorials/tutorial-transform-spec.md b/docs/content/tutorials/tutorial-transform-spec.md
new file mode 100644
index 00000000000..4d3ab0634ae
--- /dev/null
+++ b/docs/content/tutorials/tutorial-transform-spec.md
@@ -0,0 +1,159 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Transforming input data
+
+This tutorial will demonstrate how to use transform specs to filter and transform input data during ingestion.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html) and [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html).
+
+## Sample data
+
+We've included sample data for this tutorial at `examples/transform-data.json`, reproduced here for convenience:
+
+```
+{"timestamp":"2018-01-01T07:01:35Z","animal":"octopus", "location":1, "number":100}
+{"timestamp":"2018-01-01T05:01:35Z","animal":"mongoose", "location":2,"number":200}
+{"timestamp":"2018-01-01T06:01:35Z","animal":"snake", "location":3, "number":300}
+{"timestamp":"2018-01-01T01:01:35Z","animal":"lion", "location":4, "number":300}
+```
+
+## Load data with transform specs
+
+We will ingest the sample data using the following spec, which demonstrates the use of transform specs:
+
+```
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "transform-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal",
+ { "name": "location", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" },
+ { "type" : "longSum", "name" : "triple-number", "fieldName" : "triple-number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ },
+ "transformSpec": {
+ "transforms": [
+ {
+ "type": "expression",
+ "name": "animal",
+ "expression": "concat('super-', animal)"
+ },
+ {
+ "type": "expression",
+ "name": "triple-number",
+ "expression": "number * 3"
+ }
+ ],
+ "filter": {
+ "type":"or",
+ "fields": [
+ { "type": "selector", "dimension": "animal", "value": "super-mongoose" },
+ { "type": "selector", "dimension": "triple-number", "value": "300" },
+ { "type": "selector", "dimension": "location", "value": "3" }
+ ]
+ }
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "transform-data.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
+```
+
+In the transform spec, we have two expression transforms:
+* `super-animal`: prepends "super-" to the values in the `animal` column. This will override the `animal` column with the transformed version, since the transform's name is `animal`.
+* `triple-number`: multiplies the `number` column by 3. This will create a new `triple-number` column. Note that we are ingesting both the original and the transformed column.
+
+Additionally, we have an OR filter with three clauses:
+* `super-animal` values that match "super-mongoose"
+* `triple-number` values that match 300
+* `location` values that match 3
+
+This filter selects the first 3 rows, and it will exclude the final "lion" row in the input data. Note that the filter is applied after the transformation.
+
+Let's submit this task now, which has been included at `quickstart/tutorial/transform-index.json`:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/transform-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+## Query the transformed data
+
+Let's a `select * from "transform-tutorial";` query to see what was ingested:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/transform-select-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[
+ {
+ "__time": "2018-01-01T05:01:00.000Z",
+ "animal": "super-mongoose",
+ "count": 1,
+ "location": 2,
+ "number": 200,
+ "triple-number": 600
+ },
+ {
+ "__time": "2018-01-01T06:01:00.000Z",
+ "animal": "super-snake",
+ "count": 1,
+ "location": 3,
+ "number": 300,
+ "triple-number": 900
+ },
+ {
+ "__time": "2018-01-01T07:01:00.000Z",
+ "animal": "super-octopus",
+ "count": 1,
+ "location": 1,
+ "number": 100,
+ "triple-number": 300
+ }
+]
+```
+
+The "lion" row has been discarded, the `animal` column has been transformed, and we have both the original and transformed `number` column.
\ No newline at end of file
diff --git a/docs/content/tutorials/tutorial-update-data.md b/docs/content/tutorials/tutorial-update-data.md
new file mode 100644
index 00000000000..e37b18a9efb
--- /dev/null
+++ b/docs/content/tutorials/tutorial-update-data.md
@@ -0,0 +1,229 @@
+---
+layout: doc_page
+---
+
+# Tutorial: Updating existing data
+
+This tutorial demonstrates how to update existing data, showing both overwrites and appends.
+
+For this tutorial, we'll assume you've already downloaded Druid as described in
+the [single-machine quickstart](index.html) and have it running on your local machine.
+
+It will also be helpful to have finished [Tutorial: Loading a file](/docs/VERSION/tutorials/tutorial-batch.html), [Tutorial: Querying data](/docs/VERSION/tutorials/tutorial-query.html), and [Tutorial: Rollup](/docs/VERSION/tutorials/tutorial-rollup.html).
+
+## Overwrite
+
+This section of the tutorial will cover how to overwrite an existing interval of data.
+
+### Load initial data
+
+Let's load an initial data set which we will overwrite and append to.
+
+The spec we'll use for this tutorial is located at `examples/updates-init-index.json`. This spec creates a datasource called `updates-tutorial` from the `examples/updates-data.json` input file.
+
+Let's submit that task:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-init-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+We have three initial rows containing an "animal" dimension and "number" metric:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-select-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "animal": "tiger",
+ "count": 1,
+ "number": 100
+ },
+ {
+ "__time": "2018-01-01T03:01:00.000Z",
+ "animal": "aardvark",
+ "count": 1,
+ "number": 42
+ },
+ {
+ "__time": "2018-01-01T03:01:00.000Z",
+ "animal": "giraffe",
+ "count": 1,
+ "number": 14124
+ }
+]
+```
+
+### Overwrite the initial data
+
+To overwrite this data, we can submit another task for the same interval, but with different input data.
+
+The `examples/updates-overwrite-index.json` spec will perform an overwrite on the `updates-tutorial` datasource.
+
+Note that this task reads input from `examples/updates-data2.json`, and `appendToExisting` is set to `false` (indicating this is an overwrite).
+
+Let's submit that task:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-overwrite-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+When Druid finishes loading the new segment from this overwrite task, the "tiger" row now has the value "lion", the "aardvark" row has a different number, and the "giraffe" row has been replaced. It may take a couple of minutes for the changes to take effect:
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-select-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "animal": "lion",
+ "count": 1,
+ "number": 100
+ },
+ {
+ "__time": "2018-01-01T03:01:00.000Z",
+ "animal": "aardvark",
+ "count": 1,
+ "number": 9999
+ },
+ {
+ "__time": "2018-01-01T04:01:00.000Z",
+ "animal": "bear",
+ "count": 1,
+ "number": 111
+ }
+]
+
+```
+
+## Append to the data
+
+Let's try appending data.
+
+The `examples/updates-append-index.json` task spec reads input from `examples/updates-data3.json` and will append its data to the `updates-tutorial` datasource. Note that `appendToExisting` is set to `true` in this spec.
+
+Let's submit that task:
+
+```
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-append-index.json http://localhost:8090/druid/indexer/v1/task
+```
+
+When the new data is loaded, we can see two additional rows after "octopus". Note that the new "bear" row with number 222 has not been rolled up with the existing bear-111 row, because the new data is held in a separate segment. The same applies to the two "lion" rows.
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "animal": "lion",
+ "count": 1,
+ "number": 100
+ },
+ {
+ "__time": "2018-01-01T03:01:00.000Z",
+ "animal": "aardvark",
+ "count": 1,
+ "number": 9999
+ },
+ {
+ "__time": "2018-01-01T04:01:00.000Z",
+ "animal": "bear",
+ "count": 1,
+ "number": 111
+ },
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "animal": "lion",
+ "count": 1,
+ "number": 300
+ },
+ {
+ "__time": "2018-01-01T04:01:00.000Z",
+ "animal": "bear",
+ "count": 1,
+ "number": 222
+ },
+ {
+ "__time": "2018-01-01T05:01:00.000Z",
+ "animal": "mongoose",
+ "count": 1,
+ "number": 737
+ },
+ {
+ "__time": "2018-01-01T06:01:00.000Z",
+ "animal": "snake",
+ "count": 1,
+ "number": 1234
+ },
+ {
+ "__time": "2018-01-01T07:01:00.000Z",
+ "animal": "octopus",
+ "count": 1,
+ "number": 115
+ },
+ {
+ "__time": "2018-01-01T09:01:00.000Z",
+ "animal": "falcon",
+ "count": 1,
+ "number": 1241
+ }
+]
+```
+
+If we run a GroupBy query instead of a `select *`, we can see that the separate "lion" and "bear" rows will group together at query time:
+
+`select __time, animal, SUM("count"), SUM("number") from "updates-tutorial" group by __time, animal;`
+
+```bash
+curl -X 'POST' -H 'Content-Type:application/json' -d @examples/updates-groupby-sql.json http://localhost:8082/druid/v2/sql
+```
+
+```
+[
+ {
+ "__time": "2018-01-01T01:01:00.000Z",
+ "animal": "lion",
+ "EXPR$2": 2,
+ "EXPR$3": 400
+ },
+ {
+ "__time": "2018-01-01T03:01:00.000Z",
+ "animal": "aardvark",
+ "EXPR$2": 1,
+ "EXPR$3": 9999
+ },
+ {
+ "__time": "2018-01-01T04:01:00.000Z",
+ "animal": "bear",
+ "EXPR$2": 2,
+ "EXPR$3": 333
+ },
+ {
+ "__time": "2018-01-01T05:01:00.000Z",
+ "animal": "mongoose",
+ "EXPR$2": 1,
+ "EXPR$3": 737
+ },
+ {
+ "__time": "2018-01-01T06:01:00.000Z",
+ "animal": "snake",
+ "EXPR$2": 1,
+ "EXPR$3": 1234
+ },
+ {
+ "__time": "2018-01-01T07:01:00.000Z",
+ "animal": "octopus",
+ "EXPR$2": 1,
+ "EXPR$3": 115
+ },
+ {
+ "__time": "2018-01-01T09:01:00.000Z",
+ "animal": "falcon",
+ "EXPR$2": 1,
+ "EXPR$3": 1241
+ }
+]
+```
\ No newline at end of file
diff --git a/examples/conf-quickstart/druid/_common/common.runtime.properties b/examples/conf-quickstart/druid/_common/common.runtime.properties
index fd131b878cc..ee5b284b527 100644
--- a/examples/conf-quickstart/druid/_common/common.runtime.properties
+++ b/examples/conf-quickstart/druid/_common/common.runtime.properties
@@ -113,7 +113,7 @@ druid.selectors.coordinator.serviceName=druid/coordinator
# Monitoring
#
-druid.monitoring.monitors=["com.metamx.metrics.JvmMonitor"]
+druid.monitoring.monitors=["io.druid.java.util.metrics.JvmMonitor"]
druid.emitter=logging
druid.emitter.logging.logLevel=info
diff --git a/examples/conf-quickstart/druid/historical/runtime.properties b/examples/conf-quickstart/druid/historical/runtime.properties
index 8d8633d53ac..af900e8fbd5 100644
--- a/examples/conf-quickstart/druid/historical/runtime.properties
+++ b/examples/conf-quickstart/druid/historical/runtime.properties
@@ -9,5 +9,5 @@ druid.processing.buffer.sizeBytes=256000000
druid.processing.numThreads=2
# Segment storage
-druid.segmentCache.locations=[{"path":"var/druid/segment-cache","maxSize"\:300000000000}]
+druid.segmentCache.locations=[{"path":"var/druid/segment-cache","maxSize":300000000000}]
druid.server.maxSize=300000000000
diff --git a/examples/conf/druid/_common/common.runtime.properties b/examples/conf/druid/_common/common.runtime.properties
index a018fa01780..1c967fcd60c 100644
--- a/examples/conf/druid/_common/common.runtime.properties
+++ b/examples/conf/druid/_common/common.runtime.properties
@@ -112,7 +112,7 @@ druid.selectors.coordinator.serviceName=druid/coordinator
# Monitoring
#
-druid.monitoring.monitors=["com.metamx.metrics.JvmMonitor"]
+druid.monitoring.monitors=["io.druid.java.util.metrics.JvmMonitor"]
druid.emitter=logging
druid.emitter.logging.logLevel=info
diff --git a/examples/conf/druid/historical/runtime.properties b/examples/conf/druid/historical/runtime.properties
index 56f7f6e0fee..7b83a647070 100644
--- a/examples/conf/druid/historical/runtime.properties
+++ b/examples/conf/druid/historical/runtime.properties
@@ -9,5 +9,5 @@ druid.processing.buffer.sizeBytes=536870912
druid.processing.numThreads=7
# Segment storage
-druid.segmentCache.locations=[{"path":"var/druid/segment-cache","maxSize"\:130000000000}]
+druid.segmentCache.locations=[{"path":"var/druid/segment-cache","maxSize":130000000000}]
druid.server.maxSize=130000000000
diff --git a/examples/pom.xml b/examples/pom.xml
index 231469f4b06..10a20d9cc7f 100644
--- a/examples/pom.xml
+++ b/examples/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/examples/quickstart/tutorial/examples/compaction-count-sql.json b/examples/quickstart/tutorial/examples/compaction-count-sql.json
new file mode 100644
index 00000000000..1a835e3804a
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/compaction-count-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"select count(*) from \"compaction-tutorial\""
+}
diff --git a/examples/quickstart/tutorial/examples/compaction-final-index.json b/examples/quickstart/tutorial/examples/compaction-final-index.json
new file mode 100644
index 00000000000..b84e2ed78d5
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/compaction-final-index.json
@@ -0,0 +1,11 @@
+{
+ "type": "compact",
+ "dataSource": "compaction-tutorial",
+ "interval": "2015-09-12/2015-09-13",
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/compaction-init-index.json b/examples/quickstart/tutorial/examples/compaction-init-index.json
new file mode 100644
index 00000000000..f03c3714f51
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/compaction-init-index.json
@@ -0,0 +1,64 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "compaction-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "hour",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "quickstart/",
+ "filter" : "wikiticker-2015-09-12-sampled.json.gz"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/conf/druid/_common/common.runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/_common/common.runtime.properties
new file mode 100644
index 00000000000..bdff17d6cc0
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/_common/common.runtime.properties
@@ -0,0 +1,140 @@
+#
+# 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.
+#
+
+# Extensions specified in the load list will be loaded by Druid
+# We are using local fs for deep storage - not recommended for production - use S3, HDFS, or NFS instead
+# We are using local derby for the metadata store - not recommended for production - use MySQL or Postgres instead
+
+# If you specify `druid.extensions.loadList=[]`, Druid won't load any extension from file system.
+# If you don't specify `druid.extensions.loadList`, Druid will load all the extensions under root extension directory.
+# More info: http://druid.io/docs/latest/operations/including-extensions.html
+druid.extensions.loadList=["druid-hdfs-storage", "druid-kafka-indexing-service"]
+
+# If you have a different version of Hadoop, place your Hadoop client jar files in your hadoop-dependencies directory
+# and uncomment the line below to point to your directory.
+#druid.extensions.hadoopDependenciesDir=/my/dir/hadoop-dependencies
+
+
+#
+# Hostname
+#
+druid.host=localhost
+
+#
+# Logging
+#
+
+# Log all runtime properties on startup. Disable to avoid logging properties on startup:
+druid.startup.logging.logProperties=true
+
+#
+# Zookeeper
+#
+
+druid.zk.service.host=localhost
+druid.zk.paths.base=/druid
+
+#
+# Metadata storage
+#
+
+# For Derby server on your Druid Coordinator (only viable in a cluster with a single Coordinator, no fail-over):
+druid.metadata.storage.type=derby
+druid.metadata.storage.connector.connectURI=jdbc:derby://localhost:1527/var/druid/metadata.db;create=true
+druid.metadata.storage.connector.host=localhost
+druid.metadata.storage.connector.port=1527
+
+# For MySQL:
+#druid.metadata.storage.type=mysql
+#druid.metadata.storage.connector.connectURI=jdbc:mysql://db.example.com:3306/druid
+#druid.metadata.storage.connector.user=...
+#druid.metadata.storage.connector.password=...
+
+# For PostgreSQL:
+#druid.metadata.storage.type=postgresql
+#druid.metadata.storage.connector.connectURI=jdbc:postgresql://db.example.com:5432/druid
+#druid.metadata.storage.connector.user=...
+#druid.metadata.storage.connector.password=...
+
+#
+# Deep storage
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+druid.storage.type=local
+druid.storage.storageDirectory=var/druid/segments
+
+# For HDFS:
+#druid.storage.type=hdfs
+#druid.storage.storageDirectory=/druid/segments
+
+# For S3:
+#druid.storage.type=s3
+#druid.storage.bucket=your-bucket
+#druid.storage.baseKey=druid/segments
+#druid.s3.accessKey=...
+#druid.s3.secretKey=...
+
+#
+# Indexing service logs
+#
+
+# For local disk (only viable in a cluster if this is a network mount):
+druid.indexer.logs.type=file
+druid.indexer.logs.directory=var/druid/indexing-logs
+
+# For HDFS:
+#druid.indexer.logs.type=hdfs
+#druid.indexer.logs.directory=/druid/indexing-logs
+
+# For S3:
+#druid.indexer.logs.type=s3
+#druid.indexer.logs.s3Bucket=your-bucket
+#druid.indexer.logs.s3Prefix=druid/indexing-logs
+
+#
+# Service discovery
+#
+
+druid.selectors.indexing.serviceName=druid/overlord
+druid.selectors.coordinator.serviceName=druid/coordinator
+
+#
+# Monitoring
+#
+
+druid.monitoring.monitors=["io.druid.java.util.metrics.JvmMonitor"]
+druid.emitter=logging
+druid.emitter.logging.logLevel=info
+
+# Storage type of double columns
+# ommiting this will lead to index double as float at the storage layer
+
+druid.indexing.doubleStorage=double
+
+#
+# Security
+#
+druid.server.hiddenProperties=["druid.s3.accessKey","druid.s3.secretKey","druid.metadata.storage.connector.password"]
+
+
+#
+# SQL
+#
+druid.sql.enable=true
diff --git a/examples/quickstart/tutorial/examples/conf/druid/_common/hadoop-xml/dummyfile b/examples/quickstart/tutorial/examples/conf/druid/_common/hadoop-xml/dummyfile
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/examples/quickstart/tutorial/examples/conf/druid/_common/log4j2.xml b/examples/quickstart/tutorial/examples/conf/druid/_common/log4j2.xml
new file mode 100644
index 00000000000..a60ebda9eb4
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/_common/log4j2.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!--
+ ~ 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.
+-->
+
+<Configuration status="WARN">
+ <Appenders>
+ <Console name="Console" target="SYSTEM_OUT">
+ <PatternLayout pattern="%d{ISO8601} %p [%t] %c - %m%n"/>
+ </Console>
+ </Appenders>
+ <Loggers>
+ <Root level="info">
+ <AppenderRef ref="Console"/>
+ </Root>
+ </Loggers>
+</Configuration>
+
diff --git a/examples/quickstart/tutorial/examples/conf/druid/broker/jvm.config b/examples/quickstart/tutorial/examples/conf/druid/broker/jvm.config
new file mode 100644
index 00000000000..608aa35f84f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/broker/jvm.config
@@ -0,0 +1,8 @@
+-server
+-Xms1g
+-Xmx1g
+-XX:MaxDirectMemorySize=1792m
+-Duser.timezone=UTC
+-Dfile.encoding=UTF-8
+-Djava.io.tmpdir=var/tmp
+-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
diff --git a/examples/quickstart/tutorial/examples/conf/druid/broker/main.config b/examples/quickstart/tutorial/examples/conf/druid/broker/main.config
new file mode 100644
index 00000000000..de21e417fa1
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/broker/main.config
@@ -0,0 +1 @@
+io.druid.cli.Main server broker
diff --git a/examples/quickstart/tutorial/examples/conf/druid/broker/runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/broker/runtime.properties
new file mode 100644
index 00000000000..bb2aababe54
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/broker/runtime.properties
@@ -0,0 +1,16 @@
+druid.service=druid/broker
+druid.port=8082
+
+# HTTP server threads
+druid.broker.http.numConnections=5
+druid.server.http.numThreads=9
+
+# Processing threads and buffers
+druid.processing.buffer.sizeBytes=256000000
+druid.processing.numThreads=2
+
+# Query cache (we use a small local cache)
+druid.broker.cache.useCache=true
+druid.broker.cache.populateCache=true
+druid.cache.type=local
+druid.cache.sizeInBytes=10000000
diff --git a/examples/quickstart/tutorial/examples/conf/druid/coordinator/jvm.config b/examples/quickstart/tutorial/examples/conf/druid/coordinator/jvm.config
new file mode 100644
index 00000000000..66aa951e81c
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/coordinator/jvm.config
@@ -0,0 +1,8 @@
+-server
+-Xms256m
+-Xmx256m
+-Duser.timezone=UTC
+-Dfile.encoding=UTF-8
+-Djava.io.tmpdir=var/tmp
+-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
+-Dderby.stream.error.file=var/druid/derby.log
diff --git a/examples/quickstart/tutorial/examples/conf/druid/coordinator/main.config b/examples/quickstart/tutorial/examples/conf/druid/coordinator/main.config
new file mode 100644
index 00000000000..e8e6ed91e7b
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/coordinator/main.config
@@ -0,0 +1 @@
+io.druid.cli.Main server coordinator
diff --git a/examples/quickstart/tutorial/examples/conf/druid/coordinator/runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/coordinator/runtime.properties
new file mode 100644
index 00000000000..a61482f2a0f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/coordinator/runtime.properties
@@ -0,0 +1,5 @@
+druid.service=druid/coordinator
+druid.port=8081
+
+druid.coordinator.startDelay=PT10S
+druid.coordinator.period=PT5S
diff --git a/examples/quickstart/tutorial/examples/conf/druid/historical/jvm.config b/examples/quickstart/tutorial/examples/conf/druid/historical/jvm.config
new file mode 100644
index 00000000000..430209ec98e
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/historical/jvm.config
@@ -0,0 +1,8 @@
+-server
+-Xms1g
+-Xmx1g
+-XX:MaxDirectMemorySize=1280m
+-Duser.timezone=UTC
+-Dfile.encoding=UTF-8
+-Djava.io.tmpdir=var/tmp
+-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
diff --git a/examples/quickstart/tutorial/examples/conf/druid/historical/main.config b/examples/quickstart/tutorial/examples/conf/druid/historical/main.config
new file mode 100644
index 00000000000..1a7749356c4
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/historical/main.config
@@ -0,0 +1 @@
+io.druid.cli.Main server historical
diff --git a/examples/quickstart/tutorial/examples/conf/druid/historical/runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/historical/runtime.properties
new file mode 100644
index 00000000000..af900e8fbd5
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/historical/runtime.properties
@@ -0,0 +1,13 @@
+druid.service=druid/historical
+druid.port=8083
+
+# HTTP server threads
+druid.server.http.numThreads=9
+
+# Processing threads and buffers
+druid.processing.buffer.sizeBytes=256000000
+druid.processing.numThreads=2
+
+# Segment storage
+druid.segmentCache.locations=[{"path":"var/druid/segment-cache","maxSize":300000000000}]
+druid.server.maxSize=300000000000
diff --git a/examples/quickstart/tutorial/examples/conf/druid/middleManager/jvm.config b/examples/quickstart/tutorial/examples/conf/druid/middleManager/jvm.config
new file mode 100644
index 00000000000..7b9f1a47b55
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/middleManager/jvm.config
@@ -0,0 +1,7 @@
+-server
+-Xms64m
+-Xmx64m
+-Duser.timezone=UTC
+-Dfile.encoding=UTF-8
+-Djava.io.tmpdir=var/tmp
+-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
diff --git a/examples/quickstart/tutorial/examples/conf/druid/middleManager/main.config b/examples/quickstart/tutorial/examples/conf/druid/middleManager/main.config
new file mode 100644
index 00000000000..aa70653e6a2
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/middleManager/main.config
@@ -0,0 +1 @@
+io.druid.cli.Main server middleManager
diff --git a/examples/quickstart/tutorial/examples/conf/druid/middleManager/runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/middleManager/runtime.properties
new file mode 100644
index 00000000000..fcfb974603f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/middleManager/runtime.properties
@@ -0,0 +1,19 @@
+druid.service=druid/middleManager
+druid.port=8091
+
+# Number of tasks per middleManager
+druid.worker.capacity=3
+
+# Task launch parameters
+druid.indexer.runner.javaOpts=-server -Xmx2g -Duser.timezone=UTC -Dfile.encoding=UTF-8 -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
+druid.indexer.task.baseTaskDir=var/druid/task
+
+# HTTP server threads
+druid.server.http.numThreads=9
+
+# Processing threads and buffers on Peons
+druid.indexer.fork.property.druid.processing.buffer.sizeBytes=256000000
+druid.indexer.fork.property.druid.processing.numThreads=2
+
+# Hadoop indexing
+druid.indexer.task.hadoopWorkingPath=var/druid/hadoop-tmp
diff --git a/examples/quickstart/tutorial/examples/conf/druid/overlord/jvm.config b/examples/quickstart/tutorial/examples/conf/druid/overlord/jvm.config
new file mode 100644
index 00000000000..90526a53804
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/overlord/jvm.config
@@ -0,0 +1,7 @@
+-server
+-Xms256m
+-Xmx256m
+-Duser.timezone=UTC
+-Dfile.encoding=UTF-8
+-Djava.io.tmpdir=var/tmp
+-Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager
diff --git a/examples/quickstart/tutorial/examples/conf/druid/overlord/main.config b/examples/quickstart/tutorial/examples/conf/druid/overlord/main.config
new file mode 100644
index 00000000000..af7eda05b38
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/overlord/main.config
@@ -0,0 +1 @@
+io.druid.cli.Main server overlord
diff --git a/examples/quickstart/tutorial/examples/conf/druid/overlord/runtime.properties b/examples/quickstart/tutorial/examples/conf/druid/overlord/runtime.properties
new file mode 100644
index 00000000000..7ab544ad936
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/druid/overlord/runtime.properties
@@ -0,0 +1,7 @@
+druid.service=druid/overlord
+druid.port=8090
+
+druid.indexer.queue.startDelay=PT5S
+
+druid.indexer.runner.type=remote
+druid.indexer.storage.type=metadata
diff --git a/examples/quickstart/tutorial/examples/conf/tranquility/wikipedia-server.json b/examples/quickstart/tutorial/examples/conf/tranquility/wikipedia-server.json
new file mode 100644
index 00000000000..0895cab1e62
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/tranquility/wikipedia-server.json
@@ -0,0 +1,84 @@
+{
+ "dataSources" : {
+ "wikipedia" : {
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "wikipedia",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user"
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ {
+ "name" : "added",
+ "type" : "longSum",
+ "fieldName" : "added"
+ },
+ {
+ "name" : "deleted",
+ "type" : "longSum",
+ "fieldName" : "deleted"
+ },
+ {
+ "name" : "delta",
+ "type" : "longSum",
+ "fieldName" : "delta"
+ }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "day",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "realtime"
+ },
+ "tuningConfig" : {
+ "type" : "realtime",
+ "intermediatePersistPeriod" : "PT10M",
+ "windowPeriod" : "P3650D"
+ }
+ },
+ "properties" : {
+ "task.partitions" : "1",
+ "task.replicants" : "1"
+ }
+ }
+ },
+ "properties" : {
+ "zookeeper.connect" : "localhost",
+ "druid.discovery.curator.path" : "/druid/discovery",
+ "druid.selectors.indexing.serviceName" : "druid/overlord",
+ "http.port" : "8200",
+ "http.threads" : "9"
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/conf/tutorial-cluster.conf b/examples/quickstart/tutorial/examples/conf/tutorial-cluster.conf
new file mode 100644
index 00000000000..c1316cc5ba5
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/tutorial-cluster.conf
@@ -0,0 +1,13 @@
+:verify bin/verify-java
+:verify bin/verify-default-ports
+:kill-timeout 10
+
+!p10 zk bin/run-zk quickstart/tutorial/conf
+coordinator bin/run-druid coordinator quickstart/tutorial/conf
+broker bin/run-druid broker quickstart/tutorial/conf
+historical bin/run-druid historical quickstart/tutorial/conf
+!p80 overlord bin/run-druid overlord quickstart/tutorial/conf
+!p90 middleManager bin/run-druid middleManager quickstart/tutorial/conf
+
+# Uncomment to use Tranquility Server
+#!p95 tranquility-server tranquility/bin/tranquility server -configFile quickstart/tutorial/conf/tranquility/wikipedia-server.json -Ddruid.extensions.loadList=[]
diff --git a/examples/quickstart/tutorial/examples/conf/zk/jvm.config b/examples/quickstart/tutorial/examples/conf/zk/jvm.config
new file mode 100644
index 00000000000..3f2906d463f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/zk/jvm.config
@@ -0,0 +1,4 @@
+-server
+-Xms128m
+-Xmx128m
+-Duser.timezone=UTC
diff --git a/examples/quickstart/tutorial/examples/conf/zk/log4j.xml b/examples/quickstart/tutorial/examples/conf/zk/log4j.xml
new file mode 100644
index 00000000000..5ed9b01bdc8
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/zk/log4j.xml
@@ -0,0 +1,17 @@
+<?xml version="1.0" encoding="UTF-8" ?>
+<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
+
+<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
+ <appender name="console" class="org.apache.log4j.ConsoleAppender">
+ <param name="Target" value="System.out"/>
+ <layout class="org.apache.log4j.PatternLayout">
+ <param name="ConversionPattern" value="%d{ISO8601} %p [%t] %c - %m%n"/>
+ </layout>
+ </appender>
+
+ <root>
+ <priority value ="info" />
+ <appender-ref ref="console" />
+ </root>
+
+</log4j:configuration>
diff --git a/examples/quickstart/tutorial/examples/conf/zk/zoo.cfg b/examples/quickstart/tutorial/examples/conf/zk/zoo.cfg
new file mode 100644
index 00000000000..72e57e67d27
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/conf/zk/zoo.cfg
@@ -0,0 +1,16 @@
+#
+# Server
+#
+
+tickTime=2000
+dataDir=var/zk
+clientPort=2181
+initLimit=5
+syncLimit=2
+
+#
+# Autopurge
+#
+
+autopurge.snapRetainCount=5
+autopurge.purgeInterval=1
diff --git a/examples/quickstart/tutorial/examples/deletion-index.json b/examples/quickstart/tutorial/examples/deletion-index.json
new file mode 100644
index 00000000000..7f2f60af63f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/deletion-index.json
@@ -0,0 +1,64 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "deletion-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "hour",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "quickstart/",
+ "filter" : "wikiticker-2015-09-12-sampled.json.gz"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/deletion-kill.json b/examples/quickstart/tutorial/examples/deletion-kill.json
new file mode 100644
index 00000000000..c160a7c6632
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/deletion-kill.json
@@ -0,0 +1,5 @@
+{
+ "type": "kill",
+ "dataSource": "deletion-tutorial",
+ "interval" : "2015-09-12/2015-09-13"
+}
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/Dockerfile b/examples/quickstart/tutorial/examples/hadoop/docker/Dockerfile
new file mode 100644
index 00000000000..dbbd72240f7
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/Dockerfile
@@ -0,0 +1,107 @@
+# Creates pseudo distributed hadoop 2.7.3 with java 8
+#
+# Modified from the SequenceIQ Dockerfiles at https://github.com/sequenceiq/hadoop-docker
+#
+# docker build -t druid-hadoop-demo:2.7.3 .
+
+FROM sequenceiq/pam:centos-6.5
+MAINTAINER SequenceIQ
+
+USER root
+
+# install dev tools
+RUN yum clean all \
+ && rpm --rebuilddb \
+ && yum install -y curl which tar sudo openssh-server openssh-clients rsync yum-plugin-ovl\
+ && yum clean all \
+ && yum update -y libselinux \
+ && yum clean all
+# update libselinux. see https://github.com/sequenceiq/hadoop-docker/issues/14
+
+# passwordless ssh
+RUN ssh-keygen -q -N "" -t dsa -f /etc/ssh/ssh_host_dsa_key
+RUN ssh-keygen -q -N "" -t rsa -f /etc/ssh/ssh_host_rsa_key
+RUN ssh-keygen -q -N "" -t rsa -f /root/.ssh/id_rsa
+RUN cp /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys
+
+# zulu java 8
+RUN rpm --import http://repos.azulsystems.com/RPM-GPG-KEY-azulsystems
+RUN rpm --rebuilddb
+RUN sudo curl -o /etc/yum.repos.d/zulu.repo http://repos.azulsystems.com/rhel/zulu.repo
+RUN yum install -y zulu-8
+
+ENV JAVA_HOME /usr/lib/jvm/zulu-8
+ENV PATH $PATH:$JAVA_HOME/bin
+
+# hadoop
+RUN curl -s https://archive.apache.org/dist/hadoop/core/hadoop-2.7.3/hadoop-2.7.3.tar.gz | tar -xz -C /usr/local/
+RUN cd /usr/local && ln -s ./hadoop-2.7.3 hadoop
+
+ENV HADOOP_PREFIX /usr/local/hadoop
+ENV HADOOP_COMMON_HOME /usr/local/hadoop
+ENV HADOOP_HDFS_HOME /usr/local/hadoop
+ENV HADOOP_MAPRED_HOME /usr/local/hadoop
+ENV HADOOP_YARN_HOME /usr/local/hadoop
+ENV HADOOP_CONF_DIR /usr/local/hadoop/etc/hadoop
+ENV YARN_CONF_DIR $HADOOP_PREFIX/etc/hadoop
+
+RUN sed -i '/^export JAVA_HOME/ s:.*:export JAVA_HOME=/usr/lib/jvm/zulu-8\nexport HADOOP_PREFIX=/usr/local/hadoop\nexport HADOOP_HOME=/usr/local/hadoop\n:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh
+RUN sed -i '/^export HADOOP_CONF_DIR/ s:.*:export HADOOP_CONF_DIR=/usr/local/hadoop/etc/hadoop/:' $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh
+
+RUN mkdir $HADOOP_PREFIX/input
+RUN cp $HADOOP_PREFIX/etc/hadoop/*.xml $HADOOP_PREFIX/input
+
+# pseudo distributed
+ADD core-site.xml.template $HADOOP_PREFIX/etc/hadoop/core-site.xml.template
+RUN sed s/HOSTNAME/localhost/ /usr/local/hadoop/etc/hadoop/core-site.xml.template > /usr/local/hadoop/etc/hadoop/core-site.xml
+ADD hdfs-site.xml $HADOOP_PREFIX/etc/hadoop/hdfs-site.xml
+
+ADD mapred-site.xml $HADOOP_PREFIX/etc/hadoop/mapred-site.xml
+ADD yarn-site.xml $HADOOP_PREFIX/etc/hadoop/yarn-site.xml
+
+RUN $HADOOP_PREFIX/bin/hdfs namenode -format
+
+ADD ssh_config /root/.ssh/config
+RUN chmod 600 /root/.ssh/config
+RUN chown root:root /root/.ssh/config
+
+# # installing supervisord
+# RUN yum install -y python-setuptools
+# RUN easy_install pip
+# RUN curl https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py -o - | python
+# RUN pip install supervisor
+#
+# ADD supervisord.conf /etc/supervisord.conf
+
+ADD bootstrap.sh /etc/bootstrap.sh
+RUN chown root:root /etc/bootstrap.sh
+RUN chmod 700 /etc/bootstrap.sh
+
+ENV BOOTSTRAP /etc/bootstrap.sh
+
+# workingaround docker.io build error
+RUN ls -la /usr/local/hadoop/etc/hadoop/*-env.sh
+RUN chmod +x /usr/local/hadoop/etc/hadoop/*-env.sh
+RUN ls -la /usr/local/hadoop/etc/hadoop/*-env.sh
+
+# Copy additional .jars to classpath
+RUN cp /usr/local/hadoop/share/hadoop/tools/lib/*.jar /usr/local/hadoop/share/hadoop/common/lib/
+
+# fix the 254 error code
+RUN sed -i "/^[^#]*UsePAM/ s/.*/#&/" /etc/ssh/sshd_config
+RUN echo "UsePAM no" >> /etc/ssh/sshd_config
+RUN echo "Port 2122" >> /etc/ssh/sshd_config
+
+RUN service sshd start && $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && $HADOOP_PREFIX/sbin/start-dfs.sh && $HADOOP_PREFIX/bin/hdfs dfs -mkdir -p /user/root
+RUN service sshd start && $HADOOP_PREFIX/etc/hadoop/hadoop-env.sh && $HADOOP_PREFIX/sbin/start-dfs.sh && $HADOOP_PREFIX/bin/hdfs dfs -put $HADOOP_PREFIX/etc/hadoop/ input
+
+CMD ["/etc/bootstrap.sh", "-d"]
+
+# Hdfs ports
+EXPOSE 50010 50020 50070 50075 50090 8020 9000
+# Mapred ports
+EXPOSE 10020 19888
+#Yarn ports
+EXPOSE 8030 8031 8032 8033 8040 8042 8088
+#Other ports
+EXPOSE 49707 2122
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/LICENSE b/examples/quickstart/tutorial/examples/hadoop/docker/LICENSE
new file mode 100644
index 00000000000..4f4964bf3f3
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/LICENSE
@@ -0,0 +1,1331 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed 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.
+
+
+Apache Knox Subcomponents (binary distributions):
+
+Apache Knox includes a number of sub-components with separate copyright
+notices and license terms. Your use of these sub-components is subject
+to the terms and conditions of the following licenses.
+
+------------------------------------------------------------------------------
+From Jetty and Jerico
+------------------------------------------------------------------------------
+Eclipse Public License - v 1.0
+
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
+LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
+CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
+
+1. DEFINITIONS
+
+"Contribution" means:
+
+a) in the case of the initial Contributor, the initial code and documentation
+distributed under this Agreement, and
+
+b) in the case of each subsequent Contributor:
+
+i) changes to the Program, and
+
+ii) additions to the Program;
+
+where such changes and/or additions to the Program originate from and are
+distributed by that particular Contributor. A Contribution 'originates' from a
+Contributor if it was added to the Program by such Contributor itself or anyone
+acting on such Contributor's behalf. Contributions do not include additions to
+the Program which: (i) are separate modules of software distributed in
+conjunction with the Program under their own license agreement, and (ii) are not
+derivative works of the Program.
+
+"Contributor" means any person or entity that distributes the Program.
+
+"Licensed Patents" mean patent claims licensable by a Contributor which are
+necessarily infringed by the use or sale of its Contribution alone or when
+combined with the Program.
+
+"Program" means the Contributions distributed in accordance with this Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement,
+including all Contributors.
+
+2. GRANT OF RIGHTS
+
+a) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free copyright license to
+reproduce, prepare derivative works of, publicly display, publicly perform,
+distribute and sublicense the Contribution of such Contributor, if any, and such
+derivative works, in source code and object code form.
+
+b) Subject to the terms of this Agreement, each Contributor hereby grants
+Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed
+Patents to make, use, sell, offer to sell, import and otherwise transfer the
+Contribution of such Contributor, if any, in source code and object code form.
+This patent license shall apply to the combination of the Contribution and the
+Program if, at the time the Contribution is added by the Contributor, such
+addition of the Contribution causes such combination to be covered by the
+Licensed Patents. The patent license shall not apply to any other combinations
+which include the Contribution. No hardware per se is licensed hereunder.
+
+c) Recipient understands that although each Contributor grants the licenses to
+its Contributions set forth herein, no assurances are provided by any
+Contributor that the Program does not infringe the patent or other intellectual
+property rights of any other entity. Each Contributor disclaims any liability to
+Recipient for claims brought by any other entity based on infringement of
+intellectual property rights or otherwise. As a condition to exercising the
+rights and licenses granted hereunder, each Recipient hereby assumes sole
+responsibility to secure any other intellectual property rights needed, if any.
+For example, if a third party patent license is required to allow Recipient to
+distribute the Program, it is Recipient's responsibility to acquire that license
+before distributing the Program.
+
+d) Each Contributor represents that to its knowledge it has sufficient copyright
+rights in its Contribution, if any, to grant the copyright license set forth in
+this Agreement.
+
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form under its
+own license agreement, provided that:
+
+a) it complies with the terms and conditions of this Agreement; and
+
+b) its license agreement:
+
+i) effectively disclaims on behalf of all Contributors all warranties and
+conditions, express and implied, including warranties or conditions of title and
+non-infringement, and implied warranties or conditions of merchantability and
+fitness for a particular purpose;
+
+ii) effectively excludes on behalf of all Contributors all liability for
+damages, including direct, indirect, special, incidental and consequential
+damages, such as lost profits;
+
+iii) states that any provisions which differ from this Agreement are offered by
+that Contributor alone and not by any other party; and
+
+iv) states that source code for the Program is available from such Contributor,
+and informs licensees how to obtain it in a reasonable manner on or through a
+medium customarily used for software exchange.
+
+When the Program is made available in source code form:
+
+a) it must be made available under this Agreement; and
+
+b) a copy of this Agreement must be included with each copy of the Program.
+
+Contributors may not remove or alter any copyright notices contained within the
+Program.
+
+Each Contributor must identify itself as the originator of its Contribution, if
+any, in a manner that reasonably allows subsequent Recipients to identify the
+originator of the Contribution.
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with
+respect to end users, business partners and the like. While this license is
+intended to facilitate the commercial use of the Program, the Contributor who
+includes the Program in a commercial product offering should do so in a manner
+which does not create potential liability for other Contributors. Therefore, if
+a Contributor includes the Program in a commercial product offering, such
+Contributor ("Commercial Contributor") hereby agrees to defend and indemnify
+every other Contributor ("Indemnified Contributor") against any losses, damages
+and costs (collectively "Losses") arising from claims, lawsuits and other legal
+actions brought by a third party against the Indemnified Contributor to the
+extent caused by the acts or omissions of such Commercial Contributor in
+connection with its distribution of the Program in a commercial product
+offering. The obligations in this section do not apply to any claims or Losses
+relating to any actual or alleged intellectual property infringement. In order
+to qualify, an Indemnified Contributor must: a) promptly notify the Commercial
+Contributor in writing of such claim, and b) allow the Commercial Contributor
+to control, and cooperate with the Commercial Contributor in, the defense and
+any related settlement negotiations. The Indemnified Contributor may
+participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product
+offering, Product X. That Contributor is then a Commercial Contributor. If that
+Commercial Contributor then makes performance claims, or offers warranties
+related to Product X, those performance claims and warranties are such
+Commercial Contributor's responsibility alone. Under this section, the
+Commercial Contributor would have to defend claims against the other
+Contributors related to those performance claims and warranties, and if a court
+requires any other Contributor to pay any damages as a result, the Commercial
+Contributor must pay those damages.
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN
+"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
+IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE,
+NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each
+Recipient is solely responsible for determining the appropriateness of using and
+distributing the Program and assumes all risks associated with its exercise of
+rights under this Agreement , including but not limited to the risks and costs
+of program errors, compliance with applicable laws, damage to or loss of data,
+programs or equipment, and unavailability or interruption of operations.
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
+CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST
+PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
+OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS
+GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under applicable
+law, it shall not affect the validity or enforceability of the remainder of the
+terms of this Agreement, and without further action by the parties hereto, such
+provision shall be reformed to the minimum extent necessary to make such
+provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Program itself
+(excluding combinations of the Program with other software or hardware)
+infringes such Recipient's patent(s), then such Recipient's rights granted under
+Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient's rights under this Agreement shall terminate if it fails to
+comply with any of the material terms or conditions of this Agreement and does
+not cure such failure in a reasonable period of time after becoming aware of
+such noncompliance. If all Recipient's rights under this Agreement terminate,
+Recipient agrees to cease use and distribution of the Program as soon as
+reasonably practicable. However, Recipient's obligations under this Agreement
+and any licenses granted by Recipient relating to the Program shall continue and
+survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in
+order to avoid inconsistency the Agreement is copyrighted and may only be
+modified in the following manner. The Agreement Steward reserves the right to
+publish new versions (including revisions) of this Agreement from time to time.
+No one other than the Agreement Steward has the right to modify this Agreement.
+The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation
+may assign the responsibility to serve as the Agreement Steward to a suitable
+separate entity. Each new version of the Agreement will be given a
+distinguishing version number. The Program (including Contributions) may always
+be distributed subject to the version of the Agreement under which it was
+received. In addition, after a new version of the Agreement is published,
+Contributor may elect to distribute the Program (including its Contributions)
+under the new version. Except as expressly stated in Sections 2(a) and 2(b)
+above, Recipient receives no rights or licenses to the intellectual property of
+any Contributor under this Agreement, whether expressly, by implication,
+estoppel or otherwise. All rights in the Program not expressly granted under
+this Agreement are reserved.
+
+This Agreement is governed by the laws of the State of New York and the
+intellectual property laws of the United States of America. No party to this
+Agreement will bring a legal action under this Agreement more than one year
+after the cause of action arose. Each party waives its rights to a jury trial in
+any resulting litigation.
+
+
+For TODO.jar (Jave EE Servlet API)
+
+COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
+
+1. Definitions.
+
+ 1.1. Contributor. means each individual or entity that creates or contributes
+ to the creation of Modifications.
+
+ 1.2. Contributor Version. means the combination of the Original Software,
+ prior Modifications used by a Contributor (if any), and the
+ Modifications made by that particular Contributor.
+
+ 1.3. Covered Software. means (a) the Original Software, or (b) Modifications,
+ or (c) the combination of files containing Original Software with files
+ containing Modifications, in each case including portions thereof.
+
+ 1.4. Executable. means the Covered Software in any form other than Source
+ Code.
+
+ 1.5. Initial Developer. means the individual or entity that first makes
+ Original Software available under this License.
+
+ 1.6. Larger Work. means a work which combines Covered Software or portions
+ thereof with code not governed by the terms of this License.
+
+ 1.7. License. means this document.
+
+ 1.8. Licensable. means having the right to grant, to the maximum extent
+ possible, whether at the time of the initial grant or subsequently
+ acquired, any and all of the rights conveyed herein.
+
+ 1.9. Modifications. means the Source Code and Executable form of any of the
+ following:
+
+ A. Any file that results from an addition to, deletion from or
+ modification of the contents of a file containing Original Software
+ or previous Modifications;
+
+ B. Any new file that contains any part of the Original Software or
+ previous Modification; or
+
+ C. Any new file that is contributed or otherwise made available under
+ the terms of this License.
+
+ 1.10. Original Software. means the Source Code and Executable form of
+ computer software code that is originally released under this License.
+
+ 1.11. Patent Claims. means any patent claim(s), now owned or hereafter
+ acquired, including without limitation, method, process, and apparatus
+ claims, in any patent Licensable by grantor.
+
+ 1.12. Source Code. means (a) the common form of computer software code in
+ which modifications are made and (b) associated documentation included
+ in or with such code.
+
+ 1.13. You. (or .Your.) means an individual or a legal entity exercising
+ rights under, and complying with all of the terms of, this License. For
+ legal entities, .You. includes any entity which controls, is controlled
+ by, or is under common control with You. For purposes of this
+ definition, .control. means (a) the power, direct or indirect, to cause
+ the direction or management of such entity, whether by contract or
+ otherwise, or (b) ownership of more than fifty percent (50%) of the
+ outstanding shares or beneficial ownership of such entity.
+
+2. License Grants.
+
+ 2.1. The Initial Developer Grant.
+
+ Conditioned upon Your compliance with Section 3.1 below and subject to
+ third party intellectual property claims, the Initial Developer hereby
+ grants You a world-wide, royalty-free, non-exclusive license:
+
+ (a) under intellectual property rights (other than patent or trademark)
+ Licensable by Initial Developer, to use, reproduce, modify, display,
+ perform, sublicense and distribute the Original Software (or
+ portions thereof), with or without Modifications, and/or as part of
+ a Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using or selling of
+ Original Software, to make, have made, use, practice, sell, and
+ offer for sale, and/or otherwise dispose of the Original Software
+ (or portions thereof).
+
+ (c) The licenses granted in Sections 2.1(a) and (b) are effective on the
+ date Initial Developer first distributes or otherwise makes the
+ Original Software available to a third party under the terms of this
+ License.
+
+ (d) Notwithstanding Section 2.1(b) above, no patent license is granted:
+ (1) for code that You delete from the Original Software, or (2) for
+ infringements caused by: (i) the modification of the Original
+ Software, or (ii) the combination of the Original Software with
+ other software or devices.
+
+ 2.2. Contributor Grant.
+
+ Conditioned upon Your compliance with Section 3.1 below and subject to third
+ party intellectual property claims, each Contributor hereby grants You a
+ world-wide, royalty-free, non-exclusive license:
+
+ (a) under intellectual property rights (other than patent or trademark)
+ Licensable by Contributor to use, reproduce, modify, display,
+ perform, sublicense and distribute the Modifications created by such
+ Contributor (or portions thereof), either on an unmodified basis,
+ with other Modifications, as Covered Software and/or as part of a
+ Larger Work; and
+
+ (b) under Patent Claims infringed by the making, using, or selling of
+ Modifications made by that Contributor either alone and/or in
+ combination with its Contributor Version (or portions of such
+ combination), to make, use, sell, offer for sale, have made, and/or
+ otherwise dispose of: (1) Modifications made by that Contributor (or
+ portions thereof); and (2) the combination of Modifications made by
+ that Contributor with its Contributor Version (or portions of such
+ combination).
+
+ (c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on
+ the date Contributor first distributes or otherwise makes the
+ Modifications available to a third party.
+
+ (d) Notwithstanding Section 2.2(b) above, no patent license is granted:
+ (1) for any code that Contributor has deleted from the Contributor
+ Version; (2) for infringements caused by: (i) third party
+ modifications of Contributor Version, or (ii) the combination of
+ Modifications made by that Contributor with other software (except
+ as part of the Contributor Version) or other devices; or (3) under
+ Patent Claims infringed by Covered Software in the absence of
+ Modifications made by that Contributor.
+
+3. Distribution Obligations.
+
+ 3.1. Availability of Source Code.
+ Any Covered Software that You distribute or otherwise make available in
+ Executable form must also be made available in Source Code form and that
+ Source Code form must be distributed only under the terms of this License.
+ You must include a copy of this License with every copy of the Source Code
+ form of the Covered Software You distribute or otherwise make available.
+ You must inform recipients of any such Covered Software in Executable form
+ as to how they can obtain such Covered Software in Source Code form in a
+ reasonable manner on or through a medium customarily used for software
+ exchange.
+
+ 3.2. Modifications.
+ The Modifications that You create or to which You contribute are governed
+ by the terms of this License. You represent that You believe Your
+ Modifications are Your original creation(s) and/or You have sufficient
+ rights to grant the rights conveyed by this License.
+
+ 3.3. Required Notices.
+ You must include a notice in each of Your Modifications that identifies
+ You as the Contributor of the Modification. You may not remove or alter
+ any copyright, patent or trademark notices contained within the Covered
+ Software, or any notices of licensing or any descriptive text giving
+ attribution to any Contributor or the Initial Developer.
+
+ 3.4. Application of Additional Terms.
+ You may not offer or impose any terms on any Covered Software in Source
+ Code form that alters or restricts the applicable version of this License
+ or the recipients. rights hereunder. You may choose to offer, and to
+ charge a fee for, warranty, support, indemnity or liability obligations to
+ one or more recipients of Covered Software. However, you may do so only on
+ Your own behalf, and not on behalf of the Initial Developer or any
+ Contributor. You must make it absolutely clear that any such warranty,
+ support, indemnity or liability obligation is offered by You alone, and
+ You hereby agree to indemnify the Initial Developer and every Contributor
+ for any liability incurred by the Initial Developer or such Contributor as
+ a result of warranty, support, indemnity or liability terms You offer.
+
+ 3.5. Distribution of Executable Versions.
+ You may distribute the Executable form of the Covered Software under the
+ terms of this License or under the terms of a license of Your choice,
+ which may contain terms different from this License, provided that You are
+ in compliance with the terms of this License and that the license for the
+ Executable form does not attempt to limit or alter the recipient.s rights
+ in the Source Code form from the rights set forth in this License. If You
+ distribute the Covered Software in Executable form under a different
+ license, You must make it absolutely clear that any terms which differ
+ from this License are offered by You alone, not by the Initial Developer
+ or Contributor. You hereby agree to indemnify the Initial Developer and
+ every Contributor for any liability incurred by the Initial Developer or
+ such Contributor as a result of any such terms You offer.
+
+ 3.6. Larger Works.
+ You may create a Larger Work by combining Covered Software with other code
+ not governed by the terms of this License and distribute the Larger Work
+ as a single product. In such a case, You must make sure the requirements
+ of this License are fulfilled for the Covered Software.
+
+4. Versions of the License.
+
+ 4.1. New Versions.
+ Sun Microsystems, Inc. is the initial license steward and may publish
+ revised and/or new versions of this License from time to time. Each
+ version will be given a distinguishing version number. Except as provided
+ in Section 4.3, no one other than the license steward has the right to
+ modify this License.
+
+ 4.2. Effect of New Versions.
+ You may always continue to use, distribute or otherwise make the Covered
+ Software available under the terms of the version of the License under
+ which You originally received the Covered Software. If the Initial
+ Developer includes a notice in the Original Software prohibiting it from
+ being distributed or otherwise made available under any subsequent version
+ of the License, You must distribute and make the Covered Software
+ available under the terms of the version of the License under which You
+ originally received the Covered Software. Otherwise, You may also choose
+ to use, distribute or otherwise make the Covered Software available under
+ the terms of any subsequent version of the License published by the
+ license steward.
+
+ 4.3. Modified Versions.
+ When You are an Initial Developer and You want to create a new license for
+ Your Original Software, You may create and use a modified version of this
+ License if You: (a) rename the license and remove any references to the
+ name of the license steward (except to note that the license differs from
+ this License); and (b) otherwise make it clear that the license contains
+ terms which differ from this License.
+
+5. DISCLAIMER OF WARRANTY.
+
+ COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN .AS IS. BASIS, WITHOUT
+ WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT
+ LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS,
+ MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK
+ AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD
+ ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL
+ DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY
+ SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN
+ ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED
+ HEREUNDER EXCEPT UNDER THIS DISCLAIMER.
+
+6. TERMINATION.
+
+ 6.1. This License and the rights granted hereunder will terminate
+ automatically if You fail to comply with terms herein and fail to
+ cure such breach within 30 days of becoming aware of the breach.
+ Provisions which, by their nature, must remain in effect beyond the
+ termination of this License shall survive.
+
+ 6.2. If You assert a patent infringement claim (excluding declaratory
+ judgment actions) against Initial Developer or a Contributor (the
+ Initial Developer or Contributor against whom You assert such claim
+ is referred to as .Participant.) alleging that the Participant
+ Software (meaning the Contributor Version where the Participant is a
+ Contributor or the Original Software where the Participant is the
+ Initial Developer) directly or indirectly infringes any patent, then
+ any and all rights granted directly or indirectly to You by such
+ Participant, the Initial Developer (if the Initial Developer is not
+ the Participant) and all Contributors under Sections 2.1 and/or 2.2
+ of this License shall, upon 60 days notice from Participant terminate
+ prospectively and automatically at the expiration of such 60 day
+ notice period, unless if within such 60 day period You withdraw Your
+ claim with respect to the Participant Software against such
+ Participant either unilaterally or pursuant to a written agreement
+ with Participant.
+
+ 6.3. In the event of termination under Sections 6.1 or 6.2 above, all end
+ user licenses that have been validly granted by You or any
+ distributor hereunder prior to termination (excluding licenses
+ granted to You by any distributor) shall survive termination.
+
+7. LIMITATION OF LIABILITY.
+
+ UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING
+ NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY
+ OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF
+ ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL,
+ INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT
+ LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE,
+ COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR
+ LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF
+ SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR
+ DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY.S NEGLIGENCE TO THE EXTENT
+ APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE
+ EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS
+ EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU.
+
+8. U.S. GOVERNMENT END USERS.
+
+ The Covered Software is a .commercial item,. as that term is defined in 48
+ C.F.R. 2.101 (Oct. 1995), consisting of .commercial computer software. (as
+ that term is defined at 48 C.F.R. ? 252.227-7014(a)(1)) and commercial
+ computer software documentation. as such terms are used in 48 C.F.R. 12.212
+ (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1
+ through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered
+ Software with only those rights set forth herein. This U.S. Government Rights
+ clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or
+ provision that addresses Government rights in computer software under this
+ License.
+
+9. MISCELLANEOUS.
+
+ This License represents the complete agreement concerning subject matter
+ hereof. If any provision of this License is held to be unenforceable, such
+ provision shall be reformed only to the extent necessary to make it
+ enforceable. This License shall be governed by the law of the jurisdiction
+ specified in a notice contained within the Original Software (except to the
+ extent applicable law, if any, provides otherwise), excluding such
+ jurisdiction's conflict-of-law provisions. Any litigation relating to this
+ License shall be subject to the jurisdiction of the courts located in the
+ jurisdiction and venue specified in a notice contained within the Original
+ Software, with the losing party responsible for costs, including, without
+ limitation, court costs and reasonable attorneys. fees and expenses. The
+ application of the United Nations Convention on Contracts for the
+ International Sale of Goods is expressly excluded. Any law or regulation
+ which provides that the language of a contract shall be construed against
+ the drafter shall not apply to this License. You agree that You alone are
+ responsible for compliance with the United States export administration
+ regulations (and the export control laws and regulation of any other
+ countries) when You use, distribute or otherwise make available any Covered
+ Software.
+
+10. RESPONSIBILITY FOR CLAIMS.
+
+ As between Initial Developer and the Contributors, each party is responsible
+ for claims and damages arising, directly or indirectly, out of its
+ utilization of rights under this License and You agree to work with Initial
+ Developer and Contributors to distribute such responsibility on an equitable
+ basis. Nothing herein is intended or shall be deemed to constitute any
+ admission of liability.
+
+ NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION
+ LICENSE (CDDL)
+
+ The code released under the CDDL shall be governed by the laws of the State
+ of California (excluding conflict-of-law provisions). Any litigation relating
+ to this License shall be subject to the jurisdiction of the Federal Courts of
+ the Northern District of California and the state courts of the State of
+ California, with venue lying in Santa Clara County, California.
+
+
+------------------------------------------------------------------------------
+ANTLR 2 License (from ApacheDS, Groovy)
+------------------------------------------------------------------------------
+We reserve no legal rights to the ANTLR--it is fully in the public domain.
+An individual or company may do whatever they wish with source code
+distributed with ANTLR or the code generated by ANTLR, including the
+incorporation of ANTLR, or its output, into commerical software.
+We encourage users to develop software with ANTLR. However, we do ask that
+credit is given to us for developing ANTLR. By "credit", we mean that if you
+use ANTLR or incorporate any source code into one of your programs
+(commercial product, research project, or otherwise) that you acknowledge
+this fact somewhere in the documentation, research report, etc... If you like
+ANTLR and have developed a nice tool with the output, please mention that you
+developed it using ANTLR. In addition, we ask that the headers remain intact
+in our source code. As long as these guidelines are kept, we expect to
+continue enhancing this system and expect to make other tools available as
+they are completed.
+
+------------------------------------------------------------------------------
+ASM Project License (from CGLib, Groovy)
+------------------------------------------------------------------------------
+Copyright (c) 2000-2011 INRIA, France Telecom
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions
+are met:
+
+1. Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+
+2. Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+
+3. Neither the name of the copyright holders nor the names of its
+ contributors may be used to endorse or promote products derived from
+ this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
+AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
+LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
+SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
+THE POSSIBILITY OF SUCH DAMAGE.
+
+
+------------------------------------------------------------------------------
+Bouncy Castle License (from ApacheDS)
+------------------------------------------------------------------------------
+Copyright (c) 2000 - 2012 The Legion Of The Bouncy Castle
+(http://www.bouncycastle.org)
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is furnished
+to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
+
+
+------------------------------------------------------------------------------
+Eclipse Public License - v1.0 (from Jetty/Jerico)
+------------------------------------------------------------------------------
+THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC
+LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM
+CONSTITUTES RECIPIENT’S ACCEPTANCE OF THIS AGREEMENT.
+
+1. DEFINITIONS
+
+"Contribution" means:
+
+a) in the case of the initial Contributor, the initial code and documentation
+ distributed under this Agreement, and
+b) in the case of each subsequent Contributor:
+
+i)changes to the Program, and
+
+ii)additions to the Program;
+
+where such changes and/or additions to the Program originate from and are
+distributed by that particular Contributor. A Contribution 'originates' from
+a Contributor if it was added to the Program by such Contributor itself or
+anyone acting on such Contributor’s behalf. Contributions do not include
+additions to the Program which: (i) are separate modules of software
+distributed in conjunction with the Program under their own license agreement,
+and (ii) are not derivative works of the Program.
+
+"Contributor" means any person or entity that distributes the Program.
+
+"Licensed Patents " mean patent claims licensable by a Contributor which are
+necessarily infringed by the use or sale of its Contribution alone or when
+combined with the Program.
+
+"Program" means the Contributions distributed in accordance with this
+Agreement.
+
+"Recipient" means anyone who receives the Program under this Agreement,
+including all Contributors.
+
+2. GRANT OF RIGHTS
+
+a) Subject to the terms of this Agreement, each Contributor hereby grants
+ Recipient a non-exclusive, worldwide, royalty-free copyright license to
+ reproduce, prepare derivative works of, publicly display, publicly perform,
+ distribute and sublicense the Contribution of such Contributor, if any,
+ and such derivative works, in source code and object code form.
+
+b) Subject to the terms of this Agreement, each Contributor hereby grants
+ Recipient a non-exclusive, worldwide, royalty-free patent license under
+ Licensed Patents to make, use, sell, offer to sell, import and otherwise
+ transfer the Contribution of such Contributor, if any, in source code and
+ object code form. This patent license shall apply to the combination of the
+ Contribution and the Program if, at the time the Contribution is added by
+ the Contributor, such addition of the Contribution causes such combination
+ to be covered by the Licensed Patents. The patent license shall not apply
+ to any other combinations which include the Contribution. No hardware per
+ se is licensed hereunder.
+
+c) Recipient understands that although each Contributor grants the licenses
+ to its Contributions set forth herein, no assurances are provided by any
+ Contributor that the Program does not infringe the patent or other
+ intellectual property rights of any other entity. Each Contributor
+ disclaims any liability to Recipient for claims brought by any other
+ entity based on infringement of intellectual property rights or otherwise.
+ As a condition to exercising the rights and licenses granted hereunder,
+ each Recipient hereby assumes sole responsibility to secure any other
+ intellectual property rights needed, if any. For example, if a third
+ party patent license is required to allow Recipient to distribute the
+ Program, it is Recipient’s responsibility to acquire that license before
+ distributing the Program.
+
+d) Each Contributor represents that to its knowledge it has sufficient
+ copyright rights in its Contribution, if any, to grant the copyright
+ license set forth in this Agreement.
+
+3. REQUIREMENTS
+
+A Contributor may choose to distribute the Program in object code form under
+its own license agreement, provided that:
+
+a) it complies with the terms and conditions of this Agreement; and
+
+b) its license agreement:
+
+i) effectively disclaims on behalf of all Contributors all warranties and
+ conditions, express and implied, including warranties or conditions of
+ title and non-infringement, and implied warranties or conditions of
+ merchantability and fitness for a particular purpose;
+
+ii) effectively excludes on behalf of all Contributors all liability for
+ damages, including direct, indirect, special, incidental and consequential
+ damages, such as lost profits;
+
+iii) states that any provisions which differ from this Agreement are offered by
+ that Contributor alone and not by any other party; and
+
+iv) states that source code for the Program is available from such
+ Contributor, and informs licensees how to obtain it in a reasonable manner
+ on or through a medium customarily used for software exchange.
+
+When the Program is made available in source code form:
+
+a) it must be made available under this Agreement; and
+
+b) a copy of this Agreement must be included with each copy of the Program.
+
+Contributors may not remove or alter any copyright notices contained within
+the Program.
+
+Each Contributor must identify itself as the originator of its Contribution,
+if any, in a manner that reasonably allows subsequent Recipients to identify
+the originator of the Contribution.
+
+4. COMMERCIAL DISTRIBUTION
+
+Commercial distributors of software may accept certain responsibilities with
+respect to end users, business partners and the like. While this license is
+intended to facilitate the commercial use of the Program, the Contributor who
+includes the Program in a commercial product offering should do so in a manner
+which does not create potential liability for other Contributors. Therefore,
+if a Contributor includes the Program in a commercial product offering, such
+Contributor ("Commercial Contributor") hereby agrees to defend and indemnify
+every other Contributor ("Indemnified Contributor") against any losses,
+damages and costs (collectively "Losses") arising from claims, lawsuits and
+other legal actions brought by a third party against the Indemnified
+Contributor to the extent caused by the acts or omissions of such Commercial
+Contributor in connection with its distribution of the Program in a commercial
+product offering. The obligations in this section do not apply to any claims
+or Losses relating to any actual or alleged intellectual property infringement.
+In order to qualify, an Indemnified Contributor must: a) promptly notify the
+Commercial Contributor in writing of such claim, and b) allow the Commercial
+Contributor to control, and cooperate with the Commercial Contributor in, the
+defense and any related settlement negotiations. The Indemnified Contributor
+may participate in any such claim at its own expense.
+
+For example, a Contributor might include the Program in a commercial product
+offering, Product X. That Contributor is then a Commercial Contributor. If
+that Commercial Contributor then makes performance claims, or offers
+warranties related to Product X, those performance claims and warranties are
+such Commercial Contributor’s responsibility alone. Under this section, the
+Commercial Contributor would have to defend claims against the other
+Contributors related to those performance claims and warranties, and if a
+court requires any other Contributor to pay any damages as a result, the
+Commercial Contributor must pay those damages.
+
+5. NO WARRANTY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON
+AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS
+OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF
+TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
+Each Recipient is solely responsible for determining the appropriateness of
+using and distributing the Program and assumes all risks associated with its
+exercise of rights under this Agreement , including but not limited to the
+risks and costs of program errors, compliance with applicable laws, damage to
+or loss of data, programs or equipment, and unavailability or interruption of
+operations.
+
+6. DISCLAIMER OF LIABILITY
+
+EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY
+CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
+LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE
+EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY
+OF SUCH DAMAGES.
+
+7. GENERAL
+
+If any provision of this Agreement is invalid or unenforceable under
+applicable law, it shall not affect the validity or enforceability of the
+remainder of the terms of this Agreement, and without further action by the
+parties hereto, such provision shall be reformed to the minimum extent
+necessary to make such provision valid and enforceable.
+
+If Recipient institutes patent litigation against any entity (including a
+cross-claim or counterclaim in a lawsuit) alleging that the Program itself
+(excluding combinations of the Program with other software or hardware)
+infringes such Recipient’s patent(s), then such Recipient’s rights granted
+under Section 2(b) shall terminate as of the date such litigation is filed.
+
+All Recipient’s rights under this Agreement shall terminate if it fails to
+comply with any of the material terms or conditions of this Agreement and
+does not cure such failure in a reasonable period of time after becoming
+aware of such noncompliance. If all Recipient’s rights under this Agreement
+terminate, Recipient agrees to cease use and distribution of the Program as
+soon as reasonably practicable. However, Recipient’s obligations under this
+Agreement and any licenses granted by Recipient relating to the Program shall
+continue and survive.
+
+Everyone is permitted to copy and distribute copies of this Agreement, but in
+order to avoid inconsistency the Agreement is copyrighted and may only be
+modified in the following manner. The Agreement Steward reserves the right to
+publish new versions (including revisions) of this Agreement from time to
+time. No one other than the Agreement Steward has the right to modify this
+Agreement. The Eclipse Foundation is the initial Agreement Steward. The
+Eclipse Foundation may assign the responsibility to serve as the Agreement
+Steward to a suitable separate entity. Each new version of the Agreement
+will be given a distinguishing version number. The Program (including
+Contributions) may always be distributed subject to the version of the
+Agreement under which it was received. In addition, after a new version of
+the Agreement is published, Contributor may elect to distribute the Program
+(including its Contributions) under the new version. Except as expressly
+stated in Sections 2(a) and 2(b) above, Recipient receives no rights or
+licenses to the intellectual property of any Contributor under this Agreement,
+whether expressly, by implication, estoppel or otherwise. All rights in the
+Program not expressly granted under this Agreement are reserved.
+
+This Agreement is governed by the laws of the State of New York and the
+intellectual property laws of the United States of America. No party to this
+Agreement will bring a legal action under this Agreement more than one year
+after the cause of action arose. Each party waives its rights to a jury trial
+in any resulting litigation.
+
+
+--------------------------------------------------------------------------------------------------
+JDBM LICENSE v1.00 (from ApacheDS)
+--------------------------------------------------------------------------------------------------
+/**
+ * JDBM LICENSE v1.00
+ *
+ * Redistribution and use of this software and associated documentation
+ * ("Software"), with or without modification, are permitted provided
+ * that the following conditions are met:
+ *
+ * 1. Redistributions of source code must retain copyright
+ * statements and notices. Redistributions must also contain a
+ * copy of this document.
+ *
+ * 2. Redistributions in binary form must reproduce the
+ * above copyright notice, this list of conditions and the
+ * following disclaimer in the documentation and/or other
+ * materials provided with the distribution.
+ *
+ * 3. The name "JDBM" must not be used to endorse or promote
+ * products derived from this Software without prior written
+ * permission of Cees de Groot. For written permission,
+ * please contact cg@cdegroot.com.
+ *
+ * 4. Products derived from this Software may not be called "JDBM"
+ * nor may "JDBM" appear in their names without prior written
+ * permission of Cees de Groot.
+ *
+ * 5. Due credit should be given to the JDBM Project
+ * (http://jdbm.sourceforge.net/).
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE JDBM PROJECT AND CONTRIBUTORS
+ * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT
+ * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
+ * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
+ * CEES DE GROOT OR ANY CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
+ * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
+ * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
+ * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+ * OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * Copyright 2000 (C) Cees de Groot. All Rights Reserved.
+ * Contributions are Copyright (C) 2000 by their associated contributors.
+ *
+ * $Id: LICENSE.txt,v 1.1 2000/05/05 23:59:52 boisvert Exp $
+ */
+
+------------------------------------------------------------------------------
+JLine License - BSD (from Groovy)
+------------------------------------------------------------------------------
+Copyright (c) 2002-2006, Marc Prud'hommeaux <mw...@cornell.edu>
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or
+without modification, are permitted provided that the following
+conditions are met:
+
+Redistributions of source code must retain the above copyright
+notice, this list of conditions and the following disclaimer.
+
+Redistributions in binary form must reproduce the above copyright
+notice, this list of conditions and the following disclaimer
+in the documentation and/or other materials provided with
+the distribution.
+
+Neither the name of JLine nor the names of its contributors
+may be used to endorse or promote products derived from this
+software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
+BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
+FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
+OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
+AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
+OF THE POSSIBILITY OF SUCH DAMAGE.
+
+
+------------------------------------------------------------------------------
+SL4J License - MIT
+------------------------------------------------------------------------------
+Copyright (c) 2004-2013 QOS.ch
+All rights reserved.
+
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of this software and associated documentation files (the
+"Software"), to deal in the Software without restriction, including
+without limitation the rights to use, copy, modify, merge, publish,
+distribute, sublicense, and/or sell copies of the Software, and to
+permit persons to whom the Software is furnished to do so, subject to
+the following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
+LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
+WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+------------------------------------------------------------------------------
+Tanuki Software License (from ApacheDS)
+------------------------------------------------------------------------------
+Copyright (c) 1999, 2004 Tanuki Software
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of the Java Service Wrapper and associated
+documentation files (the "Software"), to deal in the Software
+without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sub-license,
+and/or sell copies of the Software, and to permit persons to
+whom the Software is furnished to do so, subject to the
+following conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+
+------------------------------------------------------------------------------
+Silver Egg Technology License (from ApacheDS)
+------------------------------------------------------------------------------
+Portions of the Software have been derived from source code
+developed by Silver Egg Technology under the following license:
+
+Copyright (c) 2001 Silver Egg Technology
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sub-license, and/or
+sell copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+
+------------------------------------------------------------------------------
+Sun Microsystems, Inc. License (from Groovy)
+------------------------------------------------------------------------------
+The following notice applies to the files:
+
+src/main/org/codehaus/groovy/jsr223/GroovyCompiledScript.java
+src/main/org/codehaus/groovy/jsr223/GroovyScriptEngineFactory.java
+src/main/org/codehaus/groovy/jsr223/GroovyScriptEngineImpl.java
+
+/*
+ * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
+ * Use is subject to license terms.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are
+ * permitted provided that the following conditions are met: Redistributions of source code
+ * must retain the above copyright notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright notice, this list of
+ * conditions and the following disclaimer in the documentation and/or other materials
+ * provided with the distribution. Neither the name of the Sun Microsystems nor the names of
+ * is contributors may be used to endorse or promote products derived from this software
+ * without specific prior written permission.
+
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
+ * OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
+ * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
+ * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
+ * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
+ * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
+ * OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+------------------------------------------------------------------------------
+European Commission License (from Hadoop)
+------------------------------------------------------------------------------
+For the org.apache.hadoop.util.bloom.* classes:
+
+/**
+ *
+ * Copyright (c) 2005, European Commission project OneLab under contract
+ * 034819 (http://www.one-lab.org)
+ * All rights reserved.
+ * Redistribution and use in source and binary forms, with or
+ * without modification, are permitted provided that the following
+ * conditions are met:
+ * - Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright
+ * notice, this list of conditions and the following disclaimer in
+ * the documentation and/or other materials provided with the distribution.
+ * - Neither the name of the University Catholique de Louvain - UCL
+ * nor the names of its contributors may be used to endorse or
+ * promote products derived from this software without specific prior
+ * written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
+ * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
+ * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
+ * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
+ * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
+ * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
+ * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
+ * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+ * POSSIBILITY OF SUCH DAMAGE.
+ */
+
+------------------------------------------------------------------------------
+zlib/libpng License
+------------------------------------------------------------------------------
+This software is provided 'as-is', without any express or implied warranty. In
+no event will the authors be held liable for any damages arising from the use of
+this software.
+
+Permission is granted to anyone to use this software for any purpose, including
+commercial applications, and to alter it and redistribute it freely, subject to
+the following restrictions:
+
+ 1. The origin of this software must not be misrepresented; you must not claim
+ that you wrote the original software. If you use this software in a
+ product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 3. This notice may not be removed or altered from any source distribution.
+
+
+------------------------------------------------------------------------------
+bzip2 License
+------------------------------------------------------------------------------
+Redistribution and use in source and binary forms, with or without modification,
+are permitted provided that the following conditions are met:
+
+ 1. Redistributions of source code must retain the above copyright notice,
+ this list of conditions and the following disclaimer.
+ 2. The origin of this software must not be misrepresented; you must not claim
+ that you wrote the original software. If you use this software in a
+ product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+ 3. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+ 4. The name of the author may not be used to endorse or promote products
+ derived from this software without specific prior written permission.
+
+THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS AND ANY EXPRESS OR IMPLIED
+WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
+OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
+CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
+IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
+OF SUCH DAMAGE.
+
+Julian Seward, Cambridge, UK.
+jseward@acm.org
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/bootstrap.sh b/examples/quickstart/tutorial/examples/hadoop/docker/bootstrap.sh
new file mode 100755
index 00000000000..4cf0e55b135
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/bootstrap.sh
@@ -0,0 +1,27 @@
+#!/bin/bash
+
+: ${HADOOP_PREFIX:=/usr/local/hadoop}
+
+$HADOOP_PREFIX/etc/hadoop/hadoop-env.sh
+
+rm /tmp/*.pid
+
+# installing libraries if any - (resource urls added comma separated to the ACP system variable)
+cd $HADOOP_PREFIX/share/hadoop/common ; for cp in ${ACP//,/ }; do echo == $cp; curl -LO $cp ; done; cd -
+
+# altering the core-site configuration
+sed s/HOSTNAME/$HOSTNAME/ /usr/local/hadoop/etc/hadoop/core-site.xml.template > /usr/local/hadoop/etc/hadoop/core-site.xml
+
+
+service sshd start
+$HADOOP_PREFIX/sbin/start-dfs.sh
+$HADOOP_PREFIX/sbin/start-yarn.sh
+$HADOOP_PREFIX/sbin/mr-jobhistory-daemon.sh start historyserver
+
+if [[ $1 == "-d" ]]; then
+ while true; do sleep 1000; done
+fi
+
+if [[ $1 == "-bash" ]]; then
+ /bin/bash
+fi
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/core-site.xml.template b/examples/quickstart/tutorial/examples/hadoop/docker/core-site.xml.template
new file mode 100644
index 00000000000..00ab59528b8
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/core-site.xml.template
@@ -0,0 +1,6 @@
+ <configuration>
+ <property>
+ <name>fs.defaultFS</name>
+ <value>hdfs://HOSTNAME:9000</value>
+ </property>
+ </configuration>
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/hdfs-site.xml b/examples/quickstart/tutorial/examples/hadoop/docker/hdfs-site.xml
new file mode 100644
index 00000000000..d29556190ad
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/hdfs-site.xml
@@ -0,0 +1,14 @@
+<configuration>
+ <property>
+ <name>dfs.replication</name>
+ <value>1</value>
+ </property>
+ <property>
+ <name>dfs.client.use.datanode.hostname</name>
+ <value>true</value>
+ </property>
+ <property>
+ <name>dfs.datanode.use.datanode.hostname</name>
+ <value>true</value>
+ </property>
+</configuration>
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/mapred-site.xml b/examples/quickstart/tutorial/examples/hadoop/docker/mapred-site.xml
new file mode 100644
index 00000000000..dba582f1c31
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/mapred-site.xml
@@ -0,0 +1,6 @@
+<configuration>
+ <property>
+ <name>mapreduce.framework.name</name>
+ <value>yarn</value>
+ </property>
+</configuration>
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/ssh_config b/examples/quickstart/tutorial/examples/hadoop/docker/ssh_config
new file mode 100644
index 00000000000..535f9d32bd4
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/ssh_config
@@ -0,0 +1,5 @@
+Host *
+ UserKnownHostsFile /dev/null
+ StrictHostKeyChecking no
+ LogLevel quiet
+ Port 2122
diff --git a/examples/quickstart/tutorial/examples/hadoop/docker/yarn-site.xml b/examples/quickstart/tutorial/examples/hadoop/docker/yarn-site.xml
new file mode 100644
index 00000000000..becf69465f1
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/hadoop/docker/yarn-site.xml
@@ -0,0 +1,47 @@
+<configuration>
+ <property>
+ <name>yarn.nodemanager.aux-services</name>
+ <value>mapreduce_shuffle</value>
+ </property>
+
+ <property>
+ <name>yarn.application.classpath</name>
+ <value>/usr/local/hadoop/etc/hadoop, /usr/local/hadoop/share/hadoop/common/*, /usr/local/hadoop/share/hadoop/common/lib/*, /usr/local/hadoop/share/hadoop/hdfs/*, /usr/local/hadoop/share/hadoop/hdfs/lib/*, /usr/local/hadoop/share/hadoop/mapreduce/*, /usr/local/hadoop/share/hadoop/mapreduce/lib/*, /usr/local/hadoop/share/hadoop/yarn/*, /usr/local/hadoop/share/hadoop/yarn/lib/*</value>
+ </property>
+
+ <property>
+ <description>
+ Number of seconds after an application finishes before the nodemanager's
+ DeletionService will delete the application's localized file directory
+ and log directory.
+
+ To diagnose Yarn application problems, set this property's value large
+ enough (for example, to 600 = 10 minutes) to permit examination of these
+ directories. After changing the property's value, you must restart the
+ nodemanager in order for it to have an effect.
+
+ The roots of Yarn applications' work directories is configurable with
+ the yarn.nodemanager.local-dirs property (see below), and the roots
+ of the Yarn applications' log directories is configurable with the
+ yarn.nodemanager.log-dirs property (see also below).
+ </description>
+ <name>yarn.nodemanager.delete.debug-delay-sec</name>
+ <value>600</value>
+ </property>
+
+ <property>
+ <name>yarn.log-aggregation-enable</name>
+ <value>true</value>
+ </property>
+
+ <property>
+ <name>yarn.log-aggregation.retain-seconds</name>
+ <value>900000</value>
+ </property>
+
+ <property>
+ <name>yarn.nodemanager.vmem-check-enabled</name>
+ <value>false</value>
+ </property>
+
+</configuration>
diff --git a/examples/quickstart/tutorial/examples/ingestion-tutorial-select-sql.json b/examples/quickstart/tutorial/examples/ingestion-tutorial-select-sql.json
new file mode 100644
index 00000000000..08896fe09b6
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/ingestion-tutorial-select-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"select * from \"ingestion-tutorial\""
+}
diff --git a/examples/quickstart/tutorial/examples/retention-index.json b/examples/quickstart/tutorial/examples/retention-index.json
new file mode 100644
index 00000000000..5ae9d327661
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/retention-index.json
@@ -0,0 +1,64 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "retention-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "hour",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "quickstart/",
+ "filter" : "wikiticker-2015-09-12-sampled.json.gz"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/rollup-data.json b/examples/quickstart/tutorial/examples/rollup-data.json
new file mode 100644
index 00000000000..63c8dd7b659
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/rollup-data.json
@@ -0,0 +1,9 @@
+{"timestamp":"2018-01-01T01:01:35Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":20,"bytes":9024}
+{"timestamp":"2018-01-01T01:01:51Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":255,"bytes":21133}
+{"timestamp":"2018-01-01T01:01:59Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":11,"bytes":5780}
+{"timestamp":"2018-01-01T01:02:14Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":38,"bytes":6289}
+{"timestamp":"2018-01-01T01:02:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":377,"bytes":359971}
+{"timestamp":"2018-01-01T01:03:29Z","srcIP":"1.1.1.1", "dstIP":"2.2.2.2","packets":49,"bytes":10204}
+{"timestamp":"2018-01-02T21:33:14Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":38,"bytes":6289}
+{"timestamp":"2018-01-02T21:33:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":123,"bytes":93999}
+{"timestamp":"2018-01-02T21:35:45Z","srcIP":"7.7.7.7", "dstIP":"8.8.8.8","packets":12,"bytes":2818}
diff --git a/examples/quickstart/tutorial/examples/rollup-index.json b/examples/quickstart/tutorial/examples/rollup-index.json
new file mode 100644
index 00000000000..d205e408a8f
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/rollup-index.json
@@ -0,0 +1,51 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "rollup-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "srcIP",
+ "dstIP"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "packets", "fieldName" : "packets" },
+ { "type" : "longSum", "name" : "bytes", "fieldName" : "bytes" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "rollup-data.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/rollup-select-sql.json b/examples/quickstart/tutorial/examples/rollup-select-sql.json
new file mode 100644
index 00000000000..a6fe9f93586
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/rollup-select-sql.json
@@ -0,0 +1,3 @@
+{
+"query":"select * from \"rollup-tutorial\""
+}
diff --git a/examples/quickstart/tutorial/examples/transform-data.json b/examples/quickstart/tutorial/examples/transform-data.json
new file mode 100644
index 00000000000..562c6f4d519
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/transform-data.json
@@ -0,0 +1,4 @@
+{"timestamp":"2018-01-01T07:01:35Z","animal":"octopus", "location":1, "number":100}
+{"timestamp":"2018-01-01T05:01:35Z","animal":"mongoose", "location":2,"number":200}
+{"timestamp":"2018-01-01T06:01:35Z","animal":"snake", "location":3, "number":300}
+{"timestamp":"2018-01-01T01:01:35Z","animal":"lion", "location":4, "number":300}
diff --git a/examples/quickstart/tutorial/examples/transform-index.json b/examples/quickstart/tutorial/examples/transform-index.json
new file mode 100644
index 00000000000..baaeccd78a7
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/transform-index.json
@@ -0,0 +1,73 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "transform-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal",
+ { "name": "location", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" },
+ { "type" : "longSum", "name" : "triple-number", "fieldName" : "triple-number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ },
+ "transformSpec": {
+ "transforms": [
+ {
+ "type": "expression",
+ "name": "animal",
+ "expression": "concat('super-', animal)"
+ },
+ {
+ "type": "expression",
+ "name": "triple-number",
+ "expression": "number * 3"
+ }
+ ],
+ "filter": {
+ "type":"or",
+ "fields": [
+ { "type": "selector", "dimension": "animal", "value": "super-mongoose" },
+ { "type": "selector", "dimension": "triple-number", "value": "300" },
+ { "type": "selector", "dimension": "location", "value": "3" }
+ ]
+ }
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "transform-data.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/transform-select-sql.json b/examples/quickstart/tutorial/examples/transform-select-sql.json
new file mode 100644
index 00000000000..acc3f0aea8b
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/transform-select-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"select * from \"transform-tutorial\""
+}
diff --git a/examples/quickstart/tutorial/examples/updates-append-index.json b/examples/quickstart/tutorial/examples/updates-append-index.json
new file mode 100644
index 00000000000..164de1b2a0b
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-append-index.json
@@ -0,0 +1,49 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "updates-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "updates-data3.json"
+ },
+ "appendToExisting" : true
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/updates-append-index2.json b/examples/quickstart/tutorial/examples/updates-append-index2.json
new file mode 100644
index 00000000000..2c9a40cd463
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-append-index2.json
@@ -0,0 +1,49 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "updates-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "updates-data4.json"
+ },
+ "appendToExisting" : true
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/updates-data.json b/examples/quickstart/tutorial/examples/updates-data.json
new file mode 100644
index 00000000000..da59a6b813a
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-data.json
@@ -0,0 +1,3 @@
+{"timestamp":"2018-01-01T01:01:35Z","animal":"tiger", "number":100}
+{"timestamp":"2018-01-01T03:01:35Z","animal":"aardvark", "number":42}
+{"timestamp":"2018-01-01T03:01:35Z","animal":"giraffe", "number":14124}
diff --git a/examples/quickstart/tutorial/examples/updates-data2.json b/examples/quickstart/tutorial/examples/updates-data2.json
new file mode 100644
index 00000000000..640210fc651
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-data2.json
@@ -0,0 +1,3 @@
+{"timestamp":"2018-01-01T01:01:35Z","animal":"lion", "number":100}
+{"timestamp":"2018-01-01T03:01:35Z","animal":"aardvark", "number":9999}
+{"timestamp":"2018-01-01T04:01:35Z","animal":"bear", "number":111}
diff --git a/examples/quickstart/tutorial/examples/updates-data3.json b/examples/quickstart/tutorial/examples/updates-data3.json
new file mode 100644
index 00000000000..68f8cdccef8
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-data3.json
@@ -0,0 +1,6 @@
+{"timestamp":"2018-01-01T07:01:35Z","animal":"octopus", "number":115}
+{"timestamp":"2018-01-01T05:01:35Z","animal":"mongoose", "number":737}
+{"timestamp":"2018-01-01T06:01:35Z","animal":"snake", "number":1234}
+{"timestamp":"2018-01-01T01:01:35Z","animal":"lion", "number":300}
+{"timestamp":"2018-01-01T04:01:35Z","animal":"bear", "number":222}
+{"timestamp":"2018-01-01T09:01:35Z","animal":"falcon", "number":1241}
diff --git a/examples/quickstart/tutorial/examples/updates-data4.json b/examples/quickstart/tutorial/examples/updates-data4.json
new file mode 100644
index 00000000000..a0a95b2843c
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-data4.json
@@ -0,0 +1,2 @@
+{"timestamp":"2018-01-01T04:01:35Z","animal":"bear", "number":222}
+{"timestamp":"2018-01-01T09:01:35Z","animal":"falcon", "number":1241}
diff --git a/examples/quickstart/tutorial/examples/updates-groupby-sql.json b/examples/quickstart/tutorial/examples/updates-groupby-sql.json
new file mode 100644
index 00000000000..ab90d68f8b2
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-groupby-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"select __time, animal, SUM(\"count\"), SUM(\"number\") from \"updates-tutorial\" group by __time, animal"
+}
diff --git a/examples/quickstart/tutorial/examples/updates-init-index.json b/examples/quickstart/tutorial/examples/updates-init-index.json
new file mode 100644
index 00000000000..ed4cf76f8e8
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-init-index.json
@@ -0,0 +1,49 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "updates-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "updates-data.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/updates-overwrite-index.json b/examples/quickstart/tutorial/examples/updates-overwrite-index.json
new file mode 100644
index 00000000000..7f96a580c45
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-overwrite-index.json
@@ -0,0 +1,49 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "updates-tutorial",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "animal"
+ ]
+ },
+ "timestampSpec": {
+ "column": "timestamp",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [
+ { "type" : "count", "name" : "count" },
+ { "type" : "longSum", "name" : "number", "fieldName" : "number" }
+ ],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "week",
+ "queryGranularity" : "minute",
+ "intervals" : ["2018-01-01/2018-01-03"],
+ "rollup" : true
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "examples/",
+ "filter" : "updates-data2.json"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/updates-select-sql.json b/examples/quickstart/tutorial/examples/updates-select-sql.json
new file mode 100644
index 00000000000..b840e12f79b
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/updates-select-sql.json
@@ -0,0 +1,3 @@
+{
+"query":"select * from \"updates-tutorial\""
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-explain-top-pages-sql.json b/examples/quickstart/tutorial/examples/wikipedia-explain-top-pages-sql.json
new file mode 100644
index 00000000000..a64ab7775d2
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-explain-top-pages-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"EXPLAIN PLAN FOR SELECT page, COUNT(*) AS Edits FROM wikipedia WHERE \"__time\" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00' GROUP BY page ORDER BY Edits DESC LIMIT 10"
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-groupby-sql.json b/examples/quickstart/tutorial/examples/wikipedia-groupby-sql.json
new file mode 100644
index 00000000000..5d1735b9d93
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-groupby-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"SELECT channel, SUM(added) FROM wikipedia WHERE \"__time\" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00' GROUP BY channel ORDER BY SUM(added) DESC LIMIT 5"
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-index-hadoop.json b/examples/quickstart/tutorial/examples/wikipedia-index-hadoop.json
new file mode 100644
index 00000000000..1c63d741dc1
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-index-hadoop.json
@@ -0,0 +1,79 @@
+{
+ "type" : "index_hadoop",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "wikipedia",
+ "parser" : {
+ "type" : "hadoopyString",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec" : {
+ "format" : "auto",
+ "column" : "time"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "day",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "hadoop",
+ "inputSpec" : {
+ "type" : "static",
+ "paths" : "/quickstart/wikiticker-2015-09-12-sampled.json.gz"
+ }
+ },
+ "tuningConfig" : {
+ "type" : "hadoop",
+ "partitionsSpec" : {
+ "type" : "hashed",
+ "targetPartitionSize" : 5000000
+ },
+ "forceExtendableShardSpecs" : true,
+ "jobProperties" : {
+ "fs.default.name" : "hdfs://druid-hadoop-demo:9000",
+ "fs.defaultFS" : "hdfs://druid-hadoop-demo:9000",
+ "dfs.datanode.address" : "druid-hadoop-demo",
+ "dfs.client.use.datanode.hostname" : "true",
+ "dfs.datanode.use.datanode.hostname" : "true",
+ "yarn.resourcemanager.hostname" : "druid-hadoop-demo",
+ "yarn.nodemanager.vmem-check-enabled" : "false",
+ "mapreduce.map.java.opts" : "-Duser.timezone=UTC -Dfile.encoding=UTF-8",
+ "mapreduce.job.user.classpath.first" : "true",
+ "mapreduce.reduce.java.opts" : "-Duser.timezone=UTC -Dfile.encoding=UTF-8",
+ "mapreduce.map.memory.mb" : 1024,
+ "mapreduce.reduce.memory.mb" : 1024
+ }
+ }
+ },
+ "hadoopDependencyCoordinates": ["org.apache.hadoop:hadoop-client:2.7.3"]
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-index.json b/examples/quickstart/tutorial/examples/wikipedia-index.json
new file mode 100644
index 00000000000..b24bca0c9a0
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-index.json
@@ -0,0 +1,64 @@
+{
+ "type" : "index",
+ "spec" : {
+ "dataSchema" : {
+ "dataSource" : "wikipedia",
+ "parser" : {
+ "type" : "string",
+ "parseSpec" : {
+ "format" : "json",
+ "dimensionsSpec" : {
+ "dimensions" : [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ },
+ "timestampSpec": {
+ "column": "time",
+ "format": "iso"
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec" : {
+ "type" : "uniform",
+ "segmentGranularity" : "day",
+ "queryGranularity" : "none",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "rollup" : false
+ }
+ },
+ "ioConfig" : {
+ "type" : "index",
+ "firehose" : {
+ "type" : "local",
+ "baseDir" : "quickstart/",
+ "filter" : "wikiticker-2015-09-12-sampled.json.gz"
+ },
+ "appendToExisting" : false
+ },
+ "tuningConfig" : {
+ "type" : "index",
+ "targetPartitionSize" : 5000000,
+ "maxRowsInMemory" : 25000,
+ "forceExtendableShardSpecs" : true
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-kafka-supervisor.json b/examples/quickstart/tutorial/examples/wikipedia-kafka-supervisor.json
new file mode 100644
index 00000000000..6988e19b172
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-kafka-supervisor.json
@@ -0,0 +1,59 @@
+{
+ "type": "kafka",
+ "dataSchema": {
+ "dataSource": "wikipedia",
+ "parser": {
+ "type": "string",
+ "parseSpec": {
+ "format": "json",
+ "timestampSpec": {
+ "column": "time",
+ "format": "auto"
+ },
+ "dimensionsSpec": {
+ "dimensions": [
+ "channel",
+ "cityName",
+ "comment",
+ "countryIsoCode",
+ "countryName",
+ "isAnonymous",
+ "isMinor",
+ "isNew",
+ "isRobot",
+ "isUnpatrolled",
+ "metroCode",
+ "namespace",
+ "page",
+ "regionIsoCode",
+ "regionName",
+ "user",
+ { "name": "added", "type": "long" },
+ { "name": "deleted", "type": "long" },
+ { "name": "delta", "type": "long" }
+ ]
+ }
+ }
+ },
+ "metricsSpec" : [],
+ "granularitySpec": {
+ "type": "uniform",
+ "segmentGranularity": "DAY",
+ "queryGranularity": "NONE",
+ "rollup": false
+ }
+ },
+ "tuningConfig": {
+ "type": "kafka",
+ "reportParseExceptions": false
+ },
+ "ioConfig": {
+ "topic": "wikipedia",
+ "replicas": 2,
+ "taskDuration": "PT10M",
+ "completionTimeout": "PT20M",
+ "consumerProperties": {
+ "bootstrap.servers": "localhost:9092"
+ }
+ }
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-scan-sql.json b/examples/quickstart/tutorial/examples/wikipedia-scan-sql.json
new file mode 100644
index 00000000000..c663370106c
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-scan-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"SELECT user, page FROM wikipedia WHERE \"__time\" BETWEEN TIMESTAMP '2015-09-12 02:00:00' AND TIMESTAMP '2015-09-12 03:00:00' LIMIT 5"
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-timeseries-sql.json b/examples/quickstart/tutorial/examples/wikipedia-timeseries-sql.json
new file mode 100644
index 00000000000..c857be24000
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-timeseries-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"SELECT FLOOR(__time to HOUR) AS HourTime, SUM(deleted) AS LinesDeleted FROM wikipedia WHERE \"__time\" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00' GROUP BY FLOOR(__time to HOUR)"
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-top-pages-sql.json b/examples/quickstart/tutorial/examples/wikipedia-top-pages-sql.json
new file mode 100644
index 00000000000..b1b0fdcd5a8
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-top-pages-sql.json
@@ -0,0 +1,3 @@
+{
+ "query":"SELECT page, COUNT(*) AS Edits FROM wikipedia WHERE \"__time\" BETWEEN TIMESTAMP '2015-09-12 00:00:00' AND TIMESTAMP '2015-09-13 00:00:00' GROUP BY page ORDER BY Edits DESC LIMIT 10"
+}
diff --git a/examples/quickstart/tutorial/examples/wikipedia-top-pages.json b/examples/quickstart/tutorial/examples/wikipedia-top-pages.json
new file mode 100644
index 00000000000..2961480e539
--- /dev/null
+++ b/examples/quickstart/tutorial/examples/wikipedia-top-pages.json
@@ -0,0 +1,15 @@
+{
+ "queryType" : "topN",
+ "dataSource" : "wikipedia",
+ "intervals" : ["2015-09-12/2015-09-13"],
+ "granularity" : "all",
+ "dimension" : "page",
+ "metric" : "count",
+ "threshold" : 10,
+ "aggregations" : [
+ {
+ "type" : "count",
+ "name" : "count"
+ }
+ ]
+}
\ No newline at end of file
diff --git a/extendedset/pom.xml b/extendedset/pom.xml
index 91f19144c8e..4e0fc8c8c43 100755
--- a/extendedset/pom.xml
+++ b/extendedset/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://maven.apache.org/POM/4.0.0"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>extendedset</artifactId>
@@ -32,7 +31,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/extensions-contrib/ambari-metrics-emitter/pom.xml b/extensions-contrib/ambari-metrics-emitter/pom.xml
index 14fe7cd44bb..fe36d4cab21 100644
--- a/extensions-contrib/ambari-metrics-emitter/pom.xml
+++ b/extensions-contrib/ambari-metrics-emitter/pom.xml
@@ -18,14 +18,13 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -48,8 +47,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitter.java b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitter.java
index 1838e8952c1..f8f2e76fa1f 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitter.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitter.java
@@ -20,11 +20,11 @@
package io.druid.emitter.ambari.metrics;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import com.metamx.common.ISE;
-import com.metamx.emitter.core.Emitter;
-import com.metamx.emitter.core.Event;
-import com.metamx.emitter.service.AlertEvent;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.common.ISE;
+import io.druid.java.util.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Event;
+import io.druid.java.util.emitter.service.AlertEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.logger.Logger;
import org.apache.hadoop.metrics2.sink.timeline.AbstractTimelineMetricsSink;
diff --git a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitterModule.java b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitterModule.java
index ad029a08787..6dc5e49edc4 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitterModule.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/AmbariMetricsEmitterModule.java
@@ -28,7 +28,7 @@
import com.google.inject.Provides;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-import com.metamx.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Emitter;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.ManageLifecycle;
import io.druid.initialization.DruidModule;
diff --git a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/DruidToTimelineMetricConverter.java b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/DruidToTimelineMetricConverter.java
index bcc09f68905..9912ced6843 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/DruidToTimelineMetricConverter.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/DruidToTimelineMetricConverter.java
@@ -21,7 +21,7 @@
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.hadoop.metrics2.sink.timeline.TimelineMetric;
diff --git a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/SendAllTimelineEventConverter.java b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/SendAllTimelineEventConverter.java
index f5be89a2385..2189fac55f0 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/SendAllTimelineEventConverter.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/SendAllTimelineEventConverter.java
@@ -26,7 +26,7 @@
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import org.apache.hadoop.metrics2.sink.timeline.TimelineMetric;
/**
diff --git a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverter.java b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverter.java
index 5d2a4629096..cf4bd86821e 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverter.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/main/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverter.java
@@ -32,8 +32,8 @@
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.io.CharStreams;
import com.google.common.io.Files;
-import com.metamx.common.ISE;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.common.ISE;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.logger.Logger;
import org.apache.hadoop.metrics2.sink.timeline.TimelineMetric;
diff --git a/extensions-contrib/ambari-metrics-emitter/src/test/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverterTest.java b/extensions-contrib/ambari-metrics-emitter/src/test/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverterTest.java
index eeb4048a9b4..be58f3c1934 100644
--- a/extensions-contrib/ambari-metrics-emitter/src/test/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverterTest.java
+++ b/extensions-contrib/ambari-metrics-emitter/src/test/java/io/druid/emitter/ambari/metrics/WhiteListBasedDruidToTimelineEventConverterTest.java
@@ -20,7 +20,7 @@
package io.druid.emitter.ambari.metrics;
import com.google.common.collect.Maps;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.java.util.common.DateTimes;
import junitparams.JUnitParamsRunner;
diff --git a/extensions-contrib/azure-extensions/pom.xml b/extensions-contrib/azure-extensions/pom.xml
index 1c647b0e91d..98307d68730 100644
--- a/extensions-contrib/azure-extensions/pom.xml
+++ b/extensions-contrib/azure-extensions/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions.contrib</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPusher.java b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPusher.java
index 97bc1a0167a..592b956c260 100644
--- a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPusher.java
+++ b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureDataSegmentPusher.java
@@ -25,7 +25,6 @@
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.microsoft.azure.storage.StorageException;
-
import io.druid.java.util.common.CompressionUtils;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.logger.Logger;
@@ -92,9 +91,9 @@ public File createSegmentDescriptorFile(final ObjectMapper jsonMapper, final Dat
return descriptorFile;
}
- public Map<String, String> getAzurePaths(final DataSegment segment)
+ public Map<String, String> getAzurePaths(final DataSegment segment, final boolean useUniquePath)
{
- final String storageDir = this.getStorageDir(segment);
+ final String storageDir = this.getStorageDir(segment, useUniquePath);
return ImmutableMap.of(
"index", StringUtils.format("%s/%s", storageDir, AzureStorageDruidModule.INDEX_ZIP_FILE_NAME),
@@ -131,9 +130,9 @@ public DataSegment uploadDataSegment(
}
@Override
- public DataSegment push(final File indexFilesDir, final DataSegment segment) throws IOException
+ public DataSegment push(final File indexFilesDir, final DataSegment segment, final boolean useUniquePath)
+ throws IOException
{
-
log.info("Uploading [%s] to Azure.", indexFilesDir);
final int version = SegmentUtils.getVersionFromDir(indexFilesDir);
@@ -145,7 +144,7 @@ public DataSegment push(final File indexFilesDir, final DataSegment segment) thr
final long size = CompressionUtils.zip(indexFilesDir, zipOutFile);
final File descFile = descriptorFile = createSegmentDescriptorFile(jsonMapper, segment);
- final Map<String, String> azurePaths = getAzurePaths(segment);
+ final Map<String, String> azurePaths = getAzurePaths(segment, useUniquePath);
return AzureUtils.retryAzureOperation(
new Callable<DataSegment>()
diff --git a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureStorage.java b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureStorage.java
index 8585bf04379..25a4764ad84 100644
--- a/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureStorage.java
+++ b/extensions-contrib/azure-extensions/src/main/java/io/druid/storage/azure/AzureStorage.java
@@ -23,9 +23,7 @@
import com.microsoft.azure.storage.blob.CloudBlob;
import com.microsoft.azure.storage.blob.CloudBlobClient;
import com.microsoft.azure.storage.blob.CloudBlobContainer;
-import com.microsoft.azure.storage.blob.CloudBlockBlob;
import com.microsoft.azure.storage.blob.ListBlobItem;
-
import io.druid.java.util.common.logger.Logger;
import java.io.File;
@@ -78,17 +76,14 @@ public CloudBlobContainer getCloudBlobContainer(final String containerName)
}
return deletedFiles;
-
}
public void uploadBlob(final File file, final String containerName, final String blobPath)
throws IOException, StorageException, URISyntaxException
-
{
CloudBlobContainer container = getCloudBlobContainer(containerName);
try (FileInputStream stream = new FileInputStream(file)) {
- CloudBlockBlob blob = container.getBlockBlobReference(blobPath);
- blob.upload(stream, file.length());
+ container.getBlockBlobReference(blobPath).upload(stream, file.length());
}
}
diff --git a/extensions-contrib/azure-extensions/src/test/java/io/druid/storage/azure/AzureDataSegmentPusherTest.java b/extensions-contrib/azure-extensions/src/test/java/io/druid/storage/azure/AzureDataSegmentPusherTest.java
index af76f357142..3201c4afeca 100644
--- a/extensions-contrib/azure-extensions/src/test/java/io/druid/storage/azure/AzureDataSegmentPusherTest.java
+++ b/extensions-contrib/azure-extensions/src/test/java/io/druid/storage/azure/AzureDataSegmentPusherTest.java
@@ -82,6 +82,17 @@ public void before()
@Test
public void testPush() throws Exception
+ {
+ testPushInternal(false, "foo/2015-01-01T00:00:00\\.000Z_2016-01-01T00:00:00\\.000Z/0/0/index\\.zip");
+ }
+
+ @Test
+ public void testPushUseUniquePath() throws Exception
+ {
+ testPushInternal(true, "foo/2015-01-01T00:00:00\\.000Z_2016-01-01T00:00:00\\.000Z/0/0/[A-Za-z0-9-]{36}/index\\.zip");
+ }
+
+ private void testPushInternal(boolean useUniquePath, String matcher) throws Exception
{
AzureDataSegmentPusher pusher = new AzureDataSegmentPusher(azureStorage, azureAccountConfig, jsonMapper);
@@ -104,7 +115,12 @@ public void testPush() throws Exception
size
);
- DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush);
+ DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush, useUniquePath);
+
+ Assert.assertTrue(
+ segment.getLoadSpec().get("blobPath").toString(),
+ segment.getLoadSpec().get("blobPath").toString().matches(matcher)
+ );
Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
}
@@ -114,10 +130,13 @@ public void getAzurePathsTest()
{
AzureDataSegmentPusher pusher = new AzureDataSegmentPusher(azureStorage, azureAccountConfig, jsonMapper);
- final String storageDir = pusher.getStorageDir(dataSegment);
- Map<String, String> paths = pusher.getAzurePaths(dataSegment);
+ final String storageDir = pusher.getStorageDir(dataSegment, false);
+ Map<String, String> paths = pusher.getAzurePaths(dataSegment, false);
- assertEquals(StringUtils.format("%s/%s", storageDir, AzureStorageDruidModule.INDEX_ZIP_FILE_NAME), paths.get("index"));
+ assertEquals(
+ StringUtils.format("%s/%s", storageDir, AzureStorageDruidModule.INDEX_ZIP_FILE_NAME),
+ paths.get("index")
+ );
assertEquals(
StringUtils.format("%s/%s", storageDir, AzureStorageDruidModule.DESCRIPTOR_FILE_NAME),
paths.get("descriptor")
@@ -131,7 +150,7 @@ public void uploadDataSegmentTest() throws StorageException, IOException, URISyn
final int version = 9;
final File compressedSegmentData = new File("index.zip");
final File descriptorFile = new File("descriptor.json");
- final Map<String, String> azurePaths = pusher.getAzurePaths(dataSegment);
+ final Map<String, String> azurePaths = pusher.getAzurePaths(dataSegment, false);
azureStorage.uploadBlob(compressedSegmentData, containerName, azurePaths.get("index"));
expectLastCall();
diff --git a/extensions-contrib/cassandra-storage/pom.xml b/extensions-contrib/cassandra-storage/pom.xml
index ea32b084b02..39e29466330 100644
--- a/extensions-contrib/cassandra-storage/pom.xml
+++ b/extensions-contrib/cassandra-storage/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/cassandra-storage/src/main/java/io/druid/storage/cassandra/CassandraDataSegmentPusher.java b/extensions-contrib/cassandra-storage/src/main/java/io/druid/storage/cassandra/CassandraDataSegmentPusher.java
index 3595147ace8..16ff585327d 100644
--- a/extensions-contrib/cassandra-storage/src/main/java/io/druid/storage/cassandra/CassandraDataSegmentPusher.java
+++ b/extensions-contrib/cassandra-storage/src/main/java/io/druid/storage/cassandra/CassandraDataSegmentPusher.java
@@ -24,8 +24,9 @@
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
import com.netflix.astyanax.MutationBatch;
+import com.netflix.astyanax.connectionpool.exceptions.NotFoundException;
import com.netflix.astyanax.recipes.storage.ChunkedStorage;
-
+import com.netflix.astyanax.recipes.storage.ChunkedStorageProvider;
import io.druid.java.util.common.CompressionUtils;
import io.druid.java.util.common.logger.Logger;
import io.druid.segment.SegmentUtils;
@@ -53,7 +54,8 @@
@Inject
public CassandraDataSegmentPusher(
CassandraDataSegmentConfig config,
- ObjectMapper jsonMapper)
+ ObjectMapper jsonMapper
+ )
{
super(config);
this.jsonMapper = jsonMapper;
@@ -73,13 +75,13 @@ public String getPathForHadoop(String dataSource)
}
@Override
- public DataSegment push(final File indexFilesDir, DataSegment segment) throws IOException
+ public DataSegment push(final File indexFilesDir, DataSegment segment, final boolean useUniquePath) throws IOException
{
log.info("Writing [%s] to C*", indexFilesDir);
String key = JOINER.join(
config.getKeyspace().isEmpty() ? null : config.getKeyspace(),
- this.getStorageDir(segment)
- );
+ this.getStorageDir(segment, useUniquePath)
+ );
// Create index
final File compressedIndexFile = File.createTempFile("druid", "index.zip");
@@ -91,12 +93,12 @@ public DataSegment push(final File indexFilesDir, DataSegment segment) throws IO
try {
long start = System.currentTimeMillis();
ChunkedStorage.newWriter(indexStorage, key, new FileInputStream(compressedIndexFile))
- .withConcurrencyLevel(CONCURRENCY).call();
+ .withConcurrencyLevel(CONCURRENCY).call();
byte[] json = jsonMapper.writeValueAsBytes(segment);
MutationBatch mutation = this.keyspace.prepareMutationBatch();
mutation.withRow(descriptorStorage, key)
- .putColumn("lastmodified", System.currentTimeMillis(), null)
- .putColumn("descriptor", json, null);
+ .putColumn("lastmodified", System.currentTimeMillis(), null)
+ .putColumn("descriptor", json, null);
mutation.execute();
log.info("Wrote index to C* in [%s] ms", System.currentTimeMillis() - start);
}
@@ -105,10 +107,8 @@ public DataSegment push(final File indexFilesDir, DataSegment segment) throws IO
}
segment = segment.withSize(indexSize)
- .withLoadSpec(
- ImmutableMap.<String, Object> of("type", "c*", "key", key)
- )
- .withBinaryVersion(version);
+ .withLoadSpec(ImmutableMap.<String, Object>of("type", "c*", "key", key))
+ .withBinaryVersion(version);
log.info("Deleting zipped index File[%s]", compressedIndexFile);
compressedIndexFile.delete();
@@ -120,4 +120,14 @@ public DataSegment push(final File indexFilesDir, DataSegment segment) throws IO
{
throw new UnsupportedOperationException("not supported");
}
+
+ private boolean doesObjectExist(ChunkedStorageProvider provider, String objectName) throws Exception
+ {
+ try {
+ return ChunkedStorage.newInfoReader(provider, objectName).call().isValidForRead();
+ }
+ catch (NotFoundException e) {
+ return false;
+ }
+ }
}
diff --git a/extensions-contrib/cloudfiles-extensions/pom.xml b/extensions-contrib/cloudfiles-extensions/pom.xml
index da06a9e9e51..dcfb7278532 100644
--- a/extensions-contrib/cloudfiles-extensions/pom.xml
+++ b/extensions-contrib/cloudfiles-extensions/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
- xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions.contrib</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusher.java b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusher.java
index a08105b0575..be3e2547235 100644
--- a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusher.java
+++ b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusher.java
@@ -31,7 +31,6 @@
import org.jclouds.rackspace.cloudfiles.v1.CloudFilesApi;
import java.io.File;
-import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.util.Map;
@@ -74,9 +73,12 @@ public String getPathForHadoop(final String dataSource)
}
@Override
- public DataSegment push(final File indexFilesDir, final DataSegment inSegment) throws IOException
+ public DataSegment push(final File indexFilesDir, final DataSegment inSegment, final boolean useUniquePath)
{
- final String segmentPath = CloudFilesUtils.buildCloudFilesPath(this.config.getBasePath(), getStorageDir(inSegment));
+ final String segmentPath = CloudFilesUtils.buildCloudFilesPath(
+ this.config.getBasePath(),
+ getStorageDir(inSegment, useUniquePath)
+ );
File descriptorFile = null;
File zipOutFile = null;
@@ -98,6 +100,7 @@ public DataSegment call() throws Exception
segmentPath, outFile, objectApi.getRegion(),
objectApi.getContainer()
);
+
log.info("Pushing %s.", segmentData.getPath());
objectApi.put(segmentData);
@@ -111,6 +114,7 @@ public DataSegment call() throws Exception
log.info("Pushing %s.", descriptorData.getPath());
objectApi.put(descriptorData);
+
final DataSegment outSegment = inSegment
.withSize(indexSize)
.withLoadSpec(makeLoadSpec(new URI(segmentData.getPath())))
diff --git a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesObjectApiProxy.java b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesObjectApiProxy.java
index 7f41497b37c..d495fcc1c77 100644
--- a/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesObjectApiProxy.java
+++ b/extensions-contrib/cloudfiles-extensions/src/main/java/io/druid/storage/cloudfiles/CloudFilesObjectApiProxy.java
@@ -58,4 +58,9 @@ public CloudFilesObject get(String path)
Payload payload = swiftObject.getPayload();
return new CloudFilesObject(payload, this.region, this.container, path);
}
+
+ public boolean exists(String path)
+ {
+ return objectApi.getWithoutBody(path) != null;
+ }
}
diff --git a/extensions-contrib/cloudfiles-extensions/src/test/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusherTest.java b/extensions-contrib/cloudfiles-extensions/src/test/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusherTest.java
index b257efb1282..2be6f584811 100644
--- a/extensions-contrib/cloudfiles-extensions/src/test/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusherTest.java
+++ b/extensions-contrib/cloudfiles-extensions/src/test/java/io/druid/storage/cloudfiles/CloudFilesDataSegmentPusherTest.java
@@ -84,7 +84,7 @@ public void testPush() throws Exception
size
);
- DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush);
+ DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush, false);
Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
diff --git a/extensions-contrib/distinctcount/pom.xml b/extensions-contrib/distinctcount/pom.xml
index 86c3fcc09c9..5bf57e683fa 100644
--- a/extensions-contrib/distinctcount/pom.xml
+++ b/extensions-contrib/distinctcount/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions.contrib</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/druid-rocketmq/pom.xml b/extensions-contrib/druid-rocketmq/pom.xml
index 924a07cdd42..099f22868f3 100644
--- a/extensions-contrib/druid-rocketmq/pom.xml
+++ b/extensions-contrib/druid-rocketmq/pom.xml
@@ -17,14 +17,12 @@
~ specific language governing permissions and limitations
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/google-extensions/pom.xml b/extensions-contrib/google-extensions/pom.xml
index 20a3dd7ba3d..4f91369287a 100644
--- a/extensions-contrib/google-extensions/pom.xml
+++ b/extensions-contrib/google-extensions/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentKiller.java b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentKiller.java
index b7fbdc162a2..2285fbd6069 100644
--- a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentKiller.java
+++ b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentKiller.java
@@ -19,6 +19,7 @@
package io.druid.storage.google;
+import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.inject.Inject;
import io.druid.java.util.common.MapUtils;
import io.druid.java.util.common.logger.Logger;
@@ -52,14 +53,27 @@ public void kill(DataSegment segment) throws SegmentLoadingException
final String descriptorPath = indexPath.substring(0, indexPath.lastIndexOf("/")) + "/descriptor.json";
try {
- storage.delete(bucket, indexPath);
- storage.delete(bucket, descriptorPath);
+ deleteIfPresent(bucket, indexPath);
+ deleteIfPresent(bucket, descriptorPath);
}
catch (IOException e) {
throw new SegmentLoadingException(e, "Couldn't kill segment[%s]: [%s]", segment.getIdentifier(), e.getMessage());
}
}
+ private void deleteIfPresent(String bucket, String path) throws IOException
+ {
+ try {
+ storage.delete(bucket, path);
+ }
+ catch (GoogleJsonResponseException e) {
+ if (e.getStatusCode() != 404) {
+ throw e;
+ }
+ LOG.debug("Already deleted: [%s] [%s]", bucket, path);
+ }
+ }
+
@Override
public void killAll() throws IOException
{
diff --git a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPusher.java b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPusher.java
index 527e7e14025..7a3581462d3 100644
--- a/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPusher.java
+++ b/extensions-contrib/google-extensions/src/main/java/io/druid/storage/google/GoogleDataSegmentPusher.java
@@ -93,7 +93,8 @@ public File createDescriptorFile(final ObjectMapper jsonMapper, final DataSegmen
return descriptorFile;
}
- public void insert(final File file, final String contentType, final String path) throws IOException
+ public void insert(final File file, final String contentType, final String path)
+ throws IOException
{
LOG.info("Inserting [%s] to [%s]", file, path);
@@ -106,7 +107,8 @@ public void insert(final File file, final String contentType, final String path)
}
@Override
- public DataSegment push(final File indexFilesDir, final DataSegment segment) throws IOException
+ public DataSegment push(final File indexFilesDir, final DataSegment segment, final boolean useUniquePath)
+ throws IOException
{
LOG.info("Uploading [%s] to Google.", indexFilesDir);
@@ -117,7 +119,7 @@ public DataSegment push(final File indexFilesDir, final DataSegment segment) thr
try {
indexFile = File.createTempFile("index", ".zip");
final long indexSize = CompressionUtils.zip(indexFilesDir, indexFile);
- final String storageDir = this.getStorageDir(segment);
+ final String storageDir = this.getStorageDir(segment, useUniquePath);
final String indexPath = buildPath(storageDir + "/" + "index.zip");
final String descriptorPath = buildPath(storageDir + "/" + "descriptor.json");
diff --git a/extensions-contrib/google-extensions/src/test/java/io/druid/storage/google/GoogleDataSegmentPusherTest.java b/extensions-contrib/google-extensions/src/test/java/io/druid/storage/google/GoogleDataSegmentPusherTest.java
index 6c845d433c7..b90f0d5f560 100644
--- a/extensions-contrib/google-extensions/src/test/java/io/druid/storage/google/GoogleDataSegmentPusherTest.java
+++ b/extensions-contrib/google-extensions/src/test/java/io/druid/storage/google/GoogleDataSegmentPusherTest.java
@@ -89,7 +89,7 @@ public void testPush() throws Exception
"foo",
Intervals.of("2015/2016"),
"0",
- Maps.<String, Object>newHashMap(),
+ Maps.newHashMap(),
Lists.<String>newArrayList(),
Lists.<String>newArrayList(),
new NoneShardSpec(),
@@ -105,18 +105,26 @@ public void testPush() throws Exception
jsonMapper
).addMockedMethod("insert", File.class, String.class, String.class).createMock();
- final String storageDir = pusher.getStorageDir(segmentToPush);
+ final String storageDir = pusher.getStorageDir(segmentToPush, false);
final String indexPath = prefix + "/" + storageDir + "/" + "index.zip";
final String descriptorPath = prefix + "/" + storageDir + "/" + "descriptor.json";
- pusher.insert(EasyMock.anyObject(File.class), EasyMock.eq("application/zip"), EasyMock.eq(indexPath));
+ pusher.insert(
+ EasyMock.anyObject(File.class),
+ EasyMock.eq("application/zip"),
+ EasyMock.eq(indexPath)
+ );
expectLastCall();
- pusher.insert(EasyMock.anyObject(File.class), EasyMock.eq("application/json"), EasyMock.eq(descriptorPath));
+ pusher.insert(
+ EasyMock.anyObject(File.class),
+ EasyMock.eq("application/json"),
+ EasyMock.eq(descriptorPath)
+ );
expectLastCall();
replayAll();
- DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush);
+ DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush, false);
Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
Assert.assertEquals(segmentToPush, segment);
diff --git a/extensions-contrib/graphite-emitter/pom.xml b/extensions-contrib/graphite-emitter/pom.xml
index 8569823ea94..a847ea74806 100644
--- a/extensions-contrib/graphite-emitter/pom.xml
+++ b/extensions-contrib/graphite-emitter/pom.xml
@@ -18,14 +18,13 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -54,8 +53,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/DruidToGraphiteEventConverter.java b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/DruidToGraphiteEventConverter.java
index 673fa2af2af..243b6119799 100644
--- a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/DruidToGraphiteEventConverter.java
+++ b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/DruidToGraphiteEventConverter.java
@@ -21,7 +21,7 @@
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, property = "type", defaultImpl = WhiteListBasedConverter.class)
diff --git a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitter.java b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitter.java
index cb0fb30d05b..bba2796862c 100644
--- a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitter.java
+++ b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitter.java
@@ -23,10 +23,10 @@
import com.codahale.metrics.graphite.GraphiteSender;
import com.codahale.metrics.graphite.PickledGraphite;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import com.metamx.emitter.core.Emitter;
-import com.metamx.emitter.core.Event;
-import com.metamx.emitter.service.AlertEvent;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Event;
+import io.druid.java.util.emitter.service.AlertEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.logger.Logger;
diff --git a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitterModule.java b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitterModule.java
index b7fd38b3681..12b27213c79 100644
--- a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitterModule.java
+++ b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/GraphiteEmitterModule.java
@@ -29,7 +29,7 @@
import com.google.inject.Provides;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
-import com.metamx.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Emitter;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.ManageLifecycle;
import io.druid.initialization.DruidModule;
diff --git a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/SendAllGraphiteEventConverter.java b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/SendAllGraphiteEventConverter.java
index dc26014e1b3..e3b70568429 100644
--- a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/SendAllGraphiteEventConverter.java
+++ b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/SendAllGraphiteEventConverter.java
@@ -26,7 +26,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSortedSet;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import java.util.concurrent.TimeUnit;
diff --git a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/WhiteListBasedConverter.java b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/WhiteListBasedConverter.java
index ac53033ca6a..25018c5f504 100644
--- a/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/WhiteListBasedConverter.java
+++ b/extensions-contrib/graphite-emitter/src/main/java/io/druid/emitter/graphite/WhiteListBasedConverter.java
@@ -33,7 +33,7 @@
import com.google.common.collect.ImmutableSortedMap;
import com.google.common.io.Files;
import com.google.common.io.Resources;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.logger.Logger;
diff --git a/extensions-contrib/graphite-emitter/src/test/java/io/druid/emitter/graphite/WhiteListBasedConverterTest.java b/extensions-contrib/graphite-emitter/src/test/java/io/druid/emitter/graphite/WhiteListBasedConverterTest.java
index 11908fb1bb2..10022a4023b 100644
--- a/extensions-contrib/graphite-emitter/src/test/java/io/druid/emitter/graphite/WhiteListBasedConverterTest.java
+++ b/extensions-contrib/graphite-emitter/src/test/java/io/druid/emitter/graphite/WhiteListBasedConverterTest.java
@@ -20,7 +20,7 @@
package io.druid.emitter.graphite;
import com.google.common.collect.Maps;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.java.util.common.DateTimes;
import junitparams.JUnitParamsRunner;
diff --git a/extensions-contrib/kafka-eight-simpleConsumer/pom.xml b/extensions-contrib/kafka-eight-simpleConsumer/pom.xml
index 1c9f5c17ffe..04c05f52fb3 100644
--- a/extensions-contrib/kafka-eight-simpleConsumer/pom.xml
+++ b/extensions-contrib/kafka-eight-simpleConsumer/pom.xml
@@ -16,8 +16,7 @@
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions.contrib</groupId>
<artifactId>druid-kafka-eight-simple-consumer</artifactId>
@@ -27,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -39,8 +38,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-contrib/kafka-eight-simpleConsumer/src/main/java/io/druid/firehose/kafka/KafkaEightSimpleConsumerFirehoseFactory.java b/extensions-contrib/kafka-eight-simpleConsumer/src/main/java/io/druid/firehose/kafka/KafkaEightSimpleConsumerFirehoseFactory.java
index 0c53007311d..c65fa808d70 100644
--- a/extensions-contrib/kafka-eight-simpleConsumer/src/main/java/io/druid/firehose/kafka/KafkaEightSimpleConsumerFirehoseFactory.java
+++ b/extensions-contrib/kafka-eight-simpleConsumer/src/main/java/io/druid/firehose/kafka/KafkaEightSimpleConsumerFirehoseFactory.java
@@ -25,8 +25,8 @@
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.io.Closeables;
-import com.metamx.common.parsers.ParseException;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.common.parsers.ParseException;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.data.input.ByteBufferInputRowParser;
import io.druid.data.input.Committer;
import io.druid.data.input.FirehoseFactoryV2;
diff --git a/extensions-contrib/kafka-emitter/pom.xml b/extensions-contrib/kafka-emitter/pom.xml
index 9130834d243..bc64469009e 100644
--- a/extensions-contrib/kafka-emitter/pom.xml
+++ b/extensions-contrib/kafka-emitter/pom.xml
@@ -18,14 +18,13 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -53,8 +52,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitter.java b/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitter.java
index 7a791be5c84..7628521dd8d 100644
--- a/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitter.java
+++ b/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitter.java
@@ -22,10 +22,10 @@
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableMap;
-import com.metamx.emitter.core.Emitter;
-import com.metamx.emitter.core.Event;
-import com.metamx.emitter.service.AlertEvent;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Event;
+import io.druid.java.util.emitter.service.AlertEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.emitter.kafka.MemoryBoundLinkedBlockingQueue.ObjectContainer;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.lifecycle.LifecycleStart;
diff --git a/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitterModule.java b/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitterModule.java
index 0608b1f0d89..7db5724787f 100644
--- a/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitterModule.java
+++ b/extensions-contrib/kafka-emitter/src/main/java/io/druid/emitter/kafka/KafkaEmitterModule.java
@@ -24,7 +24,7 @@
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.name.Named;
-import com.metamx.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Emitter;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.ManageLifecycle;
import io.druid.initialization.DruidModule;
diff --git a/extensions-contrib/orc-extensions/pom.xml b/extensions-contrib/orc-extensions/pom.xml
index 4eb48e949eb..805d763d3ee 100644
--- a/extensions-contrib/orc-extensions/pom.xml
+++ b/extensions-contrib/orc-extensions/pom.xml
@@ -15,9 +15,7 @@
~ See the License for the specific language governing permissions and
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>io.druid.extensions.contrib</groupId>
<artifactId>druid-orc-extensions</artifactId>
<name>druid-orc-extensions</name>
@@ -26,7 +24,7 @@
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
diff --git a/extensions-contrib/parquet-extensions/pom.xml b/extensions-contrib/parquet-extensions/pom.xml
index b2a460fc289..cb48fc8fc38 100644
--- a/extensions-contrib/parquet-extensions/pom.xml
+++ b/extensions-contrib/parquet-extensions/pom.xml
@@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>io.druid.extensions.contrib</groupId>
<artifactId>druid-parquet-extensions</artifactId>
<name>druid-parquet-extensions</name>
@@ -10,7 +8,7 @@
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
diff --git a/extensions-contrib/rabbitmq/pom.xml b/extensions-contrib/rabbitmq/pom.xml
index 8f1ebc47f19..40b4549450c 100644
--- a/extensions-contrib/rabbitmq/pom.xml
+++ b/extensions-contrib/rabbitmq/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/redis-cache/pom.xml b/extensions-contrib/redis-cache/pom.xml
index 9d0c578bcd0..a1612daa706 100644
--- a/extensions-contrib/redis-cache/pom.xml
+++ b/extensions-contrib/redis-cache/pom.xml
@@ -19,8 +19,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions.contrib</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/redis-cache/src/main/java/io/druid/client/cache/RedisCache.java b/extensions-contrib/redis-cache/src/main/java/io/druid/client/cache/RedisCache.java
index 11b63a2e0f9..9b4744fd961 100644
--- a/extensions-contrib/redis-cache/src/main/java/io/druid/client/cache/RedisCache.java
+++ b/extensions-contrib/redis-cache/src/main/java/io/druid/client/cache/RedisCache.java
@@ -21,8 +21,8 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.Lists;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.logger.Logger;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
diff --git a/extensions-contrib/sqlserver-metadata-storage/pom.xml b/extensions-contrib/sqlserver-metadata-storage/pom.xml
index 0f3970cdf20..ced21811596 100644
--- a/extensions-contrib/sqlserver-metadata-storage/pom.xml
+++ b/extensions-contrib/sqlserver-metadata-storage/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/statsd-emitter/pom.xml b/extensions-contrib/statsd-emitter/pom.xml
index 061b2a961a8..522771030d0 100644
--- a/extensions-contrib/statsd-emitter/pom.xml
+++ b/extensions-contrib/statsd-emitter/pom.xml
@@ -17,13 +17,11 @@
~ specific language governing permissions and limitations
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -47,8 +45,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitter.java b/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitter.java
index c949f13f477..d395146f87e 100644
--- a/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitter.java
+++ b/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitter.java
@@ -22,9 +22,9 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import com.google.common.collect.ImmutableList;
-import com.metamx.emitter.core.Emitter;
-import com.metamx.emitter.core.Event;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Event;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import com.timgroup.statsd.NonBlockingStatsDClient;
import com.timgroup.statsd.StatsDClient;
import com.timgroup.statsd.StatsDClientErrorHandler;
diff --git a/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitterModule.java b/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitterModule.java
index 3d00da34eff..2d8bd2087c0 100644
--- a/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitterModule.java
+++ b/extensions-contrib/statsd-emitter/src/main/java/io/druid/emitter/statsd/StatsDEmitterModule.java
@@ -24,7 +24,7 @@
import com.google.inject.Binder;
import com.google.inject.Provides;
import com.google.inject.name.Named;
-import com.metamx.emitter.core.Emitter;
+import io.druid.java.util.emitter.core.Emitter;
import io.druid.guice.JsonConfigProvider;
import io.druid.guice.ManageLifecycle;
import io.druid.initialization.DruidModule;
diff --git a/extensions-contrib/statsd-emitter/src/test/java/DimensionConverterTest.java b/extensions-contrib/statsd-emitter/src/test/java/DimensionConverterTest.java
index b4c8fa33243..62132a266cf 100644
--- a/extensions-contrib/statsd-emitter/src/test/java/DimensionConverterTest.java
+++ b/extensions-contrib/statsd-emitter/src/test/java/DimensionConverterTest.java
@@ -19,7 +19,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableList;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.emitter.statsd.DimensionConverter;
import io.druid.emitter.statsd.StatsDMetric;
import io.druid.java.util.common.DateTimes;
diff --git a/extensions-contrib/statsd-emitter/src/test/java/StatsDEmitterTest.java b/extensions-contrib/statsd-emitter/src/test/java/StatsDEmitterTest.java
index 531ca7a5dbf..16175d917a4 100644
--- a/extensions-contrib/statsd-emitter/src/test/java/StatsDEmitterTest.java
+++ b/extensions-contrib/statsd-emitter/src/test/java/StatsDEmitterTest.java
@@ -18,7 +18,7 @@
*/
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import com.timgroup.statsd.StatsDClient;
import io.druid.emitter.statsd.StatsDEmitter;
import io.druid.emitter.statsd.StatsDEmitterConfig;
diff --git a/extensions-contrib/thrift-extensions/pom.xml b/extensions-contrib/thrift-extensions/pom.xml
index 18c51677a61..af57708474d 100644
--- a/extensions-contrib/thrift-extensions/pom.xml
+++ b/extensions-contrib/thrift-extensions/pom.xml
@@ -1,7 +1,5 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<groupId>io.druid.extensions.contrib</groupId>
<artifactId>druid-thrift-extensions</artifactId>
@@ -11,7 +9,7 @@
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
diff --git a/extensions-contrib/thrift-extensions/src/main/java/io/druid/data/input/thrift/ThriftInputRowParser.java b/extensions-contrib/thrift-extensions/src/main/java/io/druid/data/input/thrift/ThriftInputRowParser.java
index 87169252b8f..aa523f34993 100644
--- a/extensions-contrib/thrift-extensions/src/main/java/io/druid/data/input/thrift/ThriftInputRowParser.java
+++ b/extensions-contrib/thrift-extensions/src/main/java/io/druid/data/input/thrift/ThriftInputRowParser.java
@@ -23,7 +23,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-import com.metamx.common.IAE;
+import io.druid.java.util.common.IAE;
import com.twitter.elephantbird.mapreduce.io.ThriftWritable;
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedInputRow;
diff --git a/extensions-contrib/time-min-max/pom.xml b/extensions-contrib/time-min-max/pom.xml
index 59bc7ee6b1a..38bafa004a9 100644
--- a/extensions-contrib/time-min-max/pom.xml
+++ b/extensions-contrib/time-min-max/pom.xml
@@ -17,13 +17,11 @@
~ specific language governing permissions and limitations
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
diff --git a/extensions-contrib/virtual-columns/pom.xml b/extensions-contrib/virtual-columns/pom.xml
index 3102a75d1d9..c408bd4a2de 100644
--- a/extensions-contrib/virtual-columns/pom.xml
+++ b/extensions-contrib/virtual-columns/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/DruidVirtualColumnsModule.java b/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/DruidVirtualColumnsModule.java
index 184225d0245..9db5be737a2 100644
--- a/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/DruidVirtualColumnsModule.java
+++ b/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/DruidVirtualColumnsModule.java
@@ -20,6 +20,7 @@
package io.druid.segment;
import com.fasterxml.jackson.databind.Module;
+import com.fasterxml.jackson.databind.jsontype.NamedType;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
@@ -34,7 +35,12 @@
@Override
public List<? extends Module> getJacksonModules()
{
- return ImmutableList.of(new SimpleModule().registerSubtypes(MapVirtualColumn.class));
+ return ImmutableList.of(
+ new SimpleModule(getClass().getSimpleName())
+ .registerSubtypes(
+ new NamedType(MapVirtualColumn.class, "map")
+ )
+ );
}
@Override
diff --git a/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/MapVirtualColumn.java b/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/MapVirtualColumn.java
index c17b219a038..79950efd087 100644
--- a/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/MapVirtualColumn.java
+++ b/extensions-contrib/virtual-columns/src/main/java/io/druid/segment/MapVirtualColumn.java
@@ -24,7 +24,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
-import com.metamx.common.StringUtils;
+import io.druid.java.util.common.StringUtils;
import io.druid.query.dimension.DefaultDimensionSpec;
import io.druid.query.dimension.DimensionSpec;
import io.druid.query.filter.DimFilterUtils;
diff --git a/extensions-contrib/virtual-columns/src/test/java/io/druid/segment/MapVirtualColumnTest.java b/extensions-contrib/virtual-columns/src/test/java/io/druid/segment/MapVirtualColumnTest.java
index 283aa8684a9..cc9417f7a0b 100644
--- a/extensions-contrib/virtual-columns/src/test/java/io/druid/segment/MapVirtualColumnTest.java
+++ b/extensions-contrib/virtual-columns/src/test/java/io/druid/segment/MapVirtualColumnTest.java
@@ -19,6 +19,7 @@
package io.druid.segment;
+import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
@@ -138,6 +139,18 @@ public MapVirtualColumnTest(QueryRunner runner)
.pagingSpec(new PagingSpec(null, 3));
}
+ @Test
+ public void testSerde() throws IOException
+ {
+ final ObjectMapper mapper = new DefaultObjectMapper();
+ new DruidVirtualColumnsModule().getJacksonModules().forEach(mapper::registerModule);
+
+ final MapVirtualColumn column = new MapVirtualColumn("keys", "values", "params");
+ final String json = mapper.writeValueAsString(column);
+ final VirtualColumn fromJson = mapper.readValue(json, VirtualColumn.class);
+ Assert.assertEquals(column, fromJson);
+ }
+
@Test
public void testBasic() throws Exception
{
diff --git a/extensions-core/avro-extensions/pom.xml b/extensions-core/avro-extensions/pom.xml
index 9102202fac3..05d9a621df5 100644
--- a/extensions-core/avro-extensions/pom.xml
+++ b/extensions-core/avro-extensions/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/datasketches/pom.xml b/extensions-core/datasketches/pom.xml
index f7cf74e7458..ce113995ead 100644
--- a/extensions-core/datasketches/pom.xml
+++ b/extensions-core/datasketches/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorFactory.java b/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorFactory.java
index 7ebb40b5d7a..bfbaaac86f7 100644
--- a/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorFactory.java
+++ b/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorFactory.java
@@ -21,7 +21,7 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
-import com.metamx.common.IAE;
+import io.druid.java.util.common.IAE;
import com.yahoo.sketches.Util;
import com.yahoo.sketches.quantiles.DoublesSketch;
import com.yahoo.sketches.quantiles.DoublesUnion;
diff --git a/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchModule.java b/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchModule.java
index 0e3081965b0..f26bf348a33 100644
--- a/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchModule.java
+++ b/extensions-core/datasketches/src/main/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchModule.java
@@ -35,6 +35,7 @@
{
public static final String DOUBLES_SKETCH = "quantilesDoublesSketch";
+ public static final String DOUBLES_SKETCH_MERGE = "quantilesDoublesSketchMerge";
public static final String DOUBLES_SKETCH_HISTOGRAM_POST_AGG = "quantilesDoublesSketchToHistogram";
public static final String DOUBLES_SKETCH_QUANTILE_POST_AGG = "quantilesDoublesSketchToQuantile";
@@ -55,6 +56,7 @@ public void configure(final Binder binder)
return Arrays.<Module> asList(
new SimpleModule("DoublesQuantilesSketchModule").registerSubtypes(
new NamedType(DoublesSketchAggregatorFactory.class, DOUBLES_SKETCH),
+ new NamedType(DoublesSketchMergeAggregatorFactory.class, DOUBLES_SKETCH_MERGE),
new NamedType(DoublesSketchToHistogramPostAggregator.class, DOUBLES_SKETCH_HISTOGRAM_POST_AGG),
new NamedType(DoublesSketchToQuantilePostAggregator.class, DOUBLES_SKETCH_QUANTILE_POST_AGG),
new NamedType(DoublesSketchToQuantilesPostAggregator.class, DOUBLES_SKETCH_QUANTILES_POST_AGG),
diff --git a/extensions-core/datasketches/src/test/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorTest.java b/extensions-core/datasketches/src/test/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorTest.java
index 899c8392e4f..ea07be5567b 100644
--- a/extensions-core/datasketches/src/test/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorTest.java
+++ b/extensions-core/datasketches/src/test/java/io/druid/query/aggregation/datasketches/quantiles/DoublesSketchAggregatorTest.java
@@ -28,6 +28,7 @@
import io.druid.java.util.common.guava.Sequence;
import io.druid.java.util.common.guava.Sequences;
import io.druid.query.aggregation.AggregationTestHelper;
+import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.groupby.GroupByQueryConfig;
import io.druid.query.groupby.GroupByQueryRunnerTest;
import org.junit.Assert;
@@ -60,7 +61,8 @@ public DoublesSketchAggregatorTest(final GroupByQueryConfig config)
module.getJacksonModules(), config, tempFolder);
timeSeriesHelper = AggregationTestHelper.createTimeseriesQueryAggregationTestHelper(
module.getJacksonModules(),
- tempFolder);
+ tempFolder
+ );
}
@Parameterized.Parameters(name = "{0}")
@@ -68,7 +70,7 @@ public DoublesSketchAggregatorTest(final GroupByQueryConfig config)
{
final List<Object[]> constructors = Lists.newArrayList();
for (GroupByQueryConfig config : GroupByQueryRunnerTest.testConfigs()) {
- constructors.add(new Object[] {config});
+ constructors.add(new Object[]{config});
}
return constructors;
}
@@ -78,11 +80,29 @@ public DoublesSketchAggregatorTest(final GroupByQueryConfig config)
public void serializeDeserializeFactoryWithFieldName() throws Exception
{
ObjectMapper objectMapper = new DefaultObjectMapper();
+ new DoublesSketchModule().getJacksonModules().forEach(objectMapper::registerModule);
DoublesSketchAggregatorFactory factory = new DoublesSketchAggregatorFactory("name", "filedName", 128);
- DoublesSketchAggregatorFactory other = objectMapper.readValue(
+ AggregatorFactory other = objectMapper.readValue(
objectMapper.writeValueAsString(factory),
- DoublesSketchAggregatorFactory.class);
+ AggregatorFactory.class
+ );
+
+ Assert.assertEquals(factory, other);
+ }
+
+ // this is to test Json properties and equals for the combining factory
+ @Test
+ public void serializeDeserializeCombiningFactoryWithFieldName() throws Exception
+ {
+ ObjectMapper objectMapper = new DefaultObjectMapper();
+ new DoublesSketchModule().getJacksonModules().forEach(objectMapper::registerModule);
+ DoublesSketchAggregatorFactory factory = new DoublesSketchMergeAggregatorFactory("name", 128);
+
+ AggregatorFactory other = objectMapper.readValue(
+ objectMapper.writeValueAsString(factory),
+ AggregatorFactory.class
+ );
Assert.assertEquals(factory, other);
}
@@ -92,7 +112,8 @@ public void ingestingSketches() throws Exception
{
Sequence<Row> seq = helper.createIndexAndRunQueryOnSegment(
new File(this.getClass().getClassLoader().getResource("quantiles/doubles_sketch_data.tsv").getFile()),
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"type\": \"string\",",
" \"parseSpec\": {",
@@ -105,16 +126,20 @@ public void ingestingSketches() throws Exception
" },",
" \"columns\": [\"timestamp\", \"product\", \"sketch\"]",
" }",
- "}"),
- String.join("\n",
+ "}"
+ ),
+ String.join(
+ "\n",
"[",
" {\"type\": \"quantilesDoublesSketch\", \"name\": \"sketch\", \"fieldName\": \"sketch\", \"k\": 128},",
" {\"type\": \"quantilesDoublesSketch\", \"name\": \"non_existent_sketch\", \"fieldName\": \"non_existent_sketch\", \"k\": 128}",
- "]"),
+ "]"
+ ),
0, // minTimestamp
Granularities.NONE,
10, // maxRowCount
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"queryType\": \"groupBy\",",
" \"dataSource\": \"test_datasource\",",
@@ -129,8 +154,10 @@ public void ingestingSketches() throws Exception
" {\"type\": \"quantilesDoublesSketchToHistogram\", \"name\": \"histogram\", \"splitPoints\": [0.25, 0.5, 0.75], \"field\": {\"type\": \"fieldAccess\", \"fieldName\": \"sketch\"}}",
" ],",
" \"intervals\": [\"2016-01-01T00:00:00.000Z/2016-01-31T00:00:00.000Z\"]",
- "}"));
- List<Row> results = Sequences.toList(seq, new ArrayList<Row>());
+ "}"
+ )
+ );
+ List<Row> results = Sequences.toList(seq, new ArrayList<>());
Assert.assertEquals(1, results.size());
Row row = results.get(0);
@@ -156,9 +183,9 @@ public void ingestingSketches() throws Exception
Object histogramObject = row.getRaw("histogram");
Assert.assertTrue(histogramObject instanceof double[]);
double[] histogram = (double[]) histogramObject;
- for (final double bin: histogram) {
- Assert.assertEquals(100, bin, 100 * 0.2); // 400 items uniformly
- // distributed into 4 bins
+ for (final double bin : histogram) {
+ // 400 items uniformly distributed into 4 bins
+ Assert.assertEquals(100, bin, 100 * 0.2);
}
}
@@ -167,7 +194,8 @@ public void buildingSketchesAtIngestionTime() throws Exception
{
Sequence<Row> seq = helper.createIndexAndRunQueryOnSegment(
new File(this.getClass().getClassLoader().getResource("quantiles/doubles_build_data.tsv").getFile()),
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"type\": \"string\",",
" \"parseSpec\": {",
@@ -180,12 +208,14 @@ public void buildingSketchesAtIngestionTime() throws Exception
" },",
" \"columns\": [\"timestamp\", \"sequenceNumber\", \"product\", \"value\"]",
" }",
- "}"),
+ "}"
+ ),
"[{\"type\": \"quantilesDoublesSketch\", \"name\": \"sketch\", \"fieldName\": \"value\", \"k\": 128}]",
0, // minTimestamp
Granularities.NONE,
10, // maxRowCount
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"queryType\": \"groupBy\",",
" \"dataSource\": \"test_datasource\",",
@@ -200,8 +230,10 @@ public void buildingSketchesAtIngestionTime() throws Exception
" {\"type\": \"quantilesDoublesSketchToHistogram\", \"name\": \"histogram\", \"splitPoints\": [0.25, 0.5, 0.75], \"field\": {\"type\": \"fieldAccess\", \"fieldName\": \"sketch\"}}",
" ],",
" \"intervals\": [\"2016-01-01T00:00:00.000Z/2016-01-31T00:00:00.000Z\"]",
- "}"));
- List<Row> results = Sequences.toList(seq, new ArrayList<Row>());
+ "}"
+ )
+ );
+ List<Row> results = Sequences.toList(seq, new ArrayList<>());
Assert.assertEquals(1, results.size());
Row row = results.get(0);
@@ -225,7 +257,7 @@ public void buildingSketchesAtIngestionTime() throws Exception
Assert.assertEquals(4, histogram.length);
for (final double bin: histogram) {
Assert.assertEquals(100, bin, 100 * 0.2); // 400 items uniformly
- // distributed into 4 bins
+ // distributed into 4 bins
}
}
@@ -234,7 +266,8 @@ public void buildingSketchesAtQueryTime() throws Exception
{
Sequence<Row> seq = helper.createIndexAndRunQueryOnSegment(
new File(this.getClass().getClassLoader().getResource("quantiles/doubles_build_data.tsv").getFile()),
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"type\": \"string\",",
" \"parseSpec\": {",
@@ -247,12 +280,14 @@ public void buildingSketchesAtQueryTime() throws Exception
" },",
" \"columns\": [\"timestamp\", \"sequenceNumber\", \"product\", \"value\"]",
" }",
- "}"),
+ "}"
+ ),
"[{\"type\": \"doubleSum\", \"name\": \"value\", \"fieldName\": \"value\"}]",
0, // minTimestamp
Granularities.NONE,
10, // maxRowCount
- String.join("\n",
+ String.join(
+ "\n",
"{",
" \"queryType\": \"groupBy\",",
" \"dataSource\": \"test_datasource\",",
@@ -267,8 +302,10 @@ public void buildingSketchesAtQueryTime() throws Exception
" {\"type\": \"quantilesDoublesSketchToHistogram\", \"name\": \"histogram\", \"splitPoints\": [0.25, 0.5, 0.75], \"field\": {\"type\": \"fieldAccess\", \"fieldName\": \"sketch\"}}",
" ],",
" \"intervals\": [\"2016-01-01T00:00:00.000Z/2016-01-31T00:00:00.000Z\"]",
- "}"));
- List<Row> results = Sequences.toList(seq, new ArrayList<Row>());
+ "}"
+ )
+ );
+ List<Row> results = Sequences.toList(seq, new ArrayList<>());
Assert.assertEquals(1, results.size());
Row row = results.get(0);
@@ -296,7 +333,7 @@ public void buildingSketchesAtQueryTime() throws Exception
double[] histogram = (double[]) histogramObject;
for (final double bin: histogram) {
Assert.assertEquals(100, bin, 100 * 0.2); // 400 items uniformly
- // distributed into 4 bins
+ // distributed into 4 bins
}
}
@@ -319,7 +356,8 @@ public void QueryingDataWithFieldNameValueAsFloatInsteadOfSketch() throws Except
" },",
" \"columns\": [\"timestamp\", \"sequenceNumber\", \"product\", \"value\"]",
" }",
- "}"),
+ "}"
+ ),
"[{\"type\": \"doubleSum\", \"name\": \"value\", \"fieldName\": \"value\"}]",
0, // minTimestamp
Granularities.NONE,
@@ -340,8 +378,10 @@ public void QueryingDataWithFieldNameValueAsFloatInsteadOfSketch() throws Except
" {\"type\": \"quantilesDoublesSketchToHistogram\", \"name\": \"histogram\", \"splitPoints\": [0.25, 0.5, 0.75], \"field\": {\"type\": \"fieldAccess\", \"fieldName\": \"sketch\"}}",
" ],",
" \"intervals\": [\"2016-01-01T00:00:00.000Z/2016-01-31T00:00:00.000Z\"]",
- "}"));
- List<Row> results = Sequences.toList(seq, new ArrayList<Row>());
+ "}"
+ )
+ );
+ List<Row> results = Sequences.toList(seq, new ArrayList<>());
Assert.assertEquals(1, results.size());
Row row = results.get(0);
@@ -369,7 +409,7 @@ public void QueryingDataWithFieldNameValueAsFloatInsteadOfSketch() throws Except
double[] histogram = (double[]) histogramObject;
for (final double bin: histogram) {
Assert.assertEquals(100, bin, 100 * 0.2); // 400 items uniformly
- // distributed into 4 bins
+ // distributed into 4 bins
}
}
@@ -392,7 +432,8 @@ public void TimeSeriesQueryInputAsFloat() throws Exception
" },",
" \"columns\": [\"timestamp\", \"sequenceNumber\", \"product\", \"value\"]",
" }",
- "}"),
+ "}"
+ ),
"[{\"type\": \"doubleSum\", \"name\": \"value\", \"fieldName\": \"value\"}]",
0, // minTimestamp
Granularities.NONE,
@@ -412,8 +453,10 @@ public void TimeSeriesQueryInputAsFloat() throws Exception
" {\"type\": \"quantilesDoublesSketchToHistogram\", \"name\": \"histogram1\", \"splitPoints\": [0.25, 0.5, 0.75], \"field\": {\"type\": \"fieldAccess\", \"fieldName\": \"sketch\"}}",
" ],",
" \"intervals\": [\"2016-01-01T00:00:00.000Z/2016-01-31T00:00:00.000Z\"]",
- "}"));
- List<Row> results = Sequences.toList(seq, new ArrayList<Row>());
+ "}"
+ )
+ );
+ List<Row> results = Sequences.toList(seq, new ArrayList<>());
Assert.assertEquals(1, results.size());
}
}
diff --git a/extensions-core/druid-basic-security/pom.xml b/extensions-core/druid-basic-security/pom.xml
index 1de01638186..1ad7b3e4d95 100644
--- a/extensions-core/druid-basic-security/pom.xml
+++ b/extensions-core/druid-basic-security/pom.xml
@@ -17,9 +17,7 @@
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -30,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/BasicAuthUtils.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/BasicAuthUtils.java
index 9b1f92d1603..5bc80f8ed81 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/BasicAuthUtils.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/BasicAuthUtils.java
@@ -117,7 +117,7 @@ public static String getEncodedCredentials(final String unencodedCreds)
}
@Nullable
- public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq)
+ public static String getEncodedUserSecretFromHttpReq(HttpServletRequest httpReq)
{
String authHeader = httpReq.getHeader("Authorization");
@@ -133,8 +133,12 @@ public static String getBasicUserSecretFromHttpReq(HttpServletRequest httpReq)
return null;
}
- String encodedUserSecret = authHeader.substring(6);
+ return authHeader.substring(6);
+ }
+ @Nullable
+ public static String decodeUserSecret(String encodedUserSecret)
+ {
try {
return StringUtils.fromUtf8(Base64.getDecoder().decode(encodedUserSecret));
}
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/CommonCacheNotifier.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/CommonCacheNotifier.java
index 4b7a557197c..9554928ba60 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/CommonCacheNotifier.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/CommonCacheNotifier.java
@@ -21,12 +21,12 @@
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.HttpClient;
-import com.metamx.http.client.Request;
-import com.metamx.http.client.response.ClientResponse;
-import com.metamx.http.client.response.HttpResponseHandler;
-import com.metamx.http.client.response.StatusResponseHolder;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.HttpClient;
+import io.druid.java.util.http.client.Request;
+import io.druid.java.util.http.client.response.ClientResponse;
+import io.druid.java.util.http.client.response.HttpResponseHandler;
+import io.druid.java.util.http.client.response.StatusResponseHolder;
import io.druid.discovery.DiscoveryDruidNode;
import io.druid.discovery.DruidNodeDiscovery;
import io.druid.discovery.DruidNodeDiscoveryProvider;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPAuthenticator.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPAuthenticator.java
index b127687999b..e895b8c6fc5 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPAuthenticator.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPAuthenticator.java
@@ -105,7 +105,7 @@ public AuthenticationResult authenticateJDBCContext(Map<String, Object> context)
}
if (checkCredentials(user, password.toCharArray())) {
- return new AuthenticationResult(user, name, null);
+ return new AuthenticationResult(user, authorizerName, name, null);
} else {
return null;
}
@@ -155,15 +155,22 @@ public void doFilter(
) throws IOException, ServletException
{
HttpServletResponse httpResp = (HttpServletResponse) servletResponse;
- String userSecret = BasicAuthUtils.getBasicUserSecretFromHttpReq((HttpServletRequest) servletRequest);
- if (userSecret == null) {
+ String encodedUserSecret = BasicAuthUtils.getEncodedUserSecretFromHttpReq((HttpServletRequest) servletRequest);
+ if (encodedUserSecret == null) {
// Request didn't have HTTP Basic auth credentials, move on to the next filter
filterChain.doFilter(servletRequest, servletResponse);
return;
}
- String[] splits = userSecret.split(":");
+ String decodedUserSecret = BasicAuthUtils.decodeUserSecret(encodedUserSecret);
+ if (decodedUserSecret == null) {
+ // we recognized a Basic auth header, but could not decode the user secret
+ httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ return;
+ }
+
+ String[] splits = decodedUserSecret.split(":");
if (splits.length != 2) {
httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
return;
@@ -173,8 +180,11 @@ public void doFilter(
char[] password = splits[1].toCharArray();
if (checkCredentials(user, password)) {
- AuthenticationResult authenticationResult = new AuthenticationResult(user, authorizerName, null);
+ AuthenticationResult authenticationResult = new AuthenticationResult(user, authorizerName, name, null);
servletRequest.setAttribute(AuthConfig.DRUID_AUTHENTICATION_RESULT, authenticationResult);
+ } else {
+ httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ return;
}
filterChain.doFilter(servletRequest, servletResponse);
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPEscalator.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPEscalator.java
index 2eb73a23bf2..d2993f6509d 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPEscalator.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BasicHTTPEscalator.java
@@ -22,21 +22,11 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
-import com.google.common.base.Throwables;
-import com.metamx.http.client.CredentialedHttpClient;
-import com.metamx.http.client.HttpClient;
-import com.metamx.http.client.auth.BasicCredentials;
-import io.druid.java.util.common.StringUtils;
-import io.druid.security.basic.BasicAuthUtils;
+import io.druid.java.util.http.client.CredentialedHttpClient;
+import io.druid.java.util.http.client.HttpClient;
+import io.druid.java.util.http.client.auth.BasicCredentials;
import io.druid.server.security.AuthenticationResult;
import io.druid.server.security.Escalator;
-import org.eclipse.jetty.client.api.Authentication;
-import org.eclipse.jetty.client.api.ContentResponse;
-import org.eclipse.jetty.client.api.Request;
-import org.eclipse.jetty.util.Attributes;
-import org.jboss.netty.handler.codec.http.HttpHeaders;
-
-import java.net.URI;
@JsonTypeName("basic")
public class BasicHTTPEscalator implements Escalator
@@ -66,51 +56,11 @@ public HttpClient createEscalatedClient(HttpClient baseClient)
);
}
- @Override
- public org.eclipse.jetty.client.HttpClient createEscalatedJettyClient(org.eclipse.jetty.client.HttpClient baseClient)
- {
- baseClient.getAuthenticationStore().addAuthentication(new Authentication()
- {
- @Override
- public boolean matches(String type, URI uri, String realm)
- {
- return true;
- }
-
- @Override
- public Result authenticate(
- final Request request, ContentResponse response, Authentication.HeaderInfo headerInfo, Attributes context
- )
- {
- return new Result()
- {
- @Override
- public URI getURI()
- {
- return request.getURI();
- }
-
- @Override
- public void apply(Request request)
- {
- try {
- final String unencodedCreds = StringUtils.format("%s:%s", internalClientUsername, internalClientPassword);
- final String base64Creds = BasicAuthUtils.getEncodedCredentials(unencodedCreds);
- request.getHeaders().add(HttpHeaders.Names.AUTHORIZATION, "Basic " + base64Creds);
- }
- catch (Throwable e) {
- Throwables.propagate(e);
- }
- }
- };
- }
- });
- return baseClient;
- }
-
@Override
public AuthenticationResult createEscalatedAuthenticationResult()
{
- return new AuthenticationResult(internalClientUsername, authorizerName, null);
+ // if you found your self asking why the authenticatedBy field is set to null please read this:
+ // https://github.com/druid-io/druid/pull/5706#discussion_r185940889
+ return new AuthenticationResult(internalClientUsername, authorizerName, null, null);
}
}
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHandler.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHandler.java
index d8b65a5e8ff..c548cfc0ac1 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHandler.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHandler.java
@@ -19,9 +19,9 @@
package io.druid.security.basic.authentication;
-import com.metamx.http.client.response.ClientResponse;
-import com.metamx.http.client.response.FullResponseHolder;
-import com.metamx.http.client.response.HttpResponseHandler;
+import io.druid.java.util.http.client.response.ClientResponse;
+import io.druid.java.util.http.client.response.FullResponseHolder;
+import io.druid.java.util.http.client.response.HttpResponseHandler;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpResponse;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHolder.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHolder.java
index a273f503098..b701468b461 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHolder.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/BytesFullResponseHolder.java
@@ -19,7 +19,7 @@
package io.druid.security.basic.authentication;
-import com.metamx.http.client.response.FullResponseHolder;
+import io.druid.java.util.http.client.response.FullResponseHolder;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.jboss.netty.handler.codec.http.HttpResponseStatus;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorBasicAuthenticatorCacheNotifier.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorBasicAuthenticatorCacheNotifier.java
index 2eff574cfd9..5ab501b5166 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorBasicAuthenticatorCacheNotifier.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorBasicAuthenticatorCacheNotifier.java
@@ -21,8 +21,8 @@
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.HttpClient;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.HttpClient;
import io.druid.concurrent.LifecycleLock;
import io.druid.discovery.DruidNodeDiscoveryProvider;
import io.druid.guice.ManageLifecycle;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorPollingBasicAuthenticatorCacheManager.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorPollingBasicAuthenticatorCacheManager.java
index 178232e13df..bc9a713b9c1 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorPollingBasicAuthenticatorCacheManager.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/cache/CoordinatorPollingBasicAuthenticatorCacheManager.java
@@ -21,16 +21,16 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
-import com.google.common.io.Files;
import com.google.inject.Inject;
import com.google.inject.Injector;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.Request;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.Request;
import io.druid.client.coordinator.Coordinator;
import io.druid.concurrent.LifecycleLock;
import io.druid.discovery.DruidLeaderClient;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Smile;
+import io.druid.java.util.common.FileUtils;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.RetryUtils;
import io.druid.java.util.common.StringUtils;
@@ -235,7 +235,7 @@ private void writeUserMapToDisk(String prefix, byte[] userMapBytes) throws IOExc
File cacheDir = new File(commonCacheConfig.getCacheDirectory());
cacheDir.mkdirs();
File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserMapFilename(prefix));
- Files.write(userMapBytes, userMapFile);
+ FileUtils.writeAtomically(userMapFile, out -> out.write(userMapBytes));
}
private Map<String, BasicAuthenticatorUser> tryFetchUserMapFromCoordinator(String prefix) throws Exception
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/updater/CoordinatorBasicAuthenticatorMetadataStorageUpdater.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/updater/CoordinatorBasicAuthenticatorMetadataStorageUpdater.java
index eacc0242237..872cdc10320 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/updater/CoordinatorBasicAuthenticatorMetadataStorageUpdater.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authentication/db/updater/CoordinatorBasicAuthenticatorMetadataStorageUpdater.java
@@ -22,7 +22,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.common.config.ConfigManager;
import io.druid.concurrent.LifecycleLock;
import io.druid.guice.ManageLifecycle;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorBasicAuthorizerCacheNotifier.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorBasicAuthorizerCacheNotifier.java
index 924107cf92a..9f7a1def62a 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorBasicAuthorizerCacheNotifier.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorBasicAuthorizerCacheNotifier.java
@@ -21,8 +21,8 @@
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.HttpClient;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.HttpClient;
import io.druid.concurrent.LifecycleLock;
import io.druid.discovery.DruidNodeDiscoveryProvider;
import io.druid.guice.ManageLifecycle;
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorPollingBasicAuthorizerCacheManager.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorPollingBasicAuthorizerCacheManager.java
index a57d931c97f..5f993d3121f 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorPollingBasicAuthorizerCacheManager.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/cache/CoordinatorPollingBasicAuthorizerCacheManager.java
@@ -21,16 +21,16 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
-import com.google.common.io.Files;
import com.google.inject.Inject;
import com.google.inject.Injector;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.Request;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.Request;
import io.druid.client.coordinator.Coordinator;
import io.druid.concurrent.LifecycleLock;
import io.druid.discovery.DruidLeaderClient;
import io.druid.guice.ManageLifecycle;
import io.druid.guice.annotations.Smile;
+import io.druid.java.util.common.FileUtils;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.RetryUtils;
import io.druid.java.util.common.StringUtils;
@@ -212,7 +212,7 @@ private void writeMapToDisk(String prefix, byte[] userMapBytes) throws IOExcepti
File cacheDir = new File(commonCacheConfig.getCacheDirectory());
cacheDir.mkdirs();
File userMapFile = new File(commonCacheConfig.getCacheDirectory(), getUserRoleMapFilename(prefix));
- Files.write(userMapBytes, userMapFile);
+ FileUtils.writeAtomically(userMapFile, out -> out.write(userMapBytes));
}
@Nullable
diff --git a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/updater/CoordinatorBasicAuthorizerMetadataStorageUpdater.java b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/updater/CoordinatorBasicAuthorizerMetadataStorageUpdater.java
index ca80d19712d..adc0a60591c 100644
--- a/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/updater/CoordinatorBasicAuthorizerMetadataStorageUpdater.java
+++ b/extensions-core/druid-basic-security/src/main/java/io/druid/security/basic/authorization/db/updater/CoordinatorBasicAuthorizerMetadataStorageUpdater.java
@@ -23,7 +23,7 @@
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.common.config.ConfigManager;
import io.druid.concurrent.LifecycleLock;
import io.druid.guice.ManageLifecycle;
diff --git a/extensions-core/druid-basic-security/src/test/java/io/druid/security/authentication/BasicHTTPAuthenticatorTest.java b/extensions-core/druid-basic-security/src/test/java/io/druid/security/authentication/BasicHTTPAuthenticatorTest.java
new file mode 100644
index 00000000000..e78b424b8fc
--- /dev/null
+++ b/extensions-core/druid-basic-security/src/test/java/io/druid/security/authentication/BasicHTTPAuthenticatorTest.java
@@ -0,0 +1,261 @@
+/*
+ * 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.security.authentication;
+
+import com.google.common.collect.ImmutableMap;
+import com.google.inject.Provider;
+import com.google.inject.util.Providers;
+import io.druid.java.util.common.StringUtils;
+import io.druid.security.basic.authentication.BasicHTTPAuthenticator;
+import io.druid.security.basic.authentication.db.cache.BasicAuthenticatorCacheManager;
+import io.druid.security.basic.authentication.entity.BasicAuthenticatorCredentialUpdate;
+import io.druid.security.basic.authentication.entity.BasicAuthenticatorCredentials;
+import io.druid.security.basic.authentication.entity.BasicAuthenticatorUser;
+import io.druid.server.security.AuthConfig;
+import io.druid.server.security.AuthenticationResult;
+import org.asynchttpclient.util.Base64;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+import java.util.Map;
+
+public class BasicHTTPAuthenticatorTest
+{
+ public static BasicAuthenticatorCredentials USER_A_CREDENTIALS = new BasicAuthenticatorCredentials(
+ new BasicAuthenticatorCredentialUpdate("helloworld", 20)
+ );
+
+ public static Provider<BasicAuthenticatorCacheManager> CACHE_MANAGER_PROVIDER = Providers.of(
+ new BasicAuthenticatorCacheManager()
+ {
+ @Override
+ public void handleAuthenticatorUpdate(String authenticatorPrefix, byte[] serializedUserMap)
+ {
+
+ }
+
+ @Override
+ public Map<String, BasicAuthenticatorUser> getUserMap(String authenticatorPrefix)
+ {
+ return ImmutableMap.of(
+ "userA", new BasicAuthenticatorUser("userA", USER_A_CREDENTIALS)
+ );
+ }
+ }
+ );
+
+ public static BasicHTTPAuthenticator AUTHENTICATOR = new BasicHTTPAuthenticator(
+ CACHE_MANAGER_PROVIDER,
+ "basic",
+ "basic",
+ "a",
+ "a",
+ false,
+ null,
+ null
+ );
+
+ @Test
+ public void testGoodPassword() throws IOException, ServletException
+ {
+ String header = Base64.encode(
+ StringUtils.toUtf8("userA:helloworld")
+ );
+ header = StringUtils.format("Basic %s", header);
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ req.setAttribute(
+ AuthConfig.DRUID_AUTHENTICATION_RESULT,
+ new AuthenticationResult("userA", "basic", "basic", null)
+ );
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ EasyMock.replay(resp);
+
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ filterChain.doFilter(req, resp);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testBadPassword() throws IOException, ServletException
+ {
+ String header = Base64.encode(
+ StringUtils.toUtf8("userA:badpassword")
+ );
+ header = StringUtils.format("Basic %s", header);
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(resp);
+
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testUnknownUser() throws IOException, ServletException
+ {
+ String header = Base64.encode(
+ StringUtils.toUtf8("userB:helloworld")
+ );
+ header = StringUtils.format("Basic %s", header);
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(resp);
+
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testRecognizedButMalformedBasicAuthHeader() throws IOException, ServletException
+ {
+ String header = Base64.encode(
+ StringUtils.toUtf8("malformed decoded header data")
+ );
+ header = StringUtils.format("Basic %s", header);
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(resp);
+
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testRecognizedButNotBase64BasicAuthHeader() throws IOException, ServletException
+ {
+ String header = "Basic this_is_not_base64";
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(resp);
+
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testUnrecognizedHeader() throws IOException, ServletException
+ {
+ String header = Base64.encode(
+ StringUtils.toUtf8("userA:helloworld")
+ );
+ header = StringUtils.format("NotBasic %s", header);
+
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(header);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ EasyMock.replay(resp);
+
+ // Authentication filter should move on to the next filter in the chain without sending a response
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ filterChain.doFilter(req, resp);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+
+ @Test
+ public void testMissingHeader() throws IOException, ServletException
+ {
+ HttpServletRequest req = EasyMock.createMock(HttpServletRequest.class);
+ EasyMock.expect(req.getHeader("Authorization")).andReturn(null);
+ EasyMock.replay(req);
+
+ HttpServletResponse resp = EasyMock.createMock(HttpServletResponse.class);
+ EasyMock.replay(resp);
+
+ // Authentication filter should move on to the next filter in the chain without sending a response
+ FilterChain filterChain = EasyMock.createMock(FilterChain.class);
+ filterChain.doFilter(req, resp);
+ EasyMock.expectLastCall().times(1);
+ EasyMock.replay(filterChain);
+
+ Filter authenticatorFilter = AUTHENTICATOR.getFilter();
+ authenticatorFilter.doFilter(req, resp, filterChain);
+
+ EasyMock.verify(req, resp, filterChain);
+ }
+}
diff --git a/extensions-core/druid-basic-security/src/test/java/io/druid/security/authorization/BasicRoleBasedAuthorizerTest.java b/extensions-core/druid-basic-security/src/test/java/io/druid/security/authorization/BasicRoleBasedAuthorizerTest.java
index 6132753c684..aafac305525 100644
--- a/extensions-core/druid-basic-security/src/test/java/io/druid/security/authorization/BasicRoleBasedAuthorizerTest.java
+++ b/extensions-core/druid-basic-security/src/test/java/io/druid/security/authorization/BasicRoleBasedAuthorizerTest.java
@@ -116,7 +116,7 @@ public void testAuth()
updater.setPermissions(AUTHORIZER_NAME, "druidRole", permissions);
- AuthenticationResult authenticationResult = new AuthenticationResult("druid", "druid", null);
+ AuthenticationResult authenticationResult = new AuthenticationResult("druid", "druid", null, null);
Access access = authorizer.authorize(
authenticationResult,
diff --git a/extensions-core/druid-kerberos/pom.xml b/extensions-core/druid-kerberos/pom.xml
index 08696bed812..ff556390722 100644
--- a/extensions-core/druid-kerberos/pom.xml
+++ b/extensions-core/druid-kerberos/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -30,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosAuthenticator.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosAuthenticator.java
index 785a5a415cb..df799c09df5 100644
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosAuthenticator.java
+++ b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosAuthenticator.java
@@ -23,6 +23,8 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import io.druid.guice.annotations.Self;
import io.druid.java.util.common.StringUtils;
@@ -41,6 +43,8 @@
import org.apache.hadoop.security.authentication.util.Signer;
import org.apache.hadoop.security.authentication.util.SignerException;
import org.apache.hadoop.security.authentication.util.SignerSecretProvider;
+import org.eclipse.jetty.client.api.Request;
+import org.eclipse.jetty.http.HttpHeader;
import sun.security.krb5.EncryptedData;
import sun.security.krb5.EncryptionKey;
import sun.security.krb5.internal.APReq;
@@ -72,18 +76,25 @@
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
+import java.net.HttpCookie;
import java.security.Principal;
+import java.text.SimpleDateFormat;
import java.util.Collections;
+import java.util.Date;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
+import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
+import java.util.TimeZone;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
@JsonTypeName("kerberos")
public class KerberosAuthenticator implements Authenticator
@@ -91,40 +102,44 @@
private static final Logger log = new Logger(KerberosAuthenticator.class);
private static final Pattern HADOOP_AUTH_COOKIE_REGEX = Pattern.compile(".*p=(\\S+)&t=.*");
public static final List<String> DEFAULT_EXCLUDED_PATHS = Collections.emptyList();
+ public static final String SIGNED_TOKEN_ATTRIBUTE = "signedToken";
private final DruidNode node;
private final String serverPrincipal;
private final String serverKeytab;
- private final String internalClientPrincipal;
- private final String internalClientKeytab;
private final String authToLocal;
private final List<String> excludedPaths;
private final String cookieSignatureSecret;
private final String authorizerName;
+ private final String name;
private LoginContext loginContext;
@JsonCreator
public KerberosAuthenticator(
@JsonProperty("serverPrincipal") String serverPrincipal,
@JsonProperty("serverKeytab") String serverKeytab,
- @JsonProperty("internalClientPrincipal") String internalClientPrincipal,
- @JsonProperty("internalClientKeytab") String internalClientKeytab,
@JsonProperty("authToLocal") String authToLocal,
@JsonProperty("excludedPaths") List<String> excludedPaths,
@JsonProperty("cookieSignatureSecret") String cookieSignatureSecret,
@JsonProperty("authorizerName") String authorizerName,
+ @JsonProperty("name") String name,
@JacksonInject @Self DruidNode node
)
{
this.node = node;
- this.serverPrincipal = serverPrincipal;
this.serverKeytab = serverKeytab;
- this.internalClientPrincipal = internalClientPrincipal;
- this.internalClientKeytab = internalClientKeytab;
this.authToLocal = authToLocal == null ? "DEFAULT" : authToLocal;
this.excludedPaths = excludedPaths == null ? DEFAULT_EXCLUDED_PATHS : excludedPaths;
this.cookieSignatureSecret = cookieSignatureSecret;
this.authorizerName = authorizerName;
+ this.name = Preconditions.checkNotNull(name);
+
+ try {
+ this.serverPrincipal = SecurityUtil.getServerPrincipal(serverPrincipal, node.getHost());
+ }
+ catch (Exception e) {
+ throw new RuntimeException(e);
+ }
}
@Override
@@ -259,7 +274,7 @@ public void doFilter(
if (clientPrincipal != null) {
request.setAttribute(
AuthConfig.DRUID_AUTHENTICATION_RESULT,
- new AuthenticationResult(clientPrincipal, authorizerName, null)
+ new AuthenticationResult(clientPrincipal, authorizerName, name, null)
);
}
}
@@ -333,7 +348,20 @@ public Principal getUserPrincipal()
createAuthCookie(httpResponse, signedToken, getCookieDomain(),
getCookiePath(), token.getExpires(), isHttps
);
+ request.setAttribute(SIGNED_TOKEN_ATTRIBUTE, tokenToCookieString(
+ signedToken,
+ getCookieDomain(),
+ getCookiePath(),
+ token.getExpires(),
+ !token.isExpired() && token.getExpires() > 0,
+ isHttps
+ ));
}
+ // Since this request is validated also set DRUID_AUTHENTICATION_RESULT
+ request.setAttribute(
+ AuthConfig.DRUID_AUTHENTICATION_RESULT,
+ new AuthenticationResult(token.getName(), authorizerName, name, null)
+ );
doFilter(filterChain, httpRequest, httpResponse);
}
} else {
@@ -345,7 +373,7 @@ public Principal getUserPrincipal()
errCode = HttpServletResponse.SC_FORBIDDEN;
authenticationEx = ex;
if (log.isDebugEnabled()) {
- log.debug("Authentication exception: " + ex.getMessage(), ex);
+ log.debug(ex, "Authentication exception: " + ex.getMessage());
} else {
log.warn("Authentication exception: " + ex.getMessage());
}
@@ -388,20 +416,12 @@ public Principal getUserPrincipal()
public Map<String, String> getInitParameters()
{
Map<String, String> params = new HashMap<String, String>();
- try {
- params.put(
- "kerberos.principal",
- SecurityUtil.getServerPrincipal(serverPrincipal, node.getHost())
- );
- params.put("kerberos.keytab", serverKeytab);
- params.put(AuthenticationFilter.AUTH_TYPE, DruidKerberosAuthenticationHandler.class.getName());
- params.put("kerberos.name.rules", authToLocal);
- if (cookieSignatureSecret != null) {
- params.put("signature.secret", cookieSignatureSecret);
- }
- }
- catch (IOException e) {
- Throwables.propagate(e);
+ params.put("kerberos.principal", serverPrincipal);
+ params.put("kerberos.keytab", serverKeytab);
+ params.put(AuthenticationFilter.AUTH_TYPE, DruidKerberosAuthenticationHandler.class.getName());
+ params.put("kerberos.name.rules", authToLocal);
+ if (cookieSignatureSecret != null) {
+ params.put("signature.secret", cookieSignatureSecret);
}
return params;
}
@@ -440,6 +460,22 @@ private boolean isExcluded(String path)
return false;
}
+ @Override
+ public void decorateProxyRequest(
+ HttpServletRequest clientRequest, HttpServletResponse proxyResponse, Request proxyRequest
+ )
+ {
+ Object cookieToken = clientRequest.getAttribute(SIGNED_TOKEN_ATTRIBUTE);
+ if (cookieToken != null && cookieToken instanceof String) {
+ log.debug("Found cookie token will attache it to proxyRequest as cookie");
+ String authResult = (String) cookieToken;
+ String existingCookies = proxyRequest.getCookies()
+ .stream()
+ .map(HttpCookie::toString)
+ .collect(Collectors.joining(";"));
+ proxyRequest.header(HttpHeader.COOKIE, Joiner.on(";").join(authResult, existingCookies));
+ }
+ }
/**
* Kerberos context configuration for the JDK GSS library. Copied from hadoop-auth's KerberosAuthenticationHandler.
@@ -533,8 +569,8 @@ private String getPrincipalFromRequestNew(HttpServletRequest req)
for (Object cred : serverCreds) {
if (cred instanceof KeyTab) {
KeyTab serverKeyTab = (KeyTab) cred;
- KerberosPrincipal serverPrincipal = new KerberosPrincipal(this.serverPrincipal);
- KerberosKey[] serverKeys = serverKeyTab.getKeys(serverPrincipal);
+ KerberosPrincipal kerberosPrincipal = new KerberosPrincipal(serverPrincipal);
+ KerberosKey[] serverKeys = serverKeyTab.getKeys(kerberosPrincipal);
for (KerberosKey key : serverKeys) {
if (key.getKeyType() == eType) {
finalKey = new EncryptionKey(key.getKeyType(), key.getEncoded());
@@ -573,12 +609,10 @@ private boolean isValueAPReq(DerValue value)
private void initializeKerberosLogin() throws ServletException
{
- String principal;
String keytab;
try {
- principal = SecurityUtil.getServerPrincipal(serverPrincipal, node.getHost());
- if (principal == null || principal.trim().length() == 0) {
+ if (serverPrincipal == null || serverPrincipal.trim().length() == 0) {
throw new ServletException("Principal not defined in configuration");
}
keytab = serverKeytab;
@@ -590,19 +624,85 @@ private void initializeKerberosLogin() throws ServletException
}
Set<Principal> principals = new HashSet<Principal>();
- principals.add(new KerberosPrincipal(principal));
+ principals.add(new KerberosPrincipal(serverPrincipal));
Subject subject = new Subject(false, principals, new HashSet<Object>(), new HashSet<Object>());
- DruidKerberosConfiguration kerberosConfiguration = new DruidKerberosConfiguration(keytab, principal);
+ DruidKerberosConfiguration kerberosConfiguration = new DruidKerberosConfiguration(keytab, serverPrincipal);
- log.info("Login using keytab " + keytab + ", for principal " + principal);
+ log.info("Login using keytab " + keytab + ", for principal " + serverPrincipal);
loginContext = new LoginContext("", subject, null, kerberosConfiguration);
loginContext.login();
- log.info("Initialized, principal %s from keytab %s", principal, keytab);
+ log.info("Initialized, principal %s from keytab %s", serverPrincipal, keytab);
}
catch (Exception ex) {
throw new ServletException(ex);
}
}
+
+ /**
+ * Creates the Hadoop authentication HTTP cookie.
+ *
+ * @param resp the response object.
+ * @param token authentication token for the cookie.
+ * @param domain the cookie domain.
+ * @param path the cookie path.
+ * @param expires UNIX timestamp that indicates the expire date of the
+ * cookie. It has no effect if its value < 0.
+ * @param isSecure is the cookie secure?
+ * @param isCookiePersistent whether the cookie is persistent or not.
+ *the following code copy/past from Hadoop 3.0.0 copied to avoid compilation issue due to new signature,
+ * org.apache.hadoop.security.authentication.server.AuthenticationFilter#createAuthCookie
+ * (
+ * javax.servlet.http.HttpServletResponse,
+ * java.lang.String,
+ * java.lang.String,
+ * java.lang.String,
+ * long, boolean, boolean)
+ */
+ private static void tokenToAuthCookie(
+ HttpServletResponse resp, String token,
+ String domain, String path, long expires,
+ boolean isCookiePersistent,
+ boolean isSecure
+ )
+ {
+ resp.addHeader("Set-Cookie", tokenToCookieString(token, domain, path, expires, isCookiePersistent, isSecure));
+ }
+
+ private static String tokenToCookieString(
+ String token,
+ String domain, String path, long expires,
+ boolean isCookiePersistent,
+ boolean isSecure
+ )
+ {
+ StringBuilder sb = new StringBuilder(AuthenticatedURL.AUTH_COOKIE)
+ .append("=");
+ if (token != null && token.length() > 0) {
+ sb.append("\"").append(token).append("\"");
+ }
+
+ if (path != null) {
+ sb.append("; Path=").append(path);
+ }
+
+ if (domain != null) {
+ sb.append("; Domain=").append(domain);
+ }
+
+ if (expires >= 0 && isCookiePersistent) {
+ Date date = new Date(expires);
+ SimpleDateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss zzz", Locale.ENGLISH);
+ df.setTimeZone(TimeZone.getTimeZone("GMT"));
+ sb.append("; Expires=").append(df.format(date));
+ }
+
+ if (isSecure) {
+ sb.append("; Secure");
+ }
+
+ sb.append("; HttpOnly");
+ return sb.toString();
+ }
}
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosEscalator.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosEscalator.java
index e995233a23c..3b25f5e8af2 100644
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosEscalator.java
+++ b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosEscalator.java
@@ -22,20 +22,10 @@
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
-import com.google.common.base.Throwables;
-import com.metamx.http.client.HttpClient;
import io.druid.java.util.common.logger.Logger;
+import io.druid.java.util.http.client.HttpClient;
import io.druid.server.security.AuthenticationResult;
import io.druid.server.security.Escalator;
-import org.apache.hadoop.security.UserGroupInformation;
-import org.eclipse.jetty.client.api.Authentication;
-import org.eclipse.jetty.client.api.ContentResponse;
-import org.eclipse.jetty.client.api.Request;
-import org.eclipse.jetty.util.Attributes;
-import org.jboss.netty.handler.codec.http.HttpHeaders;
-
-import java.net.URI;
-import java.security.PrivilegedExceptionAction;
@JsonTypeName("kerberos")
public class KerberosEscalator implements Escalator
@@ -64,71 +54,12 @@ public HttpClient createEscalatedClient(HttpClient baseClient)
return new KerberosHttpClient(baseClient, internalClientPrincipal, internalClientKeytab);
}
- @Override
- public org.eclipse.jetty.client.HttpClient createEscalatedJettyClient(org.eclipse.jetty.client.HttpClient baseClient)
- {
- baseClient.getAuthenticationStore().addAuthentication(new Authentication()
- {
- @Override
- public boolean matches(String type, URI uri, String realm)
- {
- return true;
- }
-
- @Override
- public Result authenticate(
- final Request request, ContentResponse response, Authentication.HeaderInfo headerInfo, Attributes context
- )
- {
- return new Result()
- {
- @Override
- public URI getURI()
- {
- return request.getURI();
- }
-
- @Override
- public void apply(Request request)
- {
- try {
- // No need to set cookies as they are handled by Jetty Http Client itself.
- URI uri = request.getURI();
- if (DruidKerberosUtil.needToSendCredentials(baseClient.getCookieStore(), uri)) {
- log.debug(
- "No Auth Cookie found for URI[%s]. Existing Cookies[%s] Authenticating... ",
- uri,
- baseClient.getCookieStore().getCookies()
- );
- final String host = request.getHost();
- DruidKerberosUtil.authenticateIfRequired(internalClientPrincipal, internalClientKeytab);
- UserGroupInformation currentUser = UserGroupInformation.getCurrentUser();
- String challenge = currentUser.doAs(new PrivilegedExceptionAction<String>()
- {
- @Override
- public String run() throws Exception
- {
- return DruidKerberosUtil.kerberosChallenge(host);
- }
- });
- request.getHeaders().add(HttpHeaders.Names.AUTHORIZATION, "Negotiate " + challenge);
- } else {
- log.debug("Found Auth Cookie found for URI[%s].", uri);
- }
- }
- catch (Throwable e) {
- Throwables.propagate(e);
- }
- }
- };
- }
- });
- return baseClient;
- }
-
@Override
public AuthenticationResult createEscalatedAuthenticationResult()
{
- return new AuthenticationResult(internalClientPrincipal, authorizerName, null);
+ // if you found your self asking why the authenticatedBy field is set to null please read this:
+ // https://github.com/druid-io/druid/pull/5706#discussion_r185940889
+ return new AuthenticationResult(internalClientPrincipal, authorizerName, null, null);
}
+
}
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosHttpClient.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosHttpClient.java
index c79deaf60e3..b1a66a8b2a7 100644
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosHttpClient.java
+++ b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/KerberosHttpClient.java
@@ -24,10 +24,10 @@
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
-import com.metamx.http.client.AbstractHttpClient;
-import com.metamx.http.client.HttpClient;
-import com.metamx.http.client.Request;
-import com.metamx.http.client.response.HttpResponseHandler;
+import io.druid.java.util.http.client.AbstractHttpClient;
+import io.druid.java.util.http.client.HttpClient;
+import io.druid.java.util.http.client.Request;
+import io.druid.java.util.http.client.response.HttpResponseHandler;
import io.druid.java.util.common.concurrent.Execs;
import io.druid.java.util.common.logger.Logger;
import org.apache.hadoop.security.UserGroupInformation;
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/ResponseCookieHandler.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/ResponseCookieHandler.java
index 5a4d4df0b43..755cdb96547 100644
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/ResponseCookieHandler.java
+++ b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/ResponseCookieHandler.java
@@ -21,8 +21,8 @@
import com.google.common.base.Function;
import com.google.common.collect.Maps;
-import com.metamx.http.client.response.ClientResponse;
-import com.metamx.http.client.response.HttpResponseHandler;
+import io.druid.java.util.http.client.response.ClientResponse;
+import io.druid.java.util.http.client.response.HttpResponseHandler;
import io.druid.java.util.common.logger.Logger;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpHeaders;
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/RetryIfUnauthorizedResponseHandler.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/RetryIfUnauthorizedResponseHandler.java
index 8d8148842c8..01a7987e2ba 100644
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/RetryIfUnauthorizedResponseHandler.java
+++ b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/RetryIfUnauthorizedResponseHandler.java
@@ -19,8 +19,8 @@
package io.druid.security.kerberos;
-import com.metamx.http.client.response.ClientResponse;
-import com.metamx.http.client.response.HttpResponseHandler;
+import io.druid.java.util.http.client.response.ClientResponse;
+import io.druid.java.util.http.client.response.HttpResponseHandler;
import io.druid.java.util.common.logger.Logger;
import org.jboss.netty.handler.codec.http.HttpChunk;
import org.jboss.netty.handler.codec.http.HttpResponse;
diff --git a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/SpnegoFilterConfig.java b/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/SpnegoFilterConfig.java
deleted file mode 100644
index 4dd4f9b01f9..00000000000
--- a/extensions-core/druid-kerberos/src/main/java/io/druid/security/kerberos/SpnegoFilterConfig.java
+++ /dev/null
@@ -1,134 +0,0 @@
-/*
- * 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.security.kerberos;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
-import java.util.Collections;
-import java.util.List;
-
-public class SpnegoFilterConfig
-{
-
- public static final List<String> DEFAULT_EXCLUDED_PATHS = Collections.emptyList();
-
- @JsonProperty
- private final String principal;
-
- @JsonProperty
- private final String keytab;
-
- @JsonProperty
- private final String authToLocal;
-
- @JsonProperty
- private final List<String> excludedPaths;
-
- @JsonProperty
- private final String cookieSignatureSecret;
-
- @JsonCreator
- public SpnegoFilterConfig(
- @JsonProperty("principal") String principal,
- @JsonProperty("keytab") String keytab,
- @JsonProperty("authToLocal") String authToLocal,
- @JsonProperty("excludedPaths") List<String> excludedPaths,
- @JsonProperty("cookieSignatureSecret") String cookieSignatureSecret
- )
- {
- this.principal = principal;
- this.keytab = keytab;
- this.authToLocal = authToLocal == null ? "DEFAULT" : authToLocal;
- this.excludedPaths = excludedPaths == null ? DEFAULT_EXCLUDED_PATHS : excludedPaths;
- this.cookieSignatureSecret = cookieSignatureSecret;
- }
-
- @JsonProperty
- public String getPrincipal()
- {
- return principal;
- }
-
- @JsonProperty
- public String getKeytab()
- {
- return keytab;
- }
-
- @JsonProperty
- public String getAuthToLocal()
- {
- return authToLocal;
- }
-
- @JsonProperty
- public List<String> getExcludedPaths()
- {
- return excludedPaths;
- }
-
- @JsonProperty
- public String getCookieSignatureSecret()
- {
- return cookieSignatureSecret;
- }
-
- @Override
- public boolean equals(Object o)
- {
- if (this == o) {
- return true;
- }
- if (o == null || getClass() != o.getClass()) {
- return false;
- }
-
- SpnegoFilterConfig that = (SpnegoFilterConfig) o;
-
- if (principal != null ? !principal.equals(that.principal) : that.principal != null) {
- return false;
- }
- if (keytab != null ? !keytab.equals(that.keytab) : that.keytab != null) {
- return false;
- }
- if (authToLocal != null ? !authToLocal.equals(that.authToLocal) : that.authToLocal != null) {
- return false;
- }
- if (excludedPaths != null ? !excludedPaths.equals(that.excludedPaths) : that.excludedPaths != null) {
- return false;
- }
- return cookieSignatureSecret != null
- ? cookieSignatureSecret.equals(that.cookieSignatureSecret)
- : that.cookieSignatureSecret == null;
-
- }
-
- @Override
- public int hashCode()
- {
- int result = principal != null ? principal.hashCode() : 0;
- result = 31 * result + (keytab != null ? keytab.hashCode() : 0);
- result = 31 * result + (authToLocal != null ? authToLocal.hashCode() : 0);
- result = 31 * result + (excludedPaths != null ? excludedPaths.hashCode() : 0);
- result = 31 * result + (cookieSignatureSecret != null ? cookieSignatureSecret.hashCode() : 0);
- return result;
- }
-}
diff --git a/extensions-core/druid-kerberos/src/test/java/io/druid/security/kerberos/SpnegoFilterConfigTest.java b/extensions-core/druid-kerberos/src/test/java/io/druid/security/kerberos/SpnegoFilterConfigTest.java
deleted file mode 100644
index e1ee9860632..00000000000
--- a/extensions-core/druid-kerberos/src/test/java/io/druid/security/kerberos/SpnegoFilterConfigTest.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * 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.security.kerberos;
-
-import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.inject.Binder;
-import com.google.inject.Guice;
-import com.google.inject.Injector;
-import com.google.inject.Module;
-import com.google.inject.Provides;
-import io.druid.guice.ConfigModule;
-import io.druid.guice.DruidGuiceExtensions;
-import io.druid.guice.JsonConfigProvider;
-import io.druid.guice.LazySingleton;
-import io.druid.guice.PropertiesModule;
-import io.druid.jackson.DefaultObjectMapper;
-import org.junit.Assert;
-import org.junit.Test;
-
-import java.util.Arrays;
-import java.util.Properties;
-
-public class SpnegoFilterConfigTest
-{
- @Test
- public void testserde()
- {
- Injector injector = Guice.createInjector(
- new Module()
- {
- @Override
- public void configure(Binder binder)
- {
- binder.install(new PropertiesModule(Arrays.asList("test.runtime.properties")));
- binder.install(new ConfigModule());
- binder.install(new DruidGuiceExtensions());
- JsonConfigProvider.bind(binder, "druid.hadoop.security.spnego", SpnegoFilterConfig.class);
- }
-
- @Provides
- @LazySingleton
- public ObjectMapper jsonMapper()
- {
- return new DefaultObjectMapper();
- }
- }
- );
-
- Properties props = injector.getInstance(Properties.class);
- SpnegoFilterConfig config = injector.getInstance(SpnegoFilterConfig.class);
-
- Assert.assertEquals(props.getProperty("druid.hadoop.security.spnego.principal"), config.getPrincipal());
- Assert.assertEquals(props.getProperty("druid.hadoop.security.spnego.keytab"), config.getKeytab());
- Assert.assertEquals(props.getProperty("druid.hadoop.security.spnego.authToLocal"), config.getAuthToLocal());
-
-
- }
-}
diff --git a/extensions-core/hdfs-storage/pom.xml b/extensions-core/hdfs-storage/pom.xml
index 5b6bb1cd432..b46181f01c7 100644
--- a/extensions-core/hdfs-storage/pom.xml
+++ b/extensions-core/hdfs-storage/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -44,6 +44,12 @@
<version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
+ <dependency>
+ <groupId>io.druid</groupId>
+ <artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
+ <scope>provided</scope>
+ </dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-client</artifactId>
@@ -135,11 +141,6 @@
</exclusion>
</exclusions>
</dependency>
- <dependency>
- <groupId>com.metamx</groupId>
- <artifactId>java-util</artifactId>
- <scope>provided</scope>
- </dependency>
<dependency>
<groupId>org.apache.hadoop</groupId>
<artifactId>hadoop-aws</artifactId>
diff --git a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentFinder.java b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentFinder.java
index 6fba009cf86..8e75b36057c 100644
--- a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentFinder.java
+++ b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentFinder.java
@@ -20,13 +20,14 @@
package io.druid.storage.hdfs;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.collect.Sets;
+import com.google.common.base.Preconditions;
import com.google.inject.Inject;
+import io.druid.java.util.common.Pair;
+import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.logger.Logger;
import io.druid.segment.loading.DataSegmentFinder;
import io.druid.segment.loading.SegmentLoadingException;
import io.druid.timeline.DataSegment;
-import io.druid.java.util.common.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocatedFileStatus;
@@ -34,14 +35,15 @@
import org.apache.hadoop.fs.RemoteIterator;
import java.io.IOException;
+import java.util.HashMap;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
/**
*/
public class HdfsDataSegmentFinder implements DataSegmentFinder
{
-
private static final Logger log = new Logger(HdfsDataSegmentFinder.class);
private final Configuration config;
@@ -58,7 +60,7 @@ public HdfsDataSegmentFinder(Configuration config, ObjectMapper mapper)
public Set<DataSegment> findSegments(String workingDirPathStr, boolean updateDescriptor)
throws SegmentLoadingException
{
- final Set<DataSegment> segments = Sets.newHashSet();
+ final Map<String, Pair<DataSegment, Long>> timestampedSegments = new HashMap<>();
final Path workingDirPath = new Path(workingDirPathStr);
FileSystem fs;
try {
@@ -80,15 +82,31 @@ public HdfsDataSegmentFinder(Configuration config, ObjectMapper mapper)
final LocatedFileStatus locatedFileStatus = it.next();
final Path path = locatedFileStatus.getPath();
if (path.getName().endsWith("descriptor.json")) {
- final Path indexZip;
+
+ // There are 3 supported path formats:
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum/descriptor.json
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_descriptor.json
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_UUID_descriptor.json
final String descriptorParts[] = path.getName().split("_");
- if (descriptorParts.length == 2
- && descriptorParts[1].equals("descriptor.json")
- && org.apache.commons.lang.StringUtils.isNumeric(descriptorParts[0])) {
- indexZip = new Path(path.getParent(), StringUtils.format("%s_index.zip", descriptorParts[0]));
- } else {
- indexZip = new Path(path.getParent(), "index.zip");
+
+ Path indexZip = new Path(path.getParent(), "index.zip");
+ if (descriptorParts.length > 1) {
+ Preconditions.checkState(descriptorParts.length <= 3 &&
+ org.apache.commons.lang.StringUtils.isNumeric(descriptorParts[0]) &&
+ "descriptor.json".equals(descriptorParts[descriptorParts.length - 1]),
+ "Unexpected descriptor filename format [%s]", path
+ );
+
+ indexZip = new Path(
+ path.getParent(),
+ StringUtils.format(
+ "%s_%sindex.zip",
+ descriptorParts[0],
+ descriptorParts.length == 2 ? "" : descriptorParts[1] + "_"
+ )
+ );
}
+
if (fs.exists(indexZip)) {
final DataSegment dataSegment = mapper.readValue(fs.open(path), DataSegment.class);
log.info("Found segment [%s] located at [%s]", dataSegment.getIdentifier(), indexZip);
@@ -105,7 +123,12 @@ public HdfsDataSegmentFinder(Configuration config, ObjectMapper mapper)
mapper.writeValue(fs.create(path, true), dataSegment);
}
}
- segments.add(dataSegment);
+
+ DataSegmentFinder.putInMapRetainingNewest(
+ timestampedSegments,
+ dataSegment,
+ locatedFileStatus.getModificationTime()
+ );
} else {
throw new SegmentLoadingException(
"index.zip didn't exist at [%s] while descripter.json exists!?",
@@ -119,7 +142,6 @@ public HdfsDataSegmentFinder(Configuration config, ObjectMapper mapper)
throw new SegmentLoadingException(e, "Problems interacting with filesystem[%s].", workingDirPath);
}
- return segments;
+ return timestampedSegments.values().stream().map(x -> x.lhs).collect(Collectors.toSet());
}
-
}
diff --git a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentKiller.java b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentKiller.java
index d910ae51b0a..6cbd1eccd7c 100644
--- a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentKiller.java
+++ b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentKiller.java
@@ -19,8 +19,9 @@
package io.druid.storage.hdfs;
+import com.google.common.base.Preconditions;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.segment.loading.DataSegmentKiller;
import io.druid.segment.loading.SegmentLoadingException;
import io.druid.timeline.DataSegment;
@@ -57,65 +58,53 @@ private static Path getPath(DataSegment segment)
public void kill(DataSegment segment) throws SegmentLoadingException
{
final Path segmentPath = getPath(segment);
- log.info("killing segment[%s] mapped to path[%s]", segment.getIdentifier(), segmentPath);
+ log.info("Killing segment[%s] mapped to path[%s]", segment.getIdentifier(), segmentPath);
try {
- String segmentLocation = segmentPath.getName();
+ String filename = segmentPath.getName();
final FileSystem fs = segmentPath.getFileSystem(config);
- if (!segmentLocation.endsWith(".zip")) {
+ if (!filename.endsWith(".zip")) {
throw new SegmentLoadingException("Unknown file type[%s]", segmentPath);
} else {
if (!fs.exists(segmentPath)) {
- log.warn("Segment Path [%s] does not exist. It appears to have been deleted already.", segmentPath);
+ log.warn("Segment path [%s] does not exist", segmentPath);
return;
}
- String[] zipParts = segmentLocation.split("_");
- // for segments stored as hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_index.zip
- if (zipParts.length == 2
- && zipParts[1].equals("index.zip")
- && StringUtils.isNumeric(zipParts[0])) {
- if (!fs.delete(segmentPath, false)) {
- throw new SegmentLoadingException(
- "Unable to kill segment, failed to delete [%s]",
- segmentPath.toString()
- );
- }
- Path descriptorPath = new Path(
+ // There are 3 supported path formats:
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum/index.zip
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_index.zip
+ // - hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_UUID_index.zip
+ String[] zipParts = filename.split("_");
+
+ Path descriptorPath = new Path(segmentPath.getParent(), "descriptor.json");
+ if (zipParts.length > 1) {
+ Preconditions.checkState(zipParts.length <= 3 &&
+ StringUtils.isNumeric(zipParts[0]) &&
+ "index.zip".equals(zipParts[zipParts.length - 1]),
+ "Unexpected segmentPath format [%s]", segmentPath
+ );
+
+ descriptorPath = new Path(
segmentPath.getParent(),
- io.druid.java.util.common.StringUtils.format("%s_descriptor.json", zipParts[0])
+ io.druid.java.util.common.StringUtils.format(
+ "%s_%sdescriptor.json",
+ zipParts[0],
+ zipParts.length == 2 ? "" : zipParts[1] + "_"
+ )
);
- //delete partitionNumber_descriptor.json
- if (!fs.delete(descriptorPath, false)) {
- throw new SegmentLoadingException(
- "Unable to kill segment, failed to delete [%s]",
- descriptorPath.toString()
- );
- }
- //for segments stored as hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum_index.zip
- // max depth to look is 2, i.e version directory and interval.
- mayBeDeleteParentsUpto(fs, segmentPath, 2);
-
- } else { //for segments stored as hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum/
- // index.zip
- if (!fs.delete(segmentPath, false)) {
- throw new SegmentLoadingException(
- "Unable to kill segment, failed to delete [%s]",
- segmentPath.toString()
- );
- }
- Path descriptorPath = new Path(segmentPath.getParent(), "descriptor.json");
- if (!fs.delete(descriptorPath, false)) {
- throw new SegmentLoadingException(
- "Unable to kill segment, failed to delete [%s]",
- descriptorPath.toString()
- );
- }
- //for segments stored as hdfs://nn1/hdfs_base_directory/data_source_name/interval/version/shardNum/index.zip
- //max depth to look is 3, i.e partition number directory,version directory and interval.
- mayBeDeleteParentsUpto(fs, segmentPath, 3);
}
+
+ if (!fs.delete(segmentPath, false)) {
+ throw new SegmentLoadingException("Unable to kill segment, failed to delete [%s]", segmentPath.toString());
+ }
+
+ if (!fs.delete(descriptorPath, false)) {
+ throw new SegmentLoadingException("Unable to kill segment, failed to delete [%s]", descriptorPath.toString());
+ }
+
+ removeEmptyParentDirectories(fs, segmentPath, zipParts.length > 1 ? 2 : 3);
}
}
catch (IOException e) {
@@ -131,11 +120,11 @@ public void killAll() throws IOException
fs.delete(storageDirectory, true);
}
- private void mayBeDeleteParentsUpto(final FileSystem fs, final Path segmentPath, final int maxDepthTobeDeleted)
+ private void removeEmptyParentDirectories(final FileSystem fs, final Path segmentPath, final int depth)
{
Path path = segmentPath;
try {
- for (int i = 1; i <= maxDepthTobeDeleted; i++) {
+ for (int i = 1; i <= depth; i++) {
path = path.getParent();
if (fs.listStatus(path).length != 0 || !fs.delete(path, false)) {
break;
diff --git a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentPusher.java b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentPusher.java
index 33a85ac2147..61e194bfcc3 100644
--- a/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentPusher.java
+++ b/extensions-core/hdfs-storage/src/main/java/io/druid/storage/hdfs/HdfsDataSegmentPusher.java
@@ -20,6 +20,7 @@
package io.druid.storage.hdfs;
import com.fasterxml.jackson.databind.ObjectMapper;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteSink;
import com.google.common.io.ByteSource;
@@ -57,11 +58,8 @@
private final String fullyQualifiedStorageDirectory;
@Inject
- public HdfsDataSegmentPusher(
- HdfsDataSegmentPusherConfig config,
- Configuration hadoopConfig,
- ObjectMapper jsonMapper
- ) throws IOException
+ public HdfsDataSegmentPusher(HdfsDataSegmentPusherConfig config, Configuration hadoopConfig, ObjectMapper jsonMapper)
+ throws IOException
{
this.config = config;
this.hadoopConfig = hadoopConfig;
@@ -89,9 +87,11 @@ public String getPathForHadoop()
}
@Override
- public DataSegment push(File inDir, DataSegment segment) throws IOException
+ public DataSegment push(final File inDir, final DataSegment segment, final boolean useUniquePath) throws IOException
{
- final String storageDir = this.getStorageDir(segment);
+ // For HDFS, useUniquePath does not affect the directory tree but instead affects the filename, which is of the form
+ // '{partitionNum}_index.zip' without unique paths and '{partitionNum}_{UUID}_index.zip' with unique paths.
+ final String storageDir = this.getStorageDir(segment, false);
log.info(
"Copying segment[%s] to HDFS at location[%s/%s]",
@@ -114,19 +114,25 @@ public DataSegment push(File inDir, DataSegment segment) throws IOException
final long size;
final DataSegment dataSegment;
- try (FSDataOutputStream out = fs.create(tmpIndexFile)) {
- size = CompressionUtils.zip(inDir, out);
+ try {
+ try (FSDataOutputStream out = fs.create(tmpIndexFile)) {
+ size = CompressionUtils.zip(inDir, out);
+ }
+
+ final String uniquePrefix = useUniquePath ? DataSegmentPusher.generateUniquePath() + "_" : "";
final Path outIndexFile = new Path(StringUtils.format(
- "%s/%s/%d_index.zip",
+ "%s/%s/%d_%sindex.zip",
fullyQualifiedStorageDirectory,
storageDir,
- segment.getShardSpec().getPartitionNum()
+ segment.getShardSpec().getPartitionNum(),
+ uniquePrefix
));
final Path outDescriptorFile = new Path(StringUtils.format(
- "%s/%s/%d_descriptor.json",
+ "%s/%s/%d_%sdescriptor.json",
fullyQualifiedStorageDirectory,
storageDir,
- segment.getShardSpec().getPartitionNum()
+ segment.getShardSpec().getPartitionNum(),
+ uniquePrefix
));
dataSegment = segment.withLoadSpec(makeLoadSpec(outIndexFile.toUri()))
@@ -167,13 +173,12 @@ private void copyFilesWithChecks(final FileSystem fs, final Path from, final Pat
if (!HadoopFsWrapper.rename(fs, from, to)) {
if (fs.exists(to)) {
log.info(
- "Unable to rename temp Index file[%s] to final segment path [%s]. "
- + "It is already pushed by a replica task.",
+ "Unable to rename temp file [%s] to segment path [%s], it may have already been pushed by a replica task.",
from,
to
);
} else {
- throw new IOE("Failed to rename temp Index file[%s] and final segment path[%s] is not present.", from, to);
+ throw new IOE("Failed to rename temp file [%s] and final segment path [%s] is not present.", from, to);
}
}
}
@@ -208,8 +213,17 @@ public OutputStream openStream() throws IOException
*/
@Override
- public String getStorageDir(DataSegment segment)
+ public String getStorageDir(DataSegment segment, boolean useUniquePath)
{
+ // This is only called by HdfsDataSegmentPusher.push(), which will always set useUniquePath to false since any
+ // 'uniqueness' will be applied not to the directory but to the filename along with the shard number. This is done
+ // to avoid performance issues due to excessive HDFS directories. Hence useUniquePath is ignored here and we
+ // expect it to be false.
+ Preconditions.checkArgument(
+ !useUniquePath,
+ "useUniquePath must be false for HdfsDataSegmentPusher.getStorageDir()"
+ );
+
return JOINER.join(
segment.getDataSource(),
StringUtils.format(
@@ -224,9 +238,10 @@ public String getStorageDir(DataSegment segment)
@Override
public String makeIndexPathName(DataSegment dataSegment, String indexName)
{
+ // This is only called from Hadoop batch which doesn't require unique segment paths so set useUniquePath=false
return StringUtils.format(
"./%s/%d_%s",
- this.getStorageDir(dataSegment),
+ this.getStorageDir(dataSegment, false),
dataSegment.getShardSpec().getPartitionNum(),
indexName
);
diff --git a/extensions-core/hdfs-storage/src/main/java/org/apache/hadoop/fs/HadoopFsWrapper.java b/extensions-core/hdfs-storage/src/main/java/org/apache/hadoop/fs/HadoopFsWrapper.java
index df00fdb7a0f..913adb0977b 100644
--- a/extensions-core/hdfs-storage/src/main/java/org/apache/hadoop/fs/HadoopFsWrapper.java
+++ b/extensions-core/hdfs-storage/src/main/java/org/apache/hadoop/fs/HadoopFsWrapper.java
@@ -36,14 +36,15 @@
private HadoopFsWrapper() {}
/**
- * Same as FileSystem.rename(from, to, Options.Rename.NONE) . That is,
- * it returns "false" when "to" directory already exists. It is different from FileSystem.rename(from, to)
- * which moves "from" directory inside "to" directory if it already exists.
+ * Same as FileSystem.rename(from, to, Options.Rename). It is different from FileSystem.rename(from, to) which moves
+ * "from" directory inside "to" directory if it already exists.
*
* @param from
* @param to
- * @return
- * @throws IOException
+ *
+ * @return true if operation succeeded, false if destination already exists
+ *
+ * @throws IOException if trying to overwrite a non-empty directory
*/
public static boolean rename(FileSystem fs, Path from, Path to) throws IOException
{
@@ -51,8 +52,8 @@ public static boolean rename(FileSystem fs, Path from, Path to) throws IOExcepti
fs.rename(from, to, Options.Rename.NONE);
return true;
}
- catch (IOException ex) {
- log.warn(ex, "Failed to rename [%s] to [%s].", from, to);
+ catch (FileAlreadyExistsException ex) {
+ log.info(ex, "Destination exists while renaming [%s] to [%s]", from, to);
return false;
}
}
diff --git a/extensions-core/hdfs-storage/src/test/java/io/druid/segment/loading/HdfsDataSegmentFinderTest.java b/extensions-core/hdfs-storage/src/test/java/io/druid/segment/loading/HdfsDataSegmentFinderTest.java
index 62612462252..5e052df1e6d 100644
--- a/extensions-core/hdfs-storage/src/test/java/io/druid/segment/loading/HdfsDataSegmentFinderTest.java
+++ b/extensions-core/hdfs-storage/src/test/java/io/druid/segment/loading/HdfsDataSegmentFinderTest.java
@@ -25,6 +25,7 @@
import com.google.common.collect.ImmutableMap;
import io.druid.java.util.common.IOE;
import io.druid.java.util.common.Intervals;
+import io.druid.java.util.common.StringUtils;
import io.druid.segment.TestHelper;
import io.druid.storage.hdfs.HdfsDataSegmentFinder;
import io.druid.timeline.DataSegment;
@@ -278,6 +279,30 @@ public void testFindSegmentsFail() throws Exception
hdfsDataSegmentFinder.findSegments(dataSourceDir.toString(), false);
}
+ @Test
+ public void testPreferNewestSegment() throws Exception
+ {
+ dataSourceDir = new Path(new Path(uriBase), "/usr/replicaDataSource");
+ descriptor1 = new Path(dataSourceDir, StringUtils.format("interval1/v1/%d_%s_%s", 0, "older", DESCRIPTOR_JSON));
+ descriptor2 = new Path(dataSourceDir, StringUtils.format("interval1/v1/%d_%s_%s", 0, "newer", DESCRIPTOR_JSON));
+ indexZip1 = new Path(descriptor1.getParent(), StringUtils.format("%d_%s_%s", 0, "older", INDEX_ZIP));
+ indexZip2 = new Path(descriptor2.getParent(), StringUtils.format("%d_%s_%s", 0, "newer", INDEX_ZIP));
+
+ mapper.writeValue(fs.create(descriptor1), SEGMENT_1);
+ mapper.writeValue(fs.create(descriptor2), SEGMENT_1);
+
+ create(indexZip1);
+ Thread.sleep(1000);
+ create(indexZip2);
+
+ final Set<DataSegment> segments = new HdfsDataSegmentFinder(conf, mapper).findSegments(
+ dataSourceDir.toString(), false
+ );
+
+ Assert.assertEquals(1, segments.size());
+ Assert.assertEquals(indexZip2.toUri().getPath(), segments.iterator().next().getLoadSpec().get("path"));
+ }
+
private String getDescriptorPath(DataSegment segment)
{
final Path indexzip = new Path(String.valueOf(segment.getLoadSpec().get("path")));
diff --git a/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentKillerTest.java b/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentKillerTest.java
index bdf499dcd90..dba43507a69 100644
--- a/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentKillerTest.java
+++ b/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentKillerTest.java
@@ -26,13 +26,13 @@
import io.druid.timeline.DataSegment;
import io.druid.timeline.partition.NoneShardSpec;
import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.junit.Assert;
import org.junit.Test;
import java.io.IOException;
+import java.util.UUID;
/**
*/
@@ -129,7 +129,10 @@ public String getStorageDirectory()
Path interval1Dir = new Path(dataSourceDir, "intervalNew");
Path version11Dir = new Path(interval1Dir, "v1");
- makePartitionDirWithIndexWitNewFormat(fs, version11Dir, 3);
+ Assert.assertTrue(fs.mkdirs(version11Dir));
+ fs.createNewFile(new Path(version11Dir, StringUtils.format("%s_index.zip", 3)));
+ fs.createNewFile(new Path(version11Dir, StringUtils.format("%s_descriptor.json", 3)));
+
killer.kill(getSegmentWithPath(new Path(version11Dir, "3_index.zip").toString()));
Assert.assertFalse(fs.exists(version11Dir));
@@ -141,7 +144,7 @@ public String getStorageDirectory()
}
@Test
- public void testKillNonExistingSegment() throws Exception
+ public void testKillForSegmentWithUniquePath() throws Exception
{
Configuration config = new Configuration();
HdfsDataSegmentKiller killer = new HdfsDataSegmentKiller(
@@ -155,28 +158,51 @@ public String getStorageDirectory()
}
}
);
- killer.kill(getSegmentWithPath(new Path("/xxx/", "index.zip").toString()));
+
+ FileSystem fs = FileSystem.get(config);
+ Path dataSourceDir = new Path("/tmp/dataSourceNew");
+
+ Path interval1Dir = new Path(dataSourceDir, "intervalNew");
+ Path version11Dir = new Path(interval1Dir, "v1");
+ String uuid = UUID.randomUUID().toString().substring(0, 5);
+
+ Assert.assertTrue(fs.mkdirs(version11Dir));
+ fs.createNewFile(new Path(version11Dir, StringUtils.format("%s_%s_index.zip", 3, uuid)));
+ fs.createNewFile(new Path(version11Dir, StringUtils.format("%s_%s_descriptor.json", 3, uuid)));
+
+ killer.kill(getSegmentWithPath(new Path(version11Dir, StringUtils.format("%s_%s_index.zip", 3, uuid)).toString()));
+
+ Assert.assertFalse(fs.exists(version11Dir));
+ Assert.assertFalse(fs.exists(interval1Dir));
+ Assert.assertTrue(fs.exists(dataSourceDir));
+ Assert.assertTrue(fs.exists(new Path("/tmp")));
+ Assert.assertTrue(fs.exists(dataSourceDir));
+ Assert.assertTrue(fs.delete(dataSourceDir, false));
}
- private void makePartitionDirWithIndex(FileSystem fs, Path path) throws IOException
+ @Test
+ public void testKillNonExistingSegment() throws Exception
{
- Assert.assertTrue(fs.mkdirs(path));
- try (FSDataOutputStream os = fs.create(new Path(path, "index.zip")); FSDataOutputStream oos = fs.create(new Path(
- path,
- "descriptor.json"
- ))) {
- }
+ Configuration config = new Configuration();
+ HdfsDataSegmentKiller killer = new HdfsDataSegmentKiller(
+ config,
+ new HdfsDataSegmentPusherConfig()
+ {
+ @Override
+ public String getStorageDirectory()
+ {
+ return "/tmp";
+ }
+ }
+ );
+ killer.kill(getSegmentWithPath(new Path("/xxx/", "index.zip").toString()));
}
- private void makePartitionDirWithIndexWitNewFormat(FileSystem fs, Path path, Integer partitionNumber)
- throws IOException
+ private void makePartitionDirWithIndex(FileSystem fs, Path path) throws IOException
{
Assert.assertTrue(fs.mkdirs(path));
- try (FSDataOutputStream os = fs.create(new Path(
- path,
- StringUtils.format("%s_index.zip", partitionNumber)
- )); FSDataOutputStream oos = fs.create(new Path(path, StringUtils.format("%s_descriptor.json", partitionNumber)))) {
- }
+ fs.createNewFile(new Path(path, "index.zip"));
+ fs.createNewFile(new Path(path, "descriptor.json"));
}
private DataSegment getSegmentWithPath(String path)
diff --git a/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentPusherTest.java b/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentPusherTest.java
index 95dd85bf2b9..9bb25f90707 100644
--- a/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentPusherTest.java
+++ b/extensions-core/hdfs-storage/src/test/java/io/druid/storage/hdfs/HdfsDataSegmentPusherTest.java
@@ -127,7 +127,8 @@ public void testPushWithMultipleSegments() throws Exception
testUsingSchemeForMultipleSegments("file", 3);
}
- private void testUsingScheme(final String scheme) throws Exception
+ @Test
+ public void testUsingUniqueFilePath() throws Exception
{
Configuration conf = new Configuration(true);
@@ -142,11 +143,7 @@ private void testUsingScheme(final String scheme) throws Exception
HdfsDataSegmentPusherConfig config = new HdfsDataSegmentPusherConfig();
final File storageDirectory = tempFolder.newFolder();
- config.setStorageDirectory(
- scheme != null
- ? StringUtils.format("%s://%s", scheme, storageDirectory.getAbsolutePath())
- : storageDirectory.getAbsolutePath()
- );
+ config.setStorageDirectory(StringUtils.format("file://%s", storageDirectory.getAbsolutePath()));
HdfsDataSegmentPusher pusher = new HdfsDataSegmentPusher(config, conf, new DefaultObjectMapper());
DataSegment segmentToPush = new DataSegment(
@@ -161,51 +158,13 @@ private void testUsingScheme(final String scheme) throws Exception
size
);
- DataSegment segment = pusher.push(segmentDir, segmentToPush);
-
+ DataSegment segment = pusher.push(segmentDir, segmentToPush, true);
- String indexUri = StringUtils.format(
- "%s/%s/%d_index.zip",
- FileSystem.newInstance(conf).makeQualified(new Path(config.getStorageDirectory())).toUri().toString(),
- pusher.getStorageDir(segmentToPush),
- segmentToPush.getShardSpec().getPartitionNum()
+ String matcher = ".*/foo/20150101T000000\\.000Z_20160101T000000\\.000Z/0/0_[A-Za-z0-9-]{36}_index\\.zip";
+ Assert.assertTrue(
+ segment.getLoadSpec().get("path").toString(),
+ segment.getLoadSpec().get("path").toString().matches(matcher)
);
-
- Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
- Assert.assertEquals(segmentToPush, segment);
- Assert.assertEquals(ImmutableMap.of(
- "type",
- "hdfs",
- "path",
- indexUri
- ), segment.getLoadSpec());
- // rename directory after push
- final String segmentPath = pusher.getStorageDir(segment);
-
- File indexFile = new File(StringUtils.format(
- "%s/%s/%d_index.zip",
- storageDirectory,
- segmentPath,
- segment.getShardSpec().getPartitionNum()
- ));
- Assert.assertTrue(indexFile.exists());
- File descriptorFile = new File(StringUtils.format(
- "%s/%s/%d_descriptor.json",
- storageDirectory,
- segmentPath,
- segment.getShardSpec().getPartitionNum()
- ));
- Assert.assertTrue(descriptorFile.exists());
-
- // push twice will fail and temp dir cleaned
- File outDir = new File(StringUtils.format("%s/%s", config.getStorageDirectory(), segmentPath));
- outDir.setReadOnly();
- try {
- pusher.push(segmentDir, segmentToPush);
- }
- catch (IOException e) {
- Assert.fail("should not throw exception");
- }
}
private void testUsingSchemeForMultipleSegments(final String scheme, final int numberOfSegments) throws Exception
@@ -246,12 +205,12 @@ private void testUsingSchemeForMultipleSegments(final String scheme, final int n
}
for (int i = 0; i < numberOfSegments; i++) {
- final DataSegment pushedSegment = pusher.push(segmentDir, segments[i]);
+ final DataSegment pushedSegment = pusher.push(segmentDir, segments[i], false);
String indexUri = StringUtils.format(
"%s/%s/%d_index.zip",
FileSystem.newInstance(conf).makeQualified(new Path(config.getStorageDirectory())).toUri().toString(),
- pusher.getStorageDir(segments[i]),
+ pusher.getStorageDir(segments[i], false),
segments[i].getShardSpec().getPartitionNum()
);
@@ -264,7 +223,7 @@ private void testUsingSchemeForMultipleSegments(final String scheme, final int n
indexUri
), pushedSegment.getLoadSpec());
// rename directory after push
- String segmentPath = pusher.getStorageDir(pushedSegment);
+ String segmentPath = pusher.getStorageDir(pushedSegment, false);
File indexFile = new File(StringUtils.format(
"%s/%s/%d_index.zip",
@@ -293,7 +252,7 @@ private void testUsingSchemeForMultipleSegments(final String scheme, final int n
indexUri
), fromDescriptorFileDataSegment.getLoadSpec());
// rename directory after push
- segmentPath = pusher.getStorageDir(fromDescriptorFileDataSegment);
+ segmentPath = pusher.getStorageDir(fromDescriptorFileDataSegment, false);
indexFile = new File(StringUtils.format(
"%s/%s/%d_index.zip",
@@ -308,7 +267,7 @@ private void testUsingSchemeForMultipleSegments(final String scheme, final int n
File outDir = new File(StringUtils.format("%s/%s", config.getStorageDirectory(), segmentPath));
outDir.setReadOnly();
try {
- pusher.push(segmentDir, segments[i]);
+ pusher.push(segmentDir, segments[i], false);
}
catch (IOException e) {
Assert.fail("should not throw exception");
@@ -316,6 +275,87 @@ private void testUsingSchemeForMultipleSegments(final String scheme, final int n
}
}
+ private void testUsingScheme(final String scheme) throws Exception
+ {
+ Configuration conf = new Configuration(true);
+
+ // Create a mock segment on disk
+ File segmentDir = tempFolder.newFolder();
+ File tmp = new File(segmentDir, "version.bin");
+
+ final byte[] data = new byte[]{0x0, 0x0, 0x0, 0x1};
+ Files.write(data, tmp);
+ final long size = data.length;
+
+ HdfsDataSegmentPusherConfig config = new HdfsDataSegmentPusherConfig();
+ final File storageDirectory = tempFolder.newFolder();
+
+ config.setStorageDirectory(
+ scheme != null
+ ? StringUtils.format("%s://%s", scheme, storageDirectory.getAbsolutePath())
+ : storageDirectory.getAbsolutePath()
+ );
+ HdfsDataSegmentPusher pusher = new HdfsDataSegmentPusher(config, conf, new DefaultObjectMapper());
+
+ DataSegment segmentToPush = new DataSegment(
+ "foo",
+ Intervals.of("2015/2016"),
+ "0",
+ Maps.<String, Object>newHashMap(),
+ Lists.<String>newArrayList(),
+ Lists.<String>newArrayList(),
+ NoneShardSpec.instance(),
+ 0,
+ size
+ );
+
+ DataSegment segment = pusher.push(segmentDir, segmentToPush, false);
+
+
+ String indexUri = StringUtils.format(
+ "%s/%s/%d_index.zip",
+ FileSystem.newInstance(conf).makeQualified(new Path(config.getStorageDirectory())).toUri().toString(),
+ pusher.getStorageDir(segmentToPush, false),
+ segmentToPush.getShardSpec().getPartitionNum()
+ );
+
+ Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
+ Assert.assertEquals(segmentToPush, segment);
+ Assert.assertEquals(ImmutableMap.of(
+ "type",
+ "hdfs",
+ "path",
+ indexUri
+ ), segment.getLoadSpec());
+ // rename directory after push
+ final String segmentPath = pusher.getStorageDir(segment, false);
+
+ File indexFile = new File(StringUtils.format(
+ "%s/%s/%d_index.zip",
+ storageDirectory,
+ segmentPath,
+ segment.getShardSpec().getPartitionNum()
+ ));
+ Assert.assertTrue(indexFile.exists());
+ File descriptorFile = new File(StringUtils.format(
+ "%s/%s/%d_descriptor.json",
+ storageDirectory,
+ segmentPath,
+ segment.getShardSpec().getPartitionNum()
+ ));
+ Assert.assertTrue(descriptorFile.exists());
+
+ // push twice will fail and temp dir cleaned
+ File outDir = new File(StringUtils.format("%s/%s", config.getStorageDirectory(), segmentPath));
+ outDir.setReadOnly();
+ try {
+ pusher.push(segmentDir, segmentToPush, false);
+ }
+ catch (IOException e) {
+ Assert.fail("should not throw exception");
+ }
+ }
+
public static class TestObjectMapper extends ObjectMapper
{
public TestObjectMapper()
@@ -371,7 +411,7 @@ public void shouldNotHaveColonsInHdfsStorageDir() throws Exception
1
);
- String storageDir = hdfsDataSegmentPusher.getStorageDir(segment);
+ String storageDir = hdfsDataSegmentPusher.getStorageDir(segment, false);
Assert.assertEquals("something/20111001T000000.000Z_20111002T000000.000Z/brand_new_version", storageDir);
}
diff --git a/extensions-core/histogram/pom.xml b/extensions-core/histogram/pom.xml
index 5f0a3765d64..4a372f2e5ba 100644
--- a/extensions-core/histogram/pom.xml
+++ b/extensions-core/histogram/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/histogram/src/main/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregator.java b/extensions-core/histogram/src/main/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregator.java
index 6711c36f4b1..b9c8d3d3d46 100644
--- a/extensions-core/histogram/src/main/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregator.java
+++ b/extensions-core/histogram/src/main/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregator.java
@@ -93,15 +93,27 @@ public Aggregation toDruidAggregation(
project,
aggregateCall.getArgList().get(1)
);
- final float probability = ((Number) RexLiteral.value(probabilityArg)).floatValue();
+ if (!probabilityArg.isA(SqlKind.LITERAL)) {
+ // Probability must be a literal in order to plan.
+ return null;
+ }
+
+ final float probability = ((Number) RexLiteral.value(probabilityArg)).floatValue();
final int resolution;
+
if (aggregateCall.getArgList().size() >= 3) {
final RexNode resolutionArg = Expressions.fromFieldAccess(
rowSignature,
project,
aggregateCall.getArgList().get(2)
);
+
+ if (!resolutionArg.isA(SqlKind.LITERAL)) {
+ // Resolution must be a literal in order to plan.
+ return null;
+ }
+
resolution = ((Number) RexLiteral.value(resolutionArg)).intValue();
} else {
resolution = ApproximateHistogram.DEFAULT_HISTOGRAM_SIZE;
diff --git a/extensions-core/histogram/src/test/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregatorTest.java b/extensions-core/histogram/src/test/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregatorTest.java
index 45197c2c7e0..5582ceab291 100644
--- a/extensions-core/histogram/src/test/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregatorTest.java
+++ b/extensions-core/histogram/src/test/java/io/druid/query/aggregation/histogram/sql/QuantileSqlAggregatorTest.java
@@ -27,6 +27,7 @@
import io.druid.java.util.common.guava.Sequences;
import io.druid.segment.writeout.OffHeapMemorySegmentWriteOutMediumFactory;
import io.druid.query.Druids;
+import io.druid.query.QueryDataSource;
import io.druid.query.aggregation.CountAggregatorFactory;
import io.druid.query.aggregation.DoubleSumAggregatorFactory;
import io.druid.query.aggregation.FilteredAggregatorFactory;
@@ -34,9 +35,13 @@
import io.druid.query.aggregation.histogram.ApproximateHistogramDruidModule;
import io.druid.query.aggregation.histogram.ApproximateHistogramFoldingAggregatorFactory;
import io.druid.query.aggregation.histogram.QuantilePostAggregator;
+import io.druid.query.aggregation.post.ArithmeticPostAggregator;
+import io.druid.query.aggregation.post.FieldAccessPostAggregator;
+import io.druid.query.dimension.DefaultDimensionSpec;
import io.druid.query.expression.TestExprMacroTable;
import io.druid.query.filter.NotDimFilter;
import io.druid.query.filter.SelectorDimFilter;
+import io.druid.query.groupby.GroupByQuery;
import io.druid.query.spec.MultipleIntervalSegmentSpec;
import io.druid.segment.IndexBuilder;
import io.druid.segment.QueryableIndex;
@@ -47,13 +52,13 @@
import io.druid.server.security.AuthConfig;
import io.druid.server.security.AuthTestUtils;
import io.druid.sql.calcite.filtration.Filtration;
-import io.druid.sql.calcite.planner.Calcites;
import io.druid.sql.calcite.planner.DruidOperatorTable;
import io.druid.sql.calcite.planner.DruidPlanner;
import io.druid.sql.calcite.planner.PlannerConfig;
import io.druid.sql.calcite.planner.PlannerFactory;
import io.druid.sql.calcite.planner.PlannerResult;
import io.druid.sql.calcite.schema.DruidSchema;
+import io.druid.sql.calcite.util.CalciteTestBase;
import io.druid.sql.calcite.util.CalciteTests;
import io.druid.sql.calcite.util.QueryLogHook;
import io.druid.sql.calcite.util.SpecificSegmentsQuerySegmentWalker;
@@ -69,7 +74,7 @@
import java.util.ArrayList;
import java.util.List;
-public class QuantileSqlAggregatorTest
+public class QuantileSqlAggregatorTest extends CalciteTestBase
{
private static final String DATA_SOURCE = "foo";
@@ -85,8 +90,6 @@
@Before
public void setUp() throws Exception
{
- Calcites.setSystemProperties();
-
// Note: this is needed in order to properly register the serde for Histogram.
new ApproximateHistogramDruidModule().configure(null);
@@ -293,4 +296,69 @@ public void testQuantileOnComplexColumn() throws Exception
);
}
}
+
+ @Test
+ public void testQuantileOnInnerQuery() throws Exception
+ {
+ try (final DruidPlanner planner = plannerFactory.createPlanner(null)) {
+ final String sql = "SELECT AVG(x), APPROX_QUANTILE(x, 0.98)\n"
+ + "FROM (SELECT dim2, SUM(m1) AS x FROM foo GROUP BY dim2)";
+
+ final PlannerResult plannerResult = planner.plan(sql);
+
+ // Verify results
+ final List<Object[]> results = Sequences.toList(plannerResult.run(), new ArrayList<Object[]>());
+ final List<Object[]> expectedResults = ImmutableList.of(
+ new Object[]{7.0, 8.26386833190918}
+ );
+ Assert.assertEquals(expectedResults.size(), results.size());
+ for (int i = 0; i < expectedResults.size(); i++) {
+ Assert.assertArrayEquals(expectedResults.get(i), results.get(i));
+ }
+
+ // Verify query
+ Assert.assertEquals(
+ GroupByQuery.builder()
+ .setDataSource(
+ new QueryDataSource(
+ GroupByQuery.builder()
+ .setDataSource(CalciteTests.DATASOURCE1)
+ .setInterval(new MultipleIntervalSegmentSpec(ImmutableList.of(Filtration.eternity())))
+ .setGranularity(Granularities.ALL)
+ .setDimensions(ImmutableList.of(new DefaultDimensionSpec("dim2", "d0")))
+ .setAggregatorSpecs(
+ ImmutableList.of(
+ new DoubleSumAggregatorFactory("a0", "m1")
+ )
+ )
+ .setContext(ImmutableMap.of())
+ .build()
+ )
+ )
+ .setInterval(new MultipleIntervalSegmentSpec(ImmutableList.of(Filtration.eternity())))
+ .setGranularity(Granularities.ALL)
+ .setAggregatorSpecs(ImmutableList.of(
+ new DoubleSumAggregatorFactory("_a0:sum", "a0"),
+ new CountAggregatorFactory("_a0:count"),
+ new ApproximateHistogramAggregatorFactory("_a1:agg", "a0", null, null, null, null)
+ ))
+ .setPostAggregatorSpecs(
+ ImmutableList.of(
+ new ArithmeticPostAggregator(
+ "_a0",
+ "quotient",
+ ImmutableList.of(
+ new FieldAccessPostAggregator(null, "_a0:sum"),
+ new FieldAccessPostAggregator(null, "_a0:count")
+ )
+ ),
+ new QuantilePostAggregator("_a1", "_a1:agg", 0.98f)
+ )
+ )
+ .setContext(ImmutableMap.of())
+ .build(),
+ Iterables.getOnlyElement(queryLogHook.getRecordedQueries())
+ );
+ }
+ }
}
diff --git a/extensions-core/kafka-eight/pom.xml b/extensions-core/kafka-eight/pom.xml
index 2b94032c587..7da379db9a0 100644
--- a/extensions-core/kafka-eight/pom.xml
+++ b/extensions-core/kafka-eight/pom.xml
@@ -27,7 +27,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/kafka-extraction-namespace/pom.xml b/extensions-core/kafka-extraction-namespace/pom.xml
index 0edc753e9bc..51ae7f11787 100644
--- a/extensions-core/kafka-extraction-namespace/pom.xml
+++ b/extensions-core/kafka-extraction-namespace/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
<artifactId>druid-kafka-extraction-namespace</artifactId>
@@ -29,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/kafka-indexing-service/pom.xml b/extensions-core/kafka-indexing-service/pom.xml
index 007336e282f..a0d0886245a 100644
--- a/extensions-core/kafka-indexing-service/pom.xml
+++ b/extensions-core/kafka-indexing-service/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIOConfig.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIOConfig.java
index d9a7fb20ee8..4878da24df0 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIOConfig.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIOConfig.java
@@ -26,43 +26,44 @@
import io.druid.segment.indexing.IOConfig;
import org.joda.time.DateTime;
+import javax.annotation.Nullable;
import java.util.Map;
public class KafkaIOConfig implements IOConfig
{
private static final boolean DEFAULT_USE_TRANSACTION = true;
- private static final boolean DEFAULT_PAUSE_AFTER_READ = false;
private static final boolean DEFAULT_SKIP_OFFSET_GAPS = false;
+ @Nullable
+ private final Integer taskGroupId;
private final String baseSequenceName;
private final KafkaPartitions startPartitions;
private final KafkaPartitions endPartitions;
private final Map<String, String> consumerProperties;
private final boolean useTransaction;
- private final boolean pauseAfterRead;
private final Optional<DateTime> minimumMessageTime;
private final Optional<DateTime> maximumMessageTime;
private final boolean skipOffsetGaps;
@JsonCreator
public KafkaIOConfig(
+ @JsonProperty("taskGroupId") @Nullable Integer taskGroupId, // can be null for backward compabitility
@JsonProperty("baseSequenceName") String baseSequenceName,
@JsonProperty("startPartitions") KafkaPartitions startPartitions,
@JsonProperty("endPartitions") KafkaPartitions endPartitions,
@JsonProperty("consumerProperties") Map<String, String> consumerProperties,
@JsonProperty("useTransaction") Boolean useTransaction,
- @JsonProperty("pauseAfterRead") Boolean pauseAfterRead,
@JsonProperty("minimumMessageTime") DateTime minimumMessageTime,
@JsonProperty("maximumMessageTime") DateTime maximumMessageTime,
@JsonProperty("skipOffsetGaps") Boolean skipOffsetGaps
)
{
+ this.taskGroupId = taskGroupId;
this.baseSequenceName = Preconditions.checkNotNull(baseSequenceName, "baseSequenceName");
this.startPartitions = Preconditions.checkNotNull(startPartitions, "startPartitions");
this.endPartitions = Preconditions.checkNotNull(endPartitions, "endPartitions");
this.consumerProperties = Preconditions.checkNotNull(consumerProperties, "consumerProperties");
this.useTransaction = useTransaction != null ? useTransaction : DEFAULT_USE_TRANSACTION;
- this.pauseAfterRead = pauseAfterRead != null ? pauseAfterRead : DEFAULT_PAUSE_AFTER_READ;
this.minimumMessageTime = Optional.fromNullable(minimumMessageTime);
this.maximumMessageTime = Optional.fromNullable(maximumMessageTime);
this.skipOffsetGaps = skipOffsetGaps != null ? skipOffsetGaps : DEFAULT_SKIP_OFFSET_GAPS;
@@ -87,6 +88,13 @@ public KafkaIOConfig(
}
}
+ @Nullable
+ @JsonProperty
+ public Integer getTaskGroupId()
+ {
+ return taskGroupId;
+ }
+
@JsonProperty
public String getBaseSequenceName()
{
@@ -117,12 +125,6 @@ public boolean isUseTransaction()
return useTransaction;
}
- @JsonProperty
- public boolean isPauseAfterRead()
- {
- return pauseAfterRead;
- }
-
@JsonProperty
public Optional<DateTime> getMaximumMessageTime()
{
@@ -145,12 +147,12 @@ public boolean isSkipOffsetGaps()
public String toString()
{
return "KafkaIOConfig{" +
- "baseSequenceName='" + baseSequenceName + '\'' +
+ "taskGroupId=" + taskGroupId +
+ ", baseSequenceName='" + baseSequenceName + '\'' +
", startPartitions=" + startPartitions +
", endPartitions=" + endPartitions +
", consumerProperties=" + consumerProperties +
", useTransaction=" + useTransaction +
- ", pauseAfterRead=" + pauseAfterRead +
", minimumMessageTime=" + minimumMessageTime +
", maximumMessageTime=" + maximumMessageTime +
", skipOffsetGaps=" + skipOffsetGaps +
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTask.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTask.java
index d4fee282bde..5f039c0336b 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTask.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTask.java
@@ -33,7 +33,6 @@
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
@@ -42,9 +41,7 @@
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.ListeningExecutorService;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.metamx.emitter.EmittingLogger;
+import com.google.common.util.concurrent.SettableFuture;
import io.druid.data.input.Committer;
import io.druid.data.input.InputRow;
import io.druid.data.input.impl.InputRowParser;
@@ -62,14 +59,16 @@
import io.druid.indexing.common.task.AbstractTask;
import io.druid.indexing.common.task.RealtimeIndexTask;
import io.druid.indexing.common.task.TaskResource;
+import io.druid.indexing.common.task.Tasks;
import io.druid.indexing.kafka.supervisor.KafkaSupervisor;
import io.druid.java.util.common.DateTimes;
import io.druid.java.util.common.ISE;
+import io.druid.java.util.common.Intervals;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.collect.Utils;
-import io.druid.java.util.common.concurrent.Execs;
import io.druid.java.util.common.guava.Sequence;
import io.druid.java.util.common.parsers.ParseException;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.query.DruidMetrics;
import io.druid.query.NoopQueryRunner;
import io.druid.query.Query;
@@ -81,11 +80,11 @@
import io.druid.segment.realtime.FireDepartmentMetrics;
import io.druid.segment.realtime.RealtimeMetricsMonitor;
import io.druid.segment.realtime.appenderator.Appenderator;
-import io.druid.segment.realtime.appenderator.AppenderatorDriver;
import io.druid.segment.realtime.appenderator.AppenderatorDriverAddResult;
import io.druid.segment.realtime.appenderator.Appenderators;
import io.druid.segment.realtime.appenderator.SegmentIdentifier;
import io.druid.segment.realtime.appenderator.SegmentsAndMetadata;
+import io.druid.segment.realtime.appenderator.StreamAppenderatorDriver;
import io.druid.segment.realtime.appenderator.TransactionalSegmentPublisher;
import io.druid.segment.realtime.firehose.ChatHandler;
import io.druid.segment.realtime.firehose.ChatHandlerProvider;
@@ -125,24 +124,21 @@
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
+import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.TreeMap;
-import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
-import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
-import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
@@ -178,7 +174,7 @@
private final AuthorizerMapper authorizerMapper;
private final Optional<ChatHandlerProvider> chatHandlerProvider;
- private final Map<Integer, Long> endOffsets = new ConcurrentHashMap<>();
+ private final Map<Integer, Long> endOffsets;
private final Map<Integer, Long> nextOffsets = new ConcurrentHashMap<>();
private final Map<Integer, Long> maxEndOffsets = new HashMap<>();
private final Map<Integer, Long> lastPersistedOffsets = new ConcurrentHashMap<>();
@@ -186,12 +182,11 @@
private TaskToolbox toolbox;
private volatile Appenderator appenderator = null;
- private volatile AppenderatorDriver driver = null;
+ private volatile StreamAppenderatorDriver driver = null;
private volatile FireDepartmentMetrics fireDepartmentMetrics = null;
private volatile DateTime startTime;
private volatile Status status = Status.NOT_STARTED; // this is only ever set by the task runner thread (runThread)
private volatile Thread runThread = null;
- private volatile File sequencesPersistFile = null;
private final AtomicBoolean stopRequested = new AtomicBoolean(false);
private final AtomicBoolean publishOnStop = new AtomicBoolean(false);
@@ -231,20 +226,17 @@
private final Object statusLock = new Object();
private volatile boolean pauseRequested = false;
- private volatile long pauseMillis = 0;
// This value can be tuned in some tests
private long pollRetryMs = 30000;
private final Set<String> publishingSequences = Sets.newConcurrentHashSet();
- private final BlockingQueue<SequenceMetadata> publishQueue = new LinkedBlockingQueue<>();
- private final List<ListenableFuture<SegmentsAndMetadata>> handOffWaitList = new CopyOnWriteArrayList<>(); // to prevent concurrency visibility issue
- private final CountDownLatch waitForPublishes = new CountDownLatch(1);
- private final AtomicReference<Throwable> throwableAtomicReference = new AtomicReference<>();
+ private final List<ListenableFuture<SegmentsAndMetadata>> publishWaitList = new LinkedList<>();
+ private final List<ListenableFuture<SegmentsAndMetadata>> handOffWaitList = new LinkedList<>();
private final String topic;
private volatile CopyOnWriteArrayList<SequenceMetadata> sequences;
- private ListeningExecutorService publishExecService;
+ private volatile Throwable backgroundThreadException;
private final boolean useLegacy;
@JsonCreator
@@ -273,7 +265,7 @@ public KafkaIndexTask(
this.ioConfig = Preconditions.checkNotNull(ioConfig, "ioConfig");
this.chatHandlerProvider = Optional.fromNullable(chatHandlerProvider);
this.authorizerMapper = authorizerMapper;
- this.endOffsets.putAll(ioConfig.getEndPartitions().getPartitionOffsetMap());
+ this.endOffsets = new ConcurrentHashMap<>(ioConfig.getEndPartitions().getPartitionOffsetMap());
this.maxEndOffsets.putAll(endOffsets.entrySet()
.stream()
.collect(Collectors.toMap(
@@ -306,6 +298,12 @@ private static String makeTaskId(String dataSource, int randomBits)
return Joiner.on("_").join(TYPE, dataSource, suffix);
}
+ @Override
+ public int getPriority()
+ {
+ return getContextValue(Tasks.PRIORITY_KEY, Tasks.DEFAULT_REALTIME_TASK_PRIORITY);
+ }
+
@Override
public String getType()
{
@@ -336,75 +334,6 @@ public KafkaIOConfig getIOConfig()
return ioConfig;
}
- private void createAndStartPublishExecutor()
- {
- publishExecService = MoreExecutors.listeningDecorator(Execs.singleThreaded("publish-driver"));
- publishExecService.submit(
- (Runnable) () -> {
- while (true) {
- try {
- final SequenceMetadata sequenceMetadata = publishQueue.take();
-
- Preconditions.checkNotNull(driver);
-
- if (sequenceMetadata.isSentinel()) {
- waitForPublishes.countDown();
- break;
- }
-
- log.info("Publishing segments for sequence [%s]", sequenceMetadata);
-
- final SegmentsAndMetadata result = driver.publish(
- sequenceMetadata.getPublisher(toolbox, ioConfig.isUseTransaction()),
- sequenceMetadata.getCommitterSupplier(topic, lastPersistedOffsets).get(),
- ImmutableList.of(sequenceMetadata.getSequenceName())
- ).get();
-
- if (result == null) {
- throw new ISE(
- "Transaction failure publishing segments for sequence [%s]",
- sequenceMetadata
- );
- } else {
- log.info(
- "Published segments[%s] with metadata[%s].",
- Joiner.on(", ").join(
- result.getSegments().stream().map(DataSegment::getIdentifier).collect(Collectors.toList())
- ),
- result.getCommitMetadata()
- );
- }
-
- sequences.remove(sequenceMetadata);
- publishingSequences.remove(sequenceMetadata.getSequenceName());
- try {
- persistSequences();
- }
- catch (IOException e) {
- log.error(e, "Unable to persist state, dying");
- Throwables.propagate(e);
- }
-
- final ListenableFuture<SegmentsAndMetadata> handOffFuture = driver.registerHandoff(result);
- handOffWaitList.add(handOffFuture);
- }
- catch (Throwable t) {
- if ((t instanceof InterruptedException || (t instanceof RejectedExecutionException
- && t.getCause() instanceof InterruptedException))) {
- log.warn("Stopping publish thread as we are interrupted, probably we are shutting down");
- } else {
- log.makeAlert(t, "Error in publish thread, dying").emit();
- throwableAtomicReference.set(t);
- }
- Futures.allAsList(handOffWaitList).cancel(true);
- waitForPublishes.countDown();
- break;
- }
- }
- }
- );
- }
-
@Override
public TaskStatus run(final TaskToolbox toolbox) throws Exception
{
@@ -419,45 +348,40 @@ public TaskStatus run(final TaskToolbox toolbox) throws Exception
status = Status.STARTING;
this.toolbox = toolbox;
- if (getContext() != null && getContext().get("checkpoints") != null) {
- log.info("Got checkpoints [%s]", (String) getContext().get("checkpoints"));
- final TreeMap<Integer, Map<Integer, Long>> checkpoints = toolbox.getObjectMapper().readValue(
- (String) getContext().get("checkpoints"), new TypeReference<TreeMap<Integer, Map<Integer, Long>>>()
- {
- });
-
- Iterator<Map.Entry<Integer, Map<Integer, Long>>> sequenceOffsets = checkpoints.entrySet().iterator();
- Map.Entry<Integer, Map<Integer, Long>> previous = sequenceOffsets.next();
- while (sequenceOffsets.hasNext()) {
- Map.Entry<Integer, Map<Integer, Long>> current = sequenceOffsets.next();
+ if (!restoreSequences()) {
+ final TreeMap<Integer, Map<Integer, Long>> checkpoints = getCheckPointsFromContext(toolbox, this);
+ if (checkpoints != null) {
+ Iterator<Map.Entry<Integer, Map<Integer, Long>>> sequenceOffsets = checkpoints.entrySet().iterator();
+ Map.Entry<Integer, Map<Integer, Long>> previous = sequenceOffsets.next();
+ while (sequenceOffsets.hasNext()) {
+ Map.Entry<Integer, Map<Integer, Long>> current = sequenceOffsets.next();
+ sequences.add(new SequenceMetadata(
+ previous.getKey(),
+ StringUtils.format("%s_%s", ioConfig.getBaseSequenceName(), previous.getKey()),
+ previous.getValue(),
+ current.getValue(),
+ true
+ ));
+ previous = current;
+ }
sequences.add(new SequenceMetadata(
previous.getKey(),
StringUtils.format("%s_%s", ioConfig.getBaseSequenceName(), previous.getKey()),
previous.getValue(),
- current.getValue(),
- true
+ maxEndOffsets,
+ false
+ ));
+ } else {
+ sequences.add(new SequenceMetadata(
+ 0,
+ StringUtils.format("%s_%s", ioConfig.getBaseSequenceName(), 0),
+ ioConfig.getStartPartitions().getPartitionOffsetMap(),
+ maxEndOffsets,
+ false
));
- previous = current;
}
- sequences.add(new SequenceMetadata(
- previous.getKey(),
- StringUtils.format("%s_%s", ioConfig.getBaseSequenceName(), previous.getKey()),
- previous.getValue(),
- maxEndOffsets,
- false
- ));
- } else {
- sequences.add(new SequenceMetadata(
- 0,
- StringUtils.format("%s_%s", ioConfig.getBaseSequenceName(), 0),
- ioConfig.getStartPartitions().getPartitionOffsetMap(),
- maxEndOffsets,
- false
- ));
- }
- sequencesPersistFile = new File(toolbox.getPersistDir(), "sequences.json");
- restoreSequences();
+ }
log.info("Starting with sequences: %s", sequences);
if (chatHandlerProvider.isPresent()) {
@@ -495,15 +419,12 @@ public TaskStatus run(final TaskToolbox toolbox) throws Exception
)
);
- try (
- final KafkaConsumer<byte[], byte[]> consumer = newConsumer()
- ) {
+ try (final KafkaConsumer<byte[], byte[]> consumer = newConsumer()) {
toolbox.getDataSegmentServerAnnouncer().announce();
toolbox.getDruidNodeAnnouncer().announce(discoveryDruidNode);
appenderator = newAppenderator(fireDepartmentMetrics, toolbox);
driver = newDriver(appenderator, toolbox, fireDepartmentMetrics);
- createAndStartPublishExecutor();
final String topic = ioConfig.getStartPartitions().getTopic();
@@ -511,13 +432,14 @@ public TaskStatus run(final TaskToolbox toolbox) throws Exception
final Object restoredMetadata = driver.startJob();
if (restoredMetadata == null) {
// no persist has happened so far
+ // so either this is a brand new task or replacement of a failed task
Preconditions.checkState(sequences.get(0).startOffsets.entrySet().stream().allMatch(
partitionOffsetEntry -> Longs.compare(
partitionOffsetEntry.getValue(),
ioConfig.getStartPartitions()
.getPartitionOffsetMap()
.get(partitionOffsetEntry.getKey())
- ) == 0
+ ) >= 0
), "Sequence offsets are not compatible with start offsets of task");
nextOffsets.putAll(sequences.get(0).startOffsets);
} else {
@@ -544,7 +466,7 @@ public TaskStatus run(final TaskToolbox toolbox) throws Exception
ioConfig.getStartPartitions().getPartitionOffsetMap().keySet()
);
}
- // sequences size can 0 only when all sequences got published and task stopped before it could finish
+ // sequences size can be 0 only when all sequences got published and task stopped before it could finish
// which is super rare
if (sequences.size() == 0 || sequences.get(sequences.size() - 1).isCheckpointed()) {
this.endOffsets.putAll(sequences.size() == 0
@@ -592,7 +514,7 @@ public void run()
status = Status.READING;
try {
while (stillReading) {
- if (possiblyPause(assignment)) {
+ if (possiblyPause()) {
// The partition assignments may have changed while paused by a call to setEndOffsets() so reassign
// partitions upon resuming. This is safe even if the end offsets have not been modified.
assignment = assignPartitionsAndSeekToNext(consumer, topic);
@@ -605,8 +527,7 @@ public void run()
}
// if stop is requested or task's end offset is set by call to setEndOffsets method with finish set to true
- if (stopRequested.get() || (sequences.get(sequences.size() - 1).isCheckpointed()
- && !ioConfig.isPauseAfterRead())) {
+ if (stopRequested.get() || sequences.get(sequences.size() - 1).isCheckpointed()) {
status = Status.PUBLISHING;
}
@@ -614,11 +535,12 @@ public void run()
break;
}
- checkAndMaybeThrowException();
-
- if (!ioConfig.isPauseAfterRead()) {
- maybePersistAndPublishSequences(committerSupplier);
+ if (backgroundThreadException != null) {
+ throw new RuntimeException(backgroundThreadException);
}
+ checkPublishAndHandoffFailure();
+
+ maybePersistAndPublishSequences(committerSupplier);
// The retrying business is because the KafkaConsumer throws OffsetOutOfRangeException if the seeked-to
// offset is not present in the topic-partition. This can happen if we're asking a task to read from data
@@ -630,19 +552,17 @@ public void run()
catch (OffsetOutOfRangeException e) {
log.warn("OffsetOutOfRangeException with message [%s]", e.getMessage());
possiblyResetOffsetsOrWait(e.offsetOutOfRangePartitions(), consumer, toolbox);
- stillReading = ioConfig.isPauseAfterRead() || !assignment.isEmpty();
+ stillReading = !assignment.isEmpty();
}
SequenceMetadata sequenceToCheckpoint = null;
for (ConsumerRecord<byte[], byte[]> record : records) {
- if (log.isTraceEnabled()) {
- log.trace(
- "Got topic[%s] partition[%d] offset[%,d].",
- record.topic(),
- record.partition(),
- record.offset()
- );
- }
+ log.trace(
+ "Got topic[%s] partition[%d] offset[%,d].",
+ record.topic(),
+ record.partition(),
+ record.offset()
+ );
if (record.offset() < endOffsets.get(record.partition())) {
if (record.offset() != nextOffsets.get(record.partition())) {
@@ -670,24 +590,23 @@ public void run()
: parser.parseBatch(ByteBuffer.wrap(valueBytes));
boolean isPersistRequired = false;
- for (InputRow row : rows) {
- if (row != null && withinMinMaxRecordTime(row)) {
- SequenceMetadata sequenceToUse = null;
- for (SequenceMetadata sequence : sequences) {
- if (sequence.canHandle(record)) {
- sequenceToUse = sequence;
- }
- }
+ final SequenceMetadata sequenceToUse = sequences
+ .stream()
+ .filter(sequenceMetadata -> sequenceMetadata.canHandle(record))
+ .findFirst()
+ .orElse(null);
- if (sequenceToUse == null) {
- throw new ISE(
- "WTH?! cannot find any valid sequence for record with partition [%d] and offset [%d]. Current sequences: %s",
- record.partition(),
- record.offset(),
- sequences
- );
- }
+ if (sequenceToUse == null) {
+ throw new ISE(
+ "WTH?! cannot find any valid sequence for record with partition [%d] and offset [%d]. Current sequences: %s",
+ record.partition(),
+ record.offset(),
+ sequences
+ );
+ }
+ for (InputRow row : rows) {
+ if (row != null && withinMinMaxRecordTime(row)) {
final AppenderatorDriverAddResult addResult = driver.add(
row,
sequenceToUse.getSequenceName(),
@@ -707,7 +626,7 @@ public void run()
if (addResult.isOk()) {
// If the number of rows in the segment exceeds the threshold after adding a row,
- // move the segment out from the active segments of AppenderatorDriver to make a new segment.
+ // move the segment out from the active segments of BaseAppenderatorDriver to make a new segment.
if (addResult.getNumRowsInSegment() > tuningConfig.getMaxRowsPerSegment()) {
if (!sequenceToUse.isCheckpointed()) {
sequenceToCheckpoint = sequenceToUse;
@@ -741,11 +660,10 @@ public void onSuccess(@Nullable Object result)
public void onFailure(Throwable t)
{
log.error("Persist failed, dying");
- throwableAtomicReference.set(t);
+ backgroundThreadException = t;
}
}
);
-
}
}
catch (ParseException e) {
@@ -770,11 +688,11 @@ public void onFailure(Throwable t)
&& assignment.remove(record.partition())) {
log.info("Finished reading topic[%s], partition[%,d].", record.topic(), record.partition());
assignPartitions(consumer, topic, assignment);
- stillReading = ioConfig.isPauseAfterRead() || !assignment.isEmpty();
+ stillReading = !assignment.isEmpty();
}
}
- if (sequenceToCheckpoint != null && !ioConfig.isPauseAfterRead()) {
+ if (sequenceToCheckpoint != null && stillReading) {
Preconditions.checkArgument(
sequences.get(sequences.size() - 1)
.getSequenceName()
@@ -783,18 +701,24 @@ public void onFailure(Throwable t)
sequenceToCheckpoint,
sequences
);
- requestPause(PAUSE_FOREVER);
- if (!toolbox.getTaskActionClient().submit(new CheckPointDataSourceMetadataAction(
+ requestPause();
+ final CheckPointDataSourceMetadataAction checkpointAction = new CheckPointDataSourceMetadataAction(
getDataSource(),
- ioConfig.getBaseSequenceName(),
+ ioConfig.getTaskGroupId(),
new KafkaDataSourceMetadata(new KafkaPartitions(topic, sequenceToCheckpoint.getStartOffsets())),
new KafkaDataSourceMetadata(new KafkaPartitions(topic, nextOffsets))
- ))) {
+ );
+ if (!toolbox.getTaskActionClient().submit(checkpointAction)) {
throw new ISE("Checkpoint request with offsets [%s] failed, dying", nextOffsets);
}
}
}
}
+ catch (Exception e) {
+ // (1) catch all exceptions while reading from kafka
+ log.error(e, "Encountered exception in run() before persisting.");
+ throw e;
+ }
finally {
log.info("Persisting all pending data");
driver.persist(committerSupplier.get()); // persist pending data
@@ -815,16 +739,23 @@ public void onFailure(Throwable t)
sequenceMetadata.updateAssignments(nextOffsets);
publishingSequences.add(sequenceMetadata.getSequenceName());
// persist already done in finally, so directly add to publishQueue
- publishQueue.add(sequenceMetadata);
+ publishAndRegisterHandoff(sequenceMetadata);
}
}
- // add Sentinel SequenceMetadata to indicate end of all sequences
- publishQueue.add(SequenceMetadata.getSentinelSequenceMetadata());
- waitForPublishes.await();
- checkAndMaybeThrowException();
+ if (backgroundThreadException != null) {
+ throw new RuntimeException(backgroundThreadException);
+ }
+
+ // Wait for publish futures to complete.
+ Futures.allAsList(publishWaitList).get();
- List<SegmentsAndMetadata> handedOffList = Lists.newArrayList();
+ // Wait for handoff futures to complete.
+ // Note that every publishing task (created by calling AppenderatorDriver.publish()) has a corresponding
+ // handoffFuture. handoffFuture can throw an exception if 1) the corresponding publishFuture failed or 2) it
+ // failed to persist sequences. It might also return null if handoff failed, but was recoverable.
+ // See publishAndRegisterHandoff() for details.
+ List<SegmentsAndMetadata> handedOffList = Collections.emptyList();
if (tuningConfig.getHandoffConditionTimeout() == 0) {
handedOffList = Futures.allAsList(handOffWaitList).get();
} else {
@@ -833,6 +764,8 @@ public void onFailure(Throwable t)
.get(tuningConfig.getHandoffConditionTimeout(), TimeUnit.MILLISECONDS);
}
catch (TimeoutException e) {
+ // Handoff timeout is not an indexing failure, but coordination failure. We simply ignore timeout exception
+ // here.
log.makeAlert("Timed out after [%d] millis waiting for handoffs", tuningConfig.getHandoffConditionTimeout())
.addData("TaskId", this.getId())
.emit();
@@ -848,12 +781,18 @@ public void onFailure(Throwable t)
Joiner.on(", ").join(
handedOff.getSegments().stream().map(DataSegment::getIdentifier).collect(Collectors.toList())
),
- handedOff.getCommitMetadata()
+ Preconditions.checkNotNull(handedOff.getCommitMetadata(), "commitMetadata")
);
}
}
+
+ appenderator.close();
}
catch (InterruptedException | RejectedExecutionException e) {
+ // (2) catch InterruptedException and RejectedExecutionException thrown for the whole ingestion steps including
+ // the final publishing.
+ Futures.allAsList(publishWaitList).cancel(true);
+ Futures.allAsList(handOffWaitList).cancel(true);
appenderator.closeNow();
// handle the InterruptedException that gets wrapped in a RejectedExecutionException
if (e instanceof RejectedExecutionException
@@ -869,14 +808,14 @@ public void onFailure(Throwable t)
log.info("The task was asked to stop before completing");
}
+ catch (Exception e) {
+ // (3) catch all other exceptions thrown for the whole ingestion steps including the final publishing.
+ Futures.allAsList(publishWaitList).cancel(true);
+ Futures.allAsList(handOffWaitList).cancel(true);
+ appenderator.closeNow();
+ throw e;
+ }
finally {
- if (appenderator != null) {
- if (throwableAtomicReference.get() != null) {
- appenderator.closeNow();
- } else {
- appenderator.close();
- }
- }
if (driver != null) {
driver.close();
}
@@ -884,10 +823,6 @@ public void onFailure(Throwable t)
chatHandlerProvider.get().unregister(getId());
}
- if (publishExecService != null) {
- publishExecService.shutdownNow();
- }
-
toolbox.getDruidNodeAnnouncer().unannounce(discoveryDruidNode);
toolbox.getDataSegmentServerAnnouncer().unannounce();
}
@@ -939,7 +874,7 @@ private TaskStatus runLegacy(final TaskToolbox toolbox) throws Exception
try (
final Appenderator appenderator0 = newAppenderator(fireDepartmentMetrics, toolbox);
- final AppenderatorDriver driver = newDriver(appenderator0, toolbox, fireDepartmentMetrics);
+ final StreamAppenderatorDriver driver = newDriver(appenderator0, toolbox, fireDepartmentMetrics);
final KafkaConsumer<byte[], byte[]> consumer = newConsumer()
) {
toolbox.getDataSegmentServerAnnouncer().announce();
@@ -1023,7 +958,7 @@ public void run()
status = Status.READING;
try {
while (stillReading) {
- if (possiblyPause(assignment)) {
+ if (possiblyPause()) {
// The partition assignments may have changed while paused by a call to setEndOffsets() so reassign
// partitions upon resuming. This is safe even if the end offsets have not been modified.
assignment = assignPartitionsAndSeekToNext(consumer, topic);
@@ -1049,7 +984,7 @@ public void run()
catch (OffsetOutOfRangeException e) {
log.warn("OffsetOutOfRangeException with message [%s]", e.getMessage());
possiblyResetOffsetsOrWait(e.offsetOutOfRangePartitions(), consumer, toolbox);
- stillReading = ioConfig.isPauseAfterRead() || !assignment.isEmpty();
+ stillReading = !assignment.isEmpty();
}
for (ConsumerRecord<byte[], byte[]> record : records) {
@@ -1102,7 +1037,7 @@ public void run()
if (addResult.isOk()) {
// If the number of rows in the segment exceeds the threshold after adding a row,
- // move the segment out from the active segments of AppenderatorDriver to make a new segment.
+ // move the segment out from the active segments of BaseAppenderatorDriver to make a new segment.
if (addResult.getNumRowsInSegment() > tuningConfig.getMaxRowsPerSegment()) {
segmentsToMoveOut.computeIfAbsent(sequenceName, k -> new HashSet<>())
.add(addResult.getSegmentIdentifier());
@@ -1149,7 +1084,7 @@ public void run()
&& assignment.remove(record.partition())) {
log.info("Finished reading topic[%s], partition[%,d].", record.topic(), record.partition());
assignPartitions(consumer, topic, assignment);
- stillReading = ioConfig.isPauseAfterRead() || !assignment.isEmpty();
+ stillReading = !assignment.isEmpty();
}
}
}
@@ -1168,7 +1103,7 @@ public void run()
final TransactionalSegmentPublisher publisher = (segments, commitMetadata) -> {
final KafkaPartitions finalPartitions = toolbox.getObjectMapper().convertValue(
- ((Map) commitMetadata).get(METADATA_NEXT_PARTITIONS),
+ ((Map) Preconditions.checkNotNull(commitMetadata, "commitMetadata")).get(METADATA_NEXT_PARTITIONS),
KafkaPartitions.class
);
@@ -1202,33 +1137,38 @@ public void run()
sequenceNames.values()
).get();
+ final List<String> publishedSegments = published.getSegments()
+ .stream()
+ .map(DataSegment::getIdentifier)
+ .collect(Collectors.toList());
+ log.info(
+ "Published segments[%s] with metadata[%s].",
+ publishedSegments,
+ Preconditions.checkNotNull(published.getCommitMetadata(), "commitMetadata")
+ );
+
final Future<SegmentsAndMetadata> handoffFuture = driver.registerHandoff(published);
- final SegmentsAndMetadata handedOff;
+ SegmentsAndMetadata handedOff = null;
if (tuningConfig.getHandoffConditionTimeout() == 0) {
handedOff = handoffFuture.get();
} else {
- handedOff = handoffFuture.get(tuningConfig.getHandoffConditionTimeout(), TimeUnit.MILLISECONDS);
+ try {
+ handedOff = handoffFuture.get(tuningConfig.getHandoffConditionTimeout(), TimeUnit.MILLISECONDS);
+ }
+ catch (TimeoutException e) {
+ log.makeAlert("Timed out after [%d] millis waiting for handoffs", tuningConfig.getHandoffConditionTimeout())
+ .addData("TaskId", getId())
+ .emit();
+ }
}
if (handedOff == null) {
- throw new ISE("Transaction failure publishing segments, aborting");
+ log.warn("Failed to handoff segments[%s]", publishedSegments);
} else {
log.info(
- "Published segments[%s] with metadata[%s].",
- Joiner.on(", ").join(
- Iterables.transform(
- handedOff.getSegments(),
- new Function<DataSegment, String>()
- {
- @Override
- public String apply(DataSegment input)
- {
- return input.getIdentifier();
- }
- }
- )
- ),
- handedOff.getCommitMetadata()
+ "Handoff completed for segments[%s] with metadata[%s]",
+ handedOff.getSegments().stream().map(DataSegment::getIdentifier).collect(Collectors.toList()),
+ Preconditions.checkNotNull(handedOff.getCommitMetadata(), "commitMetadata")
);
}
}
@@ -1259,15 +1199,158 @@ public String apply(DataSegment input)
return success();
}
- private void checkAndMaybeThrowException()
+ private void checkPublishAndHandoffFailure() throws ExecutionException, InterruptedException
+ {
+ // Check if any publishFuture failed.
+ final List<ListenableFuture<SegmentsAndMetadata>> publishFinished = publishWaitList
+ .stream()
+ .filter(Future::isDone)
+ .collect(Collectors.toList());
+
+ for (ListenableFuture<SegmentsAndMetadata> publishFuture : publishFinished) {
+ // If publishFuture failed, the below line will throw an exception and catched by (1), and then (2) or (3).
+ publishFuture.get();
+ }
+
+ publishWaitList.removeAll(publishFinished);
+
+ // Check if any handoffFuture failed.
+ final List<ListenableFuture<SegmentsAndMetadata>> handoffFinished = handOffWaitList
+ .stream()
+ .filter(Future::isDone)
+ .collect(Collectors.toList());
+
+ for (ListenableFuture<SegmentsAndMetadata> handoffFuture : handoffFinished) {
+ // If handoffFuture failed, the below line will throw an exception and catched by (1), and then (2) or (3).
+ handoffFuture.get();
+ }
+
+ handOffWaitList.removeAll(handoffFinished);
+ }
+
+ private void publishAndRegisterHandoff(SequenceMetadata sequenceMetadata)
+ {
+ log.info("Publishing segments for sequence [%s]", sequenceMetadata);
+
+ final ListenableFuture<SegmentsAndMetadata> publishFuture = Futures.transform(
+ driver.publish(
+ sequenceMetadata.createPublisher(toolbox, ioConfig.isUseTransaction()),
+ sequenceMetadata.getCommitterSupplier(topic, lastPersistedOffsets).get(),
+ Collections.singletonList(sequenceMetadata.getSequenceName())
+ ),
+ (Function<SegmentsAndMetadata, SegmentsAndMetadata>) publishedSegmentsAndMetadata -> {
+ if (publishedSegmentsAndMetadata == null) {
+ throw new ISE(
+ "Transaction failure publishing segments for sequence [%s]",
+ sequenceMetadata
+ );
+ } else {
+ return publishedSegmentsAndMetadata;
+ }
+ }
+ );
+ publishWaitList.add(publishFuture);
+
+ // Create a handoffFuture for every publishFuture. The created handoffFuture must fail if publishFuture fails.
+ final SettableFuture<SegmentsAndMetadata> handoffFuture = SettableFuture.create();
+ handOffWaitList.add(handoffFuture);
+
+ Futures.addCallback(
+ publishFuture,
+ new FutureCallback<SegmentsAndMetadata>()
+ {
+ @Override
+ public void onSuccess(SegmentsAndMetadata publishedSegmentsAndMetadata)
+ {
+ log.info(
+ "Published segments[%s] with metadata[%s].",
+ publishedSegmentsAndMetadata.getSegments()
+ .stream()
+ .map(DataSegment::getIdentifier)
+ .collect(Collectors.toList()),
+ Preconditions.checkNotNull(publishedSegmentsAndMetadata.getCommitMetadata(), "commitMetadata")
+ );
+
+ sequences.remove(sequenceMetadata);
+ publishingSequences.remove(sequenceMetadata.getSequenceName());
+ try {
+ persistSequences();
+ }
+ catch (IOException e) {
+ log.error(e, "Unable to persist state, dying");
+ handoffFuture.setException(e);
+ throw new RuntimeException(e);
+ }
+
+ Futures.transform(
+ driver.registerHandoff(publishedSegmentsAndMetadata),
+ new Function<SegmentsAndMetadata, Void>()
+ {
+ @Nullable
+ @Override
+ public Void apply(@Nullable SegmentsAndMetadata handoffSegmentsAndMetadata)
+ {
+ if (handoffSegmentsAndMetadata == null) {
+ log.warn(
+ "Failed to handoff segments[%s]",
+ publishedSegmentsAndMetadata.getSegments()
+ .stream()
+ .map(DataSegment::getIdentifier)
+ .collect(Collectors.toList())
+ );
+ }
+ handoffFuture.set(handoffSegmentsAndMetadata);
+ return null;
+ }
+ }
+ );
+ }
+
+ @Override
+ public void onFailure(Throwable t)
+ {
+ log.error(t, "Error while publishing segments for sequence[%s]", sequenceMetadata);
+ handoffFuture.setException(t);
+ }
+ }
+ );
+ }
+
+ private static File getSequencesPersistFile(TaskToolbox toolbox)
+ {
+ return new File(toolbox.getPersistDir(), "sequences.json");
+ }
+
+ private boolean restoreSequences() throws IOException
{
- if (throwableAtomicReference.get() != null) {
- Throwables.propagate(throwableAtomicReference.get());
+ final File sequencesPersistFile = getSequencesPersistFile(toolbox);
+ if (sequencesPersistFile.exists()) {
+ sequences = new CopyOnWriteArrayList<>(
+ toolbox.getObjectMapper().<List<SequenceMetadata>>readValue(
+ sequencesPersistFile,
+ new TypeReference<List<SequenceMetadata>>()
+ {
+ }
+ )
+ );
+ return true;
+ } else {
+ return false;
}
}
+ private synchronized void persistSequences() throws IOException
+ {
+ log.info("Persisting Sequences Metadata [%s]", sequences);
+ toolbox.getObjectMapper().writerWithType(
+ new TypeReference<List<SequenceMetadata>>()
+ {
+ }
+ ).writeValue(getSequencesPersistFile(toolbox), sequences);
+ }
+
private void maybePersistAndPublishSequences(Supplier<Committer> committerSupplier)
- throws ExecutionException, InterruptedException
+ throws InterruptedException
{
for (SequenceMetadata sequenceMetadata : sequences) {
sequenceMetadata.updateAssignments(nextOffsets);
@@ -1280,7 +1363,7 @@ private void maybePersistAndPublishSequences(Supplier<Committer> committerSuppli
result,
sequenceMetadata
);
- publishQueue.add(sequenceMetadata);
+ publishAndRegisterHandoff(sequenceMetadata);
}
catch (InterruptedException e) {
log.warn("Interrupted while persisting sequence [%s]", sequenceMetadata);
@@ -1290,73 +1373,194 @@ private void maybePersistAndPublishSequences(Supplier<Committer> committerSuppli
}
}
- private void restoreSequences() throws IOException
+ private Set<Integer> assignPartitionsAndSeekToNext(KafkaConsumer consumer, String topic)
{
- Preconditions.checkNotNull(sequencesPersistFile);
- if (sequencesPersistFile.exists()) {
- sequences = new CopyOnWriteArrayList<>(toolbox.getObjectMapper().<List<SequenceMetadata>>readValue(
- sequencesPersistFile, new TypeReference<List<SequenceMetadata>>()
- {
- }));
+ // Initialize consumer assignment.
+ final Set<Integer> assignment = Sets.newHashSet();
+ for (Map.Entry<Integer, Long> entry : nextOffsets.entrySet()) {
+ final long endOffset = endOffsets.get(entry.getKey());
+ if (entry.getValue() < endOffset) {
+ assignment.add(entry.getKey());
+ } else if (entry.getValue() == endOffset) {
+ log.info("Finished reading partition[%d].", entry.getKey());
+ } else {
+ throw new ISE(
+ "WTF?! Cannot start from offset[%,d] > endOffset[%,d]",
+ entry.getValue(),
+ endOffset
+ );
+ }
}
- }
- private synchronized void persistSequences() throws IOException
- {
- log.info("Persisting Sequences Metadata [%s]", sequences);
- toolbox.getObjectMapper().writerWithType(
- new TypeReference<List<SequenceMetadata>>()
- {
- }
- ).writeValue(sequencesPersistFile, sequences);
- }
+ KafkaIndexTask.assignPartitions(consumer, topic, assignment);
- @Override
- public boolean canRestore()
- {
- return true;
+ // Seek to starting offsets.
+ for (final int partition : assignment) {
+ final long offset = nextOffsets.get(partition);
+ log.info("Seeking partition[%d] to offset[%,d].", partition, offset);
+ consumer.seek(new TopicPartition(topic, partition), offset);
+ }
+
+ return assignment;
}
/**
- * Authorizes action to be performed on this task's datasource
+ * Checks if the pauseRequested flag was set and if so blocks until pauseRequested is cleared.
+ * <p/>
+ * Sets paused = true and signals paused so callers can be notified when the pause command has been accepted.
+ * <p/>
*
- * @return authorization result
+ * @return true if a pause request was handled, false otherwise
*/
- private Access authorizationCheck(final HttpServletRequest req, Action action)
+ private boolean possiblyPause() throws InterruptedException
{
- ResourceAction resourceAction = new ResourceAction(
- new Resource(dataSchema.getDataSource(), ResourceType.DATASOURCE),
- action
- );
+ pauseLock.lockInterruptibly();
+ try {
+ if (pauseRequested) {
+ status = Status.PAUSED;
+ hasPaused.signalAll();
- Access access = AuthorizationUtils.authorizeResourceAction(req, resourceAction, authorizerMapper);
- if (!access.isAllowed()) {
- throw new ForbiddenException(access.toString());
- }
+ while (pauseRequested) {
+ log.info("Pausing ingestion until resumed");
+ shouldResume.await();
+ }
- return access;
- }
+ status = Status.READING;
+ shouldResume.signalAll();
+ log.info("Ingestion loop resumed");
+ return true;
+ }
+ }
+ finally {
+ pauseLock.unlock();
+ }
- @VisibleForTesting
- Appenderator getAppenderator()
- {
- return appenderator;
+ return false;
}
- @Override
- public void stopGracefully()
+ private void possiblyResetOffsetsOrWait(
+ Map<TopicPartition, Long> outOfRangePartitions,
+ KafkaConsumer<byte[], byte[]> consumer,
+ TaskToolbox taskToolbox
+ ) throws InterruptedException, IOException
{
- log.info("Stopping gracefully (status: [%s])", status);
- stopRequested.set(true);
-
- synchronized (statusLock) {
- if (status == Status.PUBLISHING) {
- runThread.interrupt();
- return;
+ final Map<TopicPartition, Long> resetPartitions = Maps.newHashMap();
+ boolean doReset = false;
+ if (tuningConfig.isResetOffsetAutomatically()) {
+ for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) {
+ final TopicPartition topicPartition = outOfRangePartition.getKey();
+ final long nextOffset = outOfRangePartition.getValue();
+ // seek to the beginning to get the least available offset
+ consumer.seekToBeginning(Collections.singletonList(topicPartition));
+ final long leastAvailableOffset = consumer.position(topicPartition);
+ // reset the seek
+ consumer.seek(topicPartition, nextOffset);
+ // Reset consumer offset if resetOffsetAutomatically is set to true
+ // and the current message offset in the kafka partition is more than the
+ // next message offset that we are trying to fetch
+ if (leastAvailableOffset > nextOffset) {
+ doReset = true;
+ resetPartitions.put(topicPartition, nextOffset);
+ }
}
}
- try {
+ if (doReset) {
+ sendResetRequestAndWait(resetPartitions, taskToolbox);
+ } else {
+ log.warn("Retrying in %dms", pollRetryMs);
+ pollRetryLock.lockInterruptibly();
+ try {
+ long nanos = TimeUnit.MILLISECONDS.toNanos(pollRetryMs);
+ while (nanos > 0L && !pauseRequested && !stopRequested.get()) {
+ nanos = isAwaitingRetry.awaitNanos(nanos);
+ }
+ }
+ finally {
+ pollRetryLock.unlock();
+ }
+ }
+ }
+
+ private void requestPause()
+ {
+ pauseRequested = true;
+ }
+
+ private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox)
+ throws IOException
+ {
+ Map<Integer, Long> partitionOffsetMap = Maps.newHashMap();
+ for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) {
+ partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue());
+ }
+ boolean result = taskToolbox.getTaskActionClient()
+ .submit(new ResetDataSourceMetadataAction(
+ getDataSource(),
+ new KafkaDataSourceMetadata(new KafkaPartitions(
+ ioConfig.getStartPartitions()
+ .getTopic(),
+ partitionOffsetMap
+ ))
+ ));
+
+ if (result) {
+ log.makeAlert("Resetting Kafka offsets for datasource [%s]", getDataSource())
+ .addData("partitions", partitionOffsetMap.keySet())
+ .emit();
+ // wait for being killed by supervisor
+ requestPause();
+ } else {
+ log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit();
+ }
+ }
+
+ @Override
+ public boolean canRestore()
+ {
+ return true;
+ }
+
+ /**
+ * Authorizes action to be performed on this task's datasource
+ *
+ * @return authorization result
+ */
+ private Access authorizationCheck(final HttpServletRequest req, Action action)
+ {
+ ResourceAction resourceAction = new ResourceAction(
+ new Resource(dataSchema.getDataSource(), ResourceType.DATASOURCE),
+ action
+ );
+
+ Access access = AuthorizationUtils.authorizeResourceAction(req, resourceAction, authorizerMapper);
+ if (!access.isAllowed()) {
+ throw new ForbiddenException(access.toString());
+ }
+
+ return access;
+ }
+
+ @VisibleForTesting
+ Appenderator getAppenderator()
+ {
+ return appenderator;
+ }
+
+ @Override
+ public void stopGracefully()
+ {
+ log.info("Stopping gracefully (status: [%s])", status);
+ stopRequested.set(true);
+
+ synchronized (statusLock) {
+ if (status == Status.PUBLISHING) {
+ runThread.interrupt();
+ return;
+ }
+ }
+
+ try {
if (pauseLock.tryLock(LOCK_ACQUIRE_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
try {
if (pauseRequested) {
@@ -1465,25 +1669,23 @@ public Status getStatus()
@Produces(MediaType.APPLICATION_JSON)
public Response setEndOffsetsHTTP(
Map<Integer, Long> offsets,
- @QueryParam("resume") @DefaultValue("false") final boolean resume,
@QueryParam("finish") @DefaultValue("true") final boolean finish,
// this field is only for internal purposes, shouldn't be usually set by users
@Context final HttpServletRequest req
) throws InterruptedException
{
authorizationCheck(req, Action.WRITE);
- return setEndOffsets(offsets, resume, finish);
+ return setEndOffsets(offsets, finish);
}
public Response setEndOffsets(
Map<Integer, Long> offsets,
- final boolean resume,
final boolean finish // this field is only for internal purposes, shouldn't be usually set by users
) throws InterruptedException
{
// for backwards compatibility, should be removed from versions greater than 0.12.x
if (useLegacy) {
- return setEndOffsetsLegacy(offsets, resume);
+ return setEndOffsetsLegacy(offsets);
}
if (offsets == null) {
@@ -1511,7 +1713,7 @@ public Response setEndOffsets(
(latestSequence.getEndOffsets().equals(offsets) && finish)) {
log.warn("Ignoring duplicate request, end offsets already set for sequences [%s]", sequences);
return Response.ok(offsets).build();
- } else if (latestSequence.isCheckpointed() && !ioConfig.isPauseAfterRead()) {
+ } else if (latestSequence.isCheckpointed()) {
return Response.status(Response.Status.BAD_REQUEST)
.entity(StringUtils.format(
"WTH?! Sequence [%s] has already endOffsets set, cannot set to [%s]",
@@ -1544,13 +1746,12 @@ public Response setEndOffsets(
log.info("Updating endOffsets from [%s] to [%s]", endOffsets, offsets);
endOffsets.putAll(offsets);
} else {
- Preconditions.checkState(!ioConfig.isPauseAfterRead());
// create new sequence
final SequenceMetadata newSequence = new SequenceMetadata(
latestSequence.getSequenceId() + 1,
StringUtils.format("%s_%d", ioConfig.getBaseSequenceName(), latestSequence.getSequenceId() + 1),
offsets,
- maxEndOffsets,
+ endOffsets,
false
);
sequences.add(newSequence);
@@ -1560,77 +1761,23 @@ public Response setEndOffsets(
}
catch (Exception e) {
log.error(e, "Unable to set end offsets, dying");
- throwableAtomicReference.set(e);
- Throwables.propagate(e);
+ backgroundThreadException = e;
+ // should resume to immediately finish kafka index task as failed
+ resume();
+ return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
+ .entity(Throwables.getStackTraceAsString(e))
+ .build();
}
finally {
pauseLock.unlock();
}
}
- if (resume) {
- resume();
- }
+ resume();
return Response.ok(offsets).build();
}
- private Response setEndOffsetsLegacy(
- Map<Integer, Long> offsets,
- final boolean resume
- ) throws InterruptedException
- {
- if (offsets == null) {
- return Response.status(Response.Status.BAD_REQUEST)
- .entity("Request body must contain a map of { partition:endOffset }")
- .build();
- } else if (!endOffsets.keySet().containsAll(offsets.keySet())) {
- return Response.status(Response.Status.BAD_REQUEST)
- .entity(
- StringUtils.format(
- "Request contains partitions not being handled by this task, my partitions: %s",
- endOffsets.keySet()
- )
- )
- .build();
- }
-
- pauseLock.lockInterruptibly();
- try {
- if (!isPaused()) {
- return Response.status(Response.Status.BAD_REQUEST)
- .entity("Task must be paused before changing the end offsets")
- .build();
- }
-
- for (Map.Entry<Integer, Long> entry : offsets.entrySet()) {
- if (entry.getValue().compareTo(nextOffsets.get(entry.getKey())) < 0) {
- return Response.status(Response.Status.BAD_REQUEST)
- .entity(
- StringUtils.format(
- "End offset must be >= current offset for partition [%s] (current: %s)",
- entry.getKey(),
- nextOffsets.get(entry.getKey())
- )
- )
- .build();
- }
- }
-
- endOffsets.putAll(offsets);
- log.info("endOffsets changed to %s", endOffsets);
- }
- finally {
- pauseLock.unlock();
- }
-
- if (resume) {
- resume();
- }
-
- return Response.ok(endOffsets).build();
- }
-
@GET
@Path("/checkpoints")
@Produces(MediaType.APPLICATION_JSON)
@@ -1640,7 +1787,7 @@ private Response setEndOffsetsLegacy(
return getCheckpoints();
}
- public Map<Integer, Map<Integer, Long>> getCheckpoints()
+ private Map<Integer, Map<Integer, Long>> getCheckpoints()
{
TreeMap<Integer, Map<Integer, Long>> result = new TreeMap<>();
result.putAll(
@@ -1652,8 +1799,6 @@ private Response setEndOffsetsLegacy(
/**
* Signals the ingestion loop to pause.
*
- * @param timeout how long to pause for before resuming in milliseconds, <= 0 means indefinitely
- *
* @return one of the following Responses: 400 Bad Request if the task has started publishing; 202 Accepted if the
* method has timed out and returned before the task has paused; 200 OK with a map of the current partition offsets
* in the response body if the task successfully paused
@@ -1662,15 +1807,14 @@ private Response setEndOffsetsLegacy(
@Path("/pause")
@Produces(MediaType.APPLICATION_JSON)
public Response pauseHTTP(
- @QueryParam("timeout") @DefaultValue("0") final long timeout,
@Context final HttpServletRequest req
) throws InterruptedException
{
authorizationCheck(req, Action.WRITE);
- return pause(timeout);
+ return pause();
}
- public Response pause(final long timeout) throws InterruptedException
+ public Response pause() throws InterruptedException
{
if (!(status == Status.PAUSED || status == Status.READING)) {
return Response.status(Response.Status.BAD_REQUEST)
@@ -1680,7 +1824,6 @@ public Response pause(final long timeout) throws InterruptedException
pauseLock.lockInterruptibly();
try {
- pauseMillis = timeout <= 0 ? PAUSE_FOREVER : timeout;
pauseRequested = true;
pollRetryLock.lockInterruptibly();
@@ -1755,6 +1898,79 @@ public DateTime getStartTime(@Context final HttpServletRequest req)
return startTime;
}
+ @Nullable
+ private static TreeMap<Integer, Map<Integer, Long>> getCheckPointsFromContext(
+ TaskToolbox toolbox,
+ KafkaIndexTask task
+ ) throws IOException
+ {
+ final String checkpointsString = task.getContextValue("checkpoints");
+ if (checkpointsString != null) {
+ log.info("Checkpoints [%s]", checkpointsString);
+ return toolbox.getObjectMapper().readValue(
+ checkpointsString,
+ new TypeReference<TreeMap<Integer, Map<Integer, Long>>>()
+ {
+ }
+ );
+ } else {
+ return null;
+ }
+ }
+
+ private Response setEndOffsetsLegacy(
+ Map<Integer, Long> offsets
+ ) throws InterruptedException
+ {
+ if (offsets == null) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity("Request body must contain a map of { partition:endOffset }")
+ .build();
+ } else if (!endOffsets.keySet().containsAll(offsets.keySet())) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(
+ StringUtils.format(
+ "Request contains partitions not being handled by this task, my partitions: %s",
+ endOffsets.keySet()
+ )
+ )
+ .build();
+ }
+
+ pauseLock.lockInterruptibly();
+ try {
+ if (!isPaused()) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity("Task must be paused before changing the end offsets")
+ .build();
+ }
+
+ for (Map.Entry<Integer, Long> entry : offsets.entrySet()) {
+ if (entry.getValue().compareTo(nextOffsets.get(entry.getKey())) < 0) {
+ return Response.status(Response.Status.BAD_REQUEST)
+ .entity(
+ StringUtils.format(
+ "End offset must be >= current offset for partition [%s] (current: %s)",
+ entry.getKey(),
+ nextOffsets.get(entry.getKey())
+ )
+ )
+ .build();
+ }
+ }
+
+ endOffsets.putAll(offsets);
+ log.info("endOffsets changed to %s", endOffsets);
+ }
+ finally {
+ pauseLock.unlock();
+ }
+
+ resume();
+
+ return Response.ok(endOffsets).build();
+ }
+
@VisibleForTesting
FireDepartmentMetrics getFireDepartmentMetrics()
{
@@ -1766,12 +1982,6 @@ private boolean isPaused()
return status == Status.PAUSED;
}
- private void requestPause(long pauseMillis)
- {
- this.pauseMillis = pauseMillis;
- pauseRequested = true;
- }
-
private Appenderator newAppenderator(FireDepartmentMetrics metrics, TaskToolbox toolbox)
{
return Appenderators.createRealtime(
@@ -1791,17 +2001,18 @@ private Appenderator newAppenderator(FireDepartmentMetrics metrics, TaskToolbox
);
}
- private AppenderatorDriver newDriver(
+ private StreamAppenderatorDriver newDriver(
final Appenderator appenderator,
final TaskToolbox toolbox,
final FireDepartmentMetrics metrics
)
{
- return new AppenderatorDriver(
+ return new StreamAppenderatorDriver(
appenderator,
new ActionBasedSegmentAllocator(toolbox.getTaskActionClient(), dataSchema),
toolbox.getSegmentHandoffNotifierFactory(),
new ActionBasedUsedSegmentChecker(toolbox.getTaskActionClient()),
+ toolbox.getDataSegmentKiller(),
toolbox.getObjectMapper(),
metrics
);
@@ -1844,169 +2055,6 @@ private static void assignPartitions(
);
}
- private Set<Integer> assignPartitionsAndSeekToNext(KafkaConsumer consumer, String topic)
- {
- // Initialize consumer assignment.
- final Set<Integer> assignment = Sets.newHashSet();
- for (Map.Entry<Integer, Long> entry : nextOffsets.entrySet()) {
- final long endOffset = endOffsets.get(entry.getKey());
- if (entry.getValue() < endOffset) {
- assignment.add(entry.getKey());
- } else if (entry.getValue() == endOffset) {
- log.info("Finished reading partition[%d].", entry.getKey());
- } else {
- throw new ISE(
- "WTF?! Cannot start from offset[%,d] > endOffset[%,d]",
- entry.getValue(),
- endOffset
- );
- }
- }
-
- assignPartitions(consumer, topic, assignment);
-
- // Seek to starting offsets.
- for (final int partition : assignment) {
- final long offset = nextOffsets.get(partition);
- log.info("Seeking partition[%d] to offset[%,d].", partition, offset);
- consumer.seek(new TopicPartition(topic, partition), offset);
- }
-
- return assignment;
- }
-
- /**
- * Checks if the pauseRequested flag was set and if so blocks:
- * a) if pauseMillis == PAUSE_FOREVER, until pauseRequested is cleared
- * b) if pauseMillis != PAUSE_FOREVER, until pauseMillis elapses -or- pauseRequested is cleared
- * <p/>
- * If pauseMillis is changed while paused, the new pause timeout will be applied. This allows adjustment of the
- * pause timeout (making a timed pause into an indefinite pause and vice versa is valid) without having to resume
- * and ensures that the loop continues to stay paused without ingesting any new events. You will need to signal
- * shouldResume after adjusting pauseMillis for the new value to take effect.
- * <p/>
- * Sets paused = true and signals paused so callers can be notified when the pause command has been accepted.
- * <p/>
- * Additionally, pauses if all partitions assignments have been read and pauseAfterRead flag is set.
- *
- * @return true if a pause request was handled, false otherwise
- */
- private boolean possiblyPause(Set<Integer> assignment) throws InterruptedException
- {
- pauseLock.lockInterruptibly();
- try {
- if (ioConfig.isPauseAfterRead() && assignment.isEmpty()) {
- pauseMillis = PAUSE_FOREVER;
- pauseRequested = true;
- }
-
- if (pauseRequested) {
- status = Status.PAUSED;
- long nanos = 0;
- hasPaused.signalAll();
-
- while (pauseRequested) {
- if (pauseMillis == PAUSE_FOREVER) {
- log.info("Pausing ingestion until resumed");
- shouldResume.await();
- } else {
- if (pauseMillis > 0) {
- log.info("Pausing ingestion for [%,d] ms", pauseMillis);
- nanos = TimeUnit.MILLISECONDS.toNanos(pauseMillis);
- pauseMillis = 0;
- }
- if (nanos <= 0L) {
- pauseRequested = false; // timeout elapsed
- }
- nanos = shouldResume.awaitNanos(nanos);
- }
- }
-
- status = Status.READING;
- shouldResume.signalAll();
- log.info("Ingestion loop resumed");
- return true;
- }
- }
- finally {
- pauseLock.unlock();
- }
-
- return false;
- }
-
- private void possiblyResetOffsetsOrWait(
- Map<TopicPartition, Long> outOfRangePartitions,
- KafkaConsumer<byte[], byte[]> consumer,
- TaskToolbox taskToolbox
- ) throws InterruptedException, IOException
- {
- final Map<TopicPartition, Long> resetPartitions = Maps.newHashMap();
- boolean doReset = false;
- if (tuningConfig.isResetOffsetAutomatically()) {
- for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) {
- final TopicPartition topicPartition = outOfRangePartition.getKey();
- final long nextOffset = outOfRangePartition.getValue();
- // seek to the beginning to get the least available offset
- consumer.seekToBeginning(Collections.singletonList(topicPartition));
- final long leastAvailableOffset = consumer.position(topicPartition);
- // reset the seek
- consumer.seek(topicPartition, nextOffset);
- // Reset consumer offset if resetOffsetAutomatically is set to true
- // and the current message offset in the kafka partition is more than the
- // next message offset that we are trying to fetch
- if (leastAvailableOffset > nextOffset) {
- doReset = true;
- resetPartitions.put(topicPartition, nextOffset);
- }
- }
- }
-
- if (doReset) {
- sendResetRequestAndWait(resetPartitions, taskToolbox);
- } else {
- log.warn("Retrying in %dms", pollRetryMs);
- pollRetryLock.lockInterruptibly();
- try {
- long nanos = TimeUnit.MILLISECONDS.toNanos(pollRetryMs);
- while (nanos > 0L && !pauseRequested && !stopRequested.get()) {
- nanos = isAwaitingRetry.awaitNanos(nanos);
- }
- }
- finally {
- pollRetryLock.unlock();
- }
- }
- }
-
- private void sendResetRequestAndWait(Map<TopicPartition, Long> outOfRangePartitions, TaskToolbox taskToolbox)
- throws IOException
- {
- Map<Integer, Long> partitionOffsetMap = Maps.newHashMap();
- for (Map.Entry<TopicPartition, Long> outOfRangePartition : outOfRangePartitions.entrySet()) {
- partitionOffsetMap.put(outOfRangePartition.getKey().partition(), outOfRangePartition.getValue());
- }
- boolean result = taskToolbox.getTaskActionClient()
- .submit(new ResetDataSourceMetadataAction(
- getDataSource(),
- new KafkaDataSourceMetadata(new KafkaPartitions(
- ioConfig.getStartPartitions()
- .getTopic(),
- partitionOffsetMap
- ))
- ));
-
- if (result) {
- log.makeAlert("Resetting Kafka offsets for datasource [%s]", getDataSource())
- .addData("partitions", partitionOffsetMap.keySet())
- .emit();
- // wait for being killed by supervisor
- requestPause(PAUSE_FOREVER);
- } else {
- log.makeAlert("Failed to send reset request for partitions [%s]", partitionOffsetMap.keySet()).emit();
- }
- }
-
private boolean withinMinMaxRecordTime(final InputRow row)
{
final boolean beforeMinimumMessageTime = ioConfig.getMinimumMessageTime().isPresent()
@@ -2015,6 +2063,19 @@ private boolean withinMinMaxRecordTime(final InputRow row)
final boolean afterMaximumMessageTime = ioConfig.getMaximumMessageTime().isPresent()
&& ioConfig.getMaximumMessageTime().get().isBefore(row.getTimestamp());
+ if (!Intervals.ETERNITY.contains(row.getTimestamp())) {
+ final String errorMsg = StringUtils.format(
+ "Encountered row with timestamp that cannot be represented as a long: [%s]",
+ row
+ );
+ log.debug(errorMsg);
+ if (tuningConfig.isReportParseExceptions()) {
+ throw new ParseException(errorMsg);
+ } else {
+ return false;
+ }
+ }
+
if (log.isDebugEnabled()) {
if (beforeMinimumMessageTime) {
log.debug(
@@ -2036,13 +2097,19 @@ private boolean withinMinMaxRecordTime(final InputRow row)
private static class SequenceMetadata
{
+ /**
+ * Lock for accessing {@link #endOffsets} and {@link #checkpointed}. This lock is required because
+ * {@link #setEndOffsets)} can be called by both the main thread and the HTTP thread.
+ */
+ private final ReentrantLock lock = new ReentrantLock();
+
private final int sequenceId;
private final String sequenceName;
private final Map<Integer, Long> startOffsets;
private final Map<Integer, Long> endOffsets;
private final Set<Integer> assignments;
private final boolean sentinel;
- private volatile boolean checkpointed;
+ private boolean checkpointed;
@JsonCreator
public SequenceMetadata(
@@ -2059,8 +2126,8 @@ public SequenceMetadata(
this.sequenceId = sequenceId;
this.sequenceName = sequenceName;
this.startOffsets = ImmutableMap.copyOf(startOffsets);
- this.endOffsets = Maps.newHashMap(endOffsets);
- this.assignments = Sets.newHashSet(startOffsets.keySet());
+ this.endOffsets = new HashMap<>(endOffsets);
+ this.assignments = new HashSet<>(startOffsets.keySet());
this.checkpointed = checkpointed;
this.sentinel = false;
}
@@ -2074,7 +2141,13 @@ public int getSequenceId()
@JsonProperty
public boolean isCheckpointed()
{
- return checkpointed;
+ lock.lock();
+ try {
+ return checkpointed;
+ }
+ finally {
+ lock.unlock();
+ }
}
@JsonProperty
@@ -2092,7 +2165,13 @@ public String getSequenceName()
@JsonProperty
public Map<Integer, Long> getEndOffsets()
{
- return endOffsets;
+ lock.lock();
+ try {
+ return endOffsets;
+ }
+ finally {
+ lock.unlock();
+ }
}
@JsonProperty
@@ -2101,68 +2180,75 @@ public boolean isSentinel()
return sentinel;
}
- public void setEndOffsets(Map<Integer, Long> newEndOffsets)
+ void setEndOffsets(Map<Integer, Long> newEndOffsets)
{
- endOffsets.putAll(newEndOffsets);
- checkpointed = true;
+ lock.lock();
+ try {
+ endOffsets.putAll(newEndOffsets);
+ checkpointed = true;
+ }
+ finally {
+ lock.unlock();
+ }
}
- public void updateAssignments(Map<Integer, Long> nextPartitionOffset)
+ void updateAssignments(Map<Integer, Long> nextPartitionOffset)
{
- assignments.clear();
- nextPartitionOffset.entrySet().forEach(partitionOffset -> {
- if (Longs.compare(endOffsets.get(partitionOffset.getKey()), nextPartitionOffset.get(partitionOffset.getKey()))
- > 0) {
- assignments.add(partitionOffset.getKey());
- }
- });
+ lock.lock();
+ try {
+ assignments.clear();
+ nextPartitionOffset.forEach((key, value) -> {
+ if (Longs.compare(endOffsets.get(key), nextPartitionOffset.get(key)) > 0) {
+ assignments.add(key);
+ }
+ });
+ }
+ finally {
+ lock.unlock();
+ }
}
- public boolean isOpen()
+ boolean isOpen()
{
return !assignments.isEmpty();
}
boolean canHandle(ConsumerRecord<byte[], byte[]> record)
{
- return isOpen()
- && endOffsets.get(record.partition()) != null
- && record.offset() >= startOffsets.get(record.partition())
- && record.offset() < endOffsets.get(record.partition());
- }
-
- private SequenceMetadata()
- {
- this.sequenceId = -1;
- this.sequenceName = null;
- this.startOffsets = null;
- this.endOffsets = null;
- this.assignments = null;
- this.checkpointed = true;
- this.sentinel = true;
- }
-
- public static SequenceMetadata getSentinelSequenceMetadata()
- {
- return new SequenceMetadata();
+ lock.lock();
+ try {
+ final Long partitionEndOffset = endOffsets.get(record.partition());
+ return isOpen()
+ && partitionEndOffset != null
+ && record.offset() >= startOffsets.get(record.partition())
+ && record.offset() < partitionEndOffset;
+ }
+ finally {
+ lock.unlock();
+ }
}
@Override
public String toString()
{
- return "SequenceMetadata{" +
- "sequenceName='" + sequenceName + '\'' +
- ", sequenceId=" + sequenceId +
- ", startOffsets=" + startOffsets +
- ", endOffsets=" + endOffsets +
- ", assignments=" + assignments +
- ", sentinel=" + sentinel +
- ", checkpointed=" + checkpointed +
- '}';
+ lock.lock();
+ try {
+ return "SequenceMetadata{" +
+ "sequenceName='" + sequenceName + '\'' +
+ ", sequenceId=" + sequenceId +
+ ", startOffsets=" + startOffsets +
+ ", endOffsets=" + endOffsets +
+ ", assignments=" + assignments +
+ ", sentinel=" + sentinel +
+ ", checkpointed=" + checkpointed +
+ '}';
+ }
+ finally {
+ lock.unlock();
+ }
}
-
- public Supplier<Committer> getCommitterSupplier(String topic, Map<Integer, Long> lastPersistedOffsets)
+ Supplier<Committer> getCommitterSupplier(String topic, Map<Integer, Long> lastPersistedOffsets)
{
// Set up committer.
return () ->
@@ -2171,28 +2257,40 @@ public String toString()
@Override
public Object getMetadata()
{
- Preconditions.checkState(
- assignments.isEmpty(),
- "This committer can be used only once all the records till offsets [%s] have been consumed, also make sure to call updateAssignments before using this committer",
- endOffsets
- );
+ lock.lock();
- // merge endOffsets for this sequence with globally lastPersistedOffsets
- // This is done because this committer would be persisting only sub set of segments
- // corresponding to the current sequence. Generally, lastPersistedOffsets should already
- // cover endOffsets but just to be sure take max of offsets and persist that
- for (Map.Entry<Integer, Long> partitionOffset : endOffsets.entrySet()) {
- lastPersistedOffsets.put(partitionOffset.getKey(), Math.max(
- partitionOffset.getValue(),
- lastPersistedOffsets.getOrDefault(partitionOffset.getKey(), 0L)
- ));
- }
+ try {
+ Preconditions.checkState(
+ assignments.isEmpty(),
+ "This committer can be used only once all the records till offsets [%s] have been consumed, also make"
+ + " sure to call updateAssignments before using this committer",
+ endOffsets
+ );
- // Publish metadata can be different from persist metadata as we are going to publish only
- // subset of segments
- return ImmutableMap.of(METADATA_NEXT_PARTITIONS, new KafkaPartitions(topic, lastPersistedOffsets),
- METADATA_PUBLISH_PARTITIONS, new KafkaPartitions(topic, endOffsets)
- );
+ // merge endOffsets for this sequence with globally lastPersistedOffsets
+ // This is done because this committer would be persisting only sub set of segments
+ // corresponding to the current sequence. Generally, lastPersistedOffsets should already
+ // cover endOffsets but just to be sure take max of offsets and persist that
+ for (Map.Entry<Integer, Long> partitionOffset : endOffsets.entrySet()) {
+ lastPersistedOffsets.put(
+ partitionOffset.getKey(),
+ Math.max(
+ partitionOffset.getValue(),
+ lastPersistedOffsets.getOrDefault(partitionOffset.getKey(), 0L)
+ )
+ );
+ }
+
+ // Publish metadata can be different from persist metadata as we are going to publish only
+ // subset of segments
+ return ImmutableMap.of(
+ METADATA_NEXT_PARTITIONS, new KafkaPartitions(topic, lastPersistedOffsets),
+ METADATA_PUBLISH_PARTITIONS, new KafkaPartitions(topic, endOffsets)
+ );
+ }
+ finally {
+ lock.unlock();
+ }
}
@Override
@@ -2203,11 +2301,11 @@ public void run()
};
}
- public TransactionalSegmentPublisher getPublisher(TaskToolbox toolbox, boolean useTransaction)
+ TransactionalSegmentPublisher createPublisher(TaskToolbox toolbox, boolean useTransaction)
{
return (segments, commitMetadata) -> {
final KafkaPartitions finalPartitions = toolbox.getObjectMapper().convertValue(
- ((Map) commitMetadata).get(METADATA_PUBLISH_PARTITIONS),
+ ((Map) Preconditions.checkNotNull(commitMetadata, "commitMetadata")).get(METADATA_PUBLISH_PARTITIONS),
KafkaPartitions.class
);
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClient.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClient.java
index 30a06de8c17..1c209805505 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClient.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClient.java
@@ -29,22 +29,22 @@
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.http.client.HttpClient;
-import com.metamx.http.client.Request;
-import com.metamx.http.client.response.FullResponseHandler;
-import com.metamx.http.client.response.FullResponseHolder;
+import io.druid.indexer.TaskLocation;
import io.druid.indexing.common.RetryPolicy;
import io.druid.indexing.common.RetryPolicyConfig;
import io.druid.indexing.common.RetryPolicyFactory;
import io.druid.indexing.common.TaskInfoProvider;
-import io.druid.indexer.TaskLocation;
import io.druid.indexing.common.TaskStatus;
import io.druid.java.util.common.IAE;
import io.druid.java.util.common.IOE;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.concurrent.Execs;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.http.client.HttpClient;
+import io.druid.java.util.http.client.Request;
+import io.druid.java.util.http.client.response.FullResponseHandler;
+import io.druid.java.util.http.client.response.FullResponseHolder;
import io.druid.segment.realtime.firehose.ChatHandlerResource;
import org.jboss.netty.channel.ChannelException;
import org.jboss.netty.handler.codec.http.HttpMethod;
@@ -166,19 +166,14 @@ public boolean resume(final String id)
public Map<Integer, Long> pause(final String id)
{
- return pause(id, 0);
- }
-
- public Map<Integer, Long> pause(final String id, final long timeout)
- {
- log.debug("Pause task[%s] timeout[%d]", id, timeout);
+ log.debug("Pause task[%s]", id);
try {
final FullResponseHolder response = submitRequest(
id,
HttpMethod.POST,
"pause",
- timeout > 0 ? StringUtils.format("timeout=%d", timeout) : null,
+ null,
true
);
@@ -320,18 +315,17 @@ public DateTime getStartTime(final String id)
public boolean setEndOffsets(
final String id,
final Map<Integer, Long> endOffsets,
- final boolean resume,
final boolean finalize
)
{
- log.debug("SetEndOffsets task[%s] endOffsets[%s] resume[%s] finalize[%s]", id, endOffsets, resume, finalize);
+ log.debug("SetEndOffsets task[%s] endOffsets[%s] finalize[%s]", id, endOffsets, finalize);
try {
final FullResponseHolder response = submitRequest(
id,
HttpMethod.POST,
"offsets/end",
- StringUtils.format("resume=%s&finish=%s", resume, finalize),
+ StringUtils.format("finish=%s", finalize),
jsonMapper.writeValueAsBytes(endOffsets),
true
);
@@ -374,11 +368,6 @@ public Boolean call() throws Exception
}
public ListenableFuture<Map<Integer, Long>> pauseAsync(final String id)
- {
- return pauseAsync(id, 0);
- }
-
- public ListenableFuture<Map<Integer, Long>> pauseAsync(final String id, final long timeout)
{
return executorService.submit(
new Callable<Map<Integer, Long>>()
@@ -386,7 +375,7 @@ public Boolean call() throws Exception
@Override
public Map<Integer, Long> call() throws Exception
{
- return pause(id, timeout);
+ return pause(id);
}
}
);
@@ -449,7 +438,7 @@ public DateTime call() throws Exception
}
public ListenableFuture<Boolean> setEndOffsetsAsync(
- final String id, final Map<Integer, Long> endOffsets, final boolean resume, final boolean finalize
+ final String id, final Map<Integer, Long> endOffsets, final boolean finalize
)
{
return executorService.submit(
@@ -458,7 +447,7 @@ public DateTime call() throws Exception
@Override
public Boolean call() throws Exception
{
- return setEndOffsets(id, endOffsets, resume, finalize);
+ return setEndOffsets(id, endOffsets, finalize);
}
}
);
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClientFactory.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClientFactory.java
index 86939264200..da4d8c369f9 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClientFactory.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/KafkaIndexTaskClientFactory.java
@@ -21,7 +21,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.inject.Inject;
-import com.metamx.http.client.HttpClient;
+import io.druid.java.util.http.client.HttpClient;
import io.druid.guice.annotations.EscalatedGlobal;
import io.druid.guice.annotations.Json;
import io.druid.indexing.common.TaskInfoProvider;
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisor.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisor.java
index d0b8ea55c24..cb3352d9402 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisor.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisor.java
@@ -43,11 +43,8 @@
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.emitter.service.ServiceMetricEvent;
-import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexer.TaskLocation;
+import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexing.common.TaskStatus;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.common.task.TaskResource;
@@ -74,6 +71,9 @@
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.emitter.EmittingLogger;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.metadata.EntryExistsException;
import io.druid.server.metrics.DruidMonitorSchedulerConfig;
import org.apache.commons.codec.digest.DigestUtils;
@@ -158,7 +158,7 @@
DateTime completionTimeout; // is set after signalTasksToFinish(); if not done by timeout, take corrective action
final TreeMap<Integer, Map<Integer, Long>> sequenceOffsets = new TreeMap<>();
- public TaskGroup(
+ TaskGroup(
ImmutableMap<Integer, Long> partitionOffsets,
Optional<DateTime> minimumMessageTime,
Optional<DateTime> maximumMessageTime
@@ -170,7 +170,7 @@ public TaskGroup(
this.sequenceOffsets.put(0, partitionOffsets);
}
- public int addNewCheckpoint(Map<Integer, Long> checkpoint)
+ int addNewCheckpoint(Map<Integer, Long> checkpoint)
{
sequenceOffsets.put(sequenceOffsets.lastKey() + 1, checkpoint);
return sequenceOffsets.lastKey();
@@ -211,9 +211,6 @@ public int addNewCheckpoint(Map<Integer, Long> checkpoint)
private final ConcurrentHashMap<Integer, ConcurrentHashMap<Integer, Long>> partitionGroups = new ConcurrentHashMap<>();
// --------------------------------------------------------
- // BaseSequenceName -> TaskGroup
- private final ConcurrentHashMap<String, TaskGroup> sequenceTaskGroup = new ConcurrentHashMap<>();
-
private final TaskStorage taskStorage;
private final TaskMaster taskMaster;
private final IndexerMetadataStorageCoordinator indexerMetadataStorageCoordinator;
@@ -493,13 +490,9 @@ public void reset(DataSourceMetadata dataSourceMetadata)
}
@Override
- public void checkpoint(
- String sequenceName,
- DataSourceMetadata previousCheckpoint,
- DataSourceMetadata currentCheckpoint
- )
+ public void checkpoint(int taskGroupId, DataSourceMetadata previousCheckpoint, DataSourceMetadata currentCheckpoint)
{
- Preconditions.checkNotNull(sequenceName, "Cannot checkpoint without a sequence name");
+ Preconditions.checkNotNull(previousCheckpoint, "previousCheckpoint");
Preconditions.checkNotNull(currentCheckpoint, "current checkpoint cannot be null");
Preconditions.checkArgument(
ioConfig.getTopic()
@@ -510,12 +503,14 @@ public void checkpoint(
((KafkaDataSourceMetadata) currentCheckpoint).getKafkaPartitions().getTopic()
);
- log.info("Checkpointing [%s] for sequence [%s]", currentCheckpoint, sequenceName);
- notices.add(new CheckpointNotice(
- sequenceName,
- (KafkaDataSourceMetadata) previousCheckpoint,
- (KafkaDataSourceMetadata) currentCheckpoint
- ));
+ log.info("Checkpointing [%s] for taskGroup [%s]", currentCheckpoint, taskGroupId);
+ notices.add(
+ new CheckpointNotice(
+ taskGroupId,
+ (KafkaDataSourceMetadata) previousCheckpoint,
+ (KafkaDataSourceMetadata) currentCheckpoint
+ )
+ );
}
public void possiblyRegisterListener()
@@ -617,17 +612,17 @@ public void handle()
private class CheckpointNotice implements Notice
{
- final String sequenceName;
+ final int taskGroupId;
final KafkaDataSourceMetadata previousCheckpoint;
final KafkaDataSourceMetadata currentCheckpoint;
CheckpointNotice(
- String sequenceName,
+ int taskGroupId,
KafkaDataSourceMetadata previousCheckpoint,
KafkaDataSourceMetadata currentCheckpoint
)
{
- this.sequenceName = sequenceName;
+ this.taskGroupId = taskGroupId;
this.previousCheckpoint = previousCheckpoint;
this.currentCheckpoint = currentCheckpoint;
}
@@ -638,17 +633,12 @@ public void handle() throws ExecutionException, InterruptedException, TimeoutExc
// check for consistency
// if already received request for this sequenceName and dataSourceMetadata combination then return
- Preconditions.checkNotNull(
- sequenceTaskGroup.get(sequenceName),
- "WTH?! cannot find task group for this sequence [%s], sequencesTaskGroup map [%s], taskGroups [%s]",
- sequenceName,
- sequenceTaskGroup,
- taskGroups
- );
- final TreeMap<Integer, Map<Integer, Long>> checkpoints = sequenceTaskGroup.get(sequenceName).sequenceOffsets;
+ final TaskGroup taskGroup = taskGroups.get(taskGroupId);
+
+ if (isValidTaskGroup(taskGroup)) {
+ final TreeMap<Integer, Map<Integer, Long>> checkpoints = taskGroup.sequenceOffsets;
- // check validity of previousCheckpoint if it is not null
- if (previousCheckpoint != null) {
+ // check validity of previousCheckpoint
int index = checkpoints.size();
for (int sequenceId : checkpoints.descendingKeySet()) {
Map<Integer, Long> checkpoint = checkpoints.get(sequenceId);
@@ -665,26 +655,39 @@ public void handle() throws ExecutionException, InterruptedException, TimeoutExc
log.info("Already checkpointed with offsets [%s]", checkpoints.lastEntry().getValue());
return;
}
- } else {
- // There cannot be more than one checkpoint when previous checkpoint is null
- // as when the task starts they are sent existing checkpoints
- Preconditions.checkState(
- checkpoints.size() <= 1,
- "Got checkpoint request with null as previous check point, however found more than one checkpoints in metadata store"
+ final int taskGroupId = getTaskGroupIdForPartition(
+ currentCheckpoint.getKafkaPartitions()
+ .getPartitionOffsetMap()
+ .keySet()
+ .iterator()
+ .next()
);
- if (checkpoints.size() == 1) {
- log.info("Already checkpointed with dataSourceMetadata [%s]", checkpoints.get(0));
- return;
+ final Map<Integer, Long> newCheckpoint = checkpointTaskGroup(taskGroupId, false).get();
+ taskGroups.get(taskGroupId).addNewCheckpoint(newCheckpoint);
+ log.info("Handled checkpoint notice, new checkpoint is [%s] for taskGroup [%s]", newCheckpoint, taskGroupId);
+ }
+ }
+
+ private boolean isValidTaskGroup(@Nullable TaskGroup taskGroup)
+ {
+ if (taskGroup == null) {
+ // taskGroup might be in pendingCompletionTaskGroups or partitionGroups
+ if (pendingCompletionTaskGroups.containsKey(taskGroupId)) {
+ log.warn(
+ "Ignoring checkpoint request because taskGroup[%d] has already stopped indexing and is waiting for "
+ + "publishing segments",
+ taskGroupId
+ );
+ return false;
+ } else if (partitionGroups.containsKey(taskGroupId)) {
+ log.warn("Ignoring checkpoint request because taskGroup[%d] is inactive", taskGroupId);
+ return false;
+ } else {
+ throw new ISE("WTH?! cannot find taskGroup [%s] among all taskGroups [%s]", taskGroupId, taskGroups);
}
}
- final int taskGroupId = getTaskGroupIdForPartition(currentCheckpoint.getKafkaPartitions()
- .getPartitionOffsetMap()
- .keySet()
- .iterator()
- .next());
- final Map<Integer, Long> newCheckpoint = checkpointTaskGroup(taskGroupId, false).get();
- sequenceTaskGroup.get(sequenceName).addNewCheckpoint(newCheckpoint);
- log.info("Handled checkpoint notice, new checkpoint is [%s] for sequence [%s]", newCheckpoint, sequenceName);
+
+ return true;
}
}
@@ -698,7 +701,6 @@ void resetInternal(DataSourceMetadata dataSourceMetadata)
taskGroups.values().forEach(this::killTasksInGroup);
taskGroups.clear();
partitionGroups.clear();
- sequenceTaskGroup.clear();
} else if (!(dataSourceMetadata instanceof KafkaDataSourceMetadata)) {
throw new IAE("Expected KafkaDataSourceMetadata but found instance of [%s]", dataSourceMetadata.getClass());
} else {
@@ -758,7 +760,6 @@ void resetInternal(DataSourceMetadata dataSourceMetadata)
resetKafkaMetadata.getKafkaPartitions().getPartitionOffsetMap().keySet().forEach(partition -> {
final int groupId = getTaskGroupIdForPartition(partition);
killTaskGroupForPartitions(ImmutableSet.of(partition));
- sequenceTaskGroup.remove(generateSequenceName(groupId));
taskGroups.remove(groupId);
partitionGroups.get(groupId).replaceAll((partitionId, offset) -> NOT_SET);
});
@@ -867,12 +868,13 @@ String generateSequenceName(
}
@VisibleForTesting
- String generateSequenceName(int groupId)
+ String generateSequenceName(TaskGroup taskGroup)
{
+ Preconditions.checkNotNull(taskGroup, "taskGroup cannot be null");
return generateSequenceName(
- taskGroups.get(groupId).partitionOffsets,
- taskGroups.get(groupId).minimumMessageTime,
- taskGroups.get(groupId).maximumMessageTime
+ taskGroup.partitionOffsets,
+ taskGroup.minimumMessageTime,
+ taskGroup.maximumMessageTime
);
}
@@ -934,9 +936,10 @@ private void updatePartitionDataFromKafka()
for (int partition = 0; partition < numPartitions; partition++) {
int taskGroupId = getTaskGroupIdForPartition(partition);
- partitionGroups.putIfAbsent(taskGroupId, new ConcurrentHashMap<Integer, Long>());
-
- ConcurrentHashMap<Integer, Long> partitionMap = partitionGroups.get(taskGroupId);
+ ConcurrentHashMap<Integer, Long> partitionMap = partitionGroups.computeIfAbsent(
+ taskGroupId,
+ k -> new ConcurrentHashMap<>()
+ );
// The starting offset for a new partition in [partitionGroups] is initially set to NOT_SET; when a new task group
// is created and is assigned partitions, if the offset in [partitionGroups] is NOT_SET it will take the starting
@@ -1066,22 +1069,21 @@ public Boolean apply(KafkaIndexTask.Status status)
}
return false;
} else {
- if (taskGroups.putIfAbsent(
+ final TaskGroup taskGroup = taskGroups.computeIfAbsent(
taskGroupId,
- new TaskGroup(
- ImmutableMap.copyOf(
- kafkaTask.getIOConfig()
- .getStartPartitions()
- .getPartitionOffsetMap()
- ), kafkaTask.getIOConfig().getMinimumMessageTime(),
- kafkaTask.getIOConfig().getMaximumMessageTime()
- )
- ) == null) {
- sequenceTaskGroup.put(generateSequenceName(taskGroupId), taskGroups.get(taskGroupId));
- log.info("Created new task group [%d]", taskGroupId);
- }
+ k -> {
+ log.info("Creating a new task group for taskGroupId[%d]", taskGroupId);
+ return new TaskGroup(
+ ImmutableMap.copyOf(
+ kafkaTask.getIOConfig().getStartPartitions().getPartitionOffsetMap()
+ ),
+ kafkaTask.getIOConfig().getMinimumMessageTime(),
+ kafkaTask.getIOConfig().getMaximumMessageTime()
+ );
+ }
+ );
taskGroupsToVerify.add(taskGroupId);
- taskGroups.get(taskGroupId).tasks.putIfAbsent(taskId, new TaskData());
+ taskGroup.tasks.putIfAbsent(taskId, new TaskData());
}
}
return true;
@@ -1234,7 +1236,6 @@ public void onFailure(Throwable t)
// killing all tasks or no task left in the group ?
// clear state about the taskgroup so that get latest offset information is fetched from metadata store
log.warn("Clearing task group [%d] information as no valid tasks left the group", groupId);
- sequenceTaskGroup.remove(generateSequenceName(groupId));
taskGroups.remove(groupId);
partitionGroups.get(groupId).replaceAll((partition, offset) -> NOT_SET);
}
@@ -1259,9 +1260,10 @@ private void addDiscoveredTaskToPendingCompletionTaskGroups(
Map<Integer, Long> startingPartitions
)
{
- pendingCompletionTaskGroups.putIfAbsent(groupId, Lists.<TaskGroup>newCopyOnWriteArrayList());
-
- CopyOnWriteArrayList<TaskGroup> taskGroupList = pendingCompletionTaskGroups.get(groupId);
+ final CopyOnWriteArrayList<TaskGroup> taskGroupList = pendingCompletionTaskGroups.computeIfAbsent(
+ groupId,
+ k -> new CopyOnWriteArrayList<>()
+ );
for (TaskGroup taskGroup : taskGroupList) {
if (taskGroup.partitionOffsets.equals(startingPartitions)) {
if (taskGroup.tasks.putIfAbsent(taskId, new TaskData()) == null) {
@@ -1389,8 +1391,7 @@ private void checkTaskDuration() throws InterruptedException, ExecutionException
if (endOffsets != null) {
// set a timeout and put this group in pendingCompletionTaskGroups so that it can be monitored for completion
group.completionTimeout = DateTimes.nowUtc().plus(ioConfig.getCompletionTimeout());
- pendingCompletionTaskGroups.putIfAbsent(groupId, Lists.<TaskGroup>newCopyOnWriteArrayList());
- pendingCompletionTaskGroups.get(groupId).add(group);
+ pendingCompletionTaskGroups.computeIfAbsent(groupId, k -> new CopyOnWriteArrayList<>()).add(group);
// set endOffsets as the next startOffsets
for (Map.Entry<Integer, Long> entry : endOffsets.entrySet()) {
@@ -1410,7 +1411,6 @@ private void checkTaskDuration() throws InterruptedException, ExecutionException
partitionGroups.get(groupId).replaceAll((partition, offset) -> NOT_SET);
}
- sequenceTaskGroup.remove(generateSequenceName(groupId));
// remove this task group from the list of current task groups now that it has been handled
taskGroups.remove(groupId);
}
@@ -1434,7 +1434,8 @@ private void checkTaskDuration() throws InterruptedException, ExecutionException
// metadata store (which will have advanced if we succeeded in publishing and will remain the same if publishing
// failed and we need to re-ingest)
return Futures.transform(
- stopTasksInGroup(taskGroup), new Function<Object, Map<Integer, Long>>()
+ stopTasksInGroup(taskGroup),
+ new Function<Object, Map<Integer, Long>>()
{
@Nullable
@Override
@@ -1505,17 +1506,16 @@ private void checkTaskDuration() throws InterruptedException, ExecutionException
if (endOffsets.equals(taskGroup.sequenceOffsets.lastEntry().getValue())) {
log.warn(
- "Not adding checkpoint [%s] as its same as the start offsets [%s] of latest sequence for the task group [%d]",
+ "Checkpoint [%s] is same as the start offsets [%s] of latest sequence for the task group [%d]",
endOffsets,
taskGroup.sequenceOffsets.lastEntry().getValue(),
groupId
);
- return endOffsets;
}
log.info("Setting endOffsets for tasks in taskGroup [%d] to %s and resuming", groupId, endOffsets);
for (final String taskId : setEndOffsetTaskIds) {
- setEndOffsetFutures.add(taskClient.setEndOffsetsAsync(taskId, endOffsets, true, finalize));
+ setEndOffsetFutures.add(taskClient.setEndOffsetsAsync(taskId, endOffsets, finalize));
}
List<Boolean> results = Futures.successfulAsList(setEndOffsetFutures)
@@ -1604,16 +1604,15 @@ private void checkPendingCompletionTasks() throws ExecutionException, Interrupte
log.warn("All tasks in group [%d] failed to publish, killing all tasks for these partitions", groupId);
} else {
log.makeAlert(
- "No task in [%s] succeeded before the completion timeout elapsed [%s]!",
+ "No task in [%s] for taskGroup [%d] succeeded before the completion timeout elapsed [%s]!",
group.taskIds(),
+ groupId,
ioConfig.getCompletionTimeout()
).emit();
}
// reset partitions offsets for this task group so that they will be re-read from metadata storage
partitionGroups.get(groupId).replaceAll((partition, offset) -> NOT_SET);
- sequenceTaskGroup.remove(generateSequenceName(groupId));
-
// kill all the tasks in this pending completion group
killTasksInGroup(group);
// set a flag so the other pending completion groups for this set of partitions will also stop
@@ -1673,7 +1672,6 @@ private void checkCurrentTaskState() throws ExecutionException, InterruptedExcep
// be recreated with the next set of offsets
if (taskData.status.isSuccess()) {
futures.add(stopTasksInGroup(taskGroup));
- sequenceTaskGroup.remove(generateSequenceName(groupId));
iTaskGroups.remove();
break;
}
@@ -1706,15 +1704,15 @@ void createNewTasks() throws JsonProcessingException
DateTimes.nowUtc().plus(ioConfig.getTaskDuration()).plus(ioConfig.getEarlyMessageRejectionPeriod().get())
) : Optional.<DateTime>absent());
+ final TaskGroup taskGroup = new TaskGroup(
+ generateStartingOffsetsForPartitionGroup(groupId),
+ minimumMessageTime,
+ maximumMessageTime
+ );
taskGroups.put(
groupId,
- new TaskGroup(
- generateStartingOffsetsForPartitionGroup(groupId),
- minimumMessageTime,
- maximumMessageTime
- )
+ taskGroup
);
- sequenceTaskGroup.put(generateSequenceName(groupId), taskGroups.get(groupId));
}
}
@@ -1749,20 +1747,20 @@ private void createKafkaTasksForGroup(int groupId, int replicas) throws JsonProc
for (Integer partition : startPartitions.keySet()) {
endPartitions.put(partition, Long.MAX_VALUE);
}
-
- String sequenceName = generateSequenceName(groupId);
+ TaskGroup group = taskGroups.get(groupId);
+ String sequenceName = generateSequenceName(group);
Map<String, String> consumerProperties = Maps.newHashMap(ioConfig.getConsumerProperties());
DateTime minimumMessageTime = taskGroups.get(groupId).minimumMessageTime.orNull();
DateTime maximumMessageTime = taskGroups.get(groupId).maximumMessageTime.orNull();
KafkaIOConfig kafkaIOConfig = new KafkaIOConfig(
+ groupId,
sequenceName,
new KafkaPartitions(ioConfig.getTopic(), startPartitions),
new KafkaPartitions(ioConfig.getTopic(), endPartitions),
consumerProperties,
true,
- false,
minimumMessageTime,
maximumMessageTime,
ioConfig.isSkipOffsetGaps()
@@ -1911,7 +1909,7 @@ private boolean isTaskCurrent(int taskGroupId, String taskId)
String taskSequenceName = ((KafkaIndexTask) taskOptional.get()).getIOConfig().getBaseSequenceName();
if (taskGroups.get(taskGroupId) != null) {
- return generateSequenceName(taskGroupId).equals(taskSequenceName);
+ return generateSequenceName(taskGroups.get(taskGroupId)).equals(taskSequenceName);
} else {
return generateSequenceName(
((KafkaIndexTask) taskOptional.get()).getIOConfig()
@@ -1923,7 +1921,7 @@ private boolean isTaskCurrent(int taskGroupId, String taskId)
}
}
- private ListenableFuture<?> stopTasksInGroup(TaskGroup taskGroup)
+ private ListenableFuture<?> stopTasksInGroup(@Nullable TaskGroup taskGroup)
{
if (taskGroup == null) {
return Futures.immediateFuture(null);
@@ -2195,4 +2193,26 @@ Runnable updateCurrentAndLatestOffsets()
}
};
}
+
+ @VisibleForTesting
+ @Nullable
+ TaskGroup removeTaskGroup(int taskGroupId)
+ {
+ return taskGroups.remove(taskGroupId);
+ }
+
+ @VisibleForTesting
+ void moveTaskGroupToPendingCompletion(int taskGroupId)
+ {
+ final TaskGroup taskGroup = taskGroups.remove(taskGroupId);
+ if (taskGroup != null) {
+ pendingCompletionTaskGroups.computeIfAbsent(taskGroupId, k -> new CopyOnWriteArrayList<>()).add(taskGroup);
+ }
+ }
+
+ @VisibleForTesting
+ int getNoticesQueueSize()
+ {
+ return notices.size();
+ }
}
diff --git a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorSpec.java b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorSpec.java
index d11709ecc62..2b540e53710 100644
--- a/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorSpec.java
+++ b/extensions-core/kafka-indexing-service/src/main/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorSpec.java
@@ -25,7 +25,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
-import com.metamx.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceEmitter;
import io.druid.guice.annotations.Json;
import io.druid.indexing.kafka.KafkaIndexTaskClientFactory;
import io.druid.indexing.overlord.IndexerMetadataStorageCoordinator;
diff --git a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIOConfigTest.java b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIOConfigTest.java
index 49a9b90033d..91335ab8cee 100644
--- a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIOConfigTest.java
+++ b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIOConfigTest.java
@@ -50,6 +50,7 @@ public void testSerdeWithDefaults() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
@@ -71,8 +72,7 @@ public void testSerdeWithDefaults() throws Exception
Assert.assertEquals("mytopic", config.getEndPartitions().getTopic());
Assert.assertEquals(ImmutableMap.of(0, 15L, 1, 200L), config.getEndPartitions().getPartitionOffsetMap());
Assert.assertEquals(ImmutableMap.of("bootstrap.servers", "localhost:9092"), config.getConsumerProperties());
- Assert.assertEquals(true, config.isUseTransaction());
- Assert.assertEquals(false, config.isPauseAfterRead());
+ Assert.assertTrue(config.isUseTransaction());
Assert.assertFalse("minimumMessageTime", config.getMinimumMessageTime().isPresent());
Assert.assertFalse("maximumMessageTime", config.getMaximumMessageTime().isPresent());
Assert.assertFalse("skipOffsetGaps", config.isSkipOffsetGaps());
@@ -83,12 +83,12 @@ public void testSerdeWithNonDefaults() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\",\n"
+ " \"skipOffsetGaps\": true\n"
@@ -109,8 +109,7 @@ public void testSerdeWithNonDefaults() throws Exception
Assert.assertEquals("mytopic", config.getEndPartitions().getTopic());
Assert.assertEquals(ImmutableMap.of(0, 15L, 1, 200L), config.getEndPartitions().getPartitionOffsetMap());
Assert.assertEquals(ImmutableMap.of("bootstrap.servers", "localhost:9092"), config.getConsumerProperties());
- Assert.assertEquals(false, config.isUseTransaction());
- Assert.assertEquals(true, config.isPauseAfterRead());
+ Assert.assertFalse(config.isUseTransaction());
Assert.assertEquals(DateTimes.of("2016-05-31T12:00Z"), config.getMinimumMessageTime().get());
Assert.assertEquals(DateTimes.of("2016-05-31T14:00Z"), config.getMaximumMessageTime().get());
Assert.assertTrue("skipOffsetGaps", config.isSkipOffsetGaps());
@@ -121,11 +120,11 @@ public void testBaseSequenceNameRequired() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -141,11 +140,11 @@ public void testStartPartitionsRequired() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -161,11 +160,11 @@ public void testEndPartitionsRequired() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -181,11 +180,11 @@ public void testConsumerPropertiesRequired() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -201,12 +200,12 @@ public void testStartAndEndTopicMatch() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"other\", \"partitionOffsetMap\" : {\"0\":15, \"1\":200}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -222,12 +221,12 @@ public void testStartAndEndPartitionSetMatch() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
@@ -243,12 +242,12 @@ public void testEndOffsetGreaterThanStart() throws Exception
{
String jsonStr = "{\n"
+ " \"type\": \"kafka\",\n"
+ + " \"taskGroupId\": 0,\n"
+ " \"baseSequenceName\": \"my-sequence-name\",\n"
+ " \"startPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":1, \"1\":10}},\n"
+ " \"endPartitions\": {\"topic\":\"mytopic\", \"partitionOffsetMap\" : {\"0\":15, \"1\":2}},\n"
+ " \"consumerProperties\": {\"bootstrap.servers\":\"localhost:9092\"},\n"
+ " \"useTransaction\": false,\n"
- + " \"pauseAfterRead\": true,\n"
+ " \"minimumMessageTime\": \"2016-05-31T12:00Z\",\n"
+ " \"maximumMessageTime\": \"2016-05-31T14:00Z\"\n"
+ "}";
diff --git a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskClientTest.java b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskClientTest.java
index 8d328aadbad..b63563b8eda 100644
--- a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskClientTest.java
+++ b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskClientTest.java
@@ -27,17 +27,17 @@
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import com.metamx.http.client.HttpClient;
-import com.metamx.http.client.Request;
-import com.metamx.http.client.response.FullResponseHandler;
-import com.metamx.http.client.response.FullResponseHolder;
-import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexer.TaskLocation;
+import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexing.common.TaskStatus;
import io.druid.jackson.DefaultObjectMapper;
import io.druid.java.util.common.DateTimes;
import io.druid.java.util.common.IAE;
import io.druid.java.util.common.StringUtils;
+import io.druid.java.util.http.client.HttpClient;
+import io.druid.java.util.http.client.Request;
+import io.druid.java.util.http.client.response.FullResponseHandler;
+import io.druid.java.util.http.client.response.FullResponseHolder;
import org.easymock.Capture;
import org.easymock.CaptureType;
import org.easymock.EasyMockSupport;
@@ -56,6 +56,7 @@
import java.io.IOException;
import java.net.URL;
+import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -139,13 +140,13 @@ public void testNoTaskLocation() throws Exception
Assert.assertEquals(false, client.stop(TEST_ID, true));
Assert.assertEquals(false, client.resume(TEST_ID));
Assert.assertEquals(ImmutableMap.of(), client.pause(TEST_ID));
- Assert.assertEquals(ImmutableMap.of(), client.pause(TEST_ID, 10));
+ Assert.assertEquals(ImmutableMap.of(), client.pause(TEST_ID));
Assert.assertEquals(KafkaIndexTask.Status.NOT_STARTED, client.getStatus(TEST_ID));
Assert.assertEquals(null, client.getStartTime(TEST_ID));
Assert.assertEquals(ImmutableMap.of(), client.getCurrentOffsets(TEST_ID, true));
Assert.assertEquals(ImmutableMap.of(), client.getEndOffsets(TEST_ID));
- Assert.assertEquals(false, client.setEndOffsets(TEST_ID, ImmutableMap.<Integer, Long>of(), false, true));
- Assert.assertEquals(false, client.setEndOffsets(TEST_ID, ImmutableMap.<Integer, Long>of(), true, true));
+ Assert.assertEquals(false, client.setEndOffsets(TEST_ID, Collections.emptyMap(), true));
+ Assert.assertEquals(false, client.setEndOffsets(TEST_ID, Collections.emptyMap(), true));
verifyAll();
}
@@ -431,33 +432,6 @@ public void testPause() throws Exception
Assert.assertEquals(10, (long) results.get(1));
}
- @Test
- public void testPauseWithTimeout() throws Exception
- {
- Capture<Request> captured = Capture.newInstance();
- expect(responseHolder.getStatus()).andReturn(HttpResponseStatus.OK).times(2);
- expect(responseHolder.getContent()).andReturn("{\"0\":1, \"1\":10}").anyTimes();
- expect(httpClient.go(capture(captured), anyObject(FullResponseHandler.class), eq(TEST_HTTP_TIMEOUT))).andReturn(
- Futures.immediateFuture(responseHolder)
- );
- replayAll();
-
- Map<Integer, Long> results = client.pause(TEST_ID, 101);
- verifyAll();
-
- Request request = captured.getValue();
- Assert.assertEquals(HttpMethod.POST, request.getMethod());
- Assert.assertEquals(
- new URL("http://test-host:1234/druid/worker/v1/chat/test-id/pause?timeout=101"),
- request.getUrl()
- );
- Assert.assertTrue(request.getHeaders().get("X-Druid-Task-Id").contains("test-id"));
-
- Assert.assertEquals(2, results.size());
- Assert.assertEquals(1, (long) results.get(0));
- Assert.assertEquals(10, (long) results.get(1));
- }
-
@Test
public void testPauseWithSubsequentGetOffsets() throws Exception
{
@@ -544,13 +518,13 @@ public void testSetEndOffsets() throws Exception
);
replayAll();
- client.setEndOffsets(TEST_ID, endOffsets, false, true);
+ client.setEndOffsets(TEST_ID, endOffsets, true);
verifyAll();
Request request = captured.getValue();
Assert.assertEquals(HttpMethod.POST, request.getMethod());
Assert.assertEquals(
- new URL("http://test-host:1234/druid/worker/v1/chat/test-id/offsets/end?resume=false&finish=true"),
+ new URL("http://test-host:1234/druid/worker/v1/chat/test-id/offsets/end?finish=true"),
request.getUrl()
);
Assert.assertTrue(request.getHeaders().get("X-Druid-Task-Id").contains("test-id"));
@@ -569,13 +543,13 @@ public void testSetEndOffsetsAndResume() throws Exception
);
replayAll();
- client.setEndOffsets(TEST_ID, endOffsets, true, true);
+ client.setEndOffsets(TEST_ID, endOffsets, true);
verifyAll();
Request request = captured.getValue();
Assert.assertEquals(HttpMethod.POST, request.getMethod());
Assert.assertEquals(
- new URL("http://test-host:1234/druid/worker/v1/chat/test-id/offsets/end?resume=true&finish=true"),
+ new URL("http://test-host:1234/druid/worker/v1/chat/test-id/offsets/end?finish=true"),
request.getUrl()
);
Assert.assertTrue(request.getHeaders().get("X-Druid-Task-Id").contains("test-id"));
@@ -723,39 +697,6 @@ public void testPauseAsync() throws Exception
}
}
- @Test
- public void testPauseAsyncWithTimeout() throws Exception
- {
- final int numRequests = TEST_IDS.size();
- Capture<Request> captured = Capture.newInstance(CaptureType.ALL);
- expect(responseHolder.getStatus()).andReturn(HttpResponseStatus.OK).anyTimes();
- expect(responseHolder.getContent()).andReturn("{\"0\":\"1\"}").anyTimes();
- expect(httpClient.go(capture(captured), anyObject(FullResponseHandler.class), eq(TEST_HTTP_TIMEOUT))).andReturn(
- Futures.immediateFuture(responseHolder)
- ).times(numRequests);
- replayAll();
-
- List<URL> expectedUrls = Lists.newArrayList();
- List<ListenableFuture<Map<Integer, Long>>> futures = Lists.newArrayList();
- for (String testId : TEST_IDS) {
- expectedUrls.add(new URL(StringUtils.format(URL_FORMATTER, TEST_HOST, TEST_PORT, testId, "pause?timeout=9")));
- futures.add(client.pauseAsync(testId, 9));
- }
-
- List<Map<Integer, Long>> responses = Futures.allAsList(futures).get();
-
- verifyAll();
- List<Request> requests = captured.getValues();
-
- Assert.assertEquals(numRequests, requests.size());
- Assert.assertEquals(numRequests, responses.size());
- for (int i = 0; i < numRequests; i++) {
- Assert.assertEquals(HttpMethod.POST, requests.get(i).getMethod());
- Assert.assertTrue("unexpectedURL", expectedUrls.contains(requests.get(i).getUrl()));
- Assert.assertEquals(Maps.newLinkedHashMap(ImmutableMap.of(0, 1L)), responses.get(i));
- }
- }
-
@Test
public void testGetStatusAsync() throws Exception
{
@@ -909,9 +850,9 @@ public void testSetEndOffsetsAsync() throws Exception
TEST_HOST,
TEST_PORT,
testId,
- StringUtils.format("offsets/end?resume=%s&finish=%s", false, true)
+ StringUtils.format("offsets/end?finish=%s", true)
)));
- futures.add(client.setEndOffsetsAsync(testId, endOffsets, false, true));
+ futures.add(client.setEndOffsetsAsync(testId, endOffsets, true));
}
List<Boolean> responses = Futures.allAsList(futures).get();
@@ -950,11 +891,11 @@ public void testSetEndOffsetsAsyncWithResume() throws Exception
TEST_HOST,
TEST_PORT,
testId,
- "offsets/end?resume=true&finish=true"
+ "offsets/end?finish=true"
)
)
);
- futures.add(client.setEndOffsetsAsync(testId, endOffsets, true, true));
+ futures.add(client.setEndOffsetsAsync(testId, endOffsets, true));
}
List<Boolean> responses = Futures.allAsList(futures).get();
diff --git a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskTest.java b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskTest.java
index 298d1490f88..2a852d4a8ad 100644
--- a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskTest.java
+++ b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/KafkaIndexTaskTest.java
@@ -38,10 +38,6 @@
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
-import com.metamx.emitter.EmittingLogger;
-import com.metamx.emitter.core.NoopEmitter;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.metrics.MonitorScheduler;
import io.druid.client.cache.CacheConfig;
import io.druid.client.cache.MapCache;
import io.druid.data.input.impl.DimensionsSpec;
@@ -85,6 +81,10 @@
import io.druid.java.util.common.logger.Logger;
import io.druid.java.util.common.parsers.JSONPathFieldSpec;
import io.druid.java.util.common.parsers.JSONPathSpec;
+import io.druid.java.util.emitter.EmittingLogger;
+import io.druid.java.util.emitter.core.NoopEmitter;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.metrics.MonitorScheduler;
import io.druid.math.expr.ExprMacroTable;
import io.druid.metadata.DerbyMetadataStorageActionHandlerFactory;
import io.druid.metadata.EntryExistsException;
@@ -155,10 +155,12 @@
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
+import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
@@ -236,16 +238,17 @@ public KafkaIndexTaskTest(boolean isIncrementalHandoffSupported)
private static List<ProducerRecord<byte[], byte[]>> generateRecords(String topic)
{
return ImmutableList.of(
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2008", "a", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2009", "b", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2010", "c", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2011", "d", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2011", "e", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, StringUtils.toUtf8("unparseable")),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, null),
- new ProducerRecord<byte[], byte[]>(topic, 0, null, JB("2013", "f", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 1, null, JB("2012", "g", "y", 1.0f)),
- new ProducerRecord<byte[], byte[]>(topic, 1, null, JB("2011", "h", "y", 1.0f))
+ new ProducerRecord<>(topic, 0, null, JB("2008", "a", "y", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, JB("2009", "b", "y", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, JB("2010", "c", "y", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, JB("2011", "d", "y", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, JB("2011", "e", "y", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, JB("246140482-04-24T15:36:27.903Z", "x", "z", 1.0f)),
+ new ProducerRecord<>(topic, 0, null, StringUtils.toUtf8("unparseable")),
+ new ProducerRecord<>(topic, 0, null, null),
+ new ProducerRecord<>(topic, 0, null, JB("2013", "f", "y", 1.0f)),
+ new ProducerRecord<>(topic, 1, null, JB("2012", "g", "y", 1.0f)),
+ new ProducerRecord<>(topic, 1, null, JB("2011", "h", "y", 1.0f))
);
}
@@ -342,12 +345,12 @@ public void testRunAfterDataInserted() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -384,12 +387,12 @@ public void testRunBeforeDataInserted() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -456,16 +459,16 @@ public void testIncrementalHandOff() throws Exception
// of events fetched across two partitions from Kafka
final KafkaPartitions checkpoint1 = new KafkaPartitions(topic, ImmutableMap.of(0, 5L, 1, 0L));
final KafkaPartitions checkpoint2 = new KafkaPartitions(topic, ImmutableMap.of(0, 4L, 1, 2L));
- final KafkaPartitions endPartitions = new KafkaPartitions(topic, ImmutableMap.of(0, 8L, 1, 2L));
+ final KafkaPartitions endPartitions = new KafkaPartitions(topic, ImmutableMap.of(0, 9L, 1, 2L));
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
baseSequenceName,
startPartitions,
endPartitions,
consumerProps,
true,
- false,
null,
null,
false
@@ -478,23 +481,25 @@ public void testIncrementalHandOff() throws Exception
final Map<Integer, Long> currentOffsets = ImmutableMap.copyOf(task.getCurrentOffsets());
Assert.assertTrue(checkpoint1.getPartitionOffsetMap().equals(currentOffsets) || checkpoint2.getPartitionOffsetMap()
.equals(currentOffsets));
- task.setEndOffsets(currentOffsets, true, false);
+ task.setEndOffsets(currentOffsets, false);
Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode());
Assert.assertEquals(1, checkpointRequestsHash.size());
- Assert.assertTrue(checkpointRequestsHash.contains(
- Objects.hash(
- DATA_SCHEMA.getDataSource(),
- baseSequenceName,
- new KafkaDataSourceMetadata(startPartitions),
- new KafkaDataSourceMetadata(new KafkaPartitions(topic, currentOffsets))
+ Assert.assertTrue(
+ checkpointRequestsHash.contains(
+ Objects.hash(
+ DATA_SCHEMA.getDataSource(),
+ 0,
+ new KafkaDataSourceMetadata(startPartitions),
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, currentOffsets))
+ )
)
- ));
+ );
// Check metrics
Assert.assertEquals(8, task.getFireDepartmentMetrics().processed());
Assert.assertEquals(1, task.getFireDepartmentMetrics().unparseable());
- Assert.assertEquals(1, task.getFireDepartmentMetrics().thrownAway());
+ Assert.assertEquals(2, task.getFireDepartmentMetrics().thrownAway());
// Check published metadata
SegmentDescriptor desc1 = SD(task, "2008/P1D", 0);
@@ -506,7 +511,7 @@ public void testIncrementalHandOff() throws Exception
SegmentDescriptor desc7 = SD(task, "2013/P1D", 0);
Assert.assertEquals(ImmutableSet.of(desc1, desc2, desc3, desc4, desc5, desc6, desc7), publishedDescriptors());
Assert.assertEquals(
- new KafkaDataSourceMetadata(new KafkaPartitions(topic, ImmutableMap.of(0, 8L, 1, 2L))),
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, ImmutableMap.of(0, 9L, 1, 2L))),
metadataStorageCoordinator.getDataSourceMetadata(DATA_SCHEMA.getDataSource())
);
@@ -528,12 +533,12 @@ public void testRunWithMinimumMessageTime() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 0L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
DateTimes.of("2010"),
null,
false
@@ -582,12 +587,12 @@ public void testRunWithMaximumMessageTime() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 0L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
DateTimes.of("2010"),
false
@@ -646,12 +651,12 @@ public void testRunWithTransformSpec() throws Exception
)
),
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 0L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -706,12 +711,12 @@ public void testRunOnNothing() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -747,12 +752,12 @@ public void testHandoffConditionTimeoutWhenHandoffOccurs() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -799,12 +804,12 @@ public void testHandoffConditionTimeoutWhenHandoffDoesNotOccur() throws Exceptio
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -814,10 +819,7 @@ public void testHandoffConditionTimeoutWhenHandoffDoesNotOccur() throws Exceptio
final ListenableFuture<TaskStatus> future = runTask(task);
// Wait for task to exit
- Assert.assertEquals(
- isIncrementalHandoffSupported ? TaskState.SUCCESS : TaskState.FAILED,
- future.get().getStatusCode()
- );
+ Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode());
// Check metrics
Assert.assertEquals(3, task.getFireDepartmentMetrics().processed());
@@ -853,12 +855,12 @@ public void testReportParseExceptions() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 7L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -886,12 +888,12 @@ public void testRunReplicas() throws Exception
final KafkaIndexTask task1 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -900,12 +902,12 @@ public void testRunReplicas() throws Exception
final KafkaIndexTask task2 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -954,12 +956,12 @@ public void testRunConflicting() throws Exception
final KafkaIndexTask task1 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -968,12 +970,12 @@ public void testRunConflicting() throws Exception
final KafkaIndexTask task2 = createTask(
null,
new KafkaIOConfig(
+ 1,
"sequence1",
new KafkaPartitions(topic, ImmutableMap.of(0, 3L)),
- new KafkaPartitions(topic, ImmutableMap.of(0, 8L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, 9L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1001,7 +1003,7 @@ public void testRunConflicting() throws Exception
Assert.assertEquals(0, task1.getFireDepartmentMetrics().thrownAway());
Assert.assertEquals(3, task2.getFireDepartmentMetrics().processed());
Assert.assertEquals(1, task2.getFireDepartmentMetrics().unparseable());
- Assert.assertEquals(1, task2.getFireDepartmentMetrics().thrownAway());
+ Assert.assertEquals(2, task2.getFireDepartmentMetrics().thrownAway());
// Check published segments & metadata, should all be from the first task
SegmentDescriptor desc1 = SD(task1, "2010/P1D", 0);
@@ -1023,12 +1025,12 @@ public void testRunConflictingWithoutTransactions() throws Exception
final KafkaIndexTask task1 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
false,
- false,
null,
null,
false
@@ -1037,12 +1039,12 @@ public void testRunConflictingWithoutTransactions() throws Exception
final KafkaIndexTask task2 = createTask(
null,
new KafkaIOConfig(
+ 1,
"sequence1",
new KafkaPartitions(topic, ImmutableMap.of(0, 3L)),
- new KafkaPartitions(topic, ImmutableMap.of(0, 8L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, 9L)),
kafkaServer.consumerProperties(),
false,
- false,
null,
null,
false
@@ -1076,7 +1078,7 @@ public void testRunConflictingWithoutTransactions() throws Exception
Assert.assertEquals(0, task1.getFireDepartmentMetrics().thrownAway());
Assert.assertEquals(3, task2.getFireDepartmentMetrics().processed());
Assert.assertEquals(1, task2.getFireDepartmentMetrics().unparseable());
- Assert.assertEquals(1, task2.getFireDepartmentMetrics().thrownAway());
+ Assert.assertEquals(2, task2.getFireDepartmentMetrics().thrownAway());
// Check published segments & metadata
SegmentDescriptor desc3 = SD(task2, "2011/P1D", 1);
@@ -1097,12 +1099,12 @@ public void testRunOneTaskTwoPartitions() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L, 1, 0L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L, 1, 2L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1162,12 +1164,12 @@ public void testRunTwoTasksTwoPartitions() throws Exception
final KafkaIndexTask task1 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1176,12 +1178,12 @@ public void testRunTwoTasksTwoPartitions() throws Exception
final KafkaIndexTask task2 = createTask(
null,
new KafkaIOConfig(
+ 1,
"sequence1",
new KafkaPartitions(topic, ImmutableMap.of(1, 0L)),
new KafkaPartitions(topic, ImmutableMap.of(1, 1L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1232,12 +1234,12 @@ public void testRestore() throws Exception
final KafkaIndexTask task1 = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1269,12 +1271,12 @@ public void testRestore() throws Exception
final KafkaIndexTask task2 = createTask(
task1.getId(),
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1321,12 +1323,12 @@ public void testRunWithPauseAndResume() throws Exception
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1351,7 +1353,7 @@ public void testRunWithPauseAndResume() throws Exception
Assert.assertEquals(KafkaIndexTask.Status.READING, task.getStatus());
Map<Integer, Long> currentOffsets = objectMapper.readValue(
- task.pause(0).getEntity().toString(),
+ task.pause().getEntity().toString(),
new TypeReference<Map<Integer, Long>>()
{
}
@@ -1399,105 +1401,18 @@ public void testRunWithPauseAndResume() throws Exception
Assert.assertEquals(ImmutableList.of("d", "e"), readSegmentColumn("dim1", desc2));
}
- @Test(timeout = 60_000L)
- public void testRunAndPauseAfterReadWithModifiedEndOffsets() throws Exception
- {
- final KafkaIndexTask task = createTask(
- null,
- new KafkaIOConfig(
- "sequence0",
- new KafkaPartitions(topic, ImmutableMap.of(0, 1L)),
- new KafkaPartitions(topic, ImmutableMap.of(0, 3L)),
- kafkaServer.consumerProperties(),
- true,
- true,
- null,
- null,
- false
- )
- );
-
- final ListenableFuture<TaskStatus> future = runTask(task);
-
- try (final KafkaProducer<byte[], byte[]> kafkaProducer = kafkaServer.newProducer()) {
- for (ProducerRecord<byte[], byte[]> record : records) {
- kafkaProducer.send(record).get();
- }
- }
-
- while (task.getStatus() != KafkaIndexTask.Status.PAUSED) {
- Thread.sleep(25);
- }
-
- // reached the end of the assigned offsets and paused instead of publishing
- Assert.assertEquals(task.getEndOffsets(), task.getCurrentOffsets());
- Assert.assertEquals(KafkaIndexTask.Status.PAUSED, task.getStatus());
-
- Assert.assertEquals(ImmutableMap.of(0, 3L), task.getEndOffsets());
- Map<Integer, Long> newEndOffsets = ImmutableMap.of(0, 4L);
- task.setEndOffsets(newEndOffsets, false, true);
- Assert.assertEquals(newEndOffsets, task.getEndOffsets());
- Assert.assertEquals(KafkaIndexTask.Status.PAUSED, task.getStatus());
- task.resume();
-
- while (task.getStatus() != KafkaIndexTask.Status.PAUSED) {
- Thread.sleep(25);
- }
-
- // reached the end of the updated offsets and paused
- Assert.assertEquals(newEndOffsets, task.getCurrentOffsets());
- Assert.assertEquals(KafkaIndexTask.Status.PAUSED, task.getStatus());
-
- // try again but with resume flag == true
- newEndOffsets = ImmutableMap.of(0, 6L);
- task.setEndOffsets(newEndOffsets, true, true);
- Assert.assertEquals(newEndOffsets, task.getEndOffsets());
- Assert.assertNotEquals(KafkaIndexTask.Status.PAUSED, task.getStatus());
-
- while (task.getStatus() != KafkaIndexTask.Status.PAUSED) {
- Thread.sleep(25);
- }
-
- Assert.assertEquals(newEndOffsets, task.getCurrentOffsets());
- Assert.assertEquals(KafkaIndexTask.Status.PAUSED, task.getStatus());
-
- task.resume();
-
- Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode());
-
- // Check metrics
- Assert.assertEquals(4, task.getFireDepartmentMetrics().processed());
- Assert.assertEquals(1, task.getFireDepartmentMetrics().unparseable());
- Assert.assertEquals(0, task.getFireDepartmentMetrics().thrownAway());
-
- // Check published metadata
- SegmentDescriptor desc1 = SD(task, "2009/P1D", 0);
- SegmentDescriptor desc2 = SD(task, "2010/P1D", 0);
- SegmentDescriptor desc3 = SD(task, "2011/P1D", 0);
- Assert.assertEquals(ImmutableSet.of(desc1, desc2, desc3), publishedDescriptors());
- Assert.assertEquals(
- new KafkaDataSourceMetadata(new KafkaPartitions(topic, ImmutableMap.of(0, 6L))),
- metadataStorageCoordinator.getDataSourceMetadata(DATA_SCHEMA.getDataSource())
- );
-
- // Check segments in deep storage
- Assert.assertEquals(ImmutableList.of("b"), readSegmentColumn("dim1", desc1));
- Assert.assertEquals(ImmutableList.of("c"), readSegmentColumn("dim1", desc2));
- Assert.assertEquals(ImmutableList.of("d", "e"), readSegmentColumn("dim1", desc3));
- }
-
@Test(timeout = 30_000L)
public void testRunWithOffsetOutOfRangeExceptionAndPause() throws Exception
{
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 2L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1510,7 +1425,7 @@ public void testRunWithOffsetOutOfRangeExceptionAndPause() throws Exception
Thread.sleep(2000);
}
- task.pause(0);
+ task.pause();
while (!task.getStatus().equals(KafkaIndexTask.Status.PAUSED)) {
Thread.sleep(25);
@@ -1531,12 +1446,12 @@ public void testRunWithOffsetOutOfRangeExceptionAndNextOffsetGreaterThanLeastAva
final KafkaIndexTask task = createTask(
null,
new KafkaIOConfig(
+ 0,
"sequence0",
new KafkaPartitions(topic, ImmutableMap.of(0, 200L)),
new KafkaPartitions(topic, ImmutableMap.of(0, 500L)),
kafkaServer.consumerProperties(),
true,
- false,
null,
null,
false
@@ -1556,6 +1471,72 @@ public void testRunWithOffsetOutOfRangeExceptionAndNextOffsetGreaterThanLeastAva
}
}
+ @Test(timeout = 60_000L)
+ public void testRunContextSequenceAheadOfStartingOffsets() throws Exception
+ {
+ // This tests the case when a replacement task is created in place of a failed test
+ // which has done some incremental handoffs, thus the context will contain starting
+ // sequence offsets from which the task should start reading and ignore the start offsets
+ if (!isIncrementalHandoffSupported) {
+ return;
+ }
+ // Insert data
+ try (final KafkaProducer<byte[], byte[]> kafkaProducer = kafkaServer.newProducer()) {
+ for (ProducerRecord<byte[], byte[]> record : records) {
+ kafkaProducer.send(record).get();
+ }
+ }
+
+ final TreeMap<Integer, Map<Integer, Long>> sequences = new TreeMap<>();
+ // Here the sequence number is 1 meaning that one incremental handoff was done by the failed task
+ // and this task should start reading from offset 2 for partition 0
+ sequences.put(1, ImmutableMap.of(0, 2L));
+ final Map<String, Object> context = new HashMap<>();
+ context.put("checkpoints", objectMapper.writerWithType(new TypeReference<TreeMap<Integer, Map<Integer, Long>>>()
+ {
+ }).writeValueAsString(sequences));
+
+ final KafkaIndexTask task = createTask(
+ null,
+ new KafkaIOConfig(
+ 0,
+ "sequence0",
+ // task should ignore these and use sequence info sent in the context
+ new KafkaPartitions(topic, ImmutableMap.of(0, 0L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, 5L)),
+ kafkaServer.consumerProperties(),
+ true,
+ null,
+ null,
+ false
+ ),
+ context
+ );
+
+ final ListenableFuture<TaskStatus> future = runTask(task);
+
+ // Wait for task to exit
+ Assert.assertEquals(TaskState.SUCCESS, future.get().getStatusCode());
+
+ // Check metrics
+ Assert.assertEquals(3, task.getFireDepartmentMetrics().processed());
+ Assert.assertEquals(0, task.getFireDepartmentMetrics().unparseable());
+ Assert.assertEquals(0, task.getFireDepartmentMetrics().thrownAway());
+
+ // Check published metadata
+ SegmentDescriptor desc1 = SD(task, "2010/P1D", 0);
+ SegmentDescriptor desc2 = SD(task, "2011/P1D", 0);
+ Assert.assertEquals(ImmutableSet.of(desc1, desc2), publishedDescriptors());
+ Assert.assertEquals(
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, ImmutableMap.of(0, 5L))),
+ metadataStorageCoordinator.getDataSourceMetadata(DATA_SCHEMA.getDataSource())
+ );
+
+ // Check segments in deep storage
+ Assert.assertEquals(ImmutableList.of("c"), readSegmentColumn("dim1", desc1));
+ Assert.assertEquals(ImmutableList.of("d", "e"), readSegmentColumn("dim1", desc2));
+ }
+
private ListenableFuture<TaskStatus> runTask(final Task task)
{
try {
@@ -1614,6 +1595,15 @@ private KafkaIndexTask createTask(
return createTask(taskId, DATA_SCHEMA, ioConfig);
}
+ private KafkaIndexTask createTask(
+ final String taskId,
+ final KafkaIOConfig ioConfig,
+ final Map<String, Object> context
+ )
+ {
+ return createTask(taskId, DATA_SCHEMA, ioConfig, context);
+ }
+
private KafkaIndexTask createTask(
final String taskId,
final DataSchema dataSchema,
@@ -1650,6 +1640,45 @@ private KafkaIndexTask createTask(
return task;
}
+
+ private KafkaIndexTask createTask(
+ final String taskId,
+ final DataSchema dataSchema,
+ final KafkaIOConfig ioConfig,
+ final Map<String, Object> context
+ )
+ {
+ final KafkaTuningConfig tuningConfig = new KafkaTuningConfig(
+ 1000,
+ maxRowsPerSegment,
+ new Period("P1Y"),
+ null,
+ null,
+ null,
+ true,
+ reportParseExceptions,
+ handoffConditionTimeout,
+ resetOffsetAutomatically,
+ null
+ );
+ if (isIncrementalHandoffSupported) {
+ context.put(KafkaSupervisor.IS_INCREMENTAL_HANDOFF_SUPPORTED, true);
+ }
+
+ final KafkaIndexTask task = new KafkaIndexTask(
+ taskId,
+ null,
+ cloneDataSchema(dataSchema),
+ tuningConfig,
+ ioConfig,
+ context,
+ null,
+ null
+ );
+ task.setPollRetryMs(POLL_RETRY_MS);
+ return task;
+ }
+
private static DataSchema cloneDataSchema(final DataSchema dataSchema)
{
return new DataSchema(
@@ -1747,18 +1776,20 @@ private void makeToolboxFactory() throws IOException
@Override
public boolean checkPointDataSourceMetadata(
String supervisorId,
- @Nullable String sequenceName,
+ int taskGroupId,
@Nullable DataSourceMetadata previousDataSourceMetadata,
@Nullable DataSourceMetadata currentDataSourceMetadata
)
{
log.info("Adding checkpoint hash to the set");
- checkpointRequestsHash.add(Objects.hash(
- supervisorId,
- sequenceName,
- previousDataSourceMetadata,
- currentDataSourceMetadata
- ));
+ checkpointRequestsHash.add(
+ Objects.hash(
+ supervisorId,
+ taskGroupId,
+ previousDataSourceMetadata,
+ currentDataSourceMetadata
+ )
+ );
return true;
}
}
@@ -1884,9 +1915,9 @@ private File getSegmentDirectory()
private List<String> readSegmentColumn(final String column, final SegmentDescriptor descriptor) throws IOException
{
- File indexZip = new File(
+ File indexBasePath = new File(
StringUtils.format(
- "%s/%s/%s_%s/%s/%d/index.zip",
+ "%s/%s/%s_%s/%s/%d",
getSegmentDirectory(),
DATA_SCHEMA.getDataSource(),
descriptor.getInterval().getStart(),
@@ -1895,6 +1926,7 @@ private File getSegmentDirectory()
descriptor.getPartitionNumber()
)
);
+
File outputLocation = new File(
directory,
StringUtils.format(
@@ -1907,7 +1939,7 @@ private File getSegmentDirectory()
);
outputLocation.mkdir();
CompressionUtils.unzip(
- Files.asByteSource(indexZip),
+ Files.asByteSource(new File(indexBasePath.listFiles()[0], "index.zip")),
outputLocation,
Predicates.<Throwable>alwaysFalse(),
false
diff --git a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorTest.java b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorTest.java
index 29041e27de5..2add456df8e 100644
--- a/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorTest.java
+++ b/extensions-core/kafka-indexing-service/src/test/java/io/druid/indexing/kafka/supervisor/KafkaSupervisorTest.java
@@ -19,6 +19,7 @@
package io.druid.indexing.kafka.supervisor;
+import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Charsets;
import com.google.common.base.Optional;
@@ -29,13 +30,11 @@
import io.druid.data.input.impl.DimensionSchema;
import io.druid.data.input.impl.DimensionsSpec;
import io.druid.data.input.impl.JSONParseSpec;
-import io.druid.java.util.common.parsers.JSONPathFieldSpec;
-import io.druid.java.util.common.parsers.JSONPathSpec;
import io.druid.data.input.impl.StringDimensionSchema;
import io.druid.data.input.impl.StringInputRowParser;
import io.druid.data.input.impl.TimestampSpec;
-import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexer.TaskLocation;
+import io.druid.indexing.common.TaskInfoProvider;
import io.druid.indexing.common.TaskStatus;
import io.druid.indexing.common.task.RealtimeIndexTask;
import io.druid.indexing.common.task.Task;
@@ -60,6 +59,9 @@
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.granularity.Granularities;
+import io.druid.java.util.common.parsers.JSONPathFieldSpec;
+import io.druid.java.util.common.parsers.JSONPathSpec;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.query.aggregation.AggregatorFactory;
import io.druid.query.aggregation.CountAggregatorFactory;
import io.druid.segment.TestHelper;
@@ -68,6 +70,7 @@
import io.druid.segment.indexing.granularity.UniformGranularitySpec;
import io.druid.segment.realtime.FireDepartment;
import io.druid.server.metrics.DruidMonitorSchedulerConfig;
+import io.druid.server.metrics.ExceptionCapturingServiceEmitter;
import io.druid.server.metrics.NoopServiceEmitter;
import org.apache.curator.test.TestingCluster;
import org.apache.kafka.clients.producer.KafkaProducer;
@@ -97,7 +100,9 @@
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
+import java.util.concurrent.TimeoutException;
import static org.easymock.EasyMock.anyBoolean;
import static org.easymock.EasyMock.anyObject;
@@ -138,6 +143,7 @@
private KafkaIndexTaskClient taskClient;
private TaskQueue taskQueue;
private String topic;
+ private ExceptionCapturingServiceEmitter serviceEmitter;
private static String getTopic()
{
@@ -204,6 +210,8 @@ public void setupTest() throws Exception
);
topic = getTopic();
+ serviceEmitter = new ExceptionCapturingServiceEmitter();
+ EmittingLogger.registerEmitter(serviceEmitter);
}
@After
@@ -254,7 +262,6 @@ public void testNoInitialState() throws Exception
Assert.assertEquals("myCustomValue", taskConfig.getConsumerProperties().get("myCustomKey"));
Assert.assertEquals("sequenceName-0", taskConfig.getBaseSequenceName());
Assert.assertTrue("isUseTransaction", taskConfig.isUseTransaction());
- Assert.assertFalse("pauseAfterRead", taskConfig.isPauseAfterRead());
Assert.assertFalse("minimumMessageTime", taskConfig.getMinimumMessageTime().isPresent());
Assert.assertFalse("maximumMessageTime", taskConfig.getMaximumMessageTime().isPresent());
Assert.assertFalse("skipOffsetGaps", taskConfig.isSkipOffsetGaps());
@@ -545,7 +552,7 @@ public void testKillIncompatibleTasks() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "index_kafka_testDS__some_other_sequenceName",
+ 1,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, 10L)),
null,
@@ -556,7 +563,7 @@ public void testKillIncompatibleTasks() throws Exception
Task id2 = createKafkaIndexTask(
"id2",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, 333L, 1, 333L, 2, 333L)),
null,
@@ -567,7 +574,7 @@ public void testKillIncompatibleTasks() throws Exception
Task id3 = createKafkaIndexTask(
"id3",
DATASOURCE,
- "index_kafka_testDS__some_other_sequenceName",
+ 1,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 1L)),
new KafkaPartitions("topic", ImmutableMap.of(0, 333L, 1, 333L, 2, 330L)),
null,
@@ -578,7 +585,7 @@ public void testKillIncompatibleTasks() throws Exception
Task id4 = createKafkaIndexTask(
"id4",
"other-datasource",
- "index_kafka_testDS_d927edff33c4b3f",
+ 2,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, 10L)),
null,
@@ -626,7 +633,9 @@ public void testKillIncompatibleTasks() throws Exception
TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
checkpoints.put(0, ImmutableMap.of(0, 0L, 1, 0L, 2, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(2);
replayAll();
@@ -644,7 +653,7 @@ public void testKillBadPartitionAssignment() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -653,7 +662,7 @@ public void testKillBadPartitionAssignment() throws Exception
Task id2 = createKafkaIndexTask(
"id2",
DATASOURCE,
- "sequenceName-1",
+ 1,
new KafkaPartitions("topic", ImmutableMap.of(1, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(1, Long.MAX_VALUE)),
null,
@@ -662,7 +671,7 @@ public void testKillBadPartitionAssignment() throws Exception
Task id3 = createKafkaIndexTask(
"id3",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -671,7 +680,7 @@ public void testKillBadPartitionAssignment() throws Exception
Task id4 = createKafkaIndexTask(
"id4",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE)),
null,
@@ -680,7 +689,7 @@ public void testKillBadPartitionAssignment() throws Exception
Task id5 = createKafkaIndexTask(
"id5",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -719,8 +728,12 @@ public void testKillBadPartitionAssignment() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1)).times(1);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2)).times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(1);
taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
taskQueue.shutdown("id4");
@@ -757,10 +770,12 @@ public void testRequeueTaskWhenFailed() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .anyTimes();
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .anyTimes();
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .anyTimes();
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .anyTimes();
taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
replayAll();
@@ -822,7 +837,7 @@ public void testRequeueAdoptedTaskWhenFailed() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
now,
@@ -849,7 +864,9 @@ public void testRequeueAdoptedTaskWhenFailed() throws Exception
TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
checkpoints.put(0, ImmutableMap.of(0, 0L, 2, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(2);
taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
replayAll();
@@ -870,9 +887,12 @@ public void testRequeueAdoptedTaskWhenFailed() throws Exception
reset(taskClient);
// for the newly created replica task
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(captured.getValue())).anyTimes();
expect(taskStorage.getStatus(iHaveFailed.getId())).andReturn(Optional.of(TaskStatus.failure(iHaveFailed.getId())));
@@ -945,10 +965,12 @@ public void testQueueNextTasksOnSuccess() throws Exception
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
// there would be 4 tasks, 2 for each task group
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(2);
expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes();
for (Task task : tasks) {
@@ -1046,7 +1068,6 @@ public void testBeginPublishAndQueueNextTasks() throws Exception
taskClient.setEndOffsetsAsync(
EasyMock.contains("sequenceName-0"),
EasyMock.eq(ImmutableMap.of(0, 10L, 1, 20L, 2, 35L)),
- EasyMock.eq(true),
EasyMock.eq(true)
)
).andReturn(Futures.immediateFuture(true)).times(2);
@@ -1056,10 +1077,12 @@ public void testBeginPublishAndQueueNextTasks() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(2);
replay(taskStorage, taskRunner, taskClient, taskQueue);
@@ -1074,7 +1097,6 @@ public void testBeginPublishAndQueueNextTasks() throws Exception
KafkaIOConfig taskConfig = kafkaIndexTask.getIOConfig();
Assert.assertEquals("sequenceName-0", taskConfig.getBaseSequenceName());
Assert.assertTrue("isUseTransaction", taskConfig.isUseTransaction());
- Assert.assertFalse("pauseAfterRead", taskConfig.isPauseAfterRead());
Assert.assertEquals(topic, taskConfig.getStartPartitions().getTopic());
Assert.assertEquals(10L, (long) taskConfig.getStartPartitions().getPartitionOffsetMap().get(0));
@@ -1094,7 +1116,7 @@ public void testDiscoverExistingPublishingTask() throws Exception
Task task = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1164,7 +1186,6 @@ public void testDiscoverExistingPublishingTask() throws Exception
Assert.assertEquals("myCustomValue", capturedTaskConfig.getConsumerProperties().get("myCustomKey"));
Assert.assertEquals("sequenceName-0", capturedTaskConfig.getBaseSequenceName());
Assert.assertTrue("isUseTransaction", capturedTaskConfig.isUseTransaction());
- Assert.assertFalse("pauseAfterRead", capturedTaskConfig.isPauseAfterRead());
// check that the new task was created with starting offsets matching where the publishing task finished
Assert.assertEquals(topic, capturedTaskConfig.getStartPartitions().getTopic());
@@ -1189,7 +1210,7 @@ public void testDiscoverExistingPublishingTaskWithDifferentPartitionAllocation()
Task task = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1255,7 +1276,6 @@ public void testDiscoverExistingPublishingTaskWithDifferentPartitionAllocation()
Assert.assertEquals("myCustomValue", capturedTaskConfig.getConsumerProperties().get("myCustomKey"));
Assert.assertEquals("sequenceName-0", capturedTaskConfig.getBaseSequenceName());
Assert.assertTrue("isUseTransaction", capturedTaskConfig.isUseTransaction());
- Assert.assertFalse("pauseAfterRead", capturedTaskConfig.isPauseAfterRead());
// check that the new task was created with starting offsets matching where the publishing task finished
Assert.assertEquals(topic, capturedTaskConfig.getStartPartitions().getTopic());
@@ -1282,7 +1302,7 @@ public void testDiscoverExistingPublishingAndReadingTask() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1292,7 +1312,7 @@ public void testDiscoverExistingPublishingAndReadingTask() throws Exception
Task id2 = createKafkaIndexTask(
"id2",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 1L, 1, 2L, 2, 3L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1330,7 +1350,9 @@ public void testDiscoverExistingPublishingAndReadingTask() throws Exception
// since id1 is publishing, so getCheckpoints wouldn't be called for it
TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
checkpoints.put(0, ImmutableMap.of(0, 1L, 1, 2L, 2, 3L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
replayAll();
@@ -1406,10 +1428,12 @@ public void testKillUnresponsiveTasksWhileGettingStartTime() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(2);
expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes();
for (Task task : tasks) {
@@ -1465,10 +1489,12 @@ public void testKillUnresponsiveTasksWhilePausing() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(2);
captured = Capture.newInstance(CaptureType.ALL);
expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes();
@@ -1542,10 +1568,12 @@ public void testKillUnresponsiveTasksWhileSettingEndOffsets() throws Exception
checkpoints1.put(0, ImmutableMap.of(0, 0L, 2, 0L));
TreeMap<Integer, Map<Integer, Long>> checkpoints2 = new TreeMap<>();
checkpoints2.put(0, ImmutableMap.of(1, 0L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints1))
- .times(2);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints2))
- .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-0"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints1))
+ .times(2);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("sequenceName-1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints2))
+ .times(2);
captured = Capture.newInstance(CaptureType.ALL);
expect(taskStorage.getActiveTasks()).andReturn(tasks).anyTimes();
@@ -1570,7 +1598,6 @@ public void testKillUnresponsiveTasksWhileSettingEndOffsets() throws Exception
taskClient.setEndOffsetsAsync(
EasyMock.contains("sequenceName-0"),
EasyMock.eq(ImmutableMap.of(0, 10L, 1, 20L, 2, 35L)),
- EasyMock.eq(true),
EasyMock.eq(true)
)
).andReturn(Futures.<Boolean>immediateFailedFuture(new RuntimeException())).times(2);
@@ -1625,7 +1652,7 @@ public void testStopGracefully() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1635,7 +1662,7 @@ public void testStopGracefully() throws Exception
Task id2 = createKafkaIndexTask(
"id2",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1645,7 +1672,7 @@ public void testStopGracefully() throws Exception
Task id3 = createKafkaIndexTask(
"id3",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1681,8 +1708,12 @@ public void testStopGracefully() throws Exception
// getCheckpoints will not be called for id1 as it is in publishing state
TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
checkpoints.put(0, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
replayAll();
@@ -1695,7 +1726,7 @@ public void testStopGracefully() throws Exception
expect(taskRunner.getRunningTasks()).andReturn(workItems).anyTimes();
expect(taskClient.pauseAsync("id2"))
.andReturn(Futures.immediateFuture((Map<Integer, Long>) ImmutableMap.of(0, 15L, 1, 25L, 2, 30L)));
- expect(taskClient.setEndOffsetsAsync("id2", ImmutableMap.of(0, 15L, 1, 25L, 2, 30L), true, true))
+ expect(taskClient.setEndOffsetsAsync("id2", ImmutableMap.of(0, 15L, 1, 25L, 2, 30L), true))
.andReturn(Futures.immediateFuture(true));
taskQueue.shutdown("id3");
expectLastCall().times(2);
@@ -1827,7 +1858,7 @@ public void testResetRunningTasks() throws Exception
Task id1 = createKafkaIndexTask(
"id1",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1837,7 +1868,7 @@ public void testResetRunningTasks() throws Exception
Task id2 = createKafkaIndexTask(
"id2",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1847,7 +1878,7 @@ public void testResetRunningTasks() throws Exception
Task id3 = createKafkaIndexTask(
"id3",
DATASOURCE,
- "sequenceName-0",
+ 0,
new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
null,
@@ -1882,8 +1913,98 @@ public void testResetRunningTasks() throws Exception
TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
checkpoints.put(0, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L));
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
- expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean())).andReturn(Futures.immediateFuture(checkpoints)).times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+
+ taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
+ replayAll();
+
+ supervisor.start();
+ supervisor.runInternal();
+ verifyAll();
+
+ reset(taskQueue, indexerMetadataStorageCoordinator);
+ expect(indexerMetadataStorageCoordinator.deleteDataSourceMetadata(DATASOURCE)).andReturn(true);
+ taskQueue.shutdown("id2");
+ taskQueue.shutdown("id3");
+ replay(taskQueue, indexerMetadataStorageCoordinator);
+
+ supervisor.resetInternal(null);
+ verifyAll();
+ }
+
+ @Test
+ public void testNoDataIngestionTasks() throws Exception
+ {
+ final DateTime startTime = DateTimes.nowUtc();
+ supervisor = getSupervisor(2, 1, true, "PT1S", null, null, false);
+ //not adding any events
+ Task id1 = createKafkaIndexTask(
+ "id1",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions("topic", ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
+ new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ Task id2 = createKafkaIndexTask(
+ "id2",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ Task id3 = createKafkaIndexTask(
+ "id3",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions("topic", ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions("topic", ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes();
+ expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes();
+ expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2, id3)).anyTimes();
+ expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes();
+ expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes();
+ expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes();
+ expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes();
+ expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes();
+ expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes();
+ expect(indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn(
+ new KafkaDataSourceMetadata(
+ null
+ )
+ ).anyTimes();
+ expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+ expect(taskClient.getStatusAsync("id2")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+ expect(taskClient.getStatusAsync("id3")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+ expect(taskClient.getStartTimeAsync("id1")).andReturn(Futures.immediateFuture(startTime));
+ expect(taskClient.getStartTimeAsync("id2")).andReturn(Futures.immediateFuture(startTime));
+ expect(taskClient.getStartTimeAsync("id3")).andReturn(Futures.immediateFuture(startTime));
+
+ TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
+ checkpoints.put(0, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L));
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
replayAll();
@@ -1894,6 +2015,7 @@ public void testResetRunningTasks() throws Exception
reset(taskQueue, indexerMetadataStorageCoordinator);
expect(indexerMetadataStorageCoordinator.deleteDataSourceMetadata(DATASOURCE)).andReturn(true);
+ taskQueue.shutdown("id1");
taskQueue.shutdown("id2");
taskQueue.shutdown("id3");
replay(taskQueue, indexerMetadataStorageCoordinator);
@@ -1902,6 +2024,172 @@ public void testResetRunningTasks() throws Exception
verifyAll();
}
+ @Test(timeout = 60_000L)
+ public void testCheckpointForInactiveTaskGroup()
+ throws InterruptedException, ExecutionException, TimeoutException, JsonProcessingException
+ {
+ supervisor = getSupervisor(2, 1, true, "PT1S", null, null, false);
+ //not adding any events
+ final Task id1 = createKafkaIndexTask(
+ "id1",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ final Task id2 = createKafkaIndexTask(
+ "id2",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ final Task id3 = createKafkaIndexTask(
+ "id3",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes();
+ expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes();
+ expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2, id3)).anyTimes();
+ expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes();
+ expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes();
+ expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes();
+ expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes();
+ expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes();
+ expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes();
+ expect(
+ indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn(new KafkaDataSourceMetadata(null)
+ ).anyTimes();
+ expect(taskClient.getStatusAsync("id1")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+ expect(taskClient.getStatusAsync("id2")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+ expect(taskClient.getStatusAsync("id3")).andReturn(Futures.immediateFuture(KafkaIndexTask.Status.READING));
+
+ final DateTime startTime = DateTimes.nowUtc();
+ expect(taskClient.getStartTimeAsync("id1")).andReturn(Futures.immediateFuture(startTime));
+ expect(taskClient.getStartTimeAsync("id2")).andReturn(Futures.immediateFuture(startTime));
+ expect(taskClient.getStartTimeAsync("id3")).andReturn(Futures.immediateFuture(startTime));
+
+ final TreeMap<Integer, Map<Integer, Long>> checkpoints = new TreeMap<>();
+ checkpoints.put(0, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L));
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id1"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id2"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+ expect(taskClient.getCheckpointsAsync(EasyMock.contains("id3"), anyBoolean()))
+ .andReturn(Futures.immediateFuture(checkpoints))
+ .times(1);
+
+ taskRunner.registerListener(anyObject(TaskRunnerListener.class), anyObject(Executor.class));
+ replayAll();
+
+ supervisor.start();
+ supervisor.runInternal();
+
+ final Map<Integer, Long> fakeCheckpoints = Collections.emptyMap();
+ supervisor.moveTaskGroupToPendingCompletion(0);
+ supervisor.checkpoint(
+ 0,
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, checkpoints.get(0))),
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, fakeCheckpoints))
+ );
+
+ while (supervisor.getNoticesQueueSize() > 0) {
+ Thread.sleep(100);
+ }
+
+ verifyAll();
+
+ Assert.assertNull(serviceEmitter.getStackTrace());
+ Assert.assertNull(serviceEmitter.getExceptionMessage());
+ Assert.assertNull(serviceEmitter.getExceptionClass());
+ }
+
+ @Test(timeout = 60_000L)
+ public void testCheckpointForUnknownTaskGroup() throws InterruptedException
+ {
+ supervisor = getSupervisor(2, 1, true, "PT1S", null, null, false);
+ //not adding any events
+ final Task id1 = createKafkaIndexTask(
+ "id1",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 0L, 1, 0L, 2, 0L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ final Task id2 = createKafkaIndexTask(
+ "id2",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ final Task id3 = createKafkaIndexTask(
+ "id3",
+ DATASOURCE,
+ 0,
+ new KafkaPartitions(topic, ImmutableMap.of(0, 10L, 1, 20L, 2, 30L)),
+ new KafkaPartitions(topic, ImmutableMap.of(0, Long.MAX_VALUE, 1, Long.MAX_VALUE, 2, Long.MAX_VALUE)),
+ null,
+ null
+ );
+
+ expect(taskMaster.getTaskQueue()).andReturn(Optional.of(taskQueue)).anyTimes();
+ expect(taskMaster.getTaskRunner()).andReturn(Optional.of(taskRunner)).anyTimes();
+ expect(taskStorage.getActiveTasks()).andReturn(ImmutableList.of(id1, id2, id3)).anyTimes();
+ expect(taskStorage.getStatus("id1")).andReturn(Optional.of(TaskStatus.running("id1"))).anyTimes();
+ expect(taskStorage.getStatus("id2")).andReturn(Optional.of(TaskStatus.running("id2"))).anyTimes();
+ expect(taskStorage.getStatus("id3")).andReturn(Optional.of(TaskStatus.running("id3"))).anyTimes();
+ expect(taskStorage.getTask("id1")).andReturn(Optional.of(id1)).anyTimes();
+ expect(taskStorage.getTask("id2")).andReturn(Optional.of(id2)).anyTimes();
+ expect(taskStorage.getTask("id3")).andReturn(Optional.of(id3)).anyTimes();
+ expect(
+ indexerMetadataStorageCoordinator.getDataSourceMetadata(DATASOURCE)).andReturn(new KafkaDataSourceMetadata(null)
+ ).anyTimes();
+
+ replayAll();
+
+ supervisor.start();
+
+ supervisor.checkpoint(
+ 0,
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, Collections.emptyMap())),
+ new KafkaDataSourceMetadata(new KafkaPartitions(topic, Collections.emptyMap()))
+ );
+
+ while (supervisor.getNoticesQueueSize() > 0) {
+ Thread.sleep(100);
+ }
+
+ verifyAll();
+
+ Assert.assertNotNull(serviceEmitter.getStackTrace());
+ Assert.assertEquals(
+ "WTH?! cannot find taskGroup [0] among all taskGroups [{}]",
+ serviceEmitter.getExceptionMessage()
+ );
+ Assert.assertEquals(ISE.class, serviceEmitter.getExceptionClass());
+ }
+
private void addSomeEvents(int numEventsPerPartition) throws Exception
{
try (final KafkaProducer<byte[], byte[]> kafkaProducer = kafkaServer.newProducer()) {
@@ -2026,7 +2314,7 @@ private static DataSchema getDataSchema(String dataSource)
private KafkaIndexTask createKafkaIndexTask(
String id,
String dataSource,
- String sequenceName,
+ int taskGroupId,
KafkaPartitions startPartitions,
KafkaPartitions endPartitions,
DateTime minimumMessageTime,
@@ -2039,17 +2327,17 @@ private KafkaIndexTask createKafkaIndexTask(
getDataSchema(dataSource),
tuningConfig,
new KafkaIOConfig(
- sequenceName,
+ taskGroupId,
+ "sequenceName-" + taskGroupId,
startPartitions,
endPartitions,
ImmutableMap.<String, String>of(),
true,
- false,
minimumMessageTime,
maximumMessageTime,
false
),
- ImmutableMap.<String, Object>of(),
+ Collections.emptyMap(),
null,
null
);
@@ -2087,12 +2375,6 @@ public TestableKafkaSupervisor(
super(taskStorage, taskMaster, indexerMetadataStorageCoordinator, taskClientFactory, mapper, spec);
}
- @Override
- protected String generateSequenceName(int groupId)
- {
- return StringUtils.format("sequenceName-%d", groupId);
- }
-
@Override
protected String generateSequenceName(
Map<Integer, Long> startPartitions,
@@ -2100,7 +2382,8 @@ protected String generateSequenceName(
Optional<DateTime> maximumMessageTime
)
{
- return generateSequenceName(getTaskGroupIdForPartition(startPartitions.keySet().iterator().next()));
+ final int groupId = getTaskGroupIdForPartition(startPartitions.keySet().iterator().next());
+ return StringUtils.format("sequenceName-%d", groupId);
}
}
}
diff --git a/extensions-core/lookups-cached-global/pom.xml b/extensions-core/lookups-cached-global/pom.xml
index 4ce26c7a803..74c5c35eb3f 100644
--- a/extensions-core/lookups-cached-global/pom.xml
+++ b/extensions-core/lookups-cached-global/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
<artifactId>druid-lookups-cached-global</artifactId>
@@ -29,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/CacheScheduler.java b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/CacheScheduler.java
index 38fcce978aa..1f1d3e3f813 100644
--- a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/CacheScheduler.java
+++ b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/CacheScheduler.java
@@ -22,8 +22,9 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.inject.Inject;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.concurrent.ConcurrentAwaitableCounter;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.guice.LazySingleton;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.StringUtils;
@@ -51,11 +52,11 @@
* // cacheState could be either NoCache or VersionedCache.
* if (cacheState instanceof NoCache) {
* // the cache is not yet created, or already closed
- * } else if (cacheState instanceof VersionedCache) {
+ * } else {
* Map<String, String> cache = ((VersionedCache) cacheState).getCache(); // use the cache
* // Although VersionedCache implements AutoCloseable, versionedCache shouldn't be manually closed
* // when obtained from entry.getCacheState(). If the namespace updates should be ceased completely,
- * // entry.close() (see below) should be called, it will close the last VersionedCache itself.
+ * // entry.close() (see below) should be called, it will close the last VersionedCache as well.
* // On scheduled updates, outdated VersionedCaches are also closed automatically.
* }
* ...
@@ -105,14 +106,16 @@ public CacheState getCacheState()
return impl.updaterFuture;
}
+ @VisibleForTesting
public void awaitTotalUpdates(int totalUpdates) throws InterruptedException
{
- impl.updateCounter.awaitTotalUpdates(totalUpdates);
+ impl.updateCounter.awaitCount(totalUpdates);
}
+ @VisibleForTesting
void awaitNextUpdates(int nextUpdates) throws InterruptedException
{
- impl.updateCounter.awaitNextUpdates(nextUpdates);
+ impl.updateCounter.awaitNextIncrements(nextUpdates);
}
/**
@@ -145,7 +148,7 @@ public String toString()
private final Future<?> updaterFuture;
private final Cleaner entryCleaner;
private final CacheGenerator<T> cacheGenerator;
- private final UpdateCounter updateCounter = new UpdateCounter();
+ private final ConcurrentAwaitableCounter updateCounter = new ConcurrentAwaitableCounter();
private final CountDownLatch startLatch = new CountDownLatch(1);
private EntryImpl(final T namespace, final Entry<T> entry, final CacheGenerator<T> cacheGenerator)
@@ -276,7 +279,7 @@ private CacheState swapCacheState(VersionedCache newVersionedCache)
return lastCacheState;
}
} while (!cacheStateHolder.compareAndSet(lastCacheState, newVersionedCache));
- updateCounter.update();
+ updateCounter.increment();
return lastCacheState;
}
@@ -485,7 +488,7 @@ public Entry scheduleAndWait(ExtractionNamespace namespace, long waitForFirstRun
log.debug("Scheduled new %s", entry);
boolean success = false;
try {
- success = entry.impl.updateCounter.awaitFirstUpdate(waitForFirstRunMs, TimeUnit.MILLISECONDS);
+ success = entry.impl.updateCounter.awaitFirstIncrement(waitForFirstRunMs, TimeUnit.MILLISECONDS);
if (success) {
return entry;
} else {
diff --git a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/NamespaceExtractionCacheManager.java b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/NamespaceExtractionCacheManager.java
index 65f646d5af6..49047294c9c 100644
--- a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/NamespaceExtractionCacheManager.java
+++ b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/NamespaceExtractionCacheManager.java
@@ -22,7 +22,7 @@
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Throwables;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
-import com.metamx.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceEmitter;
import io.druid.java.util.common.concurrent.ExecutorServices;
import io.druid.java.util.common.lifecycle.Lifecycle;
import io.druid.java.util.common.logger.Logger;
diff --git a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OffHeapNamespaceExtractionCacheManager.java b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OffHeapNamespaceExtractionCacheManager.java
index e591f8da90d..ab069001e39 100644
--- a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OffHeapNamespaceExtractionCacheManager.java
+++ b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OffHeapNamespaceExtractionCacheManager.java
@@ -21,8 +21,8 @@
import com.google.common.base.Throwables;
import com.google.inject.Inject;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.lifecycle.Lifecycle;
import io.druid.java.util.common.logger.Logger;
import io.druid.server.lookup.namespace.NamespaceExtractionConfig;
diff --git a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OnHeapNamespaceExtractionCacheManager.java b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OnHeapNamespaceExtractionCacheManager.java
index 6a5e015f252..d538c8f2da8 100644
--- a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OnHeapNamespaceExtractionCacheManager.java
+++ b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/OnHeapNamespaceExtractionCacheManager.java
@@ -21,8 +21,8 @@
import com.google.common.primitives.Chars;
import com.google.inject.Inject;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.lifecycle.Lifecycle;
import io.druid.java.util.common.logger.Logger;
diff --git a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/UpdateCounter.java b/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/UpdateCounter.java
deleted file mode 100644
index ed229b45f89..00000000000
--- a/extensions-core/lookups-cached-global/src/main/java/io/druid/server/lookup/namespace/cache/UpdateCounter.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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 java.util.concurrent.Phaser;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-
-final class UpdateCounter
-{
- /**
- * Max {@link Phaser}'s phase, specified in it's javadoc. Then it wraps to zero.
- */
- private static final int MAX_PHASE = Integer.MAX_VALUE;
-
- private final Phaser phaser = new Phaser(1);
-
- void update()
- {
- phaser.arrive();
- }
-
- void awaitTotalUpdates(int totalUpdates) throws InterruptedException
- {
- totalUpdates &= MAX_PHASE;
- int currentUpdates = phaser.getPhase();
- checkNotTerminated(currentUpdates);
- while (comparePhases(totalUpdates, currentUpdates) > 0) {
- currentUpdates = phaser.awaitAdvanceInterruptibly(currentUpdates);
- checkNotTerminated(currentUpdates);
- }
- }
-
- private static int comparePhases(int phase1, int phase2)
- {
- int diff = (phase1 - phase2) & MAX_PHASE;
- if (diff == 0) {
- return 0;
- }
- return diff < MAX_PHASE / 2 ? 1 : -1;
- }
-
- private void checkNotTerminated(int phase)
- {
- if (phase < 0) {
- throw new IllegalStateException("Phaser[" + phaser + "] unexpectedly terminated.");
- }
- }
-
- void awaitNextUpdates(int nextUpdates) throws InterruptedException
- {
- if (nextUpdates <= 0) {
- throw new IllegalArgumentException("nextUpdates is not positive: " + nextUpdates);
- }
- if (nextUpdates > MAX_PHASE / 4) {
- throw new UnsupportedOperationException("Couldn't wait for so many updates: " + nextUpdates);
- }
- awaitTotalUpdates(phaser.getPhase() + nextUpdates);
- }
-
- boolean awaitFirstUpdate(long timeout, TimeUnit unit) throws InterruptedException
- {
- try {
- phaser.awaitAdvanceInterruptibly(0, timeout, unit);
- return true;
- }
- catch (TimeoutException e) {
- return false;
- }
- }
-}
diff --git a/extensions-core/lookups-cached-single/pom.xml b/extensions-core/lookups-cached-single/pom.xml
index 9b4ea5a5ea3..9cdb614fa0c 100644
--- a/extensions-core/lookups-cached-single/pom.xml
+++ b/extensions-core/lookups-cached-single/pom.xml
@@ -18,8 +18,7 @@
~ under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
<artifactId>druid-lookups-cached-single</artifactId>
@@ -29,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/mysql-metadata-storage/pom.xml b/extensions-core/mysql-metadata-storage/pom.xml
index 950a985ce8f..aa6e53acf2f 100644
--- a/extensions-core/mysql-metadata-storage/pom.xml
+++ b/extensions-core/mysql-metadata-storage/pom.xml
@@ -28,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnector.java b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnector.java
index 3079ad427ea..910f397f447 100644
--- a/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnector.java
+++ b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnector.java
@@ -19,6 +19,7 @@
package io.druid.metadata.storage.mysql;
+import com.google.common.base.Joiner;
import com.google.common.base.Supplier;
import com.google.common.collect.ImmutableList;
import com.google.inject.Inject;
@@ -36,6 +37,7 @@
import org.skife.jdbi.v2.tweak.HandleCallback;
import org.skife.jdbi.v2.util.BooleanMapper;
+import java.io.File;
import java.sql.SQLException;
public class MySQLConnector extends SQLMetadataConnector
@@ -48,7 +50,11 @@
private final DBI dbi;
@Inject
- public MySQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<MetadataStorageTablesConfig> dbTables)
+ public MySQLConnector(
+ Supplier<MetadataStorageConnectorConfig> config,
+ Supplier<MetadataStorageTablesConfig> dbTables,
+ MySQLConnectorConfig connectorConfig
+ )
{
super(config, dbTables);
@@ -57,6 +63,68 @@ public MySQLConnector(Supplier<MetadataStorageConnectorConfig> config, Supplier<
// so we need to help JDBC find the driver
datasource.setDriverClassLoader(getClass().getClassLoader());
datasource.setDriverClassName("com.mysql.jdbc.Driver");
+ datasource.addConnectionProperty("useSSL", String.valueOf(connectorConfig.isUseSSL()));
+ if (connectorConfig.isUseSSL()) {
+ log.info("SSL is enabled on this MySQL connection. ");
+
+ datasource.addConnectionProperty(
+ "verifyServerCertificate",
+ String.valueOf(connectorConfig.isVerifyServerCertificate())
+ );
+ if (connectorConfig.isVerifyServerCertificate()) {
+ log.info("Server certificate verification is enabled. ");
+
+ if (connectorConfig.getTrustCertificateKeyStoreUrl() != null) {
+ datasource.addConnectionProperty(
+ "trustCertificateKeyStoreUrl",
+ new File(connectorConfig.getTrustCertificateKeyStoreUrl()).toURI().toString()
+ );
+ }
+ if (connectorConfig.getTrustCertificateKeyStoreType() != null) {
+ datasource.addConnectionProperty(
+ "trustCertificateKeyStoreType",
+ connectorConfig.getTrustCertificateKeyStoreType()
+ );
+ }
+ if (connectorConfig.getTrustCertificateKeyStorePassword() == null) {
+ log.warn(
+ "Trust store password is empty. Ensure that the trust store has been configured with an empty password.");
+ } else {
+ datasource.addConnectionProperty(
+ "trustCertificateKeyStorePassword",
+ connectorConfig.getTrustCertificateKeyStorePassword()
+ );
+ }
+ }
+ if (connectorConfig.getClientCertificateKeyStoreUrl() != null) {
+ datasource.addConnectionProperty(
+ "clientCertificateKeyStoreUrl",
+ new File(connectorConfig.getClientCertificateKeyStoreUrl()).toURI().toString()
+ );
+ }
+ if (connectorConfig.getClientCertificateKeyStoreType() != null) {
+ datasource.addConnectionProperty(
+ "clientCertificateKeyStoreType",
+ connectorConfig.getClientCertificateKeyStoreType()
+ );
+ }
+ if (connectorConfig.getClientCertificateKeyStorePassword() != null) {
+ datasource.addConnectionProperty(
+ "clientCertificateKeyStorePassword",
+ connectorConfig.getClientCertificateKeyStorePassword()
+ );
+ }
+ Joiner joiner = Joiner.on(",").skipNulls();
+ if (connectorConfig.getEnabledSSLCipherSuites() != null) {
+ datasource.addConnectionProperty(
+ "enabledSSLCipherSuites",
+ joiner.join(connectorConfig.getEnabledSSLCipherSuites())
+ );
+ }
+ if (connectorConfig.getEnabledTLSProtocols() != null) {
+ datasource.addConnectionProperty("enabledTLSProtocols", joiner.join(connectorConfig.getEnabledTLSProtocols()));
+ }
+ }
// use double-quotes for quoting columns, so we can write SQL that works with most databases
datasource.setConnectionInitSqls(ImmutableList.of("SET sql_mode='ANSI_QUOTES'"));
@@ -97,9 +165,9 @@ public boolean tableExists(Handle handle, String tableName)
{
// ensure database defaults to utf8, otherwise bail
boolean isUtf8 = handle
- .createQuery("SELECT @@character_set_database = 'utf8'")
- .map(BooleanMapper.FIRST)
- .first();
+ .createQuery("SELECT @@character_set_database = 'utf8'")
+ .map(BooleanMapper.FIRST)
+ .first();
if (!isUtf8) {
throw new ISE(
diff --git a/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnectorConfig.java b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnectorConfig.java
new file mode 100644
index 00000000000..77fc9dcd60b
--- /dev/null
+++ b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLConnectorConfig.java
@@ -0,0 +1,123 @@
+/*
+ * 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.metadata.storage.mysql;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import io.druid.metadata.PasswordProvider;
+
+import java.util.List;
+
+public class MySQLConnectorConfig
+{
+ @JsonProperty
+ private boolean useSSL = false;
+
+ @JsonProperty
+ private String trustCertificateKeyStoreUrl;
+
+ @JsonProperty
+ private String trustCertificateKeyStoreType;
+
+ @JsonProperty("trustCertificateKeyStorePassword")
+ private PasswordProvider trustCertificateKeyStorePasswordProvider;
+
+ @JsonProperty
+ private String clientCertificateKeyStoreUrl;
+
+ @JsonProperty
+ private String clientCertificateKeyStoreType;
+
+ @JsonProperty("clientCertificateKeyStorePassword")
+ private PasswordProvider clientCertificateKeyStorePasswordProvider;
+
+ @JsonProperty
+ private List<String> enabledSSLCipherSuites;
+
+ @JsonProperty
+ private List<String> enabledTLSProtocols;
+
+ @JsonProperty
+ private boolean verifyServerCertificate = false;
+
+ public boolean isUseSSL()
+ {
+ return useSSL;
+ }
+
+ public String getTrustCertificateKeyStoreUrl()
+ {
+ return trustCertificateKeyStoreUrl;
+ }
+
+ public String getTrustCertificateKeyStoreType()
+ {
+ return trustCertificateKeyStoreType;
+ }
+
+ public String getTrustCertificateKeyStorePassword()
+ {
+ return trustCertificateKeyStorePasswordProvider == null ? null : trustCertificateKeyStorePasswordProvider.getPassword();
+ }
+
+ public String getClientCertificateKeyStoreUrl()
+ {
+ return clientCertificateKeyStoreUrl;
+ }
+
+ public String getClientCertificateKeyStoreType()
+ {
+ return clientCertificateKeyStoreType;
+ }
+
+ public String getClientCertificateKeyStorePassword()
+ {
+ return clientCertificateKeyStorePasswordProvider == null ? null : clientCertificateKeyStorePasswordProvider.getPassword();
+ }
+
+ public List<String> getEnabledSSLCipherSuites()
+ {
+ return enabledSSLCipherSuites;
+ }
+
+ public List<String> getEnabledTLSProtocols()
+ {
+ return enabledTLSProtocols;
+ }
+
+ public boolean isVerifyServerCertificate()
+ {
+ return verifyServerCertificate;
+ }
+
+ @Override
+ public String toString()
+ {
+ return "MySQLConnectorConfig{" +
+ "useSSL='" + useSSL + '\'' +
+ ", clientCertificateKeyStoreUrl='" + clientCertificateKeyStoreUrl + '\'' +
+ ", clientCertificateKeyStoreType='" + clientCertificateKeyStoreType + '\'' +
+ ", verifyServerCertificate='" + verifyServerCertificate + '\'' +
+ ", trustCertificateKeyStoreUrl='" + trustCertificateKeyStoreUrl + '\'' +
+ ", trustCertificateKeyStoreType='" + trustCertificateKeyStoreType + '\'' +
+ ", enabledSSLCipherSuites=" + enabledSSLCipherSuites +
+ ", enabledTLSProtocols=" + enabledTLSProtocols +
+ '}';
+ }
+}
diff --git a/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLMetadataStorageModule.java b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLMetadataStorageModule.java
index 211d5ca0b0e..4ba1cb8177b 100644
--- a/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLMetadataStorageModule.java
+++ b/extensions-core/mysql-metadata-storage/src/main/java/io/druid/metadata/storage/mysql/MySQLMetadataStorageModule.java
@@ -23,6 +23,7 @@
import com.google.common.collect.ImmutableList;
import com.google.inject.Binder;
import com.google.inject.Key;
+import io.druid.guice.JsonConfigProvider;
import io.druid.guice.LazySingleton;
import io.druid.guice.PolyBind;
import io.druid.guice.SQLMetadataStorageDruidModule;
@@ -56,6 +57,8 @@ public void configure(Binder binder)
{
super.configure(binder);
+ JsonConfigProvider.bind(binder, "druid.metadata.mysql.ssl", MySQLConnectorConfig.class);
+
PolyBind
.optionBinder(binder, Key.get(MetadataStorageProvider.class))
.addBinding(TYPE)
diff --git a/extensions-core/postgresql-metadata-storage/pom.xml b/extensions-core/postgresql-metadata-storage/pom.xml
index d4625a6499c..5d413021e47 100644
--- a/extensions-core/postgresql-metadata-storage/pom.xml
+++ b/extensions-core/postgresql-metadata-storage/pom.xml
@@ -28,7 +28,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/protobuf-extensions/pom.xml b/extensions-core/protobuf-extensions/pom.xml
index e1a14d412b6..afe7838d204 100644
--- a/extensions-core/protobuf-extensions/pom.xml
+++ b/extensions-core/protobuf-extensions/pom.xml
@@ -16,9 +16,7 @@
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -29,7 +27,7 @@
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/s3-extensions/pom.xml b/extensions-core/s3-extensions/pom.xml
index c08208c81e1..d98ea873f33 100644
--- a/extensions-core/s3-extensions/pom.xml
+++ b/extensions-core/s3-extensions/pom.xml
@@ -16,8 +16,7 @@
~ limitations under the License.
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>io.druid.extensions</groupId>
@@ -28,7 +27,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
@@ -45,15 +44,15 @@
<version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
-
<dependency>
- <groupId>net.java.dev.jets3t</groupId>
- <artifactId>jets3t</artifactId>
+ <groupId>io.druid</groupId>
+ <artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
- <artifactId>java-util</artifactId>
+ <groupId>net.java.dev.jets3t</groupId>
+ <artifactId>jets3t</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
diff --git a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentFinder.java b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentFinder.java
index d6d773640e8..3f4529ec99a 100644
--- a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentFinder.java
+++ b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentFinder.java
@@ -21,9 +21,8 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
-import com.google.common.collect.Sets;
import com.google.inject.Inject;
-
+import io.druid.java.util.common.Pair;
import io.druid.java.util.common.logger.Logger;
import io.druid.segment.loading.DataSegmentFinder;
import io.druid.segment.loading.SegmentLoadingException;
@@ -35,9 +34,11 @@
import java.io.IOException;
import java.io.InputStream;
+import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Collectors;
public class S3DataSegmentFinder implements DataSegmentFinder
{
@@ -62,7 +63,7 @@ public S3DataSegmentFinder(
@Override
public Set<DataSegment> findSegments(String workingDirPath, boolean updateDescriptor) throws SegmentLoadingException
{
- final Set<DataSegment> segments = Sets.newHashSet();
+ final Map<String, Pair<DataSegment, Long>> timestampedSegments = new HashMap<>();
try {
Iterator<StorageObject> objectsIterator = S3Utils.storageObjectsIterator(
@@ -103,7 +104,12 @@ public S3DataSegmentFinder(
s3Client.putObject(config.getBucket(), newDescJsonObject);
}
}
- segments.add(dataSegment);
+
+ DataSegmentFinder.putInMapRetainingNewest(
+ timestampedSegments,
+ dataSegment,
+ indexObject.getLastModifiedDate() == null ? 0 : indexObject.getLastModifiedDate().getTime()
+ );
}
} else {
throw new SegmentLoadingException(
@@ -124,6 +130,6 @@ public S3DataSegmentFinder(
Throwables.propagateIfInstanceOf(e, SegmentLoadingException.class);
Throwables.propagate(e);
}
- return segments;
+ return timestampedSegments.values().stream().map(x -> x.lhs).collect(Collectors.toSet());
}
}
diff --git a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java
index 983837865e8..643b30407d9 100644
--- a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java
+++ b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentMover.java
@@ -72,8 +72,11 @@ public DataSegment move(DataSegment segment, Map<String, Object> targetLoadSpec)
final String targetS3Bucket = MapUtils.getString(targetLoadSpec, "bucket");
final String targetS3BaseKey = MapUtils.getString(targetLoadSpec, "baseKey");
- final String targetS3Path = S3Utils.constructSegmentPath(targetS3BaseKey, DataSegmentPusher.getDefaultStorageDir(segment));
- String targetS3DescriptorPath = S3Utils.descriptorPathForSegmentPath(targetS3Path);
+ final String targetS3Path = S3Utils.constructSegmentPath(
+ targetS3BaseKey,
+ DataSegmentPusher.getDefaultStorageDir(segment, false)
+ );
+ final String targetS3DescriptorPath = S3Utils.descriptorPathForSegmentPath(targetS3Path);
if (targetS3Bucket.isEmpty()) {
throw new SegmentLoadingException("Target S3 bucket is not specified");
diff --git a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPusher.java b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPusher.java
index 1100287cb96..eb5c4a9c10d 100644
--- a/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPusher.java
+++ b/extensions-core/s3-extensions/src/main/java/io/druid/storage/s3/S3DataSegmentPusher.java
@@ -24,9 +24,9 @@
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.inject.Inject;
-import com.metamx.emitter.EmittingLogger;
import io.druid.java.util.common.CompressionUtils;
import io.druid.java.util.common.StringUtils;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.segment.SegmentUtils;
import io.druid.segment.loading.DataSegmentPusher;
import io.druid.timeline.DataSegment;
@@ -88,9 +88,10 @@ public String getPathForHadoop(String dataSource)
}
@Override
- public DataSegment push(final File indexFilesDir, final DataSegment inSegment) throws IOException
+ public DataSegment push(final File indexFilesDir, final DataSegment inSegment, final boolean useUniquePath)
+ throws IOException
{
- final String s3Path = S3Utils.constructSegmentPath(config.getBaseKey(), getStorageDir(inSegment));
+ final String s3Path = S3Utils.constructSegmentPath(config.getBaseKey(), getStorageDir(inSegment, useUniquePath));
log.info("Copying segment[%s] to S3 at location[%s]", inSegment.getIdentifier(), s3Path);
@@ -105,21 +106,10 @@ public DataSegment push(final File indexFilesDir, final DataSegment inSegment) t
public DataSegment call() throws Exception
{
S3Object toPush = new S3Object(zipOutFile);
-
- final String outputBucket = config.getBucket();
- final String s3DescriptorPath = S3Utils.descriptorPathForSegmentPath(s3Path);
-
- toPush.setBucketName(outputBucket);
- toPush.setKey(s3Path);
- if (!config.getDisableAcl()) {
- toPush.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL);
- }
-
- log.info("Pushing %s.", toPush);
- s3Client.putObject(outputBucket, toPush);
+ putObject(config.getBucket(), s3Path, toPush);
final DataSegment outSegment = inSegment.withSize(indexSize)
- .withLoadSpec(makeLoadSpec(outputBucket, toPush.getKey()))
+ .withLoadSpec(makeLoadSpec(config.getBucket(), toPush.getKey()))
.withBinaryVersion(SegmentUtils.getVersionFromDir(indexFilesDir));
File descriptorFile = File.createTempFile("druid", "descriptor.json");
@@ -127,14 +117,12 @@ public DataSegment call() throws Exception
// runtime, and because Guava deletes methods over time, that causes incompatibilities.
Files.write(descriptorFile.toPath(), jsonMapper.writeValueAsBytes(outSegment));
S3Object descriptorObject = new S3Object(descriptorFile);
- descriptorObject.setBucketName(outputBucket);
- descriptorObject.setKey(s3DescriptorPath);
- if (!config.getDisableAcl()) {
- descriptorObject.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL);
- }
- log.info("Pushing %s", descriptorObject);
- s3Client.putObject(outputBucket, descriptorObject);
+ putObject(
+ config.getBucket(),
+ S3Utils.descriptorPathForSegmentPath(s3Path),
+ descriptorObject
+ );
log.info("Deleting zipped index File[%s]", zipOutFile);
zipOutFile.delete();
@@ -164,7 +152,6 @@ public DataSegment call() throws Exception
/**
* Any change in loadSpec need to be reflected {@link io.druid.indexer.JobHelper#getURIFromSegment()}
- *
*/
@SuppressWarnings("JavadocReference")
private Map<String, Object> makeLoadSpec(String bucket, String key)
@@ -180,4 +167,17 @@ public DataSegment call() throws Exception
config.isUseS3aSchema() ? "s3a" : "s3n"
);
}
+
+ private void putObject(String bucketName, String path, S3Object object) throws ServiceException
+ {
+ object.setBucketName(bucketName);
+ object.setKey(path);
+ if (!config.getDisableAcl()) {
+ object.setAcl(GSAccessControlList.REST_CANNED_BUCKET_OWNER_FULL_CONTROL);
+ }
+
+ log.info("Pushing %s.", object);
+
+ s3Client.putObject(bucketName, object);
+ }
}
diff --git a/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentFinderTest.java b/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentFinderTest.java
index f0df427ccb2..55ad817003d 100644
--- a/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentFinderTest.java
+++ b/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentFinderTest.java
@@ -124,7 +124,6 @@
private String indexZip4_1;
-
@BeforeClass
public static void setUpStatic()
{
@@ -210,31 +209,51 @@ public void testFindSegments() throws Exception
final String serializedSegment4_0 = mapper.writeValueAsString(updatedSegment4_0);
final String serializedSegment4_1 = mapper.writeValueAsString(updatedSegment4_1);
- Assert.assertNotEquals(serializedSegment1,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor1).getDataInputStream()));
- Assert.assertNotEquals(serializedSegment2,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor2).getDataInputStream()));
- Assert.assertNotEquals(serializedSegment3,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor3).getDataInputStream()));
- Assert.assertNotEquals(serializedSegment4_0,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_0).getDataInputStream()));
- Assert.assertNotEquals(serializedSegment4_1,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_1).getDataInputStream()));
+ Assert.assertNotEquals(
+ serializedSegment1,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor1).getDataInputStream())
+ );
+ Assert.assertNotEquals(
+ serializedSegment2,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor2).getDataInputStream())
+ );
+ Assert.assertNotEquals(
+ serializedSegment3,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor3).getDataInputStream())
+ );
+ Assert.assertNotEquals(
+ serializedSegment4_0,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_0).getDataInputStream())
+ );
+ Assert.assertNotEquals(
+ serializedSegment4_1,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_1).getDataInputStream())
+ );
final Set<DataSegment> segments2 = s3DataSegmentFinder.findSegments("", true);
Assert.assertEquals(segments, segments2);
- Assert.assertEquals(serializedSegment1,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor1).getDataInputStream()));
- Assert.assertEquals(serializedSegment2,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor2).getDataInputStream()));
- Assert.assertEquals(serializedSegment3,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor3).getDataInputStream()));
- Assert.assertEquals(serializedSegment4_0,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_0).getDataInputStream()));
- Assert.assertEquals(serializedSegment4_1,
- IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_1).getDataInputStream()));
+ Assert.assertEquals(
+ serializedSegment1,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor1).getDataInputStream())
+ );
+ Assert.assertEquals(
+ serializedSegment2,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor2).getDataInputStream())
+ );
+ Assert.assertEquals(
+ serializedSegment3,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor3).getDataInputStream())
+ );
+ Assert.assertEquals(
+ serializedSegment4_0,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_0).getDataInputStream())
+ );
+ Assert.assertEquals(
+ serializedSegment4_1,
+ IOUtils.toString(mockS3Client.getObject(bucket, descriptor4_1).getDataInputStream())
+ );
}
@Test(expected = SegmentLoadingException.class)
@@ -268,9 +287,7 @@ public void testFindSegmentsWithworkingDirPath() throws SegmentLoadingException
public void testFindSegmentsUpdateLoadSpec() throws Exception
{
config.setBucket("amazing");
- final DataSegment segmentMissingLoadSpec = DataSegment.builder(SEGMENT_1)
- .loadSpec(ImmutableMap.of())
- .build();
+ final DataSegment segmentMissingLoadSpec = DataSegment.builder(SEGMENT_1).loadSpec(ImmutableMap.of()).build();
final S3DataSegmentFinder s3DataSegmentFinder = new S3DataSegmentFinder(mockS3Client, config, mapper);
final String segmentPath = baseKey + "/interval_missing_load_spec/v1/1/";
final String descriptorPath = S3Utils.descriptorPathForSegmentPath(segmentPath);
@@ -304,6 +321,32 @@ public void testFindSegmentsUpdateLoadSpec() throws Exception
Assert.assertEquals(indexPath, testLoadSpec.get("key"));
}
+ @Test
+ public void testPreferNewestSegment() throws Exception
+ {
+ baseKey = "replicaDataSource";
+
+ config = new S3DataSegmentPusherConfig();
+ config.setBucket(bucket);
+ config.setBaseKey(baseKey);
+
+ descriptor1 = S3Utils.descriptorPathForSegmentPath(baseKey + "/interval10/v1/0/older/");
+ descriptor2 = S3Utils.descriptorPathForSegmentPath(baseKey + "/interval10/v1/0/newer/");
+
+ indexZip1 = S3Utils.indexZipForSegmentPath(descriptor1);
+ indexZip2 = S3Utils.indexZipForSegmentPath(descriptor2);
+
+ mockS3Client.putObject(bucket, new S3Object(descriptor1, mapper.writeValueAsString(SEGMENT_1)));
+ mockS3Client.putObject(bucket, new S3Object(indexZip1, "dummy"));
+ mockS3Client.putObject(bucket, new S3Object(descriptor2, mapper.writeValueAsString(SEGMENT_1)));
+ mockS3Client.putObject(bucket, new S3Object(indexZip2, "dummy"));
+
+ final S3DataSegmentFinder s3DataSegmentFinder = new S3DataSegmentFinder(mockS3Client, config, mapper);
+ final Set<DataSegment> segments = s3DataSegmentFinder.findSegments("", false);
+
+ Assert.assertEquals(1, segments.size());
+ }
+
private String getDescriptorPath(DataSegment segment)
{
return S3Utils.descriptorPathForSegmentPath(String.valueOf(segment.getLoadSpec().get("key")));
diff --git a/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentPusherTest.java b/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentPusherTest.java
index 32818b17e48..841f10e1c66 100644
--- a/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentPusherTest.java
+++ b/extensions-core/s3-extensions/src/test/java/io/druid/storage/s3/S3DataSegmentPusherTest.java
@@ -64,6 +64,20 @@ public void setValue(T value)
@Test
public void testPush() throws Exception
+ {
+ testPushInternal(false, "key/foo/2015-01-01T00:00:00\\.000Z_2016-01-01T00:00:00\\.000Z/0/0/index\\.zip");
+ }
+
+ @Test
+ public void testPushUseUniquePath() throws Exception
+ {
+ testPushInternal(
+ true,
+ "key/foo/2015-01-01T00:00:00\\.000Z_2016-01-01T00:00:00\\.000Z/0/0/[A-Za-z0-9-]{36}/index\\.zip"
+ );
+ }
+
+ private void testPushInternal(boolean useUniquePath, String matcher) throws Exception
{
RestS3Service s3Client = EasyMock.createStrictMock(RestS3Service.class);
@@ -113,14 +127,15 @@ public S3Object answer() throws Throwable
size
);
- DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush);
+ DataSegment segment = pusher.push(tempFolder.getRoot(), segmentToPush, useUniquePath);
Assert.assertEquals(segmentToPush.getSize(), segment.getSize());
Assert.assertEquals(1, (int) segment.getBinaryVersion());
Assert.assertEquals("bucket", segment.getLoadSpec().get("bucket"));
- Assert.assertEquals(
- "key/foo/2015-01-01T00:00:00.000Z_2016-01-01T00:00:00.000Z/0/0/index.zip",
- segment.getLoadSpec().get("key"));
+ Assert.assertTrue(
+ segment.getLoadSpec().get("key").toString(),
+ segment.getLoadSpec().get("key").toString().matches(matcher)
+ );
Assert.assertEquals("s3_zip", segment.getLoadSpec().get("type"));
// Verify that the pushed S3Object contains the correct data
diff --git a/extensions-core/simple-client-sslcontext/pom.xml b/extensions-core/simple-client-sslcontext/pom.xml
index 9277db3a552..bc5d4b8cc0b 100644
--- a/extensions-core/simple-client-sslcontext/pom.xml
+++ b/extensions-core/simple-client-sslcontext/pom.xml
@@ -1,11 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>druid</artifactId>
<groupId>io.druid</groupId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
@@ -35,8 +33,9 @@
<scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.metamx</groupId>
+ <groupId>io.druid</groupId>
<artifactId>java-util</artifactId>
+ <version>${project.parent.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
diff --git a/extensions-core/simple-client-sslcontext/src/main/java/io/druid/https/SSLContextProvider.java b/extensions-core/simple-client-sslcontext/src/main/java/io/druid/https/SSLContextProvider.java
index ccdacf1b733..ee53c9278e0 100644
--- a/extensions-core/simple-client-sslcontext/src/main/java/io/druid/https/SSLContextProvider.java
+++ b/extensions-core/simple-client-sslcontext/src/main/java/io/druid/https/SSLContextProvider.java
@@ -22,7 +22,7 @@
import com.google.common.base.Throwables;
import com.google.inject.Inject;
import com.google.inject.Provider;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.emitter.EmittingLogger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;
diff --git a/extensions-core/stats/pom.xml b/extensions-core/stats/pom.xml
index e6dd75e687d..eb3bc9017ed 100644
--- a/extensions-core/stats/pom.xml
+++ b/extensions-core/stats/pom.xml
@@ -29,7 +29,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
diff --git a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/StandardDeviationPostAggregator.java b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/StandardDeviationPostAggregator.java
index 443d0126cb7..f7034844d81 100644
--- a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/StandardDeviationPostAggregator.java
+++ b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/StandardDeviationPostAggregator.java
@@ -107,7 +107,8 @@ public String toString()
return "StandardDeviationPostAggregator{" +
"name='" + name + '\'' +
", fieldName='" + fieldName + '\'' +
- ", isVariancePop='" + isVariancePop + '\'' +
+ ", estimator='" + estimator + '\'' +
+ ", isVariancePop=" + isVariancePop +
'}';
}
@@ -116,6 +117,7 @@ public String toString()
{
return new CacheKeyBuilder(PostAggregatorIds.VARIANCE_STANDARD_DEVIATION)
.appendString(fieldName)
+ .appendString(estimator)
.appendBoolean(isVariancePop)
.build();
}
diff --git a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorCollector.java b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorCollector.java
index a6c8aad4ee3..ee7e6c9d9cf 100644
--- a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorCollector.java
+++ b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorCollector.java
@@ -59,20 +59,15 @@ public static VarianceAggregatorCollector from(ByteBuffer buffer)
return new VarianceAggregatorCollector(buffer.getLong(), buffer.getDouble(), buffer.getDouble());
}
- public static final Comparator<VarianceAggregatorCollector> COMPARATOR = new Comparator<VarianceAggregatorCollector>()
- {
- @Override
- public int compare(VarianceAggregatorCollector o1, VarianceAggregatorCollector o2)
- {
- int compare = Longs.compare(o1.count, o2.count);
+ public static final Comparator<VarianceAggregatorCollector> COMPARATOR = (o1, o2) -> {
+ int compare = Longs.compare(o1.count, o2.count);
+ if (compare == 0) {
+ compare = Doubles.compare(o1.sum, o2.sum);
if (compare == 0) {
- compare = Doubles.compare(o1.sum, o2.sum);
- if (compare == 0) {
- compare = Doubles.compare(o1.nvariance, o2.nvariance);
- }
+ compare = Doubles.compare(o1.nvariance, o2.nvariance);
}
- return compare;
}
+ return compare;
};
void fold(@Nullable VarianceAggregatorCollector other)
@@ -114,13 +109,6 @@ public VarianceAggregatorCollector()
this(0, 0, 0);
}
- public void reset()
- {
- count = 0;
- sum = 0;
- nvariance = 0;
- }
-
void copyFrom(VarianceAggregatorCollector other)
{
this.count = other.count;
diff --git a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorFactory.java b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorFactory.java
index aa868447835..86657977e82 100644
--- a/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorFactory.java
+++ b/extensions-core/stats/src/main/java/io/druid/query/aggregation/variance/VarianceAggregatorFactory.java
@@ -34,13 +34,13 @@
import io.druid.query.aggregation.NoopAggregator;
import io.druid.query.aggregation.NoopBufferAggregator;
import io.druid.query.aggregation.ObjectAggregateCombiner;
+import io.druid.query.cache.CacheKeyBuilder;
import io.druid.segment.ColumnSelectorFactory;
import io.druid.segment.ColumnValueSelector;
import io.druid.segment.NilColumnValueSelector;
import org.apache.commons.codec.binary.Base64;
import java.nio.ByteBuffer;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
@@ -184,7 +184,7 @@ public AggregatorFactory getCombiningFactory()
@Override
public List<AggregatorFactory> getRequiredColumns()
{
- return Arrays.<AggregatorFactory>asList(new VarianceAggregatorFactory(fieldName, fieldName, estimator, inputType));
+ return Collections.singletonList(new VarianceAggregatorFactory(fieldName, fieldName, estimator, inputType));
}
@Override
@@ -258,25 +258,23 @@ public String getInputType()
@Override
public byte[] getCacheKey()
{
- byte[] fieldNameBytes = StringUtils.toUtf8(fieldName);
- byte[] inputTypeBytes = StringUtils.toUtf8(inputType);
- return ByteBuffer.allocate(2 + fieldNameBytes.length + 1 + inputTypeBytes.length)
- .put(AggregatorUtil.VARIANCE_CACHE_TYPE_ID)
- .put(isVariancePop ? (byte) 1 : 0)
- .put(fieldNameBytes)
- .put((byte) 0xFF)
- .put(inputTypeBytes)
- .array();
+ return new CacheKeyBuilder(AggregatorUtil.VARIANCE_CACHE_TYPE_ID)
+ .appendString(fieldName)
+ .appendString(inputType)
+ .appendBoolean(isVariancePop)
+ .appendString(estimator)
+ .build();
}
@Override
public String toString()
{
- return getClass().getSimpleName() + "{" +
+ return "VarianceAggregatorFactory{" +
"fieldName='" + fieldName + '\'' +
", name='" + name + '\'' +
- ", isVariancePop='" + isVariancePop + '\'' +
+ ", estimator='" + estimator + '\'' +
", inputType='" + inputType + '\'' +
+ ", isVariancePop=" + isVariancePop +
'}';
}
@@ -289,29 +287,18 @@ public boolean equals(Object o)
if (o == null || getClass() != o.getClass()) {
return false;
}
-
VarianceAggregatorFactory that = (VarianceAggregatorFactory) o;
-
- if (!Objects.equals(name, that.name)) {
- return false;
- }
- if (!Objects.equals(isVariancePop, that.isVariancePop)) {
- return false;
- }
- if (!Objects.equals(inputType, that.inputType)) {
- return false;
- }
-
- return true;
+ return isVariancePop == that.isVariancePop &&
+ Objects.equals(fieldName, that.fieldName) &&
+ Objects.equals(name, that.name) &&
+ Objects.equals(estimator, that.estimator) &&
+ Objects.equals(inputType, that.inputType);
}
@Override
public int hashCode()
{
- int result = fieldName.hashCode();
- result = 31 * result + Objects.hashCode(name);
- result = 31 * result + Objects.hashCode(isVariancePop);
- result = 31 * result + Objects.hashCode(inputType);
- return result;
+
+ return Objects.hash(fieldName, name, estimator, inputType, isVariancePop);
}
}
diff --git a/hll/pom.xml b/hll/pom.xml
index 653b2ca63b3..56964212043 100644
--- a/hll/pom.xml
+++ b/hll/pom.xml
@@ -24,7 +24,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<artifactId>druid-hll</artifactId>
diff --git a/indexing-hadoop/pom.xml b/indexing-hadoop/pom.xml
index 9ab3867d3bf..83623d011cd 100644
--- a/indexing-hadoop/pom.xml
+++ b/indexing-hadoop/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/indexing-hadoop/src/main/java/io/druid/indexer/HadoopIngestionSpec.java b/indexing-hadoop/src/main/java/io/druid/indexer/HadoopIngestionSpec.java
index aea58796b65..b227d6fe4df 100644
--- a/indexing-hadoop/src/main/java/io/druid/indexer/HadoopIngestionSpec.java
+++ b/indexing-hadoop/src/main/java/io/druid/indexer/HadoopIngestionSpec.java
@@ -37,6 +37,7 @@
import org.joda.time.Interval;
import java.io.IOException;
+import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
@@ -151,20 +152,19 @@ public static HadoopIngestionSpec updateSegmentListIfDatasourcePathSpecIsUsed(
String ingestionSpec = "ingestionSpec";
Map<String, Object> pathSpec = spec.getIOConfig().getPathSpec();
- Map<String, Object> datasourcePathSpec = null;
+ List<Map<String, Object>> datasourcePathSpecs = new ArrayList<>();
if (pathSpec.get(type).equals(dataSource)) {
- datasourcePathSpec = pathSpec;
+ datasourcePathSpecs.add(pathSpec);
} else if (pathSpec.get(type).equals(multi)) {
List<Map<String, Object>> childPathSpecs = (List<Map<String, Object>>) pathSpec.get(children);
for (Map<String, Object> childPathSpec : childPathSpecs) {
if (childPathSpec.get(type).equals(dataSource)) {
- datasourcePathSpec = childPathSpec;
- break;
+ datasourcePathSpecs.add(childPathSpec);
}
}
}
- if (datasourcePathSpec != null) {
+ for (Map<String, Object> datasourcePathSpec : datasourcePathSpecs) {
Map<String, Object> ingestionSpecMap = (Map<String, Object>) datasourcePathSpec.get(ingestionSpec);
DatasourceIngestionSpec ingestionSpecObj = jsonMapper.convertValue(
ingestionSpecMap,
diff --git a/indexing-hadoop/src/main/java/io/druid/indexer/IndexGeneratorJob.java b/indexing-hadoop/src/main/java/io/druid/indexer/IndexGeneratorJob.java
index c9111d00cd3..a9726bb2db1 100644
--- a/indexing-hadoop/src/main/java/io/druid/indexer/IndexGeneratorJob.java
+++ b/indexing-hadoop/src/main/java/io/druid/indexer/IndexGeneratorJob.java
@@ -64,6 +64,7 @@
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapred.InvalidJobConfException;
import org.apache.hadoop.mapreduce.Counter;
+import org.apache.hadoop.mapreduce.Counters;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.JobContext;
import org.apache.hadoop.mapreduce.Partitioner;
@@ -210,9 +211,17 @@ public boolean run()
boolean success = job.waitForCompletion(true);
- Counter invalidRowCount = job.getCounters()
- .findCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER);
- jobStats.setInvalidRowCount(invalidRowCount.getValue());
+ Counters counters = job.getCounters();
+ if (counters == null) {
+ log.info("No counters found for job [%s]", job.getJobName());
+ } else {
+ Counter invalidRowCount = counters.findCounter(HadoopDruidIndexerConfig.IndexJobCounters.INVALID_ROW_COUNTER);
+ if (invalidRowCount != null) {
+ jobStats.setInvalidRowCount(invalidRowCount.getValue());
+ } else {
+ log.info("No invalid row counter found for job [%s]", job.getJobName());
+ }
+ }
return success;
}
@@ -258,6 +267,7 @@ private static IncrementalIndex makeIncrementalIndex(
private AggregatorFactory[] aggregators;
private AggregatorFactory[] combiningAggs;
+ private Map<String, InputRowSerde.IndexSerdeTypeHelper> typeHelperMap;
@Override
protected void setup(Context context)
@@ -269,6 +279,11 @@ protected void setup(Context context)
for (int i = 0; i < aggregators.length; ++i) {
combiningAggs[i] = aggregators[i].getCombiningFactory();
}
+ typeHelperMap = InputRowSerde.getTypeHelperMap(config.getSchema()
+ .getDataSchema()
+ .getParser()
+ .getParseSpec()
+ .getDimensionsSpec());
}
@Override
@@ -299,9 +314,9 @@ protected void innerMap(
// and they contain the columns as they show up in the segment after ingestion, not what you would see in raw
// data
byte[] serializedInputRow = inputRow instanceof SegmentInputRow ?
- InputRowSerde.toBytes(inputRow, combiningAggs, reportParseExceptions)
+ InputRowSerde.toBytes(typeHelperMap, inputRow, combiningAggs, reportParseExceptions)
:
- InputRowSerde.toBytes(inputRow, aggregators, reportParseExceptions);
+ InputRowSerde.toBytes(typeHelperMap, inputRow, aggregators, reportParseExceptions);
context.write(
new SortableBytes(
@@ -322,6 +337,7 @@ protected void innerMap(
private HadoopDruidIndexerConfig config;
private AggregatorFactory[] aggregators;
private AggregatorFactory[] combiningAggs;
+ private Map<String, InputRowSerde.IndexSerdeTypeHelper> typeHelperMap;
@Override
protected void setup(Context context)
@@ -334,6 +350,11 @@ protected void setup(Context context)
for (int i = 0; i < aggregators.length; ++i) {
combiningAggs[i] = aggregators[i].getCombiningFactory();
}
+ typeHelperMap = InputRowSerde.getTypeHelperMap(config.getSchema()
+ .getDataSchema()
+ .getParser()
+ .getParseSpec()
+ .getDimensionsSpec());
}
@Override
@@ -350,11 +371,11 @@ protected void reduce(
SortableBytes keyBytes = SortableBytes.fromBytesWritable(key);
Bucket bucket = Bucket.fromGroupKey(keyBytes.getGroupKey()).lhs;
IncrementalIndex index = makeIncrementalIndex(bucket, combiningAggs, config, null, null);
- index.add(InputRowSerde.fromBytes(first.getBytes(), aggregators));
+ index.add(InputRowSerde.fromBytes(typeHelperMap, first.getBytes(), aggregators));
while (iter.hasNext()) {
context.progress();
- InputRow value = InputRowSerde.fromBytes(iter.next().getBytes(), aggregators);
+ InputRow value = InputRowSerde.fromBytes(typeHelperMap, iter.next().getBytes(), aggregators);
if (!index.canAppendRow()) {
dimOrder.addAll(index.getDimensionOrder());
@@ -381,10 +402,13 @@ private void flushIndexToContextAndClose(BytesWritable key, IncrementalIndex ind
context.progress();
Row row = rows.next();
InputRow inputRow = getInputRowFromRow(row, dimensions);
+
// reportParseExceptions is true as any unparseable data is already handled by the mapper.
+ byte[] serializedRow = InputRowSerde.toBytes(typeHelperMap, inputRow, combiningAggs, true);
+
context.write(
key,
- new BytesWritable(InputRowSerde.toBytes(inputRow, combiningAggs, true))
+ new BytesWritable(serializedRow)
);
}
index.close();
@@ -479,6 +503,7 @@ public void setConf(Configuration config)
private List<String> metricNames = Lists.newArrayList();
private AggregatorFactory[] aggregators;
private AggregatorFactory[] combiningAggs;
+ private Map<String, InputRowSerde.IndexSerdeTypeHelper> typeHelperMap;
protected ProgressIndicator makeProgressIndicator(final Context context)
{
@@ -530,6 +555,11 @@ protected void setup(Context context)
metricNames.add(aggregators[i].getName());
combiningAggs[i] = aggregators[i].getCombiningFactory();
}
+ typeHelperMap = InputRowSerde.getTypeHelperMap(config.getSchema()
+ .getDataSchema()
+ .getParser()
+ .getParseSpec()
+ .getDimensionsSpec());
}
@Override
@@ -597,7 +627,7 @@ public void rejectedExecution(Runnable r, ThreadPoolExecutor executor)
for (final BytesWritable bw : values) {
context.progress();
- final InputRow inputRow = index.formatRow(InputRowSerde.fromBytes(bw.getBytes(), aggregators));
+ final InputRow inputRow = index.formatRow(InputRowSerde.fromBytes(typeHelperMap, bw.getBytes(), aggregators));
int numRows = index.add(inputRow);
++lineCount;
diff --git a/indexing-hadoop/src/main/java/io/druid/indexer/InputRowSerde.java b/indexing-hadoop/src/main/java/io/druid/indexer/InputRowSerde.java
index 672f7713374..cd1dd531604 100644
--- a/indexing-hadoop/src/main/java/io/druid/indexer/InputRowSerde.java
+++ b/indexing-hadoop/src/main/java/io/druid/indexer/InputRowSerde.java
@@ -22,17 +22,24 @@
import com.google.common.base.Supplier;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
+import com.google.common.io.ByteArrayDataInput;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
+
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedInputRow;
+import io.druid.data.input.Rows;
+import io.druid.data.input.impl.DimensionSchema;
+import io.druid.data.input.impl.DimensionsSpec;
import io.druid.java.util.common.IAE;
import io.druid.java.util.common.StringUtils;
import io.druid.java.util.common.logger.Logger;
import io.druid.java.util.common.parsers.ParseException;
import io.druid.query.aggregation.Aggregator;
import io.druid.query.aggregation.AggregatorFactory;
+import io.druid.segment.DimensionHandlerUtils;
import io.druid.segment.VirtualColumns;
+import io.druid.segment.column.ValueType;
import io.druid.segment.incremental.IncrementalIndex;
import io.druid.segment.serde.ComplexMetricSerde;
import io.druid.segment.serde.ComplexMetrics;
@@ -49,7 +56,165 @@
{
private static final Logger log = new Logger(InputRowSerde.class);
- public static final byte[] toBytes(final InputRow row, AggregatorFactory[] aggs, boolean reportParseExceptions)
+ private static final IndexSerdeTypeHelper STRING_HELPER = new StringIndexSerdeTypeHelper();
+ private static final IndexSerdeTypeHelper LONG_HELPER = new LongIndexSerdeTypeHelper();
+ private static final IndexSerdeTypeHelper FLOAT_HELPER = new FloatIndexSerdeTypeHelper();
+ private static final IndexSerdeTypeHelper DOUBLE_HELPER = new DoubleIndexSerdeTypeHelper();
+
+ public interface IndexSerdeTypeHelper<T>
+ {
+ ValueType getType();
+
+ void serialize(ByteArrayDataOutput out, Object value, boolean reportParseExceptions);
+
+ T deserialize(ByteArrayDataInput in);
+ }
+
+ public static Map<String, IndexSerdeTypeHelper> getTypeHelperMap(DimensionsSpec dimensionsSpec)
+ {
+ Map<String, IndexSerdeTypeHelper> typeHelperMap = Maps.newHashMap();
+ for (DimensionSchema dimensionSchema : dimensionsSpec.getDimensions()) {
+ IndexSerdeTypeHelper typeHelper;
+ switch (dimensionSchema.getValueType()) {
+ case STRING:
+ typeHelper = STRING_HELPER;
+ break;
+ case LONG:
+ typeHelper = LONG_HELPER;
+ break;
+ case FLOAT:
+ typeHelper = FLOAT_HELPER;
+ break;
+ case DOUBLE:
+ typeHelper = DOUBLE_HELPER;
+ break;
+ default:
+ throw new IAE("Invalid type: [%s]", dimensionSchema.getValueType());
+ }
+ typeHelperMap.put(dimensionSchema.getName(), typeHelper);
+ }
+ return typeHelperMap;
+ }
+
+ public static class StringIndexSerdeTypeHelper implements IndexSerdeTypeHelper<List<String>>
+ {
+ @Override
+ public ValueType getType()
+ {
+ return ValueType.STRING;
+ }
+
+ @Override
+ public void serialize(ByteArrayDataOutput out, Object value, boolean reportParseExceptions)
+ {
+ List<String> values = Rows.objectToStrings(value);
+ try {
+ writeStringArray(values, out);
+ }
+ catch (IOException ioe) {
+ throw new RuntimeException(ioe);
+ }
+ }
+
+ @Override
+ public List<String> deserialize(ByteArrayDataInput in)
+ {
+ try {
+ return readStringArray(in);
+ }
+ catch (IOException ioe) {
+ throw new RuntimeException(ioe);
+ }
+ }
+ }
+
+ public static class LongIndexSerdeTypeHelper implements IndexSerdeTypeHelper<Long>
+ {
+ @Override
+ public ValueType getType()
+ {
+ return ValueType.LONG;
+ }
+
+ @Override
+ public void serialize(ByteArrayDataOutput out, Object value, boolean reportParseExceptions)
+ {
+ Long ret = DimensionHandlerUtils.convertObjectToLong(value, reportParseExceptions);
+ if (ret == null) {
+ // remove null -> zero conversion when https://github.com/druid-io/druid/pull/5278 series of patches is merged
+ // we'll also need to change the serialized encoding so that it can represent numeric nulls
+ ret = DimensionHandlerUtils.ZERO_LONG;
+ }
+ out.writeLong(ret);
+ }
+
+ @Override
+ public Long deserialize(ByteArrayDataInput in)
+ {
+ return in.readLong();
+ }
+ }
+
+ public static class FloatIndexSerdeTypeHelper implements IndexSerdeTypeHelper<Float>
+ {
+ @Override
+ public ValueType getType()
+ {
+ return ValueType.FLOAT;
+ }
+
+ @Override
+ public void serialize(ByteArrayDataOutput out, Object value, boolean reportParseExceptions)
+ {
+ Float ret = DimensionHandlerUtils.convertObjectToFloat(value, reportParseExceptions);
+ if (ret == null) {
+ // remove null -> zero conversion when https://github.com/druid-io/druid/pull/5278 series of patches is merged
+ // we'll also need to change the serialized encoding so that it can represent numeric nulls
+ ret = DimensionHandlerUtils.ZERO_FLOAT;
+ }
+ out.writeFloat(ret);
+ }
+
+ @Override
+ public Float deserialize(ByteArrayDataInput in)
+ {
+ return in.readFloat();
+ }
+ }
+
+ public static class DoubleIndexSerdeTypeHelper implements IndexSerdeTypeHelper<Double>
+ {
+ @Override
+ public ValueType getType()
+ {
+ return ValueType.DOUBLE;
+ }
+
+ @Override
+ public void serialize(ByteArrayDataOutput out, Object value, boolean reportParseExceptions)
+ {
+ Double ret = DimensionHandlerUtils.convertObjectToDouble(value, reportParseExceptions);
+ if (ret == null) {
+ // remove null -> zero conversion when https://github.com/druid-io/druid/pull/5278 series of patches is merged
+ // we'll also need to change the serialized encoding so that it can represent numeric nulls
+ ret = DimensionHandlerUtils.ZERO_DOUBLE;
+ }
+ out.writeDouble(ret);
+ }
+
+ @Override
+ public Double deserialize(ByteArrayDataInput in)
+ {
+ return in.readDouble();
+ }
+ }
+
+ public static final byte[] toBytes(
+ final Map<String, IndexSerdeTypeHelper> typeHelperMap,
+ final InputRow row,
+ AggregatorFactory[] aggs,
+ boolean reportParseExceptions
+ )
{
try {
ByteArrayDataOutput out = ByteStreams.newDataOutput();
@@ -63,9 +228,12 @@
WritableUtils.writeVInt(out, dimList.size());
if (dimList != null) {
for (String dim : dimList) {
- List<String> dimValues = row.getDimension(dim);
+ IndexSerdeTypeHelper typeHelper = typeHelperMap.get(dim);
+ if (typeHelper == null) {
+ typeHelper = STRING_HELPER;
+ }
writeString(dim, out);
- writeStringArray(dimValues, out);
+ typeHelper.serialize(out, row.getRaw(dim), reportParseExceptions);
}
}
@@ -176,10 +344,14 @@ private static String readString(DataInput in) throws IOException
return values;
}
- public static final InputRow fromBytes(byte[] data, AggregatorFactory[] aggs)
+ public static final InputRow fromBytes(
+ final Map<String, IndexSerdeTypeHelper> typeHelperMap,
+ byte[] data,
+ AggregatorFactory[] aggs
+ )
{
try {
- DataInput in = ByteStreams.newDataInput(data);
+ ByteArrayDataInput in = ByteStreams.newDataInput(data);
//Read timestamp
long timestamp = in.readLong();
@@ -192,14 +364,25 @@ public static final InputRow fromBytes(byte[] data, AggregatorFactory[] aggs)
for (int i = 0; i < dimNum; i++) {
String dimension = readString(in);
dimensions.add(dimension);
- List<String> dimensionValues = readStringArray(in);
- if (dimensionValues == null) {
+
+ IndexSerdeTypeHelper typeHelper = typeHelperMap.get(dimension);
+ if (typeHelper == null) {
+ typeHelper = STRING_HELPER;
+ }
+ Object dimValues = typeHelper.deserialize(in);
+ if (dimValues == null) {
continue;
}
- if (dimensionValues.size() == 1) {
- event.put(dimension, dimensionValues.get(0));
+
+ if (typeHelper.getType() == ValueType.STRING) {
+ List<String> dimensionValues = (List<String>) dimValues;
+ if (dimensionValues.size() == 1) {
+ event.put(dimension, dimensionValues.get(0));
+ } else {
+ event.put(dimension, dimensionValues);
+ }
} else {
- event.put(dimension, dimensionValues);
+ event.put(dimension, dimValues);
}
}
diff --git a/indexing-hadoop/src/main/java/io/druid/indexer/JobHelper.java b/indexing-hadoop/src/main/java/io/druid/indexer/JobHelper.java
index 7ce678045c7..8975c01d86a 100644
--- a/indexing-hadoop/src/main/java/io/druid/indexer/JobHelper.java
+++ b/indexing-hadoop/src/main/java/io/druid/indexer/JobHelper.java
@@ -91,6 +91,7 @@ public static Path distributedClassPath(Path base)
{
return new Path(base, "classpath");
}
+
public static final String INDEX_ZIP = "index.zip";
public static final String DESCRIPTOR_JSON = "descriptor.json";
@@ -568,8 +569,10 @@ public static Path makeFileNamePath(
DataSegmentPusher dataSegmentPusher
)
{
- return new Path(prependFSIfNullScheme(fs, basePath),
- dataSegmentPusher.makeIndexPathName(segmentTemplate, baseFileName));
+ return new Path(
+ prependFSIfNullScheme(fs, basePath),
+ dataSegmentPusher.makeIndexPathName(segmentTemplate, baseFileName)
+ );
}
public static Path makeTmpPath(
@@ -582,9 +585,10 @@ public static Path makeTmpPath(
{
return new Path(
prependFSIfNullScheme(fs, basePath),
- StringUtils.format("./%s.%d",
- dataSegmentPusher.makeIndexPathName(segmentTemplate, JobHelper.INDEX_ZIP),
- taskAttemptID.getId()
+ StringUtils.format(
+ "./%s.%d",
+ dataSegmentPusher.makeIndexPathName(segmentTemplate, JobHelper.INDEX_ZIP),
+ taskAttemptID.getId()
)
);
}
diff --git a/indexing-hadoop/src/main/java/io/druid/indexer/hadoop/DatasourceInputFormat.java b/indexing-hadoop/src/main/java/io/druid/indexer/hadoop/DatasourceInputFormat.java
index b4856a925fc..a93459f6163 100644
--- a/indexing-hadoop/src/main/java/io/druid/indexer/hadoop/DatasourceInputFormat.java
+++ b/indexing-hadoop/src/main/java/io/druid/indexer/hadoop/DatasourceInputFormat.java
@@ -29,7 +29,6 @@
import io.druid.indexer.JobHelper;
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.logger.Logger;
-import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
@@ -65,7 +64,7 @@
@Override
public List<InputSplit> getSplits(JobContext context) throws IOException, InterruptedException
{
- Configuration conf = context.getConfiguration();
+ JobConf conf = new JobConf(context.getConfiguration());
String segmentsStr = Preconditions.checkNotNull(
conf.get(CONF_INPUT_SEGMENTS),
@@ -89,7 +88,7 @@
for (WindowedDataSegment segment : segments) {
totalSize += segment.getSegment().getSize();
}
- int mapTask = ((JobConf) conf).getNumMapTasks();
+ int mapTask = conf.getNumMapTasks();
if (mapTask > 0) {
maxSize = totalSize / mapTask;
}
@@ -116,11 +115,10 @@ public int compare(WindowedDataSegment s1, WindowedDataSegment s2)
List<WindowedDataSegment> list = new ArrayList<>();
long size = 0;
- JobConf dummyConf = new JobConf();
org.apache.hadoop.mapred.InputFormat fio = supplier.get();
for (WindowedDataSegment segment : segments) {
if (size + segment.getSegment().getSize() > maxSize && size > 0) {
- splits.add(toDataSourceSplit(list, fio, dummyConf));
+ splits.add(toDataSourceSplit(list, fio, conf));
list = Lists.newArrayList();
size = 0;
}
@@ -130,7 +128,7 @@ public int compare(WindowedDataSegment s1, WindowedDataSegment s2)
}
if (list.size() > 0) {
- splits.add(toDataSourceSplit(list, fio, dummyConf));
+ splits.add(toDataSourceSplit(list, fio, conf));
}
logger.info("Number of splits [%d]", splits.size());
@@ -214,14 +212,14 @@ private DatasourceInputSplit toDataSourceSplit(
try {
return Arrays.stream(split.getLocations());
}
- catch (final IOException e) {
+ catch (final Exception e) {
logger.error(e, "Exception getting locations");
return Stream.empty();
}
}
);
}
- catch (final IOException e) {
+ catch (final Exception e) {
logger.error(e, "Exception getting splits");
return Stream.empty();
}
diff --git a/indexing-hadoop/src/test/java/io/druid/indexer/HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest.java b/indexing-hadoop/src/test/java/io/druid/indexer/HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest.java
index 50f51752cbe..0351a114e9c 100644
--- a/indexing-hadoop/src/test/java/io/druid/indexer/HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest.java
+++ b/indexing-hadoop/src/test/java/io/druid/indexer/HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest.java
@@ -51,9 +51,12 @@
*/
public class HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest
{
- private final String testDatasource = "test";
- private final Interval testDatasourceInterval = Intervals.of("1970/3000");
- private final Interval testDatasourceIntervalPartial = Intervals.of("2050/3000");
+ private static final String testDatasource = "test";
+ private static final String testDatasource2 = "test2";
+ private static final Interval testDatasourceInterval = Intervals.of("1970/3000");
+ private static final Interval testDatasourceInterval2 = Intervals.of("2000/2001");
+ private static final Interval testDatasourceIntervalPartial = Intervals.of("2050/3000");
+
private final ObjectMapper jsonMapper;
public HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest()
@@ -67,7 +70,7 @@ public HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest()
}
private static final DataSegment SEGMENT = new DataSegment(
- "test1",
+ testDatasource,
Intervals.of("2000/3000"),
"ver",
ImmutableMap.<String, Object>of(
@@ -81,6 +84,21 @@ public HadoopIngestionSpecUpdateDatasourcePathSpecSegmentsTest()
2
);
+ private static final DataSegment SEGMENT2 = new DataSegment(
+ testDatasource2,
+ Intervals.of("2000/3000"),
+ "ver2",
+ ImmutableMap.<String, Object>of(
+ "type", "local",
+ "path", "/tmp/index2.zip"
+ ),
+ ImmutableList.of("host2"),
+ ImmutableList.of("visited_sum", "unique_hosts"),
+ NoneShardSpec.instance(),
+ 9,
+ 2
+ );
+
@Test
public void testUpdateSegmentListIfDatasourcePathSpecIsUsedWithNoDatasourcePathSpec() throws Exception
{
@@ -213,6 +231,22 @@ public void testUpdateSegmentListIfDatasourcePathSpecIsUsedWithMultiplePathSpec(
null
),
null
+ ),
+ new DatasourcePathSpec(
+ jsonMapper,
+ null,
+ new DatasourceIngestionSpec(
+ testDatasource2,
+ testDatasourceInterval2,
+ null,
+ null,
+ null,
+ null,
+ null,
+ false,
+ null
+ ),
+ null
)
)
);
@@ -224,6 +258,10 @@ public void testUpdateSegmentListIfDatasourcePathSpecIsUsedWithMultiplePathSpec(
ImmutableList.of(WindowedDataSegment.of(SEGMENT)),
((DatasourcePathSpec) ((MultiplePathSpec) config.getPathSpec()).getChildren().get(1)).getSegments()
);
+ Assert.assertEquals(
+ ImmutableList.of(new WindowedDataSegment(SEGMENT2, testDatasourceInterval2)),
+ ((DatasourcePathSpec) ((MultiplePathSpec) config.getPathSpec()).getChildren().get(2)).getSegments()
+ );
}
private HadoopDruidIndexerConfig testRunUpdateSegmentListIfDatasourcePathSpecIsUsed(
@@ -259,9 +297,21 @@ private HadoopDruidIndexerConfig testRunUpdateSegmentListIfDatasourcePathSpecIsU
);
UsedSegmentLister segmentLister = EasyMock.createMock(UsedSegmentLister.class);
+
EasyMock.expect(
- segmentLister.getUsedSegmentsForIntervals(testDatasource, Lists.newArrayList(jobInterval))
+ segmentLister.getUsedSegmentsForIntervals(
+ testDatasource,
+ Lists.newArrayList(jobInterval != null ? jobInterval.overlap(testDatasourceInterval) : null)
+ )
).andReturn(ImmutableList.of(SEGMENT));
+
+ EasyMock.expect(
+ segmentLister.getUsedSegmentsForIntervals(
+ testDatasource2,
+ Lists.newArrayList(jobInterval != null ? jobInterval.overlap(testDatasourceInterval2) : null)
+ )
+ ).andReturn(ImmutableList.of(SEGMENT2));
+
EasyMock.replay(segmentLister);
spec = HadoopIngestionSpec.updateSegmentListIfDatasourcePathSpecIsUsed(spec, jsonMapper, segmentLister);
diff --git a/indexing-hadoop/src/test/java/io/druid/indexer/IndexGeneratorCombinerTest.java b/indexing-hadoop/src/test/java/io/druid/indexer/IndexGeneratorCombinerTest.java
index 9eaf75349ed..9eb75e27b77 100644
--- a/indexing-hadoop/src/test/java/io/druid/indexer/IndexGeneratorCombinerTest.java
+++ b/indexing-hadoop/src/test/java/io/druid/indexer/IndexGeneratorCombinerTest.java
@@ -25,6 +25,7 @@
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedInputRow;
import io.druid.data.input.impl.DimensionsSpec;
+import io.druid.data.input.impl.StringDimensionSchema;
import io.druid.data.input.impl.StringInputRowParser;
import io.druid.data.input.impl.TimeAndDimsParseSpec;
import io.druid.data.input.impl.TimestampSpec;
@@ -144,6 +145,17 @@ public void testMultipleRowsMerged() throws Exception
);
BytesWritable key = keySortableBytes.toBytesWritable();
+ DimensionsSpec dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new StringDimensionSchema("host"),
+ new StringDimensionSchema("keywords")
+ ),
+ null,
+ null
+ );
+
+ Map<String, InputRowSerde.IndexSerdeTypeHelper> typeHelperMap = InputRowSerde.getTypeHelperMap(dimensionsSpec);
+
InputRow row1 = new MapBasedInputRow(
timestamp,
ImmutableList.<String>of("keywords"),
@@ -163,8 +175,8 @@ public void testMultipleRowsMerged() throws Exception
)
);
List<BytesWritable> rows = Lists.newArrayList(
- new BytesWritable(InputRowSerde.toBytes(row1, aggregators, true)),
- new BytesWritable(InputRowSerde.toBytes(row2, aggregators, true))
+ new BytesWritable(InputRowSerde.toBytes(typeHelperMap, row1, aggregators, true)),
+ new BytesWritable(InputRowSerde.toBytes(typeHelperMap, row2, aggregators, true))
);
Reducer.Context context = EasyMock.createNiceMock(Reducer.Context.class);
@@ -183,7 +195,7 @@ public void testMultipleRowsMerged() throws Exception
Assert.assertTrue(captureKey.getValue() == key);
- InputRow capturedRow = InputRowSerde.fromBytes(captureVal.getValue().getBytes(), aggregators);
+ InputRow capturedRow = InputRowSerde.fromBytes(typeHelperMap, captureVal.getValue().getBytes(), aggregators);
Assert.assertEquals(Arrays.asList("host", "keywords"), capturedRow.getDimensions());
Assert.assertEquals(ImmutableList.of(), capturedRow.getDimension("host"));
Assert.assertEquals(Arrays.asList("bar", "foo"), capturedRow.getDimension("keywords"));
@@ -228,9 +240,21 @@ public void testMultipleRowsNotMerged() throws Exception
"visited", 5
)
);
+
+ DimensionsSpec dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new StringDimensionSchema("host"),
+ new StringDimensionSchema("keywords")
+ ),
+ null,
+ null
+ );
+
+ Map<String, InputRowSerde.IndexSerdeTypeHelper> typeHelperMap = InputRowSerde.getTypeHelperMap(dimensionsSpec);
+
List<BytesWritable> rows = Lists.newArrayList(
- new BytesWritable(InputRowSerde.toBytes(row1, aggregators, true)),
- new BytesWritable(InputRowSerde.toBytes(row2, aggregators, true))
+ new BytesWritable(InputRowSerde.toBytes(typeHelperMap, row1, aggregators, true)),
+ new BytesWritable(InputRowSerde.toBytes(typeHelperMap, row2, aggregators, true))
);
Reducer.Context context = EasyMock.createNiceMock(Reducer.Context.class);
@@ -253,7 +277,7 @@ public void testMultipleRowsNotMerged() throws Exception
Assert.assertTrue(captureKey1.getValue() == key);
Assert.assertTrue(captureKey2.getValue() == key);
- InputRow capturedRow1 = InputRowSerde.fromBytes(captureVal1.getValue().getBytes(), aggregators);
+ InputRow capturedRow1 = InputRowSerde.fromBytes(typeHelperMap, captureVal1.getValue().getBytes(), aggregators);
Assert.assertEquals(Arrays.asList("host", "keywords"), capturedRow1.getDimensions());
Assert.assertEquals(Collections.singletonList("host1"), capturedRow1.getDimension("host"));
Assert.assertEquals(Arrays.asList("bar", "foo"), capturedRow1.getDimension("keywords"));
@@ -264,7 +288,7 @@ public void testMultipleRowsNotMerged() throws Exception
0.001
);
- InputRow capturedRow2 = InputRowSerde.fromBytes(captureVal2.getValue().getBytes(), aggregators);
+ InputRow capturedRow2 = InputRowSerde.fromBytes(typeHelperMap, captureVal2.getValue().getBytes(), aggregators);
Assert.assertEquals(Arrays.asList("host", "keywords"), capturedRow2.getDimensions());
Assert.assertEquals(Collections.singletonList("host2"), capturedRow2.getDimension("host"));
Assert.assertEquals(Arrays.asList("bar", "foo"), capturedRow2.getDimension("keywords"));
diff --git a/indexing-hadoop/src/test/java/io/druid/indexer/InputRowSerdeTest.java b/indexing-hadoop/src/test/java/io/druid/indexer/InputRowSerdeTest.java
index 67a9b5abf8a..71609e42dd3 100644
--- a/indexing-hadoop/src/test/java/io/druid/indexer/InputRowSerdeTest.java
+++ b/indexing-hadoop/src/test/java/io/druid/indexer/InputRowSerdeTest.java
@@ -20,9 +20,14 @@
package io.druid.indexer;
import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.Maps;
import io.druid.data.input.InputRow;
import io.druid.data.input.MapBasedInputRow;
+import io.druid.data.input.impl.DimensionsSpec;
+import io.druid.data.input.impl.DoubleDimensionSchema;
+import io.druid.data.input.impl.FloatDimensionSchema;
+import io.druid.data.input.impl.LongDimensionSchema;
+import io.druid.data.input.impl.StringDimensionSchema;
import io.druid.hll.HyperLogLogCollector;
import io.druid.jackson.AggregatorsModule;
import io.druid.java.util.common.parsers.ParseException;
@@ -35,8 +40,11 @@
import io.druid.segment.ColumnSelectorFactory;
import org.easymock.EasyMock;
import org.junit.Assert;
+import org.junit.Rule;
import org.junit.Test;
+import org.junit.rules.ExpectedException;
+import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
@@ -53,17 +61,22 @@
new AggregatorsModule(); //registers ComplexMetric serde for hyperUnique
}
+ @Rule
+ public ExpectedException expectedException = ExpectedException.none();
+
public InputRowSerdeTest()
{
this.timestamp = System.currentTimeMillis();
- this.dims = ImmutableList.of("dim_non_existing", "d1", "d2");
- this.event = ImmutableMap.<String, Object>of(
- "d1", "d1v",
- "d2", ImmutableList.of("d2v1", "d2v2"),
- "m1", 5.0f,
- "m2", 100L,
- "m3", "m3v"
- );
+ this.dims = ImmutableList.of("dim_non_existing", "d1", "d2", "d3", "d4", "d5");
+ this.event = Maps.newHashMap();
+ event.put("d1", "d1v");
+ event.put("d2", ImmutableList.of("d2v1", "d2v2"));
+ event.put("d3", 200L);
+ event.put("d4", 300.1f);
+ event.put("d5", 400.5d);
+ event.put("m1", 5.0f);
+ event.put("m2", 100L);
+ event.put("m3", "m3v");
}
@Test
@@ -99,14 +112,29 @@ public Aggregator factorize(ColumnSelectorFactory metricFactory)
}
};
- byte[] data = InputRowSerde.toBytes(in, aggregatorFactories, false); // Ignore Unparseable aggregator
- InputRow out = InputRowSerde.fromBytes(data, aggregatorFactories);
+ DimensionsSpec dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new StringDimensionSchema("d1"),
+ new StringDimensionSchema("d2"),
+ new LongDimensionSchema("d3"),
+ new FloatDimensionSchema("d4"),
+ new DoubleDimensionSchema("d5")
+ ),
+ null,
+ null
+ );
+
+ byte[] data = InputRowSerde.toBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), in, aggregatorFactories, false); // Ignore Unparseable aggregator
+ InputRow out = InputRowSerde.fromBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), data, aggregatorFactories);
Assert.assertEquals(timestamp, out.getTimestampFromEpoch());
Assert.assertEquals(dims, out.getDimensions());
Assert.assertEquals(Collections.EMPTY_LIST, out.getDimension("dim_non_existing"));
Assert.assertEquals(ImmutableList.of("d1v"), out.getDimension("d1"));
Assert.assertEquals(ImmutableList.of("d2v1", "d2v2"), out.getDimension("d2"));
+ Assert.assertEquals(200L, out.getRaw("d3"));
+ Assert.assertEquals(300.1f, out.getRaw("d4"));
+ Assert.assertEquals(400.5d, out.getRaw("d5"));
Assert.assertEquals(0.0f, out.getMetric("agg_non_existing").floatValue(), 0.00001);
Assert.assertEquals(5.0f, out.getMetric("m1out").floatValue(), 0.00001);
@@ -117,7 +145,7 @@ public Aggregator factorize(ColumnSelectorFactory metricFactory)
EasyMock.verify(mockedAggregator);
}
- @Test(expected = ParseException.class)
+ @Test
public void testThrowParseExceptions()
{
InputRow in = new MapBasedInputRow(
@@ -133,7 +161,66 @@ public void testThrowParseExceptions()
new LongSumAggregatorFactory("unparseable", "m3") // Unparseable from String to Long
};
- InputRowSerde.toBytes(in, aggregatorFactories, true);
+ DimensionsSpec dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new StringDimensionSchema("d1"),
+ new StringDimensionSchema("d2"),
+ new LongDimensionSchema("d3"),
+ new FloatDimensionSchema("d4"),
+ new DoubleDimensionSchema("d5")
+ ),
+ null,
+ null
+ );
+ expectedException.expect(ParseException.class);
+ expectedException.expectMessage("Encountered parse error for aggregator[unparseable]");
+ InputRowSerde.toBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), in, aggregatorFactories, true);
+ }
+
+ @Test
+ public void testDimensionParseExceptions()
+ {
+ InputRow in = new MapBasedInputRow(
+ timestamp,
+ dims,
+ event
+ );
+ AggregatorFactory[] aggregatorFactories = new AggregatorFactory[]{
+ new LongSumAggregatorFactory("m2out", "m2")
+ };
+
+ expectedException.expect(ParseException.class);
+ expectedException.expectMessage("could not convert value [d1v] to long");
+ DimensionsSpec dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new LongDimensionSchema("d1")
+ ),
+ null,
+ null
+ );
+ InputRowSerde.toBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), in, aggregatorFactories, true);
+
+ expectedException.expect(ParseException.class);
+ expectedException.expectMessage("could not convert value [d1v] to float");
+ dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new FloatDimensionSchema("d1")
+ ),
+ null,
+ null
+ );
+ InputRowSerde.toBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), in, aggregatorFactories, true);
+
+ expectedException.expect(ParseException.class);
+ expectedException.expectMessage("could not convert value [d1v] to double");
+ dimensionsSpec = new DimensionsSpec(
+ Arrays.asList(
+ new DoubleDimensionSchema("d1")
+ ),
+ null,
+ null
+ );
+ InputRowSerde.toBytes(InputRowSerde.getTypeHelperMap(dimensionsSpec), in, aggregatorFactories, true);
}
}
diff --git a/indexing-service/pom.xml b/indexing-service/pom.xml
index eedb98c9487..d780e1685e1 100644
--- a/indexing-service/pom.xml
+++ b/indexing-service/pom.xml
@@ -26,7 +26,7 @@
<parent>
<groupId>io.druid</groupId>
<artifactId>druid</artifactId>
- <version>0.12.0-SNAPSHOT</version>
+ <version>0.12.3-SNAPSHOT</version>
</parent>
<dependencies>
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/TaskLock.java b/indexing-service/src/main/java/io/druid/indexing/common/TaskLock.java
index 5c7ca14b30d..273335ed654 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/TaskLock.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/TaskLock.java
@@ -37,9 +37,22 @@
private final String dataSource;
private final Interval interval;
private final String version;
- private final int priority;
+ private final Integer priority;
private final boolean revoked;
+ public static TaskLock withPriority(TaskLock lock, int priority)
+ {
+ return new TaskLock(
+ lock.type,
+ lock.getGroupId(),
+ lock.getDataSource(),
+ lock.getInterval(),
+ lock.getVersion(),
+ priority,
+ lock.isRevoked()
+ );
+ }
+
@JsonCreator
public TaskLock(
@JsonProperty("type") @Nullable TaskLockType type, // nullable for backward compatibility
@@ -47,7 +60,7 @@ public TaskLock(
@JsonProperty("dataSource") String dataSource,
@JsonProperty("interval") Interval interval,
@JsonProperty("version") String version,
- @JsonProperty("priority") int priority,
+ @JsonProperty("priority") @Nullable Integer priority,
@JsonProperty("revoked") boolean revoked
)
{
@@ -116,11 +129,17 @@ public String getVersion()
}
@JsonProperty
- public int getPriority()
+ @Nullable
+ public Integer getPriority()
{
return priority;
}
+ public int getNonNullPriority()
+ {
+ return Preconditions.checkNotNull(priority, "priority");
+ }
+
@JsonProperty
public boolean isRevoked()
{
@@ -139,7 +158,7 @@ public boolean equals(Object o)
this.dataSource.equals(that.dataSource) &&
this.interval.equals(that.interval) &&
this.version.equals(that.version) &&
- this.priority == that.priority &&
+ Objects.equal(this.priority, that.priority) &&
this.revoked == that.revoked;
}
}
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/TaskStatus.java b/indexing-service/src/main/java/io/druid/indexing/common/TaskStatus.java
index e3535957d58..10ffacca3cb 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/TaskStatus.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/TaskStatus.java
@@ -153,4 +153,25 @@ public String toString()
.add("duration", duration)
.toString();
}
+
+ @Override
+ public boolean equals(Object o)
+ {
+ if (this == o) {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass()) {
+ return false;
+ }
+ TaskStatus that = (TaskStatus) o;
+ return getDuration() == that.getDuration() &&
+ java.util.Objects.equals(getId(), that.getId()) &&
+ status == that.status;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return java.util.Objects.hash(getId(), status, getDuration());
+ }
}
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/TaskToolbox.java b/indexing-service/src/main/java/io/druid/indexing/common/TaskToolbox.java
index 3db6e0f7b90..dd132769192 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/TaskToolbox.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/TaskToolbox.java
@@ -27,8 +27,8 @@
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import com.google.inject.Provider;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.metrics.MonitorScheduler;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.metrics.MonitorScheduler;
import io.druid.client.cache.Cache;
import io.druid.client.cache.CacheConfig;
import io.druid.discovery.DataNodeService;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/TaskToolboxFactory.java b/indexing-service/src/main/java/io/druid/indexing/common/TaskToolboxFactory.java
index 43d2abea594..c17b23fe210 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/TaskToolboxFactory.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/TaskToolboxFactory.java
@@ -23,8 +23,8 @@
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import com.google.inject.Provider;
-import com.metamx.emitter.service.ServiceEmitter;
-import com.metamx.metrics.MonitorScheduler;
+import io.druid.java.util.emitter.service.ServiceEmitter;
+import io.druid.java.util.metrics.MonitorScheduler;
import io.druid.client.cache.Cache;
import io.druid.client.cache.CacheConfig;
import io.druid.discovery.DataNodeService;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/CheckPointDataSourceMetadataAction.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/CheckPointDataSourceMetadataAction.java
index aca4a1099ae..083ef9e5355 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/CheckPointDataSourceMetadataAction.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/CheckPointDataSourceMetadataAction.java
@@ -21,6 +21,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
+import com.google.common.base.Preconditions;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.DataSourceMetadata;
@@ -29,21 +30,21 @@
public class CheckPointDataSourceMetadataAction implements TaskAction<Boolean>
{
private final String supervisorId;
- private final String sequenceName;
+ private final int taskGroupId;
private final DataSourceMetadata previousCheckPoint;
private final DataSourceMetadata currentCheckPoint;
public CheckPointDataSourceMetadataAction(
@JsonProperty("supervisorId") String supervisorId,
- @JsonProperty("sequenceName") String sequenceName,
+ @JsonProperty("taskGroupId") Integer taskGroupId,
@JsonProperty("previousCheckPoint") DataSourceMetadata previousCheckPoint,
@JsonProperty("currentCheckPoint") DataSourceMetadata currentCheckPoint
)
{
- this.supervisorId = supervisorId;
- this.sequenceName = sequenceName;
- this.previousCheckPoint = previousCheckPoint;
- this.currentCheckPoint = currentCheckPoint;
+ this.supervisorId = Preconditions.checkNotNull(supervisorId, "supervisorId");
+ this.taskGroupId = Preconditions.checkNotNull(taskGroupId, "taskGroupId");
+ this.previousCheckPoint = Preconditions.checkNotNull(previousCheckPoint, "previousCheckPoint");
+ this.currentCheckPoint = Preconditions.checkNotNull(currentCheckPoint, "currentCheckPoint");
}
@JsonProperty
@@ -53,9 +54,9 @@ public String getSupervisorId()
}
@JsonProperty
- public String getSequenceName()
+ public int getTaskGroupId()
{
- return sequenceName;
+ return taskGroupId;
}
@JsonProperty
@@ -83,8 +84,12 @@ public Boolean perform(
Task task, TaskActionToolbox toolbox
) throws IOException
{
- return toolbox.getSupervisorManager()
- .checkPointDataSourceMetadata(supervisorId, sequenceName, previousCheckPoint, currentCheckPoint);
+ return toolbox.getSupervisorManager().checkPointDataSourceMetadata(
+ supervisorId,
+ taskGroupId,
+ previousCheckPoint,
+ currentCheckPoint
+ );
}
@Override
@@ -98,7 +103,7 @@ public String toString()
{
return "CheckPointDataSourceMetadataAction{" +
"supervisorId='" + supervisorId + '\'' +
- ", sequenceName='" + sequenceName + '\'' +
+ ", taskGroupId='" + taskGroupId + '\'' +
", previousCheckPoint=" + previousCheckPoint +
", currentCheckPoint=" + currentCheckPoint +
'}';
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/LocalTaskActionClient.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/LocalTaskActionClient.java
index 7bce2b6e89b..0e688ecbfd8 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/LocalTaskActionClient.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/LocalTaskActionClient.java
@@ -19,7 +19,7 @@
package io.druid.indexing.common.actions;
-import com.metamx.emitter.EmittingLogger;
+import io.druid.java.util.emitter.EmittingLogger;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.TaskStorage;
import io.druid.java.util.common.ISE;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/RemoteTaskActionClient.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/RemoteTaskActionClient.java
index b2e3c5f23c3..9c1c7e82399 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/RemoteTaskActionClient.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/RemoteTaskActionClient.java
@@ -21,7 +21,7 @@
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Throwables;
-import com.metamx.http.client.response.FullResponseHolder;
+import io.druid.java.util.http.client.response.FullResponseHolder;
import io.druid.discovery.DruidLeaderClient;
import io.druid.indexing.common.RetryPolicy;
import io.druid.indexing.common.RetryPolicyFactory;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentMetadataUpdateAction.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentMetadataUpdateAction.java
index 2e33d5e15c0..7c55939f4d5 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentMetadataUpdateAction.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentMetadataUpdateAction.java
@@ -24,7 +24,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableSet;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.CriticalAction;
import io.druid.java.util.common.ISE;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentNukeAction.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentNukeAction.java
index 044cfebd00f..dad3ca51646 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentNukeAction.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentNukeAction.java
@@ -24,7 +24,7 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableSet;
-import com.metamx.emitter.service.ServiceMetricEvent;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.CriticalAction;
import io.druid.java.util.common.ISE;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentTransactionalInsertAction.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentTransactionalInsertAction.java
index c22275def06..acd6eb5a647 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentTransactionalInsertAction.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/SegmentTransactionalInsertAction.java
@@ -23,12 +23,12 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.collect.ImmutableSet;
-import com.metamx.emitter.service.ServiceMetricEvent;
import io.druid.indexing.common.task.Task;
import io.druid.indexing.overlord.CriticalAction;
import io.druid.indexing.overlord.DataSourceMetadata;
import io.druid.indexing.overlord.SegmentPublishResult;
import io.druid.java.util.common.logger.Logger;
+import io.druid.java.util.emitter.service.ServiceMetricEvent;
import io.druid.query.DruidMetrics;
import io.druid.timeline.DataSegment;
@@ -127,22 +127,21 @@ public SegmentPublishResult perform(Task task, TaskActionToolbox toolbox) throws
throw new RuntimeException(e);
}
+ // Emit metrics
+ final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder()
+ .setDimension(DruidMetrics.DATASOURCE, task.getDataSource())
+ .setDimension(DruidMetrics.TASK_TYPE, task.getType());
+
if (retVal.isSuccess()) {
- // Emit metrics
- final ServiceMetricEvent.Builder metricBuilder = new ServiceMetricEvent.Builder()
- .setDimension(DruidMetrics.DATASOURCE, task.getDataSource())
- .setDimension(DruidMetrics.TASK_TYPE, task.getType());
-
- if (retVal.isSuccess()) {
- toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1));
- } else {
- toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1));
- }
-
- for (DataSegment segment : retVal.getSegments()) {
- metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString());
- toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize()));
- }
+ toolbox.getEmitter().emit(metricBuilder.build("segment/txn/success", 1));
+ } else {
+ toolbox.getEmitter().emit(metricBuilder.build("segment/txn/failure", 1));
+ }
+
+ // getSegments() should return an empty set if announceHistoricalSegments() failed
+ for (DataSegment segment : retVal.getSegments()) {
+ metricBuilder.setDimension(DruidMetrics.INTERVAL, segment.getInterval().toString());
+ toolbox.getEmitter().emit(metricBuilder.build("segment/added/bytes", segment.getSize()));
}
return retVal;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/actions/TaskActionToolbox.java b/indexing-service/src/main/java/io/druid/indexing/common/actions/TaskActionToolbox.java
index 59ca2294215..4d08465b99e 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/actions/TaskActionToolbox.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/actions/TaskActionToolbox.java
@@ -20,7 +20,7 @@
package io.druid.indexing.common.actions;
import com.google.inject.Inject;
-import com.metamx.emitter.service.ServiceEmitter;
+import io.druid.java.util.emitter.service.ServiceEmitter;
import io.druid.indexing.overlord.IndexerMetadataStorageCoordinator;
import io.druid.indexing.overlord.TaskLockbox;
import io.druid.indexing.overlord.supervisor.SupervisorManager;
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/index/YeOldePlumberSchool.java b/indexing-service/src/main/java/io/druid/indexing/common/index/YeOldePlumberSchool.java
index b6e2a26d88f..4364f50f40a 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/index/YeOldePlumberSchool.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/index/YeOldePlumberSchool.java
@@ -199,7 +199,7 @@ public void finishJob()
.withDimensions(ImmutableList.copyOf(mappedSegment.getAvailableDimensions()))
.withBinaryVersion(SegmentUtils.getVersionFromDir(fileToUpload));
- dataSegmentPusher.push(fileToUpload, segmentToUpload);
+ dataSegmentPusher.push(fileToUpload, segmentToUpload, false);
log.info(
"Uploaded segment[%s]",
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/task/AbstractTask.java b/indexing-service/src/main/java/io/druid/indexing/common/task/AbstractTask.java
index cbf10f4134c..adde5e97ba7 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/task/AbstractTask.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/task/AbstractTask.java
@@ -36,6 +36,7 @@
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayList;
+import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -64,17 +65,17 @@ protected AbstractTask(String id, String dataSource, Map<String, Object> context
protected AbstractTask(
String id,
- String groupId,
- TaskResource taskResource,
+ @Nullable String groupId,
+ @Nullable TaskResource taskResource,
String dataSource,
- Map<String, Object> context
+ @Nullable Map<String, Object> context
)
{
this.id = Preconditions.checkNotNull(id, "id");
this.groupId = groupId == null ? id : groupId;
this.taskResource = taskResource == null ? new TaskResource(id, 1) : taskResource;
this.dataSource = Preconditions.checkNotNull(dataSource, "dataSource");
- this.context = context;
+ this.context = context == null ? new HashMap<>() : context;
}
static String getOrMakeId(String id, final String typeName, String dataSource)
@@ -162,11 +163,13 @@ public void stopGracefully()
@Override
public String toString()
{
- return Objects.toStringHelper(this)
- .add("id", id)
- .add("type", getType())
- .add("dataSource", dataSource)
- .toString();
+ return "AbstractTask{" +
+ "id='" + id + '\'' +
+ ", groupId='" + groupId + '\'' +
+ ", taskResource=" + taskResource +
+ ", dataSource='" + dataSource + '\'' +
+ ", context=" + context +
+ '}';
}
/**
@@ -207,13 +210,21 @@ public boolean equals(Object o)
return false;
}
- return true;
+ if (!groupId.equals(that.groupId)) {
+ return false;
+ }
+
+ if (!dataSource.equals(that.dataSource)) {
+ return false;
+ }
+
+ return context.equals(that.context);
}
@Override
public int hashCode()
{
- return id.hashCode();
+ return Objects.hashCode(id, groupId, dataSource, context);
}
static List<TaskLock> getTaskLocks(TaskActionClient client) throws IOException
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/task/CompactionTask.java b/indexing-service/src/main/java/io/druid/indexing/common/task/CompactionTask.java
index 96f3889982b..5e94285cd9f 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/task/CompactionTask.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/task/CompactionTask.java
@@ -51,6 +51,7 @@
import io.druid.java.util.common.ISE;
import io.druid.java.util.common.JodaUtils;
import io.druid.java.util.common.Pair;
+import io.druid.java.util.common.RE;
import io.druid.java.util.common.granularity.NoneGranularity;
import io.druid.java.util.common.guava.Comparators;
import io.druid.java.util.common.jackson.JacksonUtils;
@@ -78,6 +79,7 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
+import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@@ -189,26 +191,35 @@ public TaskStatus run(final TaskToolbox toolbox) throws Exception
jsonMapper
);
- indexTaskSpec = new IndexTask(
- getId(),
- getGroupId(),
- getTaskResource(),
- getDataSource(),
- ingestionSpec,
- getContext()
- );
- }
-
- if (indexTaskSpec.getIngestionSchema() == null) {
- log.info("Cannot find segments for interval");
+ if (ingestionSpec != null) {
+ indexTaskSpec = new IndexTask(
+ getId(),
+ getGroupId(),
+ getTaskResource(),
+ getDataSource(),
+ ingestionSpec,
+ getContext()
+ );
+ }
}
- final String json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(indexTaskSpec);
- log.info("Generated compaction task details: " + json);
+ if (indexTaskSpec == null) {
+ log.warn("Failed to generate compaction spec");
+ return TaskStatus.failure(getId());
+ } else {
+ final String json = jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(indexTaskSpec);
+ log.info("Generated compaction task details: " + json);
- return indexTaskSpec.run(toolbox);
+ return indexTaskSpec.run(toolbox);
+ }
}
+ /**
+ * Generate {@link IndexIngestionSpec} from input segments.
+ *
+ * @return null if input segments don't exist. Otherwise, a generated ingestionSpec.
+ */
+ @Nullable
@VisibleForTesting
static IndexIngestionSpec createIngestionSchema(
TaskToolbox toolbox,
@@ -281,12 +292,22 @@ private static DataSchema createDataSchema(
throws IOException, SegmentLoadingException
{
// find metadata for interval
- final List<QueryableIndex> queryableIndices = loadSegments(timelineSegments, segmentFileMap, indexIO);
+ final List<Pair<QueryableIndex, DataSegment>> queryableIndexAndSegments = loadSegments(
+ timelineSegments,
+ segmentFileMap,
+ indexIO
+ );
// find merged aggregators
- final List<AggregatorFactory[]> aggregatorFactories = queryableIndices
+ for (Pair<QueryableIndex, DataSegment> pair : queryableIndexAndSegments) {
+ final QueryableIndex index = pair.lhs;
+ if (index.getMetadata() == null) {
+ throw new RE("Index metadata doesn't exist for segment[%s]", pair.rhs.getIdentifier());
+ }
+ }
+ final List<AggregatorFactory[]> aggregatorFactories = queryableIndexAndSegments
.stream()
- .map(index -> index.getMetadata().getAggregators())
+ .map(pair -> pair.lhs.getMetadata().getAggregators()) // We have already done null check on index.getMetadata()
.collect(Collectors.toList());
final AggregatorFactory[] mergedAggregators = AggregatorFactory.mergeAggregators(aggregatorFactories);
@@ -296,7 +317,11 @@ private static DataSchema createDataSchema(
// find granularity spec
// set rollup only if rollup is set for all segments
- final boolean rollup = queryableIndices.stream().allMatch(index -> index.getMetadata().isRollup());
+ final boolean rollup = queryableIndexAndSegments.stream().allMatch(pair -> {
+ // We have already checked getMetadata() doesn't return null
+ final Boolean isRollup = pair.lhs.getMetadata().isRollup();
+ return isRollup != null && isRollup;
+ });
final GranularitySpec granularitySpec = new ArbitraryGranularitySpec(
new NoneGranularity(),
rollup,
@@ -305,7 +330,7 @@ private static DataSchema createDataSchema(
// find unique dimensions
final DimensionsSpec finalDimensionsSpec = dimensionsSpec == null ?
- createDimensionsSpec(queryableIndices) :
+ createDimensionsSpec(queryableIndexAndSegments) :
dimensionsSpec;
final InputRowParser parser = new NoopInputRowParser(new TimeAndDimsParseSpec(null, finalDimensionsSpec));
@@ -319,7 +344,7 @@ private static DataSchema createDataSchema(
);
}
- private static DimensionsSpec createDimensionsSpec(List<QueryableIndex> queryableIndices)
+ private static DimensionsSpec createDimensionsSpec(List<Pair<QueryableIndex, DataSegment>> queryableIndices)
{
final BiMap<String, Integer> uniqueDims = HashBiMap.create();
final Map<String, DimensionSchema> dimensionSchemaMap = new HashMap<>();
@@ -329,9 +354,24 @@ private static DimensionsSpec createDimensionsSpec(List<QueryableIndex> queryabl
// Dimensions are extracted from the recent segments to olders because recent segments are likely to be queried more
// frequently, and thus the performance should be optimized for recent ones rather than old ones.
- // timelineSegments are sorted in order of interval
+ // timelineSegments are sorted in order of interval, but we do a sanity check here.
+ final Comparator<Interval> intervalComparator = Comparators.intervalsByStartThenEnd();
+ for (int i = 0; i < queryableIndices.size() - 1; i++) {
+ final Interval shouldBeSmaller = queryableIndices.get(i).lhs.getDataInterval();
+ final Interval shouldBeLarger = queryableIndices.get(i + 1).lhs.getDataInterval();
+ Preconditions.checkState(
+ intervalComparator.compare(shouldBeSmaller, shouldBeLarger) <= 0,
+ "QueryableIndexes are not sorted! Interval[%s] of segment[%s] is laster than interval[%s] of segment[%s]",
+ shouldBeSmaller,
+ queryableIndices.get(i).rhs.getIdentifier(),
+ shouldBeLarger,
+ queryableIndices.get(i + 1).rhs.getIdentifier()
+ );
+ }
+
int index = 0;
- for (QueryableIndex queryableIndex : Lists.reverse(queryableIndices)) {
+ for (Pair<QueryableIndex, DataSegment> pair : Lists.reverse(queryableIndices)) {
+ final QueryableIndex queryableIndex = pair.lhs;
final Map<String, DimensionHandler> dimensionHandlerMap = queryableIndex.getDimensionHandlers();
for (String dimension : queryableIndex.getAvailableDimensions()) {
@@ -376,23 +416,22 @@ private static DimensionsSpec createDimensionsSpec(List<QueryableIndex> queryabl
return new DimensionsSpec(dimensionSchemas, null, null);
}
- private static List<QueryableIndex> loadSegments(
+ private static List<Pair<QueryableIndex, DataSegment>> loadSegments(
List<TimelineObjectHolder<String, DataSegment>> timelineSegments,
Map<DataSegment, File> segmentFileMap,
IndexIO indexIO
) throws IOException
{
- final List<QueryableIndex> segments = new ArrayList<>();
+ final List<Pair<QueryableIndex, DataSegment>> segments = new ArrayList<>();
for (TimelineObjectHolder<String, DataSegment> timelineSegment : timelineSegments) {
final PartitionHolder<DataSegment> partitionHolder = timelineSegment.getObject();
for (PartitionChunk<DataSegment> chunk : partitionHolder) {
final DataSegment segment = chunk.getObject();
- segments.add(
- indexIO.loadIndex(
- Preconditions.checkNotNull(segmentFileMap.get(segment), "File for segment %s", segment.getIdentifier())
- )
+ final QueryableIndex queryableIndex = indexIO.loadIndex(
+ Preconditions.checkNotNull(segmentFileMap.get(segment), "File for segment %s", segment.getIdentifier())
);
+ segments.add(Pair.of(queryableIndex, segment));
}
}
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/task/ConvertSegmentTask.java b/indexing-service/src/main/java/io/druid/indexing/common/task/ConvertSegmentTask.java
index 4605995ee61..460225af1fe 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/task/ConvertSegmentTask.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/task/ConvertSegmentTask.java
@@ -440,7 +440,8 @@ private void convertSegment(TaskToolbox toolbox) throws SegmentLoadingException,
// Appending to the version makes a new version that inherits most comparability parameters of the original
// version, but is "newer" than said original version.
DataSegment updatedSegment = segment.withVersion(StringUtils.format("%s_v%s", segment.getVersion(), outVersion));
- updatedSegment = toolbox.getSegmentPusher().push(outLocation, updatedSegment);
+
+ updatedSegment = toolbox.getSegmentPusher().push(outLocation, updatedSegment, false);
actionClient.submit(new SegmentInsertAction(Sets.newHashSet(updatedSegment)));
} else {
diff --git a/indexing-service/src/main/java/io/druid/indexing/common/task/IndexTask.java b/indexing-service/src/main/java/io/druid/indexing/common/task/IndexTask.java
index 1a9bade78c9..b9ec2705510 100644
--- a/indexing-service/src/main/java/io/druid/indexing/common/task/IndexTask.java
+++ b/indexing-service/src/main/java/io/druid/indexing/common/task/IndexTask.java
@@ -24,11 +24,9 @@
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import com.fasterxml.jackson.databind.ObjectMapper;
-import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
-import com.google.common.base.Supplier;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
@@ -36,7 +34,6 @@
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import com.google.common.util.concurrent.ListenableFuture;
-import io.druid.data.input.Committer;
import io.druid.data.input.Firehose;
import io.druid.data.input.FirehoseFactory;
import io.druid.data.input.InputRow;
@@ -57,7 +54,6 @@
import io.druid.java.util.common.guava.Comparators;
import io.druid.java.util.common.logger.Logger;
import io.druid.java.util.common.parsers.ParseException;
-import io.druid.segment.writeout.SegmentWriteOutMediumFactory;
import io.druid.query.DruidMetrics;
import io.druid.segment.IndexSpec;
import io.druid.segment.indexing.DataSchema;
@@ -71,15 +67,15 @@
import io.druid.segment.realtime.RealtimeMetricsMonitor;
import io.druid.segment.realtime.appenderator.Appenderator;
import io.druid.segment.realtime.appenderator.AppenderatorConfig;
-import io.druid.segment.realtime.appenderator.AppenderatorDriver;
import io.druid.segment.realtime.appenderator.AppenderatorDriverAddResult;
import io.druid.segment.realtime.appenderator.Appenderators;
(This diff was longer than 20,000 lines, and has been truncated...)
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on GitHub and use the
URL above to go to the specific comment.
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
With regards,
Apache Git Services
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@druid.apache.org
For additional commands, e-mail: commits-help@druid.apache.org