Package org.rhq.core.pluginapi.operation

Examples of org.rhq.core.pluginapi.operation.OperationResult


        this.service = service;
        this.parameters = parameters;
    }

    public OperationResult invoke() {
        OperationResult result = new OperationResult();
        StringBuilder sbResult = new StringBuilder();
        String snapshotName = parameters.getSimpleValue("snapshotName", "" + System.currentTimeMillis()).trim();
        if (snapshotName.isEmpty()) {
            result.setErrorMessage("Snapshot Name parameter cannot be an empty string");
            return result;
        }
        String retentionStrategy = parameters.getSimpleValue("retentionStrategy", R_STRATEGY_KEEP_ALL);
        Integer count = parameters.getSimple("count").getIntegerValue();
        String deletionStrategy = parameters.getSimpleValue("deletionStrategy", D_STRATEGY_DEL);
        String location = parameters.getSimpleValue("location");

        // validate parameters
        if (R_STRATEGY_KEEP_LASTN.equals(retentionStrategy) || R_STRATEGY_DEL_OLDERN.equals(retentionStrategy)) {
            if (count == null) {
                result.setErrorMessage("Invalid input parameters. Selected Retention Strategy [" + retentionStrategy
                    + "] but 'count' parameter was null");
                return result;
            }
        }
        if (D_STRATEGY_MOVE.equals(deletionStrategy)) {
            if (location == null) {
                result.setErrorMessage("Invalid input parameters. Selected Deletion Strategy [" + deletionStrategy
                    + "] but 'location' parameter was null");
                return result;
            }
        }

        String[] keyspaces = service.getKeyspaces().toArray(new String[] {});
        log.info("Taking snapshot of keyspaces " + Arrays.toString(keyspaces));
        long startTime = System.currentTimeMillis();
        service.takeSnapshot(keyspaces, snapshotName);
        log.info("Snapshot taken in " + (System.currentTimeMillis() - startTime) + "ms");
        sbResult.append("Snapshot [" + snapshotName + "] was successfully created.");
        if (R_STRATEGY_KEEP_ALL.equals(retentionStrategy)) { // do nothing
            result.setSimpleResult(sbResult.toString());
            return result;
        }

        // verify if we can write to location to move older snapshots
        if (D_STRATEGY_MOVE.equals(deletionStrategy)) {
            File locationDir = new File(location);
            if (!locationDir.exists()) {
                try {
                    if (!locationDir.mkdirs()) {
                        result.setErrorMessage("Location [" + locationDir.getAbsolutePath()
                            + "] did not exist and failed to be created");
                        result.setSimpleResult(sbResult.toString());
                        return result;
                    }
                } catch (Exception e) {
                    result.setErrorMessage("Location [" + locationDir.getAbsolutePath()
                        + "] did not exist and failed to be created - " + e.getMessage());
                    result.setSimpleResult(sbResult.toString());
                    return result;
                }
            }
            if (!locationDir.isDirectory()) {
                result.setErrorMessage("Location [" + locationDir.getAbsolutePath() + "] must be directory");
                result.setSimpleResult(sbResult.toString());
                return result;
            }
            if (!locationDir.canWrite()) {
                result.setErrorMessage("Location [" + locationDir.getAbsolutePath() + "] must be writable");
                result.setSimpleResult(sbResult.toString());
                return result;
            }
        }

        List<String> columnFamilyDirs = service.getColumnFamilyDirs();

        // obtain list of snapshot dirs to be moved or deleted
        List<String[]> eligibleSnapshots = findEligibleSnapshots(service.getKeySpaceDataFileLocations(),
            columnFamilyDirs, retentionStrategy, count);

        if (eligibleSnapshots.isEmpty()) {
            return result;
        }
        StringBuilder sbMoveOrDeleteErrors = new StringBuilder();
        if (D_STRATEGY_DEL.equals(deletionStrategy)) {
            log.info("Strategy [" + deletionStrategy + "] is set, deleting " + eligibleSnapshots.size() + " snapshots");
            sbResult.append("\nDeleting " + eligibleSnapshots.size() + " directories.");
            int deleted = 0;
            for (String[] snapPath : eligibleSnapshots) {
                File snapDir = new File(snapPath[0], snapPath[1]);
                log.info("Deleting " + snapDir);
                if (!FileUtils.deleteQuietly(snapDir)) {
                    log.warn("Failed to delete " + snapDir.getAbsolutePath());
                    sbMoveOrDeleteErrors.append("Failed to delete [" + snapDir.getAbsolutePath() + "]\n ");
                } else {
                    deleted++;
                }
            }
            sbResult.append("\nSuccessfully deleted " + deleted + " directories");
        }
        if (D_STRATEGY_MOVE.equals(deletionStrategy)) {
            log.info("Strategy [" + deletionStrategy + "] is set, moving " + eligibleSnapshots.size() + " snapshots");
            sbResult.append("\nMoving " + eligibleSnapshots.size() + " directories to [" + location + "].");
            int moved = 0;
            for (String[] snapPath : eligibleSnapshots) {
                File snapDir = new File(snapPath[0], snapPath[1]);
                File snapTargetDir = new File(location, snapPath[1]);
                log.info("Moving  " + snapDir + " to " + snapTargetDir);
                try {
                    FileUtils.moveDirectoryToDirectory(snapDir, snapTargetDir.getParentFile(), true);
                    moved++;
                } catch (IOException e) {
                    log.warn("Failed to move directory : " + e.getMessage());
                    sbMoveOrDeleteErrors.append("Failed to move [" + snapDir.getAbsolutePath() + "] to ["
                        + snapTargetDir.getAbsolutePath() + "]\n ");
                }
            }
            sbResult.append("\nSuccessfully moved " + moved + " directories.");
        }
        if (sbMoveOrDeleteErrors.length() > 0) {
            result.setErrorMessage(sbMoveOrDeleteErrors.toString());
        }
        result.setSimpleResult(sbResult.toString());
        return result;
    }
View Full Code Here


     * @return An operation result
     * @see org.rhq.core.pluginapi.operation.OperationFacet
     */
    public OperationResult invokeOperation(String name, Configuration params) throws Exception {

        OperationResult res = new OperationResult();
        if ("sendMessage".equals(name)) {
            String message = params.getSimple("message").getStringValue();
            context.getParentResourceComponent().sendMessage(channel, message);
        }
        return res;
View Full Code Here

        return AvailabilityType.UP;
    }

    public OperationResult invokeOperation(String name, Configuration configuration) {

        OperationResult res = new OperationResult();
        if (name.equals("installGuest")) {
            log.info("Installing a Guest");
            String command = "/usr/bin/koan";
            String virtName = configuration.getSimpleValue("name", "Guest " + System.currentTimeMillis());
            String profile = configuration.getSimpleValue("profile", "profile");
            String server = configuration.getSimpleValue("server", "localhost");
            String[] argsString = { "--virt", "--server", server, "--profile", profile, "--virt-name", virtName };
            ProcessExecutionResults pr = this.execute(command, argsString);
            if (pr.getExitCode() > 0) {
                log.error("Error executing command: " + this.buildCommandString(command, argsString));
                res.setErrorMessage(pr.getCapturedOutput());
            } else {
                res.setSimpleResult(pr.getCapturedOutput());
            }

        }

        return res;
View Full Code Here

     * @return State of execution
     * @throws Exception If anything goes wrong
     */
    protected OperationResult restartServer(Configuration parameters) throws Exception {

        OperationResult operationResult = new OperationResult();
        if (isManuallyAddedServer(operationResult, "Restarting")) {
            return operationResult;
        }

        List<String> errors = validateStartScriptPluginConfigProps();
        if (!errors.isEmpty()) {
            OperationResult result = new OperationResult();
            setErrorMessage(result, errors);
            return result;
        }

        OperationResult tmp = invokeOperation("shutdown", parameters);

        if (tmp.getErrorMessage() != null) {
            tmp.setErrorMessage("Restart failed while attempting to shut down: " + tmp.getErrorMessage());
            return tmp;
        }

        context.getAvailabilityContext().requestAvailabilityCheck();

View Full Code Here

     * Start the server by calling the start script defined in the plugin configuration.
     *
     * @return the result of the operation
     */
    protected OperationResult startServer() throws InterruptedException {
        OperationResult operationResult = new OperationResult();
        if (isManuallyAddedServer(operationResult, "Starting")) {
            return operationResult;
        }

        List<String> errors = validateStartScriptPluginConfigProps();
        if (!errors.isEmpty()) {
            setErrorMessage(operationResult, errors);
            return operationResult;
        }

        ProcessExecutionResults results = ServerControl
            .onServer(context.getPluginConfiguration(), getMode(), context.getSystemInformation())
            .lifecycle().startServer();
        logExecutionResults(results);

        if (results.getError() != null) {
            operationResult.setErrorMessage(results.getError().getMessage());
        } else if (results.getExitCode() != null && results.getExitCode() != 0) {
            operationResult.setErrorMessage("Start failed with error code " + results.getExitCode() + ":\n"
                + results.getCapturedOutput());
        } else {
            // Try to connect to the server - ping once per second, timing out after 20s.
            boolean up = waitForServerToStart();
            if (up) {
                operationResult.setSimpleResult("Success");
            } else {
                operationResult.setErrorMessage("Was not able to start the server");
            }
        }
        context.getAvailabilityContext().requestAvailabilityCheck();

        return operationResult;
View Full Code Here

     * @param parameters input configuration (either commands or file sipmle-property is expected)
     * @return the result of the operation
     * @throws InterruptedException
     */
    protected OperationResult runCliCommand(Configuration parameters) throws InterruptedException {
        OperationResult result = new OperationResult();

        if (isManuallyAddedServer(result, "Executing jboss-cli")) {
            return result;
        }

        long waitTime = Integer.parseInt(parameters.getSimpleValue("waitTime", "3600"));
        if (waitTime <= 0) {
            result.setErrorMessage("waitTime parameter must be positive integer");
            return result;
        }
        ServerControl.Cli cli = ServerControl
            .onServer(context.getPluginConfiguration(), getMode(), context.getSystemInformation())
            .waitingFor(waitTime * 1000)
            .killingOnTimeout(Boolean.parseBoolean(parameters.getSimpleValue("killOnTimeout", "false"))).cli();

        ProcessExecutionResults results;
        String commands = parameters.getSimpleValue("commands");
        if (commands != null) {
            results = cli.executeCliCommand(commands);
        } else {
            File script = new File(parameters.getSimpleValue("file"));
            if (!script.isAbsolute()) {
                script = new File(serverPluginConfig.getHomeDir(), script.getPath()).getAbsoluteFile();
            }

            results = cli.executeCliScript(script);
        }

        logExecutionResults(results);
        result.setSimpleResult(results.getCapturedOutput());

        if (results.getError() != null) {
            result.setErrorMessage(results.getError().getMessage());
            return result;
        }
        if (results.getExitCode() == null) {
            result.setErrorMessage("jboss-cli execution timed out");
            return result;
        }
        if (results.getExitCode() != 0) {
            result.setErrorMessage("jboss-cli execution failed with error code " + results.getExitCode());
            return result;
        }

        if (Boolean.parseBoolean(parameters.getSimpleValue("triggerAvailability", null))) {
            context.getAvailabilityContext().requestAvailabilityCheck();
View Full Code Here

     * @param name Name of the operation
     * @param res Result of the operation vs. AS7
     * @return OperationResult filled in from values of res
     */
    protected OperationResult postProcessResult(String name, Result res) {
        OperationResult operationResult = new OperationResult();
        if (res == null) {
            operationResult.setErrorMessage("No result received from server");
            return operationResult;
        }

        if (name.equals("shutdown") || name.equals("restart") || name.equals("reload")) {
            /*
             * Shutdown, restart and reload need a special treatment, because after sending the operation, event if
             * it succeeds, the server connection is sometimes closed and we can't read from it.
             */
            if (!res.isSuccess()) {
                if (StringUtil.isNotBlank(res.getFailureDescription())
                    && res.getFailureDescription().startsWith(ASConnection.FAILURE_NO_RESPONSE)) {
                    operationResult.setSimpleResult("Success");
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Got no response for operation '" + name + "'. "
                            + "This is considered ok, as the remote server sometimes closes the communications "
                            + "channel before sending a reply");
                    }
                } else {
                    operationResult.setErrorMessage(res.getFailureDescription());
                }
            } else {
                operationResult.setSimpleResult("Success");
            }
        } else {
            if (res.isSuccess()) {
                if (res.getResult() != null)
                    operationResult.setSimpleResult(res.getResult().toString());
                else
                    operationResult.setSimpleResult("-None provided by server-");
            } else
                operationResult.setErrorMessage(res.getFailureDescription());
        }
        return operationResult;
    }
View Full Code Here

        this.bot.sendMessage(channel, message);
    }

    public OperationResult invokeOperation(String name, Configuration parameters) throws InterruptedException, Exception {
        if (name.equals("listChannels")) {
            OperationResult result = new OperationResult();
            Configuration resultConfig = result.getComplexResults();
            PropertyList channelList = new PropertyList("channelList");

            this.bot.listChannels();

            Thread.sleep(5000); // TODO is this long enough... any other way to know when the list is done?
View Full Code Here

    protected OperationResult installManagementUser(Configuration parameters, Configuration pluginConfig) {
        String user = parameters.getSimpleValue("user", "");
        String password = parameters.getSimpleValue("password", "");

        OperationResult result = new OperationResult();

        PropertySimple remoteProp = pluginConfig.getSimple("manuallyAdded");
        if (remoteProp != null && remoteProp.getBooleanValue() != null && remoteProp.getBooleanValue()) {
            result
                .setErrorMessage("This is a manually added server. This operation can not be used to install a management user. Use the server's 'bin/add-user.sh'");
            return result;
        }

        if (user.isEmpty() || password.isEmpty()) {
            result.setErrorMessage("User and Password must not be empty");
            return result;
        }

        File baseDir = serverPluginConfig.getBaseDir();
        if (baseDir == null) {
            result.setErrorMessage("'" + ServerPluginConfiguration.Property.BASE_DIR
                + "' plugin config prop is not set.");
            return result;
        }

        HostConfiguration hostConfig = getHostConfig();
        String realm = pluginConfig.getSimpleValue("realm", "ManagementRealm");
        File propertiesFile = hostConfig.getSecurityPropertyFile(serverPluginConfig, realm);
        if (!propertiesFile.canWrite()) {
            result.setErrorMessage("Management users properties file [" + propertiesFile + "] is not writable.");
            return result;
        }

        String encryptedPassword;
        try {
            UsernamePasswordHashUtil hashUtil = new UsernamePasswordHashUtil();
            encryptedPassword = hashUtil.generateHashedHexURP(user, realm, password.toCharArray());
        } catch (Exception e) {
            throw new RuntimeException("Failed to encrypt password.", e);
        }

        boolean userAlreadyExisted;
        try {
            PropertiesFileUpdate propsFileUpdate = new PropertiesFileUpdate(propertiesFile.getPath());
            userAlreadyExisted = propsFileUpdate.update(user, encryptedPassword);
        } catch (Exception e) {
            throw new RuntimeException("Failed to update management users properties file [" + propertiesFile + "].", e);
        }

        String verb = (userAlreadyExisted) ? "updated" : "added";
        result.setSimpleResult("Management user [" + user + "] " + verb + ".");
        LOG.info("Management user [" + user + "] " + verb + " for " + context.getResourceType().getName()
            + " server with key [" + context.getResourceKey() + "].");

        context.getAvailabilityContext().requestAvailabilityCheck();
        context.getInventoryContext().requestDeferredChildResourcesDiscovery();
View Full Code Here

    @SuppressWarnings("rawtypes")
    private void executeOperation(Resource resource, String operationName, Configuration config) throws Exception {
        ResourceComponent resourceComponent = PluginContainer.getInstance().getInventoryManager()
            .getResourceComponent(resource);

        OperationResult result = ((OperationFacet) resourceComponent).invokeOperation(operationName, config);

        if (result != null) {
            log.info("Result of operation " + operationName + " was: " + result.getSimpleResult());
            if (result.getErrorMessage() != null) {
                Assert.fail("Operation execution failed");
            }
        }
    }
View Full Code Here

TOP

Related Classes of org.rhq.core.pluginapi.operation.OperationResult

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.