You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@ignite.apache.org by GitBox <gi...@apache.org> on 2022/05/26 08:19:32 UTC

[GitHub] [ignite] SammyVimes opened a new pull request, #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

SammyVimes opened a new pull request, #10042:
URL: https://github.com/apache/ignite/pull/10042

   https://issues.apache.org/jira/browse/IGNITE-17002
   
   Thank you for submitting the pull request to the Apache Ignite.
   
   In order to streamline the review of the contribution 
   we ask you to ensure the following steps have been taken:
   
   ### The Contribution Checklist
   - [ ] There is a single JIRA ticket related to the pull request. 
   - [ ] The web-link to the pull request is attached to the JIRA ticket.
   - [ ] The JIRA ticket has the _Patch Available_ state.
   - [ ] The pull request body describes changes that have been made. 
   The description explains _WHAT_ and _WHY_ was made instead of _HOW_.
   - [ ] The pull request title is treated as the final commit message. 
   The following pattern must be used: `IGNITE-XXXX Change summary` where `XXXX` - number of JIRA issue.
   - [ ] A reviewer has been mentioned through the JIRA comments 
   (see [the Maintainers list](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute#HowtoContribute-ReviewProcessandMaintainers)) 
   - [ ] The pull request has been checked by the Teamcity Bot and 
   the `green visa` attached to the JIRA ticket (see [TC.Bot: Check PR](https://mtcga.gridgain.com/prs.html))
   
   ### Notes
   - [How to Contribute](https://cwiki.apache.org/confluence/display/IGNITE/How+to+Contribute)
   - [Coding abbreviation rules](https://cwiki.apache.org/confluence/display/IGNITE/Abbreviation+Rules)
   - [Coding Guidelines](https://cwiki.apache.org/confluence/display/IGNITE/Coding+Guidelines)
   - [Apache Ignite Teamcity Bot](https://cwiki.apache.org/confluence/display/IGNITE/Apache+Ignite+Teamcity+Bot)
   
   If you need any help, please email dev@ignite.apache.org or ask anу advice on http://asf.slack.com _#ignite_ channel.
   


-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884848357


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   You can do this, just don't specify any caches: "(Optional) Specify node for indexes rebuild."



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   You can do this, just don't specify any indexes: "(Optional) Specify node for indexes rebuild."



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r908482117


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+            this.cacheGroups = cacheGroups;
+        }
+
+        /**
+         * @return Cache -> indexes map.
+         */
+        public Map<String, Set<String>> cacheToIndexes() {
+            return cacheToIndexes;
+        }
+
+        /**
+         * @return Cache groups.
+         */
+        public Set<String> cacheGroups() {

Review Comment:
   I totally forgot to test it)



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r908481855


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;

Review Comment:
   Hm, we'll have to make a deep copy in case of cacheToIndexes. Not sure if it's really necessary here...



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

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r908447654


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);

Review Comment:
   Perhaps it's just a bad name for a variable, we should use info here



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

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884531283


##########
modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/maintenance/MaintenanceRebuildIndexUtilsSelfTest.java:
##########
@@ -117,4 +125,27 @@ public void testIndexNameWithSeparatorCharacter() {
         assertEquals(cacheId, target.cacheId());
         assertEquals(idxName, target.idxName());
     }
+
+    /**
+     * Tests that maintenance task can be constructed from a map.
+     */
+    @Test
+    public void testConstructFromMap() {
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(1, new HashSet<>(Arrays.asList("foo", "bar")));
+        cacheToIndexes.put(2, new HashSet<>(Arrays.asList("foo1", "bar1")));
+
+        MaintenanceTask task = toMaintenanceTask(cacheToIndexes);
+
+        List<MaintenanceRebuildIndexTarget> targets = parseMaintenanceTaskParameters(task.parameters());
+
+        assertEquals(4, targets.size());
+
+        Map<Integer, Set<String>> result = targets.stream().collect(groupingBy(
+            MaintenanceRebuildIndexTarget::cacheId,
+            mapping(MaintenanceRebuildIndexTarget::idxName, toSet())
+        ));
+
+        assertEquals(cacheToIndexes, result);

Review Comment:
   Why? Assert equals works



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884540507


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        IndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.IndexRebuildTask",
+                new IndexRebuildTaskArg(args.cacheToIndexes),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(IndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            if (!F.isEmpty(res.notFoundCacheNames())) {
+                String warning = "WARNING: These caches were not found:";
+
+                logger.info(warning);
+
+                res.notFoundCacheNames()
+                    .stream()
+                    .sorted()
+                    .forEach(name -> logger.info(INDENT + name));
+
+                logger.info("");
+            }
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasIndexes(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasIndexes(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /** */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has indexes, {@code false} otherwise.
+     */
+    private static boolean hasIndexes(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = new HashMap<>();

Review Comment:
   This is an offer.



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes merged pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes merged PR #10042:
URL: https://github.com/apache/ignite/pull/10042


-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] rpuch commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
rpuch commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r908155981


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "

Review Comment:
   From the current help, it's unclear how `--cache-names` and `--cache-groups` work together. Are they mutually exclusive? Or, when the user specifies `--group-names`, does it add all the caches from these groups to the list of caches? Or does it replace the cache list with the caches from the groups?
   
   Could you please elaborate?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   It seems unclear what happens if we omit `--node-id`. According to the code, this will mean that the command would be executed on all nodes. Should this be explicitly stated here?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);

Review Comment:
   Why is INFO used when we think it's a warning?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;

Review Comment:
   Defensive copies? This is not executed at 1000 rps



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;

Review Comment:
   How about marking all the fields as `@Nullable` (to make it easier to understand for the reader)?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+            this.cacheGroups = cacheGroups;
+        }
+
+        /**
+         * @return Cache -> indexes map.
+         */
+        public Map<String, Set<String>> cacheToIndexes() {
+            return cacheToIndexes;
+        }
+
+        /**
+         * @return Cache groups.
+         */
+        public Set<String> cacheGroups() {
+            return cacheGroups;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = null;
+        Set<String> cacheGroups = null;
+
+        while (argIterator.hasNextSubArg()) {
+            String nextArg = argIterator.nextArg("");
+
+            IndexRebuildCommandArg arg = CommandArgUtils.of(nextArg, IndexRebuildCommandArg.class);
+
+            if (arg == null)
+                throw new IllegalArgumentException("Unknown argument: " + nextArg);
+
+            switch (arg) {
+                case NODE_ID:
+                    if (nodeId != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    nodeId = UUID.fromString(argIterator.nextArg("Failed to read node id."));
+
+                    break;
+
+                case CACHE_NAMES_TARGET:
+                    if (cacheToIndexes != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    cacheToIndexes = new HashMap<>();
+
+                    String cacheNamesArg = argIterator.nextArg("Expected a comma-separated cache names (and optionally a"
+                        + " comma-separated list of index names in square brackets).");
+
+                    Pattern cacheNamesPattern = Pattern.compile("([^,\\[\\]]+)(\\[(.*?)])?");
+                    Matcher matcher = cacheNamesPattern.matcher(cacheNamesArg);
+
+                    boolean found = false;
+
+                    while (matcher.find()) {
+                        found = true;
+
+                        String cacheName = matcher.group(1);
+                        String commaSeparatedIndexes = matcher.group(3);
+
+                        if (F.isEmpty(commaSeparatedIndexes)) {
+                            cacheToIndexes.put(cacheName, Collections.emptySet());
+
+                            continue;
+                        }
+
+                        Set<String> indexes = Arrays.stream(commaSeparatedIndexes.split(",")).collect(toSet());
+                        cacheToIndexes.put(cacheName, indexes);
+                    }
+
+                    if (!found)
+                        throw new IllegalArgumentException("Wrong format for --cache-names, should be: " + CACHE_NAMES_FORMAT);
+
+                    break;
+
+                case CACHE_GROUPS_TARGET:
+                    if (cacheGroups != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    String cacheGroupsArg = argIterator.nextArg("Expected comma-separated cache group names");
+
+                    cacheGroups = Arrays.stream(cacheGroupsArg.split(",")).collect(toSet());
+
+                    break;
+
+                default:
+                    throw new IllegalArgumentException("Unknown argument: " + arg.argName());
+            }
+        }
+
+        args = new Arguments(nodeId, cacheToIndexes, cacheGroups);
+
+        validateArguments();
+    }
+
+    /** */
+    private void validateArguments() {
+        Set<String> cacheGroups = args.cacheGroups;
+        Map<String, Set<String>> cacheToIndexes = args.cacheToIndexes;
+
+        if (cacheGroups == null && cacheToIndexes == null && cacheGroups.isEmpty() && cacheToIndexes.isEmpty())

Review Comment:
   It seems that if any of `cacheGroups` and `cacheToIndices` is `null`, this will produce an NPE.
   
   I suggest adding a test for this case (when neither `--cache-names`, nor `--group-names` are specified.



##########
modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/maintenance/MaintenanceRebuildIndexUtils.java:
##########
@@ -96,6 +99,38 @@ public static MaintenanceTask toMaintenanceTask(int cacheId, String idxName) {
         );
     }
 
+    /**
+     * Constructs an index rebuild maintenance task based on a map cacheId -> indexes.
+     * For example:
+     * <pre>
+     * {@code
+     * Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+     * cacheToIndexes.put(CU.cacheId("some-cache"), singletone("some-index"));
+     * MaintenanceTask task = toMaintenanceTask(cacheToIndexes);
+     * }
+     * </pre>
+     *
+     * @param cacheToIndexes cacheId -> indexes map.
+     * @return Maintenance task.
+     */
+    public static MaintenanceTask toMaintenanceTask(Map<Integer, Set<String>> cacheToIndexes) {
+        String parameters = cacheToIndexes.entrySet().stream().flatMap(entry -> {
+            Integer cacheId = entry.getKey();
+            Set<String> indexes = entry.getValue();
+            return indexes.stream().map(index -> {
+                String encodedIdxName = ENCODER.encodeToString(index.getBytes(StandardCharsets.UTF_8));
+
+                return cacheId + INDEX_REBUILD_PARAMETER_SEPARATOR + encodedIdxName;
+            });
+        }).collect(Collectors.joining(INDEX_REBUILD_PARAMETER_SEPARATOR));

Review Comment:
   Here, `joining()` can be imported statically, which would produce a bit more plain English-like phrase (as it is often with collectors and streams)



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerScheduleIndexRebuildTest.java:
##########
@@ -0,0 +1,595 @@
+/*
+ * 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.ignite.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexTarget;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.h2.index.Index;
+import org.junit.Test;
+
+import static java.util.Collections.singletonMap;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.mapping;
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.parseMaintenanceTaskParameters;
+import static org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.util.IgniteUtils.max;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.breakSqlIndex;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.complexIndexEntity;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillCache;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillThreeFieldsEntryCache;
+
+/**
+ * Tests for --cache schedule_indexes_rebuild command. Uses single cluster per suite.
+ */
+public class GridCommandHandlerScheduleIndexRebuildTest extends GridCommandHandlerAbstractTest {
+    /** */
+    private static final String INDEX_REBUILD_MNTC_TASK = "indexRebuildMaintenanceTask";
+
+    /** */
+    private static final String CACHE_NAME_1_1 = "cache_1_1";
+
+    /** */
+    private static final String CACHE_NAME_1_2 = "cache_1_2";
+
+    /** */
+    private static final String CACHE_NAME_2_1 = "cache_2_1";
+
+    /** */
+    private static final String CACHE_NAME_NO_GRP = "cache_no_group";
+
+    /** */
+    private static final String CACHE_NAME_NON_EXISTING = "non_existing_cache";
+
+    /** */
+    private static final String GROUP_NAME_NON_EXISTING = "non_existing_group";
+
+    /** */
+    private static final String GRP_NAME_1 = "group_1";
+
+    /** */
+    private static final String GRP_NAME_2 = "group_2";
+
+    /** */
+    private static final int GRIDS_NUM = 3;
+
+    /** */
+    private static final int LAST_NODE_NUM = GRIDS_NUM - 1;
+
+    /** */
+    private static final int REBUILD_TIMEOUT = 30_000;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(new ListeningTestLogger(log));
+
+        cfg.setBuildIndexThreadPoolSize(max(2, cfg.getBuildIndexThreadPoolSize()));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        startupTestCluster();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        super.afterTestsStopped();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        G.allGrids().forEach(ignite -> assertFalse(((IgniteEx)ignite).context().maintenanceRegistry().isMaintenanceMode()));
+    }
+
+    /** */
+    private void startupTestCluster() throws Exception {
+        for (int i = 0; i < GRIDS_NUM; i++ )

Review Comment:
   ```suggestion
           for (int i = 0; i < GRIDS_NUM; i++)
   ```



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerScheduleIndexRebuildTest.java:
##########
@@ -0,0 +1,595 @@
+/*
+ * 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.ignite.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexTarget;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.h2.index.Index;
+import org.junit.Test;
+
+import static java.util.Collections.singletonMap;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.mapping;
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.parseMaintenanceTaskParameters;
+import static org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.util.IgniteUtils.max;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.breakSqlIndex;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.complexIndexEntity;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillCache;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillThreeFieldsEntryCache;
+
+/**
+ * Tests for --cache schedule_indexes_rebuild command. Uses single cluster per suite.
+ */
+public class GridCommandHandlerScheduleIndexRebuildTest extends GridCommandHandlerAbstractTest {
+    /** */
+    private static final String INDEX_REBUILD_MNTC_TASK = "indexRebuildMaintenanceTask";
+
+    /** */
+    private static final String CACHE_NAME_1_1 = "cache_1_1";
+
+    /** */
+    private static final String CACHE_NAME_1_2 = "cache_1_2";
+
+    /** */
+    private static final String CACHE_NAME_2_1 = "cache_2_1";
+
+    /** */
+    private static final String CACHE_NAME_NO_GRP = "cache_no_group";
+
+    /** */
+    private static final String CACHE_NAME_NON_EXISTING = "non_existing_cache";
+
+    /** */
+    private static final String GROUP_NAME_NON_EXISTING = "non_existing_group";
+
+    /** */
+    private static final String GRP_NAME_1 = "group_1";
+
+    /** */
+    private static final String GRP_NAME_2 = "group_2";
+
+    /** */
+    private static final int GRIDS_NUM = 3;
+
+    /** */
+    private static final int LAST_NODE_NUM = GRIDS_NUM - 1;
+
+    /** */
+    private static final int REBUILD_TIMEOUT = 30_000;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(new ListeningTestLogger(log));
+
+        cfg.setBuildIndexThreadPoolSize(max(2, cfg.getBuildIndexThreadPoolSize()));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        startupTestCluster();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        super.afterTestsStopped();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        G.allGrids().forEach(ignite -> assertFalse(((IgniteEx)ignite).context().maintenanceRegistry().isMaintenanceMode()));
+    }
+
+    /** */
+    private void startupTestCluster() throws Exception {
+        for (int i = 0; i < GRIDS_NUM; i++ )
+            startGrid(i);
+
+        IgniteEx ignite = grid(0);
+
+        ignite.cluster().state(ClusterState.ACTIVE);
+
+        awaitPartitionMapExchange();
+
+        createAndFillCache(ignite, CACHE_NAME_1_1, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_1_2, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_2_1, GRP_NAME_2);
+
+        createAndFillThreeFieldsEntryCache(ignite, CACHE_NAME_NO_GRP, null, Collections.singletonList(complexIndexEntity()));
+
+        // Flush indexes rebuild status (it happens only on checkpoint).
+        forceCheckpoint();
+    }
+
+    /**
+     * Checks error messages when trying to rebuild indexes for non-existent cache or when trying
+     * to rebuild non-existent indexes.
+     */
+    @Test
+    public void testErrors() {
+        injectTestSystemOut();
+
+        IgniteEx lastNode = grid(LAST_NODE_NUM);
+
+        // Tests non-existing cache name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", lastNode.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_NON_EXISTING));
+
+        String notExistingCacheOutputStr = testOut.toString();
+
+        assertTrue(notExistingCacheOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+        assertTrue(notExistingCacheOutputStr.contains(
+            "WARNING: These caches were not found:" + System.lineSeparator()
+            + INDENT + CACHE_NAME_NON_EXISTING
+        ));
+
+        // Test non-existing cache group name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", lastNode.localNode().id().toString(),
+            "--group-names", GROUP_NAME_NON_EXISTING));
+
+        String notExistingGroupOutputStr = testOut.toString();
+
+        assertTrue(notExistingGroupOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+        assertTrue(notExistingGroupOutputStr.contains(
+            "WARNING: These cache groups were not found:" + System.lineSeparator()
+            + INDENT + GROUP_NAME_NON_EXISTING
+        ));
+
+        testOut.reset();
+
+        // Tests non-existing index name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", grid(LAST_NODE_NUM).localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "[non-existing-index]"));
+
+        String notExistingIndexOutputStr = testOut.toString();
+
+        assertTrue(notExistingIndexOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+
+        assertTrue(notExistingIndexOutputStr.contains(
+            "WARNING: These indexes were not found:" + System.lineSeparator()
+            + INDENT + CACHE_NAME_1_1 + ":" + System.lineSeparator()
+            + INDENT + INDENT + "non-existing-index")
+        );
+    }
+
+    /**
+     * Checks that index is rebuilt correctly.
+     */
+    @Test
+    public void testRebuild() throws Exception {
+        IgniteEx node = grid(LAST_NODE_NUM);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", node.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_NO_GRP));
+
+        checkIndexesRebuildScheduled(node, singletonMap(CU.cacheId(CACHE_NAME_NO_GRP), indexes(node, CACHE_NAME_NO_GRP)));
+
+        node.close();
+
+        node = startGrid(LAST_NODE_NUM);
+
+        assertTrue(node.context().maintenanceRegistry().isMaintenanceMode());
+
+        assertTrue(waitForIndexesRebuild(grid(LAST_NODE_NUM)));
+
+        node.close();
+
+        node = startGrid(LAST_NODE_NUM);
+
+        assertFalse(node.context().maintenanceRegistry().isMaintenanceMode());
+
+        checkIndexes(CACHE_NAME_NO_GRP);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCache() throws Exception {
+        testCorruptedIndexRebuild(false, true);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheWithGroup() throws Exception {
+        testCorruptedIndexRebuild(true, true);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheOnAllNodes() throws Exception {
+        testCorruptedIndexRebuild(false, false);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheWithGroupOnAllNodes() throws Exception {
+        testCorruptedIndexRebuild(true, false);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     *
+     * @param withCacheGroup If {@code true} creates a cache with a cache group.
+     * @param specifyNodeId If {@code true} then execute rebuild only on one node.
+     */
+    private void testCorruptedIndexRebuild(boolean withCacheGroup, boolean specifyNodeId) throws Exception {
+        IgniteEx firstNode = grid(0);
+
+        String cacheName = "tmpCache";
+
+        try {
+            createAndFillCache(firstNode, cacheName, withCacheGroup ? "tmpGrp" : null);
+
+            breakSqlIndex(firstNode.cachex(cacheName), 1, null);
+
+            injectTestSystemOut();
+
+            assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", "--check-sizes"));
+
+            assertContains(log, testOut.toString(), "issues found (listed above)");
+
+            testOut.reset();
+
+            List<String> args = new ArrayList<>();
+            args.add("--cache");
+            args.add("schedule_indexes_rebuild");
+            if (specifyNodeId) {
+                args.add("--node-id");
+                args.add(firstNode.localNode().id().toString());
+            }
+            args.add("--cache-names");
+            args.add(cacheName);
+
+            assertEquals(EXIT_CODE_OK, execute(args.toArray(new String[0])));
+
+            int nodeCount = specifyNodeId ? 1 : GRIDS_NUM;
+
+            for (int i = 0; i < nodeCount; i++) {
+                IgniteEx grid = grid(i);
+
+                checkIndexesRebuildScheduled(grid, singletonMap(CU.cacheId(cacheName), indexes(grid, cacheName)));
+
+                grid.close();
+
+                grid = startGrid(i);
+
+                assertTrue(grid.context().maintenanceRegistry().isMaintenanceMode());
+
+                assertTrue(waitForIndexesRebuild(grid));
+
+                grid.close();
+
+                startGrid(i);
+            }
+
+            checkIndexes(cacheName);
+        }
+        finally {
+            grid(0).destroyCache(cacheName);
+        }
+    }
+
+    /**
+     * Checks that command can be executed multiple times and all specified indexes will be rebuilt.
+     */
+    @Test
+    public void testConsecutiveCommandInvocations() throws Exception {
+        IgniteEx ignite = grid(0);
+
+        breakAndCheckBroken(ignite, CACHE_NAME_1_1);
+        breakAndCheckBroken(ignite, CACHE_NAME_1_2);
+        breakAndCheckBroken(ignite, CACHE_NAME_2_1);
+        breakAndCheckBroken(ignite, CACHE_NAME_NO_GRP);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "," + CACHE_NAME_1_2));
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_2_1 + "," + CACHE_NAME_NO_GRP));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), indexes(ignite, CACHE_NAME_1_1));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), indexes(ignite, CACHE_NAME_1_2));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_2_1), indexes(ignite, CACHE_NAME_2_1));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_NO_GRP), indexes(ignite, CACHE_NAME_NO_GRP));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+        checkIndexes(CACHE_NAME_2_1);
+        checkIndexes(CACHE_NAME_NO_GRP);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+        checkIndexes(CACHE_NAME_2_1);
+        checkIndexes(CACHE_NAME_NO_GRP);
+    }
+
+    /**
+     * Checks that specific indexes can be passed to the schedule rebuild command.
+     */
+    @Test
+    public void testSpecificIndexes() throws Exception {
+        IgniteEx ignite = grid(0);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "[_key_PK]," + CACHE_NAME_1_2 + "[PERSON_ORGID_ASC_IDX]"));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), Collections.singleton("_key_PK"));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), Collections.singleton("PERSON_ORGID_ASC_IDX"));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command.
+     */
+    @Test
+    public void testCacheGroupParameter() throws Exception {
+        testCacheGroupsParameter(false);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command along with cache names parameter.
+     */
+    @Test
+    public void testCacheGroupParameterWithCacheNames() throws Exception {
+        testCacheGroupsParameter(true);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command
+     * along with cache names parameter if {@code withCacheNames} is {@code true}.
+     *
+     * @param withCacheNames Pass --cache-names parameter along with --group-names.
+     * @throws Exception If failed.
+     */
+    private void testCacheGroupsParameter(boolean withCacheNames) throws Exception {
+        IgniteEx ignite = grid(0);
+
+        List<String> cmd = new ArrayList<>();
+
+        cmd.add("--cache");
+        cmd.add("schedule_indexes_rebuild");
+        cmd.add("--node-id");
+        cmd.add(ignite.localNode().id().toString());
+        cmd.add("--group-names");
+        cmd.add(GRP_NAME_1);
+
+        if (withCacheNames) {
+            cmd.add("--cache-names");
+            cmd.add(CACHE_NAME_2_1 + "[PERSON_ORGID_ASC_IDX]");
+        }
+
+        assertEquals(EXIT_CODE_OK, execute(cmd));
+
+        HashSet<String> allIndexes = new HashSet<>(Arrays.asList("_key_PK", "PERSON_ORGID_ASC_IDX", "PERSON_NAME_ASC_IDX"));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), allIndexes);
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), allIndexes);
+
+        if (withCacheNames)
+            cacheToIndexes.put(CU.cacheId(CACHE_NAME_2_1), Collections.singleton("PERSON_ORGID_ASC_IDX"));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        if (withCacheNames)
+            checkIndexes(CACHE_NAME_2_1);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        if (withCacheNames)
+            checkIndexes(CACHE_NAME_2_1);
+    }
+
+    /**
+     * Breaks sql index and checks that it is broken.
+     *
+     * @param ignite Node.
+     * @param cacheName Cache name.
+     * @throws Exception If failed.
+     */
+    private void breakAndCheckBroken(IgniteEx ignite, String cacheName) throws Exception {
+        injectTestSystemOut();
+
+        breakSqlIndex(ignite.cachex(cacheName), 1, null);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", cacheName));
+
+        assertContains(log, testOut.toString(), "issues found (listed above)");
+
+        testOut.reset();
+    }
+
+    /**
+     * Checks that indexes are valid.
+     *
+     * @param cacheName Cache name.
+     */
+    private void checkIndexes(String cacheName) {
+        injectTestSystemOut();
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", cacheName));
+
+        assertContains(log, testOut.toString(), "no issues found.");
+
+        testOut.reset();
+    }
+
+    /**
+     * Waits for the rebuild of the indexes.
+     *
+     * @param ignite Ignite instance.
+     * @return {@code True} if index rebuild was completed before {@code timeout} was reached.
+     * @throws IgniteInterruptedCheckedException if failed.
+     */
+    private boolean waitForIndexesRebuild(IgniteEx ignite) throws IgniteInterruptedCheckedException {
+        return GridTestUtils.waitForCondition(
+            () -> ignite.context().cache().publicCaches()
+                .stream()
+                .allMatch(c -> c.indexReadyFuture().isDone()),
+            REBUILD_TIMEOUT);
+    }
+
+    /**
+     * Checks that given indexes are scheduled for the rebuild.
+     *
+     * @param node Node.
+     * @param cacheToIndexes Map of caches to indexes.
+     */
+    private void checkIndexesRebuildScheduled(IgniteEx node, Map<Integer, Set<String>> cacheToIndexes) {
+        MaintenanceTask maintenanceTask = node.context().maintenanceRegistry().requestedTask(INDEX_REBUILD_MNTC_TASK);
+
+        assertNotNull(maintenanceTask);
+
+        List<MaintenanceRebuildIndexTarget> targets = parseMaintenanceTaskParameters(maintenanceTask.parameters());
+
+        Map<Integer, Set<String>> result = targets.stream().collect(groupingBy(
+            MaintenanceRebuildIndexTarget::cacheId,
+            mapping(MaintenanceRebuildIndexTarget::idxName, toSet())
+        ));
+
+        assertEqualsMaps(cacheToIndexes, result);
+    }
+
+    /**
+     * Returns indexes' names of the given cache.
+     *
+     * @param node Node.
+     * @param cache Cache name.
+     * @return Indexes of the cache.
+     */
+    private Set<String> indexes(IgniteEx node, String cache) {

Review Comment:
   I think this code is duplicated. Could we extract it to some util class to avoid duplication?



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerScheduleIndexRebuildTest.java:
##########
@@ -0,0 +1,595 @@
+/*
+ * 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.ignite.util;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexTarget;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.h2.index.Index;
+import org.junit.Test;
+
+import static java.util.Collections.singletonMap;
+import static java.util.stream.Collectors.groupingBy;
+import static java.util.stream.Collectors.mapping;
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.parseMaintenanceTaskParameters;
+import static org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.util.IgniteUtils.max;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.breakSqlIndex;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.complexIndexEntity;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillCache;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillThreeFieldsEntryCache;
+
+/**
+ * Tests for --cache schedule_indexes_rebuild command. Uses single cluster per suite.
+ */
+public class GridCommandHandlerScheduleIndexRebuildTest extends GridCommandHandlerAbstractTest {
+    /** */
+    private static final String INDEX_REBUILD_MNTC_TASK = "indexRebuildMaintenanceTask";
+
+    /** */
+    private static final String CACHE_NAME_1_1 = "cache_1_1";
+
+    /** */
+    private static final String CACHE_NAME_1_2 = "cache_1_2";
+
+    /** */
+    private static final String CACHE_NAME_2_1 = "cache_2_1";
+
+    /** */
+    private static final String CACHE_NAME_NO_GRP = "cache_no_group";
+
+    /** */
+    private static final String CACHE_NAME_NON_EXISTING = "non_existing_cache";
+
+    /** */
+    private static final String GROUP_NAME_NON_EXISTING = "non_existing_group";
+
+    /** */
+    private static final String GRP_NAME_1 = "group_1";
+
+    /** */
+    private static final String GRP_NAME_2 = "group_2";
+
+    /** */
+    private static final int GRIDS_NUM = 3;
+
+    /** */
+    private static final int LAST_NODE_NUM = GRIDS_NUM - 1;
+
+    /** */
+    private static final int REBUILD_TIMEOUT = 30_000;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(new ListeningTestLogger(log));
+
+        cfg.setBuildIndexThreadPoolSize(max(2, cfg.getBuildIndexThreadPoolSize()));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        startupTestCluster();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        super.afterTestsStopped();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        G.allGrids().forEach(ignite -> assertFalse(((IgniteEx)ignite).context().maintenanceRegistry().isMaintenanceMode()));
+    }
+
+    /** */
+    private void startupTestCluster() throws Exception {
+        for (int i = 0; i < GRIDS_NUM; i++ )
+            startGrid(i);
+
+        IgniteEx ignite = grid(0);
+
+        ignite.cluster().state(ClusterState.ACTIVE);
+
+        awaitPartitionMapExchange();
+
+        createAndFillCache(ignite, CACHE_NAME_1_1, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_1_2, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_2_1, GRP_NAME_2);
+
+        createAndFillThreeFieldsEntryCache(ignite, CACHE_NAME_NO_GRP, null, Collections.singletonList(complexIndexEntity()));
+
+        // Flush indexes rebuild status (it happens only on checkpoint).
+        forceCheckpoint();
+    }
+
+    /**
+     * Checks error messages when trying to rebuild indexes for non-existent cache or when trying
+     * to rebuild non-existent indexes.
+     */
+    @Test
+    public void testErrors() {
+        injectTestSystemOut();
+
+        IgniteEx lastNode = grid(LAST_NODE_NUM);
+
+        // Tests non-existing cache name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", lastNode.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_NON_EXISTING));
+
+        String notExistingCacheOutputStr = testOut.toString();
+
+        assertTrue(notExistingCacheOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+        assertTrue(notExistingCacheOutputStr.contains(
+            "WARNING: These caches were not found:" + System.lineSeparator()
+            + INDENT + CACHE_NAME_NON_EXISTING
+        ));
+
+        // Test non-existing cache group name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", lastNode.localNode().id().toString(),
+            "--group-names", GROUP_NAME_NON_EXISTING));
+
+        String notExistingGroupOutputStr = testOut.toString();
+
+        assertTrue(notExistingGroupOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+        assertTrue(notExistingGroupOutputStr.contains(
+            "WARNING: These cache groups were not found:" + System.lineSeparator()
+            + INDENT + GROUP_NAME_NON_EXISTING
+        ));
+
+        testOut.reset();
+
+        // Tests non-existing index name.
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", grid(LAST_NODE_NUM).localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "[non-existing-index]"));
+
+        String notExistingIndexOutputStr = testOut.toString();
+
+        assertTrue(notExistingIndexOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+
+        assertTrue(notExistingIndexOutputStr.contains(
+            "WARNING: These indexes were not found:" + System.lineSeparator()
+            + INDENT + CACHE_NAME_1_1 + ":" + System.lineSeparator()
+            + INDENT + INDENT + "non-existing-index")
+        );
+    }
+
+    /**
+     * Checks that index is rebuilt correctly.
+     */
+    @Test
+    public void testRebuild() throws Exception {
+        IgniteEx node = grid(LAST_NODE_NUM);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", node.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_NO_GRP));
+
+        checkIndexesRebuildScheduled(node, singletonMap(CU.cacheId(CACHE_NAME_NO_GRP), indexes(node, CACHE_NAME_NO_GRP)));
+
+        node.close();
+
+        node = startGrid(LAST_NODE_NUM);
+
+        assertTrue(node.context().maintenanceRegistry().isMaintenanceMode());
+
+        assertTrue(waitForIndexesRebuild(grid(LAST_NODE_NUM)));
+
+        node.close();
+
+        node = startGrid(LAST_NODE_NUM);
+
+        assertFalse(node.context().maintenanceRegistry().isMaintenanceMode());
+
+        checkIndexes(CACHE_NAME_NO_GRP);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCache() throws Exception {
+        testCorruptedIndexRebuild(false, true);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheWithGroup() throws Exception {
+        testCorruptedIndexRebuild(true, true);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheOnAllNodes() throws Exception {
+        testCorruptedIndexRebuild(false, false);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     */
+    @Test
+    public void testCorruptedIndexRebuildCacheWithGroupOnAllNodes() throws Exception {
+        testCorruptedIndexRebuild(true, false);
+    }
+
+    /**
+     * Checks that corrupted index is successfully rebuilt by the command.
+     *
+     * @param withCacheGroup If {@code true} creates a cache with a cache group.
+     * @param specifyNodeId If {@code true} then execute rebuild only on one node.
+     */
+    private void testCorruptedIndexRebuild(boolean withCacheGroup, boolean specifyNodeId) throws Exception {
+        IgniteEx firstNode = grid(0);
+
+        String cacheName = "tmpCache";
+
+        try {
+            createAndFillCache(firstNode, cacheName, withCacheGroup ? "tmpGrp" : null);
+
+            breakSqlIndex(firstNode.cachex(cacheName), 1, null);
+
+            injectTestSystemOut();
+
+            assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", "--check-sizes"));
+
+            assertContains(log, testOut.toString(), "issues found (listed above)");
+
+            testOut.reset();
+
+            List<String> args = new ArrayList<>();
+            args.add("--cache");
+            args.add("schedule_indexes_rebuild");
+            if (specifyNodeId) {
+                args.add("--node-id");
+                args.add(firstNode.localNode().id().toString());
+            }
+            args.add("--cache-names");
+            args.add(cacheName);
+
+            assertEquals(EXIT_CODE_OK, execute(args.toArray(new String[0])));
+
+            int nodeCount = specifyNodeId ? 1 : GRIDS_NUM;
+
+            for (int i = 0; i < nodeCount; i++) {
+                IgniteEx grid = grid(i);
+
+                checkIndexesRebuildScheduled(grid, singletonMap(CU.cacheId(cacheName), indexes(grid, cacheName)));
+
+                grid.close();
+
+                grid = startGrid(i);
+
+                assertTrue(grid.context().maintenanceRegistry().isMaintenanceMode());
+
+                assertTrue(waitForIndexesRebuild(grid));
+
+                grid.close();
+
+                startGrid(i);
+            }
+
+            checkIndexes(cacheName);
+        }
+        finally {
+            grid(0).destroyCache(cacheName);
+        }
+    }
+
+    /**
+     * Checks that command can be executed multiple times and all specified indexes will be rebuilt.
+     */
+    @Test
+    public void testConsecutiveCommandInvocations() throws Exception {
+        IgniteEx ignite = grid(0);
+
+        breakAndCheckBroken(ignite, CACHE_NAME_1_1);
+        breakAndCheckBroken(ignite, CACHE_NAME_1_2);
+        breakAndCheckBroken(ignite, CACHE_NAME_2_1);
+        breakAndCheckBroken(ignite, CACHE_NAME_NO_GRP);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "," + CACHE_NAME_1_2));
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_2_1 + "," + CACHE_NAME_NO_GRP));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), indexes(ignite, CACHE_NAME_1_1));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), indexes(ignite, CACHE_NAME_1_2));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_2_1), indexes(ignite, CACHE_NAME_2_1));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_NO_GRP), indexes(ignite, CACHE_NAME_NO_GRP));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+        checkIndexes(CACHE_NAME_2_1);
+        checkIndexes(CACHE_NAME_NO_GRP);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+        checkIndexes(CACHE_NAME_2_1);
+        checkIndexes(CACHE_NAME_NO_GRP);
+    }
+
+    /**
+     * Checks that specific indexes can be passed to the schedule rebuild command.
+     */
+    @Test
+    public void testSpecificIndexes() throws Exception {
+        IgniteEx ignite = grid(0);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "schedule_indexes_rebuild",
+            "--node-id", ignite.localNode().id().toString(),
+            "--cache-names", CACHE_NAME_1_1 + "[_key_PK]," + CACHE_NAME_1_2 + "[PERSON_ORGID_ASC_IDX]"));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), Collections.singleton("_key_PK"));
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), Collections.singleton("PERSON_ORGID_ASC_IDX"));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command.
+     */
+    @Test
+    public void testCacheGroupParameter() throws Exception {
+        testCacheGroupsParameter(false);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command along with cache names parameter.
+     */
+    @Test
+    public void testCacheGroupParameterWithCacheNames() throws Exception {
+        testCacheGroupsParameter(true);
+    }
+
+    /**
+     * Checks that cache groups can be passed to the schedule rebuild command
+     * along with cache names parameter if {@code withCacheNames} is {@code true}.
+     *
+     * @param withCacheNames Pass --cache-names parameter along with --group-names.
+     * @throws Exception If failed.
+     */
+    private void testCacheGroupsParameter(boolean withCacheNames) throws Exception {
+        IgniteEx ignite = grid(0);
+
+        List<String> cmd = new ArrayList<>();
+
+        cmd.add("--cache");
+        cmd.add("schedule_indexes_rebuild");
+        cmd.add("--node-id");
+        cmd.add(ignite.localNode().id().toString());
+        cmd.add("--group-names");
+        cmd.add(GRP_NAME_1);
+
+        if (withCacheNames) {
+            cmd.add("--cache-names");
+            cmd.add(CACHE_NAME_2_1 + "[PERSON_ORGID_ASC_IDX]");
+        }
+
+        assertEquals(EXIT_CODE_OK, execute(cmd));
+
+        HashSet<String> allIndexes = new HashSet<>(Arrays.asList("_key_PK", "PERSON_ORGID_ASC_IDX", "PERSON_NAME_ASC_IDX"));
+
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_1), allIndexes);
+        cacheToIndexes.put(CU.cacheId(CACHE_NAME_1_2), allIndexes);
+
+        if (withCacheNames)
+            cacheToIndexes.put(CU.cacheId(CACHE_NAME_2_1), Collections.singleton("PERSON_ORGID_ASC_IDX"));
+
+        checkIndexesRebuildScheduled(ignite, cacheToIndexes);
+
+        ignite.close();
+
+        ignite = startGrid(0);
+
+        assertTrue(waitForIndexesRebuild(ignite));
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        if (withCacheNames)
+            checkIndexes(CACHE_NAME_2_1);
+
+        ignite.close();
+
+        startGrid(0);
+
+        checkIndexes(CACHE_NAME_1_1);
+        checkIndexes(CACHE_NAME_1_2);
+
+        if (withCacheNames)
+            checkIndexes(CACHE_NAME_2_1);
+    }
+
+    /**
+     * Breaks sql index and checks that it is broken.
+     *
+     * @param ignite Node.
+     * @param cacheName Cache name.
+     * @throws Exception If failed.
+     */
+    private void breakAndCheckBroken(IgniteEx ignite, String cacheName) throws Exception {
+        injectTestSystemOut();
+
+        breakSqlIndex(ignite.cachex(cacheName), 1, null);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", cacheName));
+
+        assertContains(log, testOut.toString(), "issues found (listed above)");
+
+        testOut.reset();
+    }
+
+    /**
+     * Checks that indexes are valid.
+     *
+     * @param cacheName Cache name.
+     */
+    private void checkIndexes(String cacheName) {
+        injectTestSystemOut();
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "validate_indexes", "--check-crc", cacheName));
+
+        assertContains(log, testOut.toString(), "no issues found.");
+
+        testOut.reset();
+    }
+
+    /**
+     * Waits for the rebuild of the indexes.
+     *
+     * @param ignite Ignite instance.
+     * @return {@code True} if index rebuild was completed before {@code timeout} was reached.
+     * @throws IgniteInterruptedCheckedException if failed.
+     */
+    private boolean waitForIndexesRebuild(IgniteEx ignite) throws IgniteInterruptedCheckedException {
+        return GridTestUtils.waitForCondition(
+            () -> ignite.context().cache().publicCaches()
+                .stream()
+                .allMatch(c -> c.indexReadyFuture().isDone()),
+            REBUILD_TIMEOUT);
+    }
+
+    /**
+     * Checks that given indexes are scheduled for the rebuild.
+     *
+     * @param node Node.
+     * @param cacheToIndexes Map of caches to indexes.
+     */
+    private void checkIndexesRebuildScheduled(IgniteEx node, Map<Integer, Set<String>> cacheToIndexes) {
+        MaintenanceTask maintenanceTask = node.context().maintenanceRegistry().requestedTask(INDEX_REBUILD_MNTC_TASK);
+
+        assertNotNull(maintenanceTask);
+
+        List<MaintenanceRebuildIndexTarget> targets = parseMaintenanceTaskParameters(maintenanceTask.parameters());
+
+        Map<Integer, Set<String>> result = targets.stream().collect(groupingBy(
+            MaintenanceRebuildIndexTarget::cacheId,
+            mapping(MaintenanceRebuildIndexTarget::idxName, toSet())
+        ));
+
+        assertEqualsMaps(cacheToIndexes, result);
+    }
+
+    /**
+     * Returns indexes' names of the given cache.
+     *
+     * @param node Node.
+     * @param cache Cache name.
+     * @return Indexes of the cache.
+     */
+    private Set<String> indexes(IgniteEx node, String cache) {
+        GridQueryProcessor qry = node.context().query();
+
+        IgniteH2Indexing indexing = (IgniteH2Indexing)qry.getIndexing();
+
+        Set<String> indexes = new HashSet<>();
+
+        for (GridQueryTypeDescriptor type : qry.types(cache)) {
+            GridH2Table gridH2Tbl = indexing.schemaManager().dataTable(type.schemaName(), type.tableName());
+
+            if (gridH2Tbl == null)
+                continue;
+
+            for (Index idx : gridH2Tbl.getIndexes()) {
+                if (idx instanceof H2TreeIndexBase)

Review Comment:
   Why do we only consider `H2TreeIndexBase`? It would be great to have a comment



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerIndexingUtils.java:
##########
@@ -156,7 +156,6 @@ public static void createAndFillCache(
     ) {
         requireNonNull(ignite);
         requireNonNull(cacheName);
-        requireNonNull(grpName);

Review Comment:
   Should we also annotate `grpName` as `@Nullable`?



##########
modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/maintenance/MaintenanceRebuildIndexUtils.java:
##########
@@ -96,6 +99,38 @@ public static MaintenanceTask toMaintenanceTask(int cacheId, String idxName) {
         );
     }
 
+    /**
+     * Constructs an index rebuild maintenance task based on a map cacheId -> indexes.
+     * For example:
+     * <pre>
+     * {@code
+     * Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+     * cacheToIndexes.put(CU.cacheId("some-cache"), singletone("some-index"));

Review Comment:
   ```suggestion
        * cacheToIndexes.put(CU.cacheId("some-cache"), singleton("some-index"));
   ```



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/ScheduleIndexRebuildTaskRes.java:
##########
@@ -0,0 +1,70 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the ScheduleIndexRebuildTask.
+ */
+public class ScheduleIndexRebuildTaskRes extends IgniteDataTransferObject {
+    /** Serial version uid. */
+    private static final long serialVersionUID = 0L;
+
+    /** Map node id -> rebuild command result. */
+    private Map<UUID, ScheduleIndexRebuildJobRes> results;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public ScheduleIndexRebuildTaskRes() {
+        // No-op.
+    }
+
+    /**
+     * Constructor.
+     *
+     * @param results Map node id -> rebuild command result.
+     */
+    public ScheduleIndexRebuildTaskRes(Map<UUID, ScheduleIndexRebuildJobRes> results) {
+        this.results = results;

Review Comment:
   A defensive copy?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+            this.cacheGroups = cacheGroups;
+        }
+
+        /**
+         * @return Cache -> indexes map.
+         */
+        public Map<String, Set<String>> cacheToIndexes() {
+            return cacheToIndexes;
+        }
+
+        /**
+         * @return Cache groups.
+         */
+        public Set<String> cacheGroups() {
+            return cacheGroups;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = null;
+        Set<String> cacheGroups = null;
+
+        while (argIterator.hasNextSubArg()) {
+            String nextArg = argIterator.nextArg("");
+
+            IndexRebuildCommandArg arg = CommandArgUtils.of(nextArg, IndexRebuildCommandArg.class);
+
+            if (arg == null)
+                throw new IllegalArgumentException("Unknown argument: " + nextArg);
+
+            switch (arg) {
+                case NODE_ID:
+                    if (nodeId != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    nodeId = UUID.fromString(argIterator.nextArg("Failed to read node id."));
+
+                    break;
+
+                case CACHE_NAMES_TARGET:
+                    if (cacheToIndexes != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    cacheToIndexes = new HashMap<>();
+
+                    String cacheNamesArg = argIterator.nextArg("Expected a comma-separated cache names (and optionally a"
+                        + " comma-separated list of index names in square brackets).");
+
+                    Pattern cacheNamesPattern = Pattern.compile("([^,\\[\\]]+)(\\[(.*?)])?");
+                    Matcher matcher = cacheNamesPattern.matcher(cacheNamesArg);
+
+                    boolean found = false;
+
+                    while (matcher.find()) {
+                        found = true;
+
+                        String cacheName = matcher.group(1);
+                        String commaSeparatedIndexes = matcher.group(3);
+
+                        if (F.isEmpty(commaSeparatedIndexes)) {
+                            cacheToIndexes.put(cacheName, Collections.emptySet());

Review Comment:
   So if the user specifies `--cache-names a[]`, it means 'process all indices on a'. But the user has explicitly specified an empty set of indices. This does not make a lot of sense, but still, this looks like an ambiguity.
   
   I suggest to treat things like `a[]` like errors. If the user wants full rebuild on a cache, they should omit the brackets altogether.



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+            this.cacheGroups = cacheGroups;
+        }
+
+        /**
+         * @return Cache -> indexes map.
+         */
+        public Map<String, Set<String>> cacheToIndexes() {
+            return cacheToIndexes;
+        }
+
+        /**
+         * @return Cache groups.
+         */
+        public Set<String> cacheGroups() {

Review Comment:
   This method does not seem to be used. It it needed at all?



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884530430


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   Why do you need group names? Indexes belongs to caches, not groups



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884540333


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   Yes, for groups, you can remove the index refinement, the idea is that you need to give the opportunity to rebuild the indexes for all caches in the group.



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884475350


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheCommandList.java:
##########
@@ -87,7 +87,12 @@ public enum CacheCommandList {
     /**
      * Index force rebuild.
      */
-    INDEX_FORCE_REBUILD("indexes_force_rebuild", new CacheIndexesForceRebuild());
+    INDEX_FORCE_REBUILD("indexes_force_rebuild", new CacheIndexesForceRebuild()),
+
+    /**
+     * Schedule index rebuild.
+     */
+    INDEX_REBUILD("indexes_rebuild", new CacheIndexesRebuild());

Review Comment:
   **indexes_rebuild** doesn't sound to me like scheduling an index rebuild, but how to perform an index rebuild, I suggest calling it something else: **schedule_indexes_rebuild**



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {

Review Comment:
   Maybe: **CacheScheduleIndexesRebuild** ?



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.
+ */
+public class IndexRebuildJobRes extends IgniteDataTransferObject {
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/control-utility/src/test/java/org/apache/ignite/internal/commandline/CommandHandlerParsingTest.java:
##########
@@ -934,6 +934,26 @@ public void testIndexForceRebuildWrongArgs() {
         );
     }
 
+    /** */
+    @Test
+    public void testIndexRebuildWrongArgs() {

Review Comment:
   Missing check --node-id twice



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.
+ */
+public class IndexRebuildJobRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map cache names -> indexes scheduled for the rebuild. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /** Names of caches that were not found. */
+    private Set<String> notFoundCacheNames;
+
+    /** Names of cache indexes that were not found (cache -> set of indexes). */
+    private Map<String, Set<String>> notFoundIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildJobRes() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildJobRes(
+        Map<String, Set<String>> cacheToIndexes,
+        Map<String, Set<String>> notFoundIndexes,
+        Set<String> notFoundCacheNames
+    ) {
+        this.cacheToIndexes = cacheToIndexes;
+        this.notFoundIndexes = notFoundIndexes;
+        this.notFoundCacheNames = notFoundCacheNames;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
+        U.writeMap(out, cacheToIndexes);
+        U.writeMap(out, notFoundIndexes);
+        U.writeCollection(out, notFoundCacheNames);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
+        cacheToIndexes = U.readMap(in);
+        notFoundIndexes = U.readMap(in);
+        notFoundCacheNames = U.readSet(in);
+    }
+
+    /** */
+    public Map<String, Set<String>> cacheToIndexes() {
+        return cacheToIndexes;
+    }
+
+    /** */
+    public Set<String> notFoundCacheNames() {
+        return notFoundCacheNames;
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.
+ */
+public class IndexRebuildJobRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map cache names -> indexes scheduled for the rebuild. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /** Names of caches that were not found. */
+    private Set<String> notFoundCacheNames;
+
+    /** Names of cache indexes that were not found (cache -> set of indexes). */
+    private Map<String, Set<String>> notFoundIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildJobRes() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildJobRes(
+        Map<String, Set<String>> cacheToIndexes,
+        Map<String, Set<String>> notFoundIndexes,
+        Set<String> notFoundCacheNames
+    ) {
+        this.cacheToIndexes = cacheToIndexes;
+        this.notFoundIndexes = notFoundIndexes;
+        this.notFoundCacheNames = notFoundCacheNames;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
+        U.writeMap(out, cacheToIndexes);
+        U.writeMap(out, notFoundIndexes);
+        U.writeCollection(out, notFoundCacheNames);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
+        cacheToIndexes = U.readMap(in);
+        notFoundIndexes = U.readMap(in);
+        notFoundCacheNames = U.readSet(in);
+    }
+
+    /** */
+    public Map<String, Set<String>> cacheToIndexes() {
+        return cacheToIndexes;
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskRes.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildTask.
+ */
+public class IndexRebuildTaskRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map node id -> rebuild command result. */
+    private Map<UUID, IndexRebuildJobRes> results;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildTaskRes() {
+        // No-op.
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/indexing/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTask.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.task.GridInternal;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.internal.visor.VisorJob;
+import org.apache.ignite.internal.visor.VisorMultiNodeTask;
+import org.apache.ignite.maintenance.MaintenanceRegistry;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.h2.index.Index;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.mergeTasks;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.toMaintenanceTask;
+
+/**
+ * Task that schedules indexes rebuild for specified caches via the maintenance mode.
+ */
+@GridInternal
+public class IndexRebuildTask extends VisorMultiNodeTask<IndexRebuildTaskArg, IndexRebuildTaskRes, IndexRebuildJobRes> {
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   ```suggestion
           map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
           
   ```



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);

Review Comment:
   Why not just **new LinkedHashMap<>**?



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheSubcommands.java:
##########
@@ -88,6 +89,11 @@ public enum CacheSubcommands {
      */
     INDEX_FORCE_REBUILD("indexes_force_rebuild", IndexForceRebuildCommandArg.class, new CacheIndexesForceRebuild()),
 
+    /**
+     * Index rebuild via the maintenance mode.
+     */
+    INDEX_REBUILD("indexes_rebuild", IndexRebuildCommandArg.class, new CacheIndexesRebuild()),

Review Comment:
   **indexes_rebuild** doesn't sound to me like scheduling an index rebuild, but how to perform an index rebuild, I suggest calling it something else: **schedule_indexes_rebuild**



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerIndexRebuildTest.java:
##########
@@ -0,0 +1,369 @@
+/*
+ * 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.ignite.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.junit.Test;
+
+import static org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.util.IgniteUtils.max;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.breakSqlIndex;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.complexIndexEntity;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillCache;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillThreeFieldsEntryCache;
+
+/**
+ * Tests for --cache indexes_rebuild command. Uses single cluster per suite.
+ */
+public class GridCommandHandlerIndexRebuildTest extends GridCommandHandlerAbstractTest {
+    /** */
+    private static final String CACHE_NAME_1_1 = "cache_1_1";
+
+    /** */
+    private static final String CACHE_NAME_1_2 = "cache_1_2";
+
+    /** */
+    private static final String CACHE_NAME_2_1 = "cache_2_1";
+
+    /** */
+    private static final String CACHE_NAME_NO_GRP = "cache_no_group";
+
+    /** */
+    private static final String CACHE_NAME_NON_EXISTING = "non_existing_cache";
+
+    /** */
+    private static final String GRP_NAME_1 = "group_1";
+
+    /** */
+    private static final String GRP_NAME_2 = "group_2";
+
+    /** */
+    private static final int GRIDS_NUM = 3;
+
+    /** */
+    private static final int LAST_NODE_NUM = GRIDS_NUM - 1;
+
+    /** */
+    private static final int REBUILD_TIMEOUT = 30_000;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(new ListeningTestLogger(log));
+
+        cfg.setBuildIndexThreadPoolSize(max(2, cfg.getBuildIndexThreadPoolSize()));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        cleanPersistenceDir();
+
+        startupTestCluster();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTestsStopped() throws Exception {
+        stopAllGrids();
+
+        cleanPersistenceDir();
+
+        super.afterTestsStopped();
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void afterTest() throws Exception {
+        super.afterTest();
+
+        G.allGrids().forEach(ignite -> assertFalse(((IgniteEx)ignite).context().maintenanceRegistry().isMaintenanceMode()));
+    }
+
+    /** */
+    private void startupTestCluster() throws Exception {
+        for (int i = 0; i < GRIDS_NUM; i++ )
+            startGrid(i);
+
+        IgniteEx ignite = grid(0);
+
+        ignite.cluster().state(ClusterState.ACTIVE);
+
+        createAndFillCache(ignite, CACHE_NAME_1_1, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_1_2, GRP_NAME_1);
+        createAndFillCache(ignite, CACHE_NAME_2_1, GRP_NAME_2);
+
+        createAndFillThreeFieldsEntryCache(ignite, CACHE_NAME_NO_GRP, null, Collections.singletonList(complexIndexEntity()));
+
+        assertTrue(grid(LAST_NODE_NUM).context().config().getBuildIndexThreadPoolSize() > 1);
+    }
+
+    /**
+     * Checks error messages when trying to rebuild indexes for non-existent cache or when trying
+     * to rebuild non-existent indexes.
+     */
+    @Test
+    public void testErrors() {
+        injectTestSystemOut();
+
+        IgniteEx lastNode = grid(LAST_NODE_NUM);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "indexes_rebuild",
+            "--node-id", lastNode.localNode().id().toString(),
+            "--target", CACHE_NAME_NON_EXISTING));
+
+        String notExistingCacheOutputStr = testOut.toString();
+
+        assertTrue(notExistingCacheOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+
+        testOut.reset();
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "indexes_rebuild",
+            "--node-id", grid(LAST_NODE_NUM).localNode().id().toString(),
+            "--target", CACHE_NAME_1_1 + "=non-existing-index"));
+
+        String notExistingIndexOutputStr = testOut.toString();
+
+        assertTrue(notExistingIndexOutputStr.contains("WARNING: Indexes rebuild was not scheduled for any cache. Check command input."));
+
+        assertTrue(notExistingIndexOutputStr.contains(
+            "WARNING: These indexes were not found:" + System.lineSeparator()
+            + INDENT + CACHE_NAME_1_1 + ":" + System.lineSeparator()
+            + INDENT + INDENT + "non-existing-index")
+        );
+    }
+
+    /**
+     * Checks that index is rebuilt correctly.
+     */
+    @Test
+    public void testRebuild() throws Exception {
+        injectTestSystemOut();
+
+        IgniteEx node = grid(LAST_NODE_NUM);
+
+        assertEquals(EXIT_CODE_OK, execute("--cache", "indexes_rebuild",
+            "--node-id", node.localNode().id().toString(),
+            "--target", CACHE_NAME_NO_GRP));
+
+        node.close();

Review Comment:
   Please add a check that an index rebuild is scheduled for the given cache and index.



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        IndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.IndexRebuildTask",
+                new IndexRebuildTaskArg(args.cacheToIndexes),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(IndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            if (!F.isEmpty(res.notFoundCacheNames())) {
+                String warning = "WARNING: These caches were not found:";
+
+                logger.info(warning);
+
+                res.notFoundCacheNames()
+                    .stream()
+                    .sorted()
+                    .forEach(name -> logger.info(INDENT + name));
+
+                logger.info("");
+            }
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasIndexes(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasIndexes(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /** */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has indexes, {@code false} otherwise.
+     */
+    private static boolean hasIndexes(Map<String, Set<String>> cacheToIndexes) {

Review Comment:
   Incomprehensible method semantics.



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        IndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.IndexRebuildTask",
+                new IndexRebuildTaskArg(args.cacheToIndexes),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(IndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            if (!F.isEmpty(res.notFoundCacheNames())) {
+                String warning = "WARNING: These caches were not found:";
+
+                logger.info(warning);
+
+                res.notFoundCacheNames()
+                    .stream()
+                    .sorted()
+                    .forEach(name -> logger.info(INDENT + name));
+
+                logger.info("");
+            }
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasIndexes(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasIndexes(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /** */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has indexes, {@code false} otherwise.
+     */
+    private static boolean hasIndexes(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = new HashMap<>();

Review Comment:
   ```suggestion
           Map<String, Set<String>> cacheToIndexes = new HashMap<>();
           
   ```



##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   I think it would be better to have two arguments and have them in the following options:
   - --cache-names=cache0,cache1[idx0,idx2]
   - --group-names=grp0,grp1[idx0,idx2]



##########
modules/control-utility/src/test/java/org/apache/ignite/util/GridCommandHandlerIndexRebuildTest.java:
##########
@@ -0,0 +1,369 @@
+/*
+ * 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.ignite.util;
+
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.List;
+import org.apache.ignite.cluster.ClusterState;
+import org.apache.ignite.configuration.IgniteConfiguration;
+import org.apache.ignite.internal.IgniteEx;
+import org.apache.ignite.internal.IgniteInterruptedCheckedException;
+import org.apache.ignite.internal.util.typedef.G;
+import org.apache.ignite.testframework.GridTestUtils;
+import org.apache.ignite.testframework.ListeningTestLogger;
+import org.junit.Test;
+
+import static org.apache.ignite.internal.commandline.CommandHandler.EXIT_CODE_OK;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.util.IgniteUtils.max;
+import static org.apache.ignite.testframework.GridTestUtils.assertContains;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.breakSqlIndex;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.complexIndexEntity;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillCache;
+import static org.apache.ignite.util.GridCommandHandlerIndexingUtils.createAndFillThreeFieldsEntryCache;
+
+/**
+ * Tests for --cache indexes_rebuild command. Uses single cluster per suite.
+ */
+public class GridCommandHandlerIndexRebuildTest extends GridCommandHandlerAbstractTest {
+    /** */
+    private static final String CACHE_NAME_1_1 = "cache_1_1";
+
+    /** */
+    private static final String CACHE_NAME_1_2 = "cache_1_2";
+
+    /** */
+    private static final String CACHE_NAME_2_1 = "cache_2_1";
+
+    /** */
+    private static final String CACHE_NAME_NO_GRP = "cache_no_group";
+
+    /** */
+    private static final String CACHE_NAME_NON_EXISTING = "non_existing_cache";
+
+    /** */
+    private static final String GRP_NAME_1 = "group_1";
+
+    /** */
+    private static final String GRP_NAME_2 = "group_2";
+
+    /** */
+    private static final int GRIDS_NUM = 3;
+
+    /** */
+    private static final int LAST_NODE_NUM = GRIDS_NUM - 1;
+
+    /** */
+    private static final int REBUILD_TIMEOUT = 30_000;
+
+    /** {@inheritDoc} */
+    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
+        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);
+
+        cfg.setGridLogger(new ListeningTestLogger(log));
+
+        cfg.setBuildIndexThreadPoolSize(max(2, cfg.getBuildIndexThreadPoolSize()));
+
+        return cfg;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void beforeTestsStarted() throws Exception {
+        super.beforeTestsStarted();
+
+        cleanPersistenceDir();

Review Comment:
   ```suggestion
           stopAllGrids();
           
           cleanPersistenceDir();
   ```



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.
+ */
+public class IndexRebuildJobRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map cache names -> indexes scheduled for the rebuild. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /** Names of caches that were not found. */
+    private Set<String> notFoundCacheNames;
+
+    /** Names of cache indexes that were not found (cache -> set of indexes). */
+    private Map<String, Set<String>> notFoundIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildJobRes() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildJobRes(

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskArg.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Argument for the IndexRebuildTask.
+ */
+public class IndexRebuildTaskArg extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Cache name. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildTaskArg() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildTaskArg(Map<String, Set<String>> cacheToIndexes) {
+        this.cacheToIndexes = cacheToIndexes;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
+        U.writeMap(out, cacheToIndexes);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
+        cacheToIndexes = U.readMap(in);
+    }
+
+    /**
+     * @return Cache group name.

Review Comment:
   Wrong javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.

Review Comment:
   Missing link.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.
+ */
+public class IndexRebuildJobRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map cache names -> indexes scheduled for the rebuild. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /** Names of caches that were not found. */
+    private Set<String> notFoundCacheNames;
+
+    /** Names of cache indexes that were not found (cache -> set of indexes). */
+    private Map<String, Set<String>> notFoundIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildJobRes() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildJobRes(
+        Map<String, Set<String>> cacheToIndexes,
+        Map<String, Set<String>> notFoundIndexes,
+        Set<String> notFoundCacheNames
+    ) {
+        this.cacheToIndexes = cacheToIndexes;
+        this.notFoundIndexes = notFoundIndexes;
+        this.notFoundCacheNames = notFoundCacheNames;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
+        U.writeMap(out, cacheToIndexes);
+        U.writeMap(out, notFoundIndexes);
+        U.writeCollection(out, notFoundCacheNames);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
+        cacheToIndexes = U.readMap(in);
+        notFoundIndexes = U.readMap(in);
+        notFoundCacheNames = U.readSet(in);
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskRes.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildTask.

Review Comment:
   Missing link.



##########
modules/core/src/main/java/org/apache/ignite/internal/cache/query/index/sorted/maintenance/MaintenanceRebuildIndexUtils.java:
##########
@@ -96,6 +99,30 @@ public static MaintenanceTask toMaintenanceTask(int cacheId, String idxName) {
         );
     }
 
+    /**
+     * Constructs an index rebuild maintenance task based on a map cacheId -> indexes.
+     *

Review Comment:
   Please add example of parameters.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskRes.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildTask.
+ */
+public class IndexRebuildTaskRes extends IgniteDataTransferObject {
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskRes.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildTask.
+ */
+public class IndexRebuildTaskRes extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Map node id -> rebuild command result. */
+    private Map<UUID, IndexRebuildJobRes> results;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildTaskRes() {
+        // No-op.
+    }
+
+    /** */
+    public IndexRebuildTaskRes(Map<UUID, IndexRebuildJobRes> results) {
+        this.results = results;
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void writeExternalData(ObjectOutput out) throws IOException {
+        U.writeMap(out, results);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected void readExternalData(byte protoVer, ObjectInput in) throws IOException, ClassNotFoundException {
+        results = U.readMap(in);
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/indexing/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTask.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.task.GridInternal;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.internal.visor.VisorJob;
+import org.apache.ignite.internal.visor.VisorMultiNodeTask;
+import org.apache.ignite.maintenance.MaintenanceRegistry;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.h2.index.Index;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.mergeTasks;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.toMaintenanceTask;
+
+/**
+ * Task that schedules indexes rebuild for specified caches via the maintenance mode.
+ */
+@GridInternal
+public class IndexRebuildTask extends VisorMultiNodeTask<IndexRebuildTaskArg, IndexRebuildTaskRes, IndexRebuildJobRes> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** {@inheritDoc} */
+    @Override protected IndexRebuildJob job(IndexRebuildTaskArg arg) {
+        return new IndexRebuildJob(arg, debug);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected @Nullable IndexRebuildTaskRes reduce0(List<ComputeJobResult> results) throws IgniteException {
+        Map<UUID, IndexRebuildJobRes> taskResultMap = results.stream()
+            .collect(Collectors.toMap(res -> res.getNode().id(), ComputeJobResult::getData));
+
+        return new IndexRebuildTaskRes(taskResultMap);
+    }
+
+    /** */
+    private static class IndexRebuildJob extends VisorJob<IndexRebuildTaskArg, IndexRebuildJobRes> {
+        /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskArg.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Argument for the IndexRebuildTask.
+ */
+public class IndexRebuildTaskArg extends IgniteDataTransferObject {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** Cache name. */
+    private Map<String, Set<String>> cacheToIndexes;
+
+    /**
+     * Empty constructor required for Serializable.
+     */
+    public IndexRebuildTaskArg() {
+        // No-op.
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/indexing/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTask.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.task.GridInternal;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.internal.visor.VisorJob;
+import org.apache.ignite.internal.visor.VisorMultiNodeTask;
+import org.apache.ignite.maintenance.MaintenanceRegistry;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.h2.index.Index;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.mergeTasks;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.toMaintenanceTask;
+
+/**
+ * Task that schedules indexes rebuild for specified caches via the maintenance mode.
+ */
+@GridInternal
+public class IndexRebuildTask extends VisorMultiNodeTask<IndexRebuildTaskArg, IndexRebuildTaskRes, IndexRebuildJobRes> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** {@inheritDoc} */
+    @Override protected IndexRebuildJob job(IndexRebuildTaskArg arg) {
+        return new IndexRebuildJob(arg, debug);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected @Nullable IndexRebuildTaskRes reduce0(List<ComputeJobResult> results) throws IgniteException {
+        Map<UUID, IndexRebuildJobRes> taskResultMap = results.stream()
+            .collect(Collectors.toMap(res -> res.getNode().id(), ComputeJobResult::getData));
+
+        return new IndexRebuildTaskRes(taskResultMap);
+    }
+
+    /** */
+    private static class IndexRebuildJob extends VisorJob<IndexRebuildTaskArg, IndexRebuildJobRes> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /**
+         * Create job with specified argument.
+         *
+         * @param arg Job argument.
+         * @param debug Flag indicating whether debug information should be printed into node log.
+         */
+        protected IndexRebuildJob(@Nullable IndexRebuildTaskArg arg, boolean debug) {
+            super(arg, debug);
+        }
+
+        /** {@inheritDoc} */
+        @Override protected IndexRebuildJobRes run(@Nullable IndexRebuildTaskArg arg) throws IgniteException {
+            assert arg.cacheToIndexes() != null && !arg.cacheToIndexes().isEmpty() : "Cache to indexes map must be specified.";
+
+            Set<String> notFound = new HashSet<>();
+
+            GridCacheProcessor cacheProcessor = ignite.context().cache();
+
+            Map<String, Set<String>> cacheToIndexes = new HashMap<>();
+            Map<String, Set<String>> cacheToMissedIndexes = new HashMap<>();
+
+            for (Entry<String, Set<String>> indexesByCache : arg.cacheToIndexes().entrySet()) {
+                String cache = indexesByCache.getKey();
+                Set<String> indexesArg = indexesByCache.getValue();
+                int cacheId = CU.cacheId(cache);
+
+                GridCacheContext<?, ?> cacheCtx = cacheProcessor.context().cacheContext(cacheId);
+
+                if (cacheCtx == null) {
+                    notFound.add(cache);
+                    continue;
+                }
+
+                Set<String> existingIndexes = indexes(cache);
+                Set<String> indexesToRebuild = cacheToIndexes.computeIfAbsent(cache, s -> new HashSet<>());
+                Set<String> missedIndexes = cacheToMissedIndexes.computeIfAbsent(cache, s -> new HashSet<>());
+
+                if (indexesArg.isEmpty())
+                    indexesToRebuild.addAll(existingIndexes);
+                else {
+                    indexesArg.forEach(index -> {
+                        if (!existingIndexes.contains(index)) {
+                            missedIndexes.add(index);
+                            return;
+                        }
+
+                        indexesToRebuild.add(index);
+                    });
+                }
+            }
+
+            if (hasIndexes(cacheToIndexes)) {

Review Comment:
   Why not **!cacheToIndexes.isEmpty()**?



##########
modules/indexing/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTask.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.task.GridInternal;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.internal.visor.VisorJob;
+import org.apache.ignite.internal.visor.VisorMultiNodeTask;
+import org.apache.ignite.maintenance.MaintenanceRegistry;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.h2.index.Index;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.mergeTasks;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.toMaintenanceTask;
+
+/**
+ * Task that schedules indexes rebuild for specified caches via the maintenance mode.
+ */
+@GridInternal
+public class IndexRebuildTask extends VisorMultiNodeTask<IndexRebuildTaskArg, IndexRebuildTaskRes, IndexRebuildJobRes> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** {@inheritDoc} */
+    @Override protected IndexRebuildJob job(IndexRebuildTaskArg arg) {
+        return new IndexRebuildJob(arg, debug);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected @Nullable IndexRebuildTaskRes reduce0(List<ComputeJobResult> results) throws IgniteException {
+        Map<UUID, IndexRebuildJobRes> taskResultMap = results.stream()
+            .collect(Collectors.toMap(res -> res.getNode().id(), ComputeJobResult::getData));
+
+        return new IndexRebuildTaskRes(taskResultMap);
+    }
+
+    /** */

Review Comment:
   Missing javadoc.



##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskArg.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Argument for the IndexRebuildTask.

Review Comment:
   Missing link.



##########
modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/maintenance/MaintenanceRebuildIndexUtilsSelfTest.java:
##########
@@ -117,4 +125,27 @@ public void testIndexNameWithSeparatorCharacter() {
         assertEquals(cacheId, target.cacheId());
         assertEquals(idxName, target.idxName());
     }
+
+    /**
+     * Tests that maintenance task can be constructed from a map.
+     */
+    @Test
+    public void testConstructFromMap() {
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(1, new HashSet<>(Arrays.asList("foo", "bar")));
+        cacheToIndexes.put(2, new HashSet<>(Arrays.asList("foo1", "bar1")));
+
+        MaintenanceTask task = toMaintenanceTask(cacheToIndexes);
+
+        List<MaintenanceRebuildIndexTarget> targets = parseMaintenanceTaskParameters(task.parameters());
+
+        assertEquals(4, targets.size());
+
+        Map<Integer, Set<String>> result = targets.stream().collect(groupingBy(
+            MaintenanceRebuildIndexTarget::cacheId,
+            mapping(MaintenanceRebuildIndexTarget::idxName, toSet())
+        ));
+
+        assertEquals(cacheToIndexes, result);

Review Comment:
   Please use **GridCommonAbstractTest#assertEqualsMaps**



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884533868


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        IndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.IndexRebuildTask",
+                new IndexRebuildTaskArg(args.cacheToIndexes),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(IndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            if (!F.isEmpty(res.notFoundCacheNames())) {
+                String warning = "WARNING: These caches were not found:";
+
+                logger.info(warning);
+
+                res.notFoundCacheNames()
+                    .stream()
+                    .sorted()
+                    .forEach(name -> logger.info(INDENT + name));
+
+                logger.info("");
+            }
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasIndexes(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasIndexes(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /** */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has indexes, {@code false} otherwise.
+     */
+    private static boolean hasIndexes(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = new HashMap<>();

Review Comment:
   It's the same line



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884846705


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   I don't understand, these lines are identical



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884853242


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   Got it, it's a newline



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] rpuch commented on pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
rpuch commented on PR #10042:
URL: https://github.com/apache/ignite/pull/10042#issuecomment-1168786380

   LGTM


-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884986355


##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskRes.java:
##########
@@ -0,0 +1,64 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.UUID;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildTask.

Review Comment:
   Can't reference indexing module from here



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

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884534674


##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.

Review Comment:
   You can't add a link here, job is located in indexing module



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884533033


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   Why do you need group names? Indexes belong to caches, not groups



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884529797


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   Isn't it the same?



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884538349


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");

Review Comment:
   This is an offer.



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884540862


##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildJobRes.java:
##########
@@ -0,0 +1,90 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Result of the IndexRebuildJob.

Review Comment:
   Ok



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] tkalkirill commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
tkalkirill commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884541609


##########
modules/indexing/src/test/java/org/apache/ignite/internal/processors/query/h2/maintenance/MaintenanceRebuildIndexUtilsSelfTest.java:
##########
@@ -117,4 +125,27 @@ public void testIndexNameWithSeparatorCharacter() {
         assertEquals(cacheId, target.cacheId());
         assertEquals(idxName, target.idxName());
     }
+
+    /**
+     * Tests that maintenance task can be constructed from a map.
+     */
+    @Test
+    public void testConstructFromMap() {
+        Map<Integer, Set<String>> cacheToIndexes = new HashMap<>();
+        cacheToIndexes.put(1, new HashSet<>(Arrays.asList("foo", "bar")));
+        cacheToIndexes.put(2, new HashSet<>(Arrays.asList("foo1", "bar1")));
+
+        MaintenanceTask task = toMaintenanceTask(cacheToIndexes);
+
+        List<MaintenanceRebuildIndexTarget> targets = parseMaintenanceTaskParameters(task.parameters());
+
+        assertEquals(4, targets.size());
+
+        Map<Integer, Set<String>> result = targets.stream().collect(groupingBy(
+            MaintenanceRebuildIndexTarget::cacheId,
+            mapping(MaintenanceRebuildIndexTarget::idxName, toSet())
+        ));
+
+        assertEquals(cacheToIndexes, result);

Review Comment:
   It will be clearer than these maps differ.



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r908449223


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheScheduleIndexesRebuild.java:
##########
@@ -0,0 +1,320 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTaskRes;
+
+import static java.util.stream.Collectors.toSet;
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_GROUPS_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.CACHE_NAMES_TARGET;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheScheduleIndexesRebuild extends AbstractCommand<CacheScheduleIndexesRebuild.Arguments> {
+    /** --cache-names parameter format. */
+    private static final String CACHE_NAMES_FORMAT = "cacheName[index1,...indexN],cacheName2,cacheName3[index1]";
+
+    /** --group-names parameter format. */
+    private static final String CACHE_GROUPS_FORMAT = "groupName1,groupName2,...groupNameN";
+
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches via the Maintenance Mode.";
+
+        Map<String, String> map = new LinkedHashMap<>(2);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+
+        map.put(
+            CACHE_NAMES_TARGET.argName(),
+            "Comma-separated list of cache names with optionally specified indexes. If indexes are not specified then all indexes "
+            + "of the cache will be scheduled for the rebuild operation."
+        );
+
+        map.put(CACHE_GROUPS_TARGET.argName(), "Comma-separated list of cache group names for which indexes should be scheduled for the "
+            + "rebuild.");
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            CACHE_NAMES_TARGET + " " + CACHE_NAMES_FORMAT,
+            CACHE_GROUPS_TARGET + " " + CACHE_GROUPS_FORMAT
+        );
+    }
+
+    /** {@inheritDoc} */
+    @Override public Object execute(GridClientConfiguration clientCfg, Logger logger) throws Exception {
+        ScheduleIndexRebuildTaskRes taskRes;
+
+        try (GridClient client = Command.startClient(clientCfg)) {
+            UUID nodeId = args.nodeId;
+
+            if (nodeId == null)
+                nodeId = TaskExecutor.BROADCAST_UUID;
+
+            taskRes = TaskExecutor.executeTaskByNameOnNode(
+                client,
+                "org.apache.ignite.internal.visor.cache.index.ScheduleIndexRebuildTask",
+                new ScheduleIndexRebuildTaskArg(args.cacheToIndexes, args.cacheGroups),
+                nodeId,
+                clientCfg
+            );
+        }
+
+        printResult(taskRes, logger);
+
+        return taskRes;
+    }
+
+    /**
+     * @param taskRes Rebuild task result.
+     * @param logger Logger to print to.
+     */
+    private void printResult(ScheduleIndexRebuildTaskRes taskRes, Logger logger) {
+        taskRes.results().forEach((nodeId, res) -> {
+            printMissed(logger, "WARNING: These caches were not found:", res.notFoundCacheNames());
+            printMissed(logger, "WARNING: These cache groups were not found:", res.notFoundGroupNames());
+
+            if (!F.isEmpty(res.notFoundIndexes()) && hasAtLeastOneIndex(res.notFoundIndexes())) {
+                String warning = "WARNING: These indexes were not found:";
+
+                logger.info(warning);
+
+                printCachesAndIndexes(res.notFoundIndexes(), logger);
+            }
+
+            if (!F.isEmpty(res.cacheToIndexes()) && hasAtLeastOneIndex(res.cacheToIndexes())) {
+                logger.info("Indexes rebuild was scheduled for these caches:");
+
+                printCachesAndIndexes(res.cacheToIndexes(), logger);
+            }
+            else
+                logger.info("WARNING: Indexes rebuild was not scheduled for any cache. Check command input.");
+
+            logger.info("");
+        });
+    }
+
+    /**
+     * Prints missed caches' or cache groups' names.
+     *
+     * @param logger Logger.
+     * @param warning Warning message.
+     * @param missed Missed caches or cache groups' names.
+     */
+    private void printMissed(Logger logger, String warning, Set<String> missed) {
+        if (!F.isEmpty(missed)) {
+            logger.info(warning);
+
+            missed.stream()
+                .sorted()
+                .forEach(name -> logger.info(INDENT + name));
+
+            logger.info("");
+        }
+    }
+
+    /**
+     * Prints caches and their indexes.
+     *
+     * @param cachesToIndexes Cache -> indexes map.
+     * @param logger Logger.
+     */
+    private static void printCachesAndIndexes(Map<String, Set<String>> cachesToIndexes, Logger logger) {
+        cachesToIndexes.forEach((cacheName, indexes) -> {
+            logger.info(INDENT + cacheName + ":");
+            indexes.forEach(index -> logger.info(INDENT + INDENT + index));
+        });
+    }
+
+    /**
+     * @param cacheToIndexes Cache name -> indexes map.
+     * @return {@code true} if has at least one index in the map, {@code false} otherwise.
+     */
+    private static boolean hasAtLeastOneIndex(Map<String, Set<String>> cacheToIndexes) {
+        return cacheToIndexes.values().stream()
+            .anyMatch(indexes -> !indexes.isEmpty());
+    }
+
+    /** {@inheritDoc} */
+    @Override public Arguments arg() {
+        return args;
+    }
+
+    /** {@inheritDoc} */
+    @Override public String name() {
+        return CacheSubcommands.INDEX_REBUILD.text().toUpperCase();
+    }
+
+    /**
+     * Container for command arguments.
+     */
+    public static class Arguments {
+        /** Node id. */
+        private final UUID nodeId;
+
+        /** Cache name -> indexes. */
+        private final Map<String, Set<String>> cacheToIndexes;
+
+        /** Cache groups' names. */
+        private final Set<String> cacheGroups;
+
+        /** */
+        private Arguments(UUID nodeId, Map<String, Set<String>> cacheToIndexes, Set<String> cacheGroups) {
+            this.nodeId = nodeId;
+            this.cacheToIndexes = cacheToIndexes;
+            this.cacheGroups = cacheGroups;
+        }
+
+        /**
+         * @return Cache -> indexes map.
+         */
+        public Map<String, Set<String>> cacheToIndexes() {
+            return cacheToIndexes;
+        }
+
+        /**
+         * @return Cache groups.
+         */
+        public Set<String> cacheGroups() {
+            return cacheGroups;
+        }
+
+        /** {@inheritDoc} */
+        @Override public String toString() {
+            return S.toString(Arguments.class, this);
+        }
+    }
+
+    /** {@inheritDoc} */
+    @Override public void parseArguments(CommandArgIterator argIterator) {
+        UUID nodeId = null;
+        Map<String, Set<String>> cacheToIndexes = null;
+        Set<String> cacheGroups = null;
+
+        while (argIterator.hasNextSubArg()) {
+            String nextArg = argIterator.nextArg("");
+
+            IndexRebuildCommandArg arg = CommandArgUtils.of(nextArg, IndexRebuildCommandArg.class);
+
+            if (arg == null)
+                throw new IllegalArgumentException("Unknown argument: " + nextArg);
+
+            switch (arg) {
+                case NODE_ID:
+                    if (nodeId != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    nodeId = UUID.fromString(argIterator.nextArg("Failed to read node id."));
+
+                    break;
+
+                case CACHE_NAMES_TARGET:
+                    if (cacheToIndexes != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    cacheToIndexes = new HashMap<>();
+
+                    String cacheNamesArg = argIterator.nextArg("Expected a comma-separated cache names (and optionally a"
+                        + " comma-separated list of index names in square brackets).");
+
+                    Pattern cacheNamesPattern = Pattern.compile("([^,\\[\\]]+)(\\[(.*?)])?");
+                    Matcher matcher = cacheNamesPattern.matcher(cacheNamesArg);
+
+                    boolean found = false;
+
+                    while (matcher.find()) {
+                        found = true;
+
+                        String cacheName = matcher.group(1);
+                        String commaSeparatedIndexes = matcher.group(3);
+
+                        if (F.isEmpty(commaSeparatedIndexes)) {
+                            cacheToIndexes.put(cacheName, Collections.emptySet());
+
+                            continue;
+                        }
+
+                        Set<String> indexes = Arrays.stream(commaSeparatedIndexes.split(",")).collect(toSet());
+                        cacheToIndexes.put(cacheName, indexes);
+                    }
+
+                    if (!found)
+                        throw new IllegalArgumentException("Wrong format for --cache-names, should be: " + CACHE_NAMES_FORMAT);
+
+                    break;
+
+                case CACHE_GROUPS_TARGET:
+                    if (cacheGroups != null)
+                        throw new IllegalArgumentException(arg.argName() + " arg specified twice.");
+
+                    String cacheGroupsArg = argIterator.nextArg("Expected comma-separated cache group names");
+
+                    cacheGroups = Arrays.stream(cacheGroupsArg.split(",")).collect(toSet());
+
+                    break;
+
+                default:
+                    throw new IllegalArgumentException("Unknown argument: " + arg.argName());
+            }
+        }
+
+        args = new Arguments(nodeId, cacheToIndexes, cacheGroups);
+
+        validateArguments();
+    }
+
+    /** */
+    private void validateArguments() {
+        Set<String> cacheGroups = args.cacheGroups;
+        Map<String, Set<String>> cacheToIndexes = args.cacheToIndexes;
+
+        if (cacheGroups == null && cacheToIndexes == null && cacheGroups.isEmpty() && cacheToIndexes.isEmpty())

Review Comment:
   Ouch, you're right



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884978763


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);
+
+        map.put(NODE_ID.argName(), "(Optional) Specify node for indexes rebuild.");
+        map.put(
+            TARGET.argName(),
+            "Cache name with optionally specified indexes. If indexes are not specified then all indexes of the cache will be scheduled "
+            + "for the rebuild operation."
+        );
+
+        usageCache(
+            logger,
+            CacheSubcommands.INDEX_REBUILD,
+            desc,
+            map,
+            NODE_ID.argName() + " nodeId",
+            TARGET + " cacheName1=index1,...indexN"

Review Comment:
   Why would you want to rebuild indexes for all caches in the group? Let's not overcomplicate things



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884978027


##########
modules/control-utility/src/main/java/org/apache/ignite/internal/commandline/cache/CacheIndexesRebuild.java:
##########
@@ -0,0 +1,239 @@
+/*
+ * 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.ignite.internal.commandline.cache;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.UUID;
+import java.util.logging.Logger;
+import java.util.stream.Collectors;
+import org.apache.ignite.internal.client.GridClient;
+import org.apache.ignite.internal.client.GridClientConfiguration;
+import org.apache.ignite.internal.commandline.AbstractCommand;
+import org.apache.ignite.internal.commandline.Command;
+import org.apache.ignite.internal.commandline.CommandArgIterator;
+import org.apache.ignite.internal.commandline.TaskExecutor;
+import org.apache.ignite.internal.commandline.argument.CommandArgUtils;
+import org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg;
+import org.apache.ignite.internal.util.typedef.F;
+import org.apache.ignite.internal.util.typedef.internal.S;
+import org.apache.ignite.internal.util.typedef.internal.U;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskArg;
+import org.apache.ignite.internal.visor.cache.index.IndexRebuildTaskRes;
+
+import static org.apache.ignite.internal.commandline.CommandLogger.INDENT;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.NODE_ID;
+import static org.apache.ignite.internal.commandline.cache.argument.IndexRebuildCommandArg.TARGET;
+
+/**
+ * Cache subcommand that schedules indexes rebuild via the maintenance mode.
+ */
+public class CacheIndexesRebuild extends AbstractCommand<CacheIndexesRebuild.Arguments> {
+    /** Command's parsed arguments. */
+    private Arguments args;
+
+    /** {@inheritDoc} */
+    @Override public void printUsage(Logger logger) {
+        String desc = "Schedules rebuild of the indexes for specified caches.";
+
+        Map<String, String> map = U.newLinkedHashMap(16);

Review Comment:
   It's a convenient method for creating maps that are not going to be resized



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r885021821


##########
modules/core/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTaskArg.java:
##########
@@ -0,0 +1,66 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Map;
+import java.util.Set;
+import org.apache.ignite.internal.dto.IgniteDataTransferObject;
+import org.apache.ignite.internal.util.typedef.internal.U;
+
+/**
+ * Argument for the IndexRebuildTask.

Review Comment:
   Impossible to reference



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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


[GitHub] [ignite] SammyVimes commented on a diff in pull request #10042: IGNITE-17002 Control.sh command to schedule index rebuild in Maintenance Mode

Posted by GitBox <gi...@apache.org>.
SammyVimes commented on code in PR #10042:
URL: https://github.com/apache/ignite/pull/10042#discussion_r884531710


##########
modules/indexing/src/main/java/org/apache/ignite/internal/visor/cache/index/IndexRebuildTask.java:
##########
@@ -0,0 +1,190 @@
+/*
+ * 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.ignite.internal.visor.cache.index;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
+import java.util.UUID;
+import java.util.stream.Collectors;
+import org.apache.ignite.IgniteCheckedException;
+import org.apache.ignite.IgniteException;
+import org.apache.ignite.compute.ComputeJobResult;
+import org.apache.ignite.internal.processors.cache.GridCacheContext;
+import org.apache.ignite.internal.processors.cache.GridCacheProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryProcessor;
+import org.apache.ignite.internal.processors.query.GridQueryTypeDescriptor;
+import org.apache.ignite.internal.processors.query.h2.IgniteH2Indexing;
+import org.apache.ignite.internal.processors.query.h2.database.H2TreeIndexBase;
+import org.apache.ignite.internal.processors.query.h2.opt.GridH2Table;
+import org.apache.ignite.internal.processors.task.GridInternal;
+import org.apache.ignite.internal.util.typedef.internal.CU;
+import org.apache.ignite.internal.visor.VisorJob;
+import org.apache.ignite.internal.visor.VisorMultiNodeTask;
+import org.apache.ignite.maintenance.MaintenanceRegistry;
+import org.apache.ignite.maintenance.MaintenanceTask;
+import org.h2.index.Index;
+import org.jetbrains.annotations.Nullable;
+
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.mergeTasks;
+import static org.apache.ignite.internal.cache.query.index.sorted.maintenance.MaintenanceRebuildIndexUtils.toMaintenanceTask;
+
+/**
+ * Task that schedules indexes rebuild for specified caches via the maintenance mode.
+ */
+@GridInternal
+public class IndexRebuildTask extends VisorMultiNodeTask<IndexRebuildTaskArg, IndexRebuildTaskRes, IndexRebuildJobRes> {
+    /** */
+    private static final long serialVersionUID = 0L;
+
+    /** {@inheritDoc} */
+    @Override protected IndexRebuildJob job(IndexRebuildTaskArg arg) {
+        return new IndexRebuildJob(arg, debug);
+    }
+
+    /** {@inheritDoc} */
+    @Override protected @Nullable IndexRebuildTaskRes reduce0(List<ComputeJobResult> results) throws IgniteException {
+        Map<UUID, IndexRebuildJobRes> taskResultMap = results.stream()
+            .collect(Collectors.toMap(res -> res.getNode().id(), ComputeJobResult::getData));
+
+        return new IndexRebuildTaskRes(taskResultMap);
+    }
+
+    /** */
+    private static class IndexRebuildJob extends VisorJob<IndexRebuildTaskArg, IndexRebuildJobRes> {
+        /** */
+        private static final long serialVersionUID = 0L;
+
+        /**
+         * Create job with specified argument.
+         *
+         * @param arg Job argument.
+         * @param debug Flag indicating whether debug information should be printed into node log.
+         */
+        protected IndexRebuildJob(@Nullable IndexRebuildTaskArg arg, boolean debug) {
+            super(arg, debug);
+        }
+
+        /** {@inheritDoc} */
+        @Override protected IndexRebuildJobRes run(@Nullable IndexRebuildTaskArg arg) throws IgniteException {
+            assert arg.cacheToIndexes() != null && !arg.cacheToIndexes().isEmpty() : "Cache to indexes map must be specified.";
+
+            Set<String> notFound = new HashSet<>();
+
+            GridCacheProcessor cacheProcessor = ignite.context().cache();
+
+            Map<String, Set<String>> cacheToIndexes = new HashMap<>();
+            Map<String, Set<String>> cacheToMissedIndexes = new HashMap<>();
+
+            for (Entry<String, Set<String>> indexesByCache : arg.cacheToIndexes().entrySet()) {
+                String cache = indexesByCache.getKey();
+                Set<String> indexesArg = indexesByCache.getValue();
+                int cacheId = CU.cacheId(cache);
+
+                GridCacheContext<?, ?> cacheCtx = cacheProcessor.context().cacheContext(cacheId);
+
+                if (cacheCtx == null) {
+                    notFound.add(cache);
+                    continue;
+                }
+
+                Set<String> existingIndexes = indexes(cache);
+                Set<String> indexesToRebuild = cacheToIndexes.computeIfAbsent(cache, s -> new HashSet<>());
+                Set<String> missedIndexes = cacheToMissedIndexes.computeIfAbsent(cache, s -> new HashSet<>());
+
+                if (indexesArg.isEmpty())
+                    indexesToRebuild.addAll(existingIndexes);
+                else {
+                    indexesArg.forEach(index -> {
+                        if (!existingIndexes.contains(index)) {
+                            missedIndexes.add(index);
+                            return;
+                        }
+
+                        indexesToRebuild.add(index);
+                    });
+                }
+            }
+
+            if (hasIndexes(cacheToIndexes)) {

Review Comment:
   Because it checks collections that are values of the map, not the map itself



-- 
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.

To unsubscribe, e-mail: notifications-unsubscribe@ignite.apache.org

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