Search in sources :

Example 1 with ClusterCommandResult

use of fish.payara.micro.ClusterCommandResult in project Payara by payara.

the class SendAsadminCommand method execute.

@Override
public void execute(AdminCommandContext context) {
    final ActionReport actionReport = context.getActionReport();
    // Check if the DAS is in a Hazelcast cluster
    if (payaraMicro.isClustered()) {
        // Get the subset of targets if provided, otherwise just get all clustered Micro instances
        Map<UUID, InstanceDescriptor> targetInstanceDescriptors = getTargetInstanceDescriptors(targets);
        // Add any explicit targets to our list of target GUIDS
        targetInstanceDescriptors.putAll(getExplicitTargetInstanceDescriptors(explicitTargets));
        // If no targets have been found, throw an exception and fail out
        if (targetInstanceDescriptors.isEmpty()) {
            throw new IllegalArgumentException("No targets match!");
        }
        // Get the command parameters if provided, otherwise initialise to an empty String
        if (parameters != null) {
            parameters = parseParameters(parameters);
        } else {
            parameters = new String[] { "" };
        }
        // Run the asadmin command against the targets (or all instances if no targets given)
        Map<UUID, Future<ClusterCommandResult>> results = payaraMicro.executeClusteredASAdmin(targetInstanceDescriptors.keySet(), command, parameters);
        // Check the command results for any failures
        if (results != null) {
            List<String> successMessages = new ArrayList<>();
            List<String> warningMessages = new ArrayList<>();
            List<String> failureMessages = new ArrayList<>();
            for (Map.Entry<UUID, Future<ClusterCommandResult>> result : results.entrySet()) {
                try {
                    ClusterCommandResult commandResult = result.getValue().get();
                    switch(commandResult.getExitStatus()) {
                        case SUCCESS:
                            // Only get the success messages if we've asked for them
                            if (verbose || logOutput) {
                                // We only want to get the message, not the formatter name or exit code
                                String rawOutput = commandResult.getOutput();
                                String[] outputComponents = rawOutput.split(commandResult.getExitStatus().name());
                                String output = outputComponents.length > 1 ? outputComponents[1] : rawOutput;
                                // Box the name and add it to the output to help split up the individual responses,
                                // since the success messages don't inherently provide information about what instance
                                // the command was run on
                                String boxedInstanceName = boxInstanceName(output);
                                successMessages.add("\n" + targetInstanceDescriptors.get(result.getKey()).getInstanceName() + "\n" + boxedInstanceName);
                            }
                            break;
                        case WARNING:
                            // If one of the commands has not already failed, set the exit code as WARNING
                            if (actionReport.getActionExitCode() != ExitCode.FAILURE) {
                                actionReport.setActionExitCode(ExitCode.WARNING);
                            }
                            // We only want to get the message, not the formatter name or exit code
                            failureMessages.add("\n" + targetInstanceDescriptors.get(result.getKey()).getInstanceName() + ":" + processException(commandResult));
                            break;
                        case FAILURE:
                            actionReport.setActionExitCode(ExitCode.FAILURE);
                            // We only want to get the message, not the formatter name or exit code
                            failureMessages.add("\n" + targetInstanceDescriptors.get(result.getKey()).getInstanceName() + ":\n" + processException(commandResult));
                            break;
                    }
                } catch (InterruptedException | ExecutionException ex) {
                    actionReport.setActionExitCode(ExitCode.FAILURE);
                    actionReport.failure(Logger.getLogger(SendAsadminCommand.class.getName()), "Ran into an exception during execution: \n", ex);
                }
            }
            switch(actionReport.getActionExitCode()) {
                case SUCCESS:
                    actionReport.setMessage("Command executed successfully");
                    // Skip if neither verbose or logOutput were selected
                    if (verbose || logOutput) {
                        String output = "";
                        // Combine the success messages into one String
                        for (String successMessage : successMessages) {
                            output += "\n" + successMessage;
                        }
                        // Only print out the messages if verbose was chosen
                        if (verbose) {
                            actionReport.setMessage(output);
                        }
                        // Only log the messages if logOutput was chosen
                        if (logOutput) {
                            Logger.getLogger(SendAsadminCommand.class.getName()).log(Level.INFO, output);
                        }
                    }
                    break;
                case WARNING:
                    actionReport.setMessage("Command completed with warnings: ");
                    for (String warningMessage : warningMessages) {
                        actionReport.appendMessage("\n" + warningMessage);
                    }
                    break;
                case FAILURE:
                    actionReport.setMessage("Failures reported: ");
                    for (String failureMessage : failureMessages) {
                        actionReport.appendMessage("\n" + failureMessage);
                    }
                    break;
            }
        } else {
            actionReport.setMessage("No results returned!");
            actionReport.setActionExitCode(ExitCode.FAILURE);
        }
    } else {
        actionReport.setMessage("Hazelcast not enabled");
        actionReport.setActionExitCode(ExitCode.FAILURE);
    }
}
Also used : InstanceDescriptor(fish.payara.micro.data.InstanceDescriptor) ClusterCommandResult(fish.payara.micro.ClusterCommandResult) ArrayList(java.util.ArrayList) ActionReport(org.glassfish.api.ActionReport) Future(java.util.concurrent.Future) UUID(java.util.UUID) ExecutionException(java.util.concurrent.ExecutionException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 2 with ClusterCommandResult

use of fish.payara.micro.ClusterCommandResult in project Payara by payara.

the class PayaraMicroRuntimeImpl method run.

/**
 * Runs an asadmin command on specified  members of the Payara Micro Cluster
 * Functionally equivalent to the run method of the ClusterCommandRunner passing in
 * all cluster members obtained from getClusteredPayaras()
 * @param command The name of the asadmin command to run
 * @param args The parameters to the command
 * @return
 */
@Override
public Map<InstanceDescriptor, Future<? extends ClusterCommandResult>> run(Collection<InstanceDescriptor> members, String command, String... args) {
    HashSet<UUID> memberUUIDs = new HashSet<>(members.size());
    for (InstanceDescriptor member : members) {
        memberUUIDs.add(member.getMemberUUID());
    }
    Map<UUID, Future<ClusterCommandResult>> commandResult = instanceService.executeClusteredASAdmin(memberUUIDs, command, args);
    Map<InstanceDescriptor, Future<? extends ClusterCommandResult>> result = new HashMap<>(commandResult.size());
    for (Entry<UUID, Future<ClusterCommandResult>> entry : commandResult.entrySet()) {
        UUID uuid = entry.getKey();
        InstanceDescriptor id = instanceService.getDescriptor(uuid);
        if (id != null) {
            result.put(id, entry.getValue());
        }
    }
    return result;
}
Also used : InstanceDescriptor(fish.payara.micro.data.InstanceDescriptor) ClusterCommandResult(fish.payara.micro.ClusterCommandResult) HashMap(java.util.HashMap) Future(java.util.concurrent.Future) UUID(java.util.UUID) HashSet(java.util.HashSet)

Example 3 with ClusterCommandResult

use of fish.payara.micro.ClusterCommandResult in project Payara by payara.

the class MicroProfileHealthChecker method pingAllInstances.

/**
 * Pings MP health check endpoint of all instances and returns a map containing a {@link Future} returning the ping
 * status code for that instance. Any exceptions thrown in the process will raise a {@link ExecutionException} when
 * the {@link Future} is resolved.
 */
private Map<String, Future<Integer>> pingAllInstances(long timeoutMillis) {
    Map<String, Future<Integer>> tasks = new ConcurrentHashMap<>();
    Map<UUID, Future<ClusterCommandResult>> configs = payaraMicro.executeClusteredASAdmin(GET_MP_CONFIG_STRING);
    for (Server server : domain.getServers().getServer()) {
        @Pattern(regexp = "[A-Za-z0-9_][A-Za-z0-9\\-_\\.;]*", message = "{server.invalid.name}", payload = Server.class) String instanceName = server.getName();
        tasks.put(instanceName, payaraExecutorService.submit(() -> {
            // get the remote server's MP HealthCheck config
            MicroprofileHealthCheckConfiguration healthCheckConfig = server.getConfig().getExtensionByType(MicroprofileHealthCheckConfiguration.class);
            if (healthCheckConfig != null && Boolean.valueOf(healthCheckConfig.getEnabled())) {
                return pingHealthEndpoint(buildURI(server, healthCheckConfig.getEndpoint()));
            }
            return -1;
        }));
    }
    for (InstanceDescriptor instance : payaraMicro.getClusteredPayaras()) {
        String instanceName = instance.getInstanceName();
        if (tasks.containsKey(instanceName)) {
            continue;
        }
        tasks.put(instanceName, payaraExecutorService.submit(() -> {
            ClusterCommandResult mpHealthConfigResult = // 
            configs.get(instance.getMemberUUID()).get(timeoutMillis, MILLISECONDS);
            String values = mpHealthConfigResult.getOutput().split("\n")[1];
            Boolean enabled = Boolean.parseBoolean(values.split(" ")[0]);
            if (enabled) {
                String endpoint = values.split(" ", 2)[1].trim();
                return pingHealthEndpoint(buildURI(instance, endpoint));
            }
            return -1;
        }));
    }
    return tasks;
}
Also used : InstanceDescriptor(fish.payara.micro.data.InstanceDescriptor) Pattern(javax.validation.constraints.Pattern) ClusterCommandResult(fish.payara.micro.ClusterCommandResult) Server(com.sun.enterprise.config.serverbeans.Server) Future(java.util.concurrent.Future) MicroprofileHealthCheckConfiguration(fish.payara.microprofile.healthcheck.config.MicroprofileHealthCheckConfiguration) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) UUID(java.util.UUID)

Example 4 with ClusterCommandResult

use of fish.payara.micro.ClusterCommandResult in project Payara by payara.

the class PayaraMicroCommandsTest method bootCommandtest.

@Test
public void bootCommandtest() throws Exception {
    PayaraMicroBoot microBoot = PayaraMicroLauncher.getBootClass();
    microBoot.setNoCluster(true);
    microBoot.setPreBootHandler((t) -> {
        ClusterCommandResult result = t.run("set", "configs.config.server-config.health-check-service-configuration.enabled=true");
        Assert.assertEquals(ClusterCommandResult.ExitStatus.SUCCESS, result.getExitStatus());
        Assert.assertNull(result.getFailureCause());
        System.out.println(result.getOutput());
    });
    microBoot.setPostBootHandler((t) -> {
        ClusterCommandResult result = t.run("get-healthcheck-configuration");
        Assert.assertEquals(ClusterCommandResult.ExitStatus.SUCCESS, result.getExitStatus());
        Assert.assertNull(result.getFailureCause());
        Assert.assertTrue(result.getOutput().contains("Health Check Service Configuration is enabled?: true"));
    });
    System.out.println("Starting Payara Micro");
    microBoot.setHttpAutoBind(true);
    microBoot.bootStrap();
    try {
        microBoot.setPreBootHandler((t) -> {
            t.run("set-healthcheck-configuration", "--enabled", "false");
        });
        Assert.fail("Should not be able to add preboot comand postboot");
    } catch (IllegalStateException ex) {
    // Expected
    }
    try {
        microBoot.setPostBootHandler((t) -> {
            t.run("set-healthcheck-configuration", "--enabled", "false");
        });
        Assert.fail("Should not be able to add preboot comand postboot");
    } catch (IllegalStateException ex) {
    // Expected
    }
    System.out.println("Shutting down Payara Micro");
    microBoot.shutdown();
}
Also used : ClusterCommandResult(fish.payara.micro.ClusterCommandResult) PayaraMicroBoot(fish.payara.micro.boot.PayaraMicroBoot) Test(org.junit.Test)

Example 5 with ClusterCommandResult

use of fish.payara.micro.ClusterCommandResult in project Payara by payara.

the class PayaraMicroRuntimeImpl method run.

/**
 * Runs an asadmin command on all members of the Payara Micro Cluster
 * Functionally equivalent to the run method of the ClusterCommandRunner passing in
 * all cluster members obtained from getClusteredPayaras()
 * @param command The name of the asadmin command to run
 * @param args The parameters to the command
 * @return
 */
@Override
public Map<InstanceDescriptor, Future<? extends ClusterCommandResult>> run(String command, String... args) {
    // NEEDS TO HANDLE THE CASE FOR LOCAL RUNNING IF NO CLUSTER ENABLED
    Map<UUID, Future<ClusterCommandResult>> commandResult = instanceService.executeClusteredASAdmin(command, args);
    Map<InstanceDescriptor, Future<? extends ClusterCommandResult>> result = new HashMap<>(commandResult.size());
    for (Entry<UUID, Future<ClusterCommandResult>> entry : commandResult.entrySet()) {
        UUID uuid = entry.getKey();
        InstanceDescriptor id = instanceService.getDescriptor(uuid);
        if (id != null) {
            result.put(id, entry.getValue());
        }
    }
    return result;
}
Also used : InstanceDescriptor(fish.payara.micro.data.InstanceDescriptor) ClusterCommandResult(fish.payara.micro.ClusterCommandResult) HashMap(java.util.HashMap) Future(java.util.concurrent.Future) UUID(java.util.UUID)

Aggregations

ClusterCommandResult (fish.payara.micro.ClusterCommandResult)5 InstanceDescriptor (fish.payara.micro.data.InstanceDescriptor)4 UUID (java.util.UUID)4 Future (java.util.concurrent.Future)4 HashMap (java.util.HashMap)3 Server (com.sun.enterprise.config.serverbeans.Server)1 PayaraMicroBoot (fish.payara.micro.boot.PayaraMicroBoot)1 MicroprofileHealthCheckConfiguration (fish.payara.microprofile.healthcheck.config.MicroprofileHealthCheckConfiguration)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)1 ExecutionException (java.util.concurrent.ExecutionException)1 Pattern (javax.validation.constraints.Pattern)1 ActionReport (org.glassfish.api.ActionReport)1 Test (org.junit.Test)1