Search in sources :

Example 1 with ElasticsearchSetupException

use of com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException in project elasticsearch-maven-plugin by alexcojocaru.

the class BootstrapClusterStep method execute.

@Override
public void execute(ClusterConfiguration config) {
    if (StringUtils.isBlank(config.getPathInitScript())) {
        // nothing to do; return
        return;
    }
    String filePath = config.getPathInitScript();
    validateFile(filePath);
    // we'll run all commands against the first node in the cluster
    ElasticsearchClient client = new ElasticsearchClient.Builder().withInstanceConfiguration(config.getInstanceConfigurationList().get(0)).withHostname("localhost").build();
    Stream<String> stream = null;
    try {
        stream = Files.lines(Paths.get(filePath));
        stream.forEach(command -> executeInitCommand(client, config.getLog(), command));
    } catch (IOException e) {
        throw new ElasticsearchSetupException("Cannot read the init script file", e);
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
Also used : ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException) IOException(java.io.IOException) ElasticsearchClient(com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClient)

Example 2 with ElasticsearchSetupException

use of com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException in project elasticsearch-maven-plugin by alexcojocaru.

the class BootstrapClusterStep method parseStringCommand.

protected ElasticsearchCommand parseStringCommand(String command) {
    ElasticsearchCommand esCommand = new ElasticsearchCommand();
    String formattedCommand = command.trim();
    // skip empty lines or lines starting with '#'
    if (formattedCommand.isEmpty() || formattedCommand.charAt(0) == '#') {
        esCommand.setSkip(true);
    } else {
        int firstSeparatorIndex = formattedCommand.indexOf(':');
        int secondSeparatorIndex = formattedCommand.indexOf(':', firstSeparatorIndex + 1);
        if (firstSeparatorIndex == -1 || secondSeparatorIndex == -1) {
            throw new ElasticsearchSetupException("Command '" + command + "' in the script file is not properly formatted." + " The format is: REQUEST_METHOD:path:json_script." + " Ex: PUT:indexName/typeName/id:{\"shoe_size\":39, \"shoe_color\":\"orange\"}");
        }
        String methodName = formattedCommand.substring(0, firstSeparatorIndex).trim();
        ElasticsearchCommand.RequestMethod method = ElasticsearchCommand.RequestMethod.fromName(methodName);
        esCommand.setRequestMethod(method);
        String relativeUrl = formattedCommand.substring(firstSeparatorIndex + 1, secondSeparatorIndex).trim();
        esCommand.setRelativeUrl(relativeUrl);
        String json = formattedCommand.substring(secondSeparatorIndex + 1).trim();
        esCommand.setJson(json);
    }
    return esCommand;
}
Also used : ElasticsearchCommand(com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchCommand) ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException)

Example 3 with ElasticsearchSetupException

use of com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException in project elasticsearch-maven-plugin by alexcojocaru.

the class BootstrapClusterStep method executeInitCommand.

protected void executeInitCommand(ElasticsearchClient client, Log log, ElasticsearchCommand command) {
    String url = "/" + command.getRelativeUrl();
    String content = command.getJson();
    try {
        switch(command.getRequestMethod()) {
            case PUT:
                client.put(url, content);
                break;
            case POST:
                client.post(url, content, String.class);
                break;
            case DELETE:
                client.delete(url);
                break;
            default:
                throw new IllegalStateException(String.format("Unsupported request method: %s", command.getRequestMethod()));
        }
    } catch (ElasticsearchClientException e) {
        throw new ElasticsearchSetupException(String.format("Cannot execute command %s", command), e);
    }
}
Also used : ElasticsearchClientException(com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClientException) ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException)

Example 4 with ElasticsearchSetupException

use of com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException in project elasticsearch-maven-plugin by alexcojocaru.

the class BootstrapClusterStep method parseMapCommand.

protected ElasticsearchCommand parseMapCommand(Map<String, Object> command) {
    ElasticsearchCommand esCommand = new ElasticsearchCommand();
    String methodName = (String) command.get("method");
    esCommand.setRequestMethod(ElasticsearchCommand.RequestMethod.fromName(methodName));
    String path = (String) command.get("path");
    esCommand.setRelativeUrl(path);
    Object payload = command.get("payload");
    if (ElasticsearchCommand.RequestMethod.DELETE == esCommand.getRequestMethod()) {
        Validate.isTrue(payload == null, "For DELETE commands the payload should be undefined");
    } else {
        try {
            esCommand.setJson(new ObjectMapper().writeValueAsString(payload));
        } catch (JsonProcessingException e) {
            throw new ElasticsearchSetupException("Cannot serialize the JSON payload for command '" + command + "'", e);
        }
    }
    return esCommand;
}
Also used : ElasticsearchCommand(com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchCommand) ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)

Example 5 with ElasticsearchSetupException

use of com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException in project elasticsearch-maven-plugin by alexcojocaru.

the class ProcessUtil method executeScript.

/**
 * Run the given command as a process within the supplied instance config context
 * and wait until it finalizes. An ElasticsearchSetupException is thrown if the exit code
 * is not 0.
 * @param config - the instance config
 * @param command - the command to execute
 * @param commandInput - the optional input string to send to the given command
 * @param environment - a map of environment variables; can be null
 * @param processDestroyer - a destroyer handler for the spawned process; can be null
 * @param disableLogging - whether to disable the logging of the command or not
 * @return the output (not trimmed of whitespaces) of the given command, as separate lines
 */
public static List<String> executeScript(InstanceConfiguration config, CommandLine command, Optional<String> commandInput, Map<String, String> environment, ProcessDestroyer processDestroyer, boolean disableLogging) {
    Log log = config.getClusterConfiguration().getLog();
    int instanceId = config.getId();
    File baseDir = new File(config.getBaseDir());
    Map<String, String> completeEnvironment = createEnvironment(environment);
    DefaultExecutor executor = new DefaultExecutor();
    executor.setWorkingDirectory(baseDir);
    // allows null
    executor.setProcessDestroyer(processDestroyer);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(commandInput.map(String::getBytes).orElse(new byte[] {}));
    // set up a tap on the output stream, to collect to output and return it from this method
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(disableLogging ? outputStream : new TeeOutputStream(System.out, outputStream), disableLogging ? errorStream : new TeeOutputStream(System.err, errorStream), inputStream));
    try {
        log.debug(String.format("Using environment: %s", completeEnvironment));
        String commandMessage = String.format("Elasticsearch[%d]: Executing command '%s' with input '%s' in directory '%s'", instanceId, command.toString(), commandInput.orElse(""), baseDir);
        if (disableLogging) {
            log.debug(commandMessage);
        } else {
            log.info(commandMessage);
        }
        int exitCode = executor.execute(command, completeEnvironment);
        if (exitCode != 0) {
            throw new ElasticsearchSetupException(String.format("Elasticsearch [%d]: Command '%s' in directory '%s' finished with exit code %d; see above for details", instanceId, command, baseDir, exitCode));
        }
        String resultMessage = String.format("Elasticsearch[%d]: The process finished with exit code %d", instanceId, exitCode);
        if (disableLogging) {
            log.debug(resultMessage);
        } else {
            log.info(resultMessage);
        }
    } catch (IOException e) {
        List<String> output = readBuffer(outputStream);
        List<String> error = readBuffer(errorStream);
        String lineSeparator = System.getProperty("line.separator");
        StringBuilder message = new StringBuilder();
        message.append("Elasticsearch [");
        message.append(instanceId);
        message.append("]: Cannot execute command '");
        message.append(command);
        message.append("' in directory '");
        message.append(baseDir);
        message.append("'");
        message.append(lineSeparator);
        message.append("Output:");
        message.append(lineSeparator);
        message.append(StringUtils.join(output, lineSeparator));
        message.append(lineSeparator);
        message.append("Error:");
        message.append(lineSeparator);
        message.append(StringUtils.join(error, lineSeparator));
        throw new ElasticsearchSetupException(message.toString(), e);
    }
    return readBuffer(outputStream);
}
Also used : TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) Log(org.apache.maven.plugin.logging.Log) DefaultExecutor(org.apache.commons.exec.DefaultExecutor) ElasticsearchSetupException(com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) PumpStreamHandler(org.apache.commons.exec.PumpStreamHandler) ByteArrayInputStream(java.io.ByteArrayInputStream) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

Aggregations

ElasticsearchSetupException (com.github.alexcojocaru.mojo.elasticsearch.v2.ElasticsearchSetupException)13 IOException (java.io.IOException)8 ElasticsearchCommand (com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchCommand)5 File (java.io.File)5 List (java.util.List)3 Log (org.apache.maven.plugin.logging.Log)3 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)2 ElasticsearchClientException (com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClientException)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 ArrayList (java.util.ArrayList)2 DefaultExecutor (org.apache.commons.exec.DefaultExecutor)2 PumpStreamHandler (org.apache.commons.exec.PumpStreamHandler)2 TeeOutputStream (org.apache.commons.io.output.TeeOutputStream)2 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)1 ElasticsearchClient (com.github.alexcojocaru.mojo.elasticsearch.v2.client.ElasticsearchClient)1 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Map (java.util.Map)1 CommandLine (org.apache.commons.exec.CommandLine)1