Search in sources :

Example 1 with ManagementException

use of org.apache.geode.management.ManagementException in project geode by apache.

the class ExportLogsCommand method exportLogs.

@CliCommand(value = CliStrings.EXPORT_LOGS, help = CliStrings.EXPORT_LOGS__HELP)
@CliMetaData(shellOnly = false, isFileDownloadOverHttp = true, interceptor = "org.apache.geode.management.internal.cli.commands.ExportLogsInterceptor", relatedTopic = { CliStrings.TOPIC_GEODE_SERVER, CliStrings.TOPIC_GEODE_DEBUG_UTIL })
@ResourceOperation(resource = ResourcePermission.Resource.CLUSTER, operation = ResourcePermission.Operation.READ)
public Result exportLogs(@CliOption(key = CliStrings.EXPORT_LOGS__DIR, help = CliStrings.EXPORT_LOGS__DIR__HELP, mandatory = false) String dirName, @CliOption(key = CliStrings.EXPORT_LOGS__GROUP, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.MEMBERGROUP, help = CliStrings.EXPORT_LOGS__GROUP__HELP) String[] groups, @CliOption(key = CliStrings.EXPORT_LOGS__MEMBER, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, optionContext = ConverterHint.ALL_MEMBER_IDNAME, help = CliStrings.EXPORT_LOGS__MEMBER__HELP) String[] memberIds, @CliOption(key = CliStrings.EXPORT_LOGS__LOGLEVEL, unspecifiedDefaultValue = DEFAULT_EXPORT_LOG_LEVEL, optionContext = ConverterHint.LOG_LEVEL, help = CliStrings.EXPORT_LOGS__LOGLEVEL__HELP) String logLevel, @CliOption(key = CliStrings.EXPORT_LOGS__UPTO_LOGLEVEL, unspecifiedDefaultValue = "false", help = CliStrings.EXPORT_LOGS__UPTO_LOGLEVEL__HELP) boolean onlyLogLevel, @CliOption(key = CliStrings.EXPORT_LOGS__MERGELOG, unspecifiedDefaultValue = "false", help = CliStrings.EXPORT_LOGS__MERGELOG__HELP) boolean mergeLog, @CliOption(key = CliStrings.EXPORT_LOGS__STARTTIME, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXPORT_LOGS__STARTTIME__HELP) String start, @CliOption(key = CliStrings.EXPORT_LOGS__ENDTIME, unspecifiedDefaultValue = CliMetaData.ANNOTATION_NULL_VALUE, help = CliStrings.EXPORT_LOGS__ENDTIME__HELP) String end, @CliOption(key = CliStrings.EXPORT_LOGS__LOGSONLY, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.EXPORT_LOGS__LOGSONLY__HELP) boolean logsOnly, @CliOption(key = CliStrings.EXPORT_LOGS__STATSONLY, unspecifiedDefaultValue = "false", specifiedDefaultValue = "true", help = CliStrings.EXPORT_LOGS__STATSONLY__HELP) boolean statsOnly, @CliOption(key = CliStrings.EXPORT_LOGS__FILESIZELIMIT, unspecifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__UNSPECIFIED_DEFAULT, specifiedDefaultValue = CliStrings.EXPORT_LOGS__FILESIZELIMIT__SPECIFIED_DEFAULT, help = CliStrings.EXPORT_LOGS__FILESIZELIMIT__HELP) String fileSizeLimit) {
    long totalEstimatedExportSize = 0;
    Result result;
    InternalCache cache = getCache();
    try {
        Set<DistributedMember> targetMembers = getMembers(groups, memberIds);
        if (targetMembers.isEmpty()) {
            return ResultBuilder.createUserErrorResult(CliStrings.NO_MEMBERS_FOUND_MESSAGE);
        }
        if (parseFileSizeLimit(fileSizeLimit) > 0) {
            // Get estimated size of exported logs from all servers before exporting anything
            for (DistributedMember server : targetMembers) {
                SizeExportLogsFunction.Args args = new SizeExportLogsFunction.Args(start, end, logLevel, onlyLogLevel, logsOnly, statsOnly);
                List<Object> results = (List<Object>) estimateLogSize(args, server).getResult();
                long estimatedSize = 0;
                if (!results.isEmpty()) {
                    List<?> res = (List<?>) results.get(0);
                    if (res.get(0) instanceof Long) {
                        estimatedSize = (Long) res.get(0);
                    }
                }
                logger.info("Received estimated export size from member {}: {}", server.getId(), estimatedSize);
                totalEstimatedExportSize += estimatedSize;
            }
            // disk available on the locator
            try {
                checkIfExportLogsOverflowsDisk("locator", parseFileSizeLimit(fileSizeLimit), totalEstimatedExportSize, getLocalDiskAvailable());
            } catch (ManagementException e) {
                return ResultBuilder.createUserErrorResult(e.getMessage());
            }
        }
        // get zipped files from all servers next
        Map<String, Path> zipFilesFromMembers = new HashMap<>();
        for (DistributedMember server : targetMembers) {
            Region region = ExportLogsFunction.createOrGetExistingExportLogsRegion(true, cache);
            ExportLogsCacheWriter cacheWriter = (ExportLogsCacheWriter) region.getAttributes().getCacheWriter();
            cacheWriter.startFile(server.getName());
            CliUtil.executeFunction(new ExportLogsFunction(), new ExportLogsFunction.Args(start, end, logLevel, onlyLogLevel, logsOnly, statsOnly), server).getResult();
            Path zipFile = cacheWriter.endFile();
            ExportLogsFunction.destroyExportLogsRegion(cache);
            // only put the zipfile in the map if it is not null
            if (zipFile != null) {
                logger.info("Received zip file from member {}: {}", server.getId(), zipFile);
                zipFilesFromMembers.put(server.getId(), zipFile);
            }
        }
        if (zipFilesFromMembers.isEmpty()) {
            return ResultBuilder.createUserErrorResult("No files to be exported.");
        }
        Path tempDir = Files.createTempDirectory("exportedLogs");
        // make sure the directory is created, so that even if there is no files unzipped to this
        // dir, we can still zip it and send an empty zip file back to the client
        Path exportedLogsDir = tempDir.resolve("exportedLogs");
        FileUtils.forceMkdir(exportedLogsDir.toFile());
        for (Path zipFile : zipFilesFromMembers.values()) {
            Path unzippedMemberDir = exportedLogsDir.resolve(zipFile.getFileName().toString().replace(".zip", ""));
            ZipUtils.unzip(zipFile.toAbsolutePath().toString(), unzippedMemberDir.toString());
            FileUtils.deleteQuietly(zipFile.toFile());
        }
        Path dirPath;
        if (StringUtils.isBlank(dirName)) {
            dirPath = Paths.get(System.getProperty("user.dir"));
        } else {
            dirPath = Paths.get(dirName);
        }
        Path exportedLogsZipFile = dirPath.resolve("exportedLogs_" + System.currentTimeMillis() + ".zip").toAbsolutePath();
        logger.info("Zipping into: " + exportedLogsZipFile.toString());
        ZipUtils.zipDirectory(exportedLogsDir, exportedLogsZipFile);
        try {
            checkFileSizeWithinLimit(parseFileSizeLimit(fileSizeLimit), exportedLogsZipFile.toFile());
        } catch (ManagementException e) {
            FileUtils.deleteQuietly(exportedLogsZipFile.toFile());
            return ResultBuilder.createUserErrorResult(e.getMessage());
        } finally {
            FileUtils.deleteDirectory(tempDir.toFile());
        }
        result = ResultBuilder.createInfoResult(exportedLogsZipFile.toString());
    } catch (Exception ex) {
        logger.error(ex.getMessage(), ex);
        result = ResultBuilder.createGemFireErrorResult(ex.getMessage());
    } finally {
        ExportLogsFunction.destroyExportLogsRegion(cache);
    }
    logger.debug("Exporting logs returning = {}", result);
    return result;
}
Also used : Path(java.nio.file.Path) HashMap(java.util.HashMap) ExportLogsCacheWriter(org.apache.geode.management.internal.cli.util.ExportLogsCacheWriter) SizeExportLogsFunction(org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction) InternalCache(org.apache.geode.internal.cache.InternalCache) BytesToString(org.apache.geode.management.internal.cli.util.BytesToString) ManagementException(org.apache.geode.management.ManagementException) Result(org.apache.geode.management.cli.Result) ManagementException(org.apache.geode.management.ManagementException) DistributedMember(org.apache.geode.distributed.DistributedMember) SizeExportLogsFunction(org.apache.geode.management.internal.cli.functions.SizeExportLogsFunction) ExportLogsFunction(org.apache.geode.management.internal.cli.functions.ExportLogsFunction) Region(org.apache.geode.cache.Region) List(java.util.List) CliCommand(org.springframework.shell.core.annotation.CliCommand) CliMetaData(org.apache.geode.management.cli.CliMetaData) ResourceOperation(org.apache.geode.management.internal.security.ResourceOperation)

Example 2 with ManagementException

use of org.apache.geode.management.ManagementException in project geode by apache.

the class ExportLogsCommand method checkIfExportLogsOverflowsDisk.

/**
   * @throws ManagementException if export file size checking is enabled (fileSizeLimit > 0) and the
   *         space required on a cluster member to filter and zip up files to be exported exceeds
   *         the disk space available
   */
void checkIfExportLogsOverflowsDisk(String memberName, long fileSizeLimitBytes, long estimatedSize, long diskAvailable) {
    if (fileSizeLimitBytes > 0) {
        StringBuilder sb = new StringBuilder();
        BytesToString bytesToString = new BytesToString();
        if (estimatedSize > diskAvailable) {
            sb.append("Estimated disk space required (").append(bytesToString.of(estimatedSize)).append(") to consolidate logs on member ").append(memberName).append(" will exceed available disk space (").append(bytesToString.of(diskAvailable)).append(")");
            // FileTooBigException
            throw new ManagementException(sb.toString());
        }
    }
}
Also used : ManagementException(org.apache.geode.management.ManagementException) BytesToString(org.apache.geode.management.internal.cli.util.BytesToString)

Example 3 with ManagementException

use of org.apache.geode.management.ManagementException in project geode by apache.

the class StringBasedFilter method compileFilterList.

private void compileFilterList(String[] list, List<Pattern> patternList) {
    for (String s : list) {
        try {
            s = formatStringTokens(s);
            Pattern pattern;
            if (s.contains("*")) {
                pattern = Pattern.compile(s);
            } else {
                pattern = Pattern.compile(s, Pattern.LITERAL);
            }
            patternList.add(pattern);
        } catch (NullPointerException e) {
            throw new ManagementException(e);
        }
    }
}
Also used : Pattern(java.util.regex.Pattern) ManagementException(org.apache.geode.management.ManagementException)

Example 4 with ManagementException

use of org.apache.geode.management.ManagementException in project geode by apache.

the class MBeanJMXAdapter method hasNotificationSupport.

/**
   * Checks whether an MBean implements notification support classes or not
   * 
   * @param objectName
   * @return if this MBean can be a notification broadcaster
   */
public boolean hasNotificationSupport(ObjectName objectName) {
    try {
        if (!isRegistered(objectName)) {
            return false;
        }
        ObjectInstance instance = mbeanServer.getObjectInstance(objectName);
        String className = instance.getClassName();
        Class cls = ClassLoadUtil.classFromName(className);
        Type[] intfTyps = cls.getGenericInterfaces();
        for (int i = 0; i < intfTyps.length; i++) {
            Class intfTyp = (Class) intfTyps[i];
            if (intfTyp.equals(NotificationEmitter.class)) {
                return true;
            }
        }
        Class supreClassTyp = (Class) cls.getGenericSuperclass();
        if (supreClassTyp != null && supreClassTyp.equals(NotificationBroadcasterSupport.class)) {
            return true;
        }
    } catch (InstanceNotFoundException e) {
        throw new ManagementException(e);
    } catch (ClassNotFoundException e) {
        throw new ManagementException(e);
    }
    return false;
}
Also used : Type(java.lang.reflect.Type) ManagementException(org.apache.geode.management.ManagementException) InstanceNotFoundException(javax.management.InstanceNotFoundException) ObjectInstance(javax.management.ObjectInstance) NotificationBroadcasterSupport(javax.management.NotificationBroadcasterSupport)

Example 5 with ManagementException

use of org.apache.geode.management.ManagementException in project geode by apache.

the class MBeanProxyFactory method createAllProxies.

/**
   * This method will create all the proxies for a given DistributedMember. It does not throw any
   * exception to its caller. It handles the error and logs error messages
   * 
   * It will be called from GII or when a member joins the system
   * 
   * @param member {@link org.apache.geode.distributed.DistributedMember}
   * @param monitoringRegion monitoring region containing the proxies
   */
public void createAllProxies(DistributedMember member, Region<String, Object> monitoringRegion) {
    if (logger.isDebugEnabled()) {
        logger.debug("Creating proxy for: {}", member.getId());
    }
    if (remoteFilterChain.isServerGroupFiltered("")) {
        if (logger.isTraceEnabled()) {
            logger.trace("Returning from server group filter");
        }
        return;
    }
    if (remoteFilterChain.isManagedNodeFiltered(member)) {
        if (logger.isTraceEnabled()) {
            logger.trace("returning from managed node filter");
        }
        return;
    }
    Set<String> mbeanNames = monitoringRegion.keySet();
    Iterator<String> it = mbeanNames.iterator();
    while (it.hasNext()) {
        ObjectName objectName = null;
        if (remoteFilterChain.isRemoteMBeanFiltered(objectName)) {
            if (logger.isTraceEnabled()) {
                logger.trace("continue  from remote MBEan node filter");
            }
            continue;
        }
        try {
            objectName = ObjectName.getInstance(it.next());
            if (logger.isDebugEnabled()) {
                logger.debug("Creating proxy for ObjectName: " + objectName.toString());
            }
            createProxy(member, objectName, monitoringRegion, monitoringRegion.get(objectName.toString()));
        } catch (ManagementException e) {
            logger.warn("Create Proxy failed for {} with exception {}", objectName, e.getMessage(), e);
            continue;
        } catch (Exception e) {
            logger.warn("Create Proxy failed for {} with exception {}", objectName, e.getMessage(), e);
            continue;
        }
    }
}
Also used : ManagementException(org.apache.geode.management.ManagementException) ManagementException(org.apache.geode.management.ManagementException) InstanceNotFoundException(javax.management.InstanceNotFoundException) IntrospectionException(java.beans.IntrospectionException) ObjectName(javax.management.ObjectName)

Aggregations

ManagementException (org.apache.geode.management.ManagementException)26 IOException (java.io.IOException)8 ObjectName (javax.management.ObjectName)8 InstanceNotFoundException (javax.management.InstanceNotFoundException)6 MalformedObjectNameException (javax.management.MalformedObjectNameException)5 Notification (javax.management.Notification)4 InternalCache (org.apache.geode.internal.cache.InternalCache)4 IntrospectionException (java.beans.IntrospectionException)3 Type (java.lang.reflect.Type)3 CancellationException (java.util.concurrent.CancellationException)3 ExecutionException (java.util.concurrent.ExecutionException)3 RejectedExecutionException (java.util.concurrent.RejectedExecutionException)3 InstanceAlreadyExistsException (javax.management.InstanceAlreadyExistsException)3 MBeanRegistrationException (javax.management.MBeanRegistrationException)3 NotCompliantMBeanException (javax.management.NotCompliantMBeanException)3 ObjectInstance (javax.management.ObjectInstance)3 RegionExistsException (org.apache.geode.cache.RegionExistsException)3 TimeoutException (org.apache.geode.cache.TimeoutException)3 DistributedMember (org.apache.geode.distributed.DistributedMember)3 BytesToString (org.apache.geode.management.internal.cli.util.BytesToString)3