You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@geode.apache.org by bs...@apache.org on 2017/08/15 23:10:30 UTC
[19/50] [abbrv] geode git commit: GEODE-3436: revert recent
refactoring of GFSH commands
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
deleted file mode 100644
index b160b99..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateIndexCommand.java
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * 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.geode.management.internal.cli.commands;
-
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.CacheFactory;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.CreateIndexFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateIndexCommand implements GfshCommand {
- private static final CreateIndexFunction createIndexFunction = new CreateIndexFunction();
-
- @CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- // TODO : Add optionContext for indexName
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result createIndex(@CliOption(key = CliStrings.CREATE_INDEX__NAME, mandatory = true,
- help = CliStrings.CREATE_INDEX__NAME__HELP) final String indexName,
-
- @CliOption(key = CliStrings.CREATE_INDEX__EXPRESSION, mandatory = true,
- help = CliStrings.CREATE_INDEX__EXPRESSION__HELP) final String indexedExpression,
-
- @CliOption(key = CliStrings.CREATE_INDEX__REGION, mandatory = true,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_INDEX__REGION__HELP) String regionPath,
-
- @CliOption(key = {CliStrings.MEMBER, CliStrings.MEMBERS},
- optionContext = ConverterHint.MEMBERIDNAME,
- help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID,
-
- @CliOption(key = CliStrings.CREATE_INDEX__TYPE, unspecifiedDefaultValue = "range",
- optionContext = ConverterHint.INDEX_TYPE,
- help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType,
-
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
-
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- try {
- CacheFactory.getAnyInstance();
- int idxType;
-
- // Index type check
- if ("range".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.RANGE_INDEX;
- } else if ("hash".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.HASH_INDEX;
- } else if ("key".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.KEY_INDEX;
- } else {
- return ResultBuilder
- .createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
- }
-
- if (indexName == null || indexName.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__INDEX__NAME);
- }
-
- if (indexedExpression == null || indexedExpression.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__EXPRESSION);
- }
-
- if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.CREATE_INDEX__INVALID__REGIONPATH);
- }
-
- if (!regionPath.startsWith(Region.SEPARATOR)) {
- regionPath = Region.SEPARATOR + regionPath;
- }
-
- IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
- final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
-
- if (targetMembers.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
- }
-
- final ResultCollector<?, ?> rc =
- CliUtil.executeFunction(createIndexFunction, indexInfo, targetMembers);
-
- final List<Object> funcResults = (List<Object>) rc.getResult();
- final Set<String> successfulMembers = new TreeSet<>();
- final Map<String, Set<String>> indexOpFailMap = new HashMap<>();
-
- for (final Object funcResult : funcResults) {
- if (funcResult instanceof CliFunctionResult) {
- final CliFunctionResult cliFunctionResult = (CliFunctionResult) funcResult;
-
- if (cliFunctionResult.isSuccessful()) {
- successfulMembers.add(cliFunctionResult.getMemberIdOrName());
-
- if (xmlEntity.get() == null) {
- xmlEntity.set(cliFunctionResult.getXmlEntity());
- }
- } else {
- final String exceptionMessage = cliFunctionResult.getMessage();
- Set<String> failedMembers = indexOpFailMap.get(exceptionMessage);
-
- if (failedMembers == null) {
- failedMembers = new TreeSet<>();
- }
- failedMembers.add(cliFunctionResult.getMemberIdOrName());
- indexOpFailMap.put(exceptionMessage, failedMembers);
- }
- }
- }
-
- if (!successfulMembers.isEmpty()) {
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.CREATE_INDEX__SUCCESS__MSG);
- infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__NAME__MSG, indexName));
- infoResult.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__EXPRESSION__MSG, indexedExpression));
- infoResult.addLine(CliStrings.format(CliStrings.CREATE_INDEX__REGIONPATH__MSG, regionPath));
- infoResult.addLine(CliStrings.CREATE_INDEX__MEMBER__MSG);
-
- int num = 0;
-
- for (final String memberId : successfulMembers) {
- ++num;
- infoResult.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
- }
- result = ResultBuilder.buildResult(infoResult);
-
- } else {
- // Group members by the exception thrown.
- final ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.CREATE_INDEX__FAILURE__MSG, indexName));
- final Set<String> exceptionMessages = indexOpFailMap.keySet();
-
- for (final String exceptionMessage : exceptionMessages) {
- erd.addLine(exceptionMessage);
- erd.addLine(CliStrings.CREATE_INDEX__EXCEPTION__OCCURRED__ON);
- final Set<String> memberIds = indexOpFailMap.get(exceptionMessage);
- int num = 0;
- for (final String memberId : memberIds) {
- ++num;
- erd.addLine(
- CliStrings.format(CliStrings.CREATE_INDEX__NUMBER__AND__MEMBER, num, memberId));
- }
- }
- result = ResultBuilder.buildResult(erd);
- }
- } catch (Exception e) {
- result = ResultBuilder.createGemFireErrorResult(e.getMessage());
- }
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), group));
- }
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
deleted file mode 100644
index 8ba39b7..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/CreateRegionCommand.java
+++ /dev/null
@@ -1,741 +0,0 @@
-/*
- * 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.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-import java.util.concurrent.atomic.AtomicReference;
-
-import javax.management.ObjectName;
-
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.DataPolicy;
-import org.apache.geode.cache.PartitionResolver;
-import org.apache.geode.cache.Region;
-import org.apache.geode.cache.RegionAttributes;
-import org.apache.geode.cache.RegionShortcut;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.compression.Compressor;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.distributed.internal.DistributionManager;
-import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
-import org.apache.geode.internal.ClassPathLoader;
-import org.apache.geode.internal.cache.InternalCache;
-import org.apache.geode.internal.i18n.LocalizedStrings;
-import org.apache.geode.management.DistributedRegionMXBean;
-import org.apache.geode.management.DistributedSystemMXBean;
-import org.apache.geode.management.ManagementService;
-import org.apache.geode.management.RegionAttributesData;
-import org.apache.geode.management.RegionMXBean;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.LogWrapper;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.FetchRegionAttributesFunction;
-import org.apache.geode.management.internal.cli.functions.RegionCreateFunction;
-import org.apache.geode.management.internal.cli.functions.RegionFunctionArgs;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.cli.util.RegionPath;
-import org.apache.geode.management.internal.configuration.domain.XmlEntity;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class CreateRegionCommand implements GfshCommand {
- public static final Set<RegionShortcut> PERSISTENT_OVERFLOW_SHORTCUTS = new TreeSet<>();
-
- static {
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_OVERFLOW);
- PERSISTENT_OVERFLOW_SHORTCUTS.add(RegionShortcut.LOCAL_PERSISTENT_OVERFLOW);
- }
-
- @CliCommand(value = CliStrings.CREATE_REGION, help = CliStrings.CREATE_REGION__HELP)
- @CliMetaData(relatedTopic = CliStrings.TOPIC_GEODE_REGION)
- @ResourceOperation(resource = ResourcePermission.Resource.DATA,
- operation = ResourcePermission.Operation.MANAGE)
- public Result createRegion(
- @CliOption(key = CliStrings.CREATE_REGION__REGION, mandatory = true,
- help = CliStrings.CREATE_REGION__REGION__HELP) String regionPath,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONSHORTCUT,
- help = CliStrings.CREATE_REGION__REGIONSHORTCUT__HELP) RegionShortcut regionShortcut,
- @CliOption(key = CliStrings.CREATE_REGION__USEATTRIBUTESFROM,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_REGION__USEATTRIBUTESFROM__HELP) String useAttributesFrom,
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
- optionContext = ConverterHint.MEMBERGROUP,
- help = CliStrings.CREATE_REGION__GROUP__HELP) String[] groups,
- @CliOption(key = CliStrings.CREATE_REGION__SKIPIFEXISTS, unspecifiedDefaultValue = "true",
- specifiedDefaultValue = "true",
- help = CliStrings.CREATE_REGION__SKIPIFEXISTS__HELP) boolean skipIfExists,
-
- // the following should all be in alphabetical order according to
- // their key string
- @CliOption(key = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID,
- help = CliStrings.CREATE_REGION__ASYNCEVENTQUEUEID__HELP) String[] asyncEventQueueIds,
- @CliOption(key = CliStrings.CREATE_REGION__CACHELISTENER,
- help = CliStrings.CREATE_REGION__CACHELISTENER__HELP) String[] cacheListener,
- @CliOption(key = CliStrings.CREATE_REGION__CACHELOADER,
- help = CliStrings.CREATE_REGION__CACHELOADER__HELP) String cacheLoader,
- @CliOption(key = CliStrings.CREATE_REGION__CACHEWRITER,
- help = CliStrings.CREATE_REGION__CACHEWRITER__HELP) String cacheWriter,
- @CliOption(key = CliStrings.CREATE_REGION__COLOCATEDWITH,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.CREATE_REGION__COLOCATEDWITH__HELP) String prColocatedWith,
- @CliOption(key = CliStrings.CREATE_REGION__COMPRESSOR,
- help = CliStrings.CREATE_REGION__COMPRESSOR__HELP) String compressor,
- @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYLEVEL,
- help = CliStrings.CREATE_REGION__CONCURRENCYLEVEL__HELP) Integer concurrencyLevel,
- @CliOption(key = CliStrings.CREATE_REGION__DISKSTORE,
- help = CliStrings.CREATE_REGION__DISKSTORE__HELP) String diskStore,
- @CliOption(key = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION,
- help = CliStrings.CREATE_REGION__ENABLEASYNCCONFLATION__HELP) Boolean enableAsyncConflation,
- @CliOption(key = CliStrings.CREATE_REGION__CLONINGENABLED,
- help = CliStrings.CREATE_REGION__CLONINGENABLED__HELP) Boolean cloningEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED,
- help = CliStrings.CREATE_REGION__CONCURRENCYCHECKSENABLED__HELP) Boolean concurrencyChecksEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__MULTICASTENABLED,
- help = CliStrings.CREATE_REGION__MULTICASTENABLED__HELP) Boolean mcastEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__STATISTICSENABLED,
- help = CliStrings.CREATE_REGION__STATISTICSENABLED__HELP) Boolean statisticsEnabled,
- @CliOption(key = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION,
- help = CliStrings.CREATE_REGION__ENABLESUBSCRIPTIONCONFLATION__HELP) Boolean enableSubscriptionConflation,
- @CliOption(key = CliStrings.CREATE_REGION__DISKSYNCHRONOUS,
- help = CliStrings.CREATE_REGION__DISKSYNCHRONOUS__HELP) Boolean diskSynchronous,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIME__HELP) Integer entryExpirationIdleTime,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONIDLETIMEACTION__HELP) String entryExpirationIdleTimeAction,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTIMETOLIVE__HELP) Integer entryExpirationTTL,
- @CliOption(key = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION,
- help = CliStrings.CREATE_REGION__ENTRYEXPIRATIONTTLACTION__HELP) String entryExpirationTTLAction,
- @CliOption(key = CliStrings.CREATE_REGION__GATEWAYSENDERID,
- help = CliStrings.CREATE_REGION__GATEWAYSENDERID__HELP) String[] gatewaySenderIds,
- @CliOption(key = CliStrings.CREATE_REGION__KEYCONSTRAINT,
- help = CliStrings.CREATE_REGION__KEYCONSTRAINT__HELP) String keyConstraint,
- @CliOption(key = CliStrings.CREATE_REGION__LOCALMAXMEMORY,
- help = CliStrings.CREATE_REGION__LOCALMAXMEMORY__HELP) Integer prLocalMaxMemory,
- @CliOption(key = CliStrings.CREATE_REGION__OFF_HEAP, specifiedDefaultValue = "true",
- help = CliStrings.CREATE_REGION__OFF_HEAP__HELP) Boolean offHeap,
- @CliOption(key = CliStrings.CREATE_REGION__PARTITION_RESOLVER,
- help = CliStrings.CREATE_REGION__PARTITION_RESOLVER__HELP) String partitionResolver,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIME__HELP) Integer regionExpirationIdleTime,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONIDLETIMEACTION__HELP) String regionExpirationIdleTimeAction,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTL__HELP) Integer regionExpirationTTL,
- @CliOption(key = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION,
- help = CliStrings.CREATE_REGION__REGIONEXPIRATIONTTLACTION__HELP) String regionExpirationTTLAction,
- @CliOption(key = CliStrings.CREATE_REGION__RECOVERYDELAY,
- help = CliStrings.CREATE_REGION__RECOVERYDELAY__HELP) Long prRecoveryDelay,
- @CliOption(key = CliStrings.CREATE_REGION__REDUNDANTCOPIES,
- help = CliStrings.CREATE_REGION__REDUNDANTCOPIES__HELP) Integer prRedundantCopies,
- @CliOption(key = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY,
- help = CliStrings.CREATE_REGION__STARTUPRECOVERYDDELAY__HELP) Long prStartupRecoveryDelay,
- @CliOption(key = CliStrings.CREATE_REGION__TOTALMAXMEMORY,
- help = CliStrings.CREATE_REGION__TOTALMAXMEMORY__HELP) Long prTotalMaxMemory,
- @CliOption(key = CliStrings.CREATE_REGION__TOTALNUMBUCKETS,
- help = CliStrings.CREATE_REGION__TOTALNUMBUCKETS__HELP) Integer prTotalNumBuckets,
- @CliOption(key = CliStrings.CREATE_REGION__VALUECONSTRAINT,
- help = CliStrings.CREATE_REGION__VALUECONSTRAINT__HELP) String valueConstraint
- // NOTICE: keep the region attributes params in alphabetical order
- ) {
- Result result;
- AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
-
- try {
- InternalCache cache = getCache();
-
- if (regionShortcut != null && useAttributesFrom != null) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__ONLY_ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUESFROM_CAN_BE_SPECIFIED);
- } else if (regionShortcut == null && useAttributesFrom == null) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__ONE_OF_REGIONSHORTCUT_AND_USEATTRIBUTESFROM_IS_REQUIRED);
- }
-
- validateRegionPathAndParent(cache, regionPath);
- RegionCommandsUtils.validateGroups(cache, groups);
-
- RegionFunctionArgs.ExpirationAttrs entryIdle = null;
- if (entryExpirationIdleTime != null) {
- entryIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_IDLE, entryExpirationIdleTime,
- entryExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs entryTTL = null;
- if (entryExpirationTTL != null) {
- entryTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.ENTRY_TTL, entryExpirationTTL,
- entryExpirationTTLAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionIdle = null;
- if (regionExpirationIdleTime != null) {
- regionIdle = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_IDLE, regionExpirationIdleTime,
- regionExpirationIdleTimeAction);
- }
- RegionFunctionArgs.ExpirationAttrs regionTTL = null;
- if (regionExpirationTTL != null) {
- regionTTL = new RegionFunctionArgs.ExpirationAttrs(
- RegionFunctionArgs.ExpirationAttrs.ExpirationFor.REGION_TTL, regionExpirationTTL,
- regionExpirationTTLAction);
- }
-
- RegionFunctionArgs regionFunctionArgs;
- if (useAttributesFrom != null) {
- if (!regionExists(cache, useAttributesFrom)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
- }
-
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<Object, Object> regionAttributesResult =
- getRegionAttributes(cache, useAttributesFrom);
- RegionAttributes<?, ?> regionAttributes = regionAttributesResult.getRegionAttributes();
-
- // give preference to user specified plugins than the ones retrieved from other region
- String[] cacheListenerClasses = cacheListener != null && cacheListener.length != 0
- ? cacheListener : regionAttributesResult.getCacheListenerClasses();
- String cacheLoaderClass =
- cacheLoader != null ? cacheLoader : regionAttributesResult.getCacheLoaderClass();
- String cacheWriterClass =
- cacheWriter != null ? cacheWriter : regionAttributesResult.getCacheWriterClass();
-
- regionFunctionArgs = new RegionFunctionArgs(regionPath, useAttributesFrom, skipIfExists,
- keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL, regionIdle,
- regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
- enableSubscriptionConflation, cacheListenerClasses, cacheLoaderClass, cacheWriterClass,
- asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
- concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
- prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, offHeap, mcastEnabled,
- regionAttributes, partitionResolver);
-
- if (regionAttributes.getPartitionAttributes() == null
- && regionFunctionArgs.hasPartitionAttributes()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
- regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
- useAttributesFrom));
- }
- } else {
- regionFunctionArgs = new RegionFunctionArgs(regionPath, regionShortcut, useAttributesFrom,
- skipIfExists, keyConstraint, valueConstraint, statisticsEnabled, entryIdle, entryTTL,
- regionIdle, regionTTL, diskStore, diskSynchronous, enableAsyncConflation,
- enableSubscriptionConflation, cacheListener, cacheLoader, cacheWriter,
- asyncEventQueueIds, gatewaySenderIds, concurrencyChecksEnabled, cloningEnabled,
- concurrencyLevel, prColocatedWith, prLocalMaxMemory, prRecoveryDelay, prRedundantCopies,
- prStartupRecoveryDelay, prTotalMaxMemory, prTotalNumBuckets, null, compressor, offHeap,
- mcastEnabled, partitionResolver);
-
- if (!regionShortcut.name().startsWith("PARTITION")
- && regionFunctionArgs.hasPartitionAttributes()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__OPTION_0_CAN_BE_USED_ONLY_FOR_PARTITIONEDREGION,
- regionFunctionArgs.getPartitionArgs().getUserSpecifiedPartitionAttributes()) + " "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__0_IS_NOT_A_PARITIONEDREGION,
- useAttributesFrom));
- }
- }
-
- // Do we prefer to validate or authorize first?
- validateRegionFunctionArgs(cache, regionFunctionArgs);
- if (isPersistentShortcut(regionFunctionArgs.getRegionShortcut())
- || isAttributePersistent(regionFunctionArgs.getRegionAttributes())) {
- getSecurityService().authorize(ResourcePermission.Resource.CLUSTER,
- ResourcePermission.Operation.WRITE, ResourcePermission.Target.DISK);
- }
-
- Set<DistributedMember> membersToCreateRegionOn;
- if (groups != null && groups.length != 0) {
- membersToCreateRegionOn = CliUtil.getDistributedMembersByGroup(cache, groups);
- // have only normal members from the group
- membersToCreateRegionOn
- .removeIf(distributedMember -> ((InternalDistributedMember) distributedMember)
- .getVmKind() == DistributionManager.LOCATOR_DM_TYPE);
- } else {
- membersToCreateRegionOn = CliUtil.getAllNormalMembers(cache);
- }
-
- if (membersToCreateRegionOn.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.NO_CACHING_MEMBERS_FOUND_MESSAGE);
- }
-
- ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(RegionCreateFunction.INSTANCE,
- regionFunctionArgs, membersToCreateRegionOn);
- @SuppressWarnings("unchecked")
- List<CliFunctionResult> regionCreateResults =
- (List<CliFunctionResult>) resultCollector.getResult();
-
- TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
- final String errorPrefix = "ERROR: ";
- for (CliFunctionResult regionCreateResult : regionCreateResults) {
- boolean success = regionCreateResult.isSuccessful();
- tabularResultData.accumulate("Member", regionCreateResult.getMemberIdOrName());
- tabularResultData.accumulate("Status",
- (success ? "" : errorPrefix) + regionCreateResult.getMessage());
-
- if (success) {
- xmlEntity.set(regionCreateResult.getXmlEntity());
- }
- }
- result = ResultBuilder.buildResult(tabularResultData);
- verifyDistributedRegionMbean(cache, regionPath);
-
- } catch (IllegalArgumentException | IllegalStateException e) {
- LogWrapper.getInstance().info(e.getMessage());
- result = ResultBuilder.createUserErrorResult(e.getMessage());
- }
- if (xmlEntity.get() != null) {
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addXmlEntity(xmlEntity.get(), groups));
- }
-
- return result;
- }
-
- public boolean verifyDistributedRegionMbean(InternalCache cache, String regionName) {
- int federationInterval =
- cache.getInternalDistributedSystem().getConfig().getJmxManagerUpdateRate();
- long timeEnd = System.currentTimeMillis() + federationInterval + 50;
-
- for (; System.currentTimeMillis() <= timeEnd;) {
- try {
- DistributedRegionMXBean bean =
- ManagementService.getManagementService(cache).getDistributedRegionMXBean(regionName);
- if (bean == null) {
- bean = ManagementService.getManagementService(cache)
- .getDistributedRegionMXBean(Region.SEPARATOR + regionName);
- }
- if (bean != null) {
- return true;
- } else {
- Thread.sleep(2);
- }
- } catch (Exception ignored) {
- }
- }
- return false;
- }
-
- void validateRegionFunctionArgs(InternalCache cache, RegionFunctionArgs regionFunctionArgs) {
- if (regionFunctionArgs.getRegionPath() == null) {
- throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
- }
-
- DistributedSystemMXBean dsMBean = getDSMBean(cache);
-
- String useAttributesFrom = regionFunctionArgs.getUseAttributesFrom();
- if (useAttributesFrom != null && !useAttributesFrom.isEmpty()
- && regionExists(cache, useAttributesFrom)) {
- if (!regionExists(cache, useAttributesFrom)) { // check already done in createRegion !!!
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__USEATTRIBUTESFROM, useAttributesFrom}));
- }
- if (!regionFunctionArgs.isSetUseAttributesFrom()
- || regionFunctionArgs.getRegionAttributes() == null) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_VERIFY_REGION_EXISTS,
- useAttributesFrom));
- }
- }
-
- if (regionFunctionArgs.hasPartitionAttributes()) {
- RegionFunctionArgs.PartitionArgs partitionArgs = regionFunctionArgs.getPartitionArgs();
- String colocatedWith = partitionArgs.getPrColocatedWith();
- if (colocatedWith != null && !colocatedWith.isEmpty()) {
- String[] listAllRegionPaths = dsMBean.listAllRegionPaths();
- String foundRegionPath = null;
- for (String regionPath : listAllRegionPaths) {
- if (regionPath.equals(colocatedWith)) {
- foundRegionPath = regionPath;
- break;
- }
- }
- if (foundRegionPath == null) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH_FOR_0_REGIONPATH_1_NOT_FOUND,
- new Object[] {CliStrings.CREATE_REGION__COLOCATEDWITH, colocatedWith}));
- }
- ManagementService mgmtService = ManagementService.getExistingManagementService(cache);
- DistributedRegionMXBean distributedRegionMXBean =
- mgmtService.getDistributedRegionMXBean(foundRegionPath);
- String regionType = distributedRegionMXBean.getRegionType();
- if (!(DataPolicy.PARTITION.toString().equals(regionType)
- || DataPolicy.PERSISTENT_PARTITION.toString().equals(regionType))) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COLOCATEDWITH_REGION_0_IS_NOT_PARTITIONEDREGION,
- new Object[] {colocatedWith}));
- }
- }
- if (partitionArgs.isSetPRLocalMaxMemory()) {
- int prLocalMaxMemory = partitionArgs.getPrLocalMaxMemory();
- if (prLocalMaxMemory < 0) {
- throw new IllegalArgumentException(
- LocalizedStrings.AttributesFactory_PARTITIONATTRIBUTES_LOCALMAXMEMORY_MUST_NOT_BE_NEGATIVE
- .toLocalizedString());
- }
- }
- if (partitionArgs.isSetPRTotalMaxMemory()) {
- long prTotalMaxMemory = partitionArgs.getPrTotalMaxMemory();
- if (prTotalMaxMemory <= 0) {
- throw new IllegalArgumentException(
- LocalizedStrings.AttributesFactory_TOTAL_SIZE_OF_PARTITION_REGION_MUST_BE_0
- .toLocalizedString());
- }
- }
- if (partitionArgs.isSetPRRedundantCopies()) {
- int prRedundantCopies = partitionArgs.getPrRedundantCopies();
- switch (prRedundantCopies) {
- case 0:
- case 1:
- case 2:
- case 3:
- break;
- default:
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__REDUNDANT_COPIES_SHOULD_BE_ONE_OF_0123,
- new Object[] {prRedundantCopies}));
- }
- }
- }
-
- String keyConstraint = regionFunctionArgs.getKeyConstraint();
- if (keyConstraint != null && !RegionCommandsUtils.isClassNameValid(keyConstraint)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_KEYCONSTRAINT_0_IS_INVALID,
- new Object[] {keyConstraint}));
- }
-
- String valueConstraint = regionFunctionArgs.getValueConstraint();
- if (valueConstraint != null && !RegionCommandsUtils.isClassNameValid(valueConstraint)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_VALUECONSTRAINT_0_IS_INVALID,
- new Object[] {valueConstraint}));
- }
-
- Set<String> cacheListeners = regionFunctionArgs.getCacheListeners();
- if (cacheListeners != null && !cacheListeners.isEmpty()) {
- for (String cacheListener : cacheListeners) {
- if (!RegionCommandsUtils.isClassNameValid(cacheListener)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELISTENER_0_IS_INVALID,
- new Object[] {cacheListener}));
- }
- }
- }
-
- String cacheLoader = regionFunctionArgs.getCacheLoader();
- if (cacheLoader != null && !RegionCommandsUtils.isClassNameValid(cacheLoader)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHELOADER_0_IS_INVALID,
- new Object[] {cacheLoader}));
- }
-
- String cacheWriter = regionFunctionArgs.getCacheWriter();
- if (cacheWriter != null && !RegionCommandsUtils.isClassNameValid(cacheWriter)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_CLASSNAME_FOR_CACHEWRITER_0_IS_INVALID,
- new Object[] {cacheWriter}));
- }
-
- Set<String> gatewaySenderIds = regionFunctionArgs.getGatewaySenderIds();
- if (gatewaySenderIds != null && !gatewaySenderIds.isEmpty()) {
- String[] gatewaySenders = dsMBean.listGatewaySenders();
- if (gatewaySenders.length == 0) {
- throw new IllegalArgumentException(
- CliStrings.CREATE_REGION__MSG__NO_GATEWAYSENDERS_IN_THE_SYSTEM);
- } else {
- List<String> gatewaySendersList = new ArrayList<>(Arrays.asList(gatewaySenders));
- gatewaySenderIds = new HashSet<>(gatewaySenderIds);
- gatewaySenderIds.removeAll(gatewaySendersList);
- if (!gatewaySenderIds.isEmpty()) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_GATEWAYSENDER_ID_UNKNOWN_0,
- new Object[] {gatewaySenderIds}));
- }
- }
- }
-
- if (regionFunctionArgs.isSetConcurrencyLevel()) {
- int concurrencyLevel = regionFunctionArgs.getConcurrencyLevel();
- if (concurrencyLevel < 0) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_POSITIVE_INT_FOR_CONCURRENCYLEVEL_0_IS_NOT_VALID,
- new Object[] {concurrencyLevel}));
- }
- }
-
- String diskStore = regionFunctionArgs.getDiskStore();
- if (diskStore != null) {
- RegionShortcut regionShortcut = regionFunctionArgs.getRegionShortcut();
- if (regionShortcut != null && !PERSISTENT_OVERFLOW_SHORTCUTS.contains(regionShortcut)) {
- String subMessage =
- LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
- String message = subMessage + ". "
- + CliStrings.format(CliStrings.CREATE_REGION__MSG__USE_ONE_OF_THESE_SHORTCUTS_0,
- new Object[] {String.valueOf(PERSISTENT_OVERFLOW_SHORTCUTS)});
-
- throw new IllegalArgumentException(message);
- }
-
- RegionAttributes<?, ?> regionAttributes = regionFunctionArgs.getRegionAttributes();
- if (regionAttributes != null && !regionAttributes.getDataPolicy().withPersistence()) {
- String subMessage =
- LocalizedStrings.DiskStore_IS_USED_IN_NONPERSISTENT_REGION.toLocalizedString();
- String message = subMessage + ". "
- + CliStrings.format(
- CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FROM_REGION_0_IS_NOT_WITH_PERSISTENCE,
- new Object[] {String.valueOf(regionFunctionArgs.getUseAttributesFrom())});
-
- throw new IllegalArgumentException(message);
- }
-
- if (!diskStoreExists(cache, diskStore)) {
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_DISKSTORE_UNKNOWN_DISKSTORE_0,
- new Object[] {diskStore}));
- }
- }
-
- RegionFunctionArgs.ExpirationAttrs entryExpirationIdleTime =
- regionFunctionArgs.getEntryExpirationIdleTime();
- RegionFunctionArgs.ExpirationAttrs entryExpirationTTL =
- regionFunctionArgs.getEntryExpirationTTL();
- RegionFunctionArgs.ExpirationAttrs regionExpirationIdleTime =
- regionFunctionArgs.getRegionExpirationIdleTime();
- RegionFunctionArgs.ExpirationAttrs regionExpirationTTL =
- regionFunctionArgs.getRegionExpirationTTL();
-
- if ((!regionFunctionArgs.isSetStatisticsEnabled() || !regionFunctionArgs.isStatisticsEnabled())
- && (entryExpirationIdleTime != null || entryExpirationTTL != null
- || regionExpirationIdleTime != null || regionExpirationTTL != null)) {
- String message = LocalizedStrings.AttributesFactory_STATISTICS_MUST_BE_ENABLED_FOR_EXPIRATION
- .toLocalizedString();
- throw new IllegalArgumentException(message + ".");
- }
-
- boolean compressorFailure = false;
- if (regionFunctionArgs.isSetCompressor()) {
- String compressorClassName = regionFunctionArgs.getCompressor();
- Object compressor = null;
- try {
- Class<?> compressorClass = ClassPathLoader.getLatest().forName(compressorClassName);
- compressor = compressorClass.newInstance();
- } catch (InstantiationException | ClassNotFoundException | IllegalAccessException e) {
- compressorFailure = true;
- }
-
- if (compressorFailure || !(compressor instanceof Compressor)) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_COMPRESSOR,
- new Object[] {regionFunctionArgs.getCompressor()}));
- }
- }
-
- if (regionFunctionArgs.hasPartitionAttributes()) {
- if (regionFunctionArgs.isPartitionResolverSet()) {
- String partitionResolverClassName = regionFunctionArgs.getPartitionResolver();
- try {
- Class<PartitionResolver> resolverClass = (Class<PartitionResolver>) ClassPathLoader
- .getLatest().forName(partitionResolverClassName);
- PartitionResolver partitionResolver = resolverClass.newInstance();
- } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__INVALID_PARTITION_RESOLVER,
- new Object[] {regionFunctionArgs.getPartitionResolver()}),
- e);
- }
- }
- }
- }
-
- private boolean diskStoreExists(InternalCache cache, String diskStoreName) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
- Map<String, String[]> diskstore = dsMXBean.listMemberDiskstore();
-
- Set<Map.Entry<String, String[]>> entrySet = diskstore.entrySet();
-
- for (Map.Entry<String, String[]> entry : entrySet) {
- String[] value = entry.getValue();
- if (CliUtil.contains(value, diskStoreName)) {
- return true;
- }
- }
-
- return false;
- }
-
- private void validateRegionPathAndParent(InternalCache cache, String regionPath) {
- if (StringUtils.isEmpty(regionPath)) {
- throw new IllegalArgumentException(CliStrings.CREATE_REGION__MSG__SPECIFY_VALID_REGION_PATH);
- }
- // If a region path indicates a sub-region, check whether the parent region exists
- RegionPath regionPathData = new RegionPath(regionPath);
- String parentRegionPath = regionPathData.getParent();
- if (parentRegionPath != null && !Region.SEPARATOR.equals(parentRegionPath)) {
- if (!regionExists(cache, parentRegionPath)) {
- throw new IllegalArgumentException(
- CliStrings.format(CliStrings.CREATE_REGION__MSG__PARENT_REGION_FOR_0_DOES_NOT_EXIST,
- new Object[] {regionPath}));
- }
- }
- }
-
- private static <K, V> FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> getRegionAttributes(
- InternalCache cache, String regionPath) {
- if (!isClusterWideSameConfig(cache, regionPath)) {
- throw new IllegalStateException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__USE_ATTRIBUTES_FORM_REGIONS_EXISTS_BUT_DIFFERENT_SCOPE_OR_DATAPOLICY_USE_DESCRIBE_REGION_FOR_0,
- regionPath));
- }
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> attributes = null;
-
- // First check whether the region exists on a this manager, if yes then no
- // need to use FetchRegionAttributesFunction to fetch RegionAttributes
- try {
- attributes = FetchRegionAttributesFunction.getRegionAttributes(regionPath);
- } catch (IllegalArgumentException e) {
- /* region doesn't exist on the manager */
- }
-
- if (attributes == null) {
- // find first member which has the region
- Set<DistributedMember> regionAssociatedMembers =
- CliUtil.getRegionAssociatedMembers(regionPath, cache, false);
- if (regionAssociatedMembers != null && !regionAssociatedMembers.isEmpty()) {
- DistributedMember distributedMember = regionAssociatedMembers.iterator().next();
- ResultCollector<?, ?> resultCollector = CliUtil
- .executeFunction(FetchRegionAttributesFunction.INSTANCE, regionPath, distributedMember);
- List<?> resultsList = (List<?>) resultCollector.getResult();
-
- if (resultsList != null && !resultsList.isEmpty()) {
- for (Object object : resultsList) {
- if (object instanceof IllegalArgumentException) {
- throw (IllegalArgumentException) object;
- } else if (object instanceof Throwable) {
- Throwable th = (Throwable) object;
- LogWrapper.getInstance().info(CliUtil.stackTraceAsString((th)));
- throw new IllegalArgumentException(CliStrings.format(
- CliStrings.CREATE_REGION__MSG__COULD_NOT_RETRIEVE_REGION_ATTRS_FOR_PATH_0_REASON_1,
- new Object[] {regionPath, th.getMessage()}));
- } else { // has to be RegionAttributes
- @SuppressWarnings("unchecked") // to avoid warning :(
- FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V> regAttr =
- ((FetchRegionAttributesFunction.FetchRegionAttributesFunctionResult<K, V>) object);
- if (attributes == null) {
- attributes = regAttr;
- break;
- } // attributes null check
- } // not IllegalArgumentException or other throwable
- } // iterate over list - there should be only one result in the list
- } // result list is not null or empty
- } // regionAssociatedMembers is not-empty
- } // attributes are null because do not exist on local member
-
- return attributes;
- }
-
- private static boolean isClusterWideSameConfig(InternalCache cache, String regionPath) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
-
- DistributedSystemMXBean dsMXBean = managementService.getDistributedSystemMXBean();
-
- Set<DistributedMember> allMembers = CliUtil.getAllNormalMembers(cache);
-
- RegionAttributesData regionAttributesToValidateAgainst = null;
- for (DistributedMember distributedMember : allMembers) {
- ObjectName regionObjectName;
- try {
- regionObjectName = dsMXBean
- .fetchRegionObjectName(CliUtil.getMemberNameOrId(distributedMember), regionPath);
- RegionMXBean regionMBean =
- managementService.getMBeanInstance(regionObjectName, RegionMXBean.class);
- RegionAttributesData regionAttributes = regionMBean.listRegionAttributes();
-
- if (regionAttributesToValidateAgainst == null) {
- regionAttributesToValidateAgainst = regionAttributes;
- } else if (!(regionAttributesToValidateAgainst.getScope()
- .equals(regionAttributes.getScope())
- || regionAttributesToValidateAgainst.getDataPolicy()
- .equals(regionAttributes.getDataPolicy()))) {
- return false;
- }
- } catch (Exception e) {
- // ignore
- }
- }
-
- return true;
- }
-
- private boolean isPersistentShortcut(RegionShortcut shortcut) {
- return shortcut == RegionShortcut.LOCAL_PERSISTENT
- || shortcut == RegionShortcut.LOCAL_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.PARTITION_PERSISTENT
- || shortcut == RegionShortcut.PARTITION_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT
- || shortcut == RegionShortcut.PARTITION_REDUNDANT_PERSISTENT_OVERFLOW
- || shortcut == RegionShortcut.REPLICATE_PERSISTENT
- || shortcut == RegionShortcut.REPLICATE_PERSISTENT_OVERFLOW;
- }
-
- private boolean isAttributePersistent(RegionAttributes attributes) {
- return attributes != null && attributes.getDataPolicy() != null
- && attributes.getDataPolicy().toString().contains("PERSISTENT");
- }
-
- public static boolean regionExists(InternalCache cache, String regionPath) {
- if (regionPath == null || Region.SEPARATOR.equals(regionPath)) {
- return false;
- }
-
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- DistributedSystemMXBean dsMBean = managementService.getDistributedSystemMXBean();
-
- String[] allRegionPaths = dsMBean.listAllRegionPaths();
- return Arrays.stream(allRegionPaths).anyMatch(regionPath::equals);
- }
-
- public DistributedSystemMXBean getDSMBean(InternalCache cache) {
- ManagementService managementService = ManagementService.getExistingManagementService(cache);
- return managementService.getDistributedSystemMXBean();
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
deleted file mode 100644
index 1102cd8..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DefineIndexCommand.java
+++ /dev/null
@@ -1,95 +0,0 @@
-/*
- * 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.geode.management.internal.cli.commands;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.Region;
-import org.apache.geode.internal.lang.StringUtils;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.domain.IndexInfo;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.InfoResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DefineIndexCommand implements GfshCommand {
- @CliCommand(value = CliStrings.DEFINE_INDEX, help = CliStrings.DEFINE_INDEX__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA})
- // TODO : Add optionContext for indexName
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.QUERY)
- public Result defineIndex(
- @CliOption(key = CliStrings.DEFINE_INDEX_NAME, mandatory = true,
- help = CliStrings.DEFINE_INDEX__HELP) final String indexName,
- @CliOption(key = CliStrings.DEFINE_INDEX__EXPRESSION, mandatory = true,
- help = CliStrings.DEFINE_INDEX__EXPRESSION__HELP) final String indexedExpression,
- @CliOption(key = CliStrings.DEFINE_INDEX__REGION, mandatory = true,
- optionContext = ConverterHint.REGION_PATH,
- help = CliStrings.DEFINE_INDEX__REGION__HELP) String regionPath,
- @CliOption(key = CliStrings.DEFINE_INDEX__TYPE, unspecifiedDefaultValue = "range",
- optionContext = ConverterHint.INDEX_TYPE,
- help = CliStrings.DEFINE_INDEX__TYPE__HELP) final String indexType) {
-
- Result result;
- int idxType;
-
- // Index type check
- if ("range".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.RANGE_INDEX;
- } else if ("hash".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.HASH_INDEX;
- } else if ("key".equalsIgnoreCase(indexType)) {
- idxType = IndexInfo.KEY_INDEX;
- } else {
- return ResultBuilder
- .createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__TYPE__MESSAGE);
- }
-
- if (indexName == null || indexName.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__INDEX__NAME);
- }
-
- if (indexedExpression == null || indexedExpression.isEmpty()) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__EXPRESSION);
- }
-
- if (StringUtils.isBlank(regionPath) || regionPath.equals(Region.SEPARATOR)) {
- return ResultBuilder.createUserErrorResult(CliStrings.DEFINE_INDEX__INVALID__REGIONPATH);
- }
-
- if (!regionPath.startsWith(Region.SEPARATOR)) {
- regionPath = Region.SEPARATOR + regionPath;
- }
-
- IndexInfo indexInfo = new IndexInfo(indexName, indexedExpression, regionPath, idxType);
- IndexDefinition.indexDefinitions.add(indexInfo);
-
- final InfoResultData infoResult = ResultBuilder.createInfoResultData();
- infoResult.addLine(CliStrings.DEFINE_INDEX__SUCCESS__MSG);
- infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__NAME__MSG, indexName));
- infoResult
- .addLine(CliStrings.format(CliStrings.DEFINE_INDEX__EXPRESSION__MSG, indexedExpression));
- infoResult.addLine(CliStrings.format(CliStrings.DEFINE_INDEX__REGIONPATH__MSG, regionPath));
- result = ResultBuilder.buildResult(infoResult);
-
- return result;
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
deleted file mode 100644
index 4f46539..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommand.java
+++ /dev/null
@@ -1,190 +0,0 @@
-/*
- * 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.geode.management.internal.cli.commands;
-
-import static org.apache.commons.io.FileUtils.ONE_MB;
-
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.text.DecimalFormat;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import org.apache.commons.lang.ArrayUtils;
-import org.apache.commons.lang.StringUtils;
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.SystemFailure;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.internal.security.SecurityService;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.GfshParseResult;
-import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
-import org.apache.geode.management.internal.cli.functions.DeployFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
-import org.apache.geode.management.internal.cli.result.FileResult;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.NotAuthorizedException;
-import org.apache.geode.security.ResourcePermission;
-
-public class DeployCommand implements GfshCommand {
- private final DeployFunction deployFunction = new DeployFunction();
-
- /**
- * Deploy one or more JAR files to members of a group or all members.
- *
- * @param groups Group(s) to deploy the JAR to or null for all members
- * @param jars JAR file to deploy
- * @param dir Directory of JAR files to deploy
- * @return The result of the attempt to deploy
- */
- @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
- @CliMetaData(
- interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommand$Interceptor",
- relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.MANAGE, target = ResourcePermission.Target.JAR)
- public Result deploy(
- @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
- optionContext = ConverterHint.MEMBERGROUP) String[] groups,
- @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
- help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
- @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
- try {
-
- // since deploy function can potentially do a lot of damage to security, this action should
- // require these following privileges
- SecurityService securityService = getSecurityService();
-
- TabularResultData tabularData = ResultBuilder.createTabularResultData();
-
- byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
- String[] jarNames = CliUtil.bytesToNames(shellBytesData);
- byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
-
- Set<DistributedMember> targetMembers;
-
- targetMembers = CliUtil.findMembers(groups, null);
-
- if (targetMembers.size() > 0) {
- // this deploys the jars to all the matching servers
- ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
- new Object[] {jarNames, jarBytes}, targetMembers);
-
- List<CliFunctionResult> results =
- CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
-
- for (CliFunctionResult result : results) {
- if (result.getThrowable() != null) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Deployed JAR", "");
- tabularData.accumulate("Deployed JAR Location",
- "ERROR: " + result.getThrowable().getClass().getName() + ": "
- + result.getThrowable().getMessage());
- tabularData.setStatus(Result.Status.ERROR);
- } else {
- String[] strings = (String[]) result.getSerializables();
- for (int i = 0; i < strings.length; i += 2) {
- tabularData.accumulate("Member", result.getMemberIdOrName());
- tabularData.accumulate("Deployed JAR", strings[i]);
- tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
- }
- }
- }
- }
-
- Result result = ResultBuilder.buildResult(tabularData);
- persistClusterConfiguration(result,
- () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
- return result;
- } catch (NotAuthorizedException e) {
- // for NotAuthorizedException, will catch this later in the code
- throw e;
- } catch (VirtualMachineError e) {
- SystemFailure.initiateFailure(e);
- throw e;
- } catch (Throwable t) {
- SystemFailure.checkFailure();
- return ResultBuilder.createGemFireErrorResult(String
- .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
- }
- }
-
- /**
- * Interceptor used by gfsh to intercept execution of deploy command at "shell".
- */
- public static class Interceptor extends AbstractCliAroundInterceptor {
- private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
-
- @Override
- public Result preExecution(GfshParseResult parseResult) {
- // 2nd argument is the jar
- String[] jars = (String[]) parseResult.getArguments()[1];
- // 3rd argument is the dir
- String dir = (String) parseResult.getArguments()[2];
-
- if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
- return ResultBuilder.createUserErrorResult(
- "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
- }
-
- if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
- return ResultBuilder
- .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
- }
-
- FileResult fileResult;
- String[] filesToUpload = jars;
- if (filesToUpload == null) {
- filesToUpload = new String[] {dir};
- }
- try {
-
- fileResult = new FileResult(filesToUpload);
- } catch (FileNotFoundException fnfex) {
- return ResultBuilder
- .createGemFireErrorResult("'" + Arrays.toString(filesToUpload) + "' not found.");
- } catch (IOException ioex) {
- return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
- + ioex.getClass().getName() + ": " + ioex.getMessage());
- }
-
- // Only do this additional check if a dir was provided
- if (dir != null) {
- String message =
- "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
- + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
- + "MB\n\nContinue? ";
-
- if (readYesNo(message, Response.YES) == Response.NO) {
- return ResultBuilder.createShellClientAbortOperationResult(
- "Aborted deploy of " + Arrays.toString(filesToUpload) + ".");
- }
- }
- return fileResult;
- }
- }
-}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
new file mode 100644
index 0000000..e502154
--- /dev/null
+++ b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DeployCommands.java
@@ -0,0 +1,336 @@
+/*
+ * 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.geode.management.internal.cli.commands;
+
+import static org.apache.commons.io.FileUtils.ONE_MB;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.text.DecimalFormat;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.lang.ArrayUtils;
+import org.apache.commons.lang.StringUtils;
+import org.springframework.shell.core.annotation.CliCommand;
+import org.springframework.shell.core.annotation.CliOption;
+
+import org.apache.geode.SystemFailure;
+import org.apache.geode.cache.execute.ResultCollector;
+import org.apache.geode.distributed.DistributedMember;
+import org.apache.geode.internal.security.SecurityService;
+import org.apache.geode.management.cli.CliMetaData;
+import org.apache.geode.management.cli.ConverterHint;
+import org.apache.geode.management.cli.Result;
+import org.apache.geode.management.cli.Result.Status;
+import org.apache.geode.management.internal.cli.AbstractCliAroundInterceptor;
+import org.apache.geode.management.internal.cli.CliUtil;
+import org.apache.geode.management.internal.cli.GfshParseResult;
+import org.apache.geode.management.internal.cli.functions.CliFunctionResult;
+import org.apache.geode.management.internal.cli.functions.DeployFunction;
+import org.apache.geode.management.internal.cli.functions.ListDeployedFunction;
+import org.apache.geode.management.internal.cli.functions.UndeployFunction;
+import org.apache.geode.management.internal.cli.i18n.CliStrings;
+import org.apache.geode.management.internal.cli.remote.CommandExecutionContext;
+import org.apache.geode.management.internal.cli.result.FileResult;
+import org.apache.geode.management.internal.cli.result.ResultBuilder;
+import org.apache.geode.management.internal.cli.result.TabularResultData;
+import org.apache.geode.management.internal.security.ResourceOperation;
+import org.apache.geode.security.NotAuthorizedException;
+import org.apache.geode.security.ResourcePermission.Operation;
+import org.apache.geode.security.ResourcePermission.Resource;
+import org.apache.geode.security.ResourcePermission.Target;
+
+
+
+/**
+ * Commands for deploying, un-deploying and listing files deployed using the command line shell.
+ *
+ * @see GfshCommand
+ * @since GemFire 7.0
+ */
+public class DeployCommands implements GfshCommand {
+
+ private final DeployFunction deployFunction = new DeployFunction();
+ private final UndeployFunction undeployFunction = new UndeployFunction();
+ private final ListDeployedFunction listDeployedFunction = new ListDeployedFunction();
+
+ /**
+ * Deploy one or more JAR files to members of a group or all members.
+ *
+ * @param groups Group(s) to deploy the JAR to or null for all members
+ * @param jars JAR file to deploy
+ * @param dir Directory of JAR files to deploy
+ * @return The result of the attempt to deploy
+ */
+ @CliCommand(value = {CliStrings.DEPLOY}, help = CliStrings.DEPLOY__HELP)
+ @CliMetaData(
+ interceptor = "org.apache.geode.management.internal.cli.commands.DeployCommands$Interceptor",
+ relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ public Result deploy(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS}, help = CliStrings.DEPLOY__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+ @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+ help = CliStrings.DEPLOY__JAR__HELP) String[] jars,
+ @CliOption(key = {CliStrings.DEPLOY__DIR}, help = CliStrings.DEPLOY__DIR__HELP) String dir) {
+ try {
+
+ // since deploy function can potentially do a lot of damage to security, this action should
+ // require these following privileges
+ SecurityService securityService = getSecurityService();
+
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+
+ byte[][] shellBytesData = CommandExecutionContext.getBytesFromShell();
+ String[] jarNames = CliUtil.bytesToNames(shellBytesData);
+ byte[][] jarBytes = CliUtil.bytesToData(shellBytesData);
+
+ Set<DistributedMember> targetMembers;
+
+ targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.size() > 0) {
+ // this deploys the jars to all the matching servers
+ ResultCollector<?, ?> resultCollector = CliUtil.executeFunction(this.deployFunction,
+ new Object[] {jarNames, jarBytes}, targetMembers);
+
+ List<CliFunctionResult> results =
+ CliFunctionResult.cleanResults((List<?>) resultCollector.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Deployed JAR", "");
+ tabularData.accumulate("Deployed JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Deployed JAR", strings[i]);
+ tabularData.accumulate("Deployed JAR Location", strings[i + 1]);
+ }
+ }
+ }
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().addJarsToThisLocator(jarNames, jarBytes, groups));
+ return result;
+ } catch (NotAuthorizedException e) {
+ // for NotAuthorizedException, will catch this later in the code
+ throw e;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable t) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult(String
+ .format("Exception while attempting to deploy: (%1$s)", toString(t, isDebugging())));
+ }
+ }
+
+ /**
+ * Undeploy one or more JAR files from members of a group or all members.
+ *
+ * @param groups Group(s) to undeploy the JAR from or null for all members
+ * @param jars JAR(s) to undeploy (separated by comma)
+ * @return The result of the attempt to undeploy
+ */
+ @CliCommand(value = {CliStrings.UNDEPLOY}, help = CliStrings.UNDEPLOY__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.MANAGE, target = Target.JAR)
+ public Result undeploy(
+ @CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.UNDEPLOY__GROUP__HELP,
+ optionContext = ConverterHint.MEMBERGROUP) String[] groups,
+ @CliOption(key = {CliStrings.JAR, CliStrings.JARS},
+ help = CliStrings.UNDEPLOY__JAR__HELP) String[] jars) {
+
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(groups, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.undeployFunction, new Object[] {jars}, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Un-Deployed JAR", "");
+ tabularData.accumulate("Un-Deployed JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("Un-Deployed JAR", strings[i]);
+ tabularData.accumulate("Un-Deployed From JAR Location", strings[i + 1]);
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult(CliStrings.UNDEPLOY__NO_JARS_FOUND_MESSAGE);
+ }
+
+ Result result = ResultBuilder.buildResult(tabularData);
+ if (tabularData.getStatus().equals(Status.OK)) {
+ persistClusterConfiguration(result,
+ () -> getSharedConfiguration().removeJars(jars, groups));
+ }
+ return result;
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult("Exception while attempting to un-deploy: "
+ + th.getClass().getName() + ": " + th.getMessage());
+ }
+ }
+
+ /**
+ * List all currently deployed JARs for members of a group or for all members.
+ *
+ * @param group Group for which to list JARs or null for all members
+ * @return List of deployed JAR files
+ */
+ @CliCommand(value = {CliStrings.LIST_DEPLOYED}, help = CliStrings.LIST_DEPLOYED__HELP)
+ @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
+ @ResourceOperation(resource = Resource.CLUSTER, operation = Operation.READ)
+ public Result listDeployed(@CliOption(key = {CliStrings.GROUP, CliStrings.GROUPS},
+ help = CliStrings.LIST_DEPLOYED__GROUP__HELP) String[] group) {
+
+ try {
+ TabularResultData tabularData = ResultBuilder.createTabularResultData();
+ boolean accumulatedData = false;
+
+ Set<DistributedMember> targetMembers = CliUtil.findMembers(group, null);
+
+ if (targetMembers.isEmpty()) {
+ return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
+ }
+
+ ResultCollector<?, ?> rc =
+ CliUtil.executeFunction(this.listDeployedFunction, null, targetMembers);
+ List<CliFunctionResult> results = CliFunctionResult.cleanResults((List<?>) rc.getResult());
+
+ for (CliFunctionResult result : results) {
+ if (result.getThrowable() != null) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("JAR", "");
+ tabularData.accumulate("JAR Location",
+ "ERROR: " + result.getThrowable().getClass().getName() + ": "
+ + result.getThrowable().getMessage());
+ accumulatedData = true;
+ tabularData.setStatus(Status.ERROR);
+ } else {
+ String[] strings = (String[]) result.getSerializables();
+ for (int i = 0; i < strings.length; i += 2) {
+ tabularData.accumulate("Member", result.getMemberIdOrName());
+ tabularData.accumulate("JAR", strings[i]);
+ tabularData.accumulate("JAR Location", strings[i + 1]);
+ accumulatedData = true;
+ }
+ }
+ }
+
+ if (!accumulatedData) {
+ return ResultBuilder.createInfoResult(CliStrings.LIST_DEPLOYED__NO_JARS_FOUND_MESSAGE);
+ }
+ return ResultBuilder.buildResult(tabularData);
+
+ } catch (VirtualMachineError e) {
+ SystemFailure.initiateFailure(e);
+ throw e;
+ } catch (Throwable th) {
+ SystemFailure.checkFailure();
+ return ResultBuilder.createGemFireErrorResult("Exception while attempting to list deployed: "
+ + th.getClass().getName() + ": " + th.getMessage());
+ }
+ }
+
+ /**
+ * Interceptor used by gfsh to intercept execution of deploy command at "shell".
+ */
+ public static class Interceptor extends AbstractCliAroundInterceptor {
+ private final DecimalFormat numFormatter = new DecimalFormat("###,##0.00");
+
+ @Override
+ public Result preExecution(GfshParseResult parseResult) {
+ // 2nd argument is the jar
+ String[] jars = (String[]) parseResult.getArguments()[1];
+ // 3rd argument is the dir
+ String dir = (String) parseResult.getArguments()[2];
+
+ if (ArrayUtils.isEmpty(jars) && StringUtils.isBlank(dir)) {
+ return ResultBuilder.createUserErrorResult(
+ "Parameter \"jar\" or \"dir\" is required. Use \"help <command name>\" for assistance.");
+ }
+
+ if (ArrayUtils.isNotEmpty(jars) && StringUtils.isNotBlank(dir)) {
+ return ResultBuilder
+ .createUserErrorResult("Parameters \"jar\" and \"dir\" can not both be specified.");
+ }
+
+ FileResult fileResult;
+ String[] filesToUpload = jars;
+ if (filesToUpload == null) {
+ filesToUpload = new String[] {dir};
+ }
+ try {
+
+ fileResult = new FileResult(filesToUpload);
+ } catch (FileNotFoundException fnfex) {
+ return ResultBuilder.createGemFireErrorResult("'" + filesToUpload + "' not found.");
+ } catch (IOException ioex) {
+ return ResultBuilder.createGemFireErrorResult("I/O error when reading jar/dir: "
+ + ioex.getClass().getName() + ": " + ioex.getMessage());
+ }
+
+ // Only do this additional check if a dir was provided
+ if (dir != null) {
+ String message =
+ "\nDeploying files: " + fileResult.getFormattedFileList() + "\nTotal file size is: "
+ + this.numFormatter.format((double) fileResult.computeFileSizeTotal() / ONE_MB)
+ + "MB\n\nContinue? ";
+
+ if (readYesNo(message, Response.YES) == Response.NO) {
+ return ResultBuilder
+ .createShellClientAbortOperationResult("Aborted deploy of " + filesToUpload + ".");
+ }
+ }
+
+ return fileResult;
+ }
+ }
+}
http://git-wip-us.apache.org/repos/asf/geode/blob/645a32d0/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
----------------------------------------------------------------------
diff --git a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java b/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
deleted file mode 100644
index 824063a..0000000
--- a/geode-core/src/main/java/org/apache/geode/management/internal/cli/commands/DescribeConfigCommand.java
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * 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.geode.management.internal.cli.commands;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeSet;
-
-import org.springframework.shell.core.annotation.CliCommand;
-import org.springframework.shell.core.annotation.CliOption;
-
-import org.apache.geode.cache.execute.FunctionInvocationTargetException;
-import org.apache.geode.cache.execute.ResultCollector;
-import org.apache.geode.distributed.DistributedMember;
-import org.apache.geode.management.cli.CliMetaData;
-import org.apache.geode.management.cli.ConverterHint;
-import org.apache.geode.management.cli.Result;
-import org.apache.geode.management.internal.cli.CliUtil;
-import org.apache.geode.management.internal.cli.domain.MemberConfigurationInfo;
-import org.apache.geode.management.internal.cli.functions.GetMemberConfigInformationFunction;
-import org.apache.geode.management.internal.cli.i18n.CliStrings;
-import org.apache.geode.management.internal.cli.result.CompositeResultData;
-import org.apache.geode.management.internal.cli.result.ErrorResultData;
-import org.apache.geode.management.internal.cli.result.ResultBuilder;
-import org.apache.geode.management.internal.cli.result.TabularResultData;
-import org.apache.geode.management.internal.security.ResourceOperation;
-import org.apache.geode.security.ResourcePermission;
-
-public class DescribeConfigCommand implements GfshCommand {
- private final GetMemberConfigInformationFunction getMemberConfigFunction =
- new GetMemberConfigInformationFunction();
-
- @CliCommand(value = {CliStrings.DESCRIBE_CONFIG}, help = CliStrings.DESCRIBE_CONFIG__HELP)
- @CliMetaData(relatedTopic = {CliStrings.TOPIC_GEODE_CONFIG})
- @ResourceOperation(resource = ResourcePermission.Resource.CLUSTER,
- operation = ResourcePermission.Operation.READ)
- public Result describeConfig(
- @CliOption(key = CliStrings.MEMBER, optionContext = ConverterHint.ALL_MEMBER_IDNAME,
- help = CliStrings.DESCRIBE_CONFIG__MEMBER__HELP, mandatory = true) String memberNameOrId,
- @CliOption(key = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS,
- help = CliStrings.DESCRIBE_CONFIG__HIDE__DEFAULTS__HELP, unspecifiedDefaultValue = "true",
- specifiedDefaultValue = "true") boolean hideDefaults) {
-
- Result result = null;
- try {
- DistributedMember targetMember = null;
-
- if (memberNameOrId != null && !memberNameOrId.isEmpty()) {
- targetMember = CliUtil.getDistributedMemberByNameOrId(memberNameOrId);
- }
- if (targetMember != null) {
- ResultCollector<?, ?> rc =
- CliUtil.executeFunction(getMemberConfigFunction, hideDefaults, targetMember);
- ArrayList<?> output = (ArrayList<?>) rc.getResult();
- Object obj = output.get(0);
-
- if (obj != null && obj instanceof MemberConfigurationInfo) {
- MemberConfigurationInfo memberConfigInfo = (MemberConfigurationInfo) obj;
-
- CompositeResultData crd = ResultBuilder.createCompositeResultData();
- crd.setHeader(
- CliStrings.format(CliStrings.DESCRIBE_CONFIG__HEADER__TEXT, memberNameOrId));
-
- List<String> jvmArgsList = memberConfigInfo.getJvmInputArguments();
- TabularResultData jvmInputArgs = crd.addSection().addSection().addTable();
-
- for (String jvmArg : jvmArgsList) {
- jvmInputArgs.accumulate("JVM command line arguments", jvmArg);
- }
-
- addSection(crd, memberConfigInfo.getGfePropsSetUsingApi(),
- "GemFire properties defined using the API");
- addSection(crd, memberConfigInfo.getGfePropsRuntime(),
- "GemFire properties defined at the runtime");
- addSection(crd, memberConfigInfo.getGfePropsSetFromFile(),
- "GemFire properties defined with the property file");
- addSection(crd, memberConfigInfo.getGfePropsSetWithDefaults(),
- "GemFire properties using default values");
- addSection(crd, memberConfigInfo.getCacheAttributes(), "Cache attributes");
-
- List<Map<String, String>> cacheServerAttributesList =
- memberConfigInfo.getCacheServerAttributes();
-
- if (cacheServerAttributesList != null && !cacheServerAttributesList.isEmpty()) {
- CompositeResultData.SectionResultData cacheServerSection = crd.addSection();
- cacheServerSection.setHeader("Cache-server attributes");
-
- for (Map<String, String> cacheServerAttributes : cacheServerAttributesList) {
- addSubSection(cacheServerSection, cacheServerAttributes);
- }
- }
- result = ResultBuilder.buildResult(crd);
- }
-
- } else {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(CliStrings.format(CliStrings.DESCRIBE_CONFIG__MEMBER__NOT__FOUND,
- new Object[] {memberNameOrId}));
- result = ResultBuilder.buildResult(erd);
- }
- } catch (FunctionInvocationTargetException e) {
- result = ResultBuilder.createGemFireErrorResult(CliStrings
- .format(CliStrings.COULD_NOT_EXECUTE_COMMAND_TRY_AGAIN, CliStrings.DESCRIBE_CONFIG));
- } catch (Exception e) {
- ErrorResultData erd = ResultBuilder.createErrorResultData();
- erd.addLine(e.getMessage());
- result = ResultBuilder.buildResult(erd);
- }
- return result;
- }
-
- private void addSection(CompositeResultData crd, Map<String, String> attrMap, String headerText) {
- if (attrMap != null && !attrMap.isEmpty()) {
- CompositeResultData.SectionResultData section = crd.addSection();
- section.setHeader(headerText);
- section.addSeparator('.');
- Set<String> attributes = new TreeSet<>(attrMap.keySet());
-
- for (String attribute : attributes) {
- String attributeValue = attrMap.get(attribute);
- section.addData(attribute, attributeValue);
- }
- }
- }
-
- private void addSubSection(CompositeResultData.SectionResultData section,
- Map<String, String> attrMap) {
- if (!attrMap.isEmpty()) {
- CompositeResultData.SectionResultData subSection = section.addSection();
- Set<String> attributes = new TreeSet<>(attrMap.keySet());
- subSection.setHeader("");
-
- for (String attribute : attributes) {
- String attributeValue = attrMap.get(attribute);
- subSection.addData(attribute, attributeValue);
- }
- }
- }
-}