atris commented on a change in pull request #2403:
URL: https://github.com/apache/lucene-solr/pull/2403#discussion_r592959697



##########
File path: solr/core/src/test/org/apache/solr/search/TestTaskManagement.java
##########
@@ -0,0 +1,263 @@
+/*
+ * 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 org.apache.lucene.util.BytesRef;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.cloud.SolrCloudTestCase;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.eclipse.jetty.util.ConcurrentHashSet;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+
+public class TestTaskManagement extends SolrCloudTestCase {
+    private static final String COLLECTION_NAME = "collection1";
+
+    private ExecutorService executorService;
+
+    @BeforeClass
+    public static void setupCluster() throws Exception {
+        initCore("solrconfig.xml", "schema11.xml");
+
+        configureCluster(4)
+                .addConfig("conf", configset("sql"))
+                .configure();
+    }
+
+    @AfterClass
+    public static void tearDownCluster() throws Exception {
+        shutdownCluster();
+    }
+
+    @Before
+    public void setup() throws Exception {
+        super.setUp();
+
+        CollectionAdminRequest.createCollection(COLLECTION_NAME, "conf", 2, 1)
+                .setPerReplicaState(SolrCloudTestCase.USE_PER_REPLICA_STATE)
+                .process(cluster.getSolrClient());
+        cluster.waitForActiveCollection(COLLECTION_NAME, 2, 2);
+        cluster.getSolrClient().setDefaultCollection(COLLECTION_NAME);
+
+        cluster.getSolrClient().setDefaultCollection("collection1");
+
+        executorService = 
ExecutorUtil.newMDCAwareCachedThreadPool("TestTaskManagement");
+
+        List<SolrInputDocument> docs = new ArrayList<>();
+        for (int i = 0; i < 100; i++) {
+            SolrInputDocument doc = new SolrInputDocument();
+            doc.addField("id", i);
+            doc.addField("foo1_s", Integer.toString(i));
+            doc.addField("foo2_s", Boolean.toString(i % 2 == 0));
+            doc.addField("foo4_s", new BytesRef(Boolean.toString(i % 2 == 0)));
+
+            docs.add(doc);
+        }
+
+        cluster.getSolrClient().add(docs);
+        cluster.getSolrClient().commit();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        
CollectionAdminRequest.deleteCollection(COLLECTION_NAME).process(cluster.getSolrClient());
+        executorService.shutdown();
+        super.tearDown();
+    }
+
+    @Test
+    public void testNonExistentQuery() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        params.set("cancelUUID", "foobar");
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+        request.setPath("/tasks/cancel");
+
+        NamedList<Object> queryResponse = null;
+
+        queryResponse = cluster.getSolrClient().request(request);
+
+        assertEquals("Query with queryID foobar not found", 
queryResponse.get("status"));
+    }
+
+    @Test
+    public void testCancellationQuery() throws Exception {
+        ConcurrentHashSet<Integer> queryIdsSet = new ConcurrentHashSet<>();

Review comment:
       Sorry, missed a lot of comments. Fixing now.

##########
File path: solr/core/src/test/org/apache/solr/search/TestTaskManagement.java
##########
@@ -0,0 +1,263 @@
+/*
+ * 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 org.apache.lucene.util.BytesRef;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.cloud.SolrCloudTestCase;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.eclipse.jetty.util.ConcurrentHashSet;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+
+public class TestTaskManagement extends SolrCloudTestCase {
+    private static final String COLLECTION_NAME = "collection1";
+
+    private ExecutorService executorService;
+
+    @BeforeClass
+    public static void setupCluster() throws Exception {
+        initCore("solrconfig.xml", "schema11.xml");
+
+        configureCluster(4)
+                .addConfig("conf", configset("sql"))
+                .configure();
+    }
+
+    @AfterClass
+    public static void tearDownCluster() throws Exception {
+        shutdownCluster();
+    }
+
+    @Before
+    public void setup() throws Exception {
+        super.setUp();
+
+        CollectionAdminRequest.createCollection(COLLECTION_NAME, "conf", 2, 1)
+                .setPerReplicaState(SolrCloudTestCase.USE_PER_REPLICA_STATE)
+                .process(cluster.getSolrClient());
+        cluster.waitForActiveCollection(COLLECTION_NAME, 2, 2);
+        cluster.getSolrClient().setDefaultCollection(COLLECTION_NAME);
+
+        cluster.getSolrClient().setDefaultCollection("collection1");
+
+        executorService = 
ExecutorUtil.newMDCAwareCachedThreadPool("TestTaskManagement");
+
+        List<SolrInputDocument> docs = new ArrayList<>();
+        for (int i = 0; i < 100; i++) {
+            SolrInputDocument doc = new SolrInputDocument();
+            doc.addField("id", i);
+            doc.addField("foo1_s", Integer.toString(i));
+            doc.addField("foo2_s", Boolean.toString(i % 2 == 0));
+            doc.addField("foo4_s", new BytesRef(Boolean.toString(i % 2 == 0)));
+
+            docs.add(doc);
+        }
+
+        cluster.getSolrClient().add(docs);
+        cluster.getSolrClient().commit();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        
CollectionAdminRequest.deleteCollection(COLLECTION_NAME).process(cluster.getSolrClient());
+        executorService.shutdown();
+        super.tearDown();
+    }
+
+    @Test
+    public void testNonExistentQuery() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        params.set("cancelUUID", "foobar");
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+        request.setPath("/tasks/cancel");
+
+        NamedList<Object> queryResponse = null;
+
+        queryResponse = cluster.getSolrClient().request(request);
+
+        assertEquals("Query with queryID foobar not found", 
queryResponse.get("status"));
+    }
+
+    @Test
+    public void testCancellationQuery() throws Exception {
+        ConcurrentHashSet<Integer> queryIdsSet = new ConcurrentHashSet<>();
+        ConcurrentHashSet<Integer> notFoundIdsSet = new ConcurrentHashSet<>();
+
+        List<CompletableFuture<Void>> queryFutures = new ArrayList<>();
+
+        for (int i = 0; i < 100; i++) {
+            CompletableFuture<Void> future = 
executeQueryAsync(Integer.toString(i));
+
+            queryFutures.add(future);
+        }
+
+        List<CompletableFuture<Void>> futures = new ArrayList<>();
+
+        for (int i = 0; i < 90; i++) {
+            CompletableFuture<Void> future = cancelQuery(Integer.toString(i), 
4000, queryIdsSet, notFoundIdsSet);
+
+            futures.add(future);
+        }
+
+        futures.forEach(CompletableFuture::join);
+
+        queryFutures.forEach(CompletableFuture::join);
+
+        assertTrue(queryIdsSet.size() + notFoundIdsSet.size() == 90);
+    }
+
+    @Test
+    public void testListCancellableQueries() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+        request.setPath("/tasks/list");
+
+        for (int i = 0; i < 50; i++) {
+            executeQueryAsync(Integer.toString(i));
+        }
+
+        NamedList<Object> queryResponse = null;
+
+        queryResponse = cluster.getSolrClient().request(request);
+
+        @SuppressWarnings({"unchecked"})
+        NamedList<String> result = (NamedList<String>) 
queryResponse.get("taskList");
+
+        Iterator<Map.Entry<String, String>> iterator = result.iterator();
+
+        Set<Integer> presentQueryIDs = new HashSet<>();
+
+        while (iterator.hasNext()) {
+            Map.Entry<String, String> entry = iterator.next();
+
+            presentQueryIDs.add(Integer.parseInt(entry.getKey()));
+        }
+
+        assertTrue(presentQueryIDs.size() > 0 && presentQueryIDs.size() <= 50);
+
+        Iterator<Integer> integerIterator = presentQueryIDs.iterator();
+
+        while (integerIterator.hasNext()) {
+            int value = integerIterator.next();
+
+            assertTrue (value >= 0 && value < 50);
+        }
+    }
+
+    @Test
+    public void testCheckSpecificQueryStatus() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        params.set("taskUUID", "25");
+
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+
+        request.setPath("/tasks/list");
+
+        NamedList<Object> queryResponse = 
cluster.getSolrClient().request(request);
+
+        @SuppressWarnings({"unchecked"})
+        String result = (String) queryResponse.get("taskStatus");
+
+        assertFalse(result.contains("true"));
+    }
+
+    private CompletableFuture<Void> cancelQuery(final String queryID, final 
int sleepTime, Set<Integer> cancelledQueryIdsSet,
+                                          Set<Integer> notFoundQueryIdSet) {
+        return CompletableFuture.runAsync(() -> {
+            ModifiableSolrParams params = new ModifiableSolrParams();
+
+            params.set("cancelUUID", queryID);
+            @SuppressWarnings({"rawtypes"})
+            SolrRequest request = new QueryRequest(params);
+            request.setPath("/tasks/cancel");
+
+            // Wait for some time to let the query start
+            try {
+                if (sleepTime > 0) {
+                    Thread.sleep(sleepTime);
+                }
+
+                try {
+                    NamedList<Object> queryResponse = null;
+
+                    queryResponse = cluster.getSolrClient().request(request);
+
+                    String cancellationResult = (String) 
queryResponse.get("status");
+                    if (cancellationResult.contains("cancelled successfully")) 
{
+                        cancelledQueryIdsSet.add(Integer.parseInt(queryID));
+                    } else if (cancellationResult.contains("not found")) {
+                        notFoundQueryIdSet.add(Integer.parseInt(queryID));
+                    }

Review comment:
       Changed to returning HTTP codes

##########
File path: solr/core/src/test/org/apache/solr/search/TestTaskManagement.java
##########
@@ -0,0 +1,263 @@
+/*
+ * 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 org.apache.lucene.util.BytesRef;
+import org.apache.solr.client.solrj.SolrRequest;
+import org.apache.solr.client.solrj.request.CollectionAdminRequest;
+import org.apache.solr.client.solrj.request.QueryRequest;
+import org.apache.solr.cloud.SolrCloudTestCase;
+import org.apache.solr.common.SolrInputDocument;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.util.ExecutorUtil;
+import org.apache.solr.common.util.NamedList;
+import org.eclipse.jetty.util.ConcurrentHashSet;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Before;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.CompletableFuture;
+import java.util.concurrent.ExecutorService;
+
+public class TestTaskManagement extends SolrCloudTestCase {
+    private static final String COLLECTION_NAME = "collection1";
+
+    private ExecutorService executorService;
+
+    @BeforeClass
+    public static void setupCluster() throws Exception {
+        initCore("solrconfig.xml", "schema11.xml");
+
+        configureCluster(4)
+                .addConfig("conf", configset("sql"))
+                .configure();
+    }
+
+    @AfterClass
+    public static void tearDownCluster() throws Exception {
+        shutdownCluster();
+    }
+
+    @Before
+    public void setup() throws Exception {
+        super.setUp();
+
+        CollectionAdminRequest.createCollection(COLLECTION_NAME, "conf", 2, 1)
+                .setPerReplicaState(SolrCloudTestCase.USE_PER_REPLICA_STATE)
+                .process(cluster.getSolrClient());
+        cluster.waitForActiveCollection(COLLECTION_NAME, 2, 2);
+        cluster.getSolrClient().setDefaultCollection(COLLECTION_NAME);
+
+        cluster.getSolrClient().setDefaultCollection("collection1");
+
+        executorService = 
ExecutorUtil.newMDCAwareCachedThreadPool("TestTaskManagement");
+
+        List<SolrInputDocument> docs = new ArrayList<>();
+        for (int i = 0; i < 100; i++) {
+            SolrInputDocument doc = new SolrInputDocument();
+            doc.addField("id", i);
+            doc.addField("foo1_s", Integer.toString(i));
+            doc.addField("foo2_s", Boolean.toString(i % 2 == 0));
+            doc.addField("foo4_s", new BytesRef(Boolean.toString(i % 2 == 0)));
+
+            docs.add(doc);
+        }
+
+        cluster.getSolrClient().add(docs);
+        cluster.getSolrClient().commit();
+    }
+
+    @After
+    public void tearDown() throws Exception {
+        
CollectionAdminRequest.deleteCollection(COLLECTION_NAME).process(cluster.getSolrClient());
+        executorService.shutdown();
+        super.tearDown();
+    }
+
+    @Test
+    public void testNonExistentQuery() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        params.set("cancelUUID", "foobar");
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+        request.setPath("/tasks/cancel");
+
+        NamedList<Object> queryResponse = null;
+
+        queryResponse = cluster.getSolrClient().request(request);
+
+        assertEquals("Query with queryID foobar not found", 
queryResponse.get("status"));
+    }
+
+    @Test
+    public void testCancellationQuery() throws Exception {
+        ConcurrentHashSet<Integer> queryIdsSet = new ConcurrentHashSet<>();
+        ConcurrentHashSet<Integer> notFoundIdsSet = new ConcurrentHashSet<>();
+
+        List<CompletableFuture<Void>> queryFutures = new ArrayList<>();
+
+        for (int i = 0; i < 100; i++) {
+            CompletableFuture<Void> future = 
executeQueryAsync(Integer.toString(i));
+
+            queryFutures.add(future);
+        }
+
+        List<CompletableFuture<Void>> futures = new ArrayList<>();
+
+        for (int i = 0; i < 90; i++) {
+            CompletableFuture<Void> future = cancelQuery(Integer.toString(i), 
4000, queryIdsSet, notFoundIdsSet);
+
+            futures.add(future);
+        }
+
+        futures.forEach(CompletableFuture::join);
+
+        queryFutures.forEach(CompletableFuture::join);
+
+        assertTrue(queryIdsSet.size() + notFoundIdsSet.size() == 90);
+    }
+
+    @Test
+    public void testListCancellableQueries() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+        request.setPath("/tasks/list");
+
+        for (int i = 0; i < 50; i++) {
+            executeQueryAsync(Integer.toString(i));
+        }
+
+        NamedList<Object> queryResponse = null;
+
+        queryResponse = cluster.getSolrClient().request(request);
+
+        @SuppressWarnings({"unchecked"})
+        NamedList<String> result = (NamedList<String>) 
queryResponse.get("taskList");
+
+        Iterator<Map.Entry<String, String>> iterator = result.iterator();
+
+        Set<Integer> presentQueryIDs = new HashSet<>();
+
+        while (iterator.hasNext()) {
+            Map.Entry<String, String> entry = iterator.next();
+
+            presentQueryIDs.add(Integer.parseInt(entry.getKey()));
+        }
+
+        assertTrue(presentQueryIDs.size() > 0 && presentQueryIDs.size() <= 50);
+
+        Iterator<Integer> integerIterator = presentQueryIDs.iterator();
+
+        while (integerIterator.hasNext()) {
+            int value = integerIterator.next();
+
+            assertTrue (value >= 0 && value < 50);
+        }
+    }
+
+    @Test
+    public void testCheckSpecificQueryStatus() throws Exception {
+        ModifiableSolrParams params = new ModifiableSolrParams();
+
+        params.set("taskUUID", "25");
+
+        @SuppressWarnings({"rawtypes"})
+        SolrRequest request = new QueryRequest(params);
+
+        request.setPath("/tasks/list");
+
+        NamedList<Object> queryResponse = 
cluster.getSolrClient().request(request);
+
+        @SuppressWarnings({"unchecked"})
+        String result = (String) queryResponse.get("taskStatus");
+
+        assertFalse(result.contains("true"));
+    }
+
+    private CompletableFuture<Void> cancelQuery(final String queryID, final 
int sleepTime, Set<Integer> cancelledQueryIdsSet,

Review comment:
       Yeah, to allow future modifications :)

##########
File path: solr/core/src/java/org/apache/solr/core/CancellableQueryTracker.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.core;
+
+import org.apache.solr.client.solrj.util.Cancellable;
+import org.apache.solr.search.CancellableCollector;
+import org.apache.solr.request.SolrQueryRequest;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.ConcurrentHashMap;
+
+import static org.apache.solr.common.params.CommonParams.QUERY_UUID;
+
+/**
+ * Tracks metadata for active queries and provides methods for access
+ */
+public class CancellableQueryTracker {
+    //TODO: This needs to become a time aware storage model
+    private final Map<String, Cancellable> activeCancellableQueries = new 
ConcurrentHashMap<>();
+    private final Map<String, String> activeQueriesGenerated = new 
ConcurrentHashMap<>();
+
+    /** Generates a UUID for the given query or if the user provided a UUID
+     * for this query, uses that.
+     */
+    public String generateQueryID(SolrQueryRequest req) {
+        String queryID;
+        String customQueryUUID = req.getParams().get(QUERY_UUID, null);
+
+        if (customQueryUUID != null) {
+            queryID = customQueryUUID;
+        } else {
+            queryID = UUID.randomUUID().toString();
+        }
+
+        if (activeQueriesGenerated.containsKey(queryID)) {
+            if (customQueryUUID != null) {
+                throw new IllegalArgumentException("Duplicate query UUID 
given");

Review comment:
       Added to docs, thanks

##########
File path: 
solr/core/src/java/org/apache/solr/handler/component/TaskManagementHandler.java
##########
@@ -0,0 +1,150 @@
+/*
+ * 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.handler.component;
+
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.params.CommonParams;
+import org.apache.solr.common.params.ModifiableSolrParams;
+import org.apache.solr.common.params.ShardParams;
+import org.apache.solr.core.CoreContainer;
+import org.apache.solr.core.SolrCore;
+import org.apache.solr.handler.RequestHandlerBase;
+import org.apache.solr.request.SolrQueryRequest;
+import org.apache.solr.response.SolrQueryResponse;
+import org.apache.solr.security.PermissionNameProvider;
+import org.apache.solr.util.plugin.SolrCoreAware;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import static org.apache.solr.common.params.CommonParams.DISTRIB;
+import static org.apache.solr.common.params.CommonParams.PATH;
+
+/**
+ * Abstract class which serves as the root of all task managing handlers
+ */
+public abstract class TaskManagementHandler extends RequestHandlerBase 
implements SolrCoreAware, PermissionNameProvider {
+    private ShardHandlerFactory shardHandlerFactory;
+
+    @Override
+    public void inform(SolrCore core) {
+        this.shardHandlerFactory = 
core.getCoreContainer().getShardHandlerFactory();
+    }
+
+    /**
+     * Process the actual request.
+     * extraParams is required for allowing sub handlers to pass in custom 
parameters to be put in the
+     * outgoing shard request
+     */
+    protected void processRequest(SolrQueryRequest req, ResponseBuilder rb, 
Map<String, String> extraParams) throws IOException {
+        ShardHandler shardHandler = shardHandlerFactory.getShardHandler();
+        List<SearchComponent> components = rb.components;
+
+        shardHandler.prepDistributed(rb);
+
+        for(SearchComponent c : components) {
+            c.prepare(rb);
+        }
+
+        if (!rb.isDistrib) {
+            for (SearchComponent component : components) {
+                component.process(rb);
+            }
+        } else {
+            ShardRequest sreq = new ShardRequest();
+
+            // Distribute to all shards
+            sreq.shards = rb.shards;
+            sreq.actualShards = sreq.shards;
+
+            sreq.responses = new ArrayList<>(sreq.actualShards.length);
+            rb.finished = new ArrayList<>();
+
+            for (String shard : sreq.actualShards) {
+                ModifiableSolrParams params = new 
ModifiableSolrParams(sreq.params);
+                String reqPath = (String) req.getContext().get(PATH);
+
+                params.set(CommonParams.QT, reqPath);
+                params.remove(ShardParams.SHARDS);      // not a top-level 
request
+                params.set(DISTRIB, "false");               // not a top-level 
request
+                params.remove("indent");
+                params.remove(CommonParams.HEADER_ECHO_PARAMS);
+                params.set(ShardParams.IS_SHARD, true);  // a sub (shard) 
request
+                params.set(ShardParams.SHARDS_PURPOSE, sreq.purpose);
+                params.set(ShardParams.SHARD_URL, shard); // so the shard 
knows what was asked
+                params.set(CommonParams.OMIT_HEADER, false);

Review comment:
       Unfortunately, no, without refactoring SearchHandler, which I am 
hesitant to do




----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org



---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@lucene.apache.org
For additional commands, e-mail: issues-h...@lucene.apache.org

Reply via email to