Search in sources :

Example 91 with ActionReport

use of org.glassfish.api.ActionReport in project Payara by payara.

the class InstanceInfo method pingInstance.

// TODO what about security????
private Future<InstanceCommandResult> pingInstance() {
    try {
        ActionReport aReport = report.addSubActionsReport();
        InstanceCommandResult aResult = new InstanceCommandResult();
        ParameterMap map = new ParameterMap();
        map.set("type", "terse");
        InstanceCommandExecutor ice = new InstanceCommandExecutor(habitat, "__locations", FailurePolicy.Error, FailurePolicy.Error, svr, host, port, logger, map, aReport, aResult);
        return stateService.submitJob(svr, ice, aResult);
    /*
            String ret = rac.executeCommand(map).trim();

            if (ret == null || (!ret.endsWith("/" + name)))
            return -1;
            running = true;
            String uptimeStr = rac.getAttributes().get("Uptime_value");
            return Long.parseLong(uptimeStr);
             */
    } catch (CommandException ex) {
        running = false;
        return null;
    }
}
Also used : InstanceCommandExecutor(com.sun.enterprise.admin.util.InstanceCommandExecutor) InstanceCommandResult(org.glassfish.api.admin.InstanceCommandResult) ParameterMap(org.glassfish.api.admin.ParameterMap) CommandException(org.glassfish.api.admin.CommandException) ActionReport(org.glassfish.api.ActionReport)

Example 92 with ActionReport

use of org.glassfish.api.ActionReport in project Payara by payara.

the class GMSAnnounceAfterStartClusterCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    ActionReport report = context.getActionReport();
    announceGMSGroupStartupComplete(clusterName, report);
}
Also used : ActionReport(org.glassfish.api.ActionReport)

Example 93 with ActionReport

use of org.glassfish.api.ActionReport in project Payara by payara.

the class RemoteRestAdminCommand method executeRemoteCommand.

/**
 * Actually execute the remote command.
 */
private void executeRemoteCommand(final ParameterMap params) throws CommandException {
    doHttpCommand(getCommandURI(), "POST", new HttpCommand() {

        @Override
        public void prepareConnection(final HttpURLConnection urlConnection) throws IOException {
            try {
                if (useSse()) {
                    urlConnection.addRequestProperty("Accept", MEDIATYPE_SSE);
                } else {
                    urlConnection.addRequestProperty("Accept", MEDIATYPE_JSON + "; q=0.8, " + MEDIATYPE_MULTIPART + "; q=0.9");
                }
            } catch (CommandException cex) {
                throw new IOException(cex.getLocalizedMessage(), cex);
            }
            // add any user-specified headers
            for (Header h : requestHeaders) {
                urlConnection.addRequestProperty(h.getName(), h.getValue());
            }
            // Write data
            ParamsWithPayload pwp;
            if (doUpload) {
                urlConnection.setChunkedStreamingMode(0);
                pwp = new ParamsWithPayload(outboundPayload, params);
            } else {
                pwp = new ParamsWithPayload(null, params);
            }
            ProprietaryWriter writer = ProprietaryWriterFactory.getWriter(pwp);
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "Writer to use {0}", writer.getClass().getName());
            }
            writer.writeTo(pwp, urlConnection);
        }

        @Override
        public void useConnection(final HttpURLConnection urlConnection) throws CommandException, IOException {
            String resultMediaType = urlConnection.getContentType();
            if (logger.isLoggable(Level.FINER)) {
                logger.log(Level.FINER, "Result type is {0}", resultMediaType);
                logger.log(Level.FINER, "URL connection is {0}", urlConnection.getClass().getName());
            }
            if (resultMediaType != null && resultMediaType.startsWith(MEDIATYPE_SSE)) {
                String instanceId = null;
                boolean retryableCommand = false;
                try {
                    logger.log(Level.FINEST, "Response is SSE - about to read events");
                    closeSse = false;
                    ProprietaryReader<GfSseEventReceiver> reader = new GfSseEventReceiverProprietaryReader();
                    GfSseEventReceiver eventReceiver = reader.readFrom(urlConnection.getInputStream(), resultMediaType);
                    GfSseInboundEvent event;
                    do {
                        event = eventReceiver.readEvent();
                        if (event != null) {
                            if (logger.isLoggable(Level.FINEST)) {
                                logger.log(Level.FINEST, "Event: {0}", event.getName());
                            }
                            fireEvent(event.getName(), event);
                            if (AdminCommandState.EVENT_STATE_CHANGED.equals(event.getName())) {
                                AdminCommandState acs = event.getData(AdminCommandState.class, MEDIATYPE_JSON);
                                if (acs.getId() != null) {
                                    instanceId = acs.getId();
                                    if (logger.isLoggable(Level.FINEST)) {
                                        logger.log(Level.FINEST, "Command instance ID: {0}", instanceId);
                                    }
                                }
                                if (acs.getState() == AdminCommandState.State.COMPLETED || acs.getState() == AdminCommandState.State.RECORDED || acs.getState() == AdminCommandState.State.REVERTED) {
                                    if (acs.getActionReport() != null) {
                                        setActionReport(acs.getActionReport());
                                    }
                                    closeSse = true;
                                    if (!acs.isOutboundPayloadEmpty()) {
                                        logger.log(Level.FINEST, "Romote command holds data. Must load it");
                                        downloadPayloadFromManaged(instanceId);
                                    }
                                } else if (acs.getState() == AdminCommandState.State.FAILED_RETRYABLE) {
                                    logger.log(Level.INFO, strings.get("remotecommand.failedretryable", acs.getId()));
                                    if (acs.getActionReport() != null) {
                                        setActionReport(acs.getActionReport());
                                    }
                                    closeSse = true;
                                } else if (acs.getState() == AdminCommandState.State.RUNNING_RETRYABLE) {
                                    logger.log(Level.FINEST, "Command stores checkpoint and is retryable");
                                    retryableCommand = true;
                                }
                            }
                        }
                    } while (event != null && !eventReceiver.isClosed() && !closeSse);
                    if (closeSse) {
                        try {
                            eventReceiver.close();
                        } catch (Exception exc) {
                        }
                    }
                } catch (IOException ioex) {
                    if (instanceId != null && "Premature EOF".equals(ioex.getMessage())) {
                        if (retryableCommand) {
                            throw new CommandException(strings.get("remotecommand.lostConnection.retryableCommand", new Object[] { instanceId }), ioex);
                        } else {
                            throw new CommandException(strings.get("remotecommand.lostConnection", new Object[] { instanceId }), ioex);
                        }
                    } else {
                        throw new CommandException(ioex.getMessage(), ioex);
                    }
                } catch (Exception ex) {
                    throw new CommandException(ex.getMessage(), ex);
                }
            } else {
                ProprietaryReader<ParamsWithPayload> reader = ProprietaryReaderFactory.getReader(ParamsWithPayload.class, resultMediaType);
                if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR) {
                    ActionReport report;
                    if (reader == null) {
                        report = new CliActionReport();
                        report.setActionExitCode(ExitCode.FAILURE);
                        report.setMessage(urlConnection.getResponseMessage());
                    } else {
                        report = reader.readFrom(urlConnection.getErrorStream(), resultMediaType).getActionReport();
                    }
                    setActionReport(report);
                } else {
                    ParamsWithPayload pwp = reader.readFrom(urlConnection.getInputStream(), resultMediaType);
                    if (pwp.getPayloadInbound() == null) {
                        setActionReport(pwp.getActionReport());
                    } else if (resultMediaType.startsWith("multipart/")) {
                        RestPayloadImpl.Inbound inbound = pwp.getPayloadInbound();
                        setActionReport(pwp.getActionReport());
                        if (logger.isLoggable(Level.FINER)) {
                            logger.log(Level.FINER, "------ PAYLOAD ------");
                            Iterator<Payload.Part> parts = inbound.parts();
                            while (parts.hasNext()) {
                                Payload.Part part = parts.next();
                                logger.log(Level.FINER, " - {0} [{1}]", new Object[] { part.getName(), part.getContentType() });
                            }
                            logger.log(Level.FINER, "---- END PAYLOAD ----");
                        }
                        PayloadFilesManager downloadedFilesMgr = new PayloadFilesManager.Perm(fileOutputDir, null, logger, null);
                        try {
                            downloadedFilesMgr.processParts(inbound);
                        } catch (CommandException cex) {
                            throw cex;
                        } catch (Exception ex) {
                            throw new CommandException(ex.getMessage(), ex);
                        }
                    }
                }
            }
        }
    });
    if (actionReport == null) {
        this.output = null;
        throw new CommandException(strings.get("emptyResponse"));
    }
    if (actionReport.getActionExitCode() == ExitCode.FAILURE) {
        throw new CommandException(strings.getString("remote.failure.prefix", "remote failure:") + " " + this.output);
    }
}
Also used : CliActionReport(com.sun.enterprise.admin.remote.reader.CliActionReport) CliActionReport(com.sun.enterprise.admin.remote.reader.CliActionReport) ActionReport(org.glassfish.api.ActionReport) ProprietaryWriter(com.sun.enterprise.admin.remote.writer.ProprietaryWriter) GfSseEventReceiverProprietaryReader(com.sun.enterprise.admin.remote.sse.GfSseEventReceiverProprietaryReader) GfSseEventReceiverProprietaryReader(com.sun.enterprise.admin.remote.sse.GfSseEventReceiverProprietaryReader) ProprietaryReader(com.sun.enterprise.admin.remote.reader.ProprietaryReader) GfSseInboundEvent(com.sun.enterprise.admin.remote.sse.GfSseInboundEvent) GfSseEventReceiver(com.sun.enterprise.admin.remote.sse.GfSseEventReceiver) SSLException(javax.net.ssl.SSLException) JsonObject(javax.json.JsonObject) Payload(org.glassfish.api.admin.Payload) PayloadFilesManager(org.glassfish.admin.payload.PayloadFilesManager)

Example 94 with ActionReport

use of org.glassfish.api.ActionReport in project Payara by payara.

the class MultipartProprietaryReader method readFrom.

@Override
public ParamsWithPayload readFrom(final InputStream is, final String contentType) throws IOException {
    RestPayloadImpl.Inbound payload = null;
    ActionReport actionReport = null;
    ParameterMap parameters = null;
    Properties mtProps = parseHeaderParams(contentType);
    final String boundary = mtProps.getProperty("boundary");
    if (!StringUtils.ok(boundary)) {
        throw new IOException("ContentType does not define boundary");
    }
    final MIMEMessage mimeMessage = new MIMEMessage(is, boundary, new MIMEConfig());
    // Parse
    for (MIMEPart mimePart : mimeMessage.getAttachments()) {
        String cd = getFirst(mimePart.getHeader("Content-Disposition"));
        if (!StringUtils.ok(cd)) {
            cd = "file";
        }
        cd = cd.trim();
        Properties cdParams = parseHeaderParams(cd);
        // 3 types of content disposition
        if (cd.startsWith("form-data")) {
            // COMMAND PARAMETER
            if (!StringUtils.ok(cdParams.getProperty("name"))) {
                throw new IOException("Form-data Content-Disposition does not contains name parameter.");
            }
            if (parameters == null) {
                parameters = new ParameterMap();
            }
            parameters.add(cdParams.getProperty("name"), stream2String(mimePart.readOnce()));
        } else if (mimePart.getContentType() != null && mimePart.getContentType().startsWith("application/json")) {
            // ACTION REPORT
            actionReport = actionReportReader.readFrom(mimePart.readOnce(), "application/json");
        } else {
            // PAYLOAD
            String name = "noname";
            if (cdParams.containsKey("name")) {
                name = cdParams.getProperty("name");
            } else if (cdParams.containsKey("filename")) {
                name = cdParams.getProperty("filename");
            }
            if (payload == null) {
                payload = new RestPayloadImpl.Inbound();
            }
            String ct = mimePart.getContentType();
            if (!StringUtils.ok(ct) || ct.trim().startsWith("text/plain")) {
                payload.add(name, stream2String(mimePart.readOnce()), mimePart.getAllHeaders());
            } else {
                payload.add(name, mimePart.read(), ct, mimePart.getAllHeaders());
            }
        }
    }
    // Result
    return new ParamsWithPayload(payload, parameters, actionReport);
}
Also used : MIMEConfig(org.jvnet.mimepull.MIMEConfig) MIMEMessage(org.jvnet.mimepull.MIMEMessage) ParameterMap(org.glassfish.api.admin.ParameterMap) IOException(java.io.IOException) ParamsWithPayload(com.sun.enterprise.admin.remote.ParamsWithPayload) ActionReport(org.glassfish.api.ActionReport) Properties(java.util.Properties) RestPayloadImpl(com.sun.enterprise.admin.remote.RestPayloadImpl) MIMEPart(org.jvnet.mimepull.MIMEPart)

Example 95 with ActionReport

use of org.glassfish.api.ActionReport in project Payara by payara.

the class ClusterOperationUtil method replicateCommand.

/**
 * Replicates a given command on the given list of targets, optionally gathering
 * downloaded result payloads from the instance commands into a directory.
 * <p>
 * If intermediateDownloadDir is non-null, then any files returned from
 * the instances in the payload of the HTTP response will be stored in a
 * directory tree like this:
 * <pre>
 * ${intermediateDownloadDir}/
 *     ${instanceA}/
 *         file(s) returned from instance A
 *     ${instanceB}/
 *         file(s) returned from instance B
 *     ...
 * </pre>
 * where ${instanceA}, ${instanceB}, etc. are the names of the instances to
 * which the command was replicated.  This method does no further processing
 * on the downloaded files but leaves that to the calling command.
 */
public static ActionReport.ExitCode replicateCommand(String commandName, FailurePolicy failPolicy, FailurePolicy offlinePolicy, FailurePolicy neverStartedPolicy, List<Server> instancesForReplication, AdminCommandContext context, ParameterMap parameters, ServiceLocator habitat, final File intermediateDownloadDir) {
    ActionReport.ExitCode returnValue = ActionReport.ExitCode.SUCCESS;
    InstanceStateService instanceState = habitat.getService(InstanceStateService.class);
    validateIntermediateDownloadDir(intermediateDownloadDir);
    RemoteInstanceCommandHelper rich = new RemoteInstanceCommandHelper(habitat);
    Map<String, Future<InstanceCommandResult>> futures = new HashMap<>();
    try {
        for (Server svr : instancesForReplication) {
            if (instanceState.getState(svr.getName()) == InstanceState.StateType.NEVER_STARTED) {
                // Do not replicate commands to instances that have never been started.
                // For certain commands, warn about the failure to replicate even if
                // the instance has never been started.
                ActionReport.ExitCode finalResult = FailurePolicy.applyFailurePolicy(neverStartedPolicy, ActionReport.ExitCode.FAILURE);
                if (!finalResult.equals(ActionReport.ExitCode.SUCCESS)) {
                    ActionReport aReport = context.getActionReport().addSubActionsReport();
                    if (finalResult.equals(ActionReport.ExitCode.FAILURE)) {
                        aReport.setMessage(strings.getLocalString("clusterutil.failneverstarted", "FAILURE: Instance {0} has never been started; command {1} was not replicated to that instance", svr.getName(), commandName));
                    } else {
                        aReport.setMessage(strings.getLocalString("clusterutil.warnneverstarted", "WARNING: Instance {0} has never been started; command {1} was not replicated to that instance", svr.getName(), commandName));
                    }
                    aReport.setActionExitCode(finalResult);
                    if (returnValue == ActionReport.ExitCode.SUCCESS)
                        returnValue = finalResult;
                }
                continue;
            }
            Config scfg = svr.getConfig();
            // PAYARA-2162 Restart Required is set erroneously when _get-runtime-info is called
            if (!Boolean.valueOf(scfg.getDynamicReconfigurationEnabled()) && !ALLOWED_COMMANDS.contains(commandName)) {
                // Do not replicate to servers for which dynamic configuration is disabled
                ActionReport aReport = context.getActionReport().addSubActionsReport();
                aReport.setActionExitCode(ActionReport.ExitCode.WARNING);
                aReport.setMessage(strings.getLocalString("clusterutil.dynrecfgdisabled", "WARNING: The command {0} was not replicated to instance {1} because the " + "dynamic-reconfiguration-enabled flag is set to false for config {2}", new Object[] { commandName, svr.getName(), scfg.getName() }));
                instanceState.setState(svr.getName(), InstanceState.StateType.RESTART_REQUIRED, false);
                instanceState.addFailedCommandToInstance(svr.getName(), commandName, parameters);
                returnValue = ActionReport.ExitCode.WARNING;
                continue;
            }
            String host = svr.getAdminHost();
            int port = rich.getAdminPort(svr);
            ActionReport aReport = context.getActionReport().addSubActionsReport();
            InstanceCommandResult aResult = new InstanceCommandResult();
            // InstanceCommandExecutor ice =
            // new InstanceCommandExecutor(habitat, commandName, failPolicy, offlinePolicy,
            // svr, host, port, logger, parameters, aReport, aResult);
            // if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName()))
            // continue;
            // if (intermediateDownloadDir != null) {
            // ice.setFileOutputDirectory(
            // subdirectoryForInstance(intermediateDownloadDir, ice));
            // }
            // Future<InstanceCommandResult> f = instanceState.submitJob(svr, ice, aResult);
            // TODO: Remove this if after only one remote admin call method will be choosen
            Future<InstanceCommandResult> f;
            if (useRest()) {
                InstanceRestCommandExecutor ice = new InstanceRestCommandExecutor(habitat, commandName, failPolicy, offlinePolicy, svr, host, port, logger, parameters, aReport, aResult);
                if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName())) {
                    continue;
                }
                if (intermediateDownloadDir != null) {
                    ice.setFileOutputDirectory(new File(intermediateDownloadDir, ice.getServer().getName()));
                }
                f = instanceState.submitJob(svr, ice, aResult);
            } else {
                logger.log(Level.FINEST, "replicateCommand(): Use traditional way for replication - {0}", commandName);
                InstanceCommandExecutor ice = new InstanceCommandExecutor(habitat, commandName, failPolicy, offlinePolicy, svr, host, port, logger, parameters, aReport, aResult);
                if (CommandTarget.DAS.isValid(habitat, ice.getServer().getName())) {
                    continue;
                }
                if (intermediateDownloadDir != null) {
                    ice.setFileOutputDirectory(new File(intermediateDownloadDir, ice.getServer().getName()));
                }
                f = instanceState.submitJob(svr, ice, aResult);
            }
            if (f == null) {
                logger.severe(AdminLoggerInfo.stateNotFound);
                continue;
            }
            futures.put(svr.getName(), f);
            logger.fine(strings.getLocalString("dynamicreconfiguration.diagnostics.jobsubmitted", "Successfully submitted command {0} for execution at instance {1}", commandName, svr.getName()));
        }
    } catch (Exception ex) {
        ActionReport aReport = context.getActionReport().addSubActionsReport();
        ActionReport.ExitCode finalResult = FailurePolicy.applyFailurePolicy(failPolicy, ActionReport.ExitCode.FAILURE);
        aReport.setActionExitCode(finalResult);
        aReport.setMessage(strings.getLocalString("clusterutil.replicationfailed", "Error during command replication: {0}", ex.getLocalizedMessage()));
        logger.log(Level.SEVERE, AdminLoggerInfo.replicationError, ex.getLocalizedMessage());
        if (returnValue == ActionReport.ExitCode.SUCCESS) {
            returnValue = finalResult;
        }
    }
    boolean gotFirstResponse = false;
    long maxWaitTime = RemoteRestAdminCommand.getReadTimeout();
    long timeBeforeAsadminTimeout = maxWaitTime;
    long waitStart = System.currentTimeMillis();
    for (Map.Entry<String, Future<InstanceCommandResult>> fe : futures.entrySet()) {
        String s = fe.getKey();
        ActionReport.ExitCode finalResult;
        try {
            logger.fine(strings.getLocalString("dynamicreconfiguration.diagnostics.waitingonjob", "Waiting for command {0} to be completed at instance {1}", commandName, s));
            Future<InstanceCommandResult> aFuture = fe.getValue();
            InstanceCommandResult aResult = aFuture.get(maxWaitTime, TimeUnit.MILLISECONDS);
            long elapsedTime = System.currentTimeMillis() - waitStart;
            timeBeforeAsadminTimeout -= elapsedTime;
            if (!gotFirstResponse) {
                maxWaitTime = elapsedTime * 4;
                gotFirstResponse = true;
            }
            if ((maxWaitTime > timeBeforeAsadminTimeout) || (maxWaitTime < 60000)) {
                maxWaitTime = timeBeforeAsadminTimeout;
            }
            ActionReport iReport;
            Server iServer;
            if (useRest()) {
                InstanceRestCommandExecutor ice = (InstanceRestCommandExecutor) aResult.getInstanceCommand();
                iReport = ice.getReport();
                iServer = ice.getServer();
            } else {
                InstanceCommandExecutor ice = (InstanceCommandExecutor) aResult.getInstanceCommand();
                iReport = ice.getReport();
                iServer = ice.getServer();
            }
            if (iReport.getActionExitCode() != ActionReport.ExitCode.FAILURE) {
                completedInstances.add(iServer);
            }
            finalResult = FailurePolicy.applyFailurePolicy(failPolicy, iReport.getActionExitCode());
            if (returnValue == ActionReport.ExitCode.SUCCESS) {
                returnValue = finalResult;
            }
            if (finalResult != ActionReport.ExitCode.SUCCESS) {
                instanceState.setState(s, InstanceState.StateType.RESTART_REQUIRED, false);
                instanceState.addFailedCommandToInstance(s, commandName, parameters);
            }
        } catch (Exception ex) {
            ActionReport aReport = context.getActionReport().addSubActionsReport();
            finalResult = FailurePolicy.applyFailurePolicy(failPolicy, ActionReport.ExitCode.FAILURE);
            if (finalResult == ActionReport.ExitCode.FAILURE) {
                if (ex instanceof TimeoutException)
                    aReport.setMessage(strings.getLocalString("clusterutil.timeoutwhilewaiting", "Timed out while waiting for result from instance {0}", s));
                else
                    aReport.setMessage(strings.getLocalString("clusterutil.exceptionwhilewaiting", "Exception while waiting for result from instance {0} : {1}", s, ex.getLocalizedMessage()));
            }
            aReport.setActionExitCode(finalResult);
            if (returnValue == ActionReport.ExitCode.SUCCESS)
                returnValue = finalResult;
            instanceState.setState(s, InstanceState.StateType.RESTART_REQUIRED, false);
            instanceState.addFailedCommandToInstance(s, commandName, parameters);
        }
    }
    return returnValue;
}
Also used : Server(com.sun.enterprise.config.serverbeans.Server) Config(com.sun.enterprise.config.serverbeans.Config) ActionReport(org.glassfish.api.ActionReport) TimeoutException(java.util.concurrent.TimeoutException) Future(java.util.concurrent.Future) File(java.io.File) TimeoutException(java.util.concurrent.TimeoutException)

Aggregations

ActionReport (org.glassfish.api.ActionReport)508 TransactionFailure (org.jvnet.hk2.config.TransactionFailure)86 Properties (java.util.Properties)83 Config (com.sun.enterprise.config.serverbeans.Config)73 PropertyVetoException (java.beans.PropertyVetoException)72 ParameterMap (org.glassfish.api.admin.ParameterMap)66 Logger (java.util.logging.Logger)56 IOException (java.io.IOException)47 ArrayList (java.util.ArrayList)47 HashMap (java.util.HashMap)43 File (java.io.File)41 CommandTarget (org.glassfish.config.support.CommandTarget)30 Target (org.glassfish.internal.api.Target)30 Map (java.util.Map)27 Server (com.sun.enterprise.config.serverbeans.Server)25 List (java.util.List)25 ServiceLocator (org.glassfish.hk2.api.ServiceLocator)24 CommandRunner (org.glassfish.api.admin.CommandRunner)23 ExtendedDeploymentContext (org.glassfish.internal.deployment.ExtendedDeploymentContext)23 DeployCommandParameters (org.glassfish.api.deployment.DeployCommandParameters)19