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-unsubscr...@ignite.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org