use of org.apache.geode.management.internal.cli.result.ErrorResultData in project geode by apache.
the class ShellCommands method describeConnection.
@CliCommand(value = { CliStrings.DESCRIBE_CONNECTION }, help = CliStrings.DESCRIBE_CONNECTION__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH, CliStrings.TOPIC_GEODE_JMX })
public Result describeConnection() {
Result result = null;
try {
TabularResultData tabularResultData = ResultBuilder.createTabularResultData();
Gfsh gfshInstance = getGfsh();
if (gfshInstance.isConnectedAndReady()) {
OperationInvoker operationInvoker = gfshInstance.getOperationInvoker();
// tabularResultData.accumulate("Monitored GemFire DS", operationInvoker.toString());
tabularResultData.accumulate("Connection Endpoints", operationInvoker.toString());
} else {
tabularResultData.accumulate("Connection Endpoints", "Not connected");
}
result = ResultBuilder.buildResult(tabularResultData);
} catch (Exception e) {
ErrorResultData errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(e.getMessage());
result = ResultBuilder.buildResult(errorResultData);
}
return result;
}
use of org.apache.geode.management.internal.cli.result.ErrorResultData in project geode by apache.
the class ShellCommands method history.
@CliCommand(value = CliStrings.HISTORY, help = CliStrings.HISTORY__HELP)
@CliMetaData(shellOnly = true, relatedTopic = { CliStrings.TOPIC_GFSH })
public Result history(@CliOption(key = { CliStrings.HISTORY__FILE }, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.HISTORY__FILE__HELP) String saveHistoryTo, @CliOption(key = { CliStrings.HISTORY__CLEAR }, specifiedDefaultValue = "true", unspecifiedDefaultValue = "false", help = CliStrings.HISTORY__CLEAR__HELP) Boolean clearHistory) {
// process clear history
if (clearHistory) {
return executeClearHistory();
} else {
// Process file option
Gfsh gfsh = Gfsh.getCurrentInstance();
ErrorResultData errorResultData = null;
StringBuilder contents = new StringBuilder();
Writer output = null;
int historySize = gfsh.getHistorySize();
String historySizeString = String.valueOf(historySize);
int historySizeWordLength = historySizeString.length();
GfshHistory gfshHistory = gfsh.getGfshHistory();
Iterator<?> it = gfshHistory.entries();
boolean flagForLineNumbers = !(saveHistoryTo != null && saveHistoryTo.length() > 0);
long lineNumber = 0;
while (it.hasNext()) {
String line = it.next().toString();
if (line.isEmpty() == false) {
if (flagForLineNumbers) {
lineNumber++;
contents.append(String.format("%" + historySizeWordLength + "s ", lineNumber));
}
contents.append(line);
contents.append(GfshParser.LINE_SEPARATOR);
}
}
try {
// write to a user file
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
File saveHistoryToFile = new File(saveHistoryTo);
output = new BufferedWriter(new FileWriter(saveHistoryToFile));
if (!saveHistoryToFile.exists()) {
errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.HISTORY__MSG__FILE_DOES_NOT_EXISTS);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.isFile()) {
errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.HISTORY__MSG__FILE_SHOULD_NOT_BE_DIRECTORY);
return ResultBuilder.buildResult(errorResultData);
}
if (!saveHistoryToFile.canWrite()) {
errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine(CliStrings.HISTORY__MSG__FILE_CANNOT_BE_WRITTEN);
return ResultBuilder.buildResult(errorResultData);
}
output.write(contents.toString());
}
} catch (IOException ex) {
return ResultBuilder.createInfoResult("File error " + ex.getMessage() + " for file " + saveHistoryTo);
} finally {
try {
if (output != null) {
output.close();
}
} catch (IOException e) {
errorResultData = ResultBuilder.createErrorResultData().setErrorCode(ResultBuilder.ERRORCODE_DEFAULT).addLine("exception in closing file");
return ResultBuilder.buildResult(errorResultData);
}
}
if (saveHistoryTo != null && saveHistoryTo.length() > 0) {
// since written to file no need to display the content
return ResultBuilder.createInfoResult("Wrote successfully to file " + saveHistoryTo);
} else {
return ResultBuilder.createInfoResult(contents.toString());
}
}
}
use of org.apache.geode.management.internal.cli.result.ErrorResultData in project geode by apache.
the class IndexCommands method createIndex.
@CliCommand(value = CliStrings.CREATE_INDEX, help = CliStrings.CREATE_INDEX__HELP)
@CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA })
public // TODO : Add optionContext for indexName
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.CREATE_INDEX__MEMBER, mandatory = false, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.CREATE_INDEX__MEMBER__HELP) final String[] memberNameOrID, @CliOption(key = CliStrings.CREATE_INDEX__TYPE, mandatory = false, unspecifiedDefaultValue = "range", optionContext = ConverterHint.INDEX_TYPE, help = CliStrings.CREATE_INDEX__TYPE__HELP) final String indexType, @CliOption(key = CliStrings.CREATE_INDEX__GROUP, mandatory = false, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.CREATE_INDEX__GROUP__HELP) final String[] group) {
Result result = null;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
this.securityService.authorizeRegionManage(regionPath);
try {
final Cache cache = CacheFactory.getAnyInstance();
int idxType = IndexInfo.RANGE_INDEX;
// 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<String>();
final Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
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<String>();
}
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;
}
use of org.apache.geode.management.internal.cli.result.ErrorResultData in project geode by apache.
the class IndexCommands method createDefinedIndexes.
@CliCommand(value = CliStrings.CREATE_DEFINED_INDEXES, help = CliStrings.CREATE_DEFINED__HELP)
@CliMetaData(shellOnly = false, relatedTopic = { CliStrings.TOPIC_GEODE_REGION, CliStrings.TOPIC_GEODE_DATA })
@ResourceOperation(resource = Resource.DATA, operation = Operation.MANAGE)
public // TODO : Add optionContext for indexName
Result createDefinedIndexes(@CliOption(key = CliStrings.CREATE_DEFINED_INDEXES__MEMBER, mandatory = false, optionContext = ConverterHint.MEMBERIDNAME, help = CliStrings.CREATE_DEFINED_INDEXES__MEMBER__HELP) final String[] memberNameOrID, @CliOption(key = CliStrings.CREATE_DEFINED_INDEXES__GROUP, mandatory = false, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.CREATE_DEFINED_INDEXES__GROUP__HELP) final String[] group) {
Result result = null;
AtomicReference<XmlEntity> xmlEntity = new AtomicReference<>();
if (indexDefinitions.isEmpty()) {
final InfoResultData infoResult = ResultBuilder.createInfoResultData();
infoResult.addLine(CliStrings.DEFINE_INDEX__FAILURE__MSG);
return ResultBuilder.buildResult(infoResult);
}
try {
final Set<DistributedMember> targetMembers = CliUtil.findMembers(group, memberNameOrID);
if (targetMembers.isEmpty()) {
return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
}
final Cache cache = CacheFactory.getAnyInstance();
final ResultCollector<?, ?> rc = CliUtil.executeFunction(createDefinedIndexesFunction, indexDefinitions, targetMembers);
final List<Object> funcResults = (List<Object>) rc.getResult();
final Set<String> successfulMembers = new TreeSet<String>();
final Map<String, Set<String>> indexOpFailMap = new HashMap<String, Set<String>>();
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<String>();
}
failedMembers.add(cliFunctionResult.getMemberIdOrName());
indexOpFailMap.put(exceptionMessage, failedMembers);
}
}
}
if (!successfulMembers.isEmpty()) {
final InfoResultData infoResult = ResultBuilder.createInfoResultData();
infoResult.addLine(CliStrings.CREATE_DEFINED_INDEXES__SUCCESS__MSG);
int num = 0;
for (final String memberId : successfulMembers) {
++num;
infoResult.addLine(CliStrings.format(CliStrings.CREATE_DEFINED_INDEXES__NUMBER__AND__MEMBER, num, memberId));
}
result = ResultBuilder.buildResult(infoResult);
} else {
// Group members by the exception thrown.
final ErrorResultData erd = ResultBuilder.createErrorResultData();
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_DEFINED_INDEXES__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;
}
use of org.apache.geode.management.internal.cli.result.ErrorResultData in project geode by apache.
the class MiscellaneousCommands method getRegionMetricsFromMember.
/**
* Gets the metrics of region on a given member
*
* @return ResultData with required Region statistics or ErrorResultData if Region MBean is not
* found to gather metrics
* @throws ResultDataException if building result fails
*/
private ResultData getRegionMetricsFromMember(String regionName, DistributedMember distributedMember, String export_to_report_to, String[] categoriesArr) throws ResultDataException {
final InternalCache cache = getCache();
final SystemManagementService managementService = (SystemManagementService) ManagementService.getManagementService(cache);
ObjectName regionMBeanName = managementService.getRegionMBeanName(distributedMember, regionName);
RegionMXBean regionMxBean = managementService.getMBeanInstance(regionMBeanName, RegionMXBean.class);
if (regionMxBean != null) {
CompositeResultData crd = ResultBuilder.createCompositeResultData();
SectionResultData section = crd.addSection();
TabularResultData metricsTable = section.addTable();
metricsTable.setHeader("Metrics for region:" + regionName + " On Member " + MBeanJMXAdapter.getMemberNameOrId(distributedMember));
StringBuilder csvBuilder = null;
if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
csvBuilder = new StringBuilder();
csvBuilder.append("Category");
csvBuilder.append(',');
csvBuilder.append(CliStrings.SHOW_METRICS__METRIC__HEADER);
csvBuilder.append(',');
csvBuilder.append(CliStrings.SHOW_METRICS__VALUE__HEADER);
csvBuilder.append('\n');
}
/*
* Region Metrics
*/
Map<String, Boolean> categoriesMap = getRegionMetricsCategories();
if (categoriesArr != null && categoriesArr.length != 0) {
Set<String> categories = createSet(categoriesArr);
Set<String> checkSet = new HashSet<String>(categoriesMap.keySet());
Set<String> userCategories = getSetDifference(categories, checkSet);
// Checking if the categories specified by the user are valid or not
if (userCategories.isEmpty()) {
for (String category : checkSet) {
categoriesMap.put(category, false);
}
for (String category : categories) {
categoriesMap.put(category.toLowerCase(), true);
}
} else {
StringBuilder sb = new StringBuilder();
sb.append("Invalid Categories\n");
for (String category : userCategories) {
sb.append(category);
sb.append('\n');
}
return ResultBuilder.createErrorResultData().addLine(sb.toString());
}
}
if (categoriesMap.get("region").booleanValue()) {
writeToTableAndCsv(metricsTable, "region", "lastModifiedTime", regionMxBean.getLastModifiedTime(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lastAccessedTime", regionMxBean.getLastAccessedTime(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "missCount", regionMxBean.getMissCount(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "hitCount", regionMxBean.getHitCount(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "hitRatio", regionMxBean.getHitRatio(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "getsRate", regionMxBean.getGetsRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putsRate", regionMxBean.getPutsRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "createsRate", regionMxBean.getCreatesRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "destroyRate", regionMxBean.getDestroyRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putAllRate", regionMxBean.getPutAllRate(), csvBuilder);
}
if (categoriesMap.get("partition").booleanValue()) {
writeToTableAndCsv(metricsTable, "partition", "putLocalRate", regionMxBean.getPutLocalRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putRemoteRate", regionMxBean.getPutRemoteRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putRemoteLatency", regionMxBean.getPutRemoteLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "putRemoteAvgLatency", regionMxBean.getPutRemoteAvgLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "bucketCount", regionMxBean.getBucketCount(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "primaryBucketCount", regionMxBean.getPrimaryBucketCount(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "configuredRedundancy", regionMxBean.getConfiguredRedundancy(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "actualRedundancy", regionMxBean.getActualRedundancy(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "numBucketsWithoutRedundancy", regionMxBean.getNumBucketsWithoutRedundancy(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "totalBucketSize", regionMxBean.getTotalBucketSize(), csvBuilder);
}
/*
* Disk store
*/
if (categoriesMap.get("diskstore").booleanValue()) {
writeToTableAndCsv(metricsTable, "diskstore", "totalEntriesOnlyOnDisk", regionMxBean.getTotalEntriesOnlyOnDisk(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "diskReadsRate", "" + regionMxBean.getDiskReadsRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "diskWritesRate", regionMxBean.getDiskWritesRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "totalDiskWriteInProgress", regionMxBean.getTotalDiskWritesProgress(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "diskTaskWaiting", regionMxBean.getDiskTaskWaiting(), csvBuilder);
}
/*
* LISTENER
*/
if (categoriesMap.get("callback").booleanValue()) {
writeToTableAndCsv(metricsTable, "callback", "cacheWriterCallsAvgLatency", regionMxBean.getCacheWriterCallsAvgLatency(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "cacheListenerCallsAvgLatency", regionMxBean.getCacheListenerCallsAvgLatency(), csvBuilder);
}
/*
* Eviction
*/
if (categoriesMap.get("eviction").booleanValue()) {
writeToTableAndCsv(metricsTable, "eviction", "lruEvictionRate", regionMxBean.getLruEvictionRate(), csvBuilder);
writeToTableAndCsv(metricsTable, "", "lruDestroyRate", regionMxBean.getLruDestroyRate(), csvBuilder);
}
if (export_to_report_to != null && !export_to_report_to.isEmpty()) {
crd.addAsFile(export_to_report_to, csvBuilder.toString(), "Region Metrics exported to {0}.", false);
}
return crd;
} else {
ErrorResultData erd = ResultBuilder.createErrorResultData();
String errorMessage = CliStrings.format(CliStrings.SHOW_METRICS__ERROR, "Region MBean for " + regionName + " on member " + MBeanJMXAdapter.getMemberNameOrId(distributedMember) + " not found");
erd.addLine(errorMessage);
return erd;
}
}
Aggregations