Repository navigation
feat(php): add ScriptTrigger and CommandsTrigger #457
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
19d7702
3bd8d4a
8befe84
d0af1ae
464737f
b3a6501
8cbc917
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,280 @@ | ||
| package io.kestra.plugin.scripts.php; | ||
|
|
||
| import java.time.Duration; | ||
| import java.time.Instant; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
| import java.util.Optional; | ||
| import java.util.regex.Matcher; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import io.kestra.core.exceptions.IllegalVariableEvaluationException; | ||
| import io.kestra.core.models.annotations.Example; | ||
| import io.kestra.core.models.annotations.Plugin; | ||
| import io.kestra.core.models.annotations.PluginProperty; | ||
| import io.kestra.core.models.conditions.ConditionContext; | ||
| import io.kestra.core.models.executions.Execution; | ||
| import io.kestra.core.models.property.Property; | ||
| import io.kestra.core.models.tasks.RunnableTaskException; | ||
| import io.kestra.core.models.tasks.runners.TaskException; | ||
| import io.kestra.core.models.triggers.AbstractTrigger; | ||
| import io.kestra.core.models.triggers.PollingTriggerInterface; | ||
| import io.kestra.core.models.triggers.TriggerContext; | ||
| import io.kestra.core.models.triggers.TriggerOutput; | ||
| import io.kestra.core.models.triggers.TriggerService; | ||
| import io.kestra.core.runners.RunContext; | ||
| import io.kestra.core.storages.kv.KVStore; | ||
| import io.kestra.core.storages.kv.KVValueAndMetadata; | ||
| import io.kestra.plugin.scripts.exec.ExitConditionRegex; | ||
| import io.kestra.plugin.scripts.exec.TriggerRunContext; | ||
| import io.kestra.plugin.scripts.exec.scripts.models.ScriptOutput; | ||
| import io.swagger.v3.oas.annotations.media.Schema; | ||
| import jakarta.validation.constraints.NotNull; | ||
| import lombok.AllArgsConstructor; | ||
| import lombok.Builder; | ||
| import lombok.Data; | ||
| import lombok.EqualsAndHashCode; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import lombok.ToString; | ||
| import lombok.experimental.SuperBuilder; | ||
|
|
||
| @SuperBuilder | ||
| @ToString | ||
| @EqualsAndHashCode | ||
| @Getter | ||
| @NoArgsConstructor | ||
| @Schema( | ||
| title = "Trigger a flow when PHP commands match a condition", | ||
| description = """ | ||
| Polls by running PHP commands in a script container (default image php) and emits when exitCondition matches. \ | ||
| Edge mode (the default) emits only on a transition from not matching to matching, remembering the previous result in the namespace KV store. \ | ||
| Polls every 60s by default. Accepts 'exit N' or a regex (fallback substring) matched against emitted vars; a failed run has no vars, so only 'exit N' can match a failure. \ | ||
| Only containerImage, commands, interval, edge, and exitCondition are configurable here; the Commands task's taskRunner, env, beforeCommands, inputFiles, and namespaceFiles are not exposed on this trigger. | ||
| """ | ||
| ) | ||
| @Plugin( | ||
| examples = { | ||
| @Example( | ||
| title = "Trigger when commands fail with an implicit error (exit 1).", | ||
| full = true, | ||
| code = """ | ||
| id: php_commands_trigger | ||
| namespace: company.team | ||
|
|
||
| triggers: | ||
| - id: commands_failure | ||
| type: io.kestra.plugin.scripts.php.CommandsTrigger | ||
| interval: PT60S | ||
| exitCondition: "exit 1" | ||
| edge: true | ||
| containerImage: php | ||
| commands: | ||
| - php -r 'exit(1);' | ||
|
|
||
| tasks: | ||
| - id: log | ||
| type: io.kestra.plugin.core.log.Log | ||
| message: "Triggered with exitCode={{ trigger.exitCode }} (condition={{ trigger.condition }})" | ||
| """ | ||
| ) | ||
| } | ||
| ) | ||
| public class CommandsTrigger extends AbstractTrigger | ||
| implements PollingTriggerInterface, TriggerOutput<CommandsTrigger.Output> { | ||
|
|
||
| private static final String DEFAULT_IMAGE = "php"; | ||
| private static final Pattern EXIT_CONDITION_PATTERN = Pattern.compile("^\\s*exit\\s+(\\d+)\\s*$", Pattern.CASE_INSENSITIVE); | ||
|
|
||
| @Schema( | ||
| title = "Docker image used to execute the commands", | ||
| description = """ | ||
| Container image used by the underlying Commands task to run PHP commands. | ||
| Defaults to 'php'. | ||
| """ | ||
| ) | ||
| @Builder.Default | ||
| @PluginProperty(group = "execution") | ||
| protected Property<String> containerImage = Property.ofValue(DEFAULT_IMAGE); | ||
|
|
||
| @Schema( | ||
| title = "PHP commands to execute", | ||
| description = "Commands executed on each poll (same semantics as the PHP Commands task)." | ||
| ) | ||
| @NotNull | ||
| @PluginProperty(group = "main") | ||
| protected Property<List<String>> commands; | ||
|
|
||
| @Schema( | ||
| title = "Condition to match", | ||
| description = """ | ||
| Condition evaluated after each commands execution. The trigger emits an event only when this condition matches. | ||
|
|
||
| Supported forms: | ||
| - 'exit N' (example: 'exit 1'): matches when the process exit code equals N. | ||
| - Any other string: treated as a regex (or substring if regex is invalid) matched against the | ||
| task's 'vars' (when commands emit ::{"outputs":...}::). On a failed run no vars are available | ||
| to match against, so only an 'exit N' condition can match a failure. | ||
| """ | ||
| ) | ||
| @NotNull | ||
| @PluginProperty(group = "main") | ||
| protected Property<String> exitCondition; | ||
|
|
||
| @Schema( | ||
| title = "Check interval", | ||
| description = "Interval between polling evaluations." | ||
| ) | ||
| @Builder.Default | ||
| @PluginProperty(group = "execution") | ||
| private final Duration interval = Duration.ofSeconds(60); | ||
|
|
||
| @Schema( | ||
| title = "Edge trigger mode", | ||
| description = """ | ||
| If true (default), the trigger emits only on a transition from 'not matching' to 'matching' \ | ||
| (anti-spam). The previous result is kept in the namespace KV store, keyed by flow and trigger id. \ | ||
| If false, the trigger emits on every poll where the condition matches. | ||
| """ | ||
| ) | ||
| @Builder.Default | ||
| @PluginProperty(group = "advanced") | ||
| protected Property<Boolean> edge = Property.ofValue(true); | ||
|
|
||
| @Override | ||
| public Optional<Execution> evaluate(ConditionContext conditionContext, TriggerContext context) throws Exception { | ||
| RunContext runContext = conditionContext.getRunContext(); | ||
| boolean renderedEdge = runContext.render(this.edge).as(Boolean.class).orElse(true); | ||
| String renderedExitCondition = renderExitCondition(runContext); | ||
| Output out = runOnce(runContext, renderedExitCondition); | ||
|
|
||
| boolean matched = matchesCondition(out); | ||
|
|
||
| boolean emit = shouldEmit(runContext, context, renderedEdge, matched); | ||
|
|
||
| if (!emit) { | ||
| return Optional.empty(); | ||
| } | ||
|
|
||
| return Optional.of(TriggerService.generateExecution(this, conditionContext, context, out)); | ||
| } | ||
|
|
||
| boolean shouldEmit(RunContext runContext, TriggerContext context, boolean edge, boolean matched) throws Exception { | ||
| if (!edge) { | ||
| return matched; | ||
| } | ||
|
|
||
| KVStore kvStore = runContext.namespaceKv(context.getNamespace()); | ||
| String key = edgeStateKey(context); | ||
|
|
||
| boolean previouslyMatched = kvStore.getValue(key) | ||
| .map(value -> Boolean.parseBoolean(String.valueOf(value.value()))) | ||
| .orElse(false); | ||
|
|
||
| if (matched != previouslyMatched) { | ||
| kvStore.put(key, new KVValueAndMetadata(null, matched)); | ||
| } | ||
|
|
||
| return matched && !previouslyMatched; | ||
| } | ||
|
|
||
| static String edgeStateKey(TriggerContext context) { | ||
| return "trigger-edge-" + context.getFlowId().length() + "-" + context.getFlowId() + "-" + context.getTriggerId(); | ||
| } | ||
|
|
||
| private String renderExitCondition(RunContext runContext) throws IllegalVariableEvaluationException { | ||
| return ScriptTrigger.renderExitCondition(runContext, this.exitCondition); | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🟡 [Guidelines] Duplicated trigger logic and cross-class static call |
||
| } | ||
|
|
||
| private Output runOnce(RunContext runContext, String renderedExitCondition) throws Exception { | ||
| Commands task = Commands.builder() | ||
| .id(this.getId()) | ||
| .type(Commands.class.getName()) | ||
| .containerImage(this.containerImage) | ||
| .commands(this.commands) | ||
| .build(); | ||
|
|
||
| try { | ||
| ScriptOutput taskOutput = task.run(TriggerRunContext.forEmbeddedTask(runContext, task)); | ||
|
|
||
| return new Output(Instant.now(), renderedExitCondition, taskOutput.getExitCode(), taskOutput.getVars()); | ||
| } catch (RunnableTaskException e) { | ||
| ExtractedFailure failure = extractFailure(e); | ||
| return new Output(Instant.now(), renderedExitCondition, failure.exitCode, null); | ||
| } | ||
| } | ||
|
|
||
| boolean matchesCondition(Output out) { | ||
| String cond = out.getCondition() == null ? "" : out.getCondition().trim(); | ||
|
|
||
| Matcher exitMatcher = EXIT_CONDITION_PATTERN.matcher(cond); | ||
| if (exitMatcher.matches()) { | ||
| try { | ||
| long expected = Long.parseLong(exitMatcher.group(1)); | ||
| return out.getExitCode() != null && out.getExitCode() == expected; | ||
| } catch (NumberFormatException e) { | ||
| return false; | ||
| } | ||
| } | ||
|
|
||
| String haystack = buildHaystack(out); | ||
| if (haystack.isEmpty() || cond.isEmpty()) { | ||
| return false; | ||
| } | ||
|
|
||
| return ExitConditionRegex.find(cond, haystack); | ||
| } | ||
|
|
||
| private String buildHaystack(Output out) { | ||
| if (out.getVars() == null || out.getVars().isEmpty()) { | ||
| return ""; | ||
| } | ||
| return out.getVars().toString(); | ||
| } | ||
|
|
||
| private record ExtractedFailure(Integer exitCode) { | ||
| } | ||
|
|
||
| private ExtractedFailure extractFailure(RunnableTaskException e) { | ||
| Integer exitCode = null; | ||
|
|
||
| Throwable cur = e.getCause(); | ||
| while (cur != null) { | ||
| if (cur instanceof TaskException te) { | ||
| exitCode = te.getExitCode(); | ||
| break; | ||
| } | ||
| cur = cur.getCause(); | ||
| } | ||
|
|
||
| return new ExtractedFailure(exitCode); | ||
| } | ||
|
|
||
| @Data | ||
| @AllArgsConstructor | ||
| public static class Output implements io.kestra.core.models.tasks.Output { | ||
| @Schema(title = "Timestamp of the event that fired the trigger") | ||
| private Instant timestamp; | ||
|
|
||
| @Schema( | ||
| title = "Rendered condition", | ||
| description = "Rendered value of the exitCondition property for this poll." | ||
| ) | ||
| private String condition; | ||
|
|
||
| @Schema( | ||
| title = "Commands exit code", | ||
| description = "Exit code returned by the PHP process (may be null if not available)." | ||
| ) | ||
| private Integer exitCode; | ||
|
|
||
| @Schema( | ||
| title = "Commands vars", | ||
| description = """ | ||
| Vars produced by the task (e.g. via ::{"outputs":{...}}:: convention). May contain sensitive values \ | ||
| from command output; treat trigger payloads accordingly. | ||
| """ | ||
| ) | ||
| private Map<String, Object> vars; | ||
| } | ||
| } | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🟢 [Guidelines] Single-line
@SchemadescriptionsProblem: The
commands,interval(line 126) and bothOutput.exitCodedescriptions (CommandsTrigger.java:267,ScriptTrigger.java:275) use single-line strings instead of"""blocks.Fix: Convert them to text blocks like the other descriptions in the class.