Apache Lucene open-source search software
SOLR-4916: Add support to write and read Solr index files and transaction log files to and from HDFS.
Mark Robert Millerb9e1537a7e12
diff --git a/.gitignore b/.gitignoreindex 3530f930e77..faf37a0b2d8 100644--- a/.gitignore+++ b/.gitignore@@ -1,4 +1,5 @@-+# hdfs+/solr/example/hdfs*.jar# .diff --git a/build.xml b/build.xmlindex 58d9687f8ed..7851b7d7f66 100644--- a/build.xml+++ b/build.xml@@ -205,7 +205,7 @@<!-- TODO: find a better way to exclude duplicate JAR files & fix the servlet-api mess! --><pathconvert property="eclipse.fileset.libs" pathsep="|" dirsep="/"><fileset dir="${basedir}/lucene" includes="**/lib/*.jar" excludes="**/*servlet-api*.jar, analysis/uima/**, tools/**, build/**"/>- <fileset dir="${basedir}/solr" includes="**/lib/*.jar" excludes="core/lib/*servlet-api*.jar, contrib/analysis-extras/**, test-framework/**, build/**, dist/**, package/**" />+ <fileset dir="${basedir}/solr" includes="**/lib/*.jar" excludes="core/lib/*servlet-api*.jar, contrib/analysis-extras/**, test-framework/lib/junit*, test-framework/lib/ant*, test-framework/lib/randomizedtesting*, build/**, dist/**, package/**" /><map from="${basedir}/" to=""/></pathconvert><xslt in="${ant.file}" out=".classpath" style="dev-tools/eclipse/dot.classpath.xsl" force="true">diff --git a/lucene/common-build.xml b/lucene/common-build.xmlindex c8ee38f65fc..392c6432320 100644--- a/lucene/common-build.xml+++ b/lucene/common-build.xml@@ -354,7 +354,7 @@<target name="resolve" depends="ivy-availability-check,ivy-configure"><!-- todo, make this a property or something.only special cases need bundles -->- <ivy:retrieve type="jar,bundle" log="download-only"+ <ivy:retrieve type="jar,bundle,tests" log="download-only"conf="${ivy.default.configuration}" sync="${ivy.sync}"/></target>diff --git a/lucene/tools/custom-tasks.xml b/lucene/tools/custom-tasks.xmlindex a0e175a48ed..10e4b568ec8 100644--- a/lucene/tools/custom-tasks.xml+++ b/lucene/tools/custom-tasks.xml@@ -43,7 +43,7 @@<!-- Typical version patterns. --><replaceregex pattern="\.rc[0-9]+" replace="" flags="gi" />- <replaceregex pattern="\-(r)?([0-9\-\_\.])+(b(eta)?([0-9\-\.])*)?$" replace="" flags="gi" />+ <replaceregex pattern="\-(r)?([0-9\-\_\.])+((b(eta)?)|((a(lpha)?))([0-9\-\.])*)?(\-tests)?$" replace="" flags="gi" /><!-- git hashcode pattern: its always 40 chars right? --><replaceregex pattern="\-[a-z0-9]{40,40}$" replace="" flags="gi" />diff --git a/lucene/tools/junit4/tests.policy b/lucene/tools/junit4/tests.policyindex f8c40026378..0933cab39bf 100644--- a/lucene/tools/junit4/tests.policy+++ b/lucene/tools/junit4/tests.policy@@ -59,6 +59,10 @@ grant {permission javax.management.MBeanPermission "*", "*";permission javax.management.MBeanServerPermission "*";permission javax.management.MBeanTrustPermission "*";+ permission javax.security.auth.AuthPermission "*";+ permission javax.security.auth.PrivateCredentialPermission "org.apache.hadoop.security.Credentials * \"*\"", "read";+ permission java.security.SecurityPermission "putProviderProperty.SaslPlainServer";+ permission java.security.SecurityPermission "insertProvider.SaslPlainServer";// TIKA uses BouncyCastle and that registers new provider for PDF parsing + MSOffice parsing. Maybe report as bug!permission java.security.SecurityPermission "putProviderProperty.BC";diff --git a/solr/CHANGES.txt b/solr/CHANGES.txtindex fe4f8dcc3eb..ae64994a227 100644--- a/solr/CHANGES.txt+++ b/solr/CHANGES.txt@@ -118,6 +118,9 @@ New Features* SOLR-4921: Admin UI now supports adding documents to Solr (gsingers, steffkes)+* SOLR-4916: Add support to write and read Solr index files and transaction log+ files to and from HDFS. (phunt, Mark Miller, Greg Chanan)+Bug Fixes----------------------diff --git a/solr/NOTICE.txt b/solr/NOTICE.txtindex 707861135ea..a947165411c 100644--- a/solr/NOTICE.txt+++ b/solr/NOTICE.txt@@ -52,6 +52,7 @@ including, but not limited to:- Apache Jakarta Regexp- Apache Commons- Apache Xerces+ - Apache BlurICU4J, (under analysis/icu) is licensed under an MIT styles licenseand Copyright (c) 1995-2008 International Business Machines Corporation and others@@ -72,6 +73,9 @@ http://bitbucket.org/jpbarrette/moman/overview/The class org.apache.lucene.util.WeakIdentityMap was derived fromthe Apache CXF project and is Apache License 2.0.+The HdfsDirectory and BlockDirectory were derived from+the Apache Blur incubating project and are Apache License 2.0.+The Google Code Prettify is Apache License 2.0.See http://code.google.com/p/google-code-prettify/diff --git a/solr/build.xml b/solr/build.xmlindex 73819b3df88..1e1189f0ce5 100644--- a/solr/build.xml+++ b/solr/build.xml@@ -40,7 +40,7 @@<!-- ========================================================================= --><target name="example" description="Creates a runnable example configuration."- depends="dist-contrib,dist-war">+ depends="dist-contrib,dist-war,setup-alt-examples"><copy file="${dist}/${fullnamever}.war"tofile="${example}/webapps/${ant.project.name}.war"/><jar destfile="${example}/exampledocs/post.jar"@@ -56,6 +56,15 @@<echo>See ${example}/README.txt for how to run the Solr example configuration.</echo></target>+ <target name="setup-alt-examples">+ <copy todir="${example}/hdfs" overwrite="true">+ <fileset dir="${example}/solr"/>+ </copy>+ <copy todir="${example}/hdfs/collection1/conf" overwrite="true">+ <fileset dir="${example}/alt-configs/hdfs"/>+ </copy>+ </target>+<target name="run-example" depends="example"description="Run Solr interactively, via Jetty. -Dexample.debug=true to enable JVM debugger"><property name="example.solr.home" location="example/solr"/>diff --git a/solr/common-build.xml b/solr/common-build.xmlindex cc7336bc289..c42e22015cc 100644--- a/solr/common-build.xml+++ b/solr/common-build.xml@@ -96,6 +96,12 @@<path id="solr.test.base.classpath"><pathelement path="${common-solr.dir}/build/solr-test-framework/classes/java"/>+ <fileset dir="${common-solr.dir}/test-framework/lib">+ <include name="*.jar"/>+ <exclude name="junit-*.jar" />+ <exclude name="randomizedtesting-runner-*.jar" />+ <exclude name="ant*.jar" />+ </fileset><pathelement path="${build.dir}/test-files"/><path refid="test.base.classpath"/></path>diff --git a/solr/core/ivy.xml b/solr/core/ivy.xmlindex 2b4ccc4aec2..d028f35801d 100644--- a/solr/core/ivy.xml+++ b/solr/core/ivy.xml@@ -16,6 +16,9 @@specific language governing permissions and limitationsunder the License.-->+<!DOCTYPE ivy-module [+ <!ENTITY hadoop.version "2.0.5-alpha">+]><ivy-module version="2.0"><info organisation="org.apache.solr" module="core"/>@@ -32,6 +35,14 @@<dependency org="javax.servlet" name="javax.servlet-api" rev="3.0.1" transitive="false"/><dependency org="org.restlet.jee" name="org.restlet" rev="2.1.1" transitive="false"/><dependency org="org.restlet.jee" name="org.restlet.ext.servlet" rev="2.1.1" transitive="false"/>- <exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}"/>++ <dependency org="org.apache.hadoop" name="hadoop-common" rev="&hadoop.version;" transitive="false"/>+ <dependency org="org.apache.hadoop" name="hadoop-hdfs" rev="&hadoop.version;" transitive="false"/>+ <dependency org="org.apache.hadoop" name="hadoop-annotations" rev="&hadoop.version;" transitive="false"/>+ <dependency org="org.apache.hadoop" name="hadoop-auth" rev="&hadoop.version;" transitive="false"/>+ <dependency org="commons-configuration" name="commons-configuration" rev="1.6" transitive="false"/>+ <dependency org="com.google.protobuf" name="protobuf-java" rev="2.4.0a" transitive="false"/>+ <dependency org="com.googlecode.concurrentlinkedhashmap" name="concurrentlinkedhashmap-lru" rev="1.2" transitive="false"/>+ <exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}"/></dependencies></ivy-module>diff --git a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java b/solr/core/src/java/org/apache/solr/SolrLogFormatter.javaindex 32478d097b6..d6636e8a30f 100644--- a/solr/core/src/java/org/apache/solr/SolrLogFormatter.java+++ b/solr/core/src/java/org/apache/solr/SolrLogFormatter.java@@ -17,21 +17,25 @@ package org.apache.solr;* limitations under the License.*/+import java.util.Collections;+import java.util.HashMap;+import java.util.Map;+import java.util.WeakHashMap;+import java.util.logging.ConsoleHandler;+import java.util.logging.Formatter;+import java.util.logging.Handler;+import java.util.logging.Level;+import java.util.logging.LogRecord;+import java.util.logging.Logger;+import org.apache.solr.cloud.ZkController;import org.apache.solr.common.SolrException;import org.apache.solr.common.cloud.Replica;-import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.core.SolrCore;import org.apache.solr.request.SolrQueryRequest;import org.apache.solr.request.SolrRequestInfo;import org.slf4j.LoggerFactory;-import java.util.Collections;-import java.util.HashMap;-import java.util.Map;-import java.util.WeakHashMap;-import java.util.logging.*;-public class SolrLogFormatter extends Formatter {/** Add this interface to a thread group and the string returned by@@ -259,7 +263,7 @@ sb.append("(group_name=").append(tg.getName()).append(")");private Map<String,Object> getReplicaProps(ZkController zkController, SolrCore core) {final String collection = core.getCoreDescriptor().getCloudDescriptor().getCollectionName();- Replica replica = zkController.getClusterState().getReplica(collection, zkController.getCoreNodeName(core.getCoreDescriptor()));+ Replica replica = zkController.getClusterState().getReplica(collection, core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName());if(replica!=null) {return replica.getProperties();}diff --git a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.javaindex 20cc190be62..5eeb19c75a9 100644--- a/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java+++ b/solr/core/src/java/org/apache/solr/client/solrj/embedded/JettySolrRunner.java@@ -85,6 +85,7 @@ public class JettySolrRunner {private String shards;private String dataDir;+ private String solrUlogDir;private volatile boolean startedBefore = false;@@ -359,6 +360,9 @@ public class JettySolrRunner {if( dataDir != null) {System.setProperty("solr.data.dir", dataDir);}+ if( solrUlogDir != null) {+ System.setProperty("solr.ulog.dir", solrUlogDir);+ }if(shards != null) {System.setProperty("shard", shards);}@@ -382,6 +386,8 @@ public class JettySolrRunner {System.clearProperty("shard");System.clearProperty("solr.data.dir");System.clearProperty("coreNodeName");+ System.clearProperty("solr.ulog.dir");+}public void stop() throws Exception {@@ -485,6 +491,10 @@ public class JettySolrRunner {public void setDataDir(String dataDir) {this.dataDir = dataDir;}++ public void setUlogDir(String ulogDir) {+ this.solrUlogDir = ulogDir;+ }public void setCoreNodeName(String coreNodeName) {this.coreNodeName = coreNodeName;diff --git a/solr/core/src/java/org/apache/solr/cloud/AssignShard.java b/solr/core/src/java/org/apache/solr/cloud/Assign.javasimilarity index 77%rename from solr/core/src/java/org/apache/solr/cloud/AssignShard.javarename to solr/core/src/java/org/apache/solr/cloud/Assign.javaindex 524dfe5931d..8f0120b81d8 100644--- a/solr/core/src/java/org/apache/solr/cloud/AssignShard.java+++ b/solr/core/src/java/org/apache/solr/cloud/Assign.java@@ -23,12 +23,36 @@ import java.util.Comparator;import java.util.HashMap;import java.util.List;import java.util.Map;+import java.util.regex.Matcher;+import java.util.regex.Pattern;import org.apache.solr.common.cloud.ClusterState;+import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.cloud.Slice;-public class AssignShard {+public class Assign {+ private static Pattern COUNT = Pattern.compile("core_node(\\d+)");++ public static String assignNode(String collection, ClusterState state) {+ Map<String, Slice> sliceMap = state.getSlicesMap(collection);+ if (sliceMap == null) {+ return "core_node1";+ }++ int max = 0;+ for (Slice slice : sliceMap.values()) {+ for (Replica replica : slice.getReplicas()) {+ Matcher m = COUNT.matcher(replica.getName());+ if (m.matches()) {+ max = Math.max(max, Integer.parseInt(m.group(1)));+ }+ }+ }++ return "core_node" + (max + 1);+ }+/*** Assign a new unique id up to slices count - then add replicas evenly.*diff --git a/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java b/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.javaindex cf086fde2f3..8a071c7becb 100644--- a/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java+++ b/solr/core/src/java/org/apache/solr/cloud/CloudDescriptor.java@@ -44,6 +44,10 @@ public class CloudDescriptor {public boolean isLeader() {return isLeader;}++ public void setLeader(boolean isLeader) {+ this.isLeader = isLeader;+ }public void setShardId(String shardId) {this.shardId = shardId;diff --git a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.javaindex 1d436afd856..52d22f0f69e 100644--- a/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java+++ b/solr/core/src/java/org/apache/solr/cloud/ElectionContext.java@@ -47,9 +47,9 @@ public abstract class ElectionContext {String leaderSeqPath;private SolrZkClient zkClient;- public ElectionContext(final String shardZkNodeName,+ public ElectionContext(final String coreNodeName,final String electionPath, final String leaderPath, final ZkNodeProps leaderProps, final SolrZkClient zkClient) {- this.id = shardZkNodeName;+ this.id = coreNodeName;this.electionPath = electionPath;this.leaderPath = leaderPath;this.leaderProps = leaderProps;@@ -78,8 +78,8 @@ class ShardLeaderElectionContextBase extends ElectionContext {protected LeaderElector leaderElector;public ShardLeaderElectionContextBase(LeaderElector leaderElector, final String shardId,- final String collection, final String shardZkNodeName, ZkNodeProps props, ZkStateReader zkStateReader) {- super(shardZkNodeName, ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection + "/leader_elect/"+ final String collection, final String coreNodeName, ZkNodeProps props, ZkStateReader zkStateReader) {+ super(coreNodeName, ZkStateReader.COLLECTIONS_ZKNODE + "/" + collection + "/leader_elect/"+ shardId, ZkStateReader.getShardLeadersPath(collection, shardId),props, zkStateReader.getZkClient());this.leaderElector = leaderElector;@@ -95,7 +95,7 @@ class ShardLeaderElectionContextBase extends ElectionContext {zkClient.makePath(leaderPath, ZkStateReader.toJSON(leaderProps),CreateMode.EPHEMERAL, true);assert shardId != null;- ZkNodeProps m = ZkNodeProps.fromKeyVals(Overseer.QUEUE_OPERATION, "leader",+ ZkNodeProps m = ZkNodeProps.fromKeyVals(Overseer.QUEUE_OPERATION, ZkStateReader.LEADER_PROP,ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP,collection, ZkStateReader.BASE_URL_PROP, leaderProps.getProperties().get(ZkStateReader.BASE_URL_PROP), ZkStateReader.CORE_NAME_PROP,@@ -119,8 +119,8 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {public ShardLeaderElectionContext(LeaderElector leaderElector,final String shardId, final String collection,- final String shardZkNodeName, ZkNodeProps props, ZkController zkController, CoreContainer cc) {- super(leaderElector, shardId, collection, shardZkNodeName, props,+ final String coreNodeName, ZkNodeProps props, ZkController zkController, CoreContainer cc) {+ super(leaderElector, shardId, collection, coreNodeName, props,zkController.getZkStateReader());this.zkController = zkController;this.cc = cc;@@ -138,12 +138,12 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {@Overridevoid runLeaderProcess(boolean weAreReplacement) throws KeeperException,InterruptedException, IOException {- log.info("Running the leader process.");+ log.info("Running the leader process for shard " + shardId);String coreName = leaderProps.getStr(ZkStateReader.CORE_NAME_PROP);// clear the leader in clusterstate- ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "leader",+ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, ZkStateReader.LEADER_PROP,ZkStateReader.SHARD_ID_PROP, shardId, ZkStateReader.COLLECTION_PROP,collection);Overseer.getInQueue(zkClient).offer(ZkStateReader.toJSON(m));@@ -243,8 +243,8 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {}log.info("I am the new leader: "- + ZkCoreNodeProps.getCoreUrl(leaderProps));- core.getCoreDescriptor().getCloudDescriptor().isLeader = true;+ + ZkCoreNodeProps.getCoreUrl(leaderProps) + " " + shardId);+ core.getCoreDescriptor().getCloudDescriptor().setLeader(true);} finally {if (core != null) {core.close();@@ -254,16 +254,17 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {try {super.runLeaderProcess(weAreReplacement);} catch (Throwable t) {+ SolrException.log(log, "There was a problem trying to register as the leader", t);+ cancelElection();try {core = cc.getCore(coreName);if (core == null) {- cancelElection();throw new SolrException(ErrorCode.SERVER_ERROR,"Fatal Error, SolrCore not found:" + coreName + " in "+ cc.getCoreNames());}- core.getCoreDescriptor().getCloudDescriptor().isLeader = false;+ core.getCoreDescriptor().getCloudDescriptor().setLeader(false);// we could not publish ourselves as leader - rejoin electionrejoinLeaderElection(leaderSeqPath, core);@@ -332,7 +333,7 @@ final class ShardLeaderElectionContext extends ShardLeaderElectionContextBase {return;} else {if (cnt % 40 == 0) {- log.info("Waiting until we see more replicas up: total="+ log.info("Waiting until we see more replicas up for shard " + shardId + ": total="+ slices.getReplicasMap().size() + " found=" + found+ " timeoutin=" + (timeoutAt - System.currentTimeMillis()));}diff --git a/solr/core/src/java/org/apache/solr/cloud/Overseer.java b/solr/core/src/java/org/apache/solr/cloud/Overseer.javaindex c5a9fb43a6c..cf8d02e79b2 100644--- a/solr/core/src/java/org/apache/solr/cloud/Overseer.java+++ b/solr/core/src/java/org/apache/solr/cloud/Overseer.java@@ -50,15 +50,16 @@ import org.slf4j.LoggerFactory;*/public class Overseer {public static final String QUEUE_OPERATION = "operation";+ public static final String DELETECORE = "deletecore";public static final String REMOVECOLLECTION = "removecollection";private static final int STATE_UPDATE_DELAY = 1500; // delay between cloud state updates+private static Logger log = LoggerFactory.getLogger(Overseer.class);private class ClusterStateUpdater implements Runnable, ClosableThread {- private static final String DELETECORE = "deletecore";private final ZkStateReader reader;private final SolrZkClient zkClient;private final String myId;@@ -267,8 +268,14 @@ public class Overseer {final String collection = message.getStr(ZkStateReader.COLLECTION_PROP);String coreNodeName = message.getStr(ZkStateReader.CORE_NODE_NAME_PROP);if (coreNodeName == null) {- // it must be the default then- coreNodeName = message.getStr(ZkStateReader.NODE_NAME_PROP) + "_" + message.getStr(ZkStateReader.CORE_NAME_PROP);+ coreNodeName = getAssignedCoreNodeName(state, message);+ if (coreNodeName != null) {+ log.info("node=" + coreNodeName + " is already registered");+ } else {+ // if coreNodeName is null, auto assign one+ coreNodeName = Assign.assignNode(collection, state);+ }+ message.getProperties().put(ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);}Integer numShards = message.getStr(ZkStateReader.NUM_SHARDS_PROP)!=null?Integer.parseInt(message.getStr(ZkStateReader.NUM_SHARDS_PROP)):null;log.info("Update state numShards={} message={}", numShards, message);@@ -281,7 +288,6 @@ public class Overseer {// use the provided non null shardIdString sliceName = message.getStr(ZkStateReader.SHARD_ID_PROP);if (sliceName == null) {- //String nodeName = message.getStr(ZkStateReader.NODE_NAME_PROP);//get shardId from ClusterStatesliceName = getAssignedId(state, coreNodeName, message);if (sliceName != null) {@@ -295,8 +301,8 @@ public class Overseer {numShards = state.getCollectionStates().get(collection).getSlices().size();log.info("Collection already exists with " + ZkStateReader.NUM_SHARDS_PROP + "=" + numShards);}- sliceName = AssignShard.assignShard(collection, state, numShards);- log.info("Assigning new node to shard=" + sliceName);+ sliceName = Assign.assignShard(collection, state, numShards);+ log.info("Assigning new node to shard shard=" + sliceName);}Slice slice = state.getSlice(collection, sliceName);@@ -320,8 +326,11 @@ public class Overseer {}}- // we don't put num_shards in the clusterstate+ // we don't put these in the clusterstatereplicaProps.remove(ZkStateReader.NUM_SHARDS_PROP);+ replicaProps.remove(ZkStateReader.CORE_NODE_NAME_PROP);+ replicaProps.remove(ZkStateReader.SHARD_ID_PROP);+ replicaProps.remove(ZkStateReader.COLLECTION_PROP);replicaProps.remove(QUEUE_OPERATION);// remove any props with null values@@ -417,6 +426,26 @@ public class Overseer {return null;}+ private String getAssignedCoreNodeName(ClusterState state, ZkNodeProps message) {+ Collection<Slice> slices = state.getSlices(message.getStr(ZkStateReader.COLLECTION_PROP));+ if (slices != null) {+ for (Slice slice : slices) {+ for (Replica replica : slice.getReplicas()) {+ String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);+ String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);++ String msgBaseUrl = message.getStr(ZkStateReader.BASE_URL_PROP);+ String msgCore = message.getStr(ZkStateReader.CORE_NAME_PROP);++ if (baseUrl.equals(msgBaseUrl) && core.equals(msgCore)) {+ return replica.getName();+ }+ }+ }+ }+ return null;+ }+private ClusterState updateSlice(ClusterState state, String collectionName, Slice slice) {// System.out.println("###!!!### OLD CLUSTERSTATE: " + JSONUtil.toJSON(state.getCollectionStates()));// System.out.println("Updating slice:" + slice);@@ -526,10 +555,6 @@ public class Overseer {private ClusterState removeCore(final ClusterState clusterState, ZkNodeProps message) {String cnn = message.getStr(ZkStateReader.CORE_NODE_NAME_PROP);- if (cnn == null) {- // it must be the default then- cnn = message.getStr(ZkStateReader.NODE_NAME_PROP) + "_" + message.getStr(ZkStateReader.CORE_NAME_PROP);- }final String collection = message.getStr(ZkStateReader.COLLECTION_PROP);diff --git a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.javaindex 23c9771168a..212913dfba3 100644--- a/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java+++ b/solr/core/src/java/org/apache/solr/cloud/OverseerCollectionProcessor.java@@ -400,10 +400,11 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {// wait for parent leader to acknowledge the sub-shard corelog.info("Asking parent leader to wait for: " + subShardName + " to be alive on: " + nodeName);+ String coreNodeName = waitForCoreNodeName(collection, zkStateReader.getZkClient().getBaseUrlForNodeName(nodeName), subShardName);CoreAdminRequest.WaitForState cmd = new CoreAdminRequest.WaitForState();cmd.setCoreName(subShardName);cmd.setNodeName(nodeName);- cmd.setCoreNodeName(nodeName + "_" + subShardName);+ cmd.setCoreNodeName(coreNodeName);cmd.setState(ZkStateReader.ACTIVE);cmd.setCheckLive(true);cmd.setOnlyIfLeader(true);@@ -506,12 +507,13 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {sendShardRequest(subShardNodeName, params);+ String coreNodeName = waitForCoreNodeName(collection, zkStateReader.getZkClient().getBaseUrlForNodeName(subShardNodeName), shardName);// wait for the replicas to be seen as active on sub shard leaderlog.info("Asking sub shard leader to wait for: " + shardName + " to be alive on: " + subShardNodeName);CoreAdminRequest.WaitForState cmd = new CoreAdminRequest.WaitForState();cmd.setCoreName(subShardNames.get(i-1));cmd.setNodeName(subShardNodeName);- cmd.setCoreNodeName(subShardNodeName + "_" + shardName);+ cmd.setCoreNodeName(coreNodeName);cmd.setState(ZkStateReader.ACTIVE);cmd.setCheckLive(true);cmd.setOnlyIfLeader(true);@@ -545,6 +547,35 @@ public class OverseerCollectionProcessor implements Runnable, ClosableThread {throw new SolrException(ErrorCode.SERVER_ERROR, null, e);}}++ private String waitForCoreNodeName(DocCollection collection, String msgBaseUrl, String msgCore) {+ int retryCount = 320;+ while (retryCount-- > 0) {+ Map<String,Slice> slicesMap = zkStateReader.getClusterState()+ .getSlicesMap(collection.getName());+ if (slicesMap != null) {++ for (Slice slice : slicesMap.values()) {+ for (Replica replica : slice.getReplicas()) {+ // TODO: for really large clusters, we could 'index' on this++ String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);+ String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);++ if (baseUrl.equals(msgBaseUrl) && core.equals(msgCore)) {+ return replica.getName();+ }+ }+ }+ }+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+ throw new SolrException(ErrorCode.SERVER_ERROR, "Could not find coreNodeName");+ }private void collectShardResponses(NamedList results, boolean abortOnError, String msgOnError) {ShardResponse srsp;diff --git a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.javaindex 0dfd83ba289..7a0dc7c092c 100644--- a/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/RecoveryStrategy.java@@ -91,7 +91,7 @@ public class RecoveryStrategy extends Thread implements ClosableThread {zkController = cc.getZkController();zkStateReader = zkController.getZkStateReader();baseUrl = zkController.getBaseUrl();- coreZkNodeName = zkController.getCoreNodeName(cd);+ coreZkNodeName = cd.getCloudDescriptor().getCoreNodeName();}public void setRecoveringAfterStartup(boolean recoveringAfterStartup) {@@ -325,10 +325,10 @@ public class RecoveryStrategy extends Thread implements ClosableThread {String ourUrl = ZkCoreNodeProps.getCoreUrl(baseUrl, coreName);boolean isLeader = leaderUrl.equals(ourUrl);- if (isLeader && !cloudDesc.isLeader) {+ if (isLeader && !cloudDesc.isLeader()) {throw new SolrException(ErrorCode.SERVER_ERROR, "Cloud state still says we are leader.");}- if (cloudDesc.isLeader) {+ if (cloudDesc.isLeader()) {// we are now the leader - no one else must have been suitablelog.warn("We have not yet recovered - but we are now the leader! core=" + coreName);log.info("Finished recovery process. core=" + coreName);diff --git a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.javaindex 1a063b4eb7b..25136e3b68f 100644--- a/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java+++ b/solr/core/src/java/org/apache/solr/cloud/SyncStrategy.java@@ -160,8 +160,7 @@ public class SyncStrategy {private boolean syncWithReplicas(ZkController zkController, SolrCore core,ZkNodeProps props, String collection, String shardId) {List<ZkCoreNodeProps> nodes = zkController.getZkStateReader()- .getReplicaProps(collection, shardId,- zkController.getCoreNodeName(core.getCoreDescriptor()),+ .getReplicaProps(collection, shardId,core.getCoreDescriptor().getCloudDescriptor().getCoreNodeName(),props.getStr(ZkStateReader.CORE_NAME_PROP));if (nodes == null) {@@ -189,7 +188,7 @@ public class SyncStrategy {List<ZkCoreNodeProps> nodes = zkController.getZkStateReader().getReplicaProps(collection, shardId,- zkController.getCoreNodeName(cd),+ cd.getCloudDescriptor().getCoreNodeName(),leaderProps.getStr(ZkStateReader.CORE_NAME_PROP));if (nodes == null) {log.info(ZkCoreNodeProps.getCoreUrl(leaderProps) + " has no replicas");diff --git a/solr/core/src/java/org/apache/solr/cloud/ZkController.java b/solr/core/src/java/org/apache/solr/cloud/ZkController.javaindex 1ca10b4bef3..d8b6c6b882e 100644--- a/solr/core/src/java/org/apache/solr/cloud/ZkController.java+++ b/solr/core/src/java/org/apache/solr/cloud/ZkController.java@@ -132,6 +132,8 @@ public final class ZkController {protected volatile Overseer overseer;private String leaderVoteWait;++ private boolean genericCoreNodeNames;private int clientTimeout;@@ -140,11 +142,11 @@ public final class ZkController {private UpdateShardHandler updateShardHandler;public ZkController(final CoreContainer cc, String zkServerAddress, int zkClientTimeout, int zkClientConnectTimeout, String localHost, String locaHostPort,- String localHostContext, String leaderVoteWait, int distribUpdateConnTimeout, int distribUpdateSoTimeout, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,+ String localHostContext, String leaderVoteWait, boolean genericCoreNodeNames, int distribUpdateConnTimeout, int distribUpdateSoTimeout, final CurrentCoreDescriptorProvider registerOnReconnect) throws InterruptedException,TimeoutException, IOException {if (cc == null) throw new IllegalArgumentException("CoreContainer cannot be null.");this.cc = cc;-+ this.genericCoreNodeNames = genericCoreNodeNames;// be forgiving and strip this off leading/trailing slashes// this allows us to support users specifying hostContext="/" in// solr.xml to indicate the root context, instead of hostContext=""@@ -254,9 +256,9 @@ public final class ZkController {// before registering as live, make sure everyone is in a// down statefor (CoreDescriptor descriptor : descriptors) {- final String coreZkNodeName = getCoreNodeName(descriptor);+ final String coreZkNodeName = descriptor.getCloudDescriptor().getCoreNodeName();try {- descriptor.getCloudDescriptor().isLeader = false;+ descriptor.getCloudDescriptor().setLeader(false);publish(descriptor, ZkStateReader.DOWN, updateLastPublished);} catch (Exception e) {if (isClosed) {@@ -323,7 +325,7 @@ public final class ZkController {.getCurrentDescriptors();if (descriptors != null) {for (CoreDescriptor descriptor : descriptors) {- descriptor.getCloudDescriptor().isLeader = false;+ descriptor.getCloudDescriptor().setLeader(false);}}}@@ -544,7 +546,6 @@ public final class ZkController {if (replica.getNodeName().equals(getNodeName())&& !(replica.getStr(ZkStateReader.STATE_PROP).equals(ZkStateReader.DOWN))) {- assert replica.getStr(ZkStateReader.SHARD_ID_PROP) != null;ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",ZkStateReader.STATE_PROP, ZkStateReader.DOWN,ZkStateReader.BASE_URL_PROP, getBaseUrl(),@@ -555,8 +556,7 @@ public final class ZkController {ZkStateReader.NODE_NAME_PROP, getNodeName(),ZkStateReader.SHARD_ID_PROP,replica.getStr(ZkStateReader.SHARD_ID_PROP),- ZkStateReader.COLLECTION_PROP,- replica.getStr(ZkStateReader.COLLECTION_PROP),+ ZkStateReader.COLLECTION_PROP, collectionName,ZkStateReader.CORE_NODE_NAME_PROP, replica.getName());updatedNodes.add(replica.getStr(ZkStateReader.CORE_NAME_PROP));overseerJobQueue.offer(ZkStateReader.toJSON(m));@@ -735,7 +735,8 @@ public final class ZkController {final CloudDescriptor cloudDesc = desc.getCloudDescriptor();final String collection = cloudDesc.getCollectionName();- final String coreZkNodeName = getCoreNodeName(desc);+ final String coreZkNodeName = desc.getCloudDescriptor().getCoreNodeName();+ assert coreZkNodeName != null : "we should have a coreNodeName by now";String shardId = cloudDesc.getShardId();@@ -923,16 +924,16 @@ public final class ZkController {props.put(ZkStateReader.CORE_NAME_PROP, cd.getName());props.put(ZkStateReader.NODE_NAME_PROP, getNodeName());- final String coreZkNodeName = getCoreNodeName(cd);+ final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();ZkNodeProps ourProps = new ZkNodeProps(props);String collection = cd.getCloudDescriptor().getCollectionName();ElectionContext context = new ShardLeaderElectionContext(leaderElector, shardId,- collection, coreZkNodeName, ourProps, this, cc);+ collection, coreNodeName, ourProps, this, cc);leaderElector.setup(context);- electionContexts.put(coreZkNodeName, context);+ electionContexts.put(coreNodeName, context);leaderElector.joinElection(context, false);}@@ -1017,7 +1018,7 @@ public final class ZkController {final CloudDescriptor cloudDesc = desc.getCloudDescriptor();- final String shardId = state.getShardId(coreNodeName);+ final String shardId = state.getShardId(getBaseUrl(), desc.getName());if (shardId != null) {cloudDesc.setShardId(shardId);@@ -1028,16 +1029,21 @@ public final class ZkController {public void unregister(String coreName, CoreDescriptor cd)throws InterruptedException, KeeperException {- final String zkNodeName = getCoreNodeName(cd);- ElectionContext context = electionContexts.remove(zkNodeName);+ final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();+ ElectionContext context = electionContexts.remove(coreNodeName);++ assert context != null : coreNodeName;+if (context != null) {context.cancelElection();}+ CloudDescriptor cloudDescriptor = cd.getCloudDescriptor();ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION,- "deletecore", ZkStateReader.CORE_NAME_PROP, coreName,+ Overseer.DELETECORE, ZkStateReader.CORE_NAME_PROP, coreName,ZkStateReader.NODE_NAME_PROP, getNodeName(),- ZkStateReader.COLLECTION_PROP, cd.getCloudDescriptor().getCollectionName());+ ZkStateReader.COLLECTION_PROP, cloudDescriptor.getCollectionName(),+ ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);overseerJobQueue.offer(ZkStateReader.toJSON(m));}@@ -1206,13 +1212,60 @@ public final class ZkController {return zkStateReader;}- private String doGetShardIdProcess(String coreName, CoreDescriptor descriptor) {- final String coreNodeName = getCoreNodeName(descriptor);+ private void doGetShardIdAndNodeNameProcess(CoreDescriptor cd) {+ final String coreNodeName = cd.getCloudDescriptor().getCoreNodeName();++ if (coreNodeName != null) {+ waitForShardId(cd);+ } else {+ // if no explicit coreNodeName, we want to match by base url and core name+ waitForCoreNodeName(cd);+ waitForShardId(cd);+ }+ }++ private void waitForCoreNodeName(CoreDescriptor descriptor) {int retryCount = 320;+ log.info("look for our core node name");while (retryCount-- > 0) {- final String shardId = zkStateReader.getClusterState().getShardId(coreNodeName);+ Map<String,Slice> slicesMap = zkStateReader.getClusterState()+ .getSlicesMap(descriptor.getCloudDescriptor().getCollectionName());+ if (slicesMap != null) {++ for (Slice slice : slicesMap.values()) {+ for (Replica replica : slice.getReplicas()) {+ // TODO: for really large clusters, we could 'index' on this++ String baseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);+ String core = replica.getStr(ZkStateReader.CORE_NAME_PROP);++ String msgBaseUrl = getBaseUrl();+ String msgCore = descriptor.getName();++ if (baseUrl.equals(msgBaseUrl) && core.equals(msgCore)) {+ descriptor.getCloudDescriptor()+ .setCoreNodeName(replica.getName());+ return;+ }+ }+ }+ }+ try {+ Thread.sleep(1000);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ }+ }+ }++ private void waitForShardId(CoreDescriptor cd) {+ log.info("waiting to find shard id in clusterstate for " + cd.getName());+ int retryCount = 320;+ while (retryCount-- > 0) {+ final String shardId = zkStateReader.getClusterState().getShardId(getBaseUrl(), cd.getName());if (shardId != null) {- return shardId;+ cd.getCloudDescriptor().setShardId(shardId);+ return;}try {Thread.sleep(1000);@@ -1222,7 +1275,7 @@ public final class ZkController {}throw new SolrException(ErrorCode.SERVER_ERROR,- "Could not get shard_id for core: " + coreName + " coreNodeName:" + coreNodeName);+ "Could not get shard id for core: " + cd.getName());}public static void uploadToZK(SolrZkClient zkClient, File dir, String zkPath) throws IOException, KeeperException, InterruptedException {@@ -1261,7 +1314,7 @@ public final class ZkController {public String getCoreNodeName(CoreDescriptor descriptor){String coreNodeName = descriptor.getCloudDescriptor().getCoreNodeName();- if (coreNodeName == null) {+ if (coreNodeName == null && !genericCoreNodeNames) {// it's the defaultreturn getNodeName() + "_" + descriptor.getName();}@@ -1277,27 +1330,33 @@ public final class ZkController {downloadFromZK(zkClient, ZkController.CONFIGS_ZKNODE + "/" + configName, dir);}- public void preRegister(CoreDescriptor cd) throws KeeperException, InterruptedException {--- // before becoming available, make sure we are not live and active- // this also gets us our assigned shard id if it was not specified- publish(cd, ZkStateReader.DOWN, false);-- String coreNodeName = getCoreNodeName(cd);+ public void preRegister(CoreDescriptor cd ) {+ String coreNodeName = getCoreNodeName(cd);+// make sure the node name is set on the descriptorif (cd.getCloudDescriptor().getCoreNodeName() == null) {cd.getCloudDescriptor().setCoreNodeName(coreNodeName);}++ // before becoming available, make sure we are not live and active+ // this also gets us our assigned shard id if it was not specified+ try {+ publish(cd, ZkStateReader.DOWN, false);+ } catch (KeeperException e) {+ log.error("", e);+ throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ log.error("", e);+ throw new ZooKeeperException(SolrException.ErrorCode.SERVER_ERROR, "", e);+ }if (cd.getCloudDescriptor().getShardId() == null && needsToBeAssignedShardId(cd, zkStateReader.getClusterState(), coreNodeName)) {- String shardId;- shardId = doGetShardIdProcess(cd.getName(), cd);- cd.getCloudDescriptor().setShardId(shardId);+ doGetShardIdAndNodeNameProcess(cd);} else {// still wait till we see us in local state- doGetShardIdProcess(cd.getName(), cd);+ doGetShardIdAndNodeNameProcess(cd);}}@@ -1332,7 +1391,7 @@ public final class ZkController {}}}-+String leaderBaseUrl = leaderProps.getBaseUrl();String leaderCoreName = leaderProps.getCoreName();@@ -1494,11 +1553,11 @@ public final class ZkController {}/**- * utilitiy method fro trimming and leading and/or trailing slashes from+ * Utility method for trimming and leading and/or trailing slashes from* it's input. May return the empty string. May return null if and only* if the input is null.*/- private static String trimLeadingAndTrailingSlashes(final String in) {+ public static String trimLeadingAndTrailingSlashes(final String in) {if (null == in) return in;String out = in;diff --git a/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.javaindex 594d8f95bc8..60c4131abbb 100644--- a/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java+++ b/solr/core/src/java/org/apache/solr/core/CachingDirectoryFactory.java@@ -32,6 +32,7 @@ import java.util.Set;import org.apache.lucene.store.AlreadyClosedException;import org.apache.lucene.store.Directory;import org.apache.lucene.store.IOContext.Context;+import org.apache.lucene.store.NRTCachingDirectory;import org.apache.lucene.store.NativeFSLockFactory;import org.apache.lucene.store.NoLockFactory;import org.apache.lucene.store.RateLimitedDirectoryWrapper;@@ -40,6 +41,9 @@ import org.apache.lucene.store.SingleInstanceLockFactory;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.util.NamedList;+import org.apache.solr.store.blockcache.BlockDirectory;+import org.apache.solr.store.hdfs.HdfsDirectory;+import org.apache.solr.store.hdfs.HdfsLockFactory;import org.slf4j.Logger;import org.slf4j.LoggerFactory;@@ -498,6 +502,24 @@ public abstract class CachingDirectoryFactory extends DirectoryFactory {} else if ("single".equals(lockType)) {if (!(dir.getLockFactory() instanceof SingleInstanceLockFactory)) dir.setLockFactory(new SingleInstanceLockFactory());+ } else if ("hdfs".equals(lockType)) {+ Directory del = dir;++ if (dir instanceof NRTCachingDirectory) {+ del = ((NRTCachingDirectory) del).getDelegate();+ }++ if (del instanceof BlockDirectory) {+ del = ((BlockDirectory) del).getDirectory();+ }++ if (!(del instanceof HdfsDirectory)) {+ throw new SolrException(ErrorCode.FORBIDDEN, "Directory: "+ + del.getClass().getName()+ + ", but hdfs lock factory can only be used with HdfsDirectory");+ }++ dir.setLockFactory(new HdfsLockFactory(((HdfsDirectory)del).getHdfsDirPath(), ((HdfsDirectory)del).getConfiguration()));} else if ("none".equals(lockType)) {// Recipe for disasterlog.error("CONFIGURATION WARNING: locks are disabled on " + dir);@@ -519,7 +541,7 @@ public abstract class CachingDirectoryFactory extends DirectoryFactory {return path;}- private String stripTrailingSlash(String path) {+ protected String stripTrailingSlash(String path) {if (path.endsWith("/")) {path = path.substring(0, path.length() - 1);}diff --git a/solr/core/src/java/org/apache/solr/core/ConfigSolr.java b/solr/core/src/java/org/apache/solr/core/ConfigSolr.javaindex 63da0efb4b1..ef2ef84b2e1 100644--- a/solr/core/src/java/org/apache/solr/core/ConfigSolr.java+++ b/solr/core/src/java/org/apache/solr/core/ConfigSolr.java@@ -63,6 +63,7 @@ public abstract class ConfigSolr {SOLR_SHARDHANDLERFACTORY_SOCKETTIMEOUT,SOLR_SHARESCHEMA,SOLR_TRANSIENTCACHESIZE,+ SOLR_GENERICCORENODENAMES,SOLR_ZKCLIENTTIMEOUT,SOLR_ZKHOST,diff --git a/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java b/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.javaindex 57bc281e4ea..81f4b0f4d0a 100644--- a/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java+++ b/solr/core/src/java/org/apache/solr/core/ConfigSolrXml.java@@ -77,6 +77,7 @@ public class ConfigSolrXml extends ConfigSolr {failIfFound("solr/cores/@hostContext");failIfFound("solr/cores/@hostPort");failIfFound("solr/cores/@leaderVoteWait");+ failIfFound("solr/cores/@genericCoreNodeNames");failIfFound("solr/cores/@managementPath");failIfFound("solr/cores/@shareSchema");failIfFound("solr/cores/@transientCacheSize");@@ -118,6 +119,7 @@ public class ConfigSolrXml extends ConfigSolr {propMap.put(CfgProp.SOLR_HOSTCONTEXT, doSub("solr/solrcloud/str[@name='hostContext']"));propMap.put(CfgProp.SOLR_HOSTPORT, doSub("solr/solrcloud/int[@name='hostPort']"));propMap.put(CfgProp.SOLR_LEADERVOTEWAIT, doSub("solr/solrcloud/int[@name='leaderVoteWait']"));+ propMap.put(CfgProp.SOLR_GENERICCORENODENAMES, doSub("solr/solrcloud/bool[@name='genericCoreNodeNames']"));propMap.put(CfgProp.SOLR_MANAGEMENTPATH, doSub("solr/str[@name='managementPath']"));propMap.put(CfgProp.SOLR_SHAREDLIB, doSub("solr/str[@name='sharedLib']"));propMap.put(CfgProp.SOLR_SHARESCHEMA, doSub("solr/str[@name='shareSchema']"));diff --git a/solr/core/src/java/org/apache/solr/core/ConfigSolrXmlOld.java b/solr/core/src/java/org/apache/solr/core/ConfigSolrXmlOld.javaindex f7a7d23e377..de4d1efdacf 100644--- a/solr/core/src/java/org/apache/solr/core/ConfigSolrXmlOld.java+++ b/solr/core/src/java/org/apache/solr/core/ConfigSolrXmlOld.java@@ -73,6 +73,7 @@ public class ConfigSolrXmlOld extends ConfigSolr {failIfFound("solr/solrcloud/str[@name='hostContext']");failIfFound("solr/solrcloud/int[@name='hostPort']");failIfFound("solr/solrcloud/int[@name='leaderVoteWait']");+ failIfFound("solr/solrcloud/int[@name='genericCoreNodeNames']");failIfFound("solr/str[@name='managementPath']");failIfFound("solr/str[@name='sharedLib']");failIfFound("solr/str[@name='shareSchema']");@@ -125,6 +126,8 @@ public class ConfigSolrXmlOld extends ConfigSolr {config.getVal("solr/cores/@hostPort", false));propMap.put(CfgProp.SOLR_LEADERVOTEWAIT,config.getVal("solr/cores/@leaderVoteWait", false));+ propMap.put(CfgProp.SOLR_GENERICCORENODENAMES,+ config.getVal("solr/cores/@genericCoreNodeNames", false));propMap.put(CfgProp.SOLR_MANAGEMENTPATH,config.getVal("solr/cores/@managementPath", false));propMap.put(CfgProp.SOLR_SHARESCHEMA,diff --git a/solr/core/src/java/org/apache/solr/core/CoreContainer.java b/solr/core/src/java/org/apache/solr/core/CoreContainer.javaindex 69bae0d05b5..8df62cf0a75 100644--- a/solr/core/src/java/org/apache/solr/core/CoreContainer.java+++ b/solr/core/src/java/org/apache/solr/core/CoreContainer.java@@ -182,7 +182,7 @@ public class CoreContainercores = new CoreContainer(solrHome);// first we find zkhost, then we check for solr.xml in zk- // 1. look for zkhost from sys prop 2. look for zkhost in {solr.home}/solr.properties+ // 1. look for zkhost from sys prop 2. TODO: look for zkhost in {solr.home}/solr.properties// Either we have a config file or not.@@ -317,13 +317,15 @@ public class CoreContainertransientCacheSize = cfg.getInt(ConfigSolr.CfgProp.SOLR_TRANSIENTCACHESIZE, Integer.MAX_VALUE);+ boolean genericCoreNodeNames = cfg.getBool(ConfigSolr.CfgProp.SOLR_GENERICCORENODENAMES, false);+if (shareSchema) {indexSchemaCache = new ConcurrentHashMap<String,IndexSchema>();}zkClientTimeout = Integer.parseInt(System.getProperty("zkClientTimeout",Integer.toString(zkClientTimeout)));- zkSys.initZooKeeper(this, solrHome, zkHost, zkClientTimeout, hostPort, hostContext, host, leaderVoteWait, distribUpdateConnTimeout, distribUpdateSoTimeout);+ zkSys.initZooKeeper(this, solrHome, zkHost, zkClientTimeout, hostPort, hostContext, host, leaderVoteWait, genericCoreNodeNames, distribUpdateConnTimeout, distribUpdateSoTimeout);if (isZooKeeperAware() && coreLoadThreads <= 1) {throw new SolrException(ErrorCode.SERVER_ERROR,@@ -1143,6 +1145,8 @@ public class CoreContainerzkSys.getHostContext());addAttrib(coresAttribs, ConfigSolr.CfgProp.SOLR_LEADERVOTEWAIT, "leaderVoteWait",zkSys.getLeaderVoteWait(), LEADER_VOTE_WAIT);+ addAttrib(coresAttribs, ConfigSolr.CfgProp.SOLR_GENERICCORENODENAMES, "genericCoreNodeNames",+ Boolean.toString(zkSys.getGenericCoreNodeNames()), "false");if (transientCacheSize != Integer.MAX_VALUE) { // This test// is a consequence of testing. I really hate it.addAttrib(coresAttribs, ConfigSolr.CfgProp.SOLR_TRANSIENTCACHESIZE, "transientCacheSize",@@ -1220,18 +1224,7 @@ public class CoreContainer}public void preRegisterInZk(final CoreDescriptor p) {- try {- zkSys.getZkController().preRegister(p);- } catch (KeeperException e) {- log.error("", e);- throw new ZooKeeperException(- SolrException.ErrorCode.SERVER_ERROR, "", e);- } catch (InterruptedException e) {- Thread.currentThread().interrupt();- log.error("", e);- throw new ZooKeeperException(- SolrException.ErrorCode.SERVER_ERROR, "", e);- }+ zkSys.getZkController().preRegister(p);}public String getSolrHome() {diff --git a/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/DirectoryFactory.javaindex a5b329c3d7a..2c1aa578de3 100644--- a/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java+++ b/solr/core/src/java/org/apache/solr/core/DirectoryFactory.java@@ -167,7 +167,6 @@ public abstract class DirectoryFactory implements NamedListInitializedPlugin,*/public abstract void release(Directory directory) throws IOException;-/*** Normalize a given path.*@@ -229,5 +228,21 @@ public abstract class DirectoryFactory implements NamedListInitializedPlugin,}return isSuccess;}-++ /**+ * If your implementation can count on delete-on-last-close semantics+ * or throws an exception when trying to remove a file in use, return+ * false (eg NFS). Otherwise, return true. Defaults to returning false.+ *+ * @return true if factory impl requires that Searcher's explicitly+ * reserve commit points.+ */+ public boolean searchersReserveCommitPoints() {+ return false;+ }++ public String getDataHome(CoreDescriptor cd) throws IOException {+ // by default, we go off the instance directory+ return normalize(SolrResourceLoader.normalizeDir(cd.getInstanceDir()) + cd.getDataDir());+ }}diff --git a/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.javaindex 904db07e9f5..f7f58097ce4 100644--- a/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java+++ b/solr/core/src/java/org/apache/solr/core/EphemeralDirectoryFactory.java@@ -51,4 +51,16 @@ public abstract class EphemeralDirectoryFactory extends CachingDirectoryFactorypublic boolean isAbsolute(String path) {return true;}+++ @Override+ public void remove(Directory dir) throws IOException {+ // ram dir does not persist its dir anywhere+ }++ @Override+ public void remove(String path) throws IOException {+ // ram dir does not persist its dir anywhere+ }+}diff --git a/solr/core/src/java/org/apache/solr/core/HdfsDirectoryFactory.java b/solr/core/src/java/org/apache/solr/core/HdfsDirectoryFactory.javanew file mode 100644index 00000000000..341c8115ef6--- /dev/null+++ b/solr/core/src/java/org/apache/solr/core/HdfsDirectoryFactory.java@@ -0,0 +1,288 @@+package org.apache.solr.core;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.net.URI;+import java.net.URLEncoder;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.security.UserGroupInformation;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.NRTCachingDirectory;+import org.apache.solr.cloud.ZkController;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.common.params.SolrParams;+import org.apache.solr.common.util.NamedList;+import org.apache.solr.store.blockcache.BlockCache;+import org.apache.solr.store.blockcache.BlockDirectory;+import org.apache.solr.store.blockcache.BlockDirectoryCache;+import org.apache.solr.store.blockcache.BufferStore;+import org.apache.solr.store.blockcache.Cache;+import org.apache.solr.store.blockcache.Metrics;+import org.apache.solr.store.hdfs.HdfsDirectory;+import org.apache.solr.util.HdfsUtil;+import org.apache.solr.util.IOUtils;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HdfsDirectoryFactory extends CachingDirectoryFactory {+ public static Logger LOG = LoggerFactory+ .getLogger(HdfsDirectoryFactory.class);++ public static final String BLOCKCACHE_SLAB_COUNT = "solr.hdfs.blockcache.slab.count";+ public static final String BLOCKCACHE_DIRECT_MEMORY_ALLOCATION = "solr.hdfs.blockcache.direct.memory.allocation";+ public static final String BLOCKCACHE_ENABLED = "solr.hdfs.blockcache.enabled";+ public static final String BLOCKCACHE_READ_ENABLED = "solr.hdfs.blockcache.read.enabled";+ public static final String BLOCKCACHE_WRITE_ENABLED = "solr.hdfs.blockcache.write.enabled";++ public static final String NRTCACHINGDIRECTORY_ENABLE = "solr.hdfs.nrtcachingdirectory.enable";+ public static final String NRTCACHINGDIRECTORY_MAXMERGESIZEMB = "solr.hdfs.nrtcachingdirectory.maxmergesizemb";+ public static final String NRTCACHINGDIRECTORY_MAXCACHEMB = "solr.hdfs.nrtcachingdirectory.maxcachedmb";+ public static final String NUMBEROFBLOCKSPERBANK = "solr.hdfs.blockcache.blocksperbank";++ public static final String KERBEROS_ENABLED = "solr.hdfs.security.kerberos.enabled";+ public static final String KERBEROS_KEYTAB = "solr.hdfs.security.kerberos.keytabfile";+ public static final String KERBEROS_PRINCIPAL = "solr.hdfs.security.kerberos.principal";++ public static final String HDFS_HOME = "solr.hdfs.home";++ public static final String CONFIG_DIRECTORY = "solr.hdfs.confdir";++ private SolrParams params;++ private String hdfsDataDir;++ private String confDir;++ public static Metrics metrics;+ private static Boolean kerberosInit;++ @Override+ public void init(NamedList args) {+ params = SolrParams.toSolrParams(args);+ this.hdfsDataDir = params.get(HDFS_HOME);+ if (this.hdfsDataDir != null && this.hdfsDataDir.length() == 0) {+ this.hdfsDataDir = null;+ }+ boolean kerberosEnabled = params.getBool(KERBEROS_ENABLED, false);+ LOG.info("Solr Kerberos Authentication "+ + (kerberosEnabled ? "enabled" : "disabled"));+ if (kerberosEnabled) {+ initKerberos();+ }+ }++ @Override+ protected Directory create(String path, DirContext dirContext)+ throws IOException {+ LOG.info("creating directory factory for path {}", path);+ Configuration conf = getConf();++ if (metrics == null) {+ metrics = new Metrics(conf);+ }++ boolean blockCacheEnabled = params.getBool(BLOCKCACHE_ENABLED, true);+ boolean blockCacheReadEnabled = params.getBool(BLOCKCACHE_READ_ENABLED,+ true);+ boolean blockCacheWriteEnabled = params.getBool(BLOCKCACHE_WRITE_ENABLED, true);+ Directory dir = null;++ if (blockCacheEnabled && dirContext != DirContext.META_DATA) {+ int numberOfBlocksPerBank = params.getInt(NUMBEROFBLOCKSPERBANK, 16384);++ int blockSize = BlockDirectory.BLOCK_SIZE;++ int bankCount = params.getInt(BLOCKCACHE_SLAB_COUNT, 1);++ boolean directAllocation = params.getBool(+ BLOCKCACHE_DIRECT_MEMORY_ALLOCATION, true);++ BlockCache blockCache;++ int slabSize = numberOfBlocksPerBank * blockSize;+ LOG.info(+ "Number of slabs of block cache [{}] with direct memory allocation set to [{}]",+ bankCount, directAllocation);+ LOG.info(+ "Block cache target memory usage, slab size of [{}] will allocate [{}] slabs and use ~[{}] bytes",+ new Object[] {slabSize, bankCount,+ ((long) bankCount * (long) slabSize)});++ int _1024Size = params.getInt("solr.hdfs.blockcache.bufferstore.1024",+ 8192);+ int _8192Size = params.getInt("solr.hdfs.blockcache.bufferstore.8192",+ 8192);++ BufferStore.init(_1024Size, _8192Size, metrics);+ long totalMemory = (long) bankCount * (long) numberOfBlocksPerBank+ * (long) blockSize;+ try {+ blockCache = new BlockCache(metrics, directAllocation, totalMemory,+ slabSize, blockSize);+ } catch (OutOfMemoryError e) {+ throw new RuntimeException(+ "The max direct memory is likely too low. Either increase it (by adding -XX:MaxDirectMemorySize=<size>g -XX:+UseLargePages to your containers startup args)"+ + " or disable direct allocation using solr.hdfs.blockcache.direct.memory.allocation=false in solrconfig.xml. If you are putting the block cache on the heap,"+ + " your java heap size might not be large enough."+ + " Failed allocating ~" + totalMemory / 1000000.0 + " MB.", e);+ }+ Cache cache = new BlockDirectoryCache(blockCache, metrics);+ HdfsDirectory hdfsDirectory = new HdfsDirectory(new Path(path), conf);+ dir = new BlockDirectory("solrcore", hdfsDirectory, cache, null,+ blockCacheReadEnabled, blockCacheWriteEnabled);+ } else {+ dir = new HdfsDirectory(new Path(path), conf);+ }++ boolean nrtCachingDirectory = params.getBool(NRTCACHINGDIRECTORY_ENABLE, true);+ if (nrtCachingDirectory) {+ double nrtCacheMaxMergeSizeMB = params.getInt(+ NRTCACHINGDIRECTORY_MAXMERGESIZEMB, 16);+ double nrtCacheMaxCacheMB = params.getInt(NRTCACHINGDIRECTORY_MAXCACHEMB,+ 192);++ return new NRTCachingDirectory(dir, nrtCacheMaxMergeSizeMB,+ nrtCacheMaxCacheMB);+ }+ return dir;+ }++ @Override+ public boolean exists(String path) {+ Path hdfsDirPath = new Path(path);+ Configuration conf = getConf();+ FileSystem fileSystem = null;+ try {+ fileSystem = FileSystem.newInstance(hdfsDirPath.toUri(), conf);+ return fileSystem.exists(hdfsDirPath);+ } catch (IOException e) {+ LOG.error("Error checking if hdfs path exists", e);+ throw new RuntimeException("Error checking if hdfs path exists", e);+ } finally {+ IOUtils.closeQuietly(fileSystem);+ }+ }++ private Configuration getConf() {+ Configuration conf = new Configuration();+ confDir = params.get(CONFIG_DIRECTORY, null);+ HdfsUtil.addHdfsResources(conf, confDir);+ return conf;+ }++ protected synchronized void removeDirectory(CacheValue cacheValue)+ throws IOException {+ Configuration conf = getConf();+ FileSystem fileSystem = null;+ try {+ fileSystem = FileSystem.newInstance(new URI(cacheValue.path), conf);+ boolean success = fileSystem.delete(new Path(cacheValue.path), true);+ if (!success) {+ throw new RuntimeException("Could not remove directory");+ }+ } catch (Exception e) {+ LOG.error("Could not remove directory", e);+ throw new SolrException(ErrorCode.SERVER_ERROR,+ "Could not remove directory", e);+ } finally {+ IOUtils.closeQuietly(fileSystem);+ }+ }++ @Override+ public boolean isAbsolute(String path) {+ return path.startsWith("hdfs:/");+ }++ @Override+ public boolean isPersistent() {+ return true;+ }++ @Override+ public boolean searchersReserveCommitPoints() {+ return true;+ }++ @Override+ public String getDataHome(CoreDescriptor cd) throws IOException {+ if (hdfsDataDir == null) {+ throw new SolrException(ErrorCode.SERVER_ERROR, "You must set the "+ + this.getClass().getSimpleName() + " param " + HDFS_HOME+ + " for relative dataDir paths to work");+ }++ // by default, we go off the instance directory+ String path;+ if (cd.getCloudDescriptor() != null) {+ path = URLEncoder.encode(cd.getCloudDescriptor().getCollectionName(),+ "UTF-8")+ + "/"+ + URLEncoder.encode(cd.getCloudDescriptor().getCoreNodeName(),+ "UTF-8");+ } else {+ path = cd.getName();+ }++ return normalize(SolrResourceLoader.normalizeDir(ZkController+ .trimLeadingAndTrailingSlashes(hdfsDataDir)+ + "/"+ + path+ + "/"+ + cd.getDataDir()));+ }++ public String getConfDir() {+ return confDir;+ }++ private void initKerberos() {+ String keytabFile = params.get(KERBEROS_KEYTAB, "").trim();+ if (keytabFile.length() == 0) {+ throw new IllegalArgumentException(KERBEROS_KEYTAB + " required because "+ + KERBEROS_ENABLED + " set to true");+ }+ String principal = params.get(KERBEROS_PRINCIPAL, "");+ if (principal.length() == 0) {+ throw new IllegalArgumentException(KERBEROS_PRINCIPAL+ + " required because " + KERBEROS_ENABLED + " set to true");+ }+ synchronized (HdfsDirectoryFactory.class) {+ if (kerberosInit == null) {+ kerberosInit = new Boolean(true);+ Configuration conf = new Configuration();+ conf.set("hadoop.security.authentication", "kerberos");+ UserGroupInformation.setConfiguration(conf);+ LOG.info(+ "Attempting to acquire kerberos ticket with keytab: {}, principal: {} ",+ keytabFile, principal);+ try {+ UserGroupInformation.loginUserFromKeytab(principal, keytabFile);+ } catch (IOException ioe) {+ throw new RuntimeException(ioe);+ }+ LOG.info("Got Kerberos ticket");+ }+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/core/SolrCore.java b/solr/core/src/java/org/apache/solr/core/SolrCore.javaindex a4b85635d13..413deaf88d0 100644--- a/solr/core/src/java/org/apache/solr/core/SolrCore.java+++ b/solr/core/src/java/org/apache/solr/core/SolrCore.java@@ -673,11 +673,10 @@ public final class SolrCore implements SolrInfoMBean {if (dataDir == null) {if (cd.usingDefaultDataDir()) dataDir = config.getDataDir();if (dataDir == null) {- dataDir = cd.getDataDir();try {+ dataDir = cd.getDataDir();if (!directoryFactory.isAbsolute(dataDir)) {- dataDir = directoryFactory.normalize(SolrResourceLoader- .normalizeDir(cd.getInstanceDir()) + dataDir);+ dataDir = directoryFactory.getDataHome(cd);}} catch (IOException e) {throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, null, e);@@ -748,7 +747,6 @@ public final class SolrCore implements SolrInfoMBean {this.codec = initCodec(solrConfig, schema);if (updateHandler == null) {- initDirectoryFactory();solrCoreState = new DefaultSolrCoreState(getDirectoryFactory());} else {solrCoreState = updateHandler.getSolrCoreState();diff --git a/solr/core/src/java/org/apache/solr/core/ZkContainer.java b/solr/core/src/java/org/apache/solr/core/ZkContainer.javaindex c9ed9b3eb59..538f9ddc8d7 100644--- a/solr/core/src/java/org/apache/solr/core/ZkContainer.java+++ b/solr/core/src/java/org/apache/solr/core/ZkContainer.java@@ -50,6 +50,7 @@ public class ZkContainer {private String hostContext;private String host;private String leaderVoteWait;+ private Boolean genericCoreNodeNames;private int distribUpdateConnTimeout;public SolrZkServer getZkServer() {@@ -75,6 +76,10 @@ public class ZkContainer {public String getLeaderVoteWait() {return leaderVoteWait;}++ public boolean getGenericCoreNodeNames() {+ return genericCoreNodeNames;+ }public int getDistribUpdateConnTimeout() {return distribUpdateConnTimeout;@@ -90,7 +95,7 @@ public class ZkContainer {}- public void initZooKeeper(final CoreContainer cc, String solrHome, String zkHost, int zkClientTimeout, String hostPort, String hostContext, String host, String leaderVoteWait, int distribUpdateConnTimeout, int distribUpdateSoTimeout) {+ public void initZooKeeper(final CoreContainer cc, String solrHome, String zkHost, int zkClientTimeout, String hostPort, String hostContext, String host, String leaderVoteWait, boolean genericCoreNodeNames, int distribUpdateConnTimeout, int distribUpdateSoTimeout) {ZkController zkController = null;// if zkHost sys property is not set, we are not using ZooKeeper@@ -108,6 +113,7 @@ public class ZkContainer {this.hostContext = hostContext;this.host = host;this.leaderVoteWait = leaderVoteWait;+ this.genericCoreNodeNames = genericCoreNodeNames;this.distribUpdateConnTimeout = distribUpdateConnTimeout;this.distribUpdateSoTimeout = distribUpdateSoTimeout;@@ -163,7 +169,7 @@ public class ZkContainer {}zkController = new ZkController(cc, zookeeperHost, zkClientTimeout,zkClientConnectTimeout, host, hostPort, hostContext,- leaderVoteWait, distribUpdateConnTimeout, distribUpdateSoTimeout,+ leaderVoteWait, genericCoreNodeNames, distribUpdateConnTimeout, distribUpdateSoTimeout,new CurrentCoreDescriptorProvider() {@Overridediff --git a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.javaindex ef36bcf18fb..206fc091c40 100644--- a/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java+++ b/solr/core/src/java/org/apache/solr/handler/component/HttpShardHandler.java@@ -362,20 +362,18 @@ public class HttpShardHandler extends ShardHandler {Map<String, Replica> sliceShards = slice.getReplicasMap();// For now, recreate the | delimited list of equivalent servers- Set<String> liveNodes = clusterState.getLiveNodes();StringBuilder sliceShardsStr = new StringBuilder();boolean first = true;- for (ZkNodeProps nodeProps : sliceShards.values()) {- ZkCoreNodeProps coreNodeProps = new ZkCoreNodeProps(nodeProps);- if (!liveNodes.contains(coreNodeProps.getNodeName())- || !coreNodeProps.getState().equals(+ for (Replica replica : sliceShards.values()) {+ if (!clusterState.liveNodesContain(replica.getNodeName())+ || !replica.getStr(ZkStateReader.STATE_PROP).equals(ZkStateReader.ACTIVE)) continue;if (first) {first = false;} else {sliceShardsStr.append('|');}- String url = coreNodeProps.getCoreUrl();+ String url = ZkCoreNodeProps.getCoreUrl(replica);if (url.startsWith("http://"))url = url.substring(7);sliceShardsStr.append(url);diff --git a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.javaindex fde4e385538..24e4290b3b2 100644--- a/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java+++ b/solr/core/src/java/org/apache/solr/search/SolrIndexSearcher.java@@ -193,7 +193,13 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrInthis.name = "Searcher@" + Integer.toHexString(hashCode()) + (name!=null ? " "+name : "");log.info("Opening " + this.name);- Directory dir = this.reader.directory();+ if (directoryFactory.searchersReserveCommitPoints()) {+ // reserve commit point for life of searcher+ core.getDeletionPolicy().saveCommitPoint(+ reader.getIndexCommit().getGeneration());+ }++ Directory dir = getIndexReader().directory();this.reserveDirectory = reserveDirectory;this.createdDirectory = r == null;@@ -331,12 +337,18 @@ public class SolrIndexSearcher extends IndexSearcher implements Closeable,SolrIn// super.close();// can't use super.close() since it just calls reader.close() and that may only be called once// per reader (even if incRef() was previously called).++ long cpg = reader.getIndexCommit().getGeneration();try {if (closeReader) reader.decRef();} catch (Throwable t) {SolrException.log(log, "Problem dec ref'ing reader", t);}+ if (directoryFactory.searchersReserveCommitPoints()) {+ core.getDeletionPolicy().releaseCommitPoint(cpg);+ }+for (SolrCache cache : cacheList) {cache.close();}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockCache.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCache.javanew file mode 100644index 00000000000..a6cdf64923a--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCache.java@@ -0,0 +1,199 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.nio.ByteBuffer;+import java.util.concurrent.ConcurrentMap;+import java.util.concurrent.atomic.AtomicInteger;++import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;+import com.googlecode.concurrentlinkedhashmap.EvictionListener;++public class BlockCache {++ public static final int _128M = 134217728;+ public static final int _32K = 32768;+ private final ConcurrentMap<BlockCacheKey,BlockCacheLocation> cache;+ private final ByteBuffer[] banks;+ private final BlockLocks[] locks;+ private final AtomicInteger[] lockCounters;+ private final int blockSize;+ private final int numberOfBlocksPerBank;+ private final int maxEntries;+ private final Metrics metrics;++ public BlockCache(Metrics metrics, boolean directAllocation, long totalMemory) {+ this(metrics, directAllocation, totalMemory, _128M);+ }++ public BlockCache(Metrics metrics, boolean directAllocation,+ long totalMemory, int slabSize) {+ this(metrics, directAllocation, totalMemory, slabSize, _32K);+ }++ public BlockCache(Metrics metrics, boolean directAllocation,+ long totalMemory, int slabSize, int blockSize) {+ this.metrics = metrics;+ numberOfBlocksPerBank = slabSize / blockSize;+ int numberOfBanks = (int) (totalMemory / slabSize);++ banks = new ByteBuffer[numberOfBanks];+ locks = new BlockLocks[numberOfBanks];+ lockCounters = new AtomicInteger[numberOfBanks];+ maxEntries = (numberOfBlocksPerBank * numberOfBanks) - 1;+ for (int i = 0; i < numberOfBanks; i++) {+ if (directAllocation) {+ banks[i] = ByteBuffer.allocateDirect(numberOfBlocksPerBank * blockSize);+ } else {+ banks[i] = ByteBuffer.allocate(numberOfBlocksPerBank * blockSize);+ }+ locks[i] = new BlockLocks(numberOfBlocksPerBank);+ lockCounters[i] = new AtomicInteger();+ }++ EvictionListener<BlockCacheKey,BlockCacheLocation> listener = new EvictionListener<BlockCacheKey,BlockCacheLocation>() {+ @Override+ public void onEviction(BlockCacheKey key, BlockCacheLocation location) {+ releaseLocation(location);+ }+ };+ cache = new ConcurrentLinkedHashMap.Builder<BlockCacheKey,BlockCacheLocation>()+ .maximumWeightedCapacity(maxEntries).listener(listener).build();+ this.blockSize = blockSize;+ }++ private void releaseLocation(BlockCacheLocation location) {+ if (location == null) {+ return;+ }+ int bankId = location.getBankId();+ int block = location.getBlock();+ location.setRemoved(true);+ locks[bankId].clear(block);+ lockCounters[bankId].decrementAndGet();+ metrics.blockCacheEviction.incrementAndGet();+ metrics.blockCacheSize.decrementAndGet();+ }++ public boolean store(BlockCacheKey blockCacheKey, int blockOffset,+ byte[] data, int offset, int length) {+ if (length + blockOffset > blockSize) {+ throw new RuntimeException("Buffer size exceeded, expecting max ["+ + blockSize + "] got length [" + length + "] with blockOffset ["+ + blockOffset + "]");+ }+ BlockCacheLocation location = cache.get(blockCacheKey);+ boolean newLocation = false;+ if (location == null) {+ newLocation = true;+ location = new BlockCacheLocation();+ if (!findEmptyLocation(location)) {+ return false;+ }+ }+ if (location.isRemoved()) {+ return false;+ }+ int bankId = location.getBankId();+ int bankOffset = location.getBlock() * blockSize;+ ByteBuffer bank = getBank(bankId);+ bank.position(bankOffset + blockOffset);+ bank.put(data, offset, length);+ if (newLocation) {+ releaseLocation(cache.put(blockCacheKey.clone(), location));+ metrics.blockCacheSize.incrementAndGet();+ }+ return true;+ }++ public boolean fetch(BlockCacheKey blockCacheKey, byte[] buffer,+ int blockOffset, int off, int length) {+ BlockCacheLocation location = cache.get(blockCacheKey);+ if (location == null) {+ return false;+ }+ if (location.isRemoved()) {+ return false;+ }+ int bankId = location.getBankId();+ int offset = location.getBlock() * blockSize;+ location.touch();+ ByteBuffer bank = getBank(bankId);+ bank.position(offset + blockOffset);+ bank.get(buffer, off, length);+ return true;+ }++ public boolean fetch(BlockCacheKey blockCacheKey, byte[] buffer) {+ checkLength(buffer);+ return fetch(blockCacheKey, buffer, 0, 0, blockSize);+ }++ private boolean findEmptyLocation(BlockCacheLocation location) {+ // This is a tight loop that will try and find a location to+ // place the block before giving up+ for (int j = 0; j < 10; j++) {+ OUTER: for (int bankId = 0; bankId < banks.length; bankId++) {+ AtomicInteger bitSetCounter = lockCounters[bankId];+ BlockLocks bitSet = locks[bankId];+ if (bitSetCounter.get() == numberOfBlocksPerBank) {+ // if bitset is full+ continue OUTER;+ }+ // this check needs to spin, if a lock was attempted but not obtained+ // the rest of the bank should not be skipped+ int bit = bitSet.nextClearBit(0);+ INNER: while (bit != -1) {+ if (bit >= numberOfBlocksPerBank) {+ // bit set is full+ continue OUTER;+ }+ if (!bitSet.set(bit)) {+ // lock was not obtained+ // this restarts at 0 because another block could have been unlocked+ // while this was executing+ bit = bitSet.nextClearBit(0);+ continue INNER;+ } else {+ // lock obtained+ location.setBankId(bankId);+ location.setBlock(bit);+ bitSetCounter.incrementAndGet();+ return true;+ }+ }+ }+ }+ return false;+ }++ private void checkLength(byte[] buffer) {+ if (buffer.length != blockSize) {+ throw new RuntimeException("Buffer wrong size, expecting [" + blockSize+ + "] got [" + buffer.length + "]");+ }+ }++ private ByteBuffer getBank(int bankId) {+ return banks[bankId].duplicate();+ }++ public int getSize() {+ return cache.size();+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheKey.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheKey.javanew file mode 100644index 00000000000..d0daefe0658--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheKey.java@@ -0,0 +1,69 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class BlockCacheKey implements Cloneable {++ private long block;+ private int file;++ public long getBlock() {+ return block;+ }++ public int getFile() {+ return file;+ }++ public void setBlock(long block) {+ this.block = block;+ }++ public void setFile(int file) {+ this.file = file;+ }++ @Override+ public int hashCode() {+ final int prime = 31;+ int result = 1;+ result = prime * result + (int) (block ^ (block >>> 32));+ result = prime * result + file;+ return result;+ }++ @Override+ public boolean equals(Object obj) {+ if (this == obj) return true;+ if (obj == null) return false;+ if (getClass() != obj.getClass()) return false;+ BlockCacheKey other = (BlockCacheKey) obj;+ if (block != other.block) return false;+ if (file != other.file) return false;+ return true;+ }++ @Override+ public BlockCacheKey clone() {+ try {+ return (BlockCacheKey) super.clone();+ } catch (CloneNotSupportedException e) {+ throw new RuntimeException(e);+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheLocation.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheLocation.javanew file mode 100644index 00000000000..968628f058a--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockCacheLocation.java@@ -0,0 +1,67 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.concurrent.atomic.AtomicBoolean;++public class BlockCacheLocation {++ private int block;+ private int bankId;+ private long lastAccess = System.currentTimeMillis();+ private long accesses;+ private AtomicBoolean removed = new AtomicBoolean(false);++ public void setBlock(int block) {+ this.block = block;+ }++ public void setBankId(int bankId) {+ this.bankId = bankId;+ }++ public int getBlock() {+ return block;+ }++ public int getBankId() {+ return bankId;+ }++ public void touch() {+ lastAccess = System.currentTimeMillis();+ accesses++;+ }++ public long getLastAccess() {+ return lastAccess;+ }++ public long getNumberOfAccesses() {+ return accesses;+ }++ public boolean isRemoved() {+ return removed.get();+ }++ public void setRemoved(boolean removed) {+ this.removed.set(removed);+ }++}\ No newline at end of filediff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectory.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectory.javanew file mode 100644index 00000000000..d199002505a--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectory.java@@ -0,0 +1,385 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.FileNotFoundException;+import java.io.IOException;+import java.util.Collection;+import java.util.Set;++import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.Lock;+import org.apache.lucene.store.LockFactory;+import org.apache.solr.store.hdfs.HdfsDirectory;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class BlockDirectory extends Directory {+ public static Logger LOG = LoggerFactory.getLogger(BlockDirectory.class);++ public static final long BLOCK_SHIFT = 13; // 2^13 = 8,192 bytes per block+ public static final long BLOCK_MOD = 0x1FFF;+ public static final int BLOCK_SIZE = 1 << BLOCK_SHIFT;++ public static long getBlock(long pos) {+ return pos >>> BLOCK_SHIFT;+ }++ public static long getPosition(long pos) {+ return pos & BLOCK_MOD;+ }++ public static long getRealPosition(long block, long positionInBlock) {+ return (block << BLOCK_SHIFT) + positionInBlock;+ }++ public static Cache NO_CACHE = new Cache() {++ @Override+ public void update(String name, long blockId, int blockOffset,+ byte[] buffer, int offset, int length) {}++ @Override+ public boolean fetch(String name, long blockId, int blockOffset, byte[] b,+ int off, int lengthToReadInBlock) {+ return false;+ }++ @Override+ public void delete(String name) {++ }++ @Override+ public long size() {+ return 0;+ }++ @Override+ public void renameCacheFile(String source, String dest) {}+ };++ private Directory directory;+ private int blockSize;+ private String dirName;+ private Cache cache;+ private Set<String> blockCacheFileTypes;+ private final boolean blockCacheReadEnabled;+ private final boolean blockCacheWriteEnabled;++ public BlockDirectory(String dirName, Directory directory, Cache cache,+ Set<String> blockCacheFileTypes, boolean blockCacheReadEnabled,+ boolean blockCacheWriteEnabled) throws IOException {+ this.dirName = dirName;+ this.directory = directory;+ blockSize = BLOCK_SIZE;+ this.cache = cache;+ if (blockCacheFileTypes == null || blockCacheFileTypes.isEmpty()) {+ this.blockCacheFileTypes = null;+ } else {+ this.blockCacheFileTypes = blockCacheFileTypes;+ }+ this.blockCacheReadEnabled = blockCacheReadEnabled;+ if (!blockCacheReadEnabled) {+ LOG.info("Block cache on read is disabled");+ }+ this.blockCacheWriteEnabled = blockCacheWriteEnabled;+ if (!blockCacheWriteEnabled) {+ LOG.info("Block cache on write is disabled");+ }+ if (directory.getLockFactory() != null) {+ setLockFactory(directory.getLockFactory());+ }+ }++ private IndexInput openInput(String name, int bufferSize, IOContext context)+ throws IOException {+ final IndexInput source = directory.openInput(name, context);+ if (useReadCache(name, context)) {+ return new CachedIndexInput(source, blockSize, name,+ getFileCacheName(name), cache, bufferSize);+ }+ return source;+ }++ private boolean isCachableFile(String name) {+ for (String ext : blockCacheFileTypes) {+ if (name.endsWith(ext)) {+ return true;+ }+ }+ return false;+ }++ @Override+ public IndexInput openInput(final String name, IOContext context)+ throws IOException {+ return openInput(name, blockSize, context);+ }++ static class CachedIndexInput extends CustomBufferedIndexInput {++ private IndexInput _source;+ private int _blockSize;+ private long _fileLength;+ private String _cacheName;+ private Cache _cache;++ public CachedIndexInput(IndexInput source, int blockSize, String name,+ String cacheName, Cache cache, int bufferSize) {+ super(name, bufferSize);+ _source = source;+ _blockSize = blockSize;+ _fileLength = source.length();+ _cacheName = cacheName;+ _cache = cache;+ }++ @Override+ public IndexInput clone() {+ CachedIndexInput clone = (CachedIndexInput) super.clone();+ clone._source = (IndexInput) _source.clone();+ return clone;+ }++ @Override+ public long length() {+ return _source.length();+ }++ @Override+ protected void seekInternal(long pos) throws IOException {}++ @Override+ protected void readInternal(byte[] b, int off, int len) throws IOException {+ long position = getFilePointer();+ while (len > 0) {+ int length = fetchBlock(position, b, off, len);+ position += length;+ len -= length;+ off += length;+ }+ }++ private int fetchBlock(long position, byte[] b, int off, int len)+ throws IOException {+ // read whole block into cache and then provide needed data+ long blockId = getBlock(position);+ int blockOffset = (int) getPosition(position);+ int lengthToReadInBlock = Math.min(len, _blockSize - blockOffset);+ if (checkCache(blockId, blockOffset, b, off, lengthToReadInBlock)) {+ return lengthToReadInBlock;+ } else {+ readIntoCacheAndResult(blockId, blockOffset, b, off,+ lengthToReadInBlock);+ }+ return lengthToReadInBlock;+ }++ private void readIntoCacheAndResult(long blockId, int blockOffset,+ byte[] b, int off, int lengthToReadInBlock) throws IOException {+ long position = getRealPosition(blockId, 0);+ int length = (int) Math.min(_blockSize, _fileLength - position);+ _source.seek(position);++ byte[] buf = BufferStore.takeBuffer(_blockSize);+ _source.readBytes(buf, 0, length);+ System.arraycopy(buf, blockOffset, b, off, lengthToReadInBlock);+ _cache.update(_cacheName, blockId, 0, buf, 0, _blockSize);+ BufferStore.putBuffer(buf);+ }++ private boolean checkCache(long blockId, int blockOffset, byte[] b,+ int off, int lengthToReadInBlock) {+ return _cache.fetch(_cacheName, blockId, blockOffset, b, off,+ lengthToReadInBlock);+ }++ @Override+ protected void closeInternal() throws IOException {+ _source.close();+ }+ }++ @Override+ public void close() throws IOException {+ try {+ String[] files = listAll();++ for (String file : files) {+ cache.delete(getFileCacheName(file));+ }++ } catch (FileNotFoundException e) {+ // the local file system folder may be gone+ } finally {+ directory.close();+ }+ }++ String getFileCacheName(String name) throws IOException {+ return getFileCacheLocation(name) + ":" + getFileModified(name);+ }++ private long getFileModified(String name) throws IOException {+ if (directory instanceof FSDirectory) {+ File directory = ((FSDirectory) this.directory).getDirectory();+ File file = new File(directory, name);+ if (!file.exists()) {+ throw new FileNotFoundException("File [" + name + "] not found");+ }+ return file.lastModified();+ } else if (directory instanceof HdfsDirectory) {+ return ((HdfsDirectory) directory).fileModified(name);+ } else {+ throw new RuntimeException("Not supported");+ }+ }++ public void clearLock(String name) throws IOException {+ directory.clearLock(name);+ }++ String getFileCacheLocation(String name) {+ return dirName + "/" + name;+ }++ @Override+ public void copy(Directory to, String src, String dest, IOContext context)+ throws IOException {+ directory.copy(to, src, dest, context);+ }++ public LockFactory getLockFactory() {+ return directory.getLockFactory();+ }++ public String getLockID() {+ return directory.getLockID();+ }++ public Lock makeLock(String name) {+ return directory.makeLock(name);+ }++ public void setLockFactory(LockFactory lockFactory) throws IOException {+ directory.setLockFactory(lockFactory);+ }++ @Override+ public void sync(Collection<String> names) throws IOException {+ directory.sync(names);+ }++ // @SuppressWarnings("deprecation")+ // public void sync(String name) throws IOException {+ // _directory.sync(name);+ // }++ public String toString() {+ return directory.toString();+ }++ /**+ * Determine whether read caching should be used for a particular+ * file/context.+ */+ boolean useReadCache(String name, IOContext context) {+ if (!blockCacheReadEnabled) {+ return false;+ }+ if (blockCacheFileTypes != null && !isCachableFile(name)) {+ return false;+ }+ switch (context.context) {+ default: {+ return true;+ }+ }+ }++ /**+ * Determine whether write caching should be used for a particular+ * file/context.+ */+ boolean useWriteCache(String name, IOContext context) {+ if (!blockCacheWriteEnabled) {+ return false;+ }+ if (blockCacheFileTypes != null && !isCachableFile(name)) {+ return false;+ }+ switch (context.context) {+ case MERGE: {+ // we currently don't cache any merge context writes+ return false;+ }+ default: {+ return true;+ }+ }+ }++ @Override+ public IndexOutput createOutput(String name, IOContext context)+ throws IOException {+ IndexOutput dest = directory.createOutput(name, context);+ if (useWriteCache(name, context)) {+ return new CachedIndexOutput(this, dest, blockSize, name, cache,+ blockSize);+ }+ return dest;+ }++ public void deleteFile(String name) throws IOException {+ cache.delete(getFileCacheName(name));+ directory.deleteFile(name);+ }++ public boolean fileExists(String name) throws IOException {+ return directory.fileExists(name);+ }++ public long fileLength(String name) throws IOException {+ return directory.fileLength(name);+ }++ // @SuppressWarnings("deprecation")+ // public long fileModified(String name) throws IOException {+ // return _directory.fileModified(name);+ // }++ public String[] listAll() throws IOException {+ return directory.listAll();+ }++ // @SuppressWarnings("deprecation")+ // public void touchFile(String name) throws IOException {+ // _directory.touchFile(name);+ // }++ public Directory getDirectory() {+ return directory;+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectoryCache.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectoryCache.javanew file mode 100644index 00000000000..41ca9bb4775--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockDirectoryCache.java@@ -0,0 +1,87 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.Map;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicInteger;++public class BlockDirectoryCache implements Cache {+ private BlockCache blockCache;+ private AtomicInteger counter = new AtomicInteger();+ private Map<String,Integer> names = new ConcurrentHashMap<String,Integer>();+ private Metrics metrics;++ public BlockDirectoryCache(BlockCache blockCache, Metrics metrics) {+ this.blockCache = blockCache;+ this.metrics = metrics;+ }++ @Override+ public void delete(String name) {+ names.remove(name);+ }++ @Override+ public void update(String name, long blockId, int blockOffset, byte[] buffer,+ int offset, int length) {+ Integer file = names.get(name);+ if (file == null) {+ file = counter.incrementAndGet();+ names.put(name, file);+ }+ BlockCacheKey blockCacheKey = new BlockCacheKey();+ blockCacheKey.setBlock(blockId);+ blockCacheKey.setFile(file);+ blockCache.store(blockCacheKey, blockOffset, buffer, offset, length);+ }++ @Override+ public boolean fetch(String name, long blockId, int blockOffset, byte[] b,+ int off, int lengthToReadInBlock) {+ Integer file = names.get(name);+ if (file == null) {+ return false;+ }+ BlockCacheKey blockCacheKey = new BlockCacheKey();+ blockCacheKey.setBlock(blockId);+ blockCacheKey.setFile(file);+ boolean fetch = blockCache.fetch(blockCacheKey, b, blockOffset, off,+ lengthToReadInBlock);+ if (fetch) {+ metrics.blockCacheHit.incrementAndGet();+ } else {+ metrics.blockCacheMiss.incrementAndGet();+ }+ return fetch;+ }++ @Override+ public long size() {+ return blockCache.getSize();+ }++ @Override+ public void renameCacheFile(String source, String dest) {+ Integer file = names.remove(source);+ // possible if the file is empty+ if (file != null) {+ names.put(dest, file);+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BlockLocks.java b/solr/core/src/java/org/apache/solr/store/blockcache/BlockLocks.javanew file mode 100644index 00000000000..f29ac61b1af--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BlockLocks.java@@ -0,0 +1,96 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.concurrent.atomic.AtomicLongArray;++import org.apache.lucene.util.OpenBitSet;++public class BlockLocks {++ private AtomicLongArray bits;+ private int wlen;++ public BlockLocks(long numBits) {+ int length = OpenBitSet.bits2words(numBits);+ bits = new AtomicLongArray(length);+ wlen = length;+ }++ /**+ * Find the next clear bit in the bit set.+ *+ * @param index+ * index+ * @return next next bit+ */+ public int nextClearBit(int index) {+ int i = index >> 6;+ if (i >= wlen) return -1;+ int subIndex = index & 0x3f; // index within the word+ long word = ~bits.get(i) >> subIndex; // skip all the bits to the right of+ // index+ if (word != 0) {+ return (i << 6) + subIndex + Long.numberOfTrailingZeros(word);+ }+ while (++i < wlen) {+ word = ~bits.get(i);+ if (word != 0) {+ return (i << 6) + Long.numberOfTrailingZeros(word);+ }+ }+ return -1;+ }++ /**+ * Thread safe set operation that will set the bit if and only if the bit was+ * not previously set.+ *+ * @param index+ * the index position to set.+ * @return returns true if the bit was set and false if it was already set.+ */+ public boolean set(int index) {+ int wordNum = index >> 6; // div 64+ int bit = index & 0x3f; // mod 64+ long bitmask = 1L << bit;+ long word, oword;+ do {+ word = bits.get(wordNum);+ // if set another thread stole the lock+ if ((word & bitmask) != 0) {+ return false;+ }+ oword = word;+ word |= bitmask;+ } while (!bits.compareAndSet(wordNum, oword, word));+ return true;+ }++ public void clear(int index) {+ int wordNum = index >> 6;+ int bit = index & 0x03f;+ long bitmask = 1L << bit;+ long word, oword;+ do {+ word = bits.get(wordNum);+ oword = word;+ word &= ~bitmask;+ } while (!bits.compareAndSet(wordNum, oword, word));+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/BufferStore.java b/solr/core/src/java/org/apache/solr/store/blockcache/BufferStore.javanew file mode 100644index 00000000000..70ced2e3664--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/BufferStore.java@@ -0,0 +1,110 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.concurrent.ArrayBlockingQueue;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.atomic.AtomicLong;++import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class BufferStore {++ public static Logger LOG = LoggerFactory.getLogger(BufferStore.class);++ private static BlockingQueue<byte[]> _1024 = setupBuffers(1024, 1);+ private static BlockingQueue<byte[]> _8192 = setupBuffers(8192, 1);+ public static AtomicLong shardBuffercacheLost = new AtomicLong();+ public static AtomicLong shardBuffercacheAllocate1024 = new AtomicLong();+ public static AtomicLong shardBuffercacheAllocate8192 = new AtomicLong();+ public static AtomicLong shardBuffercacheAllocateOther = new AtomicLong();++ public static void init(int _1024Size, int _8192Size, Metrics metrics) {++ LOG.info("Initializing the 1024 buffers with [{}] buffers.", _1024Size);+ _1024 = setupBuffers(1024, _1024Size);+ LOG.info("Initializing the 8192 buffers with [{}] buffers.", _8192Size);+ _8192 = setupBuffers(8192, _8192Size);+ shardBuffercacheLost = metrics.shardBuffercacheLost;+ shardBuffercacheAllocate1024 = metrics.shardBuffercacheAllocate1024;+ shardBuffercacheAllocate8192 = metrics.shardBuffercacheAllocate8192;+ shardBuffercacheAllocateOther = metrics.shardBuffercacheAllocateOther;+ }++ private static BlockingQueue<byte[]> setupBuffers(int bufferSize, int count) {+ BlockingQueue<byte[]> queue = new ArrayBlockingQueue<byte[]>(count);+ for (int i = 0; i < count; i++) {+ queue.add(new byte[bufferSize]);+ }+ return queue;+ }++ public static byte[] takeBuffer(int bufferSize) {+ switch (bufferSize) {+ case 1024:+ return newBuffer1024(_1024.poll());+ case 8192:+ return newBuffer8192(_8192.poll());+ default:+ return newBuffer(bufferSize);+ }+ }++ public static void putBuffer(byte[] buffer) {+ if (buffer == null) {+ return;+ }+ int bufferSize = buffer.length;+ switch (bufferSize) {+ case 1024:+ checkReturn(_1024.offer(buffer));+ return;+ case 8192:+ checkReturn(_8192.offer(buffer));+ return;+ }+ }++ private static void checkReturn(boolean offer) {+ if (!offer) {+ shardBuffercacheLost.incrementAndGet();+ }+ }++ private static byte[] newBuffer1024(byte[] buf) {+ if (buf != null) {+ return buf;+ }+ shardBuffercacheAllocate1024.incrementAndGet();+ return new byte[1024];+ }++ private static byte[] newBuffer8192(byte[] buf) {+ if (buf != null) {+ return buf;+ }+ shardBuffercacheAllocate8192.incrementAndGet();+ return new byte[8192];+ }++ private static byte[] newBuffer(int size) {+ shardBuffercacheAllocateOther.incrementAndGet();+ return new byte[size];+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/Cache.java b/solr/core/src/java/org/apache/solr/store/blockcache/Cache.javanew file mode 100644index 00000000000..7e70ad0a775--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/Cache.java@@ -0,0 +1,62 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public interface Cache {++ /**+ * Remove a file from the cache.+ *+ * @param name+ * cache file name+ */+ void delete(String name);++ /**+ * Update the content of the specified cache file. Creates cache entry if+ * necessary.+ *+ */+ void update(String name, long blockId, int blockOffset, byte[] buffer,+ int offset, int length);++ /**+ * Fetch the specified cache file content.+ *+ * @return true if cached content found, otherwise return false+ */+ boolean fetch(String name, long blockId, int blockOffset, byte[] b, int off,+ int lengthToReadInBlock);++ /**+ * Number of entries in the cache.+ */+ long size();++ /**+ * Expert: Rename the specified file in the cache. Allows a file to be moved+ * without invalidating the cache.+ *+ * @param source+ * original name+ * @param dest+ * final name+ */+ void renameCacheFile(String source, String dest);++}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/CachedIndexOutput.java b/solr/core/src/java/org/apache/solr/store/blockcache/CachedIndexOutput.javanew file mode 100644index 00000000000..6e3c92ee1ac--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/CachedIndexOutput.java@@ -0,0 +1,91 @@+package org.apache.solr.store.blockcache;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.store.IndexOutput;++/*+ * Cache the blocks as they are written. The cache file name is the name of+ * the file until the file is closed, at which point the cache is updated+ * to include the last modified date (which is unknown until that point).+ */+public class CachedIndexOutput extends ReusedBufferedIndexOutput {+ private final BlockDirectory directory;+ private final IndexOutput dest;+ private final int blockSize;+ private final String name;+ private final String location;+ private final Cache cache;++ public CachedIndexOutput(BlockDirectory directory, IndexOutput dest,+ int blockSize, String name, Cache cache, int bufferSize) {+ super(bufferSize);+ this.directory = directory;+ this.dest = dest;+ this.blockSize = blockSize;+ this.name = name;+ this.location = directory.getFileCacheLocation(name);+ this.cache = cache;+ }++ @Override+ public void flushInternal() throws IOException {+ dest.flush();+ }++ @Override+ public void closeInternal() throws IOException {+ dest.close();+ cache.renameCacheFile(location, directory.getFileCacheName(name));+ }++ @Override+ public void seekInternal(long pos) throws IOException {+ throw new IOException("Seek not supported");+ }++ private int writeBlock(long position, byte[] b, int offset, int length)+ throws IOException {+ // read whole block into cache and then provide needed data+ long blockId = BlockDirectory.getBlock(position);+ int blockOffset = (int) BlockDirectory.getPosition(position);+ int lengthToWriteInBlock = Math.min(length, blockSize - blockOffset);++ // write the file and copy into the cache+ dest.writeBytes(b, offset, lengthToWriteInBlock);+ cache.update(location, blockId, blockOffset, b, offset,+ lengthToWriteInBlock);++ return lengthToWriteInBlock;+ }++ @Override+ public void writeInternal(byte[] b, int offset, int length)+ throws IOException {+ long position = getBufferStart();+ while (length > 0) {+ int len = writeBlock(position, b, offset, length);+ position += len;+ length -= len;+ offset += len;+ }+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/CustomBufferedIndexInput.java b/solr/core/src/java/org/apache/solr/store/blockcache/CustomBufferedIndexInput.javanew file mode 100644index 00000000000..d8ce7399efd--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/CustomBufferedIndexInput.java@@ -0,0 +1,272 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.EOFException;+import java.io.IOException;++import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;++public abstract class CustomBufferedIndexInput extends IndexInput {++ public static final int BUFFER_SIZE = 1024;++ private int bufferSize = BUFFER_SIZE;++ protected byte[] buffer;++ private long bufferStart = 0; // position in file of buffer+ private int bufferLength = 0; // end of valid bytes+ private int bufferPosition = 0; // next byte to read++ @Override+ public byte readByte() throws IOException {+ if (bufferPosition >= bufferLength) refill();+ return buffer[bufferPosition++];+ }++ public CustomBufferedIndexInput(String resourceDesc) {+ this(resourceDesc, BUFFER_SIZE);+ }++ public CustomBufferedIndexInput(String resourceDesc, int bufferSize) {+ super(resourceDesc);+ checkBufferSize(bufferSize);+ this.bufferSize = bufferSize;+ }++ private void checkBufferSize(int bufferSize) {+ if (bufferSize <= 0) throw new IllegalArgumentException(+ "bufferSize must be greater than 0 (got " + bufferSize + ")");+ }++ @Override+ public void readBytes(byte[] b, int offset, int len) throws IOException {+ readBytes(b, offset, len, true);+ }++ @Override+ public void readBytes(byte[] b, int offset, int len, boolean useBuffer)+ throws IOException {++ if (len <= (bufferLength - bufferPosition)) {+ // the buffer contains enough data to satisfy this request+ if (len > 0) // to allow b to be null if len is 0...+ System.arraycopy(buffer, bufferPosition, b, offset, len);+ bufferPosition += len;+ } else {+ // the buffer does not have enough data. First serve all we've got.+ int available = bufferLength - bufferPosition;+ if (available > 0) {+ System.arraycopy(buffer, bufferPosition, b, offset, available);+ offset += available;+ len -= available;+ bufferPosition += available;+ }+ // and now, read the remaining 'len' bytes:+ if (useBuffer && len < bufferSize) {+ // If the amount left to read is small enough, and+ // we are allowed to use our buffer, do it in the usual+ // buffered way: fill the buffer and copy from it:+ refill();+ if (bufferLength < len) {+ // Throw an exception when refill() could not read len bytes:+ System.arraycopy(buffer, 0, b, offset, bufferLength);+ throw new IOException("read past EOF");+ } else {+ System.arraycopy(buffer, 0, b, offset, len);+ bufferPosition = len;+ }+ } else {+ // The amount left to read is larger than the buffer+ // or we've been asked to not use our buffer -+ // there's no performance reason not to read it all+ // at once. Note that unlike the previous code of+ // this function, there is no need to do a seek+ // here, because there's no need to reread what we+ // had in the buffer.+ long after = bufferStart + bufferPosition + len;+ if (after > length()) throw new IOException("read past EOF");+ readInternal(b, offset, len);+ bufferStart = after;+ bufferPosition = 0;+ bufferLength = 0; // trigger refill() on read+ }+ }+ }++ @Override+ public int readInt() throws IOException {+ if (4 <= (bufferLength - bufferPosition)) {+ return ((buffer[bufferPosition++] & 0xFF) << 24)+ | ((buffer[bufferPosition++] & 0xFF) << 16)+ | ((buffer[bufferPosition++] & 0xFF) << 8)+ | (buffer[bufferPosition++] & 0xFF);+ } else {+ return super.readInt();+ }+ }++ @Override+ public long readLong() throws IOException {+ if (8 <= (bufferLength - bufferPosition)) {+ final int i1 = ((buffer[bufferPosition++] & 0xff) << 24)+ | ((buffer[bufferPosition++] & 0xff) << 16)+ | ((buffer[bufferPosition++] & 0xff) << 8)+ | (buffer[bufferPosition++] & 0xff);+ final int i2 = ((buffer[bufferPosition++] & 0xff) << 24)+ | ((buffer[bufferPosition++] & 0xff) << 16)+ | ((buffer[bufferPosition++] & 0xff) << 8)+ | (buffer[bufferPosition++] & 0xff);+ return (((long) i1) << 32) | (i2 & 0xFFFFFFFFL);+ } else {+ return super.readLong();+ }+ }++ @Override+ public int readVInt() throws IOException {+ if (5 <= (bufferLength - bufferPosition)) {+ byte b = buffer[bufferPosition++];+ int i = b & 0x7F;+ for (int shift = 7; (b & 0x80) != 0; shift += 7) {+ b = buffer[bufferPosition++];+ i |= (b & 0x7F) << shift;+ }+ return i;+ } else {+ return super.readVInt();+ }+ }++ @Override+ public long readVLong() throws IOException {+ if (9 <= bufferLength - bufferPosition) {+ byte b = buffer[bufferPosition++];+ long i = b & 0x7F;+ for (int shift = 7; (b & 0x80) != 0; shift += 7) {+ b = buffer[bufferPosition++];+ i |= (b & 0x7FL) << shift;+ }+ return i;+ } else {+ return super.readVLong();+ }+ }++ private void refill() throws IOException {+ long start = bufferStart + bufferPosition;+ long end = start + bufferSize;+ if (end > length()) // don't read past EOF+ end = length();+ int newLength = (int) (end - start);+ if (newLength <= 0) throw new EOFException("read past EOF");++ if (buffer == null) {+ buffer = BufferStore.takeBuffer(bufferSize);+ seekInternal(bufferStart);+ }+ readInternal(buffer, 0, newLength);+ bufferLength = newLength;+ bufferStart = start;+ bufferPosition = 0;+ }++ @Override+ public final void close() throws IOException {+ closeInternal();+ BufferStore.putBuffer(buffer);+ buffer = null;+ }++ protected abstract void closeInternal() throws IOException;++ /**+ * Expert: implements buffer refill. Reads bytes from the current position in+ * the input.+ *+ * @param b+ * the array to read bytes into+ * @param offset+ * the offset in the array to start storing bytes+ * @param length+ * the number of bytes to read+ */+ protected abstract void readInternal(byte[] b, int offset, int length)+ throws IOException;++ @Override+ public long getFilePointer() {+ return bufferStart + bufferPosition;+ }++ @Override+ public void seek(long pos) throws IOException {+ if (pos >= bufferStart && pos < (bufferStart + bufferLength)) bufferPosition = (int) (pos - bufferStart); // seek+ // within+ // buffer+ else {+ bufferStart = pos;+ bufferPosition = 0;+ bufferLength = 0; // trigger refill() on read()+ seekInternal(pos);+ }+ }++ /**+ * Expert: implements seek. Sets current position in this file, where the next+ * {@link #readInternal(byte[],int,int)} will occur.+ *+ * @see #readInternal(byte[],int,int)+ */+ protected abstract void seekInternal(long pos) throws IOException;++ @Override+ public IndexInput clone() {+ CustomBufferedIndexInput clone = (CustomBufferedIndexInput) super.clone();++ clone.buffer = null;+ clone.bufferLength = 0;+ clone.bufferPosition = 0;+ clone.bufferStart = getFilePointer();++ return clone;+ }++ /**+ * Flushes the in-memory bufer to the given output, copying at most+ * <code>numBytes</code>.+ * <p>+ * <b>NOTE:</b> this method does not refill the buffer, however it does+ * advance the buffer position.+ *+ * @return the number of bytes actually flushed from the in-memory buffer.+ */+ protected int flushBuffer(IndexOutput out, long numBytes) throws IOException {+ int toCopy = bufferLength - bufferPosition;+ if (toCopy > numBytes) {+ toCopy = (int) numBytes;+ }+ if (toCopy > 0) {+ out.writeBytes(buffer, bufferPosition, toCopy);+ bufferPosition += toCopy;+ }+ return toCopy;+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/Metrics.java b/solr/core/src/java/org/apache/solr/store/blockcache/Metrics.javanew file mode 100644index 00000000000..fce1b9d9a73--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/Metrics.java@@ -0,0 +1,126 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.Map;+import java.util.Map.Entry;+import java.util.concurrent.ConcurrentHashMap;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.metrics.MetricsContext;+import org.apache.hadoop.metrics.MetricsRecord;+import org.apache.hadoop.metrics.MetricsUtil;+import org.apache.hadoop.metrics.Updater;+import org.apache.hadoop.metrics.jvm.JvmMetrics;++public class Metrics implements Updater {++ public static class MethodCall {+ public AtomicLong invokes = new AtomicLong();+ public AtomicLong times = new AtomicLong();+ }++ public AtomicLong blockCacheHit = new AtomicLong(0);+ public AtomicLong blockCacheMiss = new AtomicLong(0);+ public AtomicLong blockCacheEviction = new AtomicLong(0);+ public AtomicLong blockCacheSize = new AtomicLong(0);+ public AtomicLong rowReads = new AtomicLong(0);+ public AtomicLong rowWrites = new AtomicLong(0);+ public AtomicLong recordReads = new AtomicLong(0);+ public AtomicLong recordWrites = new AtomicLong(0);+ public AtomicLong queriesExternal = new AtomicLong(0);+ public AtomicLong queriesInternal = new AtomicLong(0);+ public AtomicLong shardBuffercacheAllocate1024 = new AtomicLong(0);+ public AtomicLong shardBuffercacheAllocate8192 = new AtomicLong(0);+ public AtomicLong shardBuffercacheAllocateOther = new AtomicLong(0);+ public AtomicLong shardBuffercacheLost = new AtomicLong(0);+ public Map<String,MethodCall> methodCalls = new ConcurrentHashMap<String, MethodCall>();++ public AtomicLong tableCount = new AtomicLong(0);+ public AtomicLong rowCount = new AtomicLong(0);+ public AtomicLong recordCount = new AtomicLong(0);+ public AtomicLong indexCount = new AtomicLong(0);+ public AtomicLong indexMemoryUsage = new AtomicLong(0);+ public AtomicLong segmentCount = new AtomicLong(0);++ private MetricsRecord metricsRecord;+ private long previous = System.nanoTime();++ public static void main(String[] args) throws InterruptedException {+ Configuration conf = new Configuration();+ Metrics metrics = new Metrics(conf);+ MethodCall methodCall = new MethodCall();+ metrics.methodCalls.put("test",methodCall);+ for (int i = 0; i < 100; i++) {+ metrics.blockCacheHit.incrementAndGet();+ metrics.blockCacheMiss.incrementAndGet();+ methodCall.invokes.incrementAndGet();+ methodCall.times.addAndGet(56000000);+ Thread.sleep(500);+ }+ }++ public Metrics(Configuration conf) {+ JvmMetrics.init("blockcache", Long.toString(System.currentTimeMillis()));+ MetricsContext metricsContext = MetricsUtil.getContext("blockcache");+ metricsRecord = MetricsUtil.createRecord(metricsContext, "metrics");+ metricsContext.registerUpdater(this);+ }++ @Override+ public void doUpdates(MetricsContext context) {+ synchronized (this) {+ long now = System.nanoTime();+ float seconds = (now - previous) / 1000000000.0f;+ metricsRecord.setMetric("blockcache.hit", getPerSecond(blockCacheHit.getAndSet(0), seconds));+ metricsRecord.setMetric("blockcache.miss", getPerSecond(blockCacheMiss.getAndSet(0), seconds));+ metricsRecord.setMetric("blockcache.eviction", getPerSecond(blockCacheEviction.getAndSet(0), seconds));+ metricsRecord.setMetric("blockcache.size", blockCacheSize.get());+ metricsRecord.setMetric("row.reads", getPerSecond(rowReads.getAndSet(0), seconds));+ metricsRecord.setMetric("row.writes", getPerSecond(rowWrites.getAndSet(0), seconds));+ metricsRecord.setMetric("record.reads", getPerSecond(recordReads.getAndSet(0), seconds));+ metricsRecord.setMetric("record.writes", getPerSecond(recordWrites.getAndSet(0), seconds));+ metricsRecord.setMetric("query.external", getPerSecond(queriesExternal.getAndSet(0), seconds));+ metricsRecord.setMetric("query.internal", getPerSecond(queriesInternal.getAndSet(0), seconds));+ for (Entry<String,MethodCall> entry : methodCalls.entrySet()) {+ String key = entry.getKey();+ MethodCall value = entry.getValue();+ long invokes = value.invokes.getAndSet(0);+ long times = value.times.getAndSet(0);++ float avgTimes = (times / (float) invokes) / 1000000000.0f;+ metricsRecord.setMetric("methodcalls." + key + ".count", getPerSecond(invokes, seconds));+ metricsRecord.setMetric("methodcalls." + key + ".time", avgTimes);+ }+ metricsRecord.setMetric("tables", tableCount.get());+ metricsRecord.setMetric("rows", rowCount.get());+ metricsRecord.setMetric("records", recordCount.get());+ metricsRecord.setMetric("index.count", indexCount.get());+ metricsRecord.setMetric("index.memoryusage", indexMemoryUsage.get());+ metricsRecord.setMetric("index.segments", segmentCount.get());+ previous = now;+ }+ metricsRecord.update();+ }++ private float getPerSecond(long value, float seconds) {+ return (float) (value / seconds);+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/ReusedBufferedIndexOutput.java b/solr/core/src/java/org/apache/solr/store/blockcache/ReusedBufferedIndexOutput.javanew file mode 100644index 00000000000..52b68ddf3ed--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/ReusedBufferedIndexOutput.java@@ -0,0 +1,178 @@+package org.apache.solr.store.blockcache;++/**+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.store.IndexOutput;++public abstract class ReusedBufferedIndexOutput extends IndexOutput {++ public static final int BUFFER_SIZE = 1024;++ private int bufferSize = BUFFER_SIZE;++ protected byte[] buffer;++ /** position in the file of buffer */+ private long bufferStart = 0;+ /** end of valid bytes */+ private int bufferLength = 0;+ /** next byte to write */+ private int bufferPosition = 0;+ /** total length of the file */+ private long fileLength = 0;++ public ReusedBufferedIndexOutput() {+ this(BUFFER_SIZE);+ }++ public ReusedBufferedIndexOutput(int bufferSize) {+ checkBufferSize(bufferSize);+ this.bufferSize = bufferSize;+ buffer = BufferStore.takeBuffer(this.bufferSize);+ }++ protected long getBufferStart() {+ return bufferStart;+ }++ private void checkBufferSize(int bufferSize) {+ if (bufferSize <= 0) throw new IllegalArgumentException(+ "bufferSize must be greater than 0 (got " + bufferSize + ")");+ }++ /** Write the buffered bytes to cache */+ private void flushBufferToCache() throws IOException {+ writeInternal(buffer, 0, bufferLength);++ bufferStart += bufferLength;+ bufferLength = 0;+ bufferPosition = 0;+ }++ protected abstract void flushInternal() throws IOException;++ @Override+ public void flush() throws IOException {+ flushBufferToCache();+ flushInternal();+ }++ protected abstract void closeInternal() throws IOException;++ @Override+ public void close() throws IOException {+ flushBufferToCache();+ closeInternal();+ BufferStore.putBuffer(buffer);+ buffer = null;+ }++ @Override+ public long getFilePointer() {+ return bufferStart + bufferPosition;+ }++ protected abstract void seekInternal(long pos) throws IOException;++ @Override+ public long length() throws IOException {+ return fileLength;+ }++ @Override+ public void writeByte(byte b) throws IOException {+ if (bufferPosition >= bufferSize) {+ flushBufferToCache();+ }+ if (getFilePointer() >= fileLength) {+ fileLength++;+ }+ buffer[bufferPosition++] = b;+ if (bufferPosition > bufferLength) {+ bufferLength = bufferPosition;+ }+ }++ /**+ * Expert: implements buffer flushing to cache. Writes bytes to the current+ * position in the output.+ *+ * @param b+ * the array of bytes to write+ * @param offset+ * the offset in the array of bytes to write+ * @param length+ * the number of bytes to write+ */+ protected abstract void writeInternal(byte[] b, int offset, int length)+ throws IOException;++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ if (getFilePointer() + length > fileLength) {+ fileLength = getFilePointer() + length;+ }+ if (length <= bufferSize - bufferPosition) {+ // the buffer contains enough space to satisfy this request+ if (length > 0) { // to allow b to be null if len is 0...+ System.arraycopy(b, offset, buffer, bufferPosition, length);+ }+ bufferPosition += length;+ if (bufferPosition > bufferLength) {+ bufferLength = bufferPosition;+ }+ } else {+ // the buffer does not have enough space. First buffer all we've got.+ int available = bufferSize - bufferPosition;+ if (available > 0) {+ System.arraycopy(b, offset, buffer, bufferPosition, available);+ offset += available;+ length -= available;+ bufferPosition = bufferSize;+ bufferLength = bufferSize;+ }++ flushBufferToCache();++ // and now, write the remaining 'length' bytes:+ if (length < bufferSize) {+ // If the amount left to write is small enough do it in the usual+ // buffered way:+ System.arraycopy(b, offset, buffer, 0, length);+ bufferPosition = length;+ bufferLength = length;+ } else {+ // The amount left to write is larger than the buffer+ // there's no performance reason not to write it all+ // at once.+ writeInternal(b, offset, length);+ bufferStart += length;+ bufferPosition = 0;+ bufferLength = 0;+ }++ }+ }++ @Override+ protected Object clone() throws CloneNotSupportedException {+ throw new CloneNotSupportedException();+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/blockcache/package.html b/solr/core/src/java/org/apache/solr/store/blockcache/package.htmlnew file mode 100644index 00000000000..a5328c2d0f6--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/blockcache/package.html@@ -0,0 +1,29 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<!--+ Licensed to the Apache Software Foundation (ASF) under one or more+ contributor license agreements. See the NOTICE file distributed with+ this work for additional information regarding copyright ownership.+ The ASF licenses this file to You under the Apache License, Version 2.0+ (the "License"); you may not use this file except in compliance with+ the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+</head>+<body>+<p>+An HDFS blockcache implementation.+++</p>+</body>+</html>diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/HdfsDirectory.java b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsDirectory.javanew file mode 100644index 00000000000..47c0230352c--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsDirectory.java@@ -0,0 +1,262 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.List;++import org.apache.commons.io.IOUtils;+import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FSDataInputStream;+import org.apache.hadoop.fs.FileStatus;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.NoLockFactory;+import org.apache.solr.store.blockcache.CustomBufferedIndexInput;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HdfsDirectory extends Directory {+ public static Logger LOG = LoggerFactory.getLogger(HdfsDirectory.class);++ public static final int BUFFER_SIZE = 8192;++ private static final String LF_EXT = ".lf";+ protected static final String SEGMENTS_GEN = "segments.gen";+ protected static final IndexOutput NULL_WRITER = new NullIndexOutput();+ protected Path hdfsDirPath;+ protected Configuration configuration;++ private final FileSystem fileSystem;++ public HdfsDirectory(Path hdfsDirPath, Configuration configuration)+ throws IOException {+ assert hdfsDirPath.toString().startsWith("hdfs:/") : hdfsDirPath.toString();+ setLockFactory(NoLockFactory.getNoLockFactory());+ this.hdfsDirPath = hdfsDirPath;+ this.configuration = configuration;+ fileSystem = FileSystem.newInstance(hdfsDirPath.toUri(), configuration);+ try {+ if (!fileSystem.exists(hdfsDirPath)) {+ fileSystem.mkdirs(hdfsDirPath);+ }+ } catch (Exception e) {+ IOUtils.closeQuietly(fileSystem);+ throw new RuntimeException("Problem creating directory: " + hdfsDirPath,+ e);+ }+ }++ @Override+ public void close() throws IOException {+ LOG.info("Closing hdfs directory {}", hdfsDirPath);+ fileSystem.close();+ }++ @Override+ public IndexOutput createOutput(String name, IOContext context)+ throws IOException {+ if (SEGMENTS_GEN.equals(name)) {+ return NULL_WRITER;+ }+ HdfsFileWriter writer = new HdfsFileWriter(getFileSystem(), new Path(+ hdfsDirPath, name));+ return new HdfsIndexOutput(writer);+ }++ private String[] getNormalNames(List<String> files) {+ int size = files.size();+ for (int i = 0; i < size; i++) {+ String str = files.get(i);+ files.set(i, toNormalName(str));+ }+ return files.toArray(new String[] {});+ }++ private String toNormalName(String name) {+ if (name.endsWith(LF_EXT)) {+ return name.substring(0, name.length() - 3);+ }+ return name;+ }++ @Override+ public IndexInput openInput(String name, IOContext context)+ throws IOException {+ return openInput(name, BUFFER_SIZE);+ }++ private IndexInput openInput(String name, int bufferSize) throws IOException {+ return new HdfsNormalIndexInput(name, getFileSystem(), new Path(+ hdfsDirPath, name), BUFFER_SIZE);+ }++ @Override+ public void deleteFile(String name) throws IOException {+ Path path = new Path(hdfsDirPath, name);+ LOG.debug("Deleting {}", path);+ getFileSystem().delete(path, false);+ }++ @Override+ public boolean fileExists(String name) throws IOException {+ return getFileSystem().exists(new Path(hdfsDirPath, name));+ }++ @Override+ public long fileLength(String name) throws IOException {+ return HdfsFileReader.getLength(getFileSystem(),+ new Path(hdfsDirPath, name));+ }++ public long fileModified(String name) throws IOException {+ FileStatus fileStatus = getFileSystem().getFileStatus(+ new Path(hdfsDirPath, name));+ return fileStatus.getModificationTime();+ }++ @Override+ public String[] listAll() throws IOException {+ FileStatus[] listStatus = getFileSystem().listStatus(hdfsDirPath);+ List<String> files = new ArrayList<String>();+ if (listStatus == null) {+ return new String[] {};+ }+ for (FileStatus status : listStatus) {+ if (!status.isDirectory()) {+ files.add(status.getPath().getName());+ }+ }+ return getNormalNames(files);+ }++ public Path getHdfsDirPath() {+ return hdfsDirPath;+ }++ public FileSystem getFileSystem() {+ return fileSystem;+ }++ public Configuration getConfiguration() {+ return configuration;+ }++ static class HdfsNormalIndexInput extends CustomBufferedIndexInput {+ public static Logger LOG = LoggerFactory+ .getLogger(HdfsNormalIndexInput.class);++ private final Path path;+ private final FSDataInputStream inputStream;+ private final long length;+ private boolean clone = false;++ public HdfsNormalIndexInput(String name, FileSystem fileSystem, Path path,+ int bufferSize) throws IOException {+ super(name);+ this.path = path;+ LOG.debug("Opening normal index input on {}", path);+ FileStatus fileStatus = fileSystem.getFileStatus(path);+ length = fileStatus.getLen();+ inputStream = fileSystem.open(path, bufferSize);+ }++ @Override+ protected void readInternal(byte[] b, int offset, int length)+ throws IOException {+ inputStream.read(getFilePointer(), b, offset, length);+ }++ @Override+ protected void seekInternal(long pos) throws IOException {+ inputStream.seek(pos);+ }++ @Override+ protected void closeInternal() throws IOException {+ LOG.debug("Closing normal index input on {}", path);+ if (!clone) {+ inputStream.close();+ }+ }++ @Override+ public long length() {+ return length;+ }++ @Override+ public IndexInput clone() {+ HdfsNormalIndexInput clone = (HdfsNormalIndexInput) super.clone();+ clone.clone = true;+ return clone;+ }+ }++ static class HdfsIndexOutput extends IndexOutput {++ private HdfsFileWriter writer;++ public HdfsIndexOutput(HdfsFileWriter writer) {+ this.writer = writer;+ }++ @Override+ public void close() throws IOException {+ writer.close();+ }++ @Override+ public void flush() throws IOException {+ writer.flush();+ }++ @Override+ public long getFilePointer() {+ return writer.getPosition();+ }++ @Override+ public long length() {+ return writer.length();+ }++ @Override+ public void writeByte(byte b) throws IOException {+ writer.writeByte(b);+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ writer.writeBytes(b, offset, length);+ }+ }++ @Override+ public void sync(Collection<String> names) throws IOException {+ LOG.debug("Sync called on {}", Arrays.toString(names.toArray()));+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileReader.java b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileReader.javanew file mode 100644index 00000000000..8a537935ea0--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileReader.java@@ -0,0 +1,102 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.FileNotFoundException;+import java.io.IOException;++import org.apache.hadoop.fs.FSDataInputStream;+import org.apache.hadoop.fs.FileStatus;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.lucene.store.DataInput;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HdfsFileReader extends DataInput {++ public static Logger LOG = LoggerFactory.getLogger(HdfsFileReader.class);++ private final Path path;+ private FSDataInputStream inputStream;+ private long length;+ private boolean isClone;++ public HdfsFileReader(FileSystem fileSystem, Path path, int bufferSize)+ throws IOException {+ this.path = path;+ LOG.debug("Opening reader on {}", path);+ if (!fileSystem.exists(path)) {+ throw new FileNotFoundException(path.toString());+ }+ inputStream = fileSystem.open(path, bufferSize);+ FileStatus fileStatus = fileSystem.getFileStatus(path);+ length = fileStatus.getLen();+ }++ public HdfsFileReader(FileSystem fileSystem, Path path) throws IOException {+ this(fileSystem, path, HdfsDirectory.BUFFER_SIZE);+ }++ public long length() {+ return length;+ }++ public void seek(long pos) throws IOException {+ inputStream.seek(pos);+ }++ public void close() throws IOException {+ if (!isClone) {+ inputStream.close();+ }+ LOG.debug("Closing reader on {}", path);+ }++ /**+ * This method should never be used!+ */+ @Override+ public byte readByte() throws IOException {+ LOG.warn("Should not be used!");+ return inputStream.readByte();+ }++ @Override+ public void readBytes(byte[] b, int offset, int len) throws IOException {+ while (len > 0) {+ int lenRead = inputStream.read(b, offset, len);+ offset += lenRead;+ len -= lenRead;+ }+ }++ public static long getLength(FileSystem fileSystem, Path path)+ throws IOException {+ FileStatus fileStatus = fileSystem.getFileStatus(path);+ return fileStatus.getLen();+ }++ @Override+ public DataInput clone() {+ HdfsFileReader reader = (HdfsFileReader) super.clone();+ reader.isClone = true;+ return reader;+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileWriter.java b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileWriter.javanew file mode 100644index 00000000000..941f9f6da19--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsFileWriter.java@@ -0,0 +1,95 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;+import java.util.EnumSet;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.CreateFlag;+import org.apache.hadoop.fs.FSDataOutputStream;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.FsServerDefaults;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.fs.permission.FsPermission;+import org.apache.lucene.store.DataOutput;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class HdfsFileWriter extends DataOutput {+ public static Logger LOG = LoggerFactory.getLogger(HdfsFileWriter.class);++ public static final String HDFS_SYNC_BLOCK = "solr.hdfs.sync.block";++ private final Path path;+ private FSDataOutputStream outputStream;+ private long currentPosition;++ public HdfsFileWriter(FileSystem fileSystem, Path path) throws IOException {+ LOG.debug("Creating writer on {}", path);+ this.path = path;++ Configuration conf = fileSystem.getConf();+ FsServerDefaults fsDefaults = fileSystem.getServerDefaults(path);+ EnumSet<CreateFlag> flags = EnumSet.of(CreateFlag.CREATE,+ CreateFlag.OVERWRITE);+ if (Boolean.getBoolean(HDFS_SYNC_BLOCK)) {+ flags.add(CreateFlag.SYNC_BLOCK);+ }+ outputStream = fileSystem.create(path, FsPermission.getDefault()+ .applyUMask(FsPermission.getUMask(conf)), flags, fsDefaults+ .getFileBufferSize(), fsDefaults.getReplication(), fsDefaults+ .getBlockSize(), null);+ }++ public long length() {+ return currentPosition;+ }++ public void seek(long pos) throws IOException {+ LOG.error("Invalid seek called on {}", path);+ throw new IOException("Seek not supported");+ }++ public void flush() throws IOException {+ // flush to the network, not guarantees it makes it to the DN (vs hflush)+ outputStream.flush();+ LOG.debug("Flushed file {}", path);+ }++ public void close() throws IOException {+ outputStream.close();+ LOG.debug("Closed writer on {}", path);+ }++ @Override+ public void writeByte(byte b) throws IOException {+ outputStream.write(b & 0xFF);+ currentPosition++;+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ outputStream.write(b, offset, length);+ currentPosition += length;+ }++ public long getPosition() {+ return currentPosition;+ }+}diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/HdfsLockFactory.java b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsLockFactory.javanew file mode 100644index 00000000000..ecf113ace17--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/HdfsLockFactory.java@@ -0,0 +1,138 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++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.apache.lucene.store.Lock;+import org.apache.lucene.store.LockFactory;+import org.apache.lucene.store.LockReleaseFailedException;+import org.apache.solr.util.IOUtils;++public class HdfsLockFactory extends LockFactory {++ private Path lockPath;+ private Configuration configuration;++ public HdfsLockFactory(Path lockPath, Configuration configuration) {+ this.lockPath = lockPath;+ this.configuration = configuration;+ }++ @Override+ public Lock makeLock(String lockName) {++ if (lockPrefix != null) {+ lockName = lockPrefix + "-" + lockName;+ }++ HdfsLock lock = new HdfsLock(lockPath, lockName, configuration);++ return lock;+ }++ @Override+ public void clearLock(String lockName) throws IOException {+ FileSystem fs = null;+ try {+ fs = FileSystem.newInstance(lockPath.toUri(), configuration);++ if (fs.exists(lockPath)) {+ if (lockPrefix != null) {+ lockName = lockPrefix + "-" + lockName;+ }++ Path lockFile = new Path(lockPath, lockName);++ if (fs.exists(lockFile) && !fs.delete(lockFile, false)) {+ throw new IOException("Cannot delete " + lockFile);+ }+ }+ } finally {+ IOUtils.closeQuietly(fs);+ }+ }++ public Path getLockPath() {+ return lockPath;+ }++ public void setLockPath(Path lockPath) {+ this.lockPath = lockPath;+ }++ static class HdfsLock extends Lock {++ private Path lockPath;+ private String lockName;+ private Configuration conf;++ public HdfsLock(Path lockPath, String lockName, Configuration conf) {+ this.lockPath = lockPath;+ this.lockName = lockName;+ this.conf = conf;+ }++ @Override+ public boolean obtain() throws IOException {+ FSDataOutputStream file = null;+ FileSystem fs = null;+ try {+ fs = FileSystem.newInstance(lockPath.toUri(), conf);++ file = fs.create(new Path(lockPath, lockName), false);+ } catch (IOException e) {+ return false;+ } finally {+ IOUtils.closeQuietly(file);+ IOUtils.closeQuietly(fs);+ }+ return true;+ }++ @Override+ public void release() throws IOException {+ FileSystem fs = FileSystem.newInstance(lockPath.toUri(), conf);+ try {+ if (fs.exists(new Path(lockPath, lockName))+ && !fs.delete(new Path(lockPath, lockName), false)) throw new LockReleaseFailedException(+ "failed to delete " + new Path(lockPath, lockName));+ } finally {+ IOUtils.closeQuietly(fs);+ }+ }++ @Override+ public boolean isLocked() throws IOException {+ boolean isLocked = false;+ FileSystem fs = FileSystem.newInstance(lockPath.toUri(), conf);+ try {+ isLocked = fs.exists(new Path(lockPath, lockName));+ } finally {+ IOUtils.closeQuietly(fs);+ }+ return isLocked;+ }++ }++}diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/NullIndexOutput.java b/solr/core/src/java/org/apache/solr/store/hdfs/NullIndexOutput.javanew file mode 100644index 00000000000..02953859623--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/NullIndexOutput.java@@ -0,0 +1,66 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.IOException;++import org.apache.lucene.store.IndexOutput;++public class NullIndexOutput extends IndexOutput {++ private long pos;+ private long length;++ @Override+ public void close() throws IOException {++ }++ @Override+ public void flush() throws IOException {++ }++ @Override+ public long getFilePointer() {+ return pos;+ }++ @Override+ public long length() throws IOException {+ return length;+ }++ @Override+ public void writeByte(byte b) throws IOException {+ pos++;+ }++ @Override+ public void writeBytes(byte[] b, int offset, int length) throws IOException {+ pos += length;+ updateLength();+ }++ private void updateLength() {+ if (pos > length) {+ length = pos;+ }+ }++}diff --git a/solr/core/src/java/org/apache/solr/store/hdfs/package.html b/solr/core/src/java/org/apache/solr/store/hdfs/package.htmlnew file mode 100644index 00000000000..cfe928e33fc--- /dev/null+++ b/solr/core/src/java/org/apache/solr/store/hdfs/package.html@@ -0,0 +1,29 @@+<!doctype html public "-//w3c//dtd html 4.0 transitional//en">+<!--+ Licensed to the Apache Software Foundation (ASF) under one or more+ contributor license agreements. See the NOTICE file distributed with+ this work for additional information regarding copyright ownership.+ The ASF licenses this file to You under the Apache License, Version 2.0+ (the "License"); you may not use this file except in compliance with+ the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->+<html>+<head>+ <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">+</head>+<body>+<p>+An HDFS Directory implementation.+++</p>+</body>+</html>diff --git a/solr/core/src/java/org/apache/solr/update/HdfsTransactionLog.java b/solr/core/src/java/org/apache/solr/update/HdfsTransactionLog.javanew file mode 100644index 00000000000..935774d766a--- /dev/null+++ b/solr/core/src/java/org/apache/solr/update/HdfsTransactionLog.java@@ -0,0 +1,581 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.IOException;+import java.util.Collection;+import java.util.HashMap;+import java.util.List;+import java.util.Map;++import org.apache.hadoop.fs.FSDataInputStream;+import org.apache.hadoop.fs.FSDataOutputStream;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrInputDocument;+import org.apache.solr.common.util.DataInputInputStream;+import org.apache.solr.common.util.FastInputStream;+import org.apache.solr.common.util.FastOutputStream;+import org.apache.solr.common.util.JavaBinCodec;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/**+ * Log Format: List{Operation, Version, ...}+ * ADD, VERSION, DOC+ * DELETE, VERSION, ID_BYTES+ * DELETE_BY_QUERY, VERSION, String+ *+ * TODO: keep two files, one for [operation, version, id] and the other for the actual+ * document data. That way we could throw away document log files more readily+ * while retaining the smaller operation log files longer (and we can retrieve+ * the stored fields from the latest documents from the index).+ *+ * This would require keeping all source fields stored of course.+ *+ * This would also allow to not log document data for requests with commit=true+ * in them (since we know that if the request succeeds, all docs will be committed)+ *+ */+public class HdfsTransactionLog extends TransactionLog {+ public static Logger log = LoggerFactory.getLogger(HdfsTransactionLog.class);+++ Path tlogFile;+++ private FSDataOutputStream tlogOutStream;+ private FileSystem fs;++ HdfsTransactionLog(FileSystem fs, Path tlogFile, Collection<String> globalStrings) {+ this(fs, tlogFile, globalStrings, false);+ }++ HdfsTransactionLog(FileSystem fs, Path tlogFile, Collection<String> globalStrings, boolean openExisting) {+ super();+ boolean success = false;+ this.fs = fs;++ try {+ if (debug) {+ //log.debug("New TransactionLog file=" + tlogFile + ", exists=" + tlogFile.exists() + ", size=" + tlogFile.length() + ", openExisting=" + openExisting);+ }+ this.tlogFile = tlogFile;++ // TODO: look into forcefully taking over any lease+ if (fs.exists(tlogFile) && openExisting) {+ tlogOutStream = fs.append(tlogFile);+ } else {+ fs.delete(tlogFile, false);++ tlogOutStream = fs.create(tlogFile, (short)1);+ tlogOutStream.hsync();+ }++ fos = new FastOutputStream(tlogOutStream, new byte[65536], 0);+ long start = tlogOutStream.getPos();++ if (openExisting) {+ if (start > 0) {+ readHeader(null);++ // we should already be at the end+ // raf.seek(start);++ // assert channel.position() == start;+ fos.setWritten(start); // reflect that we aren't starting at the beginning+ //assert fos.size() == channel.size();+ } else {+ addGlobalStrings(globalStrings);+ }+ } else {+ if (start > 0) {+ log.error("New transaction log already exists:" + tlogFile + " size=" + tlogOutStream.size());+ }++ addGlobalStrings(globalStrings);+ }++ success = true;++ } catch (IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);+ } finally {+ if (!success && tlogOutStream != null) {+ try {+ tlogOutStream.close();+ } catch (Exception e) {+ log.error("Error closing tlog file (after error opening)", e);+ }+ }+ }+ }++ @Override+ public boolean endsWithCommit() throws IOException {+ long size;+ synchronized (this) {+ fos.flush();+ tlogOutStream.hflush();+ size = fos.size();+ }+++ // the end of the file should have the end message (added during a commit) plus a 4 byte size+ byte[] buf = new byte[ END_MESSAGE.length() ];+ long pos = size - END_MESSAGE.length() - 4;+ if (pos < 0) return false;++ FSDataFastInputStream dis = new FSDataFastInputStream(fs.open(tlogFile), pos);+ try {+ //ChannelFastInputStream is = new ChannelFastInputStream(channel, pos);+ dis.read(buf);+ for (int i=0; i<buf.length; i++) {+ if (buf[i] != END_MESSAGE.charAt(i)) return false;+ }+ } finally {+ dis.close();+ }+ return true;+ }++ // This could mess with any readers or reverse readers that are open, or anything that might try to do a log lookup.+ // This should only be used to roll back buffered updates, not actually applied updates.+ @Override+ public void rollback(long pos) throws IOException {+ synchronized (this) {+ assert snapshot_size == pos;+ fos.flush();+ tlogOutStream.hflush();+ // TODO: how do we rollback with hdfs?? We need HDFS-3107+ //raf.setLength(pos);+ fos.setWritten(pos);+ assert fos.size() == pos;+ numRecords = snapshot_numRecords;+ }+ }++ private void readHeader(FastInputStream fis) throws IOException {+ // read existing header+ boolean closeFis = false;+ if (fis == null) closeFis = true;+ fis = fis != null ? fis : new FSDataFastInputStream(fs.open(tlogFile), 0);+ Map header = null;+ try {+ LogCodec codec = new LogCodec(resolver);+ header = (Map) codec.unmarshal(fis);++ fis.readInt(); // skip size+ } finally {+ if (fis != null && closeFis) {+ fis.close();+ }+ }+ // needed to read other records++ synchronized (this) {+ globalStringList = (List<String>)header.get("strings");+ globalStringMap = new HashMap<String, Integer>(globalStringList.size());+ for (int i=0; i<globalStringList.size(); i++) {+ globalStringMap.put( globalStringList.get(i), i+1);+ }+ }+ }++ @Override+ public long writeCommit(CommitUpdateCommand cmd, int flags) {+ LogCodec codec = new LogCodec(resolver);+ synchronized (this) {+ try {+ long pos = fos.size(); // if we had flushed, this should be equal to channel.position()++ if (pos == 0) {+ writeLogHeader(codec);+ pos = fos.size();+ }++ codec.init(fos);+ codec.writeTag(JavaBinCodec.ARR, 3);+ codec.writeInt(UpdateLog.COMMIT | flags); // should just take one byte+ codec.writeLong(cmd.getVersion());+ codec.writeStr(END_MESSAGE); // ensure these bytes are (almost) last in the file++ endRecord(pos);++ fos.flush(); // flush since this will be the last record in a log fill+ tlogOutStream.hflush();++ //assert fos.size() == channel.size();++ return pos;+ } catch (IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);+ }+ }+ }+++ /* This method is thread safe */+ @Override+ public Object lookup(long pos) {+ // A negative position can result from a log replay (which does not re-log, but does+ // update the version map. This is OK since the node won't be ACTIVE when this happens.+ if (pos < 0) return null;++ try {+ // make sure any unflushed buffer has been flushed+ synchronized (this) {+ // TODO: optimize this by keeping track of what we have flushed up to+ fos.flushBuffer();++ // flush to hdfs+ tlogOutStream.hflush();+ /***+ System.out.println("###flushBuffer to " + fos.size() + " raf.length()=" + raf.length() + " pos="+pos);+ if (fos.size() != raf.length() || pos >= fos.size() ) {+ throw new RuntimeException("ERROR" + "###flushBuffer to " + fos.size() + " raf.length()=" + raf.length() + " pos="+pos);+ }+ ***/+ }++ FSDataFastInputStream dis = new FSDataFastInputStream(fs.open(tlogFile),+ pos);+ try {+ dis.seek(pos);+ LogCodec codec = new LogCodec(resolver);+ return codec.readVal(new FastInputStream(dis));+ } finally {+ dis.close();+ }+ } catch (IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "pos=" + pos, e);+ }+ }++ @Override+ public void finish(UpdateLog.SyncLevel syncLevel) {+ if (syncLevel == UpdateLog.SyncLevel.NONE) return;+ try {+ synchronized (this) {+ fos.flushBuffer();++ // we must flush to hdfs+ // TODO: we probably don't need to+ // hsync below if we do this - I+ // think they are equivalent.+ tlogOutStream.hflush();+ }++ if (syncLevel == UpdateLog.SyncLevel.FSYNC) {+ // Since fsync is outside of synchronized block, we can end up with a partial+ // last record on power failure (which is OK, and does not represent an error...+ // we just need to be aware of it when reading).++ //raf.getFD().sync();+ tlogOutStream.hsync();+ }++ } catch (IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);+ }+ }++ @Override+ protected void close() {+ try {+ if (debug) {+ log.debug("Closing tlog" + this);+ }++ synchronized (this) {+ fos.flush();+ tlogOutStream.hflush();+ fos.close();++ tlogOutStream.close();+ }++ if (deleteOnClose) {+ fs.delete(tlogFile, true);+ }+ } catch (IOException e) {+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);+ }+ }++ public String toString() {+ return "hdfs tlog{file=" + tlogFile.toString() + " refcount=" + refcount.get() + "}";+ }++ /** Returns a reader that can be used while a log is still in use.+ * Currently only *one* LogReader may be outstanding, and that log may only+ * be used from a single thread. */+ @Override+ public LogReader getReader(long startingPos) {+ return new HDFSLogReader(startingPos);+ }++ /** Returns a single threaded reverse reader */+ @Override+ public ReverseReader getReverseReader() throws IOException {+ return new HDFSReverseReader();+ }+++ public class HDFSLogReader extends LogReader{+ FSDataFastInputStream fis;+ private LogCodec codec = new LogCodec(resolver);++ public HDFSLogReader(long startingPos) {+ super();+ incref();+ try {+ FSDataInputStream fdis = fs.open(tlogFile);+ fis = new FSDataFastInputStream(fdis, startingPos);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ /** Returns the next object from the log, or null if none available.+ *+ * @return The log record, or null if EOF+ * @throws IOException If there is a low-level I/O error.+ */+ public Object next() throws IOException, InterruptedException {+ long pos = fis.position();+++ synchronized (HdfsTransactionLog.this) {+ if (trace) {+ log.trace("Reading log record. pos="+pos+" currentSize="+fos.size());+ }++ if (pos >= fos.size()) {+ return null;+ }++ fos.flushBuffer();+ tlogOutStream.hflush();++ // we actually need a new reader+ fis.close();+ try {+ FSDataInputStream fdis = fs.open(tlogFile);+ fis = new FSDataFastInputStream(fdis, pos);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ }+ if (pos == 0) {+ readHeader(fis);++ // shouldn't currently happen - header and first record are currently written at the same time+ synchronized (HdfsTransactionLog.this) {+ if (fis.position() >= fos.size()) {+ return null;+ }+ pos = fis.position();+ }+ }++ tlogOutStream.hflush();+ Object o = codec.readVal(fis);++ // skip over record size+ int size = fis.readInt();+ assert size == fis.position() - pos - 4;++ return o;+ }++ public void close() {+ try {+ fis.close();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ decref();+ }++ @Override+ public String toString() {+ synchronized (HdfsTransactionLog.this) {+ return "LogReader{" + "file=" + tlogFile + ", position=" + fis.position() + ", end=" + fos.size() + "}";+ }+ }++ }++ public class HDFSReverseReader extends ReverseReader {+ FSDataFastInputStream fis;+ private LogCodec codec = new LogCodec(resolver) {+ @Override+ public SolrInputDocument readSolrInputDocument(DataInputInputStream dis) {+ // Given that the SolrInputDocument is last in an add record, it's OK to just skip+ // reading it completely.+ return null;+ }+ };++ int nextLength; // length of the next record (the next one closer to the start of the log file)+ long prevPos; // where we started reading from last time (so prevPos - nextLength == start of next record)++ public HDFSReverseReader() throws IOException {+ incref();++ long sz;+ synchronized (HdfsTransactionLog.this) {+ fos.flushBuffer();++ // this must be an hflush+ tlogOutStream.hflush();+ sz = fos.size();+ //assert sz == channel.size();+ }++ fis = new FSDataFastInputStream(fs.open(tlogFile), 0);++ if (sz >=4) {+ // readHeader(fis); // should not be needed+ prevPos = sz - 4;+ fis.seek(prevPos);+ nextLength = fis.readInt();+ }+ }+++ /** Returns the next object from the log, or null if none available.+ *+ * @return The log record, or null if EOF+ * @throws IOException If there is a low-level I/O error.+ */+ public Object next() throws IOException {+ if (prevPos <= 0) return null;++ long endOfThisRecord = prevPos;++ int thisLength = nextLength;++ long recordStart = prevPos - thisLength; // back up to the beginning of the next record+ prevPos = recordStart - 4; // back up 4 more to read the length of the next record++ if (prevPos <= 0) return null; // this record is the header++ long bufferPos = fis.getBufferPos();+ if (prevPos >= bufferPos) {+ // nothing to do... we're within the current buffer+ } else {+ // Position buffer so that this record is at the end.+ // For small records, this will cause subsequent calls to next() to be within the buffer.+ long seekPos = endOfThisRecord - fis.getBufferSize();+ seekPos = Math.min(seekPos, prevPos); // seek to the start of the record if it's larger then the block size.+ seekPos = Math.max(seekPos, 0);+ fis.seek(seekPos);+ fis.peek(); // cause buffer to be filled+ }++ fis.seek(prevPos);+ nextLength = fis.readInt(); // this is the length of the *next* record (i.e. closer to the beginning)++ // TODO: optionally skip document data+ Object o = codec.readVal(fis);++ // assert fis.position() == prevPos + 4 + thisLength; // this is only true if we read all the data (and we currently skip reading SolrInputDocument+ return o;+ }++ /* returns the position in the log file of the last record returned by next() */+ public long position() {+ return prevPos + 4; // skip the length+ }++ public void close() {+ try {+ fis.close();+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ decref();+ }++ @Override+ public String toString() {+ synchronized (HdfsTransactionLog.this) {+ return "LogReader{" + "file=" + tlogFile + ", position=" + fis.position() + ", end=" + fos.size() + "}";+ }+ }+++ }++}++++class FSDataFastInputStream extends FastInputStream {+ private FSDataInputStream fis;++ public FSDataFastInputStream(FSDataInputStream fis, long chPosition) {+ // super(null, new byte[10],0,0); // a small buffer size for testing purposes+ super(null);+ this.fis = fis;+ super.readFromStream = chPosition;+ }++ @Override+ public int readWrappedStream(byte[] target, int offset, int len) throws IOException {+ return fis.read(readFromStream, target, offset, len);+ }++ public void seek(long position) throws IOException {+ if (position <= readFromStream && position >= getBufferPos()) {+ // seek within buffer+ pos = (int)(position - getBufferPos());+ } else {+ // long currSize = ch.size(); // not needed - underlying read should handle (unless read never done)+ // if (position > currSize) throw new EOFException("Read past EOF: seeking to " + position + " on file of size " + currSize + " file=" + ch);+ readFromStream = position;+ end = pos = 0;+ }+ assert position() == position;+ }++ /** where is the start of the buffer relative to the whole file */+ public long getBufferPos() {+ return readFromStream - end;+ }++ public int getBufferSize() {+ return buf.length;+ }++ @Override+ public void close() throws IOException {+ fis.close();+ }++ @Override+ public String toString() {+ return "readFromStream="+readFromStream +" pos="+pos +" end="+end + " bufferPos="+getBufferPos() + " position="+position() ;+ }+}++diff --git a/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.java b/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.javanew file mode 100644index 00000000000..e209c85be74--- /dev/null+++ b/solr/core/src/java/org/apache/solr/update/HdfsUpdateLog.java@@ -0,0 +1,354 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.update;++import java.io.FileNotFoundException;+import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.List;+import java.util.Locale;+import java.util.concurrent.ExecutionException;+import java.util.concurrent.Future;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FileStatus;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.fs.PathFilter;+import org.apache.lucene.util.BytesRef;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;+import org.apache.solr.core.PluginInfo;+import org.apache.solr.core.SolrCore;+import org.apache.solr.util.HdfsUtil;+import org.apache.solr.util.IOUtils;++/** @lucene.experimental */+public class HdfsUpdateLog extends UpdateLog {++ private FileSystem fs;+ private Path tlogDir;+ private String confDir;++ public HdfsUpdateLog() {++ }++ public HdfsUpdateLog(String confDir) {+ this.confDir = confDir;+ }++ public FileSystem getFs() {+ return fs;+ }++ // HACK+ // while waiting for HDFS-3107, instead of quickly+ // dropping, we slowly apply+ // This is somewhat brittle, but current usage+ // allows for it+ @Override+ public boolean dropBufferedUpdates() {+ Future<RecoveryInfo> future = applyBufferedUpdates();+ if (future != null) {+ try {+ future.get();+ } catch (InterruptedException e) {+ throw new RuntimeException(e);+ } catch (ExecutionException e) {+ throw new RuntimeException(e);+ }+ }+ return true;+ }++ @Override+ public void init(PluginInfo info) {+ dataDir = (String) info.initArgs.get("dir");++ defaultSyncLevel = SyncLevel.getSyncLevel((String) info.initArgs+ .get("syncLevel"));++ }++ private Configuration getConf() {+ Configuration conf = new Configuration();+ if (confDir != null) {+ HdfsUtil.addHdfsResources(conf, confDir);+ }++ return conf;+ }++ @Override+ public void init(UpdateHandler uhandler, SolrCore core) {++ // ulogDir from CoreDescriptor overrides+ String ulogDir = core.getCoreDescriptor().getUlogDir();++ if (ulogDir != null) {+ dataDir = ulogDir;+ }+ if (dataDir == null || dataDir.length()==0) {+ dataDir = core.getDataDir();+ }++ if (!core.getDirectoryFactory().isAbsolute(dataDir)) {+ try {+ dataDir = core.getDirectoryFactory().getDataHome(core.getCoreDescriptor());+ } catch (IOException e) {+ throw new SolrException(ErrorCode.SERVER_ERROR, e);+ }+ }++ try {+ fs = FileSystem.newInstance(new Path(dataDir).toUri(), getConf());+ } catch (IOException e) {+ throw new SolrException(ErrorCode.SERVER_ERROR, e);+ }++ this.uhandler = uhandler;++ if (dataDir.equals(lastDataDir)) {+ if (debug) {+ log.debug("UpdateHandler init: tlogDir=" + tlogDir + ", next id=" + id,+ " this is a reopen... nothing else to do.");+ }++ versionInfo.reload();++ // on a normal reopen, we currently shouldn't have to do anything+ return;+ }+ lastDataDir = dataDir;+ tlogDir = new Path(dataDir, TLOG_NAME);++ try {+ if (!fs.exists(tlogDir)) {+ boolean success = fs.mkdirs(tlogDir);+ if (!success) {+ throw new RuntimeException("Could not create directory:" + tlogDir);+ }+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }++ tlogFiles = getLogList(fs, tlogDir);+ id = getLastLogId() + 1; // add 1 since we will create a new log for the+ // next update++ if (debug) {+ log.debug("UpdateHandler init: tlogDir=" + tlogDir + ", existing tlogs="+ + Arrays.asList(tlogFiles) + ", next id=" + id);+ }++ TransactionLog oldLog = null;+ for (String oldLogName : tlogFiles) {+ Path f = new Path(tlogDir, oldLogName);+ try {+ oldLog = new HdfsTransactionLog(fs, f, null, true);+ addOldLog(oldLog, false); // don't remove old logs on startup since more+ // than one may be uncapped.+ } catch (Exception e) {+ SolrException.log(log, "Failure to open existing log file (non fatal) "+ + f, e);+ try {+ fs.delete(f, false);+ } catch (IOException e1) {+ throw new RuntimeException(e1);+ }+ }+ }++ // Record first two logs (oldest first) at startup for potential tlog+ // recovery.+ // It's possible that at abnormal shutdown both "tlog" and "prevTlog" were+ // uncapped.+ for (TransactionLog ll : logs) {+ newestLogsOnStartup.addFirst(ll);+ if (newestLogsOnStartup.size() >= 2) break;+ }++ try {+ versionInfo = new VersionInfo(this, 256);+ } catch (SolrException e) {+ log.error("Unable to use updateLog: " + e.getMessage(), e);+ throw new SolrException(SolrException.ErrorCode.SERVER_ERROR,+ "Unable to use updateLog: " + e.getMessage(), e);+ }++ // TODO: these startingVersions assume that we successfully recover from all+ // non-complete tlogs.+ HdfsUpdateLog.RecentUpdates startingUpdates = getRecentUpdates();+ try {+ startingVersions = startingUpdates.getVersions(numRecordsToKeep);+ startingOperation = startingUpdates.getLatestOperation();++ // populate recent deletes list (since we can't get that info from the+ // index)+ for (int i = startingUpdates.deleteList.size() - 1; i >= 0; i--) {+ DeleteUpdate du = startingUpdates.deleteList.get(i);+ oldDeletes.put(new BytesRef(du.id), new LogPtr(-1, du.version));+ }++ // populate recent deleteByQuery commands+ for (int i = startingUpdates.deleteByQueryList.size() - 1; i >= 0; i--) {+ Update update = startingUpdates.deleteByQueryList.get(i);+ List<Object> dbq = (List<Object>) update.log.lookup(update.pointer);+ long version = (Long) dbq.get(1);+ String q = (String) dbq.get(2);+ trackDeleteByQuery(q, version);+ }++ } finally {+ startingUpdates.close();+ }++ }++ @Override+ public String getLogDir() {+ return tlogDir.toUri().toString();+ }++ public static String[] getLogList(FileSystem fs, Path tlogDir) {+ final String prefix = TLOG_NAME + '.';+ assert fs != null;+ FileStatus[] fileStatuses;+ try {+ fileStatuses = fs.listStatus(tlogDir, new PathFilter() {++ @Override+ public boolean accept(Path path) {+ return path.getName().startsWith(prefix);+ }+ });+ } catch (FileNotFoundException e) {+ throw new RuntimeException(e);+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ String[] names = new String[fileStatuses.length];+ for (int i = 0; i < fileStatuses.length; i++) {+ names[i] = fileStatuses[i].getPath().getName();+ }+ Arrays.sort(names);++ return names;+ }++ @Override+ public void close(boolean committed) {+ synchronized (this) {+ super.close(committed);+ IOUtils.closeQuietly(fs);+ }+ }++ @Override+ protected void ensureLog() {+ if (tlog == null) {+ String newLogName = String.format(Locale.ROOT, LOG_FILENAME_PATTERN,+ TLOG_NAME, id);+ tlog = new HdfsTransactionLog(fs, new Path(tlogDir, newLogName),+ globalStrings);+ }+ }++ /**+ * Clears the logs on the file system. Only call before init.+ *+ * @param core the SolrCore+ * @param ulogPluginInfo the init info for the UpdateHandler+ */+ @Override+ public void clearLog(SolrCore core, PluginInfo ulogPluginInfo) {+ if (ulogPluginInfo == null) return;+ Path tlogDir = new Path(getTlogDir(core, ulogPluginInfo));+ try {+ if (fs.exists(tlogDir)) {+ String[] files = getLogList(tlogDir);+ for (String file : files) {+ Path f = new Path(tlogDir, file);+ boolean s = fs.delete(f, false);+ if (!s) {+ log.error("Could not remove tlog file:" + f);+ }+ }+ }+ } catch (IOException e) {+ throw new RuntimeException(e);+ }+ }++ private String[] getLogList(Path tlogDir) throws FileNotFoundException, IOException {+ final String prefix = TLOG_NAME+'.';+ FileStatus[] files = fs.listStatus(tlogDir, new PathFilter() {++ @Override+ public boolean accept(Path name) {+ return name.getName().startsWith(prefix);+ }+ });+ List<String> fileList = new ArrayList<String>(files.length);+ for (FileStatus file : files) {+ fileList.add(file.getPath().getName());+ }+ return fileList.toArray(new String[0]);+ }++ /**+ * Returns true if we were able to drop buffered updates and return to the+ * ACTIVE state+ */+ // public boolean dropBufferedUpdates() {+ // versionInfo.blockUpdates();+ // try {+ // if (state != State.BUFFERING) return false;+ //+ // if (log.isInfoEnabled()) {+ // log.info("Dropping buffered updates " + this);+ // }+ //+ // // since we blocked updates, this synchronization shouldn't strictly be+ // necessary.+ // synchronized (this) {+ // if (tlog != null) {+ // tlog.rollback(recoveryInfo.positionOfStart);+ // }+ // }+ //+ // state = State.ACTIVE;+ // operationFlags &= ~FLAG_GAP;+ // } catch (IOException e) {+ // SolrException.log(log,"Error attempting to roll back log", e);+ // return false;+ // }+ // finally {+ // versionInfo.unblockUpdates();+ // }+ // return true;+ // }++ public String toString() {+ return "HDFSUpdateLog{state=" + getState() + ", tlog=" + tlog + "}";+ }++}diff --git a/solr/core/src/java/org/apache/solr/update/TransactionLog.java b/solr/core/src/java/org/apache/solr/update/TransactionLog.javaindex 567e1bdd574..31f1a342c93 100644--- a/solr/core/src/java/org/apache/solr/update/TransactionLog.java+++ b/solr/core/src/java/org/apache/solr/update/TransactionLog.java@@ -74,7 +74,7 @@ public class TransactionLog {FastOutputStream fos; // all accesses to this stream should be synchronized on "this" (The TransactionLog)int numRecords;- volatile boolean deleteOnClose = true; // we can delete old tlogs since they are currently only used for real-time-get (and in the future, recovery)+ protected volatile boolean deleteOnClose = true; // we can delete old tlogs since they are currently only used for real-time-get (and in the future, recovery)AtomicInteger refcount = new AtomicInteger(1);Map<String,Integer> globalStringMap = new HashMap<String, Integer>();@@ -97,7 +97,7 @@ public class TransactionLog {};public class LogCodec extends JavaBinCodec {- public LogCodec() {+ public LogCodec(JavaBinCodec.ObjectResolver resolver) {super(resolver);}@@ -190,6 +190,9 @@ public class TransactionLog {}}+ // for subclasses+ protected TransactionLog() {}+/** Returns the number of records in the log (currently includes the header and an optional commit).* Note: currently returns 0 for reopened existing log files.*/@@ -244,7 +247,7 @@ public class TransactionLog {public long writeData(Object o) {- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);try {long pos = fos.size(); // if we had flushed, this should be equal to channel.position()codec.init(fos);@@ -259,7 +262,7 @@ public class TransactionLog {private void readHeader(FastInputStream fis) throws IOException {// read existing headerfis = fis != null ? fis : new ChannelFastInputStream(channel, 0);- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);Map header = (Map)codec.unmarshal(fis);fis.readInt(); // skip size@@ -275,7 +278,7 @@ public class TransactionLog {}}- private void addGlobalStrings(Collection<String> strings) {+ protected void addGlobalStrings(Collection<String> strings) {if (strings == null) return;int origSize = globalStringMap.size();for (String s : strings) {@@ -296,7 +299,7 @@ public class TransactionLog {}}- private void writeLogHeader(LogCodec codec) throws IOException {+ protected void writeLogHeader(LogCodec codec) throws IOException {long pos = fos.size();assert pos == 0;@@ -308,7 +311,7 @@ public class TransactionLog {endRecord(pos);}- private void endRecord(long startRecordPosition) throws IOException {+ protected void endRecord(long startRecordPosition) throws IOException {fos.writeInt((int)(fos.size() - startRecordPosition));numRecords++;}@@ -332,7 +335,7 @@ public class TransactionLog {int lastAddSize;public long write(AddUpdateCommand cmd, int flags) {- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);SolrInputDocument sdoc = cmd.getSolrInputDocument();try {@@ -374,7 +377,7 @@ public class TransactionLog {}public long writeDelete(DeleteUpdateCommand cmd, int flags) {- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);try {checkWriteHeader(codec, null);@@ -404,7 +407,7 @@ public class TransactionLog {}public long writeDeleteByQuery(DeleteUpdateCommand cmd, int flags) {- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);try {checkWriteHeader(codec, null);@@ -430,7 +433,7 @@ public class TransactionLog {public long writeCommit(CommitUpdateCommand cmd, int flags) {- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);synchronized (this) {try {long pos = fos.size(); // if we had flushed, this should be equal to channel.position()@@ -478,7 +481,7 @@ public class TransactionLog {}ChannelFastInputStream fis = new ChannelFastInputStream(channel, pos);- LogCodec codec = new LogCodec();+ LogCodec codec = new LogCodec(resolver);return codec.readVal(fis);} catch (IOException e) {throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, e);@@ -528,7 +531,7 @@ public class TransactionLog {}}- private void close() {+ protected void close() {try {if (debug) {log.debug("Closing tlog" + this);@@ -569,19 +572,22 @@ public class TransactionLog {/** Returns a single threaded reverse reader */public ReverseReader getReverseReader() throws IOException {- return new ReverseReader();+ return new FSReverseReader();}public class LogReader {- ChannelFastInputStream fis;- private LogCodec codec = new LogCodec();+ private ChannelFastInputStream fis;+ private LogCodec codec = new LogCodec(resolver);public LogReader(long startingPos) {incref();fis = new ChannelFastInputStream(channel, startingPos);}+ // for classes that extend+ protected LogReader() {}+/** Returns the next object from the log, or null if none available.** @return The log record, or null if EOF@@ -637,9 +643,30 @@ public class TransactionLog {}- public class ReverseReader {+ public abstract class ReverseReader {++++ /** Returns the next object from the log, or null if none available.+ *+ * @return The log record, or null if EOF+ * @throws IOException If there is a low-level I/O error.+ */+ public abstract Object next() throws IOException;++ /* returns the position in the log file of the last record returned by next() */+ public abstract long position();+ public abstract void close();++ @Override+ public abstract String toString() ;+++ }++ public class FSReverseReader extends ReverseReader {ChannelFastInputStream fis;- private LogCodec codec = new LogCodec() {+ private LogCodec codec = new LogCodec(resolver) {@Overridepublic SolrInputDocument readSolrInputDocument(DataInputInputStream dis) {// Given that the SolrInputDocument is last in an add record, it's OK to just skip@@ -651,7 +678,7 @@ public class TransactionLog {int nextLength; // length of the next record (the next one closer to the start of the log file)long prevPos; // where we started reading from last time (so prevPos - nextLength == start of next record)- public ReverseReader() throws IOException {+ public FSReverseReader() throws IOException {incref();long sz;diff --git a/solr/core/src/java/org/apache/solr/update/UpdateHandler.java b/solr/core/src/java/org/apache/solr/update/UpdateHandler.javaindex 26267d96e3e..03c5a48d698 100644--- a/solr/core/src/java/org/apache/solr/update/UpdateHandler.java+++ b/solr/core/src/java/org/apache/solr/update/UpdateHandler.java@@ -18,10 +18,11 @@package org.apache.solr.update;-import java.io.File;import java.io.IOException;import java.util.Vector;+import org.apache.solr.core.DirectoryFactory;+import org.apache.solr.core.HdfsDirectoryFactory;import org.apache.solr.core.PluginInfo;import org.apache.solr.core.SolrCore;import org.apache.solr.core.SolrEventListener;@@ -71,24 +72,6 @@ public abstract class UpdateHandler implements SolrInfoMBean {}}- // not thread safe - for startup- private void clearLog(PluginInfo ulogPluginInfo) {- if (ulogPluginInfo == null) return;- File tlogDir = UpdateLog.getTlogDir(core, ulogPluginInfo);- log.info("Clearing tlog files, tlogDir=" + tlogDir);- if (tlogDir.exists()) {- String[] files = UpdateLog.getLogList(tlogDir);- for (String file : files) {- File f = new File(tlogDir, file);- boolean s = f.delete();- if (!s) {- log.error("Could not remove tlog file:" + f.getAbsolutePath());- //throw new SolrException(ErrorCode.SERVER_ERROR, "Could not remove tlog file:" + f.getAbsolutePath());- }- }- }- }-protected void callPostCommitCallbacks() {for (SolrEventListener listener : commitCallbacks) {listener.postCommit();@@ -117,19 +100,43 @@ public abstract class UpdateHandler implements SolrInfoMBean {idFieldType = idField!=null ? idField.getType() : null;parseEventListeners();PluginInfo ulogPluginInfo = core.getSolrConfig().getPluginInfo(UpdateLog.class.getName());- if (!core.isReloaded() && !core.getDirectoryFactory().isPersistent()) {- clearLog(ulogPluginInfo);- }+if (updateLog == null && ulogPluginInfo != null && ulogPluginInfo.isEnabled()) {- ulog = new UpdateLog();+ String dataDir = (String)ulogPluginInfo.initArgs.get("dir");++ String ulogDir = core.getCoreDescriptor().getUlogDir();+ if (ulogDir != null) {+ dataDir = ulogDir;+ }+ if (dataDir == null || dataDir.length()==0) {+ dataDir = core.getDataDir();+ }++ if (dataDir != null && dataDir.startsWith("hdfs:/")) {+ DirectoryFactory dirFactory = core.getDirectoryFactory();+ if (dirFactory instanceof HdfsDirectoryFactory) {+ ulog = new HdfsUpdateLog(((HdfsDirectoryFactory)dirFactory).getConfDir());+ } else {+ ulog = new HdfsUpdateLog();+ }++ } else {+ ulog = new UpdateLog();+ }++ if (!core.isReloaded() && !core.getDirectoryFactory().isPersistent()) {+ ulog.clearLog(core, ulogPluginInfo);+ }+ulog.init(ulogPluginInfo);- // ulog = core.createInitInstance(ulogPluginInfo, UpdateLog.class, "update log", "solr.NullUpdateLog");+ulog.init(this, core);} else {ulog = updateLog;}// ulog.init() when reusing an existing log is deferred (currently at the end of the DUH2 constructor+}/**diff --git a/solr/core/src/java/org/apache/solr/update/UpdateLog.java b/solr/core/src/java/org/apache/solr/update/UpdateLog.javaindex c7c55304ef8..be01db59b3d 100644--- a/solr/core/src/java/org/apache/solr/update/UpdateLog.java+++ b/solr/core/src/java/org/apache/solr/update/UpdateLog.java@@ -17,15 +17,38 @@package org.apache.solr.update;+import static org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase.FROMLEADER;+import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;++import java.io.File;+import java.io.FileNotFoundException;+import java.io.FilenameFilter;+import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Collection;+import java.util.Deque;+import java.util.HashMap;+import java.util.LinkedHashMap;+import java.util.LinkedList;+import java.util.List;+import java.util.ListIterator;+import java.util.Locale;+import java.util.Map;+import java.util.concurrent.ExecutorCompletionService;+import java.util.concurrent.Future;+import java.util.concurrent.SynchronousQueue;+import java.util.concurrent.ThreadPoolExecutor;+import java.util.concurrent.TimeUnit;++import org.apache.hadoop.fs.FileSystem;import org.apache.lucene.util.BytesRef;import org.apache.solr.common.SolrException;import org.apache.solr.common.SolrException.ErrorCode;import org.apache.solr.common.SolrInputDocument;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.params.SolrParams;-import org.apache.solr.common.params.UpdateParams;import org.apache.solr.common.util.ExecutorUtil;-import org.apache.solr.common.util.NamedList;import org.apache.solr.core.PluginInfo;import org.apache.solr.core.SolrCore;import org.apache.solr.request.LocalSolrQueryRequest;@@ -34,9 +57,6 @@ import org.apache.solr.request.SolrRequestInfo;import org.apache.solr.response.SolrQueryResponse;import org.apache.solr.search.SolrIndexSearcher;import org.apache.solr.update.processor.DistributedUpdateProcessor;-import org.apache.solr.update.processor.DistributedUpdateProcessorFactory;-import org.apache.solr.update.processor.DistributingUpdateProcessorFactory;-import org.apache.solr.update.processor.RunUpdateProcessorFactory;import org.apache.solr.update.processor.UpdateRequestProcessor;import org.apache.solr.update.processor.UpdateRequestProcessorChain;import org.apache.solr.util.DefaultSolrThreadFactory;@@ -45,15 +65,6 @@ import org.apache.solr.util.plugin.PluginInfoInitialized;import org.slf4j.Logger;import org.slf4j.LoggerFactory;-import java.io.File;-import java.io.FilenameFilter;-import java.io.IOException;-import java.util.*;-import java.util.concurrent.*;--import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;-import static org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase.FROMLEADER;-/** @lucene.experimental */public class UpdateLog implements PluginInfoInitialized {@@ -64,6 +75,10 @@ public class UpdateLog implements PluginInfoInitialized {public boolean debug = log.isDebugEnabled();public boolean trace = log.isTraceEnabled();+ // TODO: hack+ public FileSystem getFs() {+ return null;+ }public enum SyncLevel { NONE, FLUSH, FSYNC;public static SyncLevel getSyncLevel(String level){@@ -108,27 +123,27 @@ public class UpdateLog implements PluginInfoInitialized {}long id = -1;- private State state = State.ACTIVE;- private int operationFlags; // flags to write in the transaction log with operations (i.e. FLAG_GAP)-- private TransactionLog tlog;- private TransactionLog prevTlog;- private Deque<TransactionLog> logs = new LinkedList<TransactionLog>(); // list of recent logs, newest first- private LinkedList<TransactionLog> newestLogsOnStartup = new LinkedList<TransactionLog>();- private int numOldRecords; // number of records in the recent logs-- private Map<BytesRef,LogPtr> map = new HashMap<BytesRef, LogPtr>();- private Map<BytesRef,LogPtr> prevMap; // used while committing/reopening is happening- private Map<BytesRef,LogPtr> prevMap2; // used while committing/reopening is happening- private TransactionLog prevMapLog; // the transaction log used to look up entries found in prevMap- private TransactionLog prevMapLog2; // the transaction log used to look up entries found in prevMap-- private final int numDeletesToKeep = 1000;- private final int numDeletesByQueryToKeep = 100;+ protected State state = State.ACTIVE;+ protected int operationFlags; // flags to write in the transaction log with operations (i.e. FLAG_GAP)++ protected TransactionLog tlog;+ protected TransactionLog prevTlog;+ protected Deque<TransactionLog> logs = new LinkedList<TransactionLog>(); // list of recent logs, newest first+ protected LinkedList<TransactionLog> newestLogsOnStartup = new LinkedList<TransactionLog>();+ protected int numOldRecords; // number of records in the recent logs++ protected Map<BytesRef,LogPtr> map = new HashMap<BytesRef, LogPtr>();+ protected Map<BytesRef,LogPtr> prevMap; // used while committing/reopening is happening+ protected Map<BytesRef,LogPtr> prevMap2; // used while committing/reopening is happening+ protected TransactionLog prevMapLog; // the transaction log used to look up entries found in prevMap+ protected TransactionLog prevMapLog2; // the transaction log used to look up entries found in prevMap++ protected final int numDeletesToKeep = 1000;+ protected final int numDeletesByQueryToKeep = 100;public final int numRecordsToKeep = 100;// keep track of deletes only... this is not updated on an add- private LinkedHashMap<BytesRef, LogPtr> oldDeletes = new LinkedHashMap<BytesRef, LogPtr>(numDeletesToKeep) {+ protected LinkedHashMap<BytesRef, LogPtr> oldDeletes = new LinkedHashMap<BytesRef, LogPtr>(numDeletesToKeep) {@Overrideprotected boolean removeEldestEntry(Map.Entry eldest) {return size() > numDeletesToKeep;@@ -145,21 +160,21 @@ public class UpdateLog implements PluginInfoInitialized {}}- private LinkedList<DBQ> deleteByQueries = new LinkedList<DBQ>();+ protected LinkedList<DBQ> deleteByQueries = new LinkedList<DBQ>();- private String[] tlogFiles;- private File tlogDir;- private Collection<String> globalStrings;+ protected String[] tlogFiles;+ protected File tlogDir;+ protected Collection<String> globalStrings;- private String dataDir;- private String lastDataDir;+ protected String dataDir;+ protected String lastDataDir;- private VersionInfo versionInfo;+ protected VersionInfo versionInfo;- private SyncLevel defaultSyncLevel = SyncLevel.FLUSH;+ protected SyncLevel defaultSyncLevel = SyncLevel.FLUSH;volatile UpdateHandler uhandler; // a core reload can change this reference!- private volatile boolean cancelApplyBufferUpdate;+ protected volatile boolean cancelApplyBufferUpdate;List<Long> startingVersions;int startingOperation; // last operation in the logs on startup@@ -199,7 +214,7 @@ public class UpdateLog implements PluginInfoInitialized {if (ulogDir != null) {dataDir = ulogDir;}-+if (dataDir == null || dataDir.length()==0) {dataDir = core.getDataDir();}@@ -280,8 +295,8 @@ public class UpdateLog implements PluginInfoInitialized {}- public File getLogDir() {- return tlogDir;+ public String getLogDir() {+ return tlogDir.getAbsolutePath();}public List<Long> getStartingVersions() {@@ -295,7 +310,7 @@ public class UpdateLog implements PluginInfoInitialized {/* Takes over ownership of the log, keeping it until no longer neededand then decrementing it's reference and dropping it.*/- private void addOldLog(TransactionLog oldLog, boolean removeOld) {+ protected void addOldLog(TransactionLog oldLog, boolean removeOld) {if (oldLog == null) return;numOldRecords += oldLog.numRecords();@@ -326,7 +341,7 @@ public class UpdateLog implements PluginInfoInitialized {}- public static String[] getLogList(File directory) {+ public String[] getLogList(File directory) {final String prefix = TLOG_NAME+'.';String[] names = directory.list(new FilenameFilter() {@Override@@ -334,6 +349,9 @@ public class UpdateLog implements PluginInfoInitialized {return name.startsWith(prefix);}});+ if (names == null) {+ throw new RuntimeException(new FileNotFoundException(directory.getAbsolutePath()));+ }Arrays.sort(names);return names;}@@ -544,7 +562,7 @@ public class UpdateLog implements PluginInfoInitialized {}}- private void newMap() {+ protected void newMap() {prevMap2 = prevMap;prevMapLog2 = prevMapLog;@@ -797,7 +815,7 @@ public class UpdateLog implements PluginInfoInitialized {}- private void ensureLog() {+ protected void ensureLog() {if (tlog == null) {String newLogName = String.format(Locale.ROOT, LOG_FILENAME_PATTERN, TLOG_NAME, id);tlog = new TransactionLog(new File(tlogDir, newLogName), globalStrings);@@ -1145,7 +1163,7 @@ public class UpdateLog implements PluginInfoInitialized {- private RecoveryInfo recoveryInfo;+ protected RecoveryInfo recoveryInfo;class LogReplayer implements Runnable {private Logger loglog = log; // set to something different?@@ -1422,7 +1440,7 @@ public class UpdateLog implements PluginInfoInitialized {}}- public static File getTlogDir(SolrCore core, PluginInfo info) {+ protected String getTlogDir(SolrCore core, PluginInfo info) {String dataDir = (String) info.initArgs.get("dir");String ulogDir = core.getCoreDescriptor().getUlogDir();@@ -1433,11 +1451,30 @@ public class UpdateLog implements PluginInfoInitialized {if (dataDir == null || dataDir.length() == 0) {dataDir = core.getDataDir();}-- return new File(dataDir, TLOG_NAME);++ return dataDir + "/" + TLOG_NAME;+ }++ /**+ * Clears the logs on the file system. Only call before init.+ *+ * @param core the SolrCore+ * @param ulogPluginInfo the init info for the UpdateHandler+ */+ public void clearLog(SolrCore core, PluginInfo ulogPluginInfo) {+ if (ulogPluginInfo == null) return;+ File tlogDir = new File(getTlogDir(core, ulogPluginInfo));+ if (tlogDir.exists()) {+ String[] files = getLogList(tlogDir);+ for (String file : files) {+ File f = new File(tlogDir, file);+ boolean s = f.delete();+ if (!s) {+ log.error("Could not remove tlog file:" + f);+ }+ }+ }}}--diff --git a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.javaindex 37976eb0f42..edafb2ba30d 100644--- a/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java+++ b/solr/core/src/java/org/apache/solr/update/processor/DistributedUpdateProcessor.java@@ -222,9 +222,9 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {// Replica leader = slice.getLeader();Replica leaderReplica = zkController.getZkStateReader().getLeaderRetry(collection, shardId);- ZkCoreNodeProps leaderProps = new ZkCoreNodeProps(leaderReplica);- String coreNodeName = zkController.getCoreNodeName(req.getCore().getCoreDescriptor());- isLeader = coreNodeName.equals(leaderReplica.getName());+ isLeader = leaderReplica.getName().equals(+ req.getCore().getCoreDescriptor().getCloudDescriptor()+ .getCoreNodeName());DistribPhase phase =DistribPhase.parseParam(req.getParams().get(DISTRIB_UPDATE_PARAM));@@ -240,7 +240,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {// so get the replicas...forwardToLeader = false;List<ZkCoreNodeProps> replicaProps = zkController.getZkStateReader()- .getReplicaProps(collection, shardId, coreNodeName,+ .getReplicaProps(collection, shardId, leaderReplica.getName(),coreName, null, ZkStateReader.DOWN);if (replicaProps != null) {@@ -272,7 +272,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {} else {// I need to forward onto the leader...nodes = new ArrayList<Node>(1);- nodes.add(new RetryNode(leaderProps, zkController.getZkStateReader(), collection, shardId));+ nodes.add(new RetryNode(new ZkCoreNodeProps(leaderReplica), zkController.getZkStateReader(), collection, shardId));forwardToLeader = true;}@@ -343,7 +343,9 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {if (isLeader && !localIsLeader) {log.error("ClusterState says we are the leader, but locally we don't think so");- throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "ClusterState says we are the leader, but locally we don't think so");+ throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE,+ "ClusterState says we are the leader (" + zkController.getBaseUrl()+ + "/" + req.getCore().getName() + "), but locally we don't think so. Request came from " + from);}}@@ -356,16 +358,15 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {try {Replica leaderReplica = zkController.getZkStateReader().getLeaderRetry(collection, shardId);- String leaderCoreNodeName = leaderReplica.getName();-- String coreNodeName = zkController.getCoreNodeName(req.getCore().getCoreDescriptor());- isLeader = coreNodeName.equals(leaderCoreNodeName);+ isLeader = leaderReplica.getName().equals(+ req.getCore().getCoreDescriptor().getCloudDescriptor()+ .getCoreNodeName());// TODO: what if we are no longer the leader?forwardToLeader = false;List<ZkCoreNodeProps> replicaProps = zkController.getZkStateReader()- .getReplicaProps(collection, shardId, coreNodeName,+ .getReplicaProps(collection, shardId, leaderReplica.getName(),req.getCore().getName());if (replicaProps != null) {nodes = new ArrayList<Node>(replicaProps.size());@@ -897,7 +898,7 @@ public class DistributedUpdateProcessor extends UpdateRequestProcessor {// Am I the leader for this slice?ZkCoreNodeProps coreLeaderProps = new ZkCoreNodeProps(leader);String leaderCoreNodeName = leader.getName();- String coreNodeName = zkController.getCoreNodeName(req.getCore().getCoreDescriptor());+ String coreNodeName = req.getCore().getCoreDescriptor().getCloudDescriptor().getCoreNodeName();isLeader = coreNodeName.equals(leaderCoreNodeName);if (isLeader) {diff --git a/solr/core/src/java/org/apache/solr/util/HdfsUtil.java b/solr/core/src/java/org/apache/solr/util/HdfsUtil.javanew file mode 100644index 00000000000..b46af5844d1--- /dev/null+++ b/solr/core/src/java/org/apache/solr/util/HdfsUtil.java@@ -0,0 +1,51 @@+package org.apache.solr.util;++import java.io.File;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.Path;+import org.apache.solr.common.SolrException;+import org.apache.solr.common.SolrException.ErrorCode;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class HdfsUtil {++ private static final String[] HADOOP_CONF_FILES = {"core-site.xml",+ "hdfs-site.xml", "mapred-site.xml", "yarn-site.xml", "hadoop-site.xml"};++ public static void addHdfsResources(Configuration conf, String confDir) {+ if (confDir != null && confDir.length() > 0) {+ File confDirFile = new File(confDir);+ if (!confDirFile.exists()) {+ throw new SolrException(ErrorCode.SERVER_ERROR, "Resource directory does not exist: " + confDirFile.getAbsolutePath());+ }+ if (!confDirFile.isDirectory()) {+ throw new SolrException(ErrorCode.SERVER_ERROR, "Specified resource directory is not a directory" + confDirFile.getAbsolutePath());+ }+ if (!confDirFile.canRead()) {+ throw new SolrException(ErrorCode.SERVER_ERROR, "Resource directory must be readable by the Solr process: " + confDirFile.getAbsolutePath());+ }+ for (String file : HADOOP_CONF_FILES) {+ if (new File(confDirFile, file).exists()) {+ conf.addResource(new Path(confDir, file));+ }+ }+ }+ }+}diff --git a/solr/core/src/java/org/apache/solr/util/IOUtils.java b/solr/core/src/java/org/apache/solr/util/IOUtils.javanew file mode 100644index 00000000000..e7b82eabda7--- /dev/null+++ b/solr/core/src/java/org/apache/solr/util/IOUtils.java@@ -0,0 +1,38 @@+package org.apache.solr.util;++import java.io.Closeable;++import org.apache.solr.core.HdfsDirectoryFactory;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class IOUtils {+ public static Logger LOG = LoggerFactory.getLogger(IOUtils.class);++ public static void closeQuietly(Closeable closeable) {+ try {+ if (closeable != null) {+ closeable.close();+ }+ } catch (Exception e) {+ LOG.error("Error while closing", e);+ }+ }+}diff --git a/solr/core/src/test-files/log4j.properties b/solr/core/src/test-files/log4j.propertiesindex fbc817f6e05..9b74a5f22b2 100644--- a/solr/core/src/test-files/log4j.properties+++ b/solr/core/src/test-files/log4j.properties@@ -7,3 +7,4 @@ log4j.appender.CONSOLE.layout=org.apache.solr.util.SolrLogLayoutlog4j.appender.CONSOLE.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\nlog4j.logger.org.apache.zookeeper=WARN+log4j.logger.org.apache.hadoop=WARNdiff --git a/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog.xml b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog.xmlindex 47ea0b6e469..2cacb5ae412 100644--- a/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog.xml+++ b/solr/core/src/test-files/solr/collection1/conf/solrconfig-tlog.xml@@ -24,7 +24,10 @@<directoryFactory name="DirectoryFactory" class="${solr.directoryFactory:solr.RAMDirectoryFactory}"><!-- used to keep RAM reqs down for HdfsDirectoryFactory -->+ <bool name="solr.hdfs.blockcache.enabled">${solr.hdfs.blockcache.enabled:true}</bool><int name="solr.hdfs.blockcache.blocksperbank">${solr.hdfs.blockcache.blocksperbank:1024}</int>+ <str name="solr.hdfs.home">${solr.hdfs.home:}</str>+ <str name="solr.hdfs.confdir">${solr.hdfs.confdir:}</str></directoryFactory><dataDir>${solr.data.dir:}</dataDir>diff --git a/solr/core/src/test-files/solr/solr-no-core.xml b/solr/core/src/test-files/solr/solr-no-core.xmlindex 3dbbe5b21c7..476b5bc7a10 100644--- a/solr/core/src/test-files/solr/solr-no-core.xml+++ b/solr/core/src/test-files/solr/solr-no-core.xml@@ -25,6 +25,7 @@<str name="hostContext">${hostContext:solr}</str><int name="hostPort">${hostPort:8983}</int><int name="zkClientTimeout">${solr.zkclienttimeout:30000}</int>+ <bool name="genericCoreNodeNames">${genericCoreNodeNames:true}</bool><int name="distribUpdateConnTimeout">${distribUpdateConnTimeout:15000}</int><int name="distribUpdateSoTimeout">${distribUpdateSoTimeout:120000}</int></solrcloud>@@ -35,4 +36,4 @@<int name="connTimeout">${connTimeout:15000}</int></shardHandlerFactory>-</solr>\ No newline at end of file+</solr>diff --git a/solr/core/src/test-files/solr/solr.xml b/solr/core/src/test-files/solr/solr.xmlindex d96291843fd..a25e8802c2d 100644--- a/solr/core/src/test-files/solr/solr.xml+++ b/solr/core/src/test-files/solr/solr.xml@@ -30,6 +30,7 @@--><cores adminPath="/admin/cores" defaultCoreName="collection1" host="127.0.0.1" hostPort="${hostPort:8983}"hostContext="${hostContext:solr}" zkClientTimeout="${solr.zkclienttimeout:30000}" numShards="${numShards:3}" shareSchema="${shareSchema:false}"+ genericCoreNodeNames="${genericCoreNodeNames:true}"distribUpdateConnTimeout="${distribUpdateConnTimeout:15000}" distribUpdateSoTimeout="${distribUpdateSoTimeout:120000}"><core name="collection1" instanceDir="collection1" shard="${shard:}" collection="${collection:collection1}" config="${solrconfig:solrconfig.xml}" schema="${schema:schema.xml}"coreNodeName="${coreNodeName:}"/>diff --git a/solr/core/src/test/org/apache/solr/cloud/AssignTest.java b/solr/core/src/test/org/apache/solr/cloud/AssignTest.javanew file mode 100644index 00000000000..298f515f21f--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/AssignTest.java@@ -0,0 +1,95 @@+package org.apache.solr.cloud;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.HashMap;+import java.util.HashSet;+import java.util.Map;+import java.util.Set;++import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.common.cloud.ClusterState;+import org.apache.solr.common.cloud.DocCollection;+import org.apache.solr.common.cloud.DocRouter;+import org.apache.solr.common.cloud.ImplicitDocRouter;+import org.apache.solr.common.cloud.Replica;+import org.apache.solr.common.cloud.Slice;+import org.apache.solr.common.cloud.ZkNodeProps;+import org.apache.solr.common.cloud.ZkStateReader;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;+import org.slf4j.Logger;+import org.slf4j.LoggerFactory;++public class AssignTest extends SolrTestCaseJ4 {+ protected static Logger log = LoggerFactory.getLogger(AssignTest.class);+++ @Override+ @Before+ public void setUp() throws Exception {+ super.setUp();++ }++ @Override+ @After+ public void tearDown() throws Exception {+ super.tearDown();+ }++ @Test+ public void testAssignNode() throws Exception {+ String cname = "collection1";++ Map<String,DocCollection> collectionStates = new HashMap<String,DocCollection>();++ Map<String,Slice> slices = new HashMap<String,Slice>();++ Map<String,Replica> replicas = new HashMap<String,Replica>();++ ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",+ ZkStateReader.STATE_PROP, "ACTIVE",+ ZkStateReader.BASE_URL_PROP, "0.0.0.0",+ ZkStateReader.CORE_NAME_PROP, "core1",+ ZkStateReader.ROLES_PROP, null,+ ZkStateReader.NODE_NAME_PROP, "0_0_0_0",+ ZkStateReader.SHARD_ID_PROP, "shard1",+ ZkStateReader.COLLECTION_PROP, cname,+ ZkStateReader.NUM_SHARDS_PROP, "1",+ ZkStateReader.CORE_NODE_NAME_PROP, "core_node1");+ Replica replica = new Replica("core_node1" , m.getProperties());+ replicas.put("core_node1", replica);++ Slice slice = new Slice("slice1", replicas , new HashMap<String,Object>(0));+ slices.put("slice1", slice);++ DocRouter router = new ImplicitDocRouter();+ DocCollection docCollection = new DocCollection(cname, slices, new HashMap<String,Object>(0), router);++ collectionStates.put(cname, docCollection);++ Set<String> liveNodes = new HashSet<String>();+ ClusterState state = new ClusterState(liveNodes, collectionStates);+ String nodeName = Assign.assignNode("collection1", state);++ assertEquals("core_node2", nodeName);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.javaindex c831f2ea19a..d95864770c0 100644--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZk2Test.java@@ -46,9 +46,7 @@ import org.apache.solr.common.cloud.ZkStateReader;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.params.ModifiableSolrParams;import org.apache.solr.common.util.NamedList;-import org.apache.solr.core.SolrCore;import org.apache.solr.handler.ReplicationHandler;-import org.apache.solr.servlet.SolrDispatchFilter;import org.apache.solr.util.AbstractSolrTestCase;import org.junit.BeforeClass;@@ -176,8 +174,8 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {createCmd.setCoreName(ONE_NODE_COLLECTION + "core");createCmd.setCollection(ONE_NODE_COLLECTION);createCmd.setNumShards(1);- createCmd.setDataDir(dataDir.getAbsolutePath() + File.separator- + ONE_NODE_COLLECTION);+ createCmd.setDataDir(getDataDir(dataDir.getAbsolutePath() + File.separator+ + ONE_NODE_COLLECTION));server.request(createCmd);} catch (Exception e) {e.printStackTrace();@@ -331,7 +329,7 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {ureq.process(cloudClient);} catch(SolrServerException e){// try again- Thread.sleep(500);+ Thread.sleep(3500);ureq.process(cloudClient);}@@ -415,14 +413,16 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {ModifiableSolrParams params = new ModifiableSolrParams();params.set("qt", "/replication");params.set("command", "backup");+ File location = new File(TEMP_DIR, BasicDistributedZk2Test.class.getName() + "-backupdir-" + System.currentTimeMillis());+ params.set("location", location.getAbsolutePath());QueryRequest request = new QueryRequest(params);NamedList<Object> results = client.request(request );- checkForBackupSuccess(client);+ checkForBackupSuccess(client, location);}- private void checkForBackupSuccess(final HttpSolrServer client)+ private void checkForBackupSuccess(final HttpSolrServer client, File location)throws InterruptedException, IOException {class CheckStatus extends Thread {volatile String fail = null;@@ -461,16 +461,6 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {};}- ;- SolrCore core = ((SolrDispatchFilter) shardToJetty.get(SHARD2).get(0).jetty- .getDispatchFilter().getFilter()).getCores().getCore("collection1");- String ddir;- try {- ddir = core.getDataDir();- } finally {- core.close();- }- File dataDir = new File(ddir);int waitCnt = 0;CheckStatus checkStatus = new CheckStatus();@@ -482,14 +472,14 @@ public class BasicDistributedZk2Test extends AbstractFullDistribZkTestBase {if (checkStatus.success) {break;}- Thread.sleep(200);- if (waitCnt == 20) {+ Thread.sleep(500);+ if (waitCnt == 90) {fail("Backup success not detected:" + checkStatus.response);}waitCnt++;}- File[] files = dataDir.listFiles(new FilenameFilter() {+ File[] files = location.listFiles(new FilenameFilter() {@Overridepublic boolean accept(File dir, String name) {diff --git a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.javaindex a9dadd1440b..dcb1ddb50f3 100644--- a/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/BasicDistributedZkTest.java@@ -538,11 +538,13 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {Create createCmd = new Create();createCmd.setCoreName(collection + freezeI);createCmd.setCollection(collection);- String core3dataDir = dataDir.getAbsolutePath() + File.separator- + System.currentTimeMillis() + collection + "_3n" + freezeI;- createCmd.setDataDir(core3dataDir);+createCmd.setNumShards(numShards);try {+ String core3dataDir = dataDir.getAbsolutePath() + File.separator+ + System.currentTimeMillis() + collection + "_3n" + freezeI;+ createCmd.setDataDir(getDataDir(core3dataDir));+server.request(createCmd);} catch (SolrServerException e) {throw new RuntimeException(e);@@ -574,11 +576,13 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {params.set(OverseerCollectionProcessor.MAX_SHARDS_PER_NODE, maxShardsPerNode);if (createNodeSetStr != null) params.set(OverseerCollectionProcessor.CREATE_NODE_SET, createNodeSetStr);- int clientIndex = random().nextInt(2);+ int clientIndex = clients.size() > 1 ? random().nextInt(2) : 0;List<Integer> list = new ArrayList<Integer>();list.add(numShards);list.add(numReplicas);- collectionInfos.put(collectionName, list);+ if (collectionInfos != null) {+ collectionInfos.put(collectionName, list);+ }params.set("name", collectionName);SolrRequest request = new QueryRequest(params);request.setPath("/admin/collections");@@ -932,8 +936,8 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {if (shardId == null) {createCmd.setNumShards(2);}- createCmd.setDataDir(dataDir.getAbsolutePath() + File.separator- + collection + num);+ createCmd.setDataDir(getDataDir(dataDir.getAbsolutePath() + File.separator+ + collection + num));if (shardId != null) {createCmd.setShardId(shardId);}@@ -1056,8 +1060,9 @@ public class BasicDistributedZkTest extends AbstractFullDistribZkTestBase {server.setSoTimeout(30000);Create createCmd = new Create();createCmd.setCoreName(collection);- createCmd.setDataDir(dataDir.getAbsolutePath() + File.separator- + collection + frozeUnique);+ createCmd.setDataDir(getDataDir(dataDir.getAbsolutePath() + File.separator+ + collection + frozeUnique));+server.request(createCmd);} catch (Exception e) {diff --git a/solr/core/src/test/org/apache/solr/cloud/ClusterStateUpdateTest.java b/solr/core/src/test/org/apache/solr/cloud/ClusterStateUpdateTest.javaindex 791c6bc1cbb..433d5c39b21 100644--- a/solr/core/src/test/org/apache/solr/cloud/ClusterStateUpdateTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ClusterStateUpdateTest.java@@ -71,11 +71,13 @@ public class ClusterStateUpdateTest extends SolrTestCaseJ4 {@BeforeClasspublic static void beforeClass() {System.setProperty("solrcloud.skip.autorecovery", "true");+ System.setProperty("genericCoreNodeNames", "false");}@AfterClasspublic static void afterClass() throws InterruptedException {System.clearProperty("solrcloud.skip.autorecovery");+ System.clearProperty("genericCoreNodeNames");}@Overridediff --git a/solr/core/src/test/org/apache/solr/cloud/OverseerTest.java b/solr/core/src/test/org/apache/solr/cloud/OverseerTest.javaindex 7cc550c83f5..e722f524ed4 100644--- a/solr/core/src/test/org/apache/solr/cloud/OverseerTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/OverseerTest.java@@ -36,6 +36,7 @@ import org.apache.lucene.util.LuceneTestCase.Slow;import org.apache.solr.SolrTestCaseJ4;import org.apache.solr.common.cloud.ClusterState;import org.apache.solr.common.cloud.DocCollection;+import org.apache.solr.common.cloud.Replica;import org.apache.solr.common.cloud.Slice;import org.apache.solr.common.cloud.SolrZkClient;import org.apache.solr.common.cloud.ZkNodeProps;@@ -98,7 +99,7 @@ public class OverseerTest extends SolrTestCaseJ4 {zkClient.close();}- public String publishState(String coreName, String stateName, int numShards)+ public String publishState(String coreName, String coreNodeName, String stateName, int numShards)throws KeeperException, InterruptedException, IOException {if (stateName == null) {ElectionContext ec = electionContext.remove(coreName);@@ -108,6 +109,7 @@ public class OverseerTest extends SolrTestCaseJ4 {ZkNodeProps m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "deletecore",ZkStateReader.NODE_NAME_PROP, nodeName,ZkStateReader.CORE_NAME_PROP, coreName,+ ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName,ZkStateReader.COLLECTION_PROP, collection);DistributedQueue q = Overseer.getInQueue(zkClient);q.offer(ZkStateReader.toJSON(m));@@ -117,6 +119,7 @@ public class OverseerTest extends SolrTestCaseJ4 {ZkStateReader.STATE_PROP, stateName,ZkStateReader.NODE_NAME_PROP, nodeName,ZkStateReader.CORE_NAME_PROP, coreName,+ ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName,ZkStateReader.COLLECTION_PROP, collection,ZkStateReader.NUM_SHARDS_PROP, Integer.toString(numShards),ZkStateReader.BASE_URL_PROP, "http://" + nodeName@@ -126,7 +129,8 @@ public class OverseerTest extends SolrTestCaseJ4 {}for (int i = 0; i < 120; i++) {- String shardId = getShardId(coreName);+ String shardId = getShardId("http://" + nodeName+ + "/solr/", coreName);if (shardId != null) {try {zkClient.makePath("/collections/" + collection + "/leader_elect/"@@ -136,7 +140,8 @@ public class OverseerTest extends SolrTestCaseJ4 {"http://" + nodeName + "/solr/", ZkStateReader.NODE_NAME_PROP,nodeName, ZkStateReader.CORE_NAME_PROP, coreName,ZkStateReader.SHARD_ID_PROP, shardId,- ZkStateReader.COLLECTION_PROP, collection);+ ZkStateReader.COLLECTION_PROP, collection,+ ZkStateReader.CORE_NODE_NAME_PROP, coreNodeName);ShardLeaderElectionContextBase ctx = new ShardLeaderElectionContextBase(elector, shardId, collection, nodeName + "_" + coreName, props,zkStateReader);@@ -148,13 +153,18 @@ public class OverseerTest extends SolrTestCaseJ4 {return null;}- private String getShardId(final String coreName) {+ private String getShardId(final String baseUrl, final String coreName) {Map<String,Slice> slices = zkStateReader.getClusterState().getSlicesMap(collection);if (slices != null) {for (Slice slice : slices.values()) {- if (slice.getReplicasMap().containsKey(nodeName + "_" + coreName)) {- return slice.getName();+ for (Replica replica : slice.getReplicas()) {+ // TODO: for really large clusters, we could 'index' on this+ String rbaseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);+ String rcore = replica.getStr(ZkStateReader.CORE_NAME_PROP);+ if (baseUrl.equals(rbaseUrl) && coreName.equals(rcore)) {+ return slice.getName();+ }}}}@@ -202,7 +212,7 @@ public class OverseerTest extends SolrTestCaseJ4 {final int numShards=6;for (int i = 0; i < numShards; i++) {- assertNotNull("shard got no id?", zkController.publishState("core" + (i+1), ZkStateReader.ACTIVE, 3));+ assertNotNull("shard got no id?", zkController.publishState("core" + (i+1), "node" + (i+1), ZkStateReader.ACTIVE, 3));}assertEquals(2, reader.getClusterState().getSlice("collection1", "shard1").getReplicasMap().size());@@ -277,7 +287,7 @@ public class OverseerTest extends SolrTestCaseJ4 {final String coreName = "core" + slot;try {- ids[slot]=controllers[slot % nodeCount].publishState(coreName, ZkStateReader.ACTIVE, sliceCount);+ ids[slot]=controllers[slot % nodeCount].publishState(coreName, "node" + slot, ZkStateReader.ACTIVE, sliceCount);} catch (Throwable e) {e.printStackTrace();fail("register threw exception:" + e.getClass());@@ -440,7 +450,7 @@ public class OverseerTest extends SolrTestCaseJ4 {assertEquals(reader.getClusterState().toString(), ZkStateReader.RECOVERING,reader.getClusterState().getSlice("collection1", "shard1").getReplicasMap()- .get("node1_core1").getStr(ZkStateReader.STATE_PROP));+ .get("core_node1").getStr(ZkStateReader.STATE_PROP));//publish node state (active)m = new ZkNodeProps(Overseer.QUEUE_OPERATION, "state",@@ -471,7 +481,7 @@ public class OverseerTest extends SolrTestCaseJ4 {while(maxIterations-->0) {Slice slice = reader.getClusterState().getSlice("collection1", "shard1");if(slice!=null) {- coreState = slice.getReplicasMap().get("node1_core1").getStr(ZkStateReader.STATE_PROP);+ coreState = slice.getReplicasMap().get("core_node1").getStr(ZkStateReader.STATE_PROP);if(coreState.equals(expectedState)) {return;}@@ -523,14 +533,14 @@ public class OverseerTest extends SolrTestCaseJ4 {overseerClient = electNewOverseer(server.getZkAddress());Thread.sleep(1000);- mockController.publishState("core1", ZkStateReader.RECOVERING, 1);+ mockController.publishState("core1", "core_node1", ZkStateReader.RECOVERING, 1);waitForCollections(reader, "collection1");verifyStatus(reader, ZkStateReader.RECOVERING);int version = getClusterStateVersion(controllerClient);- mockController.publishState("core1", ZkStateReader.ACTIVE, 1);+ mockController.publishState("core1", "core_node1", ZkStateReader.ACTIVE, 1);while(version == getClusterStateVersion(controllerClient));@@ -539,7 +549,7 @@ public class OverseerTest extends SolrTestCaseJ4 {overseerClient.close();Thread.sleep(1000); //wait for overseer to get killed- mockController.publishState("core1", ZkStateReader.RECOVERING, 1);+ mockController.publishState("core1", "core_node1", ZkStateReader.RECOVERING, 1);version = getClusterStateVersion(controllerClient);overseerClient = electNewOverseer(server.getZkAddress());@@ -553,7 +563,7 @@ public class OverseerTest extends SolrTestCaseJ4 {assertEquals("Shard count does not match", 1, reader.getClusterState().getSlice("collection1", "shard1").getReplicasMap().size());version = getClusterStateVersion(controllerClient);- mockController.publishState("core1", null,1);+ mockController.publishState("core1", "core_node1", null,1);while(version == getClusterStateVersion(controllerClient));Thread.sleep(500);assertFalse("collection1 should be gone after publishing the null state", reader.getClusterState().getCollections().contains("collection1"));@@ -641,16 +651,16 @@ public class OverseerTest extends SolrTestCaseJ4 {for (int i = 0; i < atLeast(4); i++) {killCounter.incrementAndGet(); //for each round allow 1 killmockController = new MockZKController(server.getZkAddress(), "node1", "collection1");- mockController.publishState("core1", "state1",1);+ mockController.publishState("core1", "node1", "state1",1);if(mockController2!=null) {mockController2.close();mockController2 = null;}- mockController.publishState("core1", "state2",1);+ mockController.publishState("core1", "node1","state2",1);mockController2 = new MockZKController(server.getZkAddress(), "node2", "collection1");- mockController.publishState("core1", "state1",1);+ mockController.publishState("core1", "node1", "state1",1);verifyShardLeader(reader, "collection1", "shard1", "core1");- mockController2.publishState("core4", "state2" ,1);+ mockController2.publishState("core4", "node2", "state2" ,1);mockController.close();mockController = null;verifyShardLeader(reader, "collection1", "shard1", "core4");@@ -697,7 +707,7 @@ public class OverseerTest extends SolrTestCaseJ4 {overseerClient = electNewOverseer(server.getZkAddress());- mockController.publishState("core1", ZkStateReader.RECOVERING, 1);+ mockController.publishState("core1", "core_node1", ZkStateReader.RECOVERING, 1);waitForCollections(reader, "collection1");@@ -708,7 +718,7 @@ public class OverseerTest extends SolrTestCaseJ4 {int version = getClusterStateVersion(controllerClient);mockController = new MockZKController(server.getZkAddress(), "node1", "collection1");- mockController.publishState("core1", ZkStateReader.RECOVERING, 1);+ mockController.publishState("core1", "core_node1", ZkStateReader.RECOVERING, 1);while (version == getClusterStateVersion(controllerClient));@@ -718,7 +728,7 @@ public class OverseerTest extends SolrTestCaseJ4 {int numFound = 0;for (DocCollection collection : state.getCollectionStates().values()) {for (Slice slice : collection.getSlices()) {- if (slice.getReplicasMap().get("node1_core1") != null) {+ if (slice.getReplicasMap().get("core_node1") != null) {numFound++;}}@@ -761,7 +771,7 @@ public class OverseerTest extends SolrTestCaseJ4 {overseerClient = electNewOverseer(server.getZkAddress());- mockController.publishState("core1", ZkStateReader.RECOVERING, 12);+ mockController.publishState("core1", "node1", ZkStateReader.RECOVERING, 12);waitForCollections(reader, "collection1");diff --git a/solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java b/solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.javaindex 2f7daebe226..28e473a39bb 100644--- a/solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/RecoveryZkTest.java@@ -86,19 +86,25 @@ public class RecoveryZkTest extends AbstractFullDistribZkTestBase {indexThread.join();indexThread2.join();- Thread.sleep(500);+ Thread.sleep(1000);- waitForThingsToLevelOut(30);+ waitForThingsToLevelOut(45);Thread.sleep(2000);waitForThingsToLevelOut(30);+ Thread.sleep(5000);+waitForRecoveriesToFinish(DEFAULT_COLLECTION, zkStateReader, false, true);// test that leader and replica have same doc count- checkShardConsistency("shard1", false, false);+ String fail = checkShardConsistency("shard1", false, false);+ if (fail != null) {+ fail(fail);+ }+SolrQuery query = new SolrQuery("*:*");query.setParam("distrib", "false");long client1Docs = shardToJetty.get("shard1").get(0).client.solrClient.query(query).getResults().getNumFound();diff --git a/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java b/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.javaindex 22948c43e3a..11cfb7c03c4 100644--- a/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/SyncSliceTest.java@@ -67,7 +67,6 @@ public class SyncSliceTest extends AbstractFullDistribZkTestBase {super.setUp();// we expect this time of exception as shards go up and down...//ignoreException(".*");- useFactory(null);System.setProperty("numShards", Integer.toString(sliceCount));}@@ -94,7 +93,7 @@ public class SyncSliceTest extends AbstractFullDistribZkTestBase {handle.put("QTime", SKIPVAL);handle.put("timestamp", SKIPVAL);- waitForThingsToLevelOut(15);+ waitForThingsToLevelOut(30);del("*:*");List<CloudJettyRunner> skipServers = new ArrayList<CloudJettyRunner>();diff --git a/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.javaindex 8b8593e3ad1..01e8045337d 100644--- a/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/UnloadDistributedZkTest.java@@ -91,7 +91,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCollection(collection);String coreDataDir = dataDir.getAbsolutePath() + File.separator+ System.currentTimeMillis() + collection + "1";- createCmd.setDataDir(coreDataDir);+ createCmd.setDataDir(getDataDir(coreDataDir));createCmd.setNumShards(2);SolrServer client = clients.get(0);@@ -107,7 +107,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCollection(collection);coreDataDir = dataDir.getAbsolutePath() + File.separator+ System.currentTimeMillis() + collection + "2";- createCmd.setDataDir(coreDataDir);+ createCmd.setDataDir(getDataDir(coreDataDir));server.request(createCmd);@@ -171,7 +171,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCollection("unloadcollection");createCmd.setNumShards(1);String core1DataDir = dataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "unloadcollection1" + "_1n";- createCmd.setDataDir(core1DataDir);+ createCmd.setDataDir(getDataDir(core1DataDir));server.request(createCmd);ZkStateReader zkStateReader = getCommonCloudSolrServer().getZkStateReader();@@ -189,7 +189,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCoreName("unloadcollection2");createCmd.setCollection("unloadcollection");String core2dataDir = dataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "unloadcollection1" + "_2n";- createCmd.setDataDir(core2dataDir);+ createCmd.setDataDir(getDataDir(core2dataDir));server.request(createCmd);zkStateReader.updateClusterState(true);@@ -227,7 +227,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCoreName("unloadcollection3");createCmd.setCollection("unloadcollection");String core3dataDir = dataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "unloadcollection" + "_3n";- createCmd.setDataDir(core3dataDir);+ createCmd.setDataDir(getDataDir(core3dataDir));server.request(createCmd);waitForRecoveriesToFinish("unloadcollection", zkStateReader, false);@@ -296,7 +296,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd.setCoreName("unloadcollection4");createCmd.setCollection("unloadcollection");String core4dataDir = dataDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + "unloadcollection" + "_4n";- createCmd.setDataDir(core4dataDir);+ createCmd.setDataDir(getDataDir(core4dataDir));server.request(createCmd);waitForRecoveriesToFinish("unloadcollection", zkStateReader, false);@@ -334,7 +334,7 @@ public class UnloadDistributedZkTest extends BasicDistributedZkTest {createCmd = new Create();createCmd.setCoreName(leaderProps.getCoreName());createCmd.setCollection("unloadcollection");- createCmd.setDataDir(core1DataDir);+ createCmd.setDataDir(getDataDir(core1DataDir));server.request(createCmd);waitForRecoveriesToFinish("unloadcollection", zkStateReader, false);diff --git a/solr/core/src/test/org/apache/solr/cloud/ZkControllerTest.java b/solr/core/src/test/org/apache/solr/cloud/ZkControllerTest.javaindex dc930eade56..530b4b55b31 100644--- a/solr/core/src/test/org/apache/solr/cloud/ZkControllerTest.java+++ b/solr/core/src/test/org/apache/solr/cloud/ZkControllerTest.java@@ -163,7 +163,7 @@ public class ZkControllerTest extends SolrTestCaseJ4 {cc = getCoreContainer();ZkController zkController = new ZkController(cc, server.getZkAddress(), TIMEOUT, 10000,- "127.0.0.1", "8983", "solr", "0", 10000, 10000, new CurrentCoreDescriptorProvider() {+ "127.0.0.1", "8983", "solr", "0", true, 10000, 10000, new CurrentCoreDescriptorProvider() {@Overridepublic List<CoreDescriptor> getCurrentDescriptors() {@@ -203,7 +203,7 @@ public class ZkControllerTest extends SolrTestCaseJ4 {cc = getCoreContainer();zkController = new ZkController(cc, server.getZkAddress(),- TIMEOUT, 10000, "127.0.0.1", "8983", "solr", "0", 10000, 10000, new CurrentCoreDescriptorProvider() {+ TIMEOUT, 10000, "127.0.0.1", "8983", "solr", "0", true, 10000, 10000, new CurrentCoreDescriptorProvider() {@Overridepublic List<CoreDescriptor> getCurrentDescriptors() {diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/BasicHdfsTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/BasicHdfsTest.javanew file mode 100644index 00000000000..dd14e615b20--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/BasicHdfsTest.java@@ -0,0 +1,106 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++package org.apache.solr.cloud.hdfs;++import java.io.File;+import java.io.IOException;+import java.net.URI;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.client.solrj.SolrQuery;+import org.apache.solr.client.solrj.request.QueryRequest;+import org.apache.solr.cloud.BasicDistributedZkTest;+import org.apache.solr.common.params.CollectionParams.CollectionAction;+import org.apache.solr.common.params.ModifiableSolrParams;+import org.apache.solr.common.util.NamedList;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class BasicHdfsTest extends BasicDistributedZkTest {++ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {++ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ System.setProperty("solr.hdfs.home", dfsCluster.getURI().toString() + "/solr");+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ System.clearProperty("solr.hdfs.home");+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++ public BasicHdfsTest() {+ super();+ sliceCount = 1;+ shardCount = 1;+ }++ protected String getSolrXml() {+ return "solr-no-core.xml";+ }++ @Override+ public void doTest() throws Exception {+ createCollection("delete_data_dir", 1, 1, 1);+ waitForRecoveriesToFinish("delete_data_dir", false);+ cloudClient.setDefaultCollection("delete_data_dir");+ cloudClient.getZkStateReader().updateClusterState(true);+ NamedList<Object> response = cloudClient.query(+ new SolrQuery().setRequestHandler("/admin/system")).getResponse();+ NamedList<Object> coreInfo = (NamedList<Object>) response.get("core");+ String dataDir = (String) ((NamedList<Object>) coreInfo.get("directory"))+ .get("data");++ ModifiableSolrParams params = new ModifiableSolrParams();+ params.set("action", CollectionAction.DELETE.toString());+ params.set("name", "delete_data_dir");+ QueryRequest request = new QueryRequest(params);+ request.setPath("/admin/collections");+ cloudClient.request(request);++ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs = FileSystem.newInstance(new URI(dataDir), conf);+ assertFalse(+ "Data directory exists after collection removal : "+ + dataDir, fs.exists(new Path(dataDir)));+ fs.close();+ }+}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.javanew file mode 100644index 00000000000..2e343eb4cdf--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZk2Test.java@@ -0,0 +1,58 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.BasicDistributedZk2Test;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsBasicDistributedZk2Test extends BasicDistributedZk2Test {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.javanew file mode 100644index 00000000000..8f7486d5ad0--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsBasicDistributedZkTest.java@@ -0,0 +1,58 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.BasicDistributedZkTest;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsBasicDistributedZkTest extends BasicDistributedZkTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsChaosMonkeySafeLeaderTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsChaosMonkeySafeLeaderTest.javanew file mode 100644index 00000000000..7e49963a226--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsChaosMonkeySafeLeaderTest.java@@ -0,0 +1,69 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.ChaosMonkeySafeLeaderTest;+import org.junit.AfterClass;+import org.junit.Before;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsChaosMonkeySafeLeaderTest extends ChaosMonkeySafeLeaderTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }++ @Before+ @Override+ public void setUp() throws Exception {+ super.setUp();++ // super class may hard code directory+ useFactory("org.apache.solr.core.HdfsDirectoryFactory");+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }+++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsCollectionsAPIDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsCollectionsAPIDistributedZkTest.javanew file mode 100644index 00000000000..226df65c8a7--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsCollectionsAPIDistributedZkTest.java@@ -0,0 +1,64 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.CollectionsAPIDistributedZkTest;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsCollectionsAPIDistributedZkTest extends CollectionsAPIDistributedZkTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsCollectionsAPIDistributedZkTest.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());++ System.setProperty("solr.hdfs.home", dfsCluster.getURI().toString() + "/solr");+ System.setProperty("solr.hdfs.blockcache.enabled", "false");++ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ System.clearProperty("solr.hdfs.home");+ System.clearProperty("solr.hdfs.blockcache.enabled");+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsRecoveryZkTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsRecoveryZkTest.javanew file mode 100644index 00000000000..c9ee82f5100--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsRecoveryZkTest.java@@ -0,0 +1,59 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.RecoveryZkTest;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsRecoveryZkTest extends RecoveryZkTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ System.setProperty("solr.hdfs.blockcache.blocksperbank", "2048");+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsSyncSliceTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsSyncSliceTest.javanew file mode 100644index 00000000000..f0a73bd1955--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsSyncSliceTest.java@@ -0,0 +1,66 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;+import java.util.Locale;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.SyncSliceTest;+import org.junit.AfterClass;+import org.junit.Before;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsSyncSliceTest extends SyncSliceTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }++ @Before+ @Override+ public void setUp() throws Exception {+ super.setUp();+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTestUtil.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTestUtil.javanew file mode 100644index 00000000000..83ad3c19a0b--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsTestUtil.java@@ -0,0 +1,82 @@+package org.apache.solr.cloud.hdfs;++import java.io.File;+import java.io.IOException;+import java.net.URI;+import java.util.Locale;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.solr.SolrTestCaseJ4;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++public class HdfsTestUtil {++ private static Locale savedLocale;++ public static MiniDFSCluster setupClass(String dataDir) throws Exception {+ savedLocale = Locale.getDefault();+ // TODO: we HACK around HADOOP-9643+ Locale.setDefault(Locale.ENGLISH);++ int dataNodes = 2;++ Configuration conf = new Configuration();+ conf.set("dfs.block.access.token.enable", "false");+ conf.set("dfs.permissions.enabled", "false");+ conf.set("hadoop.security.authentication", "simple");+ conf.set("hdfs.minidfs.basedir", dataDir + File.separator + "hdfsBaseDir");+ conf.set("dfs.namenode.name.dir", dataDir + File.separator + "nameNodeNameDir");+++ System.setProperty("test.build.data", dataDir + File.separator + "hdfs" + File.separator + "build");+ System.setProperty("test.cache.data", dataDir + File.separator + "hdfs" + File.separator + "cache");+ System.setProperty("solr.lock.type", "hdfs");++ MiniDFSCluster dfsCluster = new MiniDFSCluster(conf, dataNodes, true, null);++ SolrTestCaseJ4.useFactory("org.apache.solr.core.HdfsDirectoryFactory");++ return dfsCluster;+ }++ public static void teardownClass(MiniDFSCluster dfsCluster) throws Exception {+ SolrTestCaseJ4.resetFactory();+ System.clearProperty("solr.lock.type");+ System.clearProperty("test.build.data");+ System.clearProperty("test.cache.data");+ if (dfsCluster != null) {+ dfsCluster.shutdown();+ }++ // TODO: we HACK around HADOOP-9643+ Locale.setDefault(savedLocale);+ }++ public static String getDataDir(MiniDFSCluster dfsCluster, String dataDir)+ throws IOException {+ URI uri = dfsCluster.getURI();+ String dir = uri.toString()+ + "/"+ + new File(dataDir).toString().replaceAll(":", "_")+ .replaceAll("/", "_");+ return dir;+ }++}diff --git a/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsUnloadDistributedZkTest.java b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsUnloadDistributedZkTest.javanew file mode 100644index 00000000000..7f89b79e94a--- /dev/null+++ b/solr/core/src/test/org/apache/solr/cloud/hdfs/HdfsUnloadDistributedZkTest.java@@ -0,0 +1,58 @@+package org.apache.solr.cloud.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;++import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.util.LuceneTestCase.Slow;+import org.apache.solr.cloud.UnloadDistributedZkTest;+import org.junit.AfterClass;+import org.junit.BeforeClass;++import com.carrotsearch.randomizedtesting.annotations.Nightly;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@Slow+@Nightly+@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread(s)+public class HdfsUnloadDistributedZkTest extends UnloadDistributedZkTest {+ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void setupClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsUnloadDistributedZkTest.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ }++ @AfterClass+ public static void teardownClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }+++ @Override+ protected String getDataDir(String dataDir) throws IOException {+ return HdfsTestUtil.getDataDir(dfsCluster, dataDir);+ }++}diff --git a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.javaindex 8c591c96238..c52772cf43e 100644--- a/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java+++ b/solr/core/src/test/org/apache/solr/handler/TestReplicationHandler.java@@ -1507,7 +1507,7 @@ public class TestReplicationHandler extends SolrTestCaseJ4 {}public String getDataDir() {- return dataDir.toString();+ return dataDir.getAbsolutePath();}public String getSolrConfigFile() {diff --git a/solr/core/src/test/org/apache/solr/search/TestRecovery.java b/solr/core/src/test/org/apache/solr/search/TestRecovery.javaindex 5555dfd5aab..4b5ed59259d 100644--- a/solr/core/src/test/org/apache/solr/search/TestRecovery.java+++ b/solr/core/src/test/org/apache/solr/search/TestRecovery.java@@ -17,6 +17,8 @@package org.apache.solr.search;+import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;+import org.apache.solr.common.SolrException;import org.noggit.ObjectBuilder;import org.apache.solr.SolrTestCaseJ4;@@ -42,8 +44,16 @@ import java.util.concurrent.Future;import java.util.concurrent.Semaphore;import java.util.concurrent.TimeUnit;-import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;-import static org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.update.DirectUpdateHandler2;+import org.apache.solr.update.UpdateHandler;+import org.apache.solr.update.UpdateLog;+import org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase;+import org.junit.AfterClass;+import org.junit.BeforeClass;+import org.junit.Test;+import org.noggit.ObjectBuilder;public class TestRecovery extends SolrTestCaseJ4 {@@ -744,16 +754,17 @@ public class TestRecovery extends SolrTestCaseJ4 {clearIndex();assertU(commit());- File logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();+ File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());h.close();- String[] files = UpdateLog.getLogList(logDir);+ String[] files = ulog.getLogList(logDir);for (String file : files) {new File(logDir, file).delete();}- assertEquals(0, UpdateLog.getLogList(logDir).length);+ assertEquals(0, ulog.getLogList(logDir).length);createCore();@@ -771,7 +782,7 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(commit());assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));- assertEquals(2, UpdateLog.getLogList(logDir).length);+ assertEquals(2, ulog.getLogList(logDir).length);addDocs(105, start, versions); start+=105;assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));@@ -779,7 +790,7 @@ public class TestRecovery extends SolrTestCaseJ4 {assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));// previous two logs should be gone now- assertEquals(1, UpdateLog.getLogList(logDir).length);+ assertEquals(1, ulog.getLogList(logDir).length);addDocs(1, start, versions); start+=1;h.close();@@ -799,14 +810,14 @@ public class TestRecovery extends SolrTestCaseJ4 {assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));// previous logs should be gone now- assertEquals(1, UpdateLog.getLogList(logDir).length);+ assertEquals(1, ulog.getLogList(logDir).length);//// test that a corrupt tlog file doesn't stop us from coming up, or seeing versions before that tlog file.//addDocs(1, start, new LinkedList<Long>()); // don't add this to the versions list because we are going to lose it...h.close();- files = UpdateLog.getLogList(logDir);+ files = ulog.getLogList(logDir);Arrays.sort(files);RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");raf.writeChars("This is a trashed log file that really shouldn't work at all, but we'll see...");@@ -854,7 +865,8 @@ public class TestRecovery extends SolrTestCaseJ4 {}};- File logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();+ File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());clearIndex();assertU(commit());@@ -864,7 +876,7 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(adoc("id","F3"));h.close();- String[] files = UpdateLog.getLogList(logDir);+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");raf.seek(raf.length()); // seek to end@@ -908,7 +920,8 @@ public class TestRecovery extends SolrTestCaseJ4 {try {DirectUpdateHandler2.commitOnClose = false;- File logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();+ File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());clearIndex();assertU(commit());@@ -920,7 +933,7 @@ public class TestRecovery extends SolrTestCaseJ4 {h.close();- String[] files = UpdateLog.getLogList(logDir);+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);RandomAccessFile raf = new RandomAccessFile(new File(logDir, files[files.length-1]), "rw");long len = raf.length();@@ -991,7 +1004,8 @@ public class TestRecovery extends SolrTestCaseJ4 {}};- File logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();+ File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());clearIndex();assertU(commit());@@ -1001,7 +1015,7 @@ public class TestRecovery extends SolrTestCaseJ4 {assertU(adoc("id","CCCCCC"));h.close();- String[] files = UpdateLog.getLogList(logDir);+ String[] files = ulog.getLogList(logDir);Arrays.sort(files);String fname = files[files.length-1];RandomAccessFile raf = new RandomAccessFile(new File(logDir, fname), "rw");@@ -1071,17 +1085,18 @@ public class TestRecovery extends SolrTestCaseJ4 {// stops the core, removes the transaction logs, restarts the core.void deleteLogs() throws Exception {- File logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ UpdateLog ulog = h.getCore().getUpdateHandler().getUpdateLog();+ File logDir = new File(h.getCore().getUpdateHandler().getUpdateLog().getLogDir());h.close();try {- String[] files = UpdateLog.getLogList(logDir);+ String[] files = ulog.getLogList(logDir);for (String file : files) {new File(logDir, file).delete();}- assertEquals(0, UpdateLog.getLogList(logDir).length);+ assertEquals(0, ulog.getLogList(logDir).length);} finally {// make sure we create the core again, even if the assert fails so it won't mess// up the next test.diff --git a/solr/core/src/test/org/apache/solr/search/TestRecoveryHdfs.java b/solr/core/src/test/org/apache/solr/search/TestRecoveryHdfs.javanew file mode 100644index 00000000000..a786702222f--- /dev/null+++ b/solr/core/src/test/org/apache/solr/search/TestRecoveryHdfs.java@@ -0,0 +1,1176 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */+package org.apache.solr.search;+++import static org.apache.solr.update.processor.DistributingUpdateProcessorFactory.DISTRIB_UPDATE_PARAM;++import java.io.File;+import java.io.IOException;+import java.net.URI;+import java.net.URISyntaxException;+import java.util.ArrayDeque;+import java.util.Arrays;+import java.util.Deque;+import java.util.LinkedList;+import java.util.List;+import java.util.Locale;+import java.util.Map;+import java.util.concurrent.Future;+import java.util.concurrent.Semaphore;+import java.util.concurrent.TimeUnit;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.FSDataInputStream;+import org.apache.hadoop.fs.FSDataOutputStream;+import org.apache.hadoop.fs.FileSystem;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.cloud.hdfs.HdfsBasicDistributedZk2Test;+import org.apache.solr.cloud.hdfs.HdfsTestUtil;+import org.apache.solr.request.SolrQueryRequest;+import org.apache.solr.update.DirectUpdateHandler2;+import org.apache.solr.update.HdfsUpdateLog;+import org.apache.solr.update.UpdateHandler;+import org.apache.solr.update.UpdateLog;+import org.apache.solr.update.processor.DistributedUpdateProcessor.DistribPhase;+import org.junit.AfterClass;+import org.junit.BeforeClass;+import org.junit.Ignore;+import org.junit.Test;+import org.noggit.ObjectBuilder;++import com.carrotsearch.randomizedtesting.annotations.ThreadLeakLingering;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@ThreadLeakScope(Scope.NONE) // hdfs mini cluster currently leaks threads+@ThreadLeakLingering(linger = 0)+// TODO: longer term this should be combined with TestRecovery somehow+public class TestRecoveryHdfs extends SolrTestCaseJ4 {++ // means that we've seen the leader and have version info (i.e. we are a non-leader replica)+ private static String FROM_LEADER = DistribPhase.FROMLEADER.toString();++ private static int timeout=60; // acquire timeout in seconds. change this to a huge number when debugging to prevent threads from advancing.++ private static MiniDFSCluster dfsCluster;++ private static String hdfsUri;++ @BeforeClass+ public static void beforeClass() throws Exception {+ dfsCluster = HdfsTestUtil.setupClass(new File(TEMP_DIR,+ HdfsBasicDistributedZk2Test.class.getName() + "_"+ + System.currentTimeMillis()).getAbsolutePath());+ hdfsUri = dfsCluster.getFileSystem().getUri().toString();++ hdfsDataDir = hdfsUri + "/solr/shard1";+ System.setProperty("solr.data.dir", hdfsUri + "/solr/shard1");+ System.setProperty("solr.ulog.dir", hdfsUri + "/solr/shard1");++ initCore("solrconfig-tlog.xml","schema15.xml");+ }++ @AfterClass+ public static void afterClass() throws Exception {+ System.clearProperty("solr.ulog.dir");+ System.clearProperty("solr.data.dir");+ System.clearProperty("test.build.data");+ System.clearProperty("test.cache.data");+ hdfsDataDir = null;+ dfsCluster = null;+ HdfsTestUtil.teardownClass(dfsCluster);+ FileSystem.closeAll();+ }++ // since we make up fake versions in these tests, we can get messed up by a DBQ with a real version+ // since Solr can think following updates were reordered.+ @Override+ public void clearIndex() {+ try {+ deleteByQueryAndGetVersion("*:*", params("_version_", Long.toString(-Long.MAX_VALUE), DISTRIB_UPDATE_PARAM,FROM_LEADER));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+++ @Test+ public void testLogReplay() throws Exception {+ try {++ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ clearIndex();+ assertU(commit());++ Deque<Long> versions = new ArrayDeque<Long>();+ versions.addFirst(addAndGetVersion(sdoc("id", "A1"), null));+ versions.addFirst(addAndGetVersion(sdoc("id", "A11"), null));+ versions.addFirst(addAndGetVersion(sdoc("id", "A12"), null));+ versions.addFirst(deleteByQueryAndGetVersion("id:A11", null));+ versions.addFirst(addAndGetVersion(sdoc("id", "A13"), null));++ assertJQ(req("q","*:*"),"/response/numFound==0");++ assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);++ h.close();+ createCore();+ // Solr should kick this off now+ // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();++ // verify that previous close didn't do a commit+ // recovery should be blocked by our hook+ assertJQ(req("q","*:*") ,"/response/numFound==0");++ // make sure we can still access versions after a restart+ assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);++ // unblock recovery+ logReplay.release(1000);++ // make sure we can still access versions during recovery+ assertJQ(req("qt","/get", "getVersions",""+versions.size()),"/versions==" + versions);++ // wait until recovery has finished+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));++ assertJQ(req("q","*:*") ,"/response/numFound==3");++ // make sure we can still access versions after recovery+ assertJQ(req("qt","/get", "getVersions",""+versions.size()) ,"/versions==" + versions);++ assertU(adoc("id","A2"));+ assertU(adoc("id","A3"));+ assertU(delI("A2"));+ assertU(adoc("id","A4"));++ assertJQ(req("q","*:*") ,"/response/numFound==3");++ h.close();+ createCore();+ // Solr should kick this off now+ // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();++ // wait until recovery has finished+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));+ assertJQ(req("q","*:*") ,"/response/numFound==5");+ assertJQ(req("q","id:A2") ,"/response/numFound==0");++ // no updates, so insure that recovery does not run+ h.close();+ int permits = logReplay.availablePermits();+ createCore();+ // Solr should kick this off now+ // h.getCore().getUpdateHandler().getUpdateLog().recoverFromLog();++ assertJQ(req("q","*:*") ,"/response/numFound==5");+ Thread.sleep(100);+ assertEquals(permits, logReplay.availablePermits()); // no updates, so insure that recovery didn't run++ assertEquals(UpdateLog.State.ACTIVE, h.getCore().getUpdateHandler().getUpdateLog().getState());++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;+ }++ }++ @Test+ public void testBuffering() throws Exception {++ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ SolrQueryRequest req = req();+ UpdateHandler uhandler = req.getCore().getUpdateHandler();+ UpdateLog ulog = uhandler.getUpdateLog();++ try {+ clearIndex();+ assertU(commit());++ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());+ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());+ Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates();+ assertTrue(rinfoFuture == null);+ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());++ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());++ // simulate updates from a leader+ updateJ(jsonAdd(sdoc("id","B1", "_version_","1010")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","B11", "_version_","1015")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonDelQ("id:B1 id:B11 id:B2 id:B3"), params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-1017"));+ updateJ(jsonAdd(sdoc("id","B2", "_version_","1020")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","B3", "_version_","1030")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ deleteAndGetVersion("B1", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-2010"));++ assertJQ(req("qt","/get", "getVersions","6")+ ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"+ );++ assertU(commit());++ assertJQ(req("qt","/get", "getVersions","6")+ ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"+ );++ // updates should be buffered, so we should not see any results yet.+ assertJQ(req("q", "*:*")+ , "/response/numFound==0"+ );++ // real-time get should also not show anything (this could change in the future,+ // but it's currently used for validating version numbers too, so it would+ // be bad for updates to be visible if we're just buffering.+ assertJQ(req("qt","/get", "id","B3")+ ,"=={'doc':null}"+ );+++ rinfoFuture = ulog.applyBufferedUpdates();+ assertTrue(rinfoFuture != null);++ assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState());++ logReplay.release(1000);++ UpdateLog.RecoveryInfo rinfo = rinfoFuture.get();+ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());+++ assertJQ(req("qt","/get", "getVersions","6")+ ,"=={'versions':[-2010,1030,1020,-1017,1015,1010]}"+ );+++ assertJQ(req("q", "*:*")+ , "/response/numFound==2"+ );++ // move back to recovering+ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());++ Long ver = getVer(req("qt","/get", "id","B3"));+ assertEquals(1030L, ver.longValue());++ // add a reordered doc that shouldn't overwrite one in the index+ updateJ(jsonAdd(sdoc("id","B3", "_version_","3")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ // reorder two buffered updates+ updateJ(jsonAdd(sdoc("id","B4", "_version_","1040")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ deleteAndGetVersion("B4", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-940")); // this update should not take affect+ updateJ(jsonAdd(sdoc("id","B6", "_version_","1060")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","B5", "_version_","1050")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","B8", "_version_","1080")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ // test that delete by query is at least buffered along with everything else so it will delete the+ // currently buffered id:8 (even if it doesn't currently support versioning)+ updateJ("{\"delete\": { \"query\":\"id:B2 OR id:B8\" }}", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-3000"));++ assertJQ(req("qt","/get", "getVersions","13")+ ,"=={'versions':[-3000,1080,1050,1060,-940,1040,3,-2010,1030,1020,-1017,1015,1010]}" // the "3" appears because versions aren't checked while buffering+ );++ logReplay.drainPermits();+ rinfoFuture = ulog.applyBufferedUpdates();+ assertTrue(rinfoFuture != null);+ assertEquals(UpdateLog.State.APPLYING_BUFFERED, ulog.getState());++ // apply a single update+ logReplay.release(1);++ // now add another update+ updateJ(jsonAdd(sdoc("id","B7", "_version_","1070")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ // a reordered update that should be dropped+ deleteAndGetVersion("B5", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-950"));++ deleteAndGetVersion("B6", params(DISTRIB_UPDATE_PARAM,FROM_LEADER, "_version_","-2060"));++ logReplay.release(1000);+ UpdateLog.RecoveryInfo recInfo = rinfoFuture.get();++ assertJQ(req("q", "*:*", "sort","id asc", "fl","id,_version_")+ , "/response/docs==["+ + "{'id':'B3','_version_':1030}"+ + ",{'id':'B4','_version_':1040}"+ + ",{'id':'B5','_version_':1050}"+ + ",{'id':'B7','_version_':1070}"+ +"]"+ );++ assertEquals(1, recInfo.deleteByQuery);++ assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state+ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;++ req().close();+ }++ }+++ @Test+ @Ignore("HDFS-3107: no truncate support yet")+ public void testDropBuffered() throws Exception {++ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ SolrQueryRequest req = req();+ UpdateHandler uhandler = req.getCore().getUpdateHandler();+ UpdateLog ulog = uhandler.getUpdateLog();++ try {+ clearIndex();+ assertU(commit());++ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());+ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());+ Future<UpdateLog.RecoveryInfo> rinfoFuture = ulog.applyBufferedUpdates();+ assertTrue(rinfoFuture == null);+ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());++ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());++ // simulate updates from a leader+ updateJ(jsonAdd(sdoc("id","C1", "_version_","101")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C2", "_version_","102")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C3", "_version_","103")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ assertTrue(ulog.dropBufferedUpdates());+ ulog.bufferUpdates();+ updateJ(jsonAdd(sdoc("id", "C4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id", "C5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ logReplay.release(1000);+ rinfoFuture = ulog.applyBufferedUpdates();+ UpdateLog.RecoveryInfo rinfo = rinfoFuture.get();+ assertEquals(2, rinfo.adds);++ assertJQ(req("qt","/get", "getVersions","2")+ ,"=={'versions':[105,104]}"+ );++ // this time add some docs first before buffering starts (so tlog won't be at pos 0)+ updateJ(jsonAdd(sdoc("id","C100", "_version_","200")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C101", "_version_","201")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ ulog.bufferUpdates();+ updateJ(jsonAdd(sdoc("id","C103", "_version_","203")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C104", "_version_","204")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ assertTrue(ulog.dropBufferedUpdates());+ ulog.bufferUpdates();+ updateJ(jsonAdd(sdoc("id","C105", "_version_","205")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C106", "_version_","206")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ rinfoFuture = ulog.applyBufferedUpdates();+ rinfo = rinfoFuture.get();+ assertEquals(2, rinfo.adds);++ assertJQ(req("q", "*:*", "sort","_version_ asc", "fl","id,_version_")+ , "/response/docs==["+ + "{'id':'C4','_version_':104}"+ + ",{'id':'C5','_version_':105}"+ + ",{'id':'C100','_version_':200}"+ + ",{'id':'C101','_version_':201}"+ + ",{'id':'C105','_version_':205}"+ + ",{'id':'C106','_version_':206}"+ +"]"+ );++ assertJQ(req("qt","/get", "getVersions","6")+ ,"=={'versions':[206,205,201,200,105,104]}"+ );++ ulog.bufferUpdates();+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());+ updateJ(jsonAdd(sdoc("id","C301", "_version_","998")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C302", "_version_","999")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ assertTrue(ulog.dropBufferedUpdates());++ // make sure we can overwrite with a lower version+ // TODO: is this functionality needed?+ updateJ(jsonAdd(sdoc("id","C301", "_version_","301")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","C302", "_version_","302")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ assertU(commit());++ assertJQ(req("qt","/get", "getVersions","2")+ ,"=={'versions':[302,301]}"+ );++ assertJQ(req("q", "*:*", "sort","_version_ desc", "fl","id,_version_", "rows","2")+ , "/response/docs==["+ + "{'id':'C302','_version_':302}"+ + ",{'id':'C301','_version_':301}"+ +"]"+ );+++ updateJ(jsonAdd(sdoc("id","C2", "_version_","302")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+++++ assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state+ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;++ req().close();+ }++ }+++ @Test+ public void testBufferingFlags() throws Exception {++ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ SolrQueryRequest req = req();+ UpdateHandler uhandler = req.getCore().getUpdateHandler();+ UpdateLog ulog = uhandler.getUpdateLog();++ try {+ clearIndex();+ assertU(commit());++ assertEquals(UpdateLog.State.ACTIVE, ulog.getState());+ ulog.bufferUpdates();++ // simulate updates from a leader+ updateJ(jsonAdd(sdoc("id","Q1", "_version_","101")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","Q2", "_version_","102")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","Q3", "_version_","103")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ assertEquals(UpdateLog.State.BUFFERING, ulog.getState());++ req.close();+ h.close();+ createCore();++ req = req();+ uhandler = req.getCore().getUpdateHandler();+ ulog = uhandler.getUpdateLog();++ logReplayFinish.acquire(); // wait for replay to finish++ assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) != 0); // since we died while buffering, we should see this last++ //+ // Try again to ensure that the previous log replay didn't wipe out our flags+ //++ req.close();+ h.close();+ createCore();++ req = req();+ uhandler = req.getCore().getUpdateHandler();+ ulog = uhandler.getUpdateLog();++ assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) != 0);++ // now do some normal non-buffered adds+ updateJ(jsonAdd(sdoc("id","Q4", "_version_","114")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","Q5", "_version_","115")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","Q6", "_version_","116")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ assertU(commit());++ req.close();+ h.close();+ createCore();++ req = req();+ uhandler = req.getCore().getUpdateHandler();+ ulog = uhandler.getUpdateLog();++ assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) == 0);++ ulog.bufferUpdates();+ // simulate receiving no updates+ ulog.applyBufferedUpdates();+ updateJ(jsonAdd(sdoc("id","Q7", "_version_","117")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER)); // do another add to make sure flags are back to normal++ req.close();+ h.close();+ createCore();++ req = req();+ uhandler = req.getCore().getUpdateHandler();+ ulog = uhandler.getUpdateLog();++ assertTrue((ulog.getStartingOperation() & UpdateLog.FLAG_GAP) == 0); // check flags on Q7++ logReplayFinish.acquire();+ assertEquals(UpdateLog.State.ACTIVE, ulog.getState()); // leave each test method in a good state+ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;++ req().close();+ }++ }++++ // make sure that on a restart, versions don't start too low+ @Test+ public void testVersionsOnRestart() throws Exception {+ clearIndex();+ assertU(commit());++ assertU(adoc("id","D1", "val_i","1"));+ assertU(adoc("id","D2", "val_i","1"));+ assertU(commit());+ long v1 = getVer(req("q","id:D1"));+ long v1a = getVer(req("q","id:D2"));++ h.close();+ createCore();++ assertU(adoc("id","D1", "val_i","2"));+ assertU(commit());+ long v2 = getVer(req("q","id:D1"));++ assert(v2 > v1);++ assertJQ(req("qt","/get", "getVersions","2")+ ,"/versions==[" + v2 + "," + v1a + "]"+ );++ }++ // make sure that log isn't needlessly replayed after a clean shutdown+ @Test+ public void testCleanShutdown() throws Exception {+ DirectUpdateHandler2.commitOnClose = true;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ SolrQueryRequest req = req();+ UpdateHandler uhandler = req.getCore().getUpdateHandler();+ UpdateLog ulog = uhandler.getUpdateLog();++ try {+ clearIndex();+ assertU(commit());++ assertU(adoc("id","E1", "val_i","1"));+ assertU(adoc("id","E2", "val_i","1"));++ // set to a high enough number so this test won't hang on a bug+ logReplay.release(10);++ h.close();+ createCore();++ // make sure the docs got committed+ assertJQ(req("q","*:*"),"/response/numFound==2");++ // make sure no replay happened+ assertEquals(10, logReplay.availablePermits());++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;++ req().close();+ }+ }+++ private void addDocs(int nDocs, int start, LinkedList<Long> versions) throws Exception {+ for (int i=0; i<nDocs; i++) {+ versions.addFirst( addAndGetVersion( sdoc("id",Integer.toString(start + nDocs)) , null) );+ }+ }++ @Test+ public void testRemoveOldLogs() throws Exception {+ try {+ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };+++ clearIndex();+ assertU(commit());++ String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+++ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs;+ try {+ URI uri = new URI(hdfsUri);+ fs = FileSystem.newInstance(uri, conf);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } catch (URISyntaxException e) {+ throw new RuntimeException(e);+ }++ h.close();++ String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir));+ for (String file : files) {+ fs.delete(new Path(logDir, file), false);+ }++ assertEquals(0, HdfsUpdateLog.getLogList(fs, new Path(logDir)).length);++ createCore();++ int start = 0;+ int maxReq = 50;++ LinkedList<Long> versions = new LinkedList<Long>();+ addDocs(10, start, versions); start+=10;+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));+ assertU(commit());+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ addDocs(10, start, versions); start+=10;+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));+ assertU(commit());+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ assertEquals(2, HdfsUpdateLog.getLogList(fs, new Path(logDir)).length);++ addDocs(105, start, versions); start+=105;+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));+ assertU(commit());+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ // previous two logs should be gone now+ assertEquals(1, HdfsUpdateLog.getLogList(fs, new Path(logDir)).length);++ addDocs(1, start, versions); start+=1;+ h.close();+ createCore(); // trigger recovery, make sure that tlog reference handling is correct++ // test we can get versions while replay is happening+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ logReplay.release(1000);+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));++ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ addDocs(105, start, versions); start+=105;+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));+ assertU(commit());+ assertJQ(req("qt","/get", "getVersions",""+maxReq), "/versions==" + versions.subList(0,Math.min(maxReq,start)));++ // previous logs should be gone now+ assertEquals(1, HdfsUpdateLog.getLogList(fs, new Path(logDir)).length);++ //+ // test that a corrupt tlog file doesn't stop us from coming up, or seeing versions before that tlog file.+ //+ addDocs(1, start, new LinkedList<Long>()); // don't add this to the versions list because we are going to lose it...+ h.close();+ files = HdfsUpdateLog.getLogList(fs, new Path(logDir));;+ Arrays.sort(files);++ FSDataOutputStream dos = fs.create(new Path(new Path(logDir), files[files.length-1]), (short)1);+ dos.writeUTF("This is a trashed log file that really shouldn't work at all, but we'll see..");+ dos.close();++ ignoreException("Failure to open existing");+ createCore();+ // we should still be able to get the list of versions (not including the trashed log file)+ assertJQ(req("qt", "/get", "getVersions", "" + maxReq), "/versions==" + versions.subList(0, Math.min(maxReq, start)));+ resetExceptionIgnores();++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;+ }+ }++ //+ // test that a partially written last tlog entry (that will cause problems for both reverse reading and for+ // log replay) doesn't stop us from coming up, and from recovering the documents that were not cut off.+ //++ @Test+ public void testTruncatedLog() throws Exception {+ try {+ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };++ String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();++ clearIndex();+ assertU(commit());++ assertU(adoc("id","F1"));+ assertU(adoc("id","F2"));+ assertU(adoc("id","F3"));++ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs;+ try {+ URI uri = new URI(hdfsUri);+ fs = FileSystem.newInstance(uri, conf);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } catch (URISyntaxException e) {+ throw new RuntimeException(e);+ }++ h.close();++++ String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir));+ Arrays.sort(files);++ FSDataOutputStream dos = fs.append(new Path(logDir, files[files.length-1]));++ dos.writeLong(0xffffffffffffffffL);+ dos.writeChars("This should be appended to a good log file, representing a bad partially written record.");+ dos.close();++ logReplay.release(1000);+ logReplayFinish.drainPermits();+ ignoreException("OutOfBoundsException"); // this is what the corrupted log currently produces... subject to change.+ createCore();+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));+ resetExceptionIgnores();+ assertJQ(req("q","*:*") ,"/response/numFound==3");++ //+ // Now test that the bad log file doesn't mess up retrieving latest versions+ //++ updateJ(jsonAdd(sdoc("id","F4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","F5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","F6", "_version_","106")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ // This currently skips the bad log file and also returns the version of the clearIndex (del *:*)+ // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]");+ assertJQ(req("qt","/get", "getVersions","3"), "/versions==[106,105,104]");++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;+ }+ }+++ //+ // test that a corrupt tlog doesn't stop us from coming up+ //+ @Test+ public void testCorruptLog() throws Exception {+ try {+ DirectUpdateHandler2.commitOnClose = false;++ String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();++ clearIndex();+ assertU(commit());++ assertU(adoc("id","G1"));+ assertU(adoc("id","G2"));+ assertU(adoc("id","G3"));++ h.close();+ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs;+ try {+ URI uri = new URI(hdfsUri);+ fs = FileSystem.newInstance(uri, conf);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } catch (URISyntaxException e) {+ throw new RuntimeException(e);+ }++ String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir));+ Arrays.sort(files);++ FSDataOutputStream dos = fs.create(new Path(logDir, files[files.length-1]), (short)1);+ dos.write(new byte[(int)800]); // zero out file+ dos.close();+++ ignoreException("Failure to open existing log file"); // this is what the corrupted log currently produces... subject to change.+ createCore();+ resetExceptionIgnores();++ // just make sure it responds+ assertJQ(req("q","*:*") ,"/response/numFound==0");++ //+ // Now test that the bad log file doesn't mess up retrieving latest versions+ //++ updateJ(jsonAdd(sdoc("id","G4", "_version_","104")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","G5", "_version_","105")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));+ updateJ(jsonAdd(sdoc("id","G6", "_version_","106")), params(DISTRIB_UPDATE_PARAM,FROM_LEADER));++ // This currently skips the bad log file and also returns the version of the clearIndex (del *:*)+ // assertJQ(req("qt","/get", "getVersions","6"), "/versions==[106,105,104]");+ assertJQ(req("qt","/get", "getVersions","3"), "/versions==[106,105,104]");++ assertU(commit());++ assertJQ(req("q","*:*") ,"/response/numFound==3");++ // This messes up some other tests (on windows) if we don't remove the bad log.+ // This *should* hopefully just be because the tests are too fragile and not because of real bugs - but it should be investigated further.+ deleteLogs();++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;+ }+ }++++ // in rare circumstances, two logs can be left uncapped (lacking a commit at the end signifying that all the content in the log was committed)+ @Test+ public void testRecoveryMultipleLogs() throws Exception {+ try {+ DirectUpdateHandler2.commitOnClose = false;+ final Semaphore logReplay = new Semaphore(0);+ final Semaphore logReplayFinish = new Semaphore(0);++ UpdateLog.testing_logReplayHook = new Runnable() {+ @Override+ public void run() {+ try {+ assertTrue(logReplay.tryAcquire(timeout, TimeUnit.SECONDS));+ } catch (Exception e) {+ throw new RuntimeException(e);+ }+ }+ };++ UpdateLog.testing_logReplayFinishHook = new Runnable() {+ @Override+ public void run() {+ logReplayFinish.release();+ }+ };++ String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs;+ try {+ URI uri = new URI(hdfsUri);+ fs = FileSystem.newInstance(uri, conf);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } catch (URISyntaxException e) {+ throw new RuntimeException(e);+ }+ clearIndex();+ assertU(commit());++ assertU(adoc("id","AAAAAA"));+ assertU(adoc("id","BBBBBB"));+ assertU(adoc("id","CCCCCC"));++ h.close();+ String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir));+ Arrays.sort(files);+ String fname = files[files.length-1];++ FSDataOutputStream dos = fs.append(new Path(logDir, files[files.length-1]));+ dos.writeLong(0xffffffffffffffffL);+ dos.writeChars("This should be appended to a good log file, representing a bad partially written record.");+ dos.close();++ FSDataInputStream dis = fs.open(new Path(logDir, files[files.length-1]));+ byte[] content = new byte[(int)dis.available()];++ dis.readFully(content);++ dis.close();++ // Now make a newer log file with just the IDs changed. NOTE: this may not work if log format changes too much!+ findReplace("AAAAAA".getBytes("UTF-8"), "aaaaaa".getBytes("UTF-8"), content);+ findReplace("BBBBBB".getBytes("UTF-8"), "bbbbbb".getBytes("UTF-8"), content);+ findReplace("CCCCCC".getBytes("UTF-8"), "cccccc".getBytes("UTF-8"), content);++ // WARNING... assumes format of .00000n where n is less than 9+ long logNumber = Long.parseLong(fname.substring(fname.lastIndexOf(".") + 1));+ String fname2 = String.format(Locale.ROOT,+ UpdateLog.LOG_FILENAME_PATTERN,+ UpdateLog.TLOG_NAME,+ logNumber + 1);++ dos = fs.create(new Path(logDir, fname2), (short)1);+ dos.write(content);+ dos.close();+++ logReplay.release(1000);+ logReplayFinish.drainPermits();+ ignoreException("OutOfBoundsException"); // this is what the corrupted log currently produces... subject to change.+ createCore();+ assertTrue(logReplayFinish.tryAcquire(timeout, TimeUnit.SECONDS));+ resetExceptionIgnores();+ assertJQ(req("q","*:*") ,"/response/numFound==6");++ } finally {+ DirectUpdateHandler2.commitOnClose = true;+ UpdateLog.testing_logReplayHook = null;+ UpdateLog.testing_logReplayFinishHook = null;+ }+ }+++ // NOTE: replacement must currently be same size+ private static void findReplace(byte[] from, byte[] to, byte[] data) {+ int idx = -from.length;+ for(;;) {+ idx = indexOf(from, data, idx + from.length); // skip over previous match+ if (idx < 0) break;+ for (int i=0; i<to.length; i++) {+ data[idx+i] = to[i];+ }+ }+ }++ private static int indexOf(byte[] target, byte[] data, int start) {+ outer: for (int i=start; i<data.length - target.length; i++) {+ for (int j=0; j<target.length; j++) {+ if (data[i+j] != target[j]) continue outer;+ }+ return i;+ }+ return -1;+ }++ // stops the core, removes the transaction logs, restarts the core.+ void deleteLogs() throws Exception {+ String logDir = h.getCore().getUpdateHandler().getUpdateLog().getLogDir();+ Configuration conf = new Configuration();+ conf.setBoolean("fs.hdfs.impl.disable.cache", true);+ FileSystem fs;+ try {+ URI uri = new URI(hdfsUri);+ fs = FileSystem.newInstance(uri, conf);+ } catch (IOException e) {+ throw new RuntimeException(e);+ } catch (URISyntaxException e) {+ throw new RuntimeException(e);+ }+ h.close();++ try {+ String[] files = HdfsUpdateLog.getLogList(fs, new Path(logDir));+ for (String file : files) {+ //new File(logDir, file).delete();+ fs.delete(new Path(logDir, file), false);+ }++ assertEquals(0, HdfsUpdateLog.getLogList(fs, new Path(logDir)).length);+ } finally {+ // make sure we create the core again, even if the assert fails so it won't mess+ // up the next test.+ createCore();+ assertJQ(req("q","*:*") ,"/response/numFound=="); // ensure it works+ }+ }++ private static Long getVer(SolrQueryRequest req) throws Exception {+ String response = JQ(req);+ Map rsp = (Map) ObjectBuilder.fromJSON(response);+ Map doc = null;+ if (rsp.containsKey("doc")) {+ doc = (Map)rsp.get("doc");+ } else if (rsp.containsKey("docs")) {+ List lst = (List)rsp.get("docs");+ if (lst.size() > 0) {+ doc = (Map)lst.get(0);+ }+ } else if (rsp.containsKey("response")) {+ Map responseMap = (Map)rsp.get("response");+ List lst = (List)responseMap.get("docs");+ if (lst.size() > 0) {+ doc = (Map)lst.get(0);+ }+ }++ if (doc == null) return null;++ return (Long)doc.get("_version_");+ }+}+diff --git a/solr/core/src/test/org/apache/solr/store/blockcache/BlockCacheTest.java b/solr/core/src/test/org/apache/solr/store/blockcache/BlockCacheTest.javanew file mode 100644index 00000000000..70fd813aead--- /dev/null+++ b/solr/core/src/test/org/apache/solr/store/blockcache/BlockCacheTest.java@@ -0,0 +1,110 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.util.Arrays;+import java.util.Random;+import java.util.concurrent.atomic.AtomicLong;++import org.apache.hadoop.conf.Configuration;+import org.apache.lucene.util.LuceneTestCase;+import org.junit.Test;++public class BlockCacheTest extends LuceneTestCase {+ @Test+ public void testBlockCache() {+ int blocksInTest = 2000000;+ int blockSize = 1024;++ int slabSize = blockSize * 4096;+ long totalMemory = 2 * slabSize;++ BlockCache blockCache = new BlockCache(new Metrics(new Configuration()), true,totalMemory,slabSize,blockSize);+ byte[] buffer = new byte[1024];+ Random random = random();+ byte[] newData = new byte[blockSize];+ AtomicLong hitsInCache = new AtomicLong();+ AtomicLong missesInCache = new AtomicLong();+ long storeTime = 0;+ long fetchTime = 0;+ int passes = 10000;++ BlockCacheKey blockCacheKey = new BlockCacheKey();++ for (int j = 0; j < passes; j++) {+ long block = random.nextInt(blocksInTest);+ int file = 0;+ blockCacheKey.setBlock(block);+ blockCacheKey.setFile(file);++ if (blockCache.fetch(blockCacheKey, buffer)) {+ hitsInCache.incrementAndGet();+ } else {+ missesInCache.incrementAndGet();+ }++ byte[] testData = testData(random, blockSize, newData);+ long t1 = System.nanoTime();+ blockCache.store(blockCacheKey, 0, testData, 0, blockSize);+ storeTime += (System.nanoTime() - t1);++ long t3 = System.nanoTime();+ if (blockCache.fetch(blockCacheKey, buffer)) {+ fetchTime += (System.nanoTime() - t3);+ assertTrue(Arrays.equals(testData, buffer));+ }+ }+ System.out.println("Cache Hits = " + hitsInCache.get());+ System.out.println("Cache Misses = " + missesInCache.get());+ System.out.println("Store = " + (storeTime / (double) passes) / 1000000.0);+ System.out.println("Fetch = " + (fetchTime / (double) passes) / 1000000.0);+ System.out.println("# of Elements = " + blockCache.getSize());+ }++ /**+ * Verify checking of buffer size limits against the cached block size.+ */+ @Test+ public void testLongBuffer() {+ Random random = random();+ int blockSize = BlockCache._32K;+ int slabSize = blockSize * 1024;+ long totalMemory = 2 * slabSize;++ BlockCache blockCache = new BlockCache(new Metrics(new Configuration()),+ true, totalMemory, slabSize);+ BlockCacheKey blockCacheKey = new BlockCacheKey();+ blockCacheKey.setBlock(0);+ blockCacheKey.setFile(0);+ byte[] newData = new byte[blockSize*3];+ byte[] testData = testData(random, blockSize, newData);++ assertTrue(blockCache.store(blockCacheKey, 0, testData, 0, blockSize));+ assertTrue(blockCache.store(blockCacheKey, 0, testData, blockSize, blockSize));+ assertTrue(blockCache.store(blockCacheKey, 0, testData, blockSize*2, blockSize));++ assertTrue(blockCache.store(blockCacheKey, 1, testData, 0, blockSize - 1));+ assertTrue(blockCache.store(blockCacheKey, 1, testData, blockSize, blockSize - 1));+ assertTrue(blockCache.store(blockCacheKey, 1, testData, blockSize*2, blockSize - 1));+ }++ private static byte[] testData(Random random, int size, byte[] buf) {+ random.nextBytes(buf);+ return buf;+ }+}diff --git a/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java b/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.javanew file mode 100644index 00000000000..b829dcf549f--- /dev/null+++ b/solr/core/src/test/org/apache/solr/store/blockcache/BlockDirectoryTest.java@@ -0,0 +1,251 @@+package org.apache.solr.store.blockcache;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;+import java.util.Map;+import java.util.Random;++import org.apache.commons.io.FileUtils;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.FSDirectory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.MergeInfo;+import org.apache.lucene.util.LuceneTestCase;+import org.apache.solr.store.hdfs.HdfsDirectory;+import org.junit.After;+import org.junit.Before;+import org.junit.Test;++import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap;++public class BlockDirectoryTest extends LuceneTestCase {++ private class MapperCache implements Cache {+ public Map<String, byte[]> map = new ConcurrentLinkedHashMap.Builder<String, byte[]>().maximumWeightedCapacity(8).build();++ @Override+ public void update(String name, long blockId, int blockOffset, byte[] buffer, int offset, int length) {+ byte[] cached = map.get(name + blockId);+ if (cached != null) {+ int newlen = Math.max(cached.length, blockOffset + length);+ byte[] b = new byte[newlen];+ System.arraycopy(cached, 0, b, 0, cached.length);+ System.arraycopy(buffer, offset, b, blockOffset, length);+ cached = b;+ } else {+ cached = copy(blockOffset, buffer, offset, length);+ }+ map.put(name + blockId, cached);+ }++ private byte[] copy(int blockOffset, byte[] buffer, int offset, int length) {+ byte[] b = new byte[length + blockOffset];+ System.arraycopy(buffer, offset, b, blockOffset, length);+ return b;+ }++ @Override+ public boolean fetch(String name, long blockId, int blockOffset, byte[] b, int off, int lengthToReadInBlock) {+ // return false;+ byte[] data = map.get(name + blockId);+ if (data == null) {+ return false;+ }+ System.arraycopy(data, blockOffset, b, off, lengthToReadInBlock);+ return true;+ }++ @Override+ public void delete(String name) {++ }++ @Override+ public long size() {+ return map.size();+ }++ @Override+ public void renameCacheFile(String source, String dest) {+ }+ }++ private static final int MAX_NUMBER_OF_WRITES = 10000;+ private static final int MIN_FILE_SIZE = 100;+ private static final int MAX_FILE_SIZE = 100000;+ private static final int MIN_BUFFER_SIZE = 1;+ private static final int MAX_BUFFER_SIZE = 12000;+ private static final int MAX_NUMBER_OF_READS = 20000;+ private BlockDirectory directory;+ private File file;+ private Random random;+ private MapperCache mapperCache;++ @Before+ public void setUp() throws Exception {+ super.setUp();+ file = new File(TEMP_DIR, HdfsDirectory.class.getName() + "-" + System.currentTimeMillis());+ rm(file);+ file.mkdirs();+ FSDirectory dir = FSDirectory.open(new File(file, "base"));+ mapperCache = new MapperCache();+ directory = new BlockDirectory("test", dir, mapperCache, null, true, true);+ random = random();+ }++ @After+ public void tearDown() throws Exception {+ super.tearDown();+ FileUtils.deleteDirectory(file);+ }++ @Test+ public void testEOF() throws IOException {+ Directory fsDir = FSDirectory.open(new File(file, "normal"));+ String name = "test.eof";+ createFile(name, fsDir, directory);+ long fsLength = fsDir.fileLength(name);+ long hdfsLength = directory.fileLength(name);+ assertEquals(fsLength, hdfsLength);+ testEof(name, fsDir, fsLength);+ testEof(name, directory, hdfsLength);+ }++ private void testEof(String name, Directory directory, long length) throws IOException {+ IndexInput input = directory.openInput(name, new IOContext());+ input.seek(length);+ try {+ input.readByte();+ fail("should throw eof");+ } catch (IOException e) {+ }+ }++ @Test+ public void testRandomAccessWrites() throws IOException {+ long t1 = System.nanoTime();++ int i = 0;+ try {+ for (; i < 10; i++) {+ Directory fsDir = FSDirectory.open(new File(file, "normal"));+ String name = getName();+ createFile(name, fsDir, directory);+ assertInputsEquals(name, fsDir, directory);+ }+ } catch (Exception e) {+ e.printStackTrace();+ fail("Test failed on pass [" + i + "]");+ }+ long t2 = System.nanoTime();+ System.out.println("Total time is " + ((t2 - t1)/1000000) + "ms");+ }++ @Test+ public void testRandomAccessWritesLargeCache() throws IOException {+ mapperCache.map = new ConcurrentLinkedHashMap.Builder<String, byte[]>().maximumWeightedCapacity(10000).build();+ testRandomAccessWrites();+ }++ private void assertInputsEquals(String name, Directory fsDir, Directory hdfs) throws IOException {+ int reads = random.nextInt(MAX_NUMBER_OF_READS);+ IndexInput fsInput = fsDir.openInput(name, new IOContext());+ IndexInput hdfsInput = hdfs.openInput(name, new IOContext());+ assertEquals(fsInput.length(), hdfsInput.length());+ int fileLength = (int) fsInput.length();+ for (int i = 0; i < reads; i++) {+ byte[] fsBuf = new byte[random.nextInt(Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE, fileLength)) + MIN_BUFFER_SIZE];+ byte[] hdfsBuf = new byte[fsBuf.length];+ int offset = random.nextInt(fsBuf.length);+ int length = random.nextInt(fsBuf.length - offset);+ int pos = random.nextInt(fileLength - length);+ fsInput.seek(pos);+ fsInput.readBytes(fsBuf, offset, length);+ hdfsInput.seek(pos);+ hdfsInput.readBytes(hdfsBuf, offset, length);+ for (int f = offset; f < length; f++) {+ if (fsBuf[f] != hdfsBuf[f]) {+ fail("read [" + i + "]");+ }+ }+ }+ fsInput.close();+ hdfsInput.close();+ }++ private void createFile(String name, Directory fsDir, Directory hdfs) throws IOException {+ int writes = random.nextInt(MAX_NUMBER_OF_WRITES);+ int fileLength = random.nextInt(MAX_FILE_SIZE - MIN_FILE_SIZE) + MIN_FILE_SIZE;+ IndexOutput fsOutput = fsDir.createOutput(name, IOContext.DEFAULT);+ IndexOutput hdfsOutput = hdfs.createOutput(name, IOContext.DEFAULT);+ for (int i = 0; i < writes; i++) {+ byte[] buf = new byte[random.nextInt(Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE, fileLength)) + MIN_BUFFER_SIZE];+ random.nextBytes(buf);+ int offset = random.nextInt(buf.length);+ int length = random.nextInt(buf.length - offset);+ fsOutput.writeBytes(buf, offset, length);+ hdfsOutput.writeBytes(buf, offset, length);+ }+ fsOutput.close();+ hdfsOutput.close();+ }++ private String getName() {+ return Long.toString(Math.abs(random.nextLong()));+ }++ public static void rm(File file) {+ if (!file.exists()) {+ return;+ }+ if (file.isDirectory()) {+ for (File f : file.listFiles()) {+ rm(f);+ }+ }+ file.delete();+ }++ /**+ * Verify the configuration options for the block cache are handled+ * appropriately.+ */+ @Test+ public void ensureCacheConfigurable() throws Exception {+ IOContext mergeContext = new IOContext(new MergeInfo(1,1,false,1));++ BlockDirectory d = directory;+ assertTrue(d.useReadCache("", IOContext.DEFAULT));+ assertTrue(d.useWriteCache("", IOContext.DEFAULT));+ assertFalse(d.useWriteCache("", mergeContext));++ d = new BlockDirectory("test", directory, mapperCache, null, true, false);+ assertTrue(d.useReadCache("", IOContext.DEFAULT));+ assertFalse(d.useWriteCache("", IOContext.DEFAULT));+ assertFalse(d.useWriteCache("", mergeContext));++ d = new BlockDirectory("test", directory, mapperCache, null, false, true);+ assertFalse(d.useReadCache("", IOContext.DEFAULT));+ assertTrue(d.useWriteCache("", IOContext.DEFAULT));+ assertFalse(d.useWriteCache("", mergeContext));+ }+}diff --git a/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.javanew file mode 100644index 00000000000..23491121d54--- /dev/null+++ b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsDirectoryTest.java@@ -0,0 +1,222 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;+import java.util.HashSet;+import java.util.Random;+import java.util.Set;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.store.Directory;+import org.apache.lucene.store.IOContext;+import org.apache.lucene.store.IndexInput;+import org.apache.lucene.store.IndexOutput;+import org.apache.lucene.store.RAMDirectory;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.cloud.hdfs.HdfsTestUtil;+import org.junit.After;+import org.junit.AfterClass;+import org.junit.Before;+import org.junit.BeforeClass;+import org.junit.Test;++import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread (HADOOP-9049)+//@Ignore("this test violates the test security policy because of org.apache.hadoop.fs.RawLocalFileSystem.mkdirs")+public class HdfsDirectoryTest extends SolrTestCaseJ4 {++ private static final int MAX_NUMBER_OF_WRITES = 10000;+ private static final int MIN_FILE_SIZE = 100;+ private static final int MAX_FILE_SIZE = 100000;+ private static final int MIN_BUFFER_SIZE = 1;+ private static final int MAX_BUFFER_SIZE = 5000;+ private static final int MAX_NUMBER_OF_READS = 10000;+ private static MiniDFSCluster dfsCluster;+ private HdfsDirectory directory;+ private Random random;++ @BeforeClass+ public static void beforeClass() throws Exception {+ createTempDir();+ dfsCluster = HdfsTestUtil.setupClass(TEMP_DIR.getAbsolutePath()+ + File.separator + HdfsDirectoryTest.class.getName() + "_hdfsdir-"+ + System.currentTimeMillis());+ }++ @AfterClass+ public static void afterClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }++ @Before+ public void setUp() throws Exception {+ super.setUp();++ Configuration conf = new Configuration();+ conf.set("dfs.permissions.enabled", "false");++ directory = new HdfsDirectory(new Path(dfsCluster.getURI().toString() + dataDir.getAbsolutePath() + "/hdfs"), conf);++ random = random();+ }++ @After+ public void tearDown() throws Exception {+ super.tearDown();+ }++ @Test+ public void testWritingAndReadingAFile() throws IOException {+ String[] listAll = directory.listAll();+ for (String file : listAll) {+ directory.deleteFile(file);+ }++ IndexOutput output = directory.createOutput("testing.test", new IOContext());+ output.writeInt(12345);+ output.flush();+ output.close();++ IndexInput input = directory.openInput("testing.test", new IOContext());+ assertEquals(12345, input.readInt());+ input.close();++ listAll = directory.listAll();+ assertEquals(1, listAll.length);+ assertEquals("testing.test", listAll[0]);++ assertEquals(4, directory.fileLength("testing.test"));++ IndexInput input1 = directory.openInput("testing.test", new IOContext());++ IndexInput input2 = (IndexInput) input1.clone();+ assertEquals(12345, input2.readInt());+ input2.close();++ assertEquals(12345, input1.readInt());+ input1.close();++ assertFalse(directory.fileExists("testing.test.other"));+ assertTrue(directory.fileExists("testing.test"));+ directory.deleteFile("testing.test");+ assertFalse(directory.fileExists("testing.test"));+ }++ @Test+ public void testEOF() throws IOException {+ Directory fsDir = new RAMDirectory();+ String name = "test.eof";+ createFile(name, fsDir, directory);+ long fsLength = fsDir.fileLength(name);+ long hdfsLength = directory.fileLength(name);+ assertEquals(fsLength, hdfsLength);+ testEof(name,fsDir,fsLength);+ testEof(name,directory,hdfsLength);+ }++ private void testEof(String name, Directory directory, long length) throws IOException {+ IndexInput input = directory.openInput(name, new IOContext());+ input.seek(length);+ try {+ input.readByte();+ fail("should throw eof");+ } catch (IOException e) {+ }+ }++ @Test+ public void testRandomAccessWrites() throws IOException {+ int i = 0;+ try {+ Set<String> names = new HashSet<String>();+ for (; i< 10; i++) {+ Directory fsDir = new RAMDirectory();+ String name = getName();+ System.out.println("Working on pass [" + i +"] contains [" + names.contains(name) + "]");+ names.add(name);+ createFile(name,fsDir,directory);+ assertInputsEquals(name,fsDir,directory);+ fsDir.close();+ }+ } catch (Exception e) {+ e.printStackTrace();+ fail("Test failed on pass [" + i + "]");+ }+ }++ private void assertInputsEquals(String name, Directory fsDir, HdfsDirectory hdfs) throws IOException {+ int reads = random.nextInt(MAX_NUMBER_OF_READS);+ IndexInput fsInput = fsDir.openInput(name,new IOContext());+ IndexInput hdfsInput = hdfs.openInput(name,new IOContext());+ assertEquals(fsInput.length(), hdfsInput.length());+ int fileLength = (int) fsInput.length();+ for (int i = 0; i < reads; i++) {+ int nextInt = Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE,fileLength);+ byte[] fsBuf = new byte[random.nextInt(nextInt > 0 ? nextInt : 1) + MIN_BUFFER_SIZE];+ byte[] hdfsBuf = new byte[fsBuf.length];+ int offset = random.nextInt(fsBuf.length);++ nextInt = fsBuf.length - offset;+ int length = random.nextInt(nextInt > 0 ? nextInt : 1);+ nextInt = fileLength - length;+ int pos = random.nextInt(nextInt > 0 ? nextInt : 1);+ fsInput.seek(pos);+ fsInput.readBytes(fsBuf, offset, length);+ hdfsInput.seek(pos);+ hdfsInput.readBytes(hdfsBuf, offset, length);+ for (int f = offset; f < length; f++) {+ if (fsBuf[f] != hdfsBuf[f]) {+ fail();+ }+ }+ }+ fsInput.close();+ hdfsInput.close();+ }++ private void createFile(String name, Directory fsDir, HdfsDirectory hdfs) throws IOException {+ int writes = random.nextInt(MAX_NUMBER_OF_WRITES);+ int fileLength = random.nextInt(MAX_FILE_SIZE - MIN_FILE_SIZE) + MIN_FILE_SIZE;+ IndexOutput fsOutput = fsDir.createOutput(name, new IOContext());+ fsOutput.setLength(fileLength);+ IndexOutput hdfsOutput = hdfs.createOutput(name, new IOContext());+ hdfsOutput.setLength(fileLength);+ for (int i = 0; i < writes; i++) {+ byte[] buf = new byte[random.nextInt(Math.min(MAX_BUFFER_SIZE - MIN_BUFFER_SIZE,fileLength)) + MIN_BUFFER_SIZE];+ random.nextBytes(buf);+ int offset = random.nextInt(buf.length);+ int length = random.nextInt(buf.length - offset);+ fsOutput.writeBytes(buf, offset, length);+ hdfsOutput.writeBytes(buf, offset, length);+ }+ fsOutput.close();+ hdfsOutput.close();+ }++ private String getName() {+ return Long.toString(Math.abs(random.nextLong()));+ }++}diff --git a/solr/core/src/test/org/apache/solr/store/hdfs/HdfsLockFactoryTest.java b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsLockFactoryTest.javanew file mode 100644index 00000000000..4f9637427df--- /dev/null+++ b/solr/core/src/test/org/apache/solr/store/hdfs/HdfsLockFactoryTest.java@@ -0,0 +1,86 @@+package org.apache.solr.store.hdfs;++/*+ * Licensed to the Apache Software Foundation (ASF) under one or more+ * contributor license agreements. See the NOTICE file distributed with+ * this work for additional information regarding copyright ownership.+ * The ASF licenses this file to You under the Apache License, Version 2.0+ * (the "License"); you may not use this file except in compliance with+ * the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++import java.io.File;+import java.io.IOException;+import java.net.URI;++import org.apache.hadoop.conf.Configuration;+import org.apache.hadoop.fs.Path;+import org.apache.hadoop.hdfs.MiniDFSCluster;+import org.apache.lucene.store.Lock;+import org.apache.solr.SolrTestCaseJ4;+import org.apache.solr.cloud.hdfs.HdfsTestUtil;+import org.junit.After;+import org.junit.AfterClass;+import org.junit.Before;+import org.junit.BeforeClass;+import org.junit.Test;++import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope;+import com.carrotsearch.randomizedtesting.annotations.ThreadLeakScope.Scope;++@ThreadLeakScope(Scope.NONE) // hdfs client currently leaks thread (HADOOP-9049)+public class HdfsLockFactoryTest extends SolrTestCaseJ4 {++ private static MiniDFSCluster dfsCluster;++ @BeforeClass+ public static void beforeClass() throws Exception {+ createTempDir();+ dfsCluster = HdfsTestUtil.setupClass(TEMP_DIR.getAbsolutePath()+ + File.separator + HdfsLockFactoryTest.class.getName() + "_hdfsdir-"+ + System.currentTimeMillis());+ }++ @AfterClass+ public static void afterClass() throws Exception {+ HdfsTestUtil.teardownClass(dfsCluster);+ dfsCluster = null;+ }++ @Before+ public void setUp() throws Exception {+ super.setUp();+ }++ @After+ public void tearDown() throws Exception {+ super.tearDown();+ }++ @Test+ public void testBasic() throws IOException {+ URI uri = dfsCluster.getURI();+ Path lockPath = new Path(uri.toString(), "/lock");+ HdfsLockFactory lockFactory = new HdfsLockFactory(lockPath, new Configuration());+ Lock lock = lockFactory.makeLock("testlock");+ boolean success = lock.obtain();+ assertTrue("We could not get the lock when it should be available", success);+ success = lock.obtain();+ assertFalse("We got the lock but it should be unavailble", success);+ lock.release();+ success = lock.obtain();+ assertTrue("We could not get the lock when it should be available", success);+ success = lock.obtain();+ assertFalse("We got the lock but it should be unavailble", success);+ }+++}\ No newline at end of filediff --git a/solr/example/alt-configs/hdfs/solrconfig.xml b/solr/example/alt-configs/hdfs/solrconfig.xmlnew file mode 100644index 00000000000..7a5d28fb220--- /dev/null+++ b/solr/example/alt-configs/hdfs/solrconfig.xml@@ -0,0 +1,1807 @@+<?xml version="1.0" encoding="UTF-8" ?>+<!--+ Licensed to the Apache Software Foundation (ASF) under one or more+ contributor license agreements. See the NOTICE file distributed with+ this work for additional information regarding copyright ownership.+ The ASF licenses this file to You under the Apache License, Version 2.0+ (the "License"); you may not use this file except in compliance with+ the License. You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.+-->++<!--+ For more details about configurations options that may appear in+ this file, see http://wiki.apache.org/solr/SolrConfigXml.+-->+<config>+ <!-- In all configuration below, a prefix of "solr." for class names+ is an alias that causes solr to search appropriate packages,+ including org.apache.solr.(search|update|request|core|analysis)++ You may also specify a fully qualified Java classname if you+ have your own custom plugins.+ -->++ <!-- Controls what version of Lucene various components of Solr+ adhere to. Generally, you want to use the latest version to+ get all bug fixes and improvements. It is highly recommended+ that you fully re-index after changing this setting as it can+ affect both how text is indexed and queried.+ -->+ <luceneMatchVersion>LUCENE_43</luceneMatchVersion>++ <!-- <lib/> directives can be used to instruct Solr to load an Jars+ identified and use them to resolve any "plugins" specified in+ your solrconfig.xml or schema.xml (ie: Analyzers, Request+ Handlers, etc...).++ All directories and paths are resolved relative to the+ instanceDir.++ Please note that <lib/> directives are processed in the order+ that they appear in your solrconfig.xml file, and are "stacked"+ on top of each other when building a ClassLoader - so if you have+ plugin jars with dependencies on other jars, the "lower level"+ dependency jars should be loaded first.++ If a "./lib" directory exists in your instanceDir, all files+ found in it are included as if you had used the following+ syntax...++ <lib dir="./lib" />+ -->++ <!-- A 'dir' option by itself adds any files found in the directory+ to the classpath, this is useful for including all jars in a+ directory.++ When a 'regex' is specified in addition to a 'dir', only the+ files in that directory which completely match the regex+ (anchored on both ends) will be included.++ The examples below can be used to load some solr-contribs along+ with their external dependencies.+ -->+ <lib dir="../../../contrib/extraction/lib" regex=".*\.jar" />+ <lib dir="../../../dist/" regex="solr-cell-\d.*\.jar" />++ <lib dir="../../../contrib/clustering/lib/" regex=".*\.jar" />+ <lib dir="../../../dist/" regex="solr-clustering-\d.*\.jar" />++ <lib dir="../../../contrib/langid/lib/" regex=".*\.jar" />+ <lib dir="../../../dist/" regex="solr-langid-\d.*\.jar" />++ <lib dir="../../../contrib/velocity/lib" regex=".*\.jar" />+ <lib dir="../../../dist/" regex="solr-velocity-\d.*\.jar" />++ <!-- If a 'dir' option (with or without a regex) is used and nothing+ is found that matches, a warning will be logged.+ -->+ <lib dir="/non/existent/dir/yields/warning" />++ <!-- an exact 'path' can be used instead of a 'dir' to specify a+ specific jar file. This will cause a serious error to be logged+ if it can't be loaded.+ -->+ <!--+ <lib path="../a-jar-that-does-not-exist.jar" />+ -->++ <!-- Data Directory++ Used to specify an alternate directory to hold all index data+ other than the default ./data under the Solr home. If+ replication is in use, this should match the replication+ configuration.+ -->+ <dataDir>${solr.data.dir:}</dataDir>+++ <!-- The DirectoryFactory to use for indexes.++ solr.StandardDirectoryFactory is filesystem+ based and tries to pick the best implementation for the current+ JVM and platform. solr.NRTCachingDirectoryFactory, the default,+ wraps solr.StandardDirectoryFactory and caches small files in memory+ for better NRT performance.++ One can force a particular implementation via solr.MMapDirectoryFactory,+ solr.NIOFSDirectoryFactory, or solr.SimpleFSDirectoryFactory.++ solr.RAMDirectoryFactory is memory based, not+ persistent, and doesn't work with replication.+ -->+ <directoryFactory name="DirectoryFactory" class="org.apache.solr.core.HdfsDirectoryFactory">+ <str name="solr.hdfs.home">${solr.hdfs.home:}</str>+ <str name="solr.hdfs.confdir">${solr.hdfs.confdir:}</str>+ <str name="solr.hdfs.security.kerberos.enabled">${solr.hdfs.security.kerberos.enabled:false}</str>+ <str name="solr.hdfs.security.kerberos.keytabfile">${solr.hdfs.security.kerberos.keytabfile:}</str>+ <str name="solr.hdfs.security.kerberos.principal">${solr.hdfs.security.kerberos.principal:}</str>+ <bool name="solr.hdfs.blockcache.enabled">${solr.hdfs.blockcache.enabled:true}</bool>+ <int name="solr.hdfs.blockcache.slab.count">${solr.hdfs.blockcache.slab.count:1}</int>+ <bool name="solr.hdfs.blockcache.direct.memory.allocation">${solr.hdfs.blockcache.direct.memory.allocation:true}</bool>+ <int name="solr.hdfs.blockcache.blocksperbank">${solr.hdfs.blockcache.blocksperbank:16384}</int>+ <bool name="solr.hdfs.blockcache.read.enabled">${solr.hdfs.blockcache.read.enabled:true}</bool>+ <bool name="solr.hdfs.blockcache.write.enabled">${solr.hdfs.blockcache.write.enabled:true}</bool>+ <bool name="solr.hdfs.nrtcachingdirectory.enable">${solr.hdfs.nrtcachingdirectory.enable:true}</bool>+ <int name="solr.hdfs.nrtcachingdirectory.maxmergesizemb">${solr.hdfs.nrtcachingdirectory.maxmergesizemb:16}</int>+ <int name="solr.hdfs.nrtcachingdirectory.maxcachedmb">${solr.hdfs.nrtcachingdirectory.maxcachedmb:192}</int>+ </directoryFactory>++ <!-- The CodecFactory for defining the format of the inverted index.+ The default implementation is SchemaCodecFactory, which is the official Lucene+ index format, but hooks into the schema to provide per-field customization of+ the postings lists and per-document values in the fieldType element+ (postingsFormat/docValuesFormat). Note that most of the alternative implementations+ are experimental, so if you choose to customize the index format, its a good+ idea to convert back to the official format e.g. via IndexWriter.addIndexes(IndexReader)+ before upgrading to a newer version to avoid unnecessary reindexing.+ -->+ <codecFactory class="solr.SchemaCodecFactory"/>++ <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ Index Config - These settings control low-level behavior of indexing+ Most example settings here show the default value, but are commented+ out, to more easily see where customizations have been made.++ Note: This replaces <indexDefaults> and <mainIndex> from older versions+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->+ <indexConfig>+ <!-- maxFieldLength was removed in 4.0. To get similar behavior, include a+ LimitTokenCountFilterFactory in your fieldType definition. E.g.+ <filter class="solr.LimitTokenCountFilterFactory" maxTokenCount="10000"/>+ -->+ <!-- Maximum time to wait for a write lock (ms) for an IndexWriter. Default: 1000 -->+ <!-- <writeLockTimeout>1000</writeLockTimeout> -->++ <!-- The maximum number of simultaneous threads that may be+ indexing documents at once in IndexWriter; if more than this+ many threads arrive they will wait for others to finish.+ Default in Solr/Lucene is 8. -->+ <maxIndexingThreads>${solr.maxIndexingThreads:8}</maxIndexingThreads>++ <!-- Expert: Enabling compound file will use less files for the index,+ using fewer file descriptors on the expense of performance decrease.+ Default in Lucene is "true". Default in Solr is "false" (since 3.6) -->+ <!-- <useCompoundFile>false</useCompoundFile> -->++ <!-- ramBufferSizeMB sets the amount of RAM that may be used by Lucene+ indexing for buffering added documents and deletions before they are+ flushed to the Directory.+ maxBufferedDocs sets a limit on the number of documents buffered+ before flushing.+ If both ramBufferSizeMB and maxBufferedDocs is set, then+ Lucene will flush based on whichever limit is hit first. -->+ <ramBufferSizeMB>128</ramBufferSizeMB>+ <!-- <maxBufferedDocs>1000</maxBufferedDocs> -->++ <!-- Expert: Merge Policy+ The Merge Policy in Lucene controls how merging of segments is done.+ The default since Solr/Lucene 3.3 is TieredMergePolicy.+ The default since Lucene 2.3 was the LogByteSizeMergePolicy,+ Even older versions of Lucene used LogDocMergePolicy.+ -->+ <!--+ <mergePolicy class="org.apache.lucene.index.TieredMergePolicy">+ <int name="maxMergeAtOnce">10</int>+ <int name="segmentsPerTier">10</int>+ </mergePolicy>+ -->++ <!-- Merge Factor+ The merge factor controls how many segments will get merged at a time.+ For TieredMergePolicy, mergeFactor is a convenience parameter which+ will set both MaxMergeAtOnce and SegmentsPerTier at once.+ For LogByteSizeMergePolicy, mergeFactor decides how many new segments+ will be allowed before they are merged into one.+ Default is 10 for both merge policies.+ -->+ <!--+ <mergeFactor>10</mergeFactor>+ -->++ <!-- Expert: Merge Scheduler+ The Merge Scheduler in Lucene controls how merges are+ performed. The ConcurrentMergeScheduler (Lucene 2.3 default)+ can perform merges in the background using separate threads.+ The SerialMergeScheduler (Lucene 2.2 default) does not.+ -->+ <!--+ <mergeScheduler class="org.apache.lucene.index.ConcurrentMergeScheduler"/>+ -->++ <!-- LockFactory++ This option specifies which Lucene LockFactory implementation+ to use.++ single = SingleInstanceLockFactory - suggested for a+ read-only index or when there is no possibility of+ another process trying to modify the index.+ native = NativeFSLockFactory - uses OS native file locking.+ Do not use when multiple solr webapps in the same+ JVM are attempting to share a single index.+ simple = SimpleFSLockFactory - uses a plain file for locking++ Defaults: 'native' is default for Solr3.6 and later, otherwise+ 'simple' is the default++ More details on the nuances of each LockFactory...+ http://wiki.apache.org/lucene-java/AvailableLockFactories+ -->+ <lockType>${solr.lock.type:hdfs}</lockType>++ <!-- Unlock On Startup++ If true, unlock any held write or commit locks on startup.+ This defeats the locking mechanism that allows multiple+ processes to safely access a lucene index, and should be used+ with care. Default is "false".++ This is not needed if lock type is 'single'+ -->+ <!--+ <unlockOnStartup>false</unlockOnStartup>+ -->++ <!-- Expert: Controls how often Lucene loads terms into memory+ Default is 128 and is likely good for most everyone.+ -->+ <!-- <termIndexInterval>128</termIndexInterval> -->++ <!-- If true, IndexReaders will be reopened (often more efficient)+ instead of closed and then opened. Default: true+ -->+ <!--+ <reopenReaders>true</reopenReaders>+ -->++ <!-- Commit Deletion Policy+ Custom deletion policies can be specified here. The class must+ implement org.apache.lucene.index.IndexDeletionPolicy.++ The default Solr IndexDeletionPolicy implementation supports+ deleting index commit points on number of commits, age of+ commit point and optimized status.++ The latest commit point should always be preserved regardless+ of the criteria.+ -->+ <!--+ <deletionPolicy class="solr.SolrDeletionPolicy">+ -->+ <!-- The number of commit points to be kept -->+ <!-- <str name="maxCommitsToKeep">1</str> -->+ <!-- The number of optimized commit points to be kept -->+ <!-- <str name="maxOptimizedCommitsToKeep">0</str> -->+ <!--+ Delete all commit points once they have reached the given age.+ Supports DateMathParser syntax e.g.+ -->+ <!--+ <str name="maxCommitAge">30MINUTES</str>+ <str name="maxCommitAge">1DAY</str>+ -->+ <!--+ </deletionPolicy>+ -->++ <!-- Lucene Infostream++ To aid in advanced debugging, Lucene provides an "InfoStream"+ of detailed information when indexing.++ Setting The value to true will instruct the underlying Lucene+ IndexWriter to write its debugging info the specified file+ -->+ <!-- <infoStream file="INFOSTREAM.txt">false</infoStream> -->+ </indexConfig>+++ <!-- JMX++ This example enables JMX if and only if an existing MBeanServer+ is found, use this if you want to configure JMX through JVM+ parameters. Remove this to disable exposing Solr configuration+ and statistics to JMX.++ For more details see http://wiki.apache.org/solr/SolrJmx+ -->+ <jmx />+ <!-- If you want to connect to a particular server, specify the+ agentId+ -->+ <!-- <jmx agentId="myAgent" /> -->+ <!-- If you want to start a new MBeanServer, specify the serviceUrl -->+ <!-- <jmx serviceUrl="service:jmx:rmi:///jndi/rmi://localhost:9999/solr"/>+ -->++ <!-- The default high-performance update handler -->+ <updateHandler class="solr.DirectUpdateHandler2">++ <!-- Enables a transaction log, used for real-time get, durability, and+ and solr cloud replica recovery. The log can grow as big as+ uncommitted changes to the index, so use of a hard autoCommit+ is recommended (see below).+ "dir" - the target directory for transaction logs, defaults to the+ solr data directory. -->+ <updateLog>+ <str name="dir">${solr.ulog.dir:}</str>+ </updateLog>++ <!-- AutoCommit++ Perform a hard commit automatically under certain conditions.+ Instead of enabling autoCommit, consider using "commitWithin"+ when adding documents.++ http://wiki.apache.org/solr/UpdateXmlMessages++ maxDocs - Maximum number of documents to add since the last+ commit before automatically triggering a new commit.++ maxTime - Maximum amount of time in ms that is allowed to pass+ since a document was added before automatically+ triggering a new commit.+ openSearcher - if false, the commit causes recent index changes+ to be flushed to stable storage, but does not cause a new+ searcher to be opened to make those changes visible.++ If the updateLog is enabled, then it's highly recommended to+ have some sort of hard autoCommit to limit the log size.+ -->+ <autoCommit>+ <maxTime>${solr.autoCommit.maxTime:60000}</maxTime>+ <openSearcher>false</openSearcher>+ </autoCommit>++ <!-- softAutoCommit is like autoCommit except it causes a+ 'soft' commit which only ensures that changes are visible+ but does not ensure that data is synced to disk. This is+ faster and more near-realtime friendly than a hard commit.+ -->+ <autoSoftCommit>+ <maxTime>${solr.autoSoftCommit.maxTime:1000}</maxTime>+ </autoSoftCommit>+++ <!-- Update Related Event Listeners++ Various IndexWriter related events can trigger Listeners to+ take actions.++ postCommit - fired after every commit or optimize command+ postOptimize - fired after every optimize command+ -->+ <!-- The RunExecutableListener executes an external command from a+ hook such as postCommit or postOptimize.++ exe - the name of the executable to run+ dir - dir to use as the current working directory. (default=".")+ wait - the calling thread waits until the executable returns.+ (default="true")+ args - the arguments to pass to the program. (default is none)+ env - environment variables to set. (default is none)+ -->+ <!-- This example shows how RunExecutableListener could be used+ with the script based replication...+ http://wiki.apache.org/solr/CollectionDistribution+ -->+ <!--+ <listener event="postCommit" class="solr.RunExecutableListener">+ <str name="exe">solr/bin/snapshooter</str>+ <str name="dir">.</str>+ <bool name="wait">true</bool>+ <arr name="args"> <str>arg1</str> <str>arg2</str> </arr>+ <arr name="env"> <str>MYVAR=val1</str> </arr>+ </listener>+ -->++ </updateHandler>++ <!-- IndexReaderFactory++ Use the following format to specify a custom IndexReaderFactory,+ which allows for alternate IndexReader implementations.++ ** Experimental Feature **++ Please note - Using a custom IndexReaderFactory may prevent+ certain other features from working. The API to+ IndexReaderFactory may change without warning or may even be+ removed from future releases if the problems cannot be+ resolved.+++ ** Features that may not work with custom IndexReaderFactory **++ The ReplicationHandler assumes a disk-resident index. Using a+ custom IndexReader implementation may cause incompatibility+ with ReplicationHandler and may cause replication to not work+ correctly. See SOLR-1366 for details.++ -->+ <!--+ <indexReaderFactory name="IndexReaderFactory" class="package.class">+ <str name="someArg">Some Value</str>+ </indexReaderFactory >+ -->+ <!-- By explicitly declaring the Factory, the termIndexDivisor can+ be specified.+ -->+ <!--+ <indexReaderFactory name="IndexReaderFactory"+ class="solr.StandardIndexReaderFactory">+ <int name="setTermIndexDivisor">12</int>+ </indexReaderFactory >+ -->++ <!-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ Query section - these settings control query time things like caches+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -->+ <query>+ <!-- Max Boolean Clauses++ Maximum number of clauses in each BooleanQuery, an exception+ is thrown if exceeded.++ ** WARNING **++ This option actually modifies a global Lucene property that+ will affect all SolrCores. If multiple solrconfig.xml files+ disagree on this property, the value at any given moment will+ be based on the last SolrCore to be initialized.++ -->+ <maxBooleanClauses>1024</maxBooleanClauses>+++ <!-- Solr Internal Query Caches++ There are two implementations of cache available for Solr,+ LRUCache, based on a synchronized LinkedHashMap, and+ FastLRUCache, based on a ConcurrentHashMap.++ FastLRUCache has faster gets and slower puts in single+ threaded operation and thus is generally faster than LRUCache+ when the hit ratio of the cache is high (> 75%), and may be+ faster under other scenarios on multi-cpu systems.+ -->++ <!-- Filter Cache++ Cache used by SolrIndexSearcher for filters (DocSets),+ unordered sets of *all* documents that match a query. When a+ new searcher is opened, its caches may be prepopulated or+ "autowarmed" using data from caches in the old searcher.+ autowarmCount is the number of items to prepopulate. For+ LRUCache, the autowarmed items will be the most recently+ accessed items.++ Parameters:+ class - the SolrCache implementation LRUCache or+ (LRUCache or FastLRUCache)+ size - the maximum number of entries in the cache+ initialSize - the initial capacity (number of entries) of+ the cache. (see java.util.HashMap)+ autowarmCount - the number of entries to prepopulate from+ and old cache.+ -->+ <filterCache class="solr.FastLRUCache"+ size="512"+ initialSize="512"+ autowarmCount="0"/>++ <!-- Query Result Cache++ Caches results of searches - ordered lists of document ids+ (DocList) based on a query, a sort, and the range of documents requested.+ -->+ <queryResultCache class="solr.LRUCache"+ size="512"+ initialSize="512"+ autowarmCount="0"/>++ <!-- Document Cache++ Caches Lucene Document objects (the stored fields for each+ document). Since Lucene internal document ids are transient,+ this cache will not be autowarmed.+ -->+ <documentCache class="solr.LRUCache"+ size="512"+ initialSize="512"+ autowarmCount="0"/>++ <!-- Field Value Cache++ Cache used to hold field values that are quickly accessible+ by document id. The fieldValueCache is created by default+ even if not configured here.+ -->+ <!--+ <fieldValueCache class="solr.FastLRUCache"+ size="512"+ autowarmCount="128"+ showItems="32" />+ -->++ <!-- Custom Cache++ Example of a generic cache. These caches may be accessed by+ name through SolrIndexSearcher.getCache(),cacheLookup(), and+ cacheInsert(). The purpose is to enable easy caching of+ user/application level data. The regenerator argument should+ be specified as an implementation of solr.CacheRegenerator+ if autowarming is desired.+ -->+ <!--+ <cache name="myUserCache"+ class="solr.LRUCache"+ size="4096"+ initialSize="1024"+ autowarmCount="1024"+ regenerator="com.mycompany.MyRegenerator"+ />+ -->+++ <!-- Lazy Field Loading++ If true, stored fields that are not requested will be loaded+ lazily. This can result in a significant speed improvement+ if the usual case is to not load all stored fields,+ especially if the skipped fields are large compressed text+ fields.+ -->+ <enableLazyFieldLoading>true</enableLazyFieldLoading>++ <!-- Use Filter For Sorted Query++ A possible optimization that attempts to use a filter to+ satisfy a search. If the requested sort does not include+ score, then the filterCache will be checked for a filter+ matching the query. If found, the filter will be used as the+ source of document ids, and then the sort will be applied to+ that.++ For most situations, this will not be useful unless you+ frequently get the same search repeatedly with different sort+ options, and none of them ever use "score"+ -->+ <!--+ <useFilterForSortedQuery>true</useFilterForSortedQuery>+ -->++ <!-- Result Window Size++ An optimization for use with the queryResultCache. When a search+ is requested, a superset of the requested number of document ids+ are collected. For example, if a search for a particular query+ requests matching documents 10 through 19, and queryWindowSize is 50,+ then documents 0 through 49 will be collected and cached. Any further+ requests in that range can be satisfied via the cache.+ -->+ <queryResultWindowSize>20</queryResultWindowSize>++ <!-- Maximum number of documents to cache for any entry in the+ queryResultCache.+ -->+ <queryResultMaxDocsCached>200</queryResultMaxDocsCached>++ <!-- Query Related Event Listeners++ Various IndexSearcher related events can trigger Listeners to+ take actions.++ newSearcher - fired whenever a new searcher is being prepared+ and there is a current searcher handling requests (aka+ registered). It can be used to prime certain caches to+ prevent long request times for certain requests.++ firstSearcher - fired whenever a new searcher is being+ prepared but there is no current registered searcher to handle+ requests or to gain autowarming data from.+++ -->+ <!-- QuerySenderListener takes an array of NamedList and executes a+ local query request for each NamedList in sequence.+ -->+ <listener event="newSearcher" class="solr.QuerySenderListener">+ <arr name="queries">+ <!--+ <lst><str name="q">solr</str><str name="sort">price asc</str></lst>+ <lst><str name="q">rocks</str><str name="sort">weight asc</str></lst>+ -->+ </arr>+ </listener>+ <listener event="firstSearcher" class="solr.QuerySenderListener">+ <arr name="queries">+ <lst>+ <str name="q">static firstSearcher warming in solrconfig.xml</str>+ </lst>+ </arr>+ </listener>++ <!-- Use Cold Searcher++ If a search request comes in and there is no current+ registered searcher, then immediately register the still+ warming searcher and use it. If "false" then all requests+ will block until the first searcher is done warming.+ -->+ <useColdSearcher>false</useColdSearcher>++ <!-- Max Warming Searchers++ Maximum number of searchers that may be warming in the+ background concurrently. An error is returned if this limit+ is exceeded.++ Recommend values of 1-2 for read-only slaves, higher for+ masters w/o cache warming.+ -->+ <maxWarmingSearchers>4</maxWarmingSearchers>++ </query>+++ <!-- Request Dispatcher++ This section contains instructions for how the SolrDispatchFilter+ should behave when processing requests for this SolrCore.++ handleSelect is a legacy option that affects the behavior of requests+ such as /select?qt=XXX++ handleSelect="true" will cause the SolrDispatchFilter to process+ the request and dispatch the query to a handler specified by the+ "qt" param, assuming "/select" isn't already registered.++ handleSelect="false" will cause the SolrDispatchFilter to+ ignore "/select" requests, resulting in a 404 unless a handler+ is explicitly registered with the name "/select"++ handleSelect="true" is not recommended for new users, but is the default+ for backwards compatibility+ -->+ <requestDispatcher handleSelect="false" >+ <!-- Request Parsing++ These settings indicate how Solr Requests may be parsed, and+ what restrictions may be placed on the ContentStreams from+ those requests++ enableRemoteStreaming - enables use of the stream.file+ and stream.url parameters for specifying remote streams.++ multipartUploadLimitInKB - specifies the max size (in KiB) of+ Multipart File Uploads that Solr will allow in a Request.++ formdataUploadLimitInKB - specifies the max size (in KiB) of+ form data (application/x-www-form-urlencoded) sent via+ POST. You can use POST to pass request parameters not+ fitting into the URL.++ *** WARNING ***+ The settings below authorize Solr to fetch remote files, You+ should make sure your system has some authentication before+ using enableRemoteStreaming="true"++ -->+ <requestParsers enableRemoteStreaming="true"+ multipartUploadLimitInKB="2048000"+ formdataUploadLimitInKB="2048"/>++ <!-- HTTP Caching++ Set HTTP caching related parameters (for proxy caches and clients).++ The options below instruct Solr not to output any HTTP Caching+ related headers+ -->+ <httpCaching never304="true" />+ <!-- If you include a <cacheControl> directive, it will be used to+ generate a Cache-Control header (as well as an Expires header+ if the value contains "max-age=")++ By default, no Cache-Control header is generated.++ You can use the <cacheControl> option even if you have set+ never304="true"+ -->+ <!--+ <httpCaching never304="true" >+ <cacheControl>max-age=30, public</cacheControl>+ </httpCaching>+ -->+ <!-- To enable Solr to respond with automatically generated HTTP+ Caching headers, and to response to Cache Validation requests+ correctly, set the value of never304="false"++ This will cause Solr to generate Last-Modified and ETag+ headers based on the properties of the Index.++ The following options can also be specified to affect the+ values of these headers...++ lastModFrom - the default value is "openTime" which means the+ Last-Modified value (and validation against If-Modified-Since+ requests) will all be relative to when the current Searcher+ was opened. You can change it to lastModFrom="dirLastMod" if+ you want the value to exactly correspond to when the physical+ index was last modified.++ etagSeed="..." is an option you can change to force the ETag+ header (and validation against If-None-Match requests) to be+ different even if the index has not changed (ie: when making+ significant changes to your config file)++ (lastModifiedFrom and etagSeed are both ignored if you use+ the never304="true" option)+ -->+ <!--+ <httpCaching lastModifiedFrom="openTime"+ etagSeed="Solr">+ <cacheControl>max-age=30, public</cacheControl>+ </httpCaching>+ -->+ </requestDispatcher>++ <!-- Request Handlers++ http://wiki.apache.org/solr/SolrRequestHandler++ Incoming queries will be dispatched to a specific handler by name+ based on the path specified in the request.++ Legacy behavior: If the request path uses "/select" but no Request+ Handler has that name, and if handleSelect="true" has been specified in+ the requestDispatcher, then the Request Handler is dispatched based on+ the qt parameter. Handlers without a leading '/' are accessed this way+ like so: http://host/app/[core/]select?qt=name If no qt is+ given, then the requestHandler that declares default="true" will be+ used or the one named "standard".++ If a Request Handler is declared with startup="lazy", then it will+ not be initialized until the first request that uses it.++ -->+ <!-- SearchHandler++ http://wiki.apache.org/solr/SearchHandler++ For processing Search Queries, the primary Request Handler+ provided with Solr is "SearchHandler" It delegates to a sequent+ of SearchComponents (see below) and supports distributed+ queries across multiple shards+ -->+ <requestHandler name="/select" class="solr.SearchHandler">+ <!-- default values for query parameters can be specified, these+ will be overridden by parameters in the request+ -->+ <lst name="defaults">+ <str name="echoParams">explicit</str>+ <int name="rows">10</int>+ <str name="df">text</str>+ </lst>+ <!-- In addition to defaults, "appends" params can be specified+ to identify values which should be appended to the list of+ multi-val params from the query (or the existing "defaults").+ -->+ <!-- In this example, the param "fq=instock:true" would be appended to+ any query time fq params the user may specify, as a mechanism for+ partitioning the index, independent of any user selected filtering+ that may also be desired (perhaps as a result of faceted searching).++ NOTE: there is *absolutely* nothing a client can do to prevent these+ "appends" values from being used, so don't use this mechanism+ unless you are sure you always want it.+ -->+ <!--+ <lst name="appends">+ <str name="fq">inStock:true</str>+ </lst>+ -->+ <!-- "invariants" are a way of letting the Solr maintainer lock down+ the options available to Solr clients. Any params values+ specified here are used regardless of what values may be specified+ in either the query, the "defaults", or the "appends" params.++ In this example, the facet.field and facet.query params would+ be fixed, limiting the facets clients can use. Faceting is+ not turned on by default - but if the client does specify+ facet=true in the request, these are the only facets they+ will be able to see counts for; regardless of what other+ facet.field or facet.query params they may specify.++ NOTE: there is *absolutely* nothing a client can do to prevent these+ "invariants" values from being used, so don't use this mechanism+ unless you are sure you always want it.+ -->+ <!--+ <lst name="invariants">+ <str name="facet.field">cat</str>+ <str name="facet.field">manu_exact</str>+ <str name="facet.query">price:[* TO 500]</str>+ <str name="facet.query">price:[500 TO *]</str>+ </lst>+ -->+ <!-- If the default list of SearchComponents is not desired, that+ list can either be overridden completely, or components can be+ prepended or appended to the default list. (see below)+ -->+ <!--+ <arr name="components">+ <str>nameOfCustomComponent1</str>+ <str>nameOfCustomComponent2</str>+ </arr>+ -->+ </requestHandler>++ <!-- A request handler that returns indented JSON by default -->+ <requestHandler name="/query" class="solr.SearchHandler">+ <lst name="defaults">+ <str name="echoParams">explicit</str>+ <str name="wt">json</str>+ <str name="indent">true</str>+ <str name="df">text</str>+ </lst>+ </requestHandler>+++ <!-- realtime get handler, guaranteed to return the latest stored fields of+ any document, without the need to commit or open a new searcher. The+ current implementation relies on the updateLog feature being enabled. -->+ <requestHandler name="/get" class="solr.RealTimeGetHandler">+ <lst name="defaults">+ <str name="omitHeader">true</str>+ <str name="wt">json</str>+ <str name="indent">true</str>+ </lst>+ </requestHandler>+++ <!-- A Robust Example++ This example SearchHandler declaration shows off usage of the+ SearchHandler with many defaults declared++ Note that multiple instances of the same Request Handler+ (SearchHandler) can be registered multiple times with different+ names (and different init parameters)+ -->+ <requestHandler name="/browse" class="solr.SearchHandler">+ <lst name="defaults">+ <str name="echoParams">explicit</str>++ <!-- VelocityResponseWriter settings -->+ <str name="wt">velocity</str>+ <str name="v.template">browse</str>+ <str name="v.layout">layout</str>+ <str name="title">Solritas</str>++ <!-- Query settings -->+ <str name="defType">edismax</str>+ <str name="qf">+ text^0.5 features^1.0 name^1.2 sku^1.5 id^10.0 manu^1.1 cat^1.4+ title^10.0 description^5.0 keywords^5.0 author^2.0 resourcename^1.0+ </str>+ <str name="df">text</str>+ <str name="mm">100%</str>+ <str name="q.alt">*:*</str>+ <str name="rows">10</str>+ <str name="fl">*,score</str>++ <str name="mlt.qf">+ text^0.5 features^1.0 name^1.2 sku^1.5 id^10.0 manu^1.1 cat^1.4+ title^10.0 description^5.0 keywords^5.0 author^2.0 resourcename^1.0+ </str>+ <str name="mlt.fl">text,features,name,sku,id,manu,cat,title,description,keywords,author,resourcename</str>+ <int name="mlt.count">3</int>++ <!-- Faceting defaults -->+ <str name="facet">on</str>+ <str name="facet.field">cat</str>+ <str name="facet.field">manu_exact</str>+ <str name="facet.field">content_type</str>+ <str name="facet.field">author_s</str>+ <str name="facet.query">ipod</str>+ <str name="facet.query">GB</str>+ <str name="facet.mincount">1</str>+ <str name="facet.pivot">cat,inStock</str>+ <str name="facet.range.other">after</str>+ <str name="facet.range">price</str>+ <int name="f.price.facet.range.start">0</int>+ <int name="f.price.facet.range.end">600</int>+ <int name="f.price.facet.range.gap">50</int>+ <str name="facet.range">popularity</str>+ <int name="f.popularity.facet.range.start">0</int>+ <int name="f.popularity.facet.range.end">10</int>+ <int name="f.popularity.facet.range.gap">3</int>+ <str name="facet.range">manufacturedate_dt</str>+ <str name="f.manufacturedate_dt.facet.range.start">NOW/YEAR-10YEARS</str>+ <str name="f.manufacturedate_dt.facet.range.end">NOW</str>+ <str name="f.manufacturedate_dt.facet.range.gap">+1YEAR</str>+ <str name="f.manufacturedate_dt.facet.range.other">before</str>+ <str name="f.manufacturedate_dt.facet.range.other">after</str>++ <!-- Highlighting defaults -->+ <str name="hl">on</str>+ <str name="hl.fl">content features title name</str>+ <str name="hl.encoder">html</str>+ <str name="hl.simple.pre"><b></str>+ <str name="hl.simple.post"></b></str>+ <str name="f.title.hl.fragsize">0</str>+ <str name="f.title.hl.alternateField">title</str>+ <str name="f.name.hl.fragsize">0</str>+ <str name="f.name.hl.alternateField">name</str>+ <str name="f.content.hl.snippets">3</str>+ <str name="f.content.hl.fragsize">200</str>+ <str name="f.content.hl.alternateField">content</str>+ <str name="f.content.hl.maxAlternateFieldLength">750</str>++ <!-- Spell checking defaults -->+ <str name="spellcheck">on</str>+ <str name="spellcheck.extendedResults">false</str>+ <str name="spellcheck.count">5</str>+ <str name="spellcheck.alternativeTermCount">2</str>+ <str name="spellcheck.maxResultsForSuggest">5</str>+ <str name="spellcheck.collate">true</str>+ <str name="spellcheck.collateExtendedResults">true</str>+ <str name="spellcheck.maxCollationTries">5</str>+ <str name="spellcheck.maxCollations">3</str>+ </lst>++ <!-- append spellchecking to our list of components -->+ <arr name="last-components">+ <str>spellcheck</str>+ </arr>+ </requestHandler>+++ <!-- Update Request Handler.++ http://wiki.apache.org/solr/UpdateXmlMessages++ The canonical Request Handler for Modifying the Index through+ commands specified using XML, JSON, CSV, or JAVABIN++ Note: Since solr1.1 requestHandlers requires a valid content+ type header if posted in the body. For example, curl now+ requires: -H 'Content-type:text/xml; charset=utf-8'++ To override the request content type and force a specific+ Content-type, use the request parameter:+ ?update.contentType=text/csv++ This handler will pick a response format to match the input+ if the 'wt' parameter is not explicit+ -->+ <requestHandler name="/update" class="solr.UpdateRequestHandler">+ <!-- See below for information on defining+ updateRequestProcessorChains that can be used by name+ on each Update Request+ -->+ <!--+ <lst name="defaults">+ <str name="update.chain">dedupe</str>+ </lst>+ -->+ </requestHandler>++ <!-- for back compat with clients using /update/json and /update/csv -->+ <requestHandler name="/update/json" class="solr.JsonUpdateRequestHandler">+ <lst name="defaults">+ <str name="stream.contentType">application/json</str>+ </lst>+ </requestHandler>+ <requestHandler name="/update/csv" class="solr.CSVRequestHandler">+ <lst name="defaults">+ <str name="stream.contentType">application/csv</str>+ </lst>+ </requestHandler>++ <!-- Solr Cell Update Request Handler++ http://wiki.apache.org/solr/ExtractingRequestHandler++ -->+ <requestHandler name="/update/extract"+ startup="lazy"+ class="solr.extraction.ExtractingRequestHandler" >+ <lst name="defaults">+ <str name="lowernames">true</str>+ <str name="uprefix">ignored_</str>++ <!-- capture link hrefs but ignore div attributes -->+ <str name="captureAttr">true</str>+ <str name="fmap.a">links</str>+ <str name="fmap.div">ignored_</str>+ </lst>+ </requestHandler>+++ <!-- Field Analysis Request Handler++ RequestHandler that provides much the same functionality as+ analysis.jsp. Provides the ability to specify multiple field+ types and field names in the same request and outputs+ index-time and query-time analysis for each of them.++ Request parameters are:+ analysis.fieldname - field name whose analyzers are to be used++ analysis.fieldtype - field type whose analyzers are to be used+ analysis.fieldvalue - text for index-time analysis+ q (or analysis.q) - text for query time analysis+ analysis.showmatch (true|false) - When set to true and when+ query analysis is performed, the produced tokens of the+ field value analysis will be marked as "matched" for every+ token that is produces by the query analysis+ -->+ <requestHandler name="/analysis/field"+ startup="lazy"+ class="solr.FieldAnalysisRequestHandler" />+++ <!-- Document Analysis Handler++ http://wiki.apache.org/solr/AnalysisRequestHandler++ An analysis handler that provides a breakdown of the analysis+ process of provided documents. This handler expects a (single)+ content stream with the following format:++ <docs>+ <doc>+ <field name="id">1</field>+ <field name="name">The Name</field>+ <field name="text">The Text Value</field>+ </doc>+ <doc>...</doc>+ <doc>...</doc>+ ...+ </docs>++ Note: Each document must contain a field which serves as the+ unique key. This key is used in the returned response to associate+ an analysis breakdown to the analyzed document.++ Like the FieldAnalysisRequestHandler, this handler also supports+ query analysis by sending either an "analysis.query" or "q"+ request parameter that holds the query text to be analyzed. It+ also supports the "analysis.showmatch" parameter which when set to+ true, all field tokens that match the query tokens will be marked+ as a "match".+ -->+ <requestHandler name="/analysis/document"+ class="solr.DocumentAnalysisRequestHandler"+ startup="lazy" />++ <!-- Admin Handlers++ Admin Handlers - This will register all the standard admin+ RequestHandlers.+ -->+ <requestHandler name="/admin/"+ class="solr.admin.AdminHandlers" />+ <!-- This single handler is equivalent to the following... -->+ <!--+ <requestHandler name="/admin/luke" class="solr.admin.LukeRequestHandler" />+ <requestHandler name="/admin/system" class="solr.admin.SystemInfoHandler" />+ <requestHandler name="/admin/plugins" class="solr.admin.PluginInfoHandler" />+ <requestHandler name="/admin/threads" class="solr.admin.ThreadDumpHandler" />+ <requestHandler name="/admin/properties" class="solr.admin.PropertiesRequestHandler" />+ <requestHandler name="/admin/file" class="solr.admin.ShowFileRequestHandler" >+ -->+ <!-- If you wish to hide files under ${solr.home}/conf, explicitly+ register the ShowFileRequestHandler using:+ -->+ <!--+ <requestHandler name="/admin/file"+ class="solr.admin.ShowFileRequestHandler" >+ <lst name="invariants">+ <str name="hidden">synonyms.txt</str>+ <str name="hidden">anotherfile.txt</str>+ </lst>+ </requestHandler>+ -->++ <!-- ping/healthcheck -->+ <requestHandler name="/admin/ping" class="solr.PingRequestHandler">+ <lst name="invariants">+ <str name="q">solrpingquery</str>+ </lst>+ <lst name="defaults">+ <str name="echoParams">all</str>+ </lst>+ <!-- An optional feature of the PingRequestHandler is to configure the+ handler with a "healthcheckFile" which can be used to enable/disable+ the PingRequestHandler.+ relative paths are resolved against the data dir+ -->+ <!-- <str name="healthcheckFile">server-enabled.txt</str> -->+ </requestHandler>++ <!-- Echo the request contents back to the client -->+ <requestHandler name="/debug/dump" class="solr.DumpRequestHandler" >+ <lst name="defaults">+ <str name="echoParams">explicit</str>+ <str name="echoHandler">true</str>+ </lst>+ </requestHandler>++ <!-- Solr Replication++ The SolrReplicationHandler supports replicating indexes from a+ "master" used for indexing and "slaves" used for queries.++ http://wiki.apache.org/solr/SolrReplication++ It is also necessary for SolrCloud to function (in Cloud mode, the+ replication handler is used to bulk transfer segments when nodes+ are added or need to recover).++ https://wiki.apache.org/solr/SolrCloud/+ -->+ <requestHandler name="/replication" class="solr.ReplicationHandler" >+ <!--+ To enable simple master/slave replication, uncomment one of the+ sections below, depending on whether this solr instance should be+ the "master" or a "slave". If this instance is a "slave" you will+ also need to fill in the masterUrl to point to a real machine.+ -->+ <!--+ <lst name="master">+ <str name="replicateAfter">commit</str>+ <str name="replicateAfter">startup</str>+ <str name="confFiles">schema.xml,stopwords.txt</str>+ </lst>+ -->+ <!--+ <lst name="slave">+ <str name="masterUrl">http://your-master-hostname:8983/solr</str>+ <str name="pollInterval">00:00:60</str>+ </lst>+ -->+ </requestHandler>++ <!-- Search Components++ Search components are registered to SolrCore and used by+ instances of SearchHandler (which can access them by name)++ By default, the following components are available:++ <searchComponent name="query" class="solr.QueryComponent" />+ <searchComponent name="facet" class="solr.FacetComponent" />+ <searchComponent name="mlt" class="solr.MoreLikeThisComponent" />+ <searchComponent name="highlight" class="solr.HighlightComponent" />+ <searchComponent name="stats" class="solr.StatsComponent" />+ <searchComponent name="debug" class="solr.DebugComponent" />++ Default configuration in a requestHandler would look like:++ <arr name="components">+ <str>query</str>+ <str>facet</str>+ <str>mlt</str>+ <str>highlight</str>+ <str>stats</str>+ <str>debug</str>+ </arr>++ If you register a searchComponent to one of the standard names,+ that will be used instead of the default.++ To insert components before or after the 'standard' components, use:++ <arr name="first-components">+ <str>myFirstComponentName</str>+ </arr>++ <arr name="last-components">+ <str>myLastComponentName</str>+ </arr>++ NOTE: The component registered with the name "debug" will+ always be executed after the "last-components"++ -->++ <!-- Spell Check++ The spell check component can return a list of alternative spelling+ suggestions.++ http://wiki.apache.org/solr/SpellCheckComponent+ -->+ <searchComponent name="spellcheck" class="solr.SpellCheckComponent">++ <str name="queryAnalyzerFieldType">text_general</str>++ <!-- Multiple "Spell Checkers" can be declared and used by this+ component+ -->++ <!-- a spellchecker built from a field of the main index -->+ <lst name="spellchecker">+ <str name="name">default</str>+ <str name="field">text</str>+ <str name="classname">solr.DirectSolrSpellChecker</str>+ <!-- the spellcheck distance measure used, the default is the internal levenshtein -->+ <str name="distanceMeasure">internal</str>+ <!-- minimum accuracy needed to be considered a valid spellcheck suggestion -->+ <float name="accuracy">0.5</float>+ <!-- the maximum #edits we consider when enumerating terms: can be 1 or 2 -->+ <int name="maxEdits">2</int>+ <!-- the minimum shared prefix when enumerating terms -->+ <int name="minPrefix">1</int>+ <!-- maximum number of inspections per result. -->+ <int name="maxInspections">5</int>+ <!-- minimum length of a query term to be considered for correction -->+ <int name="minQueryLength">4</int>+ <!-- maximum threshold of documents a query term can appear to be considered for correction -->+ <float name="maxQueryFrequency">0.01</float>+ <!-- uncomment this to require suggestions to occur in 1% of the documents+ <float name="thresholdTokenFrequency">.01</float>+ -->+ </lst>++ <!-- a spellchecker that can break or combine words. See "/spell" handler below for usage -->+ <lst name="spellchecker">+ <str name="name">wordbreak</str>+ <str name="classname">solr.WordBreakSolrSpellChecker</str>+ <str name="field">name</str>+ <str name="combineWords">true</str>+ <str name="breakWords">true</str>+ <int name="maxChanges">10</int>+ </lst>++ <!-- a spellchecker that uses a different distance measure -->+ <!--+ <lst name="spellchecker">+ <str name="name">jarowinkler</str>+ <str name="field">spell</str>+ <str name="classname">solr.DirectSolrSpellChecker</str>+ <str name="distanceMeasure">+ org.apache.lucene.search.spell.JaroWinklerDistance+ </str>+ </lst>+ -->++ <!-- a spellchecker that use an alternate comparator++ comparatorClass be one of:+ 1. score (default)+ 2. freq (Frequency first, then score)+ 3. A fully qualified class name+ -->+ <!--+ <lst name="spellchecker">+ <str name="name">freq</str>+ <str name="field">lowerfilt</str>+ <str name="classname">solr.DirectSolrSpellChecker</str>+ <str name="comparatorClass">freq</str>+ -->++ <!-- A spellchecker that reads the list of words from a file -->+ <!--+ <lst name="spellchecker">+ <str name="classname">solr.FileBasedSpellChecker</str>+ <str name="name">file</str>+ <str name="sourceLocation">spellings.txt</str>+ <str name="characterEncoding">UTF-8</str>+ <str name="spellcheckIndexDir">spellcheckerFile</str>+ </lst>+ -->+ </searchComponent>++ <!-- A request handler for demonstrating the spellcheck component.++ NOTE: This is purely as an example. The whole purpose of the+ SpellCheckComponent is to hook it into the request handler that+ handles your normal user queries so that a separate request is+ not needed to get suggestions.++ IN OTHER WORDS, THERE IS REALLY GOOD CHANCE THE SETUP BELOW IS+ NOT WHAT YOU WANT FOR YOUR PRODUCTION SYSTEM!++ See http://wiki.apache.org/solr/SpellCheckComponent for details+ on the request parameters.+ -->+ <requestHandler name="/spell" class="solr.SearchHandler" startup="lazy">+ <lst name="defaults">+ <str name="df">text</str>+ <!-- Solr will use suggestions from both the 'default' spellchecker+ and from the 'wordbreak' spellchecker and combine them.+ collations (re-written queries) can include a combination of+ corrections from both spellcheckers -->+ <str name="spellcheck.dictionary">default</str>+ <str name="spellcheck.dictionary">wordbreak</str>+ <str name="spellcheck">on</str>+ <str name="spellcheck.extendedResults">true</str>+ <str name="spellcheck.count">10</str>+ <str name="spellcheck.alternativeTermCount">5</str>+ <str name="spellcheck.maxResultsForSuggest">5</str>+ <str name="spellcheck.collate">true</str>+ <str name="spellcheck.collateExtendedResults">true</str>+ <str name="spellcheck.maxCollationTries">10</str>+ <str name="spellcheck.maxCollations">5</str>+ </lst>+ <arr name="last-components">+ <str>spellcheck</str>+ </arr>+ </requestHandler>++ <!-- Term Vector Component++ http://wiki.apache.org/solr/TermVectorComponent+ -->+ <searchComponent name="tvComponent" class="solr.TermVectorComponent"/>++ <!-- A request handler for demonstrating the term vector component++ This is purely as an example.++ In reality you will likely want to add the component to your+ already specified request handlers.+ -->+ <requestHandler name="/tvrh" class="solr.SearchHandler" startup="lazy">+ <lst name="defaults">+ <str name="df">text</str>+ <bool name="tv">true</bool>+ </lst>+ <arr name="last-components">+ <str>tvComponent</str>+ </arr>+ </requestHandler>++ <!-- Clustering Component++ http://wiki.apache.org/solr/ClusteringComponent++ You'll need to set the solr.clustering.enabled system property+ when running solr to run with clustering enabled:++ java -Dsolr.clustering.enabled=true -jar start.jar++ -->+ <searchComponent name="clustering"+ enable="${solr.clustering.enabled:false}"+ class="solr.clustering.ClusteringComponent" >+ <!-- Declare an engine -->+ <lst name="engine">+ <!-- The name, only one can be named "default" -->+ <str name="name">default</str>++ <!-- Class name of Carrot2 clustering algorithm.++ Currently available algorithms are:++ * org.carrot2.clustering.lingo.LingoClusteringAlgorithm+ * org.carrot2.clustering.stc.STCClusteringAlgorithm+ * org.carrot2.clustering.kmeans.BisectingKMeansClusteringAlgorithm++ See http://project.carrot2.org/algorithms.html for the+ algorithm's characteristics.+ -->+ <str name="carrot.algorithm">org.carrot2.clustering.lingo.LingoClusteringAlgorithm</str>++ <!-- Overriding values for Carrot2 default algorithm attributes.++ For a description of all available attributes, see:+ http://download.carrot2.org/stable/manual/#chapter.components.+ Use attribute key as name attribute of str elements+ below. These can be further overridden for individual+ requests by specifying attribute key as request parameter+ name and attribute value as parameter value.+ -->+ <str name="LingoClusteringAlgorithm.desiredClusterCountBase">20</str>++ <!-- Location of Carrot2 lexical resources.++ A directory from which to load Carrot2-specific stop words+ and stop labels. Absolute or relative to Solr config directory.+ If a specific resource (e.g. stopwords.en) is present in the+ specified dir, it will completely override the corresponding+ default one that ships with Carrot2.++ For an overview of Carrot2 lexical resources, see:+ http://download.carrot2.org/head/manual/#chapter.lexical-resources+ -->+ <str name="carrot.lexicalResourcesDir">clustering/carrot2</str>++ <!-- The language to assume for the documents.++ For a list of allowed values, see:+ http://download.carrot2.org/stable/manual/#section.attribute.lingo.MultilingualClustering.defaultLanguage+ -->+ <str name="MultilingualClustering.defaultLanguage">ENGLISH</str>+ </lst>+ <lst name="engine">+ <str name="name">stc</str>+ <str name="carrot.algorithm">org.carrot2.clustering.stc.STCClusteringAlgorithm</str>+ </lst>+ </searchComponent>++ <!-- A request handler for demonstrating the clustering component++ This is purely as an example.++ In reality you will likely want to add the component to your+ already specified request handlers.+ -->+ <requestHandler name="/clustering"+ startup="lazy"+ enable="${solr.clustering.enabled:false}"+ class="solr.SearchHandler">+ <lst name="defaults">+ <bool name="clustering">true</bool>+ <str name="clustering.engine">default</str>+ <bool name="clustering.results">true</bool>+ <!-- The title field -->+ <str name="carrot.title">name</str>+ <str name="carrot.url">id</str>+ <!-- The field to cluster on -->+ <str name="carrot.snippet">features</str>+ <!-- produce summaries -->+ <bool name="carrot.produceSummary">true</bool>+ <!-- the maximum number of labels per cluster -->+ <!--<int name="carrot.numDescriptions">5</int>-->+ <!-- produce sub clusters -->+ <bool name="carrot.outputSubClusters">false</bool>++ <str name="defType">edismax</str>+ <str name="qf">+ text^0.5 features^1.0 name^1.2 sku^1.5 id^10.0 manu^1.1 cat^1.4+ </str>+ <str name="q.alt">*:*</str>+ <str name="rows">10</str>+ <str name="fl">*,score</str>+ </lst>+ <arr name="last-components">+ <str>clustering</str>+ </arr>+ </requestHandler>++ <!-- Terms Component++ http://wiki.apache.org/solr/TermsComponent++ A component to return terms and document frequency of those+ terms+ -->+ <searchComponent name="terms" class="solr.TermsComponent"/>++ <!-- A request handler for demonstrating the terms component -->+ <requestHandler name="/terms" class="solr.SearchHandler" startup="lazy">+ <lst name="defaults">+ <bool name="terms">true</bool>+ <bool name="distrib">false</bool>+ </lst>+ <arr name="components">+ <str>terms</str>+ </arr>+ </requestHandler>+++ <!-- Query Elevation Component++ http://wiki.apache.org/solr/QueryElevationComponent++ a search component that enables you to configure the top+ results for a given query regardless of the normal lucene+ scoring.+ -->+ <searchComponent name="elevator" class="solr.QueryElevationComponent" >+ <!-- pick a fieldType to analyze queries -->+ <str name="queryFieldType">string</str>+ <str name="config-file">elevate.xml</str>+ </searchComponent>++ <!-- A request handler for demonstrating the elevator component -->+ <requestHandler name="/elevate" class="solr.SearchHandler" startup="lazy">+ <lst name="defaults">+ <str name="echoParams">explicit</str>+ <str name="df">text</str>+ </lst>+ <arr name="last-components">+ <str>elevator</str>+ </arr>+ </requestHandler>++ <!-- Highlighting Component++ http://wiki.apache.org/solr/HighlightingParameters+ -->+ <searchComponent class="solr.HighlightComponent" name="highlight">+ <highlighting>+ <!-- Configure the standard fragmenter -->+ <!-- This could most likely be commented out in the "default" case -->+ <fragmenter name="gap"+ default="true"+ class="solr.highlight.GapFragmenter">+ <lst name="defaults">+ <int name="hl.fragsize">100</int>+ </lst>+ </fragmenter>++ <!-- A regular-expression-based fragmenter+ (for sentence extraction)+ -->+ <fragmenter name="regex"+ class="solr.highlight.RegexFragmenter">+ <lst name="defaults">+ <!-- slightly smaller fragsizes work better because of slop -->+ <int name="hl.fragsize">70</int>+ <!-- allow 50% slop on fragment sizes -->+ <float name="hl.regex.slop">0.5</float>+ <!-- a basic sentence pattern -->+ <str name="hl.regex.pattern">[-\w ,/\n\"']{20,200}</str>+ </lst>+ </fragmenter>++ <!-- Configure the standard formatter -->+ <formatter name="html"+ default="true"+ class="solr.highlight.HtmlFormatter">+ <lst name="defaults">+ <str name="hl.simple.pre"><![CDATA[<em>]]></str>+ <str name="hl.simple.post"><![CDATA[</em>]]></str>+ </lst>+ </formatter>++ <!-- Configure the standard encoder -->+ <encoder name="html"+ class="solr.highlight.HtmlEncoder" />++ <!-- Configure the standard fragListBuilder -->+ <fragListBuilder name="simple"+ class="solr.highlight.SimpleFragListBuilder"/>++ <!-- Configure the single fragListBuilder -->+ <fragListBuilder name="single"+ class="solr.highlight.SingleFragListBuilder"/>++ <!-- Configure the weighted fragListBuilder -->+ <fragListBuilder name="weighted"+ default="true"+ class="solr.highlight.WeightedFragListBuilder"/>++ <!-- default tag FragmentsBuilder -->+ <fragmentsBuilder name="default"+ default="true"+ class="solr.highlight.ScoreOrderFragmentsBuilder">+ <!--+ <lst name="defaults">+ <str name="hl.multiValuedSeparatorChar">/</str>+ </lst>+ -->+ </fragmentsBuilder>++ <!-- multi-colored tag FragmentsBuilder -->+ <fragmentsBuilder name="colored"+ class="solr.highlight.ScoreOrderFragmentsBuilder">+ <lst name="defaults">+ <str name="hl.tag.pre"><![CDATA[+ <b style="background:yellow">,<b style="background:lawgreen">,+ <b style="background:aquamarine">,<b style="background:magenta">,+ <b style="background:palegreen">,<b style="background:coral">,+ <b style="background:wheat">,<b style="background:khaki">,+ <b style="background:lime">,<b style="background:deepskyblue">]]></str>+ <str name="hl.tag.post"><![CDATA[</b>]]></str>+ </lst>+ </fragmentsBuilder>++ <boundaryScanner name="default"+ default="true"+ class="solr.highlight.SimpleBoundaryScanner">+ <lst name="defaults">+ <str name="hl.bs.maxScan">10</str>+ <str name="hl.bs.chars">.,!? 	 </str>+ </lst>+ </boundaryScanner>++ <boundaryScanner name="breakIterator"+ class="solr.highlight.BreakIteratorBoundaryScanner">+ <lst name="defaults">+ <!-- type should be one of CHARACTER, WORD(default), LINE and SENTENCE -->+ <str name="hl.bs.type">WORD</str>+ <!-- language and country are used when constructing Locale object. -->+ <!-- And the Locale object will be used when getting instance of BreakIterator -->+ <str name="hl.bs.language">en</str>+ <str name="hl.bs.country">US</str>+ </lst>+ </boundaryScanner>+ </highlighting>+ </searchComponent>++ <!-- Update Processors++ Chains of Update Processor Factories for dealing with Update+ Requests can be declared, and then used by name in Update+ Request Processors++ http://wiki.apache.org/solr/UpdateRequestProcessor++ -->+ <!-- Deduplication++ An example dedup update processor that creates the "id" field+ on the fly based on the hash code of some other fields. This+ example has overwriteDupes set to false since we are using the+ id field as the signatureField and Solr will maintain+ uniqueness based on that anyway.++ -->+ <!--+ <updateRequestProcessorChain name="dedupe">+ <processor class="solr.processor.SignatureUpdateProcessorFactory">+ <bool name="enabled">true</bool>+ <str name="signatureField">id</str>+ <bool name="overwriteDupes">false</bool>+ <str name="fields">name,features,cat</str>+ <str name="signatureClass">solr.processor.Lookup3Signature</str>+ </processor>+ <processor class="solr.LogUpdateProcessorFactory" />+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>+ -->++ <!-- Language identification++ This example update chain identifies the language of the incoming+ documents using the langid contrib. The detected language is+ written to field language_s. No field name mapping is done.+ The fields used for detection are text, title, subject and description,+ making this example suitable for detecting languages form full-text+ rich documents injected via ExtractingRequestHandler.+ See more about langId at http://wiki.apache.org/solr/LanguageDetection+ -->+ <!--+ <updateRequestProcessorChain name="langid">+ <processor class="org.apache.solr.update.processor.TikaLanguageIdentifierUpdateProcessorFactory">+ <str name="langid.fl">text,title,subject,description</str>+ <str name="langid.langField">language_s</str>+ <str name="langid.fallback">en</str>+ </processor>+ <processor class="solr.LogUpdateProcessorFactory" />+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>+ -->++ <!-- Script update processor++ This example hooks in an update processor implemented using JavaScript.++ See more about the script update processor at http://wiki.apache.org/solr/ScriptUpdateProcessor+ -->+ <!--+ <updateRequestProcessorChain name="script">+ <processor class="solr.StatelessScriptUpdateProcessorFactory">+ <str name="script">update-script.js</str>+ <lst name="params">+ <str name="config_param">example config parameter</str>+ </lst>+ </processor>+ <processor class="solr.RunUpdateProcessorFactory" />+ </updateRequestProcessorChain>+ -->++ <!-- Response Writers++ http://wiki.apache.org/solr/QueryResponseWriter++ Request responses will be written using the writer specified by+ the 'wt' request parameter matching the name of a registered+ writer.++ The "default" writer is the default and will be used if 'wt' is+ not specified in the request.+ -->+ <!-- The following response writers are implicitly configured unless+ overridden...+ -->+ <!--+ <queryResponseWriter name="xml"+ default="true"+ class="solr.XMLResponseWriter" />+ <queryResponseWriter name="json" class="solr.JSONResponseWriter"/>+ <queryResponseWriter name="python" class="solr.PythonResponseWriter"/>+ <queryResponseWriter name="ruby" class="solr.RubyResponseWriter"/>+ <queryResponseWriter name="php" class="solr.PHPResponseWriter"/>+ <queryResponseWriter name="phps" class="solr.PHPSerializedResponseWriter"/>+ <queryResponseWriter name="csv" class="solr.CSVResponseWriter"/>+ <queryResponseWriter name="schema.xml" class="solr.SchemaXmlResponseWriter"/>+ -->++ <queryResponseWriter name="json" class="solr.JSONResponseWriter">+ <!-- For the purposes of the tutorial, JSON responses are written as+ plain text so that they are easy to read in *any* browser.+ If you expect a MIME type of "application/json" just remove this override.+ -->+ <str name="content-type">text/plain; charset=UTF-8</str>+ </queryResponseWriter>++ <!--+ Custom response writers can be declared as needed...+ -->+ <queryResponseWriter name="velocity" class="solr.VelocityResponseWriter" startup="lazy"/>+++ <!-- XSLT response writer transforms the XML output by any xslt file found+ in Solr's conf/xslt directory. Changes to xslt files are checked for+ every xsltCacheLifetimeSeconds.+ -->+ <queryResponseWriter name="xslt" class="solr.XSLTResponseWriter">+ <int name="xsltCacheLifetimeSeconds">5</int>+ </queryResponseWriter>++ <!-- Query Parsers++ http://wiki.apache.org/solr/SolrQuerySyntax++ Multiple QParserPlugins can be registered by name, and then+ used in either the "defType" param for the QueryComponent (used+ by SearchHandler) or in LocalParams+ -->+ <!-- example of registering a query parser -->+ <!--+ <queryParser name="myparser" class="com.mycompany.MyQParserPlugin"/>+ -->++ <!-- Function Parsers++ http://wiki.apache.org/solr/FunctionQuery++ Multiple ValueSourceParsers can be registered by name, and then+ used as function names when using the "func" QParser.+ -->+ <!-- example of registering a custom function parser -->+ <!--+ <valueSourceParser name="myfunc"+ class="com.mycompany.MyValueSourceParser" />+ -->+++ <!-- Document Transformers+ http://wiki.apache.org/solr/DocTransformers+ -->+ <!--+ Could be something like:+ <transformer name="db" class="com.mycompany.LoadFromDatabaseTransformer" >+ <int name="connection">jdbc://....</int>+ </transformer>++ To add a constant value to all docs, use:+ <transformer name="mytrans2" class="org.apache.solr.response.transform.ValueAugmenterFactory" >+ <int name="value">5</int>+ </transformer>++ If you want the user to still be able to change it with _value:something_ use this:+ <transformer name="mytrans3" class="org.apache.solr.response.transform.ValueAugmenterFactory" >+ <double name="defaultValue">5</double>+ </transformer>++ If you are using the QueryElevationComponent, you may wish to mark documents that get boosted. The+ EditorialMarkerFactory will do exactly that:+ <transformer name="qecBooster" class="org.apache.solr.response.transform.EditorialMarkerFactory" />+ -->+++ <!-- Legacy config for the admin interface -->+ <admin>+ <defaultQuery>*:*</defaultQuery>+ </admin>++</config>diff --git a/solr/example/resources/log4j.properties b/solr/example/resources/log4j.propertiesindex 93dc62aaf77..d9becb605d6 100644--- a/solr/example/resources/log4j.properties+++ b/solr/example/resources/log4j.properties@@ -1,4 +1,5 @@# Logging level+solr.log=logs/log4j.rootLogger=INFO, file, CONSOLElog4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender@@ -12,8 +13,9 @@ log4j.appender.file.MaxFileSize=4MBlog4j.appender.file.MaxBackupIndex=9#- File to log to and log format-log4j.appender.file.File=logs/solr.log+log4j.appender.file.File=${solr.log}/solr.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n-log4j.logger.org.apache.zookeeper=WARN\ No newline at end of file+log4j.logger.org.apache.zookeeper=WARN+log4j.logger.org.apache.hadoop=WARNdiff --git a/solr/example/solr/solr.xml b/solr/example/solr/solr.xmlindex d02800b622a..7ae7244baa5 100644--- a/solr/example/solr/solr.xml+++ b/solr/example/solr/solr.xml@@ -33,6 +33,7 @@<int name="hostPort">${jetty.port:8983}</int><str name="hostContext">${hostContext:solr}</str><int name="zkClientTimeout">${zkClientTimeout:15000}</int>+ <bool name="genericCoreNodeNames">${genericCoreNodeNames:true}</bool></solrcloud><shardHandlerFactory name="shardHandlerFactory"diff --git a/solr/licenses/commons-configuration-1.6.jar.sha1 b/solr/licenses/commons-configuration-1.6.jar.sha1new file mode 100644index 00000000000..1f4ad4746b3--- /dev/null+++ b/solr/licenses/commons-configuration-1.6.jar.sha1@@ -0,0 +1 @@+32cadde23955d7681b0d94a2715846d20b425235diff --git a/solr/licenses/commons-configuration-LICENSE-ASL.txt b/solr/licenses/commons-configuration-LICENSE-ASL.txtnew file mode 100644index 00000000000..dd726f2eaf1--- /dev/null+++ b/solr/licenses/commons-configuration-LICENSE-ASL.txt@@ -0,0 +1,403 @@+++ 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.\ No newline at end of filediff --git a/solr/licenses/commons-configuration-NOTICE.txt b/solr/licenses/commons-configuration-NOTICE.txtnew file mode 100644index 00000000000..191633594a8--- /dev/null+++ b/solr/licenses/commons-configuration-NOTICE.txt@@ -0,0 +1,9 @@+Apache Commons Configuration++Copyright 2001-2008 The Apache Software Foundation++++This product includes software developed by++The Apache Software Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/concurrentlinkedhashmap-lru-1.2.jar.sha1 b/solr/licenses/concurrentlinkedhashmap-lru-1.2.jar.sha1new file mode 100644index 00000000000..9c0fe8a75d2--- /dev/null+++ b/solr/licenses/concurrentlinkedhashmap-lru-1.2.jar.sha1@@ -0,0 +1 @@+4316d710b6619ffe210c98deb2b0893587dad454diff --git a/solr/licenses/concurrentlinkedhashmap-lru-LICENSE-ASL.txt b/solr/licenses/concurrentlinkedhashmap-lru-LICENSE-ASL.txtnew file mode 100644index 00000000000..dd726f2eaf1--- /dev/null+++ b/solr/licenses/concurrentlinkedhashmap-lru-LICENSE-ASL.txt@@ -0,0 +1,403 @@+++ 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.\ No newline at end of filediff --git a/solr/licenses/concurrentlinkedhashmap-lru-NOTICE.txt b/solr/licenses/concurrentlinkedhashmap-lru-NOTICE.txtnew file mode 100644index 00000000000..e69de29bb2ddiff --git a/solr/licenses/hadoop-annotations-2.0.5-alpha.jar.sha1 b/solr/licenses/hadoop-annotations-2.0.5-alpha.jar.sha1new file mode 100644index 00000000000..b3ae758df40--- /dev/null+++ b/solr/licenses/hadoop-annotations-2.0.5-alpha.jar.sha1@@ -0,0 +1 @@+64e2b38638f3b3ecf14806a12c919334ebd77ff7diff --git a/solr/licenses/hadoop-annotations-LICENSE-ASL.txt b/solr/licenses/hadoop-annotations-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-annotations-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-annotations-NOTICE.txt b/solr/licenses/hadoop-annotations-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-annotations-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/hadoop-auth-2.0.5-alpha.jar.sha1 b/solr/licenses/hadoop-auth-2.0.5-alpha.jar.sha1new file mode 100644index 00000000000..d53dcc4f5ef--- /dev/null+++ b/solr/licenses/hadoop-auth-2.0.5-alpha.jar.sha1@@ -0,0 +1 @@+8ca2f6521f2582bd3b95575614d6866d81e224b7diff --git a/solr/licenses/hadoop-auth-LICENSE-ASL.txt b/solr/licenses/hadoop-auth-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-auth-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-auth-NOTICE.txt b/solr/licenses/hadoop-auth-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-auth-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/hadoop-common-2.0.0-cdh4.2.0-SNAPSHOT-tests-NOTICE.txt b/solr/licenses/hadoop-common-2.0.0-cdh4.2.0-SNAPSHOT-tests-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-common-2.0.0-cdh4.2.0-SNAPSHOT-tests-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/hadoop-common-2.0.5-alpha-tests.jar.sha1 b/solr/licenses/hadoop-common-2.0.5-alpha-tests.jar.sha1new file mode 100644index 00000000000..c869ddf8a74--- /dev/null+++ b/solr/licenses/hadoop-common-2.0.5-alpha-tests.jar.sha1@@ -0,0 +1 @@+58d40fdc9428d1b0eec42b951a7c7ecba5d91b1adiff --git a/solr/licenses/hadoop-common-2.0.5-alpha.jar.sha1 b/solr/licenses/hadoop-common-2.0.5-alpha.jar.sha1new file mode 100644index 00000000000..e85d29354d2--- /dev/null+++ b/solr/licenses/hadoop-common-2.0.5-alpha.jar.sha1@@ -0,0 +1 @@+86250ad536d7bb46f7d7d7f25863343d140a83c2diff --git a/solr/licenses/hadoop-common-LICENSE-ASL.txt b/solr/licenses/hadoop-common-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-common-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-common-NOTICE.txt b/solr/licenses/hadoop-common-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-common-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/hadoop-common-tests-LICENSE-ASL.txt b/solr/licenses/hadoop-common-tests-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-common-tests-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-hdfs-2.0.5-alpha-tests.jar.sha1 b/solr/licenses/hadoop-hdfs-2.0.5-alpha-tests.jar.sha1new file mode 100644index 00000000000..258080fd0cc--- /dev/null+++ b/solr/licenses/hadoop-hdfs-2.0.5-alpha-tests.jar.sha1@@ -0,0 +1 @@+453231318386c5ad0285c189362013d085da18d8diff --git a/solr/licenses/hadoop-hdfs-2.0.5-alpha.jar.sha1 b/solr/licenses/hadoop-hdfs-2.0.5-alpha.jar.sha1new file mode 100644index 00000000000..d3641c8ef55--- /dev/null+++ b/solr/licenses/hadoop-hdfs-2.0.5-alpha.jar.sha1@@ -0,0 +1 @@+ef9f0780c8a4a82f01db076c1738453d4b40d7f3diff --git a/solr/licenses/hadoop-hdfs-LICENSE-ASL.txt b/solr/licenses/hadoop-hdfs-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-hdfs-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-hdfs-NOTICE.txt b/solr/licenses/hadoop-hdfs-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-hdfs-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/hadoop-hdfs-tests-LICENSE-ASL.txt b/solr/licenses/hadoop-hdfs-tests-LICENSE-ASL.txtnew file mode 100644index 00000000000..9a8e847ee84--- /dev/null+++ b/solr/licenses/hadoop-hdfs-tests-LICENSE-ASL.txt@@ -0,0 +1,244 @@++ 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 HADOOP SUBCOMPONENTS:++The Apache Hadoop project contains subcomponents with separate copyright+notices and license terms. Your use of the source code for the these+subcomponents is subject to the terms and conditions of the following+licenses.++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.+ */\ No newline at end of filediff --git a/solr/licenses/hadoop-hdfs-tests-NOTICE.txt b/solr/licenses/hadoop-hdfs-tests-NOTICE.txtnew file mode 100644index 00000000000..c56a5e4eac1--- /dev/null+++ b/solr/licenses/hadoop-hdfs-tests-NOTICE.txt@@ -0,0 +1,2 @@+This product includes software developed by The Apache Software+Foundation (http://www.apache.org/).\ No newline at end of filediff --git a/solr/licenses/jersey-core-1.16.jar.sha1 b/solr/licenses/jersey-core-1.16.jar.sha1new file mode 100644index 00000000000..28e748dc38e--- /dev/null+++ b/solr/licenses/jersey-core-1.16.jar.sha1@@ -0,0 +1 @@+34e9e164039913283da97af8d806ed92a931d32bdiff --git a/solr/licenses/jersey-core-LICENSE-CDDL.txt b/solr/licenses/jersey-core-LICENSE-CDDL.txtnew file mode 100644index 00000000000..542df80fe67--- /dev/null+++ b/solr/licenses/jersey-core-LICENSE-CDDL.txt@@ -0,0 +1,81 @@+COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL)Version 1.1++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.+Oracle 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. If You assert a patent infringement claim against Participant alleging that the Participant Software directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license.+6.4. 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 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.\ No newline at end of filediff --git a/solr/licenses/jetty-6.1.26.jar.sha1 b/solr/licenses/jetty-6.1.26.jar.sha1new file mode 100644index 00000000000..9d5e6477a42--- /dev/null+++ b/solr/licenses/jetty-6.1.26.jar.sha1@@ -0,0 +1 @@+2f546e289fddd5b1fab1d4199fbb6e9ef43ee4b0diff --git a/solr/licenses/jetty-util-6.1.26.jar.sha1 b/solr/licenses/jetty-util-6.1.26.jar.sha1new file mode 100644index 00000000000..a5f4c5017a0--- /dev/null+++ b/solr/licenses/jetty-util-6.1.26.jar.sha1@@ -0,0 +1 @@+e5642fe0399814e1687d55a3862aa5a3417226a9diff --git a/solr/licenses/log4j-1.2.17.jar.sha1 b/solr/licenses/log4j-1.2.17.jar.sha1new file mode 100644index 00000000000..383110e29f1--- /dev/null+++ b/solr/licenses/log4j-1.2.17.jar.sha1@@ -0,0 +1 @@+5af35056b4d257e4b64b9e8069c0746e8b08629fdiff --git a/solr/licenses/protobuf-java-2.4.0a.jar.sha1 b/solr/licenses/protobuf-java-2.4.0a.jar.sha1new file mode 100644index 00000000000..816bf0364be--- /dev/null+++ b/solr/licenses/protobuf-java-2.4.0a.jar.sha1@@ -0,0 +1 @@+7ef75b63dc8797d36cca1e3c08665117cc69e52fdiff --git a/solr/licenses/protobuf-java-LICENSE-BSD.txt b/solr/licenses/protobuf-java-LICENSE-BSD.txtnew file mode 100644index 00000000000..28888af8f5d--- /dev/null+++ b/solr/licenses/protobuf-java-LICENSE-BSD.txt@@ -0,0 +1,9 @@+Copyright (c) <YEAR>, <OWNER>+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 <ORGANIZATION> 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 HOLDER 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.\ No newline at end of filediff --git a/solr/licenses/protobuf-java-NOTICE.txt b/solr/licenses/protobuf-java-NOTICE.txtnew file mode 100644index 00000000000..c5fd9f3ec0e--- /dev/null+++ b/solr/licenses/protobuf-java-NOTICE.txt@@ -0,0 +1,3 @@+Protocol Buffers - Google's data interchange format+Copyright 2008 Google Inc.+http://code.google.com/apis/protocolbuffers/\ No newline at end of filediff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.javaindex 7e79bcea2f8..123b0f20909 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ClusterState.java@@ -165,15 +165,18 @@ public class ClusterState implements JSONWriter.Writable {return Collections.unmodifiableSet(liveNodes);}- /**- * Get the slice/shardId for a core.- * @param coreNodeName in the form of nodeName_coreName (the name of the replica)- */- public String getShardId(String coreNodeName) {- // System.out.println("###### getShardId("+coreNodeName+") in " + collectionStates);+ public String getShardId(String baseUrl, String coreName) {+ // System.out.println("###### getShardId(" + baseUrl + "," + coreName + ") in " + collectionStates);for (DocCollection coll : collectionStates.values()) {for (Slice slice : coll.getSlices()) {- if (slice.getReplicasMap().containsKey(coreNodeName)) return slice.getName();+ for (Replica replica : slice.getReplicas()) {+ // TODO: for really large clusters, we could 'index' on this+ String rbaseUrl = replica.getStr(ZkStateReader.BASE_URL_PROP);+ String rcore = replica.getStr(ZkStateReader.CORE_NAME_PROP);+ if (baseUrl.equals(rbaseUrl) && coreName.equals(rcore)) {+ return slice.getName();+ }+ }}}return null;diff --git a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.javaindex 6365eef0a6f..356f14b9b95 100644--- a/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java+++ b/solr/solrj/src/java/org/apache/solr/common/cloud/ZkStateReader.java@@ -508,6 +508,7 @@ public class ZkStateReader {public List<ZkCoreNodeProps> getReplicaProps(String collection,String shardId, String thisCoreNodeName, String coreName, String mustMatchStateFilter, String mustNotMatchStateFilter) {+ assert thisCoreNodeName != null;ClusterState clusterState = this.clusterState;if (clusterState == null) {return null;@@ -540,7 +541,7 @@ public class ZkStateReader {}}if (nodes.size() == 0) {- // no replicas - go local+ // no replicasreturn null;}diff --git a/solr/solrj/src/test-files/solrj/log4j.properties b/solr/solrj/src/test-files/solrj/log4j.propertiesindex fbc817f6e05..9b74a5f22b2 100644--- a/solr/solrj/src/test-files/solrj/log4j.properties+++ b/solr/solrj/src/test-files/solrj/log4j.properties@@ -7,3 +7,4 @@ log4j.appender.CONSOLE.layout=org.apache.solr.util.SolrLogLayoutlog4j.appender.CONSOLE.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\nlog4j.logger.org.apache.zookeeper=WARN+log4j.logger.org.apache.hadoop=WARNdiff --git a/solr/solrj/src/test-files/solrj/solr/shared/solr.xml b/solr/solrj/src/test-files/solrj/solr/shared/solr.xmlindex 48e091b78ff..55c18eb642c 100644--- a/solr/solrj/src/test-files/solrj/solr/shared/solr.xml+++ b/solr/solrj/src/test-files/solrj/solr/shared/solr.xml@@ -30,7 +30,7 @@adminPath: RequestHandler path to manage cores.If 'null' (or absent), cores will not be manageable via REST-->- <cores adminPath="/admin/cores" defaultCoreName="core0" host="127.0.0.1" hostPort="${hostPort:8983}" hostContext="${hostContext:solr}" zkClientTimeout="8000">+ <cores adminPath="/admin/cores" defaultCoreName="core0" host="127.0.0.1" hostPort="${hostPort:8983}" hostContext="${hostContext:solr}" zkClientTimeout="8000" genericCoreNodeNames="${genericCoreNodeNames:true}"><core name="collection1" instanceDir="." /><core name="core0" instanceDir="${theInstanceDir:./}" dataDir="${dataDir1}" collection="${collection:acollection}"><property name="version" value="3.5"/>diff --git a/solr/solrj/src/test-files/solrj/solr/solr.xml b/solr/solrj/src/test-files/solrj/solr/solr.xmlindex 44d0f78a33d..73d11117219 100644--- a/solr/solrj/src/test-files/solrj/solr/solr.xml+++ b/solr/solrj/src/test-files/solrj/solr/solr.xml@@ -28,7 +28,7 @@adminPath: RequestHandler path to manage cores.If 'null' (or absent), cores will not be manageable via request handler-->- <cores adminPath="/admin/cores" defaultCoreName="collection1" host="127.0.0.1" hostPort="${hostPort:8983}" hostContext="${hostContext:solr}" zkClientTimeout="8000" numShards="${numShards:3}">+ <cores adminPath="/admin/cores" defaultCoreName="collection1" host="127.0.0.1" hostPort="${hostPort:8983}" hostContext="${hostContext:solr}" zkClientTimeout="8000" genericCoreNodeNames="${genericCoreNodeNames:true}"><core name="collection1" instanceDir="collection1" shard="${shard:}" collection="${collection:collection1}" config="${solrconfig:solrconfig.xml}" schema="${schema:schema.xml}"/></cores></solr>diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.javaindex 58645d4f872..3d2282e669b 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/embedded/TestSolrProperties.java@@ -196,7 +196,8 @@ public class TestSolrProperties extends AbstractEmbeddedSolrServerTestCase {exists("/solr/cores[@zkClientTimeout='8000']", document));assertTrue("\"/solr/cores[@hostContext='${hostContext:solr}']\" doesn't match in:\n" + solrPersistXml,exists("/solr/cores[@hostContext='${hostContext:solr}']", document));-+ assertTrue("\"/solr/cores[@genericCoreNodeNames='${genericCoreNodeNames:true}']\" doesn't match in:\n" + solrPersistXml,+ exists("/solr/cores[@genericCoreNodeNames='${genericCoreNodeNames:true}']", document));} finally {fis.close();}diff --git a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.javaindex e432bdcfcaa..d1ae630dcff 100644--- a/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java+++ b/solr/solrj/src/test/org/apache/solr/client/solrj/request/TestCoreAdmin.java@@ -103,7 +103,7 @@ public class TestCoreAdmin extends AbstractEmbeddedSolrServerTestCase {File logDir;try {- logDir = core.getUpdateHandler().getUpdateLog().getLogDir();+ logDir = new File(core.getUpdateHandler().getUpdateLog().getLogDir());} finally {coreProveIt.close();core.close();diff --git a/solr/test-framework/ivy.xml b/solr/test-framework/ivy.xmlindex 3de08223390..4e1b30fcdbf 100644--- a/solr/test-framework/ivy.xml+++ b/solr/test-framework/ivy.xml@@ -16,7 +16,10 @@specific language governing permissions and limitationsunder the License.-->-<ivy-module version="2.0">+<!DOCTYPE ivy-module [+ <!ENTITY hadoop.version "2.0.5-alpha">+]>+<ivy-module version="2.0" xmlns:m="http://ant.apache.org/ivy/maven"><info organisation="org.apache.solr" module="solr-test-framework"/><configurations>@@ -31,10 +34,25 @@<dependencies defaultconf="default"><dependency org="org.apache.ant" name="ant" rev="1.8.2" transitive="false" />- <dependency org="junit" name="junit" rev="4.10" transitive="false" conf="default->*;junit4-stdalone->*" />+ <dependency org="junit" name="junit" rev="4.10" transitive="false" conf="default->*;junit4-stdalone->*">+ <exclude org="org.hamcrest" module="hamcrest-core"/>+ </dependency><dependency org="com.carrotsearch.randomizedtesting" name="junit4-ant" rev="2.0.10" transitive="false" conf="default->*;junit4-stdalone->*" /><dependency org="com.carrotsearch.randomizedtesting" name="randomizedtesting-runner" rev="2.0.10" transitive="false" conf="default->*;junit4-stdalone->*" />+ <!-- Hadoop DfsMiniCluster Dependencies-->+ <dependency org="org.apache.hadoop" name="hadoop-common" transitive="false" rev="&hadoop.version;" conf="default->*;junit4-stdalone->*">+ <artifact name="hadoop-common" type="tests" ext="jar" m:classifier="tests" />+ </dependency>+ <dependency org="org.apache.hadoop" name="hadoop-hdfs" transitive="false" rev="&hadoop.version;" conf="default->*;junit4-stdalone->*">+ <artifact name="hadoop-hdfs" type="tests" ext="jar" m:classifier="tests" />+ </dependency>+ <dependency org="log4j" name="log4j" rev="1.2.17" transitive="false" />+ <dependency org="org.mortbay.jetty" name="jetty" rev="6.1.26" transitive="false"/>+ <dependency org="org.mortbay.jetty" name="jetty-util" rev="6.1.26" transitive="false"/>+ <dependency org="com.sun.jersey" name="jersey-core" rev="1.16" transitive="false"/>+ <dependency org="commons-collections" name="commons-collections" rev="3.2.1" transitive="false"/>+<exclude org="*" ext="*" matcher="regexp" type="${ivy.exclude.types}"/></dependencies></ivy-module>diff --git a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.javaindex 7b590046733..c2e1d35a0b4 100755--- a/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java+++ b/solr/test-framework/src/java/org/apache/solr/SolrTestCaseJ4.java@@ -345,6 +345,9 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {* The directory used to story the index managed by the TestHarness h*/protected static File dataDir;++ // hack due to File dataDir+ protected static String hdfsDataDir;/*** Initializes things your test might need@@ -395,8 +398,7 @@ public abstract class SolrTestCaseJ4 extends LuceneTestCase {public static void createCore() {assertNotNull(testSolrHome);solrConfig = TestHarness.createConfig(testSolrHome, coreName, getSolrConfigFile());- h = new TestHarness( coreName,- dataDir.getAbsolutePath(),+ h = new TestHarness( coreName, hdfsDataDir == null ? dataDir.getAbsolutePath() : hdfsDataDir,solrConfig,getSchemaFile());lrf = h.getRequestFactorydiff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.javaindex a3919516fa5..70f1c8418bc 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractDistribZkTestBase.java@@ -128,7 +128,7 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTesprotected void waitForRecoveriesToFinish(String collection, ZkStateReader zkStateReader, boolean verbose, boolean failOnTimeout)throws Exception {- waitForRecoveriesToFinish(collection, zkStateReader, verbose, failOnTimeout, 230);+ waitForRecoveriesToFinish(collection, zkStateReader, verbose, failOnTimeout, 330);}protected void waitForRecoveriesToFinish(String collection,@@ -151,8 +151,7 @@ public abstract class AbstractDistribZkTestBase extends BaseDistributedSearchTesif (verbose) System.out.println("rstate:"+ shard.getValue().getStr(ZkStateReader.STATE_PROP)+ " live:"- + clusterState.liveNodesContain(shard.getValue().getStr(- ZkStateReader.NODE_NAME_PROP)));+ + clusterState.liveNodesContain(shard.getValue().getNodeName()));String state = shard.getValue().getStr(ZkStateReader.STATE_PROP);if ((state.equals(ZkStateReader.RECOVERING) || state.equals(ZkStateReader.SYNC) || state.equals(ZkStateReader.DOWN))diff --git a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.javaindex c2db59feb0a..ec05e54f7e2 100644--- a/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java+++ b/solr/test-framework/src/java/org/apache/solr/cloud/AbstractFullDistribZkTestBase.java@@ -197,6 +197,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTes@AfterClasspublic static void afterClass() {System.clearProperty("solrcloud.update.delay");+ System.clearProperty("genericCoreNodeNames");}public AbstractFullDistribZkTestBase() {@@ -211,6 +212,10 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesuseExplicitNodeNames = random().nextBoolean();}+ protected String getDataDir(String dataDir) throws IOException {+ return dataDir;+ }+protected void initCloud() throws Exception {assert(cloudInit == false);cloudInit = true;@@ -328,8 +333,8 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesgetClass().getName() + "-jetty" + cnt + "-" + System.currentTimeMillis());jettyDir.mkdirs();setupJettySolrHome(jettyDir);- JettySolrRunner j = createJetty(jettyDir, testDir + "/jetty"- + cnt, null, "solrconfig.xml", null);+ JettySolrRunner j = createJetty(jettyDir, getDataDir(testDir + "/jetty"+ + cnt), null, "solrconfig.xml", null);jettys.add(j);SolrServer client = createNewSolrServer(j.getLocalPort());clients.add(client);@@ -428,6 +433,28 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesreturn cnt;}+ public JettySolrRunner createJetty(String dataDir, String ulogDir, String shardList,+ String solrConfigOverride) throws Exception {++ JettySolrRunner jetty = new JettySolrRunner(getSolrHome(), context, 0,+ solrConfigOverride, null, false, getExtraServlets());+ jetty.setShards(shardList);+ jetty.setDataDir(getDataDir(dataDir));+ jetty.start();++ return jetty;+ }++ public JettySolrRunner createJetty(File solrHome, String dataDir, String shardList, String solrConfigOverride, String schemaOverride) throws Exception {++ JettySolrRunner jetty = new JettySolrRunner(solrHome.getAbsolutePath(), context, 0, solrConfigOverride, schemaOverride, false, getExtraServlets());+ jetty.setShards(shardList);+ jetty.setDataDir(getDataDir(dataDir));+ jetty.start();++ return jetty;+ }+protected void updateMappingsFromZk(List<JettySolrRunner> jettys,List<SolrServer> clients) throws Exception {ZkStateReader zkStateReader = cloudClient.getZkStateReader();@@ -483,7 +510,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTescjr.jetty = jetty;cjr.info = replica;cjr.nodeName = replica.getStr(ZkStateReader.NODE_NAME_PROP);- cjr.coreNodeName = replica.getName();+ cjr.coreNodeName = replica.getNodeName();cjr.url = replica.getStr(ZkStateReader.BASE_URL_PROP) + "/" + replica.getStr(ZkStateReader.CORE_NAME_PROP);cjr.client = findClientByPort(port, theClients);list.add(cjr);@@ -1519,7 +1546,7 @@ public abstract class AbstractFullDistribZkTestBase extends AbstractDistribZkTesfor (String sliceName : slices.keySet()) {for (Replica replica : slices.get(sliceName).getReplicas()) {if (nodesAllowedToRunShards != null && !nodesAllowedToRunShards.contains(replica.getStr(ZkStateReader.NODE_NAME_PROP))) {- return "Shard " + replica.getName() + " created on node " + replica.getStr(ZkStateReader.NODE_NAME_PROP) + " not allowed to run shards for the created collection " + collectionName;+ return "Shard " + replica.getName() + " created on node " + replica.getNodeName() + " not allowed to run shards for the created collection " + collectionName;}}totalShards += slices.get(sliceName).getReplicas().size();diff --git a/solr/test-framework/src/java/org/apache/solr/util/TestHarness.java b/solr/test-framework/src/java/org/apache/solr/util/TestHarness.javaindex 2cff033457a..e0c5433a9db 100644--- a/solr/test-framework/src/java/org/apache/solr/util/TestHarness.java+++ b/solr/test-framework/src/java/org/apache/solr/util/TestHarness.java@@ -18,6 +18,7 @@package org.apache.solr.util;import org.apache.solr.common.SolrException;+import org.apache.solr.common.cloud.Slice;import org.apache.solr.common.params.CommonParams;import org.apache.solr.common.util.NamedList;import org.apache.solr.core.Config;@@ -187,7 +188,7 @@ public class TestHarness extends BaseTestHarness {String hostContext = System.getProperty("hostContext", "solr");defaultCoreName = CoreContainer.DEFAULT_DEFAULT_CORE_NAME;initShardHandler();- zkSys.initZooKeeper(this, solrHome, System.getProperty("zkHost"), 30000, hostPort, hostContext, null, "30000", 30000, 30000);+ zkSys.initZooKeeper(this, solrHome, System.getProperty("zkHost"), 30000, hostPort, hostContext, null, "30000", true, 30000, 30000);ByteArrayInputStream is = new ByteArrayInputStream(ConfigSolrXmlOld.DEF_SOLR_XML.getBytes("UTF-8"));Config config = new Config(loader, null, new InputSource(is), null, false);cfg = new ConfigSolrXmlOld(config, this);@@ -205,6 +206,9 @@ public class TestHarness extends BaseTestHarness {container.setLogging(logging);CoreDescriptor dcore = new CoreDescriptor(container, coreName, solrConfig.getResourceLoader().getInstanceDir());+ if (container.isZooKeeperAware()) {+ container.getZkController().preRegister(dcore);+ }dcore.setConfigName(solrConfig.getResourceName());dcore.setSchemaName(indexSchema.getResourceName());@@ -213,6 +217,12 @@ public class TestHarness extends BaseTestHarness {}SolrCore core = new SolrCore(coreName, dataDirectory, solrConfig, indexSchema, dcore);++ if (container.isZooKeeperAware() && Slice.CONSTRUCTION.equals(dcore.getCloudDescriptor().getShardState())) {+ // set update log to buffer before publishing the core+ core.getUpdateHandler().getUpdateLog().bufferUpdates();+ }+container.register(coreName, core, false);// TODO: we should be exercising the *same* core container initialization code, not equivalent code!