Search in sources :

Example 21 with RunContext

use of io.kestra.core.runners.RunContext in project kestra by kestra-io.

the class AbstractBash method run.

@SuppressWarnings("deprecation")
protected ScriptOutput run(RunContext runContext, Supplier<String> supplier) throws Exception {
    Logger logger = runContext.logger();
    if (this.workingDirectory == null) {
        this.workingDirectory = runContext.tempDir();
    }
    additionalVars.put("workingDir", workingDirectory.toAbsolutePath().toString());
    List<String> allOutputs = new ArrayList<>();
    // deprecated properties
    if (this.outputFiles != null && this.outputFiles.size() > 0) {
        allOutputs.addAll(this.outputFiles);
    }
    if (this.outputsFiles != null && this.outputsFiles.size() > 0) {
        allOutputs.addAll(this.outputsFiles);
    }
    if (files != null && files.size() > 0) {
        allOutputs.addAll(files);
    }
    Map<String, String> outputFiles = BashService.createOutputFiles(workingDirectory, allOutputs, additionalVars);
    BashService.createInputFiles(runContext, workingDirectory, this.finalInputFiles(), additionalVars);
    String commandAsString = supplier.get();
    // run
    RunResult runResult = this.run(runContext, logger, workingDirectory, finalCommandsWithInterpreter(commandAsString), this.finalEnv(), (inputStream, isStdErr) -> {
        AbstractLogThread thread = new LogThread(logger, inputStream, isStdErr, runContext);
        thread.setName("bash-log-" + (isStdErr ? "-err" : "-out"));
        thread.start();
        return thread;
    });
    // upload output files
    Map<String, URI> uploaded = new HashMap<>();
    outputFiles.forEach(throwBiConsumer((k, v) -> uploaded.put(k, runContext.putTempFile(new File(runContext.render(v, additionalVars))))));
    Map<String, Object> outputsVars = new HashMap<>();
    outputsVars.putAll(runResult.getStdOut().getOutputs());
    outputsVars.putAll(runResult.getStdErr().getOutputs());
    // output
    return ScriptOutput.builder().exitCode(runResult.getExitCode()).stdOutLineCount(runResult.getStdOut().getLogsCount()).stdErrLineCount(runResult.getStdErr().getLogsCount()).warningOnStdErr(this.warningOnStdErr).vars(outputsVars).files(uploaded).outputFiles(uploaded).build();
}
Also used : ScriptRunnerInterface(io.kestra.core.tasks.scripts.runners.ScriptRunnerInterface) HashMap(java.util.HashMap) Rethrow.throwBiConsumer(io.kestra.core.utils.Rethrow.throwBiConsumer) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) NotEmpty(javax.validation.constraints.NotEmpty) ProcessBuilderScriptRunner(io.kestra.core.tasks.scripts.runners.ProcessBuilderScriptRunner) Map(java.util.Map) URI(java.net.URI) Path(java.nio.file.Path) Schema(io.swagger.v3.oas.annotations.media.Schema) Logger(org.slf4j.Logger) SuperBuilder(lombok.experimental.SuperBuilder) DockerScriptRunner(io.kestra.core.tasks.scripts.runners.DockerScriptRunner) IOException(java.io.IOException) NotNull(javax.validation.constraints.NotNull) lombok(lombok) File(java.io.File) PluginProperty(io.kestra.core.models.annotations.PluginProperty) Task(io.kestra.core.models.tasks.Task) Introspected(io.micronaut.core.annotation.Introspected) List(java.util.List) RunContext(io.kestra.core.runners.RunContext) AbstractMetricEntry(io.kestra.core.models.executions.AbstractMetricEntry) InputStream(java.io.InputStream) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) Logger(org.slf4j.Logger) URI(java.net.URI) File(java.io.File)

Example 22 with RunContext

use of io.kestra.core.runners.RunContext in project kestra by kestra-io.

the class Counts method run.

@Override
public Output run(RunContext runContext) throws Exception {
    Logger logger = runContext.logger();
    ExecutionRepositoryInterface executionRepository = runContext.getApplicationContext().getBean(ExecutionRepositoryInterface.class);
    String query = null;
    if (this.states != null) {
        query = "state.current:(" + this.states.stream().map(Enum::name).collect(Collectors.joining(" OR ")) + ")";
    }
    List<ExecutionCount> executionCounts = executionRepository.executionCounts(flows, query, startDate != null ? ZonedDateTime.parse(runContext.render(startDate)) : null, endDate != null ? ZonedDateTime.parse(runContext.render(endDate)) : null);
    logger.trace("{} flows matching filters", executionCounts.size());
    List<Result> count = executionCounts.stream().filter(throwPredicate(item -> runContext.render(this.expression, ImmutableMap.of("count", item.getCount().intValue())).equals("true"))).map(item -> Result.builder().namespace(item.getNamespace()).flowId(item.getFlowId()).count(item.getCount()).build()).collect(Collectors.toList());
    logger.debug("{} flows matching the expression", count.size());
    return Output.builder().results(count).build();
}
Also used : Schema(io.swagger.v3.oas.annotations.media.Schema) Rethrow.throwPredicate(io.kestra.core.utils.Rethrow.throwPredicate) ExecutionRepositoryInterface(io.kestra.core.repositories.ExecutionRepositoryInterface) Logger(org.slf4j.Logger) ImmutableMap(com.google.common.collect.ImmutableMap) Plugin(io.kestra.core.models.annotations.Plugin) Flow(io.kestra.core.models.executions.statistics.Flow) ZonedDateTime(java.time.ZonedDateTime) SuperBuilder(lombok.experimental.SuperBuilder) NotNull(javax.validation.constraints.NotNull) ExecutionCount(io.kestra.core.models.executions.statistics.ExecutionCount) Collectors(java.util.stream.Collectors) lombok(lombok) PluginProperty(io.kestra.core.models.annotations.PluginProperty) State(io.kestra.core.models.flows.State) NotEmpty(javax.validation.constraints.NotEmpty) Task(io.kestra.core.models.tasks.Task) List(java.util.List) RunContext(io.kestra.core.runners.RunContext) Example(io.kestra.core.models.annotations.Example) RunnableTask(io.kestra.core.models.tasks.RunnableTask) ExecutionCount(io.kestra.core.models.executions.statistics.ExecutionCount) ExecutionRepositoryInterface(io.kestra.core.repositories.ExecutionRepositoryInterface) Logger(org.slf4j.Logger)

Example 23 with RunContext

use of io.kestra.core.runners.RunContext in project kestra by kestra-io.

the class AbstractScheduler method computeSchedulable.

private void computeSchedulable(List<Flow> flows) {
    schedulableNextDate = new HashMap<>();
    this.schedulable = flows.stream().filter(flow -> flow.getTriggers() != null && flow.getTriggers().size() > 0).flatMap(flow -> flow.getTriggers().stream().map(trigger -> {
        RunContext runContext = runContextFactory.of(flow, trigger);
        return new FlowWithTrigger(flow, trigger, runContext, conditionService.conditionContext(runContext, flow, null));
    })).filter(flowWithTrigger -> flowWithTrigger.getTrigger() instanceof PollingTriggerInterface).collect(Collectors.toList());
}
Also used : java.util(java.util) RunContextFactory(io.kestra.core.runners.RunContextFactory) Getter(lombok.Getter) QueueInterface(io.kestra.core.queues.QueueInterface) ZonedDateTime(java.time.ZonedDateTime) AbstractTrigger(io.kestra.core.models.triggers.AbstractTrigger) com.google.common.util.concurrent(com.google.common.util.concurrent) ConditionContext(io.kestra.core.models.conditions.ConditionContext) PollingTriggerInterface(io.kestra.core.models.triggers.PollingTriggerInterface) ApplicationContext(io.micronaut.context.ApplicationContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Duration(java.time.Duration) TriggerContext(io.kestra.core.models.triggers.TriggerContext) Logger(org.slf4j.Logger) QueueFactoryInterface(io.kestra.core.queues.QueueFactoryInterface) TaskDefaultService(io.kestra.core.services.TaskDefaultService) ConditionService(io.kestra.core.services.ConditionService) java.util.concurrent(java.util.concurrent) SuperBuilder(lombok.experimental.SuperBuilder) Throwables(com.google.common.base.Throwables) Qualifiers(io.micronaut.inject.qualifiers.Qualifiers) Singleton(jakarta.inject.Singleton) Trigger(io.kestra.core.models.triggers.Trigger) Instant(java.time.Instant) Execution(io.kestra.core.models.executions.Execution) Collectors(java.util.stream.Collectors) InternalException(io.kestra.core.exceptions.InternalException) Slf4j(lombok.extern.slf4j.Slf4j) ChronoUnit(java.time.temporal.ChronoUnit) Stream(java.util.stream.Stream) Await(io.kestra.core.utils.Await) ExecutorsUtils(io.kestra.core.utils.ExecutorsUtils) RunContext(io.kestra.core.runners.RunContext) Flow(io.kestra.core.models.flows.Flow) FlowListenersInterface(io.kestra.core.services.FlowListenersInterface) MetricRegistry(io.kestra.core.metrics.MetricRegistry) AllArgsConstructor(lombok.AllArgsConstructor) Inject(jakarta.inject.Inject) NoArgsConstructor(lombok.NoArgsConstructor) PollingTriggerInterface(io.kestra.core.models.triggers.PollingTriggerInterface) RunContext(io.kestra.core.runners.RunContext)

Example 24 with RunContext

use of io.kestra.core.runners.RunContext in project kestra by kestra-io.

the class ProcessBuilderScriptRunner method run.

public RunResult run(AbstractBash abstractBash, RunContext runContext, Logger logger, Path workingDirectory, List<String> commandsWithInterpreter, Map<String, String> env, AbstractBash.LogSupplier logSupplier, Map<String, Object> additionalVars) throws Exception {
    ProcessBuilder processBuilder = new ProcessBuilder();
    if (env != null && env.size() > 0) {
        Map<String, String> environment = processBuilder.environment();
        environment.putAll(env.entrySet().stream().map(throwFunction(r -> new AbstractMap.SimpleEntry<>(runContext.render(r.getKey(), additionalVars), runContext.render(r.getValue(), additionalVars)))).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
    }
    if (workingDirectory != null) {
        processBuilder.directory(workingDirectory.toFile());
    }
    processBuilder.command(commandsWithInterpreter);
    Process process = processBuilder.start();
    long pid = process.pid();
    logger.debug("Starting command with pid {} [{}]", pid, String.join(" ", commandsWithInterpreter));
    try {
        // logs
        AbstractLogThread stdOut = logSupplier.call(process.getInputStream(), false);
        AbstractLogThread stdErr = logSupplier.call(process.getErrorStream(), true);
        int exitCode = process.waitFor();
        stdOut.join();
        stdErr.join();
        if (exitCode != 0) {
            throw new AbstractBash.BashException(exitCode, stdOut.getLogsCount(), stdErr.getLogsCount());
        } else {
            logger.debug("Command succeed with code " + exitCode);
        }
        return new RunResult(exitCode, stdOut, stdErr);
    } catch (InterruptedException e) {
        logger.warn("Killing process {} for InterruptedException", pid);
        process.destroy();
        throw e;
    }
}
Also used : RunResult(io.kestra.core.tasks.scripts.RunResult) AbstractMap(java.util.AbstractMap) List(java.util.List) Logger(org.slf4j.Logger) Rethrow.throwFunction(io.kestra.core.utils.Rethrow.throwFunction) AbstractLogThread(io.kestra.core.tasks.scripts.AbstractLogThread) RunContext(io.kestra.core.runners.RunContext) Map(java.util.Map) AbstractBash(io.kestra.core.tasks.scripts.AbstractBash) Path(java.nio.file.Path) Collectors(java.util.stream.Collectors) AbstractLogThread(io.kestra.core.tasks.scripts.AbstractLogThread) RunResult(io.kestra.core.tasks.scripts.RunResult)

Example 25 with RunContext

use of io.kestra.core.runners.RunContext in project kestra by kestra-io.

the class NodeTest method requirements.

@Test
void requirements() throws Exception {
    RunContext runContext = runContextFactory.of();
    Map<String, String> files = new HashMap<>();
    files.put("main.js", "require('axios').get('http://google.com').then(r => { console.log('::{\"outputs\": {\"extract\":\"' + r.status + '\"}}::') })");
    files.put("package.json", "{\"dependencies\":{\"axios\":\"^0.20.0\"}}");
    Node node = Node.builder().id("test-node-task").nodePath("node").npmPath("npm").inputFiles(files).build();
    ScriptOutput run = node.run(runContext);
    assertThat(run.getExitCode(), is(0));
    assertThat(run.getVars().get("extract"), is("200"));
}
Also used : ScriptOutput(io.kestra.core.tasks.scripts.ScriptOutput) HashMap(java.util.HashMap) Node(io.kestra.core.tasks.scripts.Node) RunContext(io.kestra.core.runners.RunContext) Test(org.junit.jupiter.api.Test) MicronautTest(io.micronaut.test.extensions.junit5.annotation.MicronautTest)

Aggregations

RunContext (io.kestra.core.runners.RunContext)37 MicronautTest (io.micronaut.test.extensions.junit5.annotation.MicronautTest)31 Test (org.junit.jupiter.api.Test)31 ScriptOutput (io.kestra.core.tasks.scripts.ScriptOutput)21 HashMap (java.util.HashMap)18 Bash (io.kestra.core.tasks.scripts.Bash)11 Python (io.kestra.core.tasks.scripts.Python)9 Node (io.kestra.core.tasks.scripts.Node)7 FileInputStream (java.io.FileInputStream)6 URI (java.net.URI)6 URL (java.net.URL)5 Logger (org.slf4j.Logger)5 Collectors (java.util.stream.Collectors)4 ImmutableMap (com.google.common.collect.ImmutableMap)3 ConditionContext (io.kestra.core.models.conditions.ConditionContext)3 Execution (io.kestra.core.models.executions.Execution)3 Flow (io.kestra.core.models.flows.Flow)3 List (java.util.List)3 Map (java.util.Map)3 PluginProperty (io.kestra.core.models.annotations.PluginProperty)2