instance_id
stringlengths
17
39
repo
stringclasses
8 values
issue_id
stringlengths
14
34
pr_id
stringlengths
14
34
linking_methods
sequencelengths
1
3
base_commit
stringlengths
40
40
merge_commit
stringlengths
0
40
hints_text
sequencelengths
0
106
resolved_comments
sequencelengths
0
119
created_at
unknown
labeled_as
sequencelengths
0
7
problem_title
stringlengths
7
174
problem_statement
stringlengths
0
55.4k
gold_files
sequencelengths
0
10
gold_files_postpatch
sequencelengths
1
10
test_files
sequencelengths
0
60
gold_patch
stringlengths
220
5.83M
test_patch
stringlengths
386
194k
split_random
stringclasses
3 values
split_time
stringclasses
3 values
issue_start_time
timestamp[ns]
issue_created_at
unknown
issue_by_user
stringlengths
3
21
split_repo
stringclasses
3 values
kestra-io/kestra/933_934
kestra-io/kestra
kestra-io/kestra/933
kestra-io/kestra/934
[ "keyword_pr_to_issue" ]
5c30c0566f76db881104dc74f9f3e26496247d31
e7f2ef78bfa9e1d6cb0e38ee1814db05c6ba8d70
[]
[]
"2023-01-26T20:37:49Z"
[ "bug" ]
Mass actions UI - various issues
### Expected Behavior The new mass actions UI elements should work just fine. ### Actual Behaviour * The 'select all' button doesn't actually select the table rows. * Hitting the alert's cancel button spits an error. * The 'kill' error response spits an error. ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/executions/Executions.vue", "ui/src/utils/axios.js", "webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java" ]
[ "ui/src/components/executions/Executions.vue", "ui/src/utils/axios.js", "webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java" ]
[]
diff --git a/ui/src/components/executions/Executions.vue b/ui/src/components/executions/Executions.vue index 2ba58dd3f3..80acbca251 100644 --- a/ui/src/components/executions/Executions.vue +++ b/ui/src/components/executions/Executions.vue @@ -116,19 +116,19 @@ <bottom-line v-if="executionsSelection.length !== 0 && (canUpdate || canDelete)"> <ul> - <bottom-line-counter v-model="queryBulkAction" :selections="executionsSelection" :total="total" /> + <bottom-line-counter v-model="queryBulkAction" :selections="executionsSelection" :total="total" @update:model-value="selectAll()" /> <li v-if="canUpdate"> - <el-button :icon="Restart" type="success" class="bulk-button" @click="this.restartExecutions()"> + <el-button :icon="Restart" type="success" class="bulk-button" @click="restartExecutions()"> {{ $t('restart') }} </el-button> </li> <li v-if="canUpdate"> - <el-button :icon="StopCircleOutline" type="warning" class="bulk-button" @click="this.killExecutions()"> + <el-button :icon="StopCircleOutline" type="warning" class="bulk-button" @click="killExecutions()"> {{ $t('kill') }} </el-button> </li> <li v-if="canDelete"> - <el-button :icon="Delete" type="danger" class="bulk-button" @click="this.deleteExecutions()"> + <el-button :icon="Delete" type="danger" class="bulk-button" @click="deleteExecutions()"> {{ $t('delete') }} </el-button> </li> @@ -243,6 +243,9 @@ } this.executionsSelection = val.map(x => x.id); }, + selectAll() { + this.$refs.table.toggleAllSelection(); + }, isRunning(item){ return State.isRunning(item.state.current); }, @@ -312,7 +315,8 @@ return {message: this.$t(exec.message, {executionId: exec.invalidValue})} }), this.$t(e.message))) } - } + }, + () => {} ) }, deleteExecutions() { @@ -339,7 +343,8 @@ return {message: this.$t(exec.message, {executionId: exec.invalidValue})} }), this.$t(e.message))) } - } + }, + () => {} ) }, killExecutions() { @@ -366,7 +371,8 @@ return {message: this.$t(exec.message, {executionId: exec.invalidValue})} }), this.$t(e.message))) } - } + }, + () => {} ) }, } diff --git a/ui/src/utils/axios.js b/ui/src/utils/axios.js index b7175e0e25..e1b933508f 100644 --- a/ui/src/utils/axios.js +++ b/ui/src/utils/axios.js @@ -112,8 +112,7 @@ export default (callback, store, router) => { return Promise.reject(errorResponse); } - if (errorResponse.response.status === 422 - && ["invalid bulk kill","invalid bulk delete","invalid bulk restart"].includes(errorResponse.response.data.message)){ + if (errorResponse.response.status === 400){ return Promise.reject(errorResponse.response.data) } diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java b/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java index 852f06280f..6eee14b0b1 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java @@ -306,7 +306,7 @@ public MutableHttpResponse<?> deleteByIds( } } if (invalids.size() > 0) { - return HttpResponse.unprocessableEntity() + return HttpResponse.badRequest() .body(BulkErrorResponse .builder() .message("invalid bulk delete") @@ -635,8 +635,7 @@ public MutableHttpResponse<?> restartByIds( } } if (invalids.size() > 0) { - return HttpResponse.unprocessableEntity() - .body(BulkErrorResponse + return HttpResponse.badRequest(BulkErrorResponse .builder() .message("invalid bulk restart") .invalids(invalids) @@ -792,7 +791,7 @@ public MutableHttpResponse<?> killByIds( Optional<Execution> execution = executionRepository.findById(executionId); if (execution.isPresent() && execution.get().getState().isTerninated()) { invalids.add(ManualConstraintViolation.of( - "Execution already finished", + "execution already finished", executionId, String.class, "execution", @@ -800,7 +799,7 @@ public MutableHttpResponse<?> killByIds( )); } else if (execution.isEmpty()) { invalids.add(ManualConstraintViolation.of( - "Execution not found", + "execution not found", executionId, String.class, "execution", @@ -812,10 +811,9 @@ public MutableHttpResponse<?> killByIds( } if (invalids.size() > 0) { - return HttpResponse.unprocessableEntity() - .body(BulkErrorResponse + return HttpResponse.badRequest(BulkErrorResponse .builder() - .message("Invalid bulk kill") + .message("invalid bulk kill") .invalids(invalids) .build() );
null
train
train
2023-01-26T11:40:46
"2023-01-26T20:37:01Z"
yuri1969
train
kestra-io/kestra/948_949
kestra-io/kestra
kestra-io/kestra/948
kestra-io/kestra/949
[ "keyword_pr_to_issue" ]
88c149da7f658e32d9368ccab20e4014e39166a3
e7f0a1d177bef45c55aa4da3eb07eaa17b0d57cc
[ "I think we should just avoid using a custom name and let docker generate one. There is too many edge cases where it can fail and it didn't add any advantage.\r\n\r\nWDYT @tchiotludo I can provide a PR to remove the container name as it didn't seems to be used by anything.", "2 solutions : \r\n- support resume like kubernetes one [here](https://kestra.io/plugins/plugin-kubernetes/tasks/io.kestra.plugin.kubernetes.PodCreate.html#resume) activated by default.\r\n- randomize the name of the container \r\n\r\nThe first is better I think \r\n", "forgot the previous comment, look at this old issue : [container](https://github.com/kestra-io/kestra/issues/488)\r\n\r\nGo for the randomisation for now, it will avoid this current bug at first \r\n", "@tchiotludo OK, I also think there is possible path where we didn't kill the container, I'll update the code about this part also", "But as I said, if you want to randomize the name of the container, just let Docker do it for us! We don't use the name anywhere." ]
[]
"2023-02-02T13:37:26Z"
[ "bug", "backend" ]
Python task attempts run in the same container
### Expected Behavior When a python task fails, I would like the other attempts to run in another container, as they are new tasks. ### Actual Behaviour When a python task fails, the next attempts of this task run in the same container which causes an error saying that this container is already used. Attempt 2 ERROR 2023-01-31 04:30:02.029 1Status 409: {"message":"Conflict. The container name \"/4k73cyafagoksdsancdrk8-coaching-security-01-python\" is already in use by container \"8256073bdb5da28a5003f0481aaeb239ae40d225e65752fc185acd19a89e3926\". You have to remove (or rename) that container to be able to reuse that name."} ### Steps To Reproduce Run a python task which fails with auto retry ### Environment Information - Kestra Version: 0.5.3 - Operating System (OS / Docker / Kubernetes): Kubernetes - Java Version (If not docker): ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java" ]
[ "core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java" ]
[]
diff --git a/core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java b/core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java index fdd5686210..5f6967ca23 100644 --- a/core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java +++ b/core/src/main/java/io/kestra/core/tasks/scripts/runners/DockerScriptRunner.java @@ -19,11 +19,9 @@ import io.kestra.core.tasks.scripts.AbstractLogThread; import io.kestra.core.tasks.scripts.RunResult; import io.kestra.core.utils.RetryUtils; -import io.kestra.core.utils.Slugify; import io.micronaut.context.ApplicationContext; import io.micronaut.core.convert.format.ReadableBytesTypeConverter; import lombok.SneakyThrows; -import org.apache.commons.lang3.StringUtils; import org.apache.hc.core5.http.ConnectionClosedException; import org.slf4j.Logger; @@ -100,20 +98,6 @@ private static void metadata(RunContext runContext, CreateContainerCmd container Map<String, String> execution = (Map<String, String>) runContext.getVariables().get("execution"); Map<String, String> taskrun = (Map<String, String>) runContext.getVariables().get("taskrun"); - String name = Slugify.of(String.join( - "-", - taskrun.get("id"), - flow.get("id"), - task.get("id") - )); - - if (name.length() > 63) { - name = name.substring(0, 63); - } - - name = StringUtils.stripEnd(name, "-"); - - container.withName(name); container.withLabels(ImmutableMap.of( "flow.kestra.io/id", flow.get("id"), "flow.kestra.io/namespace", flow.get("namespace"), @@ -133,8 +117,6 @@ public RunResult run( AbstractBash.LogSupplier logSupplier, Map<String, Object> additionalVars ) throws Exception { - DockerClient dockerClient = getDockerClient(abstractBash, runContext, workingDirectory); - if (abstractBash.getDockerOptions() == null) { throw new IllegalArgumentException("Missing required dockerOptions properties"); } @@ -143,13 +125,13 @@ public RunResult run( NameParser.ReposTag imageParse = NameParser.parseRepositoryTag(image); try ( - CreateContainerCmd container = dockerClient.createContainerCmd(image); - PullImageCmd pull = dockerClient.pullImageCmd(image); + DockerClient dockerClient = getDockerClient(abstractBash, runContext, workingDirectory); PipedInputStream stdOutInputStream = new PipedInputStream(); PipedOutputStream stdOutOutputStream = new PipedOutputStream(stdOutInputStream); PipedInputStream stdErrInputStream = new PipedInputStream(); PipedOutputStream stdErrOutputStream = new PipedOutputStream(stdErrInputStream); ) { + CreateContainerCmd container = dockerClient.createContainerCmd(image); // properties metadata(runContext, container); HostConfig hostConfig = new HostConfig(); @@ -263,28 +245,30 @@ public RunResult run( // pull image if (abstractBash.getDockerOptions().getPullImage()) { - retryUtils.<Boolean, InternalServerErrorException>of( - Exponential.builder() - .delayFactor(2.0) - .interval(Duration.ofSeconds(5)) - .maxInterval(Duration.ofSeconds(120)) - .maxAttempt(5) - .build() - ).run( - (bool, throwable) -> throwable instanceof InternalServerErrorException || - throwable.getCause() instanceof ConnectionClosedException, - () -> { - String tag = !imageParse.tag.isEmpty() ? imageParse.tag : "latest"; - String repository = pull.getRepository().contains(":") - ? pull.getRepository().split(":")[0] : pull.getRepository(); - pull - .withTag(tag) - .exec(new PullImageResultCallback()) - .awaitCompletion(); - logger.debug("Image pulled [{}:{}]", repository, tag); - return true; - } - ); + try (PullImageCmd pull = dockerClient.pullImageCmd(image)) { + retryUtils.<Boolean, InternalServerErrorException>of( + Exponential.builder() + .delayFactor(2.0) + .interval(Duration.ofSeconds(5)) + .maxInterval(Duration.ofSeconds(120)) + .maxAttempt(5) + .build() + ).run( + (bool, throwable) -> throwable instanceof InternalServerErrorException || + throwable.getCause() instanceof ConnectionClosedException, + () -> { + String tag = !imageParse.tag.isEmpty() ? imageParse.tag : "latest"; + String repository = pull.getRepository().contains(":") + ? pull.getRepository().split(":")[0] : pull.getRepository(); + pull + .withTag(tag) + .exec(new PullImageResultCallback()) + .awaitCompletion(); + logger.debug("Image pulled [{}:{}]", repository, tag); + return true; + } + ); + } } // start container @@ -325,8 +309,6 @@ public void onNext(Frame item) { stdOut.join(); stdErr.join(); - dockerClient.removeContainerCmd(exec.getId()).exec(); - if (exitCode != 0) { throw new AbstractBash.BashException(exitCode, stdOut.getLogsCount(), stdErr.getLogsCount()); } else { @@ -337,9 +319,24 @@ public void onNext(Frame item) { } catch (InterruptedException e) { logger.warn("Killing process {} for InterruptedException", exec.getId()); - dockerClient.killContainerCmd(exec.getId()).exec(); - dockerClient.removeContainerCmd(exec.getId()).exec(); throw e; + } finally { + try { + var inspect = dockerClient.inspectContainerCmd(exec.getId()).exec(); + if (Boolean.TRUE.equals(inspect.getState().getRunning())) { + // kill container as it's still running, this means there was an exception and the container didn't + // come to a normal end. + try { + dockerClient.killContainerCmd(exec.getId()).exec(); + } catch (Exception e) { + logger.error("Unable to kill a running container", e); + } + } + dockerClient.removeContainerCmd(exec.getId()).exec(); + } catch (Exception ignored) { + + } + } } }
null
val
train
2023-02-01T22:17:39
"2023-02-02T10:01:44Z"
soulbah
train
kestra-io/kestra/929_955
kestra-io/kestra
kestra-io/kestra/929
kestra-io/kestra/955
[ "keyword_pr_to_issue" ]
c3ab04e2e63fef002b9cde19b4afb9c89642070c
da2de56022772984c77a24f599414dea1450e308
[]
[]
"2023-02-03T14:49:04Z"
[]
Task Logs: add a logo of the current task
A log tabs of an execution add the logo of the current task type for each rows
[ "ui/src/components/graph/TreeNode.vue", "ui/src/components/logs/LogList.vue", "ui/src/components/plugins/Plugin.vue" ]
[ "ui/src/components/graph/TreeNode.vue", "ui/src/components/logs/LogList.vue", "ui/src/components/plugins/Plugin.vue" ]
[]
diff --git a/ui/src/components/graph/TreeNode.vue b/ui/src/components/graph/TreeNode.vue index 60cc45659a..f66557a1f3 100644 --- a/ui/src/components/graph/TreeNode.vue +++ b/ui/src/components/graph/TreeNode.vue @@ -269,7 +269,7 @@ > .icon { width: 35px; height: 53px; - background: var(--white); + background: var(--bs-white); position: relative; } @@ -279,11 +279,6 @@ border-right: 1px solid var(--bs-border-color); } - .icon { - html.dark & { - background-color: var(--bs-gray-700); - } - } .is-success { background-color: var(--green); diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 143a53d906..19ba6e7779 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -11,7 +11,9 @@ <div class="attempt-number me-1"> {{ $t("attempt") }} {{ index + 1 }} </div> - + <div class="task-icon me-1" v-loading="this.tasksIcons[currentTaskRun.id] === undefined"> + <task-icon :cls="tasksIcons[currentTaskRun.id]" only-icon /> + </div> <div class="task-id flex-grow-1" :id="`attempt-${index}-${currentTaskRun.id}`"> <el-tooltip :persistent="false" transition="" :hide-after="0"> <template #content> @@ -83,10 +85,12 @@ /> <task-edit + :read-only="true" component="el-dropdown-item" :task-id="currentTaskRun.taskId" :flow-id="execution.flowId" :namespace="execution.namespace" + :revision="execution.flowRevision" /> </el-dropdown-menu> </template> @@ -127,6 +131,7 @@ import SubFlowLink from "../flows/SubFlowLink.vue" import TaskEdit from "../flows/TaskEdit.vue"; import Duration from "../layout/Duration.vue"; + import TaskIcon from "../plugins/TaskIcon.vue"; export default { components: { @@ -140,7 +145,8 @@ Status, SubFlowLink, TaskEdit, - Duration + Duration, + TaskIcon }, props: { level: { @@ -173,6 +179,7 @@ showOutputs: {}, showMetrics: {}, fullscreen: false, + tasksIcons: {} }; }, watch: { @@ -189,6 +196,18 @@ if (!this.fullScreenModal) { this.loadLogs(); } + if (this.execution){ + for(let currentTaskRun of this.execution.taskRunList){ + this.$store.dispatch("flow/loadTask", { + namespace: currentTaskRun.namespace, + id: currentTaskRun.flowId, + taskId: currentTaskRun.taskId, + revision: currentTaskRun.revision + }).then(value => { + this.tasksIcons[currentTaskRun.id] = value.type + }) + } + } }, computed: { ...mapState("execution", ["execution", "taskRun", "task", "logs"]), @@ -273,7 +292,7 @@ log.attemptNumber === attemptNumber ); }); - }, + } }, beforeUnmount() { if (this.sse) { @@ -316,6 +335,12 @@ text-overflow: ellipsis; } + .task-icon { + width: 36px; + background: var(--bs-white); + padding: 6px; + } + small { color: var(--bs-gray-500); } diff --git a/ui/src/components/plugins/Plugin.vue b/ui/src/components/plugins/Plugin.vue index c25e5c1981..34681137f7 100644 --- a/ui/src/components/plugins/Plugin.vue +++ b/ui/src/components/plugins/Plugin.vue @@ -101,13 +101,13 @@ mark { background: var(--bs-success); - color: var(--white); + color: var(--bs-white); font-size: var(--font-size-sm); padding: 2px 8px 2px 8px; border-radius: var(--bs-border-radius-sm); * { - color: var(--white) !important; + color: var(--bs-white) !important; } }
null
train
train
2023-02-03T14:45:07
"2023-01-25T20:48:50Z"
tchiotludo
train
kestra-io/kestra/928_956
kestra-io/kestra
kestra-io/kestra/928
kestra-io/kestra/956
[ "keyword_pr_to_issue" ]
c3ab04e2e63fef002b9cde19b4afb9c89642070c
277cdd7c7df333bd34766d475ed8b691ce89c214
[]
[]
"2023-02-03T14:59:51Z"
[ "bug" ]
Task edit don't handle the revision version
On an execution Topology, if I click on task edit, the version will always the last version and don't take the current execution version. We need to - fetch the good version, - disabled the save button - put the editor on readonly - display a warning to explain it's not the last version
[ "ui/src/components/executions/Topology.vue", "ui/src/components/flows/TaskEdit.vue", "ui/src/components/graph/Topology.vue", "ui/src/components/graph/TreeNode.vue", "ui/src/components/graph/nodes/Task.vue", "ui/src/components/logs/LogList.vue", "ui/src/stores/flow.js", "ui/src/translations.json", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "ui/src/components/executions/Topology.vue", "ui/src/components/flows/TaskEdit.vue", "ui/src/components/graph/Topology.vue", "ui/src/components/graph/TreeNode.vue", "ui/src/components/graph/nodes/Task.vue", "ui/src/components/logs/LogList.vue", "ui/src/stores/flow.js", "ui/src/translations.json", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[]
diff --git a/ui/src/components/executions/Topology.vue b/ui/src/components/executions/Topology.vue index 0124f9c1fd..b700224247 100644 --- a/ui/src/components/executions/Topology.vue +++ b/ui/src/components/executions/Topology.vue @@ -1,5 +1,6 @@ <template> <topology + :key="execution.id" v-if="execution && flowGraph" :flow-id="execution.flowId" :namespace="execution.namespace" diff --git a/ui/src/components/flows/TaskEdit.vue b/ui/src/components/flows/TaskEdit.vue index 1577e16598..2a7bd051fa 100644 --- a/ui/src/components/flows/TaskEdit.vue +++ b/ui/src/components/flows/TaskEdit.vue @@ -15,20 +15,30 @@ :append-to-body="true" > <template #footer> - <el-button :icon="ContentSave" @click="saveTask" v-if="canSave" type="primary"> - {{ $t('save') }} - </el-button> + <div v-loading="isLoading"> + <el-button :icon="ContentSave" @click="saveTask" v-if="canSave && !isReadOnly" type="primary"> + {{ $t('save') }} + </el-button> + <el-alert show-icon :closable="false" class="mb-0 mt-3" v-if="revision && isReadOnly" type="warning"> + <strong>{{ $t('seeing old revision', {revision: revision}) }}</strong> + </el-alert> + </div> </template> - <editor - ref="editor" - @save="saveTask" - v-model="taskYaml" - schema-type="task" - :full-height="false" - :navbar="false" - lang="yaml" - /> + <div v-loading="isLoading"> + <editor + v-if="taskYaml" + :read-only="isReadOnly" + ref="editor" + @save="saveTask" + v-model="taskYaml" + schema-type="task" + :full-height="false" + :navbar="false" + lang="yaml" + /> + </div> + </el-drawer> </component> </template> @@ -68,8 +78,15 @@ type: String, required: true }, + revision: { + type: Number, + default: undefined + } }, methods: { + loadWithRevision(taskId){ + return this.$store.dispatch("flow/loadTask", {namespace: this.namespace, id: this.flowId, taskId: taskId, revision: this.revision}); + }, load(taskId) { return YamlUtils.extractTask(this.flow.source, taskId).toString(); }, @@ -97,7 +114,11 @@ onShow() { this.isModalOpen = !this.isModalOpen; if (this.taskId || this.task.id) { - this.taskYaml = this.load(this.taskId ? this.taskId : this.task.id) + if (this.revision) { + this.loadWithRevision(this.taskId || this.task.id).then(value => this.taskYaml = YamlUtils.stringify(value)); + } else { + this.taskYaml = this.load(this.taskId ? this.taskId : this.task.id); + } } else { this.taskYaml = YamlUtils.stringify(this.task); } @@ -118,6 +139,12 @@ ...mapState("auth", ["user"]), canSave() { return canSaveFlowTemplate(true, this.user, {namespace: this.namespace}, "flow"); + }, + isLoading() { + return this.taskYaml === undefined; + }, + isReadOnly() { + return this.flow && this.revision && this.flow.revision !== this.revision } } }; diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 95119f0be9..bc88d32c6d 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -171,6 +171,7 @@ node: node, namespace: props.namespace, flowId: props.flowId, + revision: props.execution ? props.execution.flowRevision : undefined, }, }) } diff --git a/ui/src/components/graph/TreeNode.vue b/ui/src/components/graph/TreeNode.vue index 60cc45659a..f6e466c37b 100644 --- a/ui/src/components/graph/TreeNode.vue +++ b/ui/src/components/graph/TreeNode.vue @@ -7,7 +7,7 @@ <div class="task-content"> <div class="card-header"> <div class="task-title"> - <span>{{ task.id }} {{ state }}</span> + <span>{{ task.id }}</span> </div> </div> <div v-if="task.state" class="status-wrapper"> @@ -66,6 +66,7 @@ :flow-id="flowId" size="small" :namespace="namespace" + :revision="revision" /> </el-button-group> </div> @@ -141,7 +142,10 @@ type: String, required: true }, - + revision: { + type: Number, + default: undefined + }, }, methods: { forwardEvent(type, event) { diff --git a/ui/src/components/graph/nodes/Task.vue b/ui/src/components/graph/nodes/Task.vue index 533d26bea8..c51e5e52bc 100644 --- a/ui/src/components/graph/nodes/Task.vue +++ b/ui/src/components/graph/nodes/Task.vue @@ -44,6 +44,7 @@ :n="data.node" :namespace="data.namespace" :flow-id="data.flowId" + :revision="data.revision" @follow="forwardEvent('follow', $event)" @mouseover="mouseover" @mouseleave="mouseleave" diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 143a53d906..a8f93537d4 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -87,6 +87,7 @@ :task-id="currentTaskRun.taskId" :flow-id="execution.flowId" :namespace="execution.namespace" + :revision="execution.flowRevision" /> </el-dropdown-menu> </template> diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 0d84709d99..8c172a26b8 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -66,7 +66,7 @@ export default { }) }, loadTask({commit}, options) { - return this.$http.get(`/api/v1/flows/${options.namespace}/${options.id}/tasks/${options.taskId}`).then(response => { + return this.$http.get(`/api/v1/flows/${options.namespace}/${options.id}/tasks/${options.taskId}${options.revision ? "?revision=" + options.revision : ""}`).then(response => { commit("setTask", response.data) return response.data; diff --git a/ui/src/translations.json b/ui/src/translations.json index c85cdfb8b4..1b0bebadc0 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -267,7 +267,8 @@ "invalid bulk delete": "Could not delete executions", "execution not found": "Execution <code>{executionId}</code> not found", "execution not in state FAILED": "Execution <code>{executionId}</code> not in state FAILED", - "execution already finished": "Execution <code>{executionId}</code> already finished" + "execution already finished": "Execution <code>{executionId}</code> already finished", + "seeing old revision": "You are seeing an old revision: {revision}" }, "fr": { "id": "Identifiant", @@ -538,7 +539,8 @@ "execution not found": "Execution <code>{executionId}</code> non trouvée", "execution not in state FAILED": "Execution <code>{executionId}</code> n'est pas dans l'état FAILED", "execution already finished": "Execution <code>{executionId}</code> déjà terminée", - "restore revision": "Êtes-vous sur de vouloir restaurer la revision <code>{revision}</code> ?" + "restore revision": "Êtes-vous sur de vouloir restaurer la revision <code>{revision}</code> ?", + "seeing old revision": "Vous visualisez une ancienne revision : {revision}" }, "de": { "id": "Id", @@ -808,6 +810,7 @@ "invalid bulk delete": "Ausführungen konnten nicht gelöscht werden", "execution not found": "Ausführung <code>{executionId}</code> nicht gefunden", "execution not in state FAILED": "Ausführung <code>{executionId}</code> nicht im Status FAILED", - "execution already finished": "Ausführung <code>{executionId}</code> bereits abgeschlossen" + "execution already finished": "Ausführung <code>{executionId}</code> bereits abgeschlossen", + "seeing old revision": "You are seeing an old revision: {revision}" } } diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index ebd79fa682..101f67c918 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -104,10 +104,11 @@ public List<FlowWithSource> revisions( public Task flowTask( @Parameter(description = "The flow namespace") String namespace, @Parameter(description = "The flow id") String id, - @Parameter(description = "The task id") String taskId + @Parameter(description = "The task id") String taskId, + @Parameter(description = "The flow revision") @Nullable @QueryValue(value = "revision") Integer revision ) { return flowRepository - .findById(namespace, id) + .findById(namespace, id, Optional.ofNullable(revision)) .flatMap(flow -> { try { return Optional.of(flow.findTaskByTaskId(taskId));
null
test
train
2023-02-03T14:45:07
"2023-01-25T20:47:42Z"
tchiotludo
train
kestra-io/kestra/903_960
kestra-io/kestra
kestra-io/kestra/903
kestra-io/kestra/960
[ "keyword_pr_to_issue" ]
c3ab04e2e63fef002b9cde19b4afb9c89642070c
69495d748ad25d4a492a32f15eb2416c02ed4d7c
[]
[ "`ctrl + enter` is better I think and more standard ", "We can't find a proper lib for that to be able to add shortcut on the whole application quickly (and don't care about the remove listeners leak ?", "Ugly hack due to VueJS bug where submit is triggered while pressing enter when focus is on input. " ]
"2023-02-06T14:43:02Z"
[ "bug" ]
When attempting a new execution on the UI, pressing enter closes the window
### Expected Behavior Pressing enter should validate the form and trigger the execution ### Actual Behaviour The window gets closed and nothing is executed ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.6.1-SNAPSHOT ### Example flow _No response_
[ "ui/src/components/flows/FlowRun.vue" ]
[ "ui/src/components/flows/FlowRun.vue" ]
[]
diff --git a/ui/src/components/flows/FlowRun.vue b/ui/src/components/flows/FlowRun.vue index 2bcdd34832..d710a98f77 100644 --- a/ui/src/components/flows/FlowRun.vue +++ b/ui/src/components/flows/FlowRun.vue @@ -13,6 +13,7 @@ :prop="input.name" > <el-input + @keydown.enter.prevent v-if="input.type === 'STRING' || input.type === 'URI'" v-model="inputs[input.name]" /> @@ -112,24 +113,38 @@ input.focus() } }, 500) + + this._keyListener = function(e) { + if (e.keyCode === 13 && (e.ctrlKey || e.metaKey)) { + e.preventDefault(); + this.onSubmit(this.$refs.form); + } + }; + + document.addEventListener("keydown", this._keyListener.bind(this)); + }, + beforeUnmount() { + document.removeEventListener("keydown", this._keyListener); }, computed: { ...mapState("flow", ["flow"]), }, methods: { onSubmit(formRef) { - formRef.validate((valid) => { - if (!valid) { - return false; - } + if (formRef) { + formRef.validate((valid) => { + if (!valid) { + return false; + } - executeTask(this, this.flow, this.inputs, { - redirect: this.redirect, - id: this.flow.id, - namespace: this.flow.namespace - }) - this.$emit("executionTrigger"); - }); + executeTask(this, this.flow, this.inputs, { + redirect: this.redirect, + id: this.flow.id, + namespace: this.flow.namespace + }) + this.$emit("executionTrigger"); + }); + } }, onFileChange(input, e) { if (!e.target) {
null
train
train
2023-02-03T14:45:07
"2023-01-17T18:57:29Z"
Melkaz
train
kestra-io/kestra/925_963
kestra-io/kestra
kestra-io/kestra/925
kestra-io/kestra/963
[ "keyword_pr_to_issue" ]
d827c33c6b6b727c46fd743ec6afde81bbf49d2a
c0c7f7f2fe16aa801d94ed358334294d65fc76a6
[]
[]
"2023-02-06T16:11:02Z"
[]
Add a link to select latest revision, when replaying
### Feature description When replaying in the UI, could we have a simple button or link to select the latest revision ? Or maybe order the revisions list by the newest ?
[ "ui/src/components/executions/Restart.vue", "ui/src/translations.json" ]
[ "ui/src/components/executions/Restart.vue", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/executions/Restart.vue b/ui/src/components/executions/Restart.vue index 48b0a00a7b..cdb871f4c5 100644 --- a/ui/src/components/executions/Restart.vue +++ b/ui/src/components/executions/Restart.vue @@ -19,6 +19,9 @@ <el-button @click="isOpen = false"> Cancel </el-button> + <el-button @click="restartLastRevision()"> + {{ $t('replay latest revision') }} + </el-button> <el-button type="primary" @click="restart()"> OK </el-button> @@ -26,23 +29,16 @@ <p v-html="$t(replayOrRestart + ' confirm', {id: execution.id})" /> - <el-form class="text-muted"> - <p>{{ $t("restart change revision") }}</p> + <el-form> + <p class="text-muted">{{ $t("restart change revision") }}</p> <el-form-item :label="$t('revisions')"> - <el-select - v-model="revisionsSelected" - filterable - :persistent="false" - :placeholder="$t('revisions')" - > + <el-select v-model="revisionsSelected"> <el-option v-for="item in revisionsOptions" :key="item.value" :label="item.text" :value="item.value" - > - {{ item.value }} - </el-option> + /> </el-select> </el-form-item> </el-form> @@ -107,6 +103,10 @@ id: this.execution.flowId }) }, + restartLastRevision() { + this.revisionsSelected = this.revisions[this.revisions.length - 1].revision; + this.restart(); + }, restart() { this.isOpen = false @@ -145,12 +145,14 @@ return this.isReplay ? "replay" : "restart"; }, revisionsOptions() { - return (this.revisions || []).map((revision) => { - return { - value: revision.revision, - text: revision.revision + (this.sameRevision(revision.revision) ? " (" + this.$t("current") + ")" : ""), - }; - }); + return (this.revisions || []) + .map((revision) => { + return { + value: revision.revision, + text: revision.revision + (this.sameRevision(revision.revision) ? " (" + this.$t("current") + ")" : ""), + }; + }) + .reverse(); }, enabled() { if (this.isReplay && !(this.user && this.user.isAllowed(permission.EXECUTION, action.CREATE, this.execution.namespace))) { diff --git a/ui/src/translations.json b/ui/src/translations.json index c85cdfb8b4..518518f5cb 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -101,6 +101,7 @@ "restart confirm": "Are you sure to restart execution <code>{id}</code>?", "restart change revision": "You can change the revision that will be used for the new execution.", "replay": "Replay", + "replay latest revision": "Replay using latest revision", "replayed": "Execution is replayed", "replay confirm": "Are you sure to replay this execution <code>{id}</code> and create a new one?", "current": "current", @@ -371,6 +372,7 @@ "restart confirm": "Êtes-vous sur de vouloir relancer <code>{id}</code> ?", "restart change revision": "Vous pouvez changer la révision qui sera utilisé pour la nouvelle execution relancée.", "replay": "Rejouer", + "replay latest revision": "Rejouer avec la dernière révision", "replayed": "Execution est rejouée", "replay confirm": "Êtes-vous sur de vouloir relancer l'exécution <code>{-id}</code> et créer une nouvelle execution ?", "current": "actuel", @@ -642,6 +644,7 @@ "restart confirm": "Möchten Sie die Ausführung <code>{id}</code> wirklich neu starten?", "restart change revision": "Sie können die Revision ändern, diese wird für die neue Ausführung verwendet werden.", "replay": "Wiederholen", + "replay latest revision": "Replay using latest revision", "replayed": "Ausführung wurde wiederholt", "replay confirm": "Möchten Sie diese Ausführung <code>{id}</code> wirklich wiederholen und eine neue erstellen?", "current": "aktuell",
null
train
train
2023-02-06T16:02:42
"2023-01-24T17:37:27Z"
Melkaz
train
kestra-io/kestra/970_986
kestra-io/kestra
kestra-io/kestra/970
kestra-io/kestra/986
[ "keyword_pr_to_issue" ]
d895ec39dc9bf3e4c04f5caad57907f7166f8fda
9f672982fcb5ece9df50f757532f0b4afc8623cb
[]
[]
"2023-02-14T08:52:57Z"
[ "bug" ]
Flow schema validation issue with multiple conditions
### Expected Behavior _No response_ ### Actual Behaviour When using multiple conditions, the flow schema validator shows some warning but the flow works without issue. ![Capture d’écran du 2023-02-09 17-21-35](https://user-images.githubusercontent.com/1819009/217872637-b4b53cd9-f0da-4a65-b41c-bf1926678242.png) ### Steps To Reproduce You can use the example multiple condition flow, it triggers the issue: ```yaml id: trigger-multiplecondition-listener namespace: io.kestra.tests tasks: - id: onlyListener type: io.kestra.core.tasks.debugs.Return format: "let's go " triggers: - id: multipleListenFlow type: io.kestra.core.models.triggers.types.Flow conditions: - id: multiple type: io.kestra.core.models.conditions.types.MultipleCondition window: P1D windowAdvance: P0D conditions: flow-a: type: io.kestra.core.models.conditions.types.ExecutionFlowCondition namespace: io.kestra.tests flowId: trigger-multiplecondition-flow-a flow-b: type: io.kestra.core.models.conditions.types.ExecutionFlowCondition namespace: io.kestra.tests flowId: trigger-multiplecondition-flow-b ``` ### Environment Information - Kestra Version: 0.6.1-SNAPSHOT - Operating System (OS / Docker / Kubernetes): Linux - Java Version (If not docker): 17 ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java", "core/src/main/java/io/kestra/core/models/triggers/types/Flow.java", "core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java", "core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java", "core/src/main/java/io/kestra/core/plugins/PluginScanner.java", "core/src/main/java/io/kestra/core/tasks/flows/Template.java" ]
[ "core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java", "core/src/main/java/io/kestra/core/models/triggers/types/Flow.java", "core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java", "core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java", "core/src/main/java/io/kestra/core/plugins/PluginScanner.java", "core/src/main/java/io/kestra/core/tasks/flows/Template.java" ]
[ "core/src/test/java/io/kestra/core/docs/JsonSchemaGeneratorTest.java", "webserver/src/test/java/io/kestra/webserver/controllers/PluginControllerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java b/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java index ac3225c056..bfeaed4dfc 100644 --- a/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java +++ b/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java @@ -10,6 +10,7 @@ import com.github.victools.jsonschema.generator.impl.DefinitionKey; import com.github.victools.jsonschema.generator.naming.DefaultSchemaDefinitionNamingStrategy; import com.github.victools.jsonschema.module.jackson.JacksonModule; +import com.github.victools.jsonschema.module.jackson.JacksonOption; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationModule; import com.github.victools.jsonschema.module.javax.validation.JavaxValidationOption; import com.github.victools.jsonschema.module.swagger2.Swagger2Module; @@ -60,9 +61,7 @@ public <T> Map<String, Object> schemas(Class<? extends T> cls) { Map<String, Object> map = JacksonMapper.toMap(objectNode); // hack - if (cls == Task.class) { - fixTask(map); - } else if (cls == Flow.class) { + if (cls == Flow.class) { fixFlow(map); } @@ -103,14 +102,6 @@ private void mutateDescription(ObjectNode collectedTypeAttributes) { } } - @SuppressWarnings("unchecked") - private static void fixTask(Map<String, Object> map) { - var definitions = (Map<String, Map<String, Object>>) map.get("definitions"); - var task = (Map<String, Object>) definitions.get("io.kestra.core.models.tasks.Task-2"); - var allOf = (List<Object>) task.get("allOf"); - allOf.remove(1); - } - @SuppressWarnings("unchecked") private static void fixFlow(Map<String, Object> map) { var definitions = (Map<String, Map<String, Object>>) map.get("definitions"); @@ -155,7 +146,7 @@ public <T> Map<String, Object> outputs(Class<T> base, Class<? extends T> cls) { protected <T> void build(SchemaGeneratorConfigBuilder builder, Class<? extends T> cls) { builder - .with(new JacksonModule()) + .with(new JacksonModule(JacksonOption.IGNORE_TYPE_INFO_TRANSFORM)) .with(new JavaxValidationModule( JavaxValidationOption.NOT_NULLABLE_FIELD_IS_REQUIRED, JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS @@ -164,7 +155,8 @@ protected <T> void build(SchemaGeneratorConfigBuilder builder, Class<? extends T .with(Option.DEFINITIONS_FOR_ALL_OBJECTS) .with(Option.DEFINITION_FOR_MAIN_SCHEMA) .with(Option.PLAIN_DEFINITION_KEYS) - .with(Option.ALLOF_CLEANUP_AT_THE_END); + .with(Option.ALLOF_CLEANUP_AT_THE_END) + .with(Option.MAP_VALUES_AS_ADDITIONAL_PROPERTIES); // default value builder.forFields().withDefaultResolver(this::defaults); diff --git a/core/src/main/java/io/kestra/core/models/triggers/types/Flow.java b/core/src/main/java/io/kestra/core/models/triggers/types/Flow.java index 4641b7d1d1..ec0c443af2 100644 --- a/core/src/main/java/io/kestra/core/models/triggers/types/Flow.java +++ b/core/src/main/java/io/kestra/core/models/triggers/types/Flow.java @@ -1,5 +1,6 @@ package io.kestra.core.models.triggers.types; +import io.kestra.core.models.annotations.PluginProperty; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import lombok.experimental.SuperBuilder; @@ -73,6 +74,7 @@ public class Flow extends AbstractTrigger implements TriggerOutput<Flow.Output> "So you will need to go to Logs tabs on the ui to understand the error\n" + ":::" ) + @PluginProperty private Map<String, Object> inputs; public Optional<Execution> evaluate(RunContext runContext, io.kestra.core.models.flows.Flow flow, Execution current) { diff --git a/core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java b/core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java index 4091f4bbf2..1fc1015e76 100644 --- a/core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java +++ b/core/src/main/java/io/kestra/core/models/triggers/types/Schedule.java @@ -125,12 +125,13 @@ public class Schedule extends AbstractTrigger implements PollingTriggerInterface "* `@midnight`\n" + "* `@hourly`" ) + @PluginProperty private String cron; @Schema( title = "The time zone id to use for evaluate cron. Default value is the server default zone id." ) - @PluginProperty(dynamic = false) + @PluginProperty @Builder.Default private String timezone = ZoneId.systemDefault().toString(); @@ -140,6 +141,7 @@ public class Schedule extends AbstractTrigger implements PollingTriggerInterface "\n" + "Backfill will do all schedules between define date & current date and will start after the normal schedule." ) + @PluginProperty private ScheduleBackfill backfill; @Builder.Default @@ -149,6 +151,7 @@ public class Schedule extends AbstractTrigger implements PollingTriggerInterface @Schema( title = "List of schedule Conditions in order to limit schedule date." ) + @PluginProperty private List<ScheduleCondition> scheduleConditions; @Schema( @@ -161,6 +164,7 @@ public class Schedule extends AbstractTrigger implements PollingTriggerInterface title = "The maximum late delay accepted", description = "If the schedule didn't start after this delay, the execution will be skip." ) + @PluginProperty private Duration lateMaximumDelay; @Getter(AccessLevel.NONE) diff --git a/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java b/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java index 7993d45f89..a7971c7a9e 100644 --- a/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java +++ b/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import io.kestra.core.models.annotations.PluginProperty; import io.micronaut.http.HttpRequest; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; @@ -69,8 +70,10 @@ public class Webhook extends AbstractTrigger implements TriggerOutput<Webhook.Ou "\n" + "::: warning\n" + "Take care when using manual key, the key is the only security to protect your webhook and must be considered as a secret !\n" + - ":::\n" + ":::\n", + defaultValue = "<generated-hash>" ) + @PluginProperty private final String key = IdUtils.create(); public Optional<Execution> evaluate(HttpRequest<String> request, io.kestra.core.models.flows.Flow flow) { diff --git a/core/src/main/java/io/kestra/core/plugins/PluginScanner.java b/core/src/main/java/io/kestra/core/plugins/PluginScanner.java index 90085f8495..189557cc3a 100644 --- a/core/src/main/java/io/kestra/core/plugins/PluginScanner.java +++ b/core/src/main/java/io/kestra/core/plugins/PluginScanner.java @@ -8,6 +8,7 @@ import io.micronaut.core.beans.BeanIntrospectionReference; import io.micronaut.core.io.service.SoftServiceLoader; import io.micronaut.http.annotation.Controller; +import io.swagger.v3.oas.annotations.Hidden; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; @@ -113,6 +114,10 @@ private RegisteredPlugin scanClassLoader(final ClassLoader classLoader, External continue; } + if(beanType.isAnnotationPresent(Hidden.class)) { + continue; + } + if (Task.class.isAssignableFrom(beanType)) { tasks.add(beanType); } diff --git a/core/src/main/java/io/kestra/core/tasks/flows/Template.java b/core/src/main/java/io/kestra/core/tasks/flows/Template.java index 32e06077b8..3efcde2b07 100644 --- a/core/src/main/java/io/kestra/core/tasks/flows/Template.java +++ b/core/src/main/java/io/kestra/core/tasks/flows/Template.java @@ -22,6 +22,7 @@ import io.micronaut.context.ApplicationContext; import io.micronaut.context.event.StartupEvent; import io.micronaut.runtime.event.annotation.EventListener; +import io.swagger.v3.oas.annotations.Hidden; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; import lombok.experimental.SuperBuilder; @@ -198,6 +199,7 @@ protected io.kestra.core.models.templates.Template findTemplate(ApplicationConte @Getter @NoArgsConstructor @AllArgsConstructor + @Hidden public static class ExecutorTemplate extends Template { private io.kestra.core.models.templates.Template template;
diff --git a/core/src/test/java/io/kestra/core/docs/JsonSchemaGeneratorTest.java b/core/src/test/java/io/kestra/core/docs/JsonSchemaGeneratorTest.java index d90d5143d5..12fb69f16a 100644 --- a/core/src/test/java/io/kestra/core/docs/JsonSchemaGeneratorTest.java +++ b/core/src/test/java/io/kestra/core/docs/JsonSchemaGeneratorTest.java @@ -69,12 +69,11 @@ void flow() throws URISyntaxException { Map<String, Object> generate = jsonSchemaGenerator.schemas(Flow.class); var definitions = (Map<String, Map<String, Object>>) generate.get("definitions"); - var flow = definitions.get("io.kestra.core.models.flows.Flow"); assertThat((List<String>) flow.get("required"), not(contains("deleted"))); assertThat((List<String>) flow.get("required"), hasItems("id", "namespace", "tasks")); - var bash = definitions.get("io.kestra.core.tasks.scripts.Bash-1"); + var bash = definitions.get("io.kestra.core.tasks.scripts.Bash"); assertThat((List<String>) bash.get("required"), not(contains("exitOnFailed"))); assertThat((String) ((Map<String, Map<String, Object>>) bash.get("properties")).get("exitOnFailed").get("markdownDescription"), containsString("Default value is : `true`")); assertThat(((String) ((Map<String, Map<String, Object>>) bash.get("properties")).get("exitOnFailed").get("markdownDescription")).startsWith("This tells bash that"), is(true)); @@ -82,9 +81,7 @@ void flow() throws URISyntaxException { assertThat((String) bash.get("markdownDescription"), containsString("Bash with some inputs files")); assertThat((String) bash.get("markdownDescription"), containsString("outputFiles.first")); - var bashType = definitions.get("io.kestra.core.tasks.scripts.Bash-2"); - - var python = definitions.get("io.kestra.core.tasks.scripts.Python-1"); + var python = definitions.get("io.kestra.core.tasks.scripts.Python"); assertThat((List<String>) python.get("required"), not(contains("exitOnFailed"))); }); } @@ -98,10 +95,10 @@ void task() throws URISyntaxException { Map<String, Object> generate = jsonSchemaGenerator.schemas(Task.class); var definitions = (Map<String, Map<String, Object>>) generate.get("definitions"); - var task = (Map<String, Object>) definitions.get("io.kestra.core.models.tasks.Task-2"); - var allOf = (List<Object>) task.get("allOf"); + var task = (Map<String, Object>) definitions.get("io.kestra.core.models.tasks.Task"); + var anyOf = (List<Object>) task.get("anyOf"); - assertThat(allOf.size(), is(1)); + assertThat(anyOf.size(), greaterThanOrEqualTo(31)); //31 in local but 56 in CI }); } @@ -115,7 +112,7 @@ void bash() throws URISyntaxException { var definitions = (Map<String, Map<String, Object>>) generate.get("definitions"); - var bash = definitions.get("io.kestra.core.tasks.scripts.Bash-1"); + var bash = definitions.get("io.kestra.core.tasks.scripts.Bash"); assertThat((List<String>) bash.get("required"), not(contains("exitOnFailed"))); assertThat((List<String>) bash.get("required"), not(contains("interpreter"))); }); @@ -124,7 +121,6 @@ void bash() throws URISyntaxException { @Test void testEnum() { Map<String, Object> generate = jsonSchemaGenerator.properties(Task.class, TaskWithEnum.class); - System.out.println(generate); assertThat(generate, is(not(nullValue()))); assertThat(((Map<String, Map<String, Object>>) generate.get("properties")).size(), is(3)); } diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/PluginControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/PluginControllerTest.java index 4fe12c16a9..1133c4a8b7 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/PluginControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/PluginControllerTest.java @@ -132,7 +132,7 @@ void task() throws URISyntaxException { Argument.mapOf(String.class, Object.class) ); - assertThat(doc.get("$ref"), is("#/definitions/io.kestra.core.models.tasks.Task-2")); + assertThat(doc.get("$ref"), is("#/definitions/io.kestra.core.models.tasks.Task")); }); } }
train
train
2023-02-15T22:11:53
"2023-02-09T16:22:16Z"
loicmathieu
train
kestra-io/kestra/1039_1040
kestra-io/kestra
kestra-io/kestra/1039
kestra-io/kestra/1040
[ "keyword_pr_to_issue" ]
10c5d65c5111a993682434b419e9b6e5ba2e55c1
c8d32f0f34c70aca2da4cb256d5517b7f8b66e38
[]
[ "```suggestion\r\n description = \"If null and no timeout, a manual approval is needed, if not, the delay before continuing the execution\"\r\n```", "```suggestion\r\n description = \"If null and no delay, a manual approval is needed, else a manual approval is needed before the timeout or the task will fail\"\r\n```" ]
"2023-03-03T16:55:45Z"
[]
Enable setting a timeout for the Pause task
### Feature description The [Pause](https://kestra.io/plugins/core/tasks/flows/io.kestra.core.tasks.flows.Pause.html) task should be able to fail when being paused past given time interval. This feature could be used to notify operators about executions having their required resume action due. This can be achieved by adding the `timeout` property for the task.
[ "core/src/main/java/io/kestra/core/runners/ExecutionDelay.java", "core/src/main/java/io/kestra/core/runners/ExecutorService.java", "core/src/main/java/io/kestra/core/tasks/flows/Pause.java", "jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java", "runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java" ]
[ "core/src/main/java/io/kestra/core/runners/ExecutionDelay.java", "core/src/main/java/io/kestra/core/runners/ExecutorService.java", "core/src/main/java/io/kestra/core/tasks/flows/Pause.java", "jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java", "runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java" ]
[ "core/src/test/java/io/kestra/core/Helpers.java", "core/src/test/java/io/kestra/core/tasks/flows/PauseTest.java", "core/src/test/resources/flows/valids/pause-timeout.yaml", "jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java", "webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/runners/ExecutionDelay.java b/core/src/main/java/io/kestra/core/runners/ExecutionDelay.java index 6b43d82e80..7d3f17dc5b 100644 --- a/core/src/main/java/io/kestra/core/runners/ExecutionDelay.java +++ b/core/src/main/java/io/kestra/core/runners/ExecutionDelay.java @@ -1,5 +1,6 @@ package io.kestra.core.runners; +import io.kestra.core.models.flows.State; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Value; @@ -19,4 +20,6 @@ public class ExecutionDelay { @NotNull Instant date; + + @NotNull State.Type state; } diff --git a/core/src/main/java/io/kestra/core/runners/ExecutorService.java b/core/src/main/java/io/kestra/core/runners/ExecutorService.java index 09dc341ecf..0fb6023b6f 100644 --- a/core/src/main/java/io/kestra/core/runners/ExecutorService.java +++ b/core/src/main/java/io/kestra/core/runners/ExecutorService.java @@ -386,11 +386,12 @@ private Executor handlePausedDelay(Executor executor, List<WorkerTaskResult> wor if (task instanceof Pause) { Pause pauseTask = (Pause) task; - if (pauseTask.getDelay() != null) { + if (pauseTask.getDelay() != null || pauseTask.getTimeout() != null) { return ExecutionDelay.builder() .taskRunId(workerTaskResult.getTaskRun().getId()) .executionId(executor.getExecution().getId()) - .date(workerTaskResult.getTaskRun().getState().maxDate().plus(pauseTask.getDelay())) + .date(workerTaskResult.getTaskRun().getState().maxDate().plus(pauseTask.getDelay() != null ? pauseTask.getDelay() : pauseTask.getTimeout())) + .state(pauseTask.getDelay() != null ? State.Type.RUNNING : State.Type.FAILED) .build(); } } diff --git a/core/src/main/java/io/kestra/core/tasks/flows/Pause.java b/core/src/main/java/io/kestra/core/tasks/flows/Pause.java index 7c68e2ac27..49846d4677 100644 --- a/core/src/main/java/io/kestra/core/tasks/flows/Pause.java +++ b/core/src/main/java/io/kestra/core/tasks/flows/Pause.java @@ -58,11 +58,18 @@ public class Pause extends Sequential implements FlowableTask<VoidOutput> { @Schema( title = "Duration of the pause.", - description = "If null, a manual approval is need, if not, the delay before automatically continue the execution" + description = "If null and no timeout, a manual approval is needed, if not, the delay before continuing the execution" ) @PluginProperty private Duration delay; + @Schema( + title = "Timeout of the pause.", + description = "If null and no delay, a manual approval is needed, else a manual approval is needed before the timeout or the task will fail" + ) + @PluginProperty + private Duration timeout; + @Override public List<NextTaskRun> resolveNexts(RunContext runContext, Execution execution, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { if (this.needPause(parentTaskRun) || parentTaskRun.getState().getCurrent() == State.Type.PAUSED) { diff --git a/jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java b/jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java index dbc3236ae1..89328c8ea9 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java +++ b/jdbc/src/main/java/io/kestra/jdbc/runner/JdbcExecutor.java @@ -443,13 +443,16 @@ private void executionDelaySend() { Executor executor = new Executor(pair.getLeft(), null); try { - Execution markAsExecution = executionService.markAs( - pair.getKey(), - executionDelay.getTaskRunId(), - State.Type.RUNNING - ); + if (executor.getExecution().findTaskRunByTaskRunId(executionDelay.getTaskRunId()).getState().getCurrent() == State.Type.PAUSED) { + + Execution markAsExecution = executionService.markAs( + pair.getKey(), + executionDelay.getTaskRunId(), + executionDelay.getState() + ); - executor = executor.withExecution(markAsExecution, "pausedRestart"); + executor = executor.withExecution(markAsExecution, "pausedRestart"); + } } catch (Exception e) { executor = handleFailedExecutionFromExecutor(executor, e); } diff --git a/runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java b/runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java index 092e344d4e..3b533802e2 100644 --- a/runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java +++ b/runner-memory/src/main/java/io/kestra/runner/memory/MemoryExecutor.java @@ -184,13 +184,15 @@ private void handleExecution(ExecutionState state) { try { ExecutionState executionState = EXECUTIONS.get(workerTaskResultDelay.getExecutionId()); - Execution markAsExecution = executionService.markAs( - executionState.execution, - workerTaskResultDelay.getTaskRunId(), - State.Type.RUNNING - ); - - executionQueue.emit(markAsExecution); + if (executionState.execution.findTaskRunByTaskRunId(workerTaskResultDelay.getTaskRunId()).getState().getCurrent() == State.Type.PAUSED) { + Execution markAsExecution = executionService.markAs( + executionState.execution, + workerTaskResultDelay.getTaskRunId(), + workerTaskResultDelay.getState() + ); + + executionQueue.emit(markAsExecution); + } } catch (Exception e) { throw new RuntimeException(e); }
diff --git a/core/src/test/java/io/kestra/core/Helpers.java b/core/src/test/java/io/kestra/core/Helpers.java index 0e606b9489..82d12159cd 100644 --- a/core/src/test/java/io/kestra/core/Helpers.java +++ b/core/src/test/java/io/kestra/core/Helpers.java @@ -19,7 +19,7 @@ import java.util.function.Consumer; public class Helpers { - public static long FLOWS_COUNT = 52; + public static long FLOWS_COUNT = 53; public static ApplicationContext applicationContext() throws URISyntaxException { return applicationContext( diff --git a/core/src/test/java/io/kestra/core/tasks/flows/PauseTest.java b/core/src/test/java/io/kestra/core/tasks/flows/PauseTest.java index d61455e50d..44c419ff4b 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/PauseTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/PauseTest.java @@ -31,10 +31,15 @@ void run() throws Exception { } @Test - void failed() throws Exception { + void delay() throws Exception { suite.runDelay(runnerUtils); } + @Test + void timeout() throws Exception { + suite.runTimeout(runnerUtils); + } + @Singleton public static class Suite { @Inject @@ -87,6 +92,25 @@ public void runDelay(RunnerUtils runnerUtils) throws Exception { assertThat(execution.getTaskRunList().get(0).getState().getHistories().stream().filter(history -> history.getState() == State.Type.RUNNING).count(), is(2L)); assertThat(execution.getTaskRunList(), hasSize(3)); } - } + + public void runTimeout(RunnerUtils runnerUtils) throws Exception { + Execution execution = runnerUtils.runOne("io.kestra.tests", "pause-timeout"); + + assertThat(execution.getState().getCurrent(), is(State.Type.PAUSED)); + assertThat(execution.getTaskRunList().get(0).getState().getCurrent(), is(State.Type.PAUSED)); + assertThat(execution.getTaskRunList(), hasSize(1)); + + execution = runnerUtils.awaitExecution( + e -> e.getState().getCurrent() == State.Type.FAILED, + () -> {}, + Duration.ofSeconds(30) + ); + + assertThat(execution.getTaskRunList().get(0).getState().getHistories().stream().filter(history -> history.getState() == State.Type.PAUSED).count(), is(1L)); + assertThat(execution.getTaskRunList().get(0).getState().getHistories().stream().filter(history -> history.getState() == State.Type.RUNNING).count(), is(1L)); + assertThat(execution.getTaskRunList().get(0).getState().getHistories().stream().filter(history -> history.getState() == State.Type.FAILED).count(), is(1L)); + assertThat(execution.getTaskRunList(), hasSize(1)); + } + } } \ No newline at end of file diff --git a/core/src/test/resources/flows/valids/pause-timeout.yaml b/core/src/test/resources/flows/valids/pause-timeout.yaml new file mode 100644 index 0000000000..4afe6d08e1 --- /dev/null +++ b/core/src/test/resources/flows/valids/pause-timeout.yaml @@ -0,0 +1,15 @@ +id: pause-timeout +namespace: io.kestra.tests + +tasks: + - id: pause + type: io.kestra.core.tasks.flows.Pause + timeout: PT1S + tasks: + - id: ko + type: io.kestra.core.tasks.scripts.Bash + commands: + - echo "trigger 1 seconds pause" + - id: last + type: io.kestra.core.tasks.debugs.Return + format: "{{task.id}} > {{taskrun.startDate}}" diff --git a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java index 0b34d04d02..7447ad4a1d 100644 --- a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java +++ b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java @@ -227,4 +227,9 @@ public void pauseRun() throws Exception { public void pauseRunDelay() throws Exception { pauseTest.runDelay(runnerUtils); } + + @Test + public void pauseRunTimeout() throws Exception { + pauseTest.runTimeout(runnerUtils); + } } diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java index 49d4269550..eb5c3f952c 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java @@ -481,7 +481,7 @@ void exportByQuery() throws IOException { Files.write(file.toPath(), zip); try (ZipFile zipFile = new ZipFile(file)) { - assertThat(zipFile.stream().count(), is(52L)); + assertThat(zipFile.stream().count(), is(Helpers.FLOWS_COUNT)); } file.delete();
val
train
2023-03-02T22:36:43
"2023-03-03T15:31:26Z"
yuri1969
train
kestra-io/kestra/1046_1055
kestra-io/kestra
kestra-io/kestra/1046
kestra-io/kestra/1055
[ "keyword_pr_to_issue" ]
4bd1ba242a45aded271c18b2fb57580ec7efdd7f
e5204025239be58b0520c3d4a9398d9532d2583a
[ "Ideas:\r\n\r\n```yaml\r\ntype: io.kestra.core.task.log.Log\r\nlevel: INFO\r\nmessage: \"Hello World\"\r\n```\r\n\r\n```yaml\r\ntype: io.kestra.core.task.log.Log\r\nlevel: INFO\r\nmessage: \r\n - \"Hello World\"\r\n - \"Hello Kestra\"\r\n```" ]
[ "```suggestion\r\n } else if (this.message instanceof Collection) {\r\n```", "```suggestion\r\n messages.forEach(throwConsumer(message -> {\r\n```\r\n\r\nnever use this, throw `RuntimeException` is a pain \r\n```java\r\n try {\r\n render = runContext.render(message);\r\n } catch (IllegalVariableEvaluationException e) {\r\n throw new RuntimeException(e);\r\n }\r\n \r\n```", "to avoid duplication make the `Echo` task call the `Log` one \r\n ", "You should also add an example with a list of message", "misses `@Shema` with a description", "misses `@Shema` with a description, don't forget to add an `anyOff`.", "```suggestion\r\n title = \"Task that log a message in the execution log.\",\r\n```", "I think you can remove this description, people know the purpose of a log", "```suggestion\r\n String[].class\r\n```", "Thanks to this the JSON schema will know that the item in the list must be strings", "```suggestion\r\n Collection<String> messages = (Collection<String>) this.message;\r\n```", "Don't cast on implementation, always prefere to use the interface.\r\nIf Collection didn't fit, use List instead.\r\nIt's a principle called \"coding against interface\" ", "Should be in the log package not the debug package (the same where the Fetch task will be)" ]
"2023-03-10T10:54:02Z"
[]
Rename the Echo task to Log
### Feature description Rename the Echo task to Log as it's a log and not an echo. It should also be better to live in a different package as it's not a debug per see. Naming task is important now that we have autocomplete! In the meantime, we can improve it (like allowing log of multiple message at once).
[ "core/src/main/java/io/kestra/core/tasks/debugs/Echo.java", "ui/src/components/onboarding/VueTour.vue" ]
[ "core/src/main/java/io/kestra/core/tasks/debugs/Echo.java", "core/src/main/java/io/kestra/core/tasks/log/Log.java", "core/src/main/resources/icons/io.kestra.core.tasks.log.Log.svg", "ui/src/components/onboarding/VueTour.vue" ]
[ "core/src/test/java/io/kestra/core/runners/RunContextTest.java", "core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java", "core/src/test/resources/flows/invalids/duplicate-parallel.yaml", "core/src/test/resources/flows/tests/invalid-task-defaults.yaml", "core/src/test/resources/flows/tests/with-template.yaml", "core/src/test/resources/flows/valids/bash-warning.yaml", "core/src/test/resources/flows/valids/disable-error.yaml", "core/src/test/resources/flows/valids/disable-simple.yaml", "core/src/test/resources/flows/valids/errors.yaml", "core/src/test/resources/flows/valids/full.yaml", "core/src/test/resources/flows/valids/logs.yaml", "core/src/test/resources/flows/valids/restart_always_failed.yaml", "core/src/test/resources/flows/valids/restart_local_errors.yaml", "core/src/test/resources/flows/valids/retry-failed.yaml", "core/src/test/resources/flows/valids/retry-success.yaml", "jdbc/src/test/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepositoryTest.java", "webserver/src/test/java/io/kestra/webserver/controllers/ErrorControllerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/tasks/debugs/Echo.java b/core/src/main/java/io/kestra/core/tasks/debugs/Echo.java index 31611604ca..2e8e0cb94b 100644 --- a/core/src/main/java/io/kestra/core/tasks/debugs/Echo.java +++ b/core/src/main/java/io/kestra/core/tasks/debugs/Echo.java @@ -1,6 +1,7 @@ package io.kestra.core.tasks.debugs; import io.kestra.core.models.annotations.PluginProperty; +import io.kestra.core.tasks.log.Log; import io.micronaut.core.annotation.NonNull; import io.swagger.v3.oas.annotations.media.Schema; import lombok.*; @@ -11,7 +12,6 @@ import io.kestra.core.models.tasks.Task; import io.kestra.core.models.tasks.VoidOutput; import io.kestra.core.runners.RunContext; -import org.slf4j.Logger; import org.slf4j.event.Level; import javax.validation.constraints.NotBlank; @@ -36,6 +36,7 @@ ) } ) +@Deprecated public class Echo extends Task implements RunnableTask<VoidOutput> { @NonNull @NotBlank @@ -48,30 +49,11 @@ public class Echo extends Task implements RunnableTask<VoidOutput> { @Override public VoidOutput run(RunContext runContext) throws Exception { - Logger logger = runContext.logger(); - - String render = runContext.render(this.format); - - switch (this.level) { - case TRACE: - logger.trace(render); - break; - case DEBUG: - logger.debug(render); - break; - case INFO: - logger.info(render); - break; - case WARN: - logger.warn(render); - break; - case ERROR: - logger.error(render); - break; - default: - throw new IllegalArgumentException("Invalid log level '" + this.level + "'"); - } - + Log log = Log.builder() + .level(this.level) + .message(this.format) + .build(); + log.run(runContext); return null; } } diff --git a/core/src/main/java/io/kestra/core/tasks/log/Log.java b/core/src/main/java/io/kestra/core/tasks/log/Log.java new file mode 100644 index 0000000000..05f85ee75a --- /dev/null +++ b/core/src/main/java/io/kestra/core/tasks/log/Log.java @@ -0,0 +1,113 @@ +package io.kestra.core.tasks.log; + +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.tasks.RunnableTask; +import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.tasks.VoidOutput; +import io.kestra.core.runners.RunContext; +import io.micronaut.core.annotation.NonNull; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.slf4j.Logger; +import org.slf4j.event.Level; + +import javax.validation.constraints.NotBlank; +import java.util.Collection; + +import static io.kestra.core.utils.Rethrow.throwConsumer; + +@SuperBuilder +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Schema( + title = "Log a message in the task logs" +) +@Plugin( + examples = { + @Example( + code = { + "level: WARN", + "message: \"{{task.id}} > {{taskrun.startDate}}\"" + } + ), + @Example( + code = { + "level: WARN", + "message: " + + " - 'Task id : \"{{task.id}}\"'" + + " - 'Start date: \"{{taskrun.startDate}}\"'" + } + ) + } +) +public class Log extends Task implements RunnableTask<VoidOutput> { + @Schema( + title = "The message(s) to log", + description = "Can be a string or an array of string", + anyOf = { + String.class, + String[].class + } + ) + @NonNull + @NotBlank + @PluginProperty(dynamic = true) + private Object message; + + @Schema( + title = "The log level" + ) + @Builder.Default + @PluginProperty + private Level level = Level.INFO; + + @Override + public VoidOutput run(RunContext runContext) throws Exception { + Logger logger = runContext.logger(); + + if(this.message instanceof String) { + String render = runContext.render((String) this.message); + this.log(logger, this.level, render); + } else if (this.message instanceof Collection) { + Collection<String> messages = (Collection<String>) this.message; + messages.forEach(throwConsumer(message -> { + String render; + render = runContext.render(message); + this.log(logger, this.level, render); + })); + } else { + throw new IllegalArgumentException("Invalid message type '" + this.message.getClass() + "'"); + } + + return null; + } + + public void log(Logger logger, Level level, String message) { + switch (this.level) { + case TRACE: + logger.trace(message); + break; + case DEBUG: + logger.debug(message); + break; + case INFO: + logger.info(message); + break; + case WARN: + logger.warn(message); + break; + case ERROR: + logger.error(message); + break; + default: + throw new IllegalArgumentException("Invalid log level '" + this.level + "'"); + } + } +} + + diff --git a/core/src/main/resources/icons/io.kestra.core.tasks.log.Log.svg b/core/src/main/resources/icons/io.kestra.core.tasks.log.Log.svg new file mode 100644 index 0000000000..6d751be7f4 --- /dev/null +++ b/core/src/main/resources/icons/io.kestra.core.tasks.log.Log.svg @@ -0,0 +1,7 @@ +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24" height="24" + preserveAspectRatio="xMidYMid meet" viewBox="0 0 24 24" + style="-ms-transform: rotate(360deg); -webkit-transform: rotate(360deg); transform: rotate(360deg);"> + <path + d="M18 7c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2v-4h-2v4h-2V9h4V7h-4M2 7v10h6v-2H4V7H2m9 0c-1.1 0-2 .9-2 2v6c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2h-2m0 2h2v6h-2V9z" + fill="#0D1523"/> +</svg> \ No newline at end of file diff --git a/ui/src/components/onboarding/VueTour.vue b/ui/src/components/onboarding/VueTour.vue index fbee908d59..271bc874ee 100644 --- a/ui/src/components/onboarding/VueTour.vue +++ b/ui/src/components/onboarding/VueTour.vue @@ -318,8 +318,8 @@ " # " + this.$t("onboarding-flow.taskLog1") + "\n" + " # " + this.$t("onboarding-flow.taskLog2") + "\n" + " - id: log\n" + - " type: io.kestra.core.tasks.debugs.Echo\n" + - " format: The flow starts", + " type: io.kestra.core.tasks.log.Log\n" + + " message: The flow starts", " # " + this.$t("onboarding-flow.taskDL") + "\n" + " - id: downloadData\n" + " type: io.kestra.plugin.fs.http.Download\n" +
diff --git a/core/src/test/java/io/kestra/core/runners/RunContextTest.java b/core/src/test/java/io/kestra/core/runners/RunContextTest.java index f9cd3af1e9..05608fa27d 100644 --- a/core/src/test/java/io/kestra/core/runners/RunContextTest.java +++ b/core/src/test/java/io/kestra/core/runners/RunContextTest.java @@ -70,7 +70,7 @@ void logs() throws TimeoutException { filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(1)); assertThat(filters, hasSize(1)); assertThat(filters.get(0).getLevel(), is(Level.WARN)); - assertThat(filters.get(0).getMessage(), is("second io.kestra.core.tasks.debugs.Echo")); + assertThat(filters.get(0).getMessage(), is("second io.kestra.core.tasks.log.Log")); filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(2)); diff --git a/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java b/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java index b6f8f7c05c..439dbed4ed 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java @@ -1,18 +1,20 @@ package io.kestra.core.tasks.flows; import com.google.common.collect.ImmutableMap; +import io.kestra.core.models.executions.Execution; import io.kestra.core.models.executions.LogEntry; +import io.kestra.core.models.flows.State; import io.kestra.core.queues.QueueFactoryInterface; import io.kestra.core.queues.QueueInterface; import io.kestra.core.repositories.LocalFlowRepositoryLoader; -import io.kestra.core.runners.ListenersTest; -import io.kestra.core.tasks.debugs.Echo; -import org.junit.jupiter.api.Test; -import io.kestra.core.models.executions.Execution; -import io.kestra.core.models.flows.State; import io.kestra.core.repositories.TemplateRepositoryInterface; import io.kestra.core.runners.AbstractMemoryRunnerTest; +import io.kestra.core.runners.ListenersTest; import io.kestra.core.runners.RunnerUtils; +import io.kestra.core.tasks.log.Log; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import org.junit.jupiter.api.Test; import org.slf4j.event.Level; import java.io.IOException; @@ -23,8 +25,6 @@ import java.util.List; import java.util.Objects; import java.util.concurrent.TimeoutException; -import jakarta.inject.Inject; -import jakarta.inject.Named; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.hasSize; @@ -42,7 +42,7 @@ public class TemplateTest extends AbstractMemoryRunnerTest { public static final io.kestra.core.models.templates.Template TEMPLATE_1 = io.kestra.core.models.templates.Template.builder() .id("template") .namespace("io.kestra.tests") - .tasks(Collections.singletonList(Echo.builder().id("test").type(Echo.class.getName()).format("{{ parent.outputs.args['my-forward'] }}").build())).build(); + .tasks(Collections.singletonList(Log.builder().id("test").type(Log.class.getName()).message("{{ parent.outputs.args['my-forward'] }}").build())).build(); public static void withTemplate(RunnerUtils runnerUtils, TemplateRepositoryInterface templateRepository, LocalFlowRepositoryLoader repositoryLoader, QueueInterface<LogEntry> logQueue) throws TimeoutException, IOException, URISyntaxException { templateRepository.create(TEMPLATE_1); diff --git a/core/src/test/resources/flows/invalids/duplicate-parallel.yaml b/core/src/test/resources/flows/invalids/duplicate-parallel.yaml index 3b36563449..629a54285a 100644 --- a/core/src/test/resources/flows/invalids/duplicate-parallel.yaml +++ b/core/src/test/resources/flows/invalids/duplicate-parallel.yaml @@ -4,8 +4,8 @@ namespace: io.kestra.tests tasks: - id: t3 - type: io.kestra.core.tasks.debugs.Echo - format: third all optional args {{ outputs.t2.value }} + type: io.kestra.core.tasks.log.Log + message: third all optional args {{ outputs.t2.value }} retry: type: constant interval: PT15M diff --git a/core/src/test/resources/flows/tests/invalid-task-defaults.yaml b/core/src/test/resources/flows/tests/invalid-task-defaults.yaml index f285e28b27..4ca24663db 100644 --- a/core/src/test/resources/flows/tests/invalid-task-defaults.yaml +++ b/core/src/test/resources/flows/tests/invalid-task-defaults.yaml @@ -2,13 +2,13 @@ id: invalid-task-defaults namespace: io.kestra.tests taskDefaults: - - type: io.kestra.core.tasks.debugs.Echo + - type: io.kestra.core.tasks.log.Log values: level: WARN invalid: Default tasks: - id: first - type: io.kestra.core.tasks.debugs.Echo + type: io.kestra.core.tasks.log.Log level: WARN - format: "Never happen" + message: "Never happen" diff --git a/core/src/test/resources/flows/tests/with-template.yaml b/core/src/test/resources/flows/tests/with-template.yaml index 426511927c..edae4e9957 100644 --- a/core/src/test/resources/flows/tests/with-template.yaml +++ b/core/src/test/resources/flows/tests/with-template.yaml @@ -13,7 +13,7 @@ variables: var-2: '{{ var-1 }}' taskDefaults: - - type: io.kestra.core.tasks.debugs.Echo + - type: io.kestra.core.tasks.log.Log values: level: "ERROR" diff --git a/core/src/test/resources/flows/valids/bash-warning.yaml b/core/src/test/resources/flows/valids/bash-warning.yaml index ae9b872618..dbe9724ea5 100644 --- a/core/src/test/resources/flows/valids/bash-warning.yaml +++ b/core/src/test/resources/flows/valids/bash-warning.yaml @@ -9,5 +9,5 @@ tasks: errors: - id: error - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.id}} + type: io.kestra.core.tasks.log.Log + message: second {{task.id}} diff --git a/core/src/test/resources/flows/valids/disable-error.yaml b/core/src/test/resources/flows/valids/disable-error.yaml index 043596ad78..151070647a 100644 --- a/core/src/test/resources/flows/valids/disable-error.yaml +++ b/core/src/test/resources/flows/valids/disable-error.yaml @@ -9,14 +9,14 @@ tasks: errors: - id: t2 - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.id}} + type: io.kestra.core.tasks.log.Log + message: second {{task.id}} - id: t3 - type: io.kestra.core.tasks.debugs.Echo - format: third {{task.id}} + type: io.kestra.core.tasks.log.Log + message: third {{task.id}} disabled: true - id: t4 - type: io.kestra.core.tasks.debugs.Echo - format: fourth {{task.id}} + type: io.kestra.core.tasks.log.Log + message: fourth {{task.id}} diff --git a/core/src/test/resources/flows/valids/disable-simple.yaml b/core/src/test/resources/flows/valids/disable-simple.yaml index 4a6b7a5dd3..c0bb05f47c 100644 --- a/core/src/test/resources/flows/valids/disable-simple.yaml +++ b/core/src/test/resources/flows/valids/disable-simple.yaml @@ -3,15 +3,15 @@ namespace: io.kestra.tests tasks: - id: t1 - type: io.kestra.core.tasks.debugs.Echo - format: first {{task.id}} + type: io.kestra.core.tasks.log.Log + message: first {{task.id}} level: TRACE - id: t2 - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.type}} + type: io.kestra.core.tasks.log.Log + message: second {{task.type}} level: WARN disabled: true - id: t3 - type: io.kestra.core.tasks.debugs.Echo - format: third {{flow.id}} + type: io.kestra.core.tasks.log.Log + message: third {{flow.id}} level: ERROR diff --git a/core/src/test/resources/flows/valids/errors.yaml b/core/src/test/resources/flows/valids/errors.yaml index 9ebb2ba270..dd26a8dfa4 100644 --- a/core/src/test/resources/flows/valids/errors.yaml +++ b/core/src/test/resources/flows/valids/errors.yaml @@ -8,8 +8,8 @@ tasks: - 'exit 1' errors: - id: t2 - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.id}} + type: io.kestra.core.tasks.log.Log + message: second {{task.id}} - id: t3 type: io.kestra.core.tasks.flows.Parallel diff --git a/core/src/test/resources/flows/valids/full.yaml b/core/src/test/resources/flows/valids/full.yaml index e6d11f9d57..181387083a 100644 --- a/core/src/test/resources/flows/valids/full.yaml +++ b/core/src/test/resources/flows/valids/full.yaml @@ -20,8 +20,8 @@ tasks: format: second {{ execution.id }} - id: t3 - type: io.kestra.core.tasks.debugs.Echo - format: third all optional args {{ outputs.t2.value }} + type: io.kestra.core.tasks.log.Log + message: third all optional args {{ outputs.t2.value }} timeout: PT60M retry: maxAttempt: 5 diff --git a/core/src/test/resources/flows/valids/logs.yaml b/core/src/test/resources/flows/valids/logs.yaml index 1a4ff567b2..139c3d5a9f 100644 --- a/core/src/test/resources/flows/valids/logs.yaml +++ b/core/src/test/resources/flows/valids/logs.yaml @@ -6,20 +6,20 @@ labels: region: "Nord" taskDefaults: - - type: io.kestra.core.tasks.debugs.Echo + - type: io.kestra.core.tasks.log.Log values: - format: third {{flow.id}} + message: third {{flow.id}} tasks: - id: t1 - type: io.kestra.core.tasks.debugs.Echo - format: first {{task.id}} + type: io.kestra.core.tasks.log.Log + message: first {{task.id}} level: TRACE - id: t2 - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.type}} + type: io.kestra.core.tasks.log.Log + message: second {{task.type}} level: WARN - id: t3 - type: io.kestra.core.tasks.debugs.Echo - format: third {{flow.id}} + type: io.kestra.core.tasks.log.Log + message: third {{flow.id}} level: ERROR diff --git a/core/src/test/resources/flows/valids/restart_always_failed.yaml b/core/src/test/resources/flows/valids/restart_always_failed.yaml index 4609198822..900db00fdb 100644 --- a/core/src/test/resources/flows/valids/restart_always_failed.yaml +++ b/core/src/test/resources/flows/valids/restart_always_failed.yaml @@ -9,6 +9,6 @@ tasks: - 'exit 1' errors: - id: errorHandler - type: io.kestra.core.tasks.debugs.Echo - format: I'm failing {{task.id}} + type: io.kestra.core.tasks.log.Log + message: I'm failing {{task.id}} level: INFO diff --git a/core/src/test/resources/flows/valids/restart_local_errors.yaml b/core/src/test/resources/flows/valids/restart_local_errors.yaml index 7f1a5b51cc..7ee0e4f6e1 100644 --- a/core/src/test/resources/flows/valids/restart_local_errors.yaml +++ b/core/src/test/resources/flows/valids/restart_local_errors.yaml @@ -3,15 +3,15 @@ namespace: io.kestra.tests tasks: - id: before - type: io.kestra.core.tasks.debugs.Echo - format: I'm before + type: io.kestra.core.tasks.log.Log + message: I'm before - id: sequential type: io.kestra.core.tasks.flows.Sequential tasks: - id: close - type: io.kestra.core.tasks.debugs.Echo - format: I'm close to fail + type: io.kestra.core.tasks.log.Log + message: I'm close to fail - id: failStep type: io.kestra.core.tasks.scripts.Bash description: "This fails" @@ -19,9 +19,9 @@ tasks: - 'exit 1' errors: - id: errorHandler - type: io.kestra.core.tasks.debugs.Echo - format: I'm failing {{task.id}} + type: io.kestra.core.tasks.log.Log + message: I'm failing {{task.id}} - id: after - type: io.kestra.core.tasks.debugs.Echo - format: I'm after + type: io.kestra.core.tasks.log.Log + message: I'm after diff --git a/core/src/test/resources/flows/valids/retry-failed.yaml b/core/src/test/resources/flows/valids/retry-failed.yaml index a5c2f8b733..67fd67459b 100644 --- a/core/src/test/resources/flows/valids/retry-failed.yaml +++ b/core/src/test/resources/flows/valids/retry-failed.yaml @@ -14,5 +14,5 @@ tasks: errors: - id: t2 - type: io.kestra.core.tasks.debugs.Echo - format: second {{task.id}} + type: io.kestra.core.tasks.log.Log + message: second {{task.id}} diff --git a/core/src/test/resources/flows/valids/retry-success.yaml b/core/src/test/resources/flows/valids/retry-success.yaml index c51c2b8cd8..d5957c674d 100644 --- a/core/src/test/resources/flows/valids/retry-success.yaml +++ b/core/src/test/resources/flows/valids/retry-success.yaml @@ -15,5 +15,5 @@ tasks: errors: - id: never-happen - type: io.kestra.core.tasks.debugs.Echo - format: Never {{task.id}} + type: io.kestra.core.tasks.log.Log + message: Never {{task.id}} diff --git a/jdbc/src/test/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepositoryTest.java b/jdbc/src/test/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepositoryTest.java index b6c9d3afa3..039ce16fae 100644 --- a/jdbc/src/test/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepositoryTest.java +++ b/jdbc/src/test/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepositoryTest.java @@ -84,7 +84,7 @@ public void invalidFlow() { "revision", 1, "tasks", List.of(Map.of( "id", "invalid", - "type", "io.kestra.core.tasks.debugs.Echo", + "type", "io.kestra.core.tasks.log.Log", "level", "invalid" )), "deleted", false diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/ErrorControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/ErrorControllerTest.java index 5b2bb83c61..241bff1307 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/ErrorControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/ErrorControllerTest.java @@ -2,7 +2,7 @@ import com.google.common.collect.ImmutableMap; import io.kestra.core.models.flows.Flow; -import io.kestra.core.tasks.debugs.Echo; +import io.kestra.core.tasks.log.Log; import io.kestra.core.utils.IdUtils; import io.micronaut.core.type.Argument; import io.micronaut.http.HttpStatus; @@ -83,8 +83,8 @@ void invalidEnum() { "namespace", "io.kestra.test", "tasks", Collections.singletonList(ImmutableMap.of( "id", IdUtils.create(), - "type", Echo.class.getName(), - "format", "Yeah !", + "type", Log.class.getName(), + "message", "Yeah !", "level", "WRONG" )) ); @@ -97,7 +97,7 @@ void invalidEnum() { String response = exception.getResponse().getBody(String.class).get(); assertThat(response, containsString("Cannot deserialize value of type `org.slf4j.event.Level` from String \\\"WRONG\\\"")); - assertThat(response, containsString("\"path\":\"io.kestra.core.models.flows.Flow[\\\"tasks\\\"] > java.util.ArrayList[0] > io.kestra.core.tasks.debugs.Echo[\\\"level\\\"]\"")); + assertThat(response, containsString("\"path\":\"io.kestra.core.models.flows.Flow[\\\"tasks\\\"] > java.util.ArrayList[0] > io.kestra.core.tasks.log.Log[\\\"level\\\"]\"")); } } \ No newline at end of file
train
train
2023-03-13T16:23:53
"2023-03-08T13:05:33Z"
loicmathieu
train
kestra-io/kestra/1053_1061
kestra-io/kestra
kestra-io/kestra/1053
kestra-io/kestra/1061
[ "keyword_pr_to_issue" ]
3ed471813f8742a13b12600fbb47be180b1bce41
cfd8e4879d25b6a6f2aaf7868a664aa8fd3bc832
[ "Task example:\r\n\r\n```yaml\r\nid: fail\r\ntype: io.kestra.core.taks.flow.Fail\r\n#optional condition that is at true by default so fail un-conditionnaly\r\ncondition: {{outputs.previous.value == \"you must fail\"}}\r\n```" ]
[]
"2023-03-13T15:28:16Z"
[]
Provide a task to fail a flow
### Feature description Provide a `Fail` task that will fail the flow unconditionally. This can be convenient for switch to fail on un-wanted values. We can also provide a condition for fine-grain failure.
[]
[ "core/src/main/java/io/kestra/core/tasks/executions/Fail.java", "core/src/main/resources/icons/io.kestra.core.tasks.executions.Fail.svg" ]
[ "core/src/test/java/io/kestra/core/Helpers.java", "core/src/test/java/io/kestra/core/tasks/executions/FailTest.java", "core/src/test/resources/flows/valids/fail-on-condition.yaml", "core/src/test/resources/flows/valids/fail-on-switch.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/tasks/executions/Fail.java b/core/src/main/java/io/kestra/core/tasks/executions/Fail.java new file mode 100644 index 0000000000..d9182d3b5b --- /dev/null +++ b/core/src/main/java/io/kestra/core/tasks/executions/Fail.java @@ -0,0 +1,110 @@ +package io.kestra.core.tasks.executions; + +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.tasks.RunnableTask; +import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.tasks.VoidOutput; +import io.kestra.core.runners.RunContext; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +@SuperBuilder +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Schema( + title = "Fail the execution", + description = "Used to fail the execution for example on a switch branch or on some conditions based on the execution context." +) +@Plugin( + examples = { + @Example( + title = "Fail on a switch branch", + full = true, + code = { + "id: fail-on-switch\n" + + "namespace: io.kestra.tests\n" + + "\n" + + "inputs:\n" + + " - name: param\n" + + " type: STRING\n" + + " required: true\n" + + "\n" + + "tasks:\n" + + " - id: switch\n" + + " type: io.kestra.core.tasks.flows.Switch\n" + + " value: \"{{inputs.param}}\"\n" + + " cases:\n" + + " case1:\n" + + " - id: case1\n" + + " type: io.kestra.core.tasks.debugs.Echo\n" + + " format: Case 1\n" + + " case2:\n" + + " - id: case2\n" + + " type: io.kestra.core.tasks.debugs.Echo\n" + + " format: Case 2\n" + + " notexist:\n" + + " - id: fail\n" + + " type: io.kestra.core.tasks.executions.Fail", + } + ), + @Example( + title = "Fail on a condition", + full = true, + code = { + "id: fail-on-condition\n" + + "namespace: io.kestra.tests\n" + + "\n" + + "inputs:\n" + + " - name: param\n" + + " type: STRING\n" + + " required: true\n" + + "\n" + + "tasks:\n" + + " - id: before\n" + + " type: io.kestra.core.tasks.debugs.Echo\n" + + " format: I'm before the fail on condition \n" + + " - id: fail\n" + + " type: io.kestra.core.tasks.executions.Fail\n" + + " condition: '{{inputs.param == \"fail\"}}'\n" + + " - id: after\n" + + " type: io.kestra.core.tasks.debugs.Echo\n" + + " format: I'm after the fail on condition " + } + ) + } +) +public class Fail extends Task implements RunnableTask<VoidOutput> { + + @PluginProperty(dynamic = true) + @Schema(title = "Optional condition, must evaluate to a boolean.") + private String condition; + + @PluginProperty(dynamic = true) + @Schema(title = "Optional error message.") + @Builder.Default + private String errorMessage = "Task failure"; + + @Override + public VoidOutput run(RunContext runContext) throws Exception { + if (condition != null) { + String rendered = runContext.render(condition); + if (Boolean.parseBoolean(rendered)) { + runContext.logger().error(runContext.render(errorMessage)); + throw new RuntimeException("Fail on a condition"); + } + return null; + } + + runContext.logger().error(runContext.render(errorMessage)); + throw new RuntimeException("Fail always"); + } +} diff --git a/core/src/main/resources/icons/io.kestra.core.tasks.executions.Fail.svg b/core/src/main/resources/icons/io.kestra.core.tasks.executions.Fail.svg new file mode 100644 index 0000000000..f4789f1b62 --- /dev/null +++ b/core/src/main/resources/icons/io.kestra.core.tasks.executions.Fail.svg @@ -0,0 +1,10 @@ +<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" width="256" height="256" viewBox="0 0 256 256" xml:space="preserve"> + +<defs> +</defs> +<g style="stroke: none; stroke-width: 0; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: none; fill-rule: nonzero; opacity: 1;" transform="translate(1.4065934065934016 1.4065934065934016) scale(2.81 2.81)" > + <path d="M 45 90 C 20.187 90 0 69.813 0 45 C 0 20.187 20.187 0 45 0 c 24.813 0 45 20.187 45 45 C 90 69.813 69.813 90 45 90 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(236,0,0); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round" /> + <path d="M 28.5 65.5 c -1.024 0 -2.047 -0.391 -2.829 -1.172 c -1.562 -1.562 -1.562 -4.095 0 -5.656 l 33 -33 c 1.561 -1.562 4.096 -1.562 5.656 0 c 1.563 1.563 1.563 4.095 0 5.657 l -33 33 C 30.547 65.109 29.524 65.5 28.5 65.5 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(255,255,255); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round" /> + <path d="M 61.5 65.5 c -1.023 0 -2.048 -0.391 -2.828 -1.172 l -33 -33 c -1.562 -1.563 -1.562 -4.095 0 -5.657 c 1.563 -1.562 4.095 -1.562 5.657 0 l 33 33 c 1.563 1.562 1.563 4.095 0 5.656 C 63.548 65.109 62.523 65.5 61.5 65.5 z" style="stroke: none; stroke-width: 1; stroke-dasharray: none; stroke-linecap: butt; stroke-linejoin: miter; stroke-miterlimit: 10; fill: rgb(255,255,255); fill-rule: nonzero; opacity: 1;" transform=" matrix(1 0 0 1 0 0) " stroke-linecap="round" /> +</g> +</svg> \ No newline at end of file
diff --git a/core/src/test/java/io/kestra/core/Helpers.java b/core/src/test/java/io/kestra/core/Helpers.java index 9cc950bc13..fc6e06bb4e 100644 --- a/core/src/test/java/io/kestra/core/Helpers.java +++ b/core/src/test/java/io/kestra/core/Helpers.java @@ -19,7 +19,7 @@ import java.util.function.Consumer; public class Helpers { - public static long FLOWS_COUNT = 56; + public static long FLOWS_COUNT = 58; public static ApplicationContext applicationContext() throws URISyntaxException { return applicationContext( diff --git a/core/src/test/java/io/kestra/core/tasks/executions/FailTest.java b/core/src/test/java/io/kestra/core/tasks/executions/FailTest.java new file mode 100644 index 0000000000..67a8ecaa99 --- /dev/null +++ b/core/src/test/java/io/kestra/core/tasks/executions/FailTest.java @@ -0,0 +1,46 @@ +package io.kestra.core.tasks.executions; + +import io.kestra.core.models.executions.Execution; +import io.kestra.core.models.flows.State; +import io.kestra.core.runners.AbstractMemoryRunnerTest; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.TimeoutException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.hasSize; +import static org.hamcrest.Matchers.is; + +public class FailTest extends AbstractMemoryRunnerTest { + @Test + void failOnSwitch() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "fail-on-switch", null, + (f, e) -> Map.of("param", "fail") , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(1)); + assertThat(execution.findTaskRunsByTaskId("switch").get(0).getState().getCurrent(), is(State.Type.FAILED)); + assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); + } + + @Test + void failOnCondition() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "fail-on-condition", null, + (f, e) -> Map.of("param", "fail") , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("fail").get(0).getState().getCurrent(), is(State.Type.FAILED)); + assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); + } + + @Test + void dontFailOnCondition() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "fail-on-condition", null, + (f, e) -> Map.of("param", "success") , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(3)); + assertThat(execution.findTaskRunsByTaskId("fail").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + } +} diff --git a/core/src/test/resources/flows/valids/fail-on-condition.yaml b/core/src/test/resources/flows/valids/fail-on-condition.yaml new file mode 100644 index 0000000000..62c729199d --- /dev/null +++ b/core/src/test/resources/flows/valids/fail-on-condition.yaml @@ -0,0 +1,18 @@ +id: fail-on-condition +namespace: io.kestra.tests + +inputs: + - name: param + type: STRING + required: true + +tasks: + - id: before + type: io.kestra.core.tasks.debugs.Echo + format: I'm before the fail on condition + - id: fail + type: io.kestra.core.tasks.executions.Fail + condition: '{{inputs.param == "fail"}}' + - id: after + type: io.kestra.core.tasks.debugs.Echo + format: I'm after the fail on condition \ No newline at end of file diff --git a/core/src/test/resources/flows/valids/fail-on-switch.yaml b/core/src/test/resources/flows/valids/fail-on-switch.yaml new file mode 100644 index 0000000000..71aaf2d4a6 --- /dev/null +++ b/core/src/test/resources/flows/valids/fail-on-switch.yaml @@ -0,0 +1,24 @@ +id: fail-on-switch +namespace: io.kestra.tests + +inputs: + - name: param + type: STRING + required: true + +tasks: + - id: switch + type: io.kestra.core.tasks.flows.Switch + value: "{{inputs.param}}" + cases: + case1: + - id: case1 + type: io.kestra.core.tasks.debugs.Echo + format: Case 1 + case2: + - id: case2 + type: io.kestra.core.tasks.debugs.Echo + format: Case 2 + notexist: + - id: fail + type: io.kestra.core.tasks.executions.Fail \ No newline at end of file
train
train
2023-03-15T20:54:44
"2023-03-09T14:40:59Z"
loicmathieu
train
kestra-io/kestra/1070_1071
kestra-io/kestra
kestra-io/kestra/1070
kestra-io/kestra/1071
[ "keyword_pr_to_issue" ]
3105ec20e78fae314ec2d8a151aca5901b339fd1
558c41e9373c9fdfcf49cee12b9068d014edc9ff
[ "Will try to correct this :) However, I don't know if there is anywhere else where the date parsing is used in a useful way ?" ]
[]
"2023-03-17T00:27:45Z"
[ "bug" ]
4-digits String as inputs are considered as a date when displayed
### Expected Behavior My usecase was to get a warehouse id as input which can be digits-only or alphanumerics-composed. It should display String as raw IMO ? Especially since there is a type: DATE ### Actual Behaviour <img width="801" alt="image" src="https://user-images.githubusercontent.com/37618489/225765270-a861c61b-2ea0-4e29-be2a-83211f1aa125.png"> <img width="296" alt="image" src="https://user-images.githubusercontent.com/37618489/225766081-c0385822-041d-4248-a6d8-d10bda4db1db.png"> As you can see, my input is parsed and displayed as date in the input information of the execution while it is treated as my raw String inside my flow. ### Steps To Reproduce In the quickstart configuration (v0.8.0-SNAPSHOT), run the given example flow and check the executions tab ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): MacOS - Java Version (If not docker): Under docker ### Example flow ``` id: numberAsDate namespace: simple.test inputs: - name: numberAsString type: STRING defaults: "2685" tasks: - id: print type: io.kestra.core.tasks.debugs.Echo format: "{{inputs.numberAsString}}" ```
[ "ui/src/utils/utils.js" ]
[ "ui/src/utils/utils.js" ]
[]
diff --git a/ui/src/utils/utils.js b/ui/src/utils/utils.js index 983797f238..2195d08e52 100644 --- a/ui/src/utils/utils.js +++ b/ui/src/utils/utils.js @@ -52,22 +52,23 @@ export default class Utils { const flat = Utils.flatten(data); return Object.keys(flat).map(key => { + let rawValue = flat[key]; if (key === "variables.executionId") { - return {key, value: flat[key], subflow: true}; + return {key, value: rawValue, subflow: true}; } - if (typeof (flat[key]) === "string") { - let date = moment(flat[key], moment.ISO_8601); + if (typeof rawValue === "string" && rawValue.match(/\d{4}-\d{2}-\d{2}/)) { + let date = moment(rawValue, moment.ISO_8601); if (date.isValid()) { - return {key, value: flat[key], date: true}; + return {key, value: rawValue, date: true}; } } - if (typeof (flat[key]) === "number") { - return {key, value: Utils.number(flat[key])}; + if (typeof rawValue === "number") { + return {key, value: Utils.number(rawValue)}; } - return {key, value: flat[key]}; + return {key, value: rawValue}; }) }
null
val
train
2023-03-17T16:44:47
"2023-03-16T22:26:13Z"
brian-mulier-p
train
kestra-io/kestra/1072_1076
kestra-io/kestra
kestra-io/kestra/1072
kestra-io/kestra/1076
[ "keyword_pr_to_issue" ]
3a5b08ed1cbd0b5765f36482202c3e78bd22132c
1b5791d1e37f34059e59410f1a4a166b90dc2a03
[ "Hi @cuiweining thanks for reporting.\r\nI tested it and in fact it is not linked to the pause task or an execution deletion but sorting on the `id` field didn't work at all.\r\nI'll look at it.", "@cuiweining the bug is fixed and is available on the new 0.8.0-SNAPSHOT that was published minutes ago and should be available if you use our `develop-full` Docker image.\r\nYou can try it and provides feedback if any." ]
[]
"2023-03-17T08:47:29Z"
[ "bug" ]
Execution sort error
### Expected Behavior ![image](https://user-images.githubusercontent.com/44800439/225796256-234a2625-bd77-414d-9cb5-271bd4360cd0.png) Internal server error: SQL [select *, count(*) over () as "total_count" from (select "value" from executions where "deleted" = ? order by "id" desc) as "page" where true offset ? rows fetch next ? rows only]; ERROR: column "id" does not exist Position: 112 ### Actual Behaviour Create a pause Executions and check whether the executions are restarted after being deleted. After the executions are deleted, an error is reported when the executions list is sorted by ID. ### Steps To Reproduce 1, create pause flow 2, delete pause Executions 3, create pause Executions 4, Executions page id sort ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): Kubernetes - Java Version (If not docker): 1.8 ### Example flow _No response_
[]
[ "jdbc-h2/src/main/resources/migrations/h2/V6__missing_execution_id.sql", "jdbc-postgres/src/main/resources/migrations/postgres/V7__missing_execution_id.sql" ]
[ "core/src/test/java/io/kestra/core/repositories/AbstractExecutionRepositoryTest.java" ]
diff --git a/jdbc-h2/src/main/resources/migrations/h2/V6__missing_execution_id.sql b/jdbc-h2/src/main/resources/migrations/h2/V6__missing_execution_id.sql new file mode 100644 index 0000000000..e1a547265c --- /dev/null +++ b/jdbc-h2/src/main/resources/migrations/h2/V6__missing_execution_id.sql @@ -0,0 +1,1 @@ +ALTER TABLE executions ADD COLUMN "id" VARCHAR(150) NOT NULL GENERATED ALWAYS AS (JQ_STRING("value", '.id')) \ No newline at end of file diff --git a/jdbc-postgres/src/main/resources/migrations/postgres/V7__missing_execution_id.sql b/jdbc-postgres/src/main/resources/migrations/postgres/V7__missing_execution_id.sql new file mode 100644 index 0000000000..cbdb82b8ce --- /dev/null +++ b/jdbc-postgres/src/main/resources/migrations/postgres/V7__missing_execution_id.sql @@ -0,0 +1,1 @@ +ALTER TABLE executions ADD COLUMN id VARCHAR(150) NOT NULL GENERATED ALWAYS AS (value ->> 'id') STORED \ No newline at end of file
diff --git a/core/src/test/java/io/kestra/core/repositories/AbstractExecutionRepositoryTest.java b/core/src/test/java/io/kestra/core/repositories/AbstractExecutionRepositoryTest.java index b48c1773b7..38ad4e453a 100644 --- a/core/src/test/java/io/kestra/core/repositories/AbstractExecutionRepositoryTest.java +++ b/core/src/test/java/io/kestra/core/repositories/AbstractExecutionRepositoryTest.java @@ -10,6 +10,7 @@ import io.kestra.core.models.tasks.ResolvedTask; import io.kestra.core.tasks.debugs.Return; import io.micronaut.data.model.Pageable; +import io.micronaut.data.model.Sort; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; import jakarta.inject.Inject; import org.junit.jupiter.api.Test; @@ -113,6 +114,18 @@ protected void find() { assertThat(executions.getTotal(), is(8L)); } + @Test + protected void findWithSort() { + inject(); + + ArrayListTotal<Execution> executions = executionRepository.find(Pageable.from(1, 10, Sort.of(Sort.Order.desc("id"))), null, null, null, null, null, null); + assertThat(executions.getTotal(), is(28L)); + assertThat(executions.size(), is(10)); + + executions = executionRepository.find(Pageable.from(1, 10), null, null, null, null, null, List.of(State.Type.RUNNING, State.Type.FAILED)); + assertThat(executions.getTotal(), is(8L)); + } + @Test protected void findTaskRun() { inject();
train
train
2023-03-16T22:52:20
"2023-03-17T02:29:09Z"
cuiweining
train
kestra-io/kestra/1080_1081
kestra-io/kestra
kestra-io/kestra/1080
kestra-io/kestra/1081
[ "keyword_pr_to_issue" ]
3105ec20e78fae314ec2d8a151aca5901b339fd1
b95c8ed4e586818fb17c935c14e1332f81306f45
[ "I don't know if it's related to my own MAC shortcut (although I couldn't find any shortcut conflicting).\r\nI managed to get something working using this\r\n\r\n```\r\nmonaco.editor.addKeybindingRule(\r\n {\r\n keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space,\r\n command: \"editor.action.triggerSuggest\"\r\n }\r\n)\r\n```\r\n\r\nGoing to make a PR, feel free to challenge it if you think it is related to my environment but I can't get why it isn't working.\r\nAlso, I checked Monaco Editor for any clue but didn't manage to find anything related", "you can create a PR, you are not the only one I think, I already have some report about that in the past :rocket: ", "Done !" ]
[]
"2023-03-17T21:15:36Z"
[ "bug" ]
Can't trigger autocompletion modal on MacOS
### Expected Behavior Hit ⌘ + Space when the suggestion modal is off should trigger the modal back and get autocompletion back again ### Actual Behaviour Hitting the given shortcut is not working on my side and it does nothing ### Steps To Reproduce - Start typing a task - When it comes to writing the type, just write "type: " then hit escape to put the autocomplete modal OFF - Try to hit ⌘ + Space => Nothing is happening ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): MacOS ### Example flow Any flow
[ "ui/src/components/inputs/MonacoEditor.vue" ]
[ "ui/src/components/inputs/MonacoEditor.vue" ]
[]
diff --git a/ui/src/components/inputs/MonacoEditor.vue b/ui/src/components/inputs/MonacoEditor.vue index a7d47debf2..46ea2a3712 100644 --- a/ui/src/components/inputs/MonacoEditor.vue +++ b/ui/src/components/inputs/MonacoEditor.vue @@ -166,6 +166,11 @@ options["model"] = monaco.editor.createModel(this.value, this.language); } + monaco.editor.addKeybindingRule({ + keybinding: monaco.KeyMod.CtrlCmd | monaco.KeyCode.Space, + command: "editor.action.triggerSuggest" + }) + this.editor = monaco.editor.create(this.$el, options); }
null
test
train
2023-03-17T16:44:47
"2023-03-17T21:10:23Z"
brian-mulier-p
train
kestra-io/kestra/1098_1104
kestra-io/kestra
kestra-io/kestra/1098
kestra-io/kestra/1104
[ "keyword_pr_to_issue" ]
558c41e9373c9fdfcf49cee12b9068d014edc9ff
5bc65bb2c1f02d7911b18484421b1d7ca5ae4534
[]
[ "there is no null possible in pebble?", "```suggestion\r\n private List<Task> tasks;\r\n```", "add another unit test without else please", "add `@NotEmpty` (or whatever meaning size > 0) ", "No, it generates an error so I had to do it this way", "I mean `List.of(\"false\", \"0\", \"-0\", \"\", \"null\")`, not sure it exists ", "Done, and yes, there was an issue ;)", "Done" ]
"2023-03-23T13:28:31Z"
[]
Implement if-else task
### Feature description Currently, Kestra features the `io.kestra.core.tasks.flows.Switch` task acting as a value-based _switch_ statement. This allows diverting the execution path based on a resolved value. However, a simple binary conditional requires a lot of boilerplate code. The current approach to execute a simple task conditionally is illustrated bellow: ```yaml - id: run-X-when-necessary type: io.kestra.core.tasks.flows.Switch value: "{{ inputs contains 'aVariableConnectedToX' ? 'RUN' : 'SKIP' }}" cases: RUN: - id: run-X type: io.kestra.core.tasks.debugs.Echo description: "Run X" format: "Running X with {{ inputs.aVariableConnectedToX }}..." defaults: - id: skipping-X type: io.kestra.core.tasks.debugs.Echo description: "Switch requires to have a task to execute" format: "Skipping X..." ``` It would be great to have a simple task acting as the classic _if-else_ statement allowing the following notation: ```yaml - id: run-X-when-necessary type: io.kestra.core.tasks.flows.If test: "{{ inputs contains 'aVariableConnectedToX' }}" then: - id: run-X type: io.kestra.core.tasks.debugs.Echo description: "Run X" format: "Running X with {{ inputs.aVariableConnectedToX }}..." ``` or ```yaml - id: run-X-when-necessary type: io.kestra.core.tasks.flows.If test: "{{ inputs contains 'aVariableConnectedToX' }}" then: - id: run-X type: io.kestra.core.tasks.debugs.Echo description: "Run X" format: "Running X with {{ inputs.aVariableConnectedToX }}..." else: - id: run-Y type: io.kestra.core.tasks.debugs.Echo description: "Run Y" format: "Running Y..." ``` The `test` condition should use a _truth_ value - empty string being evaluated to false, etc.
[ "core/src/main/java/io/kestra/core/services/GraphService.java", "core/src/main/java/io/kestra/core/tasks/executions/Fail.java" ]
[ "core/src/main/java/io/kestra/core/services/GraphService.java", "core/src/main/java/io/kestra/core/tasks/executions/Fail.java", "core/src/main/java/io/kestra/core/tasks/flows/If.java", "core/src/main/java/io/kestra/core/utils/TruthUtils.java", "core/src/main/resources/icons/io.kestra.core.tasks.flows.If.svg" ]
[ "core/src/test/java/io/kestra/core/Helpers.java", "core/src/test/java/io/kestra/core/tasks/flows/IfTest.java", "core/src/test/resources/flows/valids/if-condition.yaml", "core/src/test/resources/flows/valids/if-without-else.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/services/GraphService.java b/core/src/main/java/io/kestra/core/services/GraphService.java index 8cad220a3f..c20a99c666 100644 --- a/core/src/main/java/io/kestra/core/services/GraphService.java +++ b/core/src/main/java/io/kestra/core/services/GraphService.java @@ -167,6 +167,25 @@ public static void switchCase( } } + public static void ifElse( + GraphCluster graph, + List<Task> then, + List<Task> _else, + List<Task> errors, + TaskRun parent, + Execution execution + ) throws IllegalVariableEvaluationException { + fillGraph(graph, then, RelationType.SEQUENTIAL, parent, execution, "then"); + if (_else != null) { + fillGraph(graph, _else, RelationType.SEQUENTIAL, parent, execution, "else"); + } + + // error cases + if (errors != null && errors.size() > 0) { + fillGraph(graph, errors, RelationType.ERROR, parent, execution, null); + } + } + private static void iterate( GraphCluster graph, List<Task> tasks, diff --git a/core/src/main/java/io/kestra/core/tasks/executions/Fail.java b/core/src/main/java/io/kestra/core/tasks/executions/Fail.java index d9182d3b5b..87fa06c355 100644 --- a/core/src/main/java/io/kestra/core/tasks/executions/Fail.java +++ b/core/src/main/java/io/kestra/core/tasks/executions/Fail.java @@ -7,6 +7,7 @@ import io.kestra.core.models.tasks.Task; import io.kestra.core.models.tasks.VoidOutput; import io.kestra.core.runners.RunContext; +import io.kestra.core.utils.TruthUtils; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; import lombok.EqualsAndHashCode; @@ -85,7 +86,10 @@ public class Fail extends Task implements RunnableTask<VoidOutput> { @PluginProperty(dynamic = true) - @Schema(title = "Optional condition, must evaluate to a boolean.") + @Schema( + title = "Optional condition, must coerce to a boolean.", + description = "Boolean coercion allows 0, -0, and '' to coerce to false, all other values to coerce to true." + ) private String condition; @PluginProperty(dynamic = true) @@ -97,7 +101,7 @@ public class Fail extends Task implements RunnableTask<VoidOutput> { public VoidOutput run(RunContext runContext) throws Exception { if (condition != null) { String rendered = runContext.render(condition); - if (Boolean.parseBoolean(rendered)) { + if (TruthUtils.isTruthy(rendered)) { runContext.logger().error(runContext.render(errorMessage)); throw new RuntimeException("Fail on a condition"); } diff --git a/core/src/main/java/io/kestra/core/tasks/flows/If.java b/core/src/main/java/io/kestra/core/tasks/flows/If.java new file mode 100644 index 0000000000..b0153d71a9 --- /dev/null +++ b/core/src/main/java/io/kestra/core/tasks/flows/If.java @@ -0,0 +1,175 @@ +package io.kestra.core.tasks.flows; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.google.common.collect.ImmutableMap; +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.executions.Execution; +import io.kestra.core.models.executions.NextTaskRun; +import io.kestra.core.models.executions.TaskRun; +import io.kestra.core.models.flows.State; +import io.kestra.core.models.hierarchies.GraphCluster; +import io.kestra.core.models.hierarchies.RelationType; +import io.kestra.core.models.tasks.FlowableTask; +import io.kestra.core.models.tasks.ResolvedTask; +import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.tasks.VoidOutput; +import io.kestra.core.runners.FlowableUtils; +import io.kestra.core.runners.RunContext; +import io.kestra.core.services.GraphService; +import io.kestra.core.utils.TruthUtils; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.ToString; +import lombok.experimental.SuperBuilder; + +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; + +@SuperBuilder +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Schema( + title = "Process some tasks conditionally depending on a contextual value", + description = "Allow some workflow based on context variables, for example branch a flow based on a previous task." +) +@Plugin( + examples = { + @Example( + full = true, + code = { + "id: if", + "namespace: io.kestra.tests", + "", + "inputs:", + " - name: string", + " type: STRING", + " required: true", + "", + "tasks:", + " - id: if", + " type: io.kestra.core.tasks.flows.If", + " condition: \"{{inputs.string == 'Condition'}}\"", + " then:", + " - id: when-true", + " type: io.kestra.core.tasks.log.Log", + " message: 'Condition was true'", + " else:", + " - id: when-false", + " type: io.kestra.core.tasks.log.Log", + " message: 'Condition was false'", + } + ) + } +) +public class If extends Task implements FlowableTask<VoidOutput> { + @PluginProperty(dynamic = true) + @Schema( + title = "If condition, must coerce to a boolean.", + description = "Boolean coercion allows 0, -0, null and '' to coerce to false, all other values to coerce to true." + ) + private String condition; + + @Valid + @PluginProperty + @Schema( + title = "List of tasks to execute when the condition is true." + ) + @NotEmpty + private List<Task> then; + + @Valid + @PluginProperty + @Schema( + title = "List of tasks to execute when the condition is false." + ) + @JsonProperty("else") + private List<Task> _else; + + @Valid + @PluginProperty + @Schema( + title = "List of tasks to execute in case of errors on a child task." + ) + private List<Task> errors; + + @Override + public List<Task> getErrors() { + return errors; + } + + @Override + public GraphCluster tasksTree(Execution execution, TaskRun taskRun, List<String> parentValues) throws IllegalVariableEvaluationException { + GraphCluster subGraph = new GraphCluster(this, taskRun, parentValues, RelationType.CHOICE); + + GraphService.ifElse( + subGraph, + this.then, + this._else, + this.errors, + taskRun, + execution + ); + + return subGraph; + } + + @Override + public List<Task> allChildTasks() { + return Stream + .concat( + this.then.stream(), + Stream.concat( + this._else != null ? this._else.stream() : Stream.empty(), + this.errors != null ? this.errors.stream() : Stream.empty()) + ) + .collect(Collectors.toList()); + } + + @Override + public List<ResolvedTask> childTasks(RunContext runContext, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + String rendered = runContext.render(condition); + if (TruthUtils.isTruthy(rendered)) { + return FlowableUtils.resolveTasks(then, parentTaskRun); + } + return FlowableUtils.resolveTasks(_else, parentTaskRun); + } + + @Override + public List<NextTaskRun> resolveNexts(RunContext runContext, Execution execution, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + return FlowableUtils.resolveSequentialNexts( + execution, + this.childTasks(runContext, parentTaskRun), + FlowableUtils.resolveTasks(this.errors, parentTaskRun), + parentTaskRun + ); + } + + @Override + public Optional<State.Type> resolveState(RunContext runContext, Execution execution, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + List<ResolvedTask> childTask = this.childTasks(runContext, parentTaskRun); + if (childTask == null) { + // no next task to run, we guess the state from the parent task + return Optional.of(execution.guessFinalState(null, parentTaskRun)); + } + + return FlowableUtils.resolveState( + execution, + this.childTasks(runContext, parentTaskRun), + FlowableUtils.resolveTasks(this.getErrors(), parentTaskRun), + parentTaskRun, + runContext + ); + } +} diff --git a/core/src/main/java/io/kestra/core/utils/TruthUtils.java b/core/src/main/java/io/kestra/core/utils/TruthUtils.java new file mode 100644 index 0000000000..8764789b00 --- /dev/null +++ b/core/src/main/java/io/kestra/core/utils/TruthUtils.java @@ -0,0 +1,11 @@ +package io.kestra.core.utils; + +import java.util.List; + +abstract public class TruthUtils { + private static final List<String> FALSE_VALUES = List.of("false", "0", "-0", ""); + + public static boolean isTruthy(String condition) { + return condition != null && !FALSE_VALUES.contains(condition); + } +} diff --git a/core/src/main/resources/icons/io.kestra.core.tasks.flows.If.svg b/core/src/main/resources/icons/io.kestra.core.tasks.flows.If.svg new file mode 100644 index 0000000000..a6d077d33a --- /dev/null +++ b/core/src/main/resources/icons/io.kestra.core.tasks.flows.If.svg @@ -0,0 +1,14 @@ +<?xml version="1.0" encoding="UTF-8"?> +<svg width="700pt" height="700pt" version="1.1" viewBox="0 0 700 700" xmlns="http://www.w3.org/2000/svg"> + <g> + <path d="m525 525c-9.6641 0-17.5-7.8281-17.5-17.5s7.8359-17.5 17.5-17.5c9.6484 0 17.5-7.8438 17.5-17.5v-20.508c0-11.723 3.8203-22.867 10.871-31.992-7.0508-9.125-10.871-20.27-10.871-31.992v-20.508c0-9.6562-7.8516-17.5-17.5-17.5-9.6641 0-17.5-7.8281-17.5-17.5s7.8359-17.5 17.5-17.5c28.949 0 52.5 23.551 52.5 52.5v20.508c0 4.5977 1.8711 9.1094 5.1289 12.375l7.2461 7.2461c6.8359 6.8359 6.8359 17.91 0 24.746l-7.2461 7.2461c-3.2578 3.2617-5.1289 7.7734-5.1289 12.371v20.508c0 28.949-23.551 52.5-52.5 52.5z"/> + <path d="m455 525c-28.949 0-52.5-23.551-52.5-52.5v-20.508c0-4.5977-1.8711-9.1094-5.1289-12.375l-7.2461-7.2461c-6.8359-6.8359-6.8359-17.91 0-24.746l7.2461-7.2461c3.2578-3.2617 5.1289-7.7734 5.1289-12.371v-20.508c0-28.949 23.551-52.5 52.5-52.5 9.6641 0 17.5 7.8281 17.5 17.5s-7.8359 17.5-17.5 17.5c-9.6484 0-17.5 7.8438-17.5 17.5v20.508c0 11.723-3.8203 22.867-10.867 31.992 7.0469 9.125 10.867 20.27 10.867 31.992v20.508c0 9.6562 7.8516 17.5 17.5 17.5 9.6641 0 17.5 7.8281 17.5 17.5s-7.8359 17.5-17.5 17.5z"/> + <path d="m245 525c-9.6641 0-17.5-7.8281-17.5-17.5s7.8359-17.5 17.5-17.5c9.6484 0 17.5-7.8438 17.5-17.5v-20.508c0-11.723 3.8203-22.867 10.871-31.992-7.0508-9.125-10.871-20.27-10.871-31.992v-20.508c0-9.6562-7.8516-17.5-17.5-17.5-9.6641 0-17.5-7.8281-17.5-17.5s7.8359-17.5 17.5-17.5c28.949 0 52.5 23.551 52.5 52.5v20.508c0 4.5977 1.8711 9.1094 5.1289 12.375l7.2461 7.2461c6.8359 6.8359 6.8359 17.91 0 24.746l-7.2461 7.2461c-3.2578 3.2617-5.1289 7.7734-5.1289 12.371v20.508c0 28.949-23.551 52.5-52.5 52.5z"/> + <path d="m175 525c-28.949 0-52.5-23.551-52.5-52.5v-20.508c0-4.5977-1.8711-9.1094-5.1289-12.375l-7.2461-7.2461c-6.8359-6.8359-6.8359-17.91 0-24.746l7.2461-7.2461c3.2578-3.2617 5.1289-7.7734 5.1289-12.371v-20.508c0-28.949 23.551-52.5 52.5-52.5 9.6641 0 17.5 7.8281 17.5 17.5s-7.8359 17.5-17.5 17.5c-9.6484 0-17.5 7.8438-17.5 17.5v20.508c0 11.723-3.8203 22.867-10.867 31.992 7.0469 9.125 10.867 20.27 10.867 31.992v20.508c0 9.6562 7.8516 17.5 17.5 17.5 9.6641 0 17.5 7.8281 17.5 17.5s-7.8359 17.5-17.5 17.5z"/> + <path d="m227.5 472.5c-4.4766 0-8.957-1.7109-12.375-5.1289l-35-35c-6.8359-6.8359-6.8359-17.91 0-24.746l35-35c6.8359-6.8359 17.91-6.8359 24.746 0 6.8359 6.8359 6.8359 17.91 0 24.746l-22.625 22.629 22.629 22.629c6.8359 6.8359 6.8359 17.91 0 24.746-3.418 3.418-7.8984 5.125-12.375 5.125z"/> + <path d="m472.5 472.5c-4.4766 0-8.957-1.7109-12.375-5.1289-6.8359-6.8359-6.8359-17.91 0-24.746l22.629-22.625-22.629-22.629c-6.8359-6.8359-6.8359-17.91 0-24.746s17.91-6.8359 24.746 0l35 35c6.8359 6.8359 6.8359 17.91 0 24.746l-35 35c-3.4141 3.4219-7.8945 5.1289-12.371 5.1289z"/> + <path d="m192.5 315h35v-35h35c9.6641 0 17.5-7.8359 17.5-17.5v-52.5h-35v35h-35c-9.6641 0-17.5 7.8359-17.5 17.5z"/> + <path d="m507.5 315h-35v-35h-35c-9.6641 0-17.5-7.8359-17.5-17.5v-52.5h35v35h35c9.6641 0 17.5 7.8359 17.5 17.5z"/> + <path d="m437.5 35h-175c-19.328 0-35 15.672-35 35v87.5c0 19.328 15.672 35 35 35h70v17.5h-17.5c-9.6719 0-17.5 7.8359-17.5 17.5s7.8281 17.5 17.5 17.5h70c9.6719 0 17.5-7.8359 17.5-17.5s-7.8281-17.5-17.5-17.5h-17.5v-17.5h70c19.328 0 35-15.672 35-35v-87.5c0-19.328-15.672-35-35-35zm-108.5 106.74c3.8711 2.9062 4.6562 8.3906 1.75 12.254-1.7148 2.2891-4.3398 3.5039-7.0039 3.5039-1.8281 0-3.6641-0.5625-5.2383-1.7422-13.348-10.016-21.004-25.328-21.004-42.008s7.6562-31.992 21.004-42.008c3.8555-2.8867 9.332-2.0859 12.246 1.7617 2.9062 3.8633 2.1211 9.3477-1.75 12.254-8.8984 6.6641-14 16.867-14 27.992s5.1016 21.328 13.996 27.992zm52.5 14.016c-1.5703 1.1797-3.4102 1.7422-5.2383 1.7422-2.668 0-5.2891-1.2148-7.0078-3.5039-2.9062-3.8633-2.1211-9.3477 1.75-12.254 8.8984-6.6641 14-16.867 14-27.992s-5.1016-21.328-13.996-27.992c-3.8711-2.9062-4.6562-8.3906-1.75-12.254 2.9141-3.8438 8.3906-4.6484 12.246-1.7617 13.344 10.016 21 25.328 21 42.008s-7.6562 31.992-21.004 42.008z"/> + </g> +</svg>
diff --git a/core/src/test/java/io/kestra/core/Helpers.java b/core/src/test/java/io/kestra/core/Helpers.java index 62e15377b2..82bd964bb3 100644 --- a/core/src/test/java/io/kestra/core/Helpers.java +++ b/core/src/test/java/io/kestra/core/Helpers.java @@ -19,7 +19,7 @@ import java.util.function.Consumer; public class Helpers { - public static long FLOWS_COUNT = 61; + public static long FLOWS_COUNT = 63; public static ApplicationContext applicationContext() throws URISyntaxException { return applicationContext( diff --git a/core/src/test/java/io/kestra/core/tasks/flows/IfTest.java b/core/src/test/java/io/kestra/core/tasks/flows/IfTest.java new file mode 100644 index 0000000000..710f6a1b91 --- /dev/null +++ b/core/src/test/java/io/kestra/core/tasks/flows/IfTest.java @@ -0,0 +1,88 @@ +package io.kestra.core.tasks.flows; + +import io.kestra.core.models.executions.Execution; +import io.kestra.core.models.flows.State; +import io.kestra.core.runners.AbstractMemoryRunnerTest; +import org.junit.jupiter.api.Test; + +import java.time.Duration; +import java.util.Map; +import java.util.concurrent.TimeoutException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.*; + +class IfTest extends AbstractMemoryRunnerTest { + @Test + void ifTruthy() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", true) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-true").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", "true") , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-true").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", 1) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-true").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + } + + @Test + void ifFalsy() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", false) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-false").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", "false") , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-false").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", 0) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-false").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-condition", null, + (f, e) -> Map.of("param", -0) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-false").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + // We cannot test null as inputs cannot be null + } + + @Test + void ifWithoutElse() throws TimeoutException { + Execution execution = runnerUtils.runOne("io.kestra.tests", "if-without-else", null, + (f, e) -> Map.of("param", true) , Duration.ofSeconds(120)); + + assertThat(execution.getTaskRunList(), hasSize(2)); + assertThat(execution.findTaskRunsByTaskId("when-true").get(0).getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + execution = runnerUtils.runOne("io.kestra.tests", "if-without-else", null, + (f, e) -> Map.of("param", false) , Duration.ofSeconds(120)); + assertThat(execution.getTaskRunList(), hasSize(1)); + assertThat(execution.findTaskRunsByTaskId("when-true").isEmpty(), is(true)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + } +} \ No newline at end of file diff --git a/core/src/test/resources/flows/valids/if-condition.yaml b/core/src/test/resources/flows/valids/if-condition.yaml new file mode 100644 index 0000000000..f3c2ce0d03 --- /dev/null +++ b/core/src/test/resources/flows/valids/if-condition.yaml @@ -0,0 +1,19 @@ +id: if-condition +namespace: io.kestra.tests + +inputs: + - name: param + type: STRING + +tasks: + - id: if + type: io.kestra.core.tasks.flows.If + condition: "{{inputs.param}}" + then: + - id: when-true + type: io.kestra.core.tasks.log.Log + message: 'Condition was true' + else: + - id: when-false + type: io.kestra.core.tasks.log.Log + message: 'Condition was false' \ No newline at end of file diff --git a/core/src/test/resources/flows/valids/if-without-else.yaml b/core/src/test/resources/flows/valids/if-without-else.yaml new file mode 100644 index 0000000000..9dd6a917c9 --- /dev/null +++ b/core/src/test/resources/flows/valids/if-without-else.yaml @@ -0,0 +1,15 @@ +id: if-without-else +namespace: io.kestra.tests + +inputs: + - name: param + type: STRING + +tasks: + - id: if + type: io.kestra.core.tasks.flows.If + condition: "{{inputs.param}}" + then: + - id: when-true + type: io.kestra.core.tasks.log.Log + message: 'Condition was true' \ No newline at end of file
val
train
2023-03-23T08:44:24
"2023-03-22T17:53:50Z"
yuri1969
train
kestra-io/kestra/1088_1105
kestra-io/kestra
kestra-io/kestra/1088
kestra-io/kestra/1105
[ "keyword_pr_to_issue" ]
5bc65bb2c1f02d7911b18484421b1d7ca5ae4534
eb9ef947e1cb3007f61b9cd11b8363b556fee303
[]
[]
"2023-03-23T15:20:13Z"
[ "bug" ]
Unable to include another file in the flow
### Expected Behavior Should be able to use syntax pattern depicted [here](https://kestra.io/docs/developer-guide/cicd/helpers/#file-txt-include-another-file) to inject an external file to the flow using `/app/kestra`. ### Actual Behaviour Get this error (truncated): `Invalid entity: Illegal flow yaml: No 'injectableValues' configured, cannot inject value with id` ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java" ]
[ "cli/src/main/java/io/kestra/cli/commands/flows/FlowExpandCommand.java", "cli/src/main/java/io/kestra/cli/commands/flows/IncludeHelperExpander.java", "cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java", "cli/src/test/resources/helper/lorem-multiple.txt", "cli/src/test/resources/helper/lorem.txt" ]
[ "cli/src/test/java/io/kestra/cli/commands/flows/FlowExpandCommandTest.java", "cli/src/test/java/io/kestra/cli/commands/flows/FlowValidateCommandTest.java", "cli/src/test/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommandTest.java", "cli/src/test/resources/helper/flow.yaml" ]
diff --git a/cli/src/main/java/io/kestra/cli/commands/flows/FlowExpandCommand.java b/cli/src/main/java/io/kestra/cli/commands/flows/FlowExpandCommand.java new file mode 100644 index 0000000000..bb6e0ac27d --- /dev/null +++ b/cli/src/main/java/io/kestra/cli/commands/flows/FlowExpandCommand.java @@ -0,0 +1,37 @@ +package io.kestra.cli.commands.flows; + +import io.kestra.cli.AbstractCommand; +import io.kestra.core.models.flows.Flow; +import io.kestra.core.models.validations.ModelValidator; +import io.kestra.core.serializers.YamlFlowParser; +import jakarta.inject.Inject; +import picocli.CommandLine; + +import java.nio.file.Files; +import java.nio.file.Path; + [email protected]( + name = "expand", + description = "expand a flow" +) +public class FlowExpandCommand extends AbstractCommand { + + @CommandLine.Parameters(index = "0", description = "the flow file to expand") + private Path file; + + @Inject + private YamlFlowParser yamlFlowParser; + + @Inject + private ModelValidator modelValidator; + + @Override + public Integer call() throws Exception { + super.call(); + String content = IncludeHelperExpander.expand(Files.readString(file), file.getParent()); + Flow flow = yamlFlowParser.parse(content, Flow.class); + modelValidator.validate(flow); + stdOut(content); + return 0; + } +} diff --git a/cli/src/main/java/io/kestra/cli/commands/flows/IncludeHelperExpander.java b/cli/src/main/java/io/kestra/cli/commands/flows/IncludeHelperExpander.java new file mode 100644 index 0000000000..2959ca0cac --- /dev/null +++ b/cli/src/main/java/io/kestra/cli/commands/flows/IncludeHelperExpander.java @@ -0,0 +1,39 @@ +package io.kestra.cli.commands.flows; + +import com.google.common.io.Files; +import lombok.SneakyThrows; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.nio.file.Path; +import java.util.List; +import java.util.stream.Collectors; + +public abstract class IncludeHelperExpander { + + public static String expand(String value, Path directory) throws IOException { + return value.lines() + .map(line -> line.contains("[[>") && line.contains("]]") ? expandLine(line, directory) : line) + .collect(Collectors.joining("\n")); + } + + @SneakyThrows + private static String expandLine(String line, Path directory) { + String prefix = line.substring(0, line.indexOf("[[>")); + String suffix = line.substring(line.indexOf("]]") + 2, line.length()); + String file = line.substring(line.indexOf("[[>") + 3 , line.indexOf("]]")).strip(); + Path includePath = directory.resolve(file); + List<String> include = Files.readLines(includePath.toFile(), Charset.defaultCharset()); + + // handle single line directly with the suffix (should be between quotes or double-quotes + if(include.size() == 1) { + String singleInclude = include.get(0); + return prefix + singleInclude + suffix; + } + + // multi-line will be expanded with the prefix but no suffix + return include.stream() + .map(includeLine -> prefix + includeLine) + .collect(Collectors.joining("\n")); + } +} diff --git a/cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java b/cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java index 3a09592651..410c3f19cb 100644 --- a/cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java +++ b/cli/src/main/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommand.java @@ -2,7 +2,7 @@ import io.kestra.cli.commands.AbstractServiceNamespaceUpdateCommand; import io.kestra.cli.commands.flows.FlowValidateCommand; -import io.kestra.core.models.flows.FlowWithSource; +import io.kestra.cli.commands.flows.IncludeHelperExpander; import io.kestra.core.serializers.YamlFlowParser; import io.micronaut.core.type.Argument; import io.micronaut.http.HttpRequest; @@ -42,7 +42,7 @@ public Integer call() throws Exception { .filter(YamlFlowParser::isValidExtension) .map(path -> { try { - return Files.readString(path, Charset.defaultCharset()); + return IncludeHelperExpander.expand(Files.readString(path, Charset.defaultCharset()), path.getParent()); } catch (IOException e) { throw new RuntimeException(e); } diff --git a/cli/src/test/resources/helper/lorem-multiple.txt b/cli/src/test/resources/helper/lorem-multiple.txt new file mode 100644 index 0000000000..4d8f63e1e1 --- /dev/null +++ b/cli/src/test/resources/helper/lorem-multiple.txt @@ -0,0 +1,2 @@ +Lorem ipsum dolor sit amet +Lorem ipsum dolor sit amet \ No newline at end of file diff --git a/cli/src/test/resources/helper/lorem.txt b/cli/src/test/resources/helper/lorem.txt new file mode 100644 index 0000000000..d781006b2d --- /dev/null +++ b/cli/src/test/resources/helper/lorem.txt @@ -0,0 +1,1 @@ +Lorem ipsum dolor sit amet \ No newline at end of file
diff --git a/cli/src/test/java/io/kestra/cli/commands/flows/FlowExpandCommandTest.java b/cli/src/test/java/io/kestra/cli/commands/flows/FlowExpandCommandTest.java new file mode 100644 index 0000000000..adfa2b6066 --- /dev/null +++ b/cli/src/test/java/io/kestra/cli/commands/flows/FlowExpandCommandTest.java @@ -0,0 +1,49 @@ +package io.kestra.cli.commands.flows; + +import io.micronaut.configuration.picocli.PicocliRunner; +import io.micronaut.context.ApplicationContext; +import io.micronaut.context.env.Environment; +import io.micronaut.runtime.server.EmbeddedServer; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.StringContains.containsString; + +class FlowExpandCommandTest { + @Test + void run() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); + + try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { + EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class); + embeddedServer.start(); + + String[] args = { + "src/test/resources/helper/flow.yaml" + }; + Integer call = PicocliRunner.call(FlowExpandCommand.class, ctx, args); + + assertThat(call, is(0)); + assertThat(out.toString(), is( + "id: include\n" + + "namespace: io.kestra.cli\n" + + "\n" + + "# The list of tasks\n" + + "tasks:\n" + + "- id: t1\n" + + " type: io.kestra.core.tasks.debugs.Return\n" + + " format: \"Lorem ipsum dolor sit amet\"\n" + + "- id: t2\n" + + " type: io.kestra.core.tasks.debugs.Return\n" + + " format: |\n" + + " Lorem ipsum dolor sit amet\n" + + " Lorem ipsum dolor sit amet\n" + )); + } + } +} \ No newline at end of file diff --git a/cli/src/test/java/io/kestra/cli/commands/flows/FlowValidateCommandTest.java b/cli/src/test/java/io/kestra/cli/commands/flows/FlowValidateCommandTest.java new file mode 100644 index 0000000000..0a40b056cc --- /dev/null +++ b/cli/src/test/java/io/kestra/cli/commands/flows/FlowValidateCommandTest.java @@ -0,0 +1,36 @@ +package io.kestra.cli.commands.flows; + +import io.micronaut.configuration.picocli.PicocliRunner; +import io.micronaut.context.ApplicationContext; +import io.micronaut.context.env.Environment; +import io.micronaut.runtime.server.EmbeddedServer; +import org.junit.jupiter.api.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.core.Is.is; +import static org.hamcrest.core.StringContains.containsString; + +class FlowValidateCommandTest { + @Test + void run() { + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); + + try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { + EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class); + embeddedServer.start(); + + String[] args = { + "--local", + "src/test/resources/helper/flow.yaml" + }; + Integer call = PicocliRunner.call(FlowValidateCommand.class, ctx, args); + + assertThat(call, is(0)); + assertThat(out.toString(), containsString("✓ - io.kestra.cli / include")); + } + } +} \ No newline at end of file diff --git a/cli/src/test/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommandTest.java b/cli/src/test/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommandTest.java index a0524dd2db..24f9327192 100644 --- a/cli/src/test/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommandTest.java +++ b/cli/src/test/java/io/kestra/cli/commands/flows/namespaces/FlowNamespaceUpdateCommandTest.java @@ -109,4 +109,31 @@ void runNoDelete() { assertThat(out.toString(), containsString("1 flow(s)")); } } + + @Test + void helper() { + URL directory = FlowNamespaceUpdateCommandTest.class.getClassLoader().getResource("helper"); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + System.setOut(new PrintStream(out)); + + try (ApplicationContext ctx = ApplicationContext.run(Environment.CLI, Environment.TEST)) { + + EmbeddedServer embeddedServer = ctx.getBean(EmbeddedServer.class); + embeddedServer.start(); + + String[] args = { + "--server", + embeddedServer.getURL().toString(), + "--user", + "myuser:pass:word", + "io.kestra.cli", + directory.getPath(), + + }; + Integer call = PicocliRunner.call(FlowNamespaceUpdateCommand.class, ctx, args); + + assertThat(call, is(0)); + assertThat(out.toString(), containsString("1 flow(s)")); + } + } } diff --git a/cli/src/test/resources/helper/flow.yaml b/cli/src/test/resources/helper/flow.yaml new file mode 100644 index 0000000000..13d03a8c51 --- /dev/null +++ b/cli/src/test/resources/helper/flow.yaml @@ -0,0 +1,12 @@ +id: include +namespace: io.kestra.cli + +# The list of tasks +tasks: +- id: t1 + type: io.kestra.core.tasks.debugs.Return + format: "[[> lorem.txt]]" +- id: t2 + type: io.kestra.core.tasks.debugs.Return + format: | + [[> lorem-multiple.txt]] \ No newline at end of file
train
train
2023-03-23T16:15:41
"2023-03-20T16:20:29Z"
Melkaz
train
kestra-io/kestra/1132_1133
kestra-io/kestra
kestra-io/kestra/1132
kestra-io/kestra/1133
[ "keyword_pr_to_issue" ]
28cbac85919514b6991d05a905d29e4ea11f2a31
0e644fe4b8b3f47ea0f81d9f475de3099cb383a9
[]
[]
"2023-04-05T17:51:45Z"
[ "bug" ]
Attempt to kill the whole process tree on timeout
### Expected Behavior In case of timeout, the Bash task tries to kill the whole spawned process tree. ### Actual Behaviour In case of timeout, the Bash task kills only the started initial process. This results in any child processes spawned by the parent process remain running - effectively avoiding the timeout restriction. ### Steps To Reproduce 1. Define a task using `io.kestra.core.tasks.scripts.Bash` running a script 2. Set a reasonable `timeout` for the task 3. Make the script run a long running action (`sleep`, etc.) 4. Run the flow 5. List running processes 6. Wait for the Bash task to hit the timeout 7. List running processes again ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): CentOS - Java Version (If not docker): openjdk version "11.0.18" 2023-01-17 LTS ### Example flow ``` yaml id: BashTest namespace: io.kestra.tests description: Test if the Bash processes tree gets killed properly. disabled: false tasks: - id: long-running-task type: io.kestra.core.tasks.scripts.Bash description: "Long Bash task gets killed on timeout" commands: - "/tmp/sleep.sh" taskDefaults: - type: io.kestra.core.tasks.scripts.Bash values: interpreter: /bin/bash timeout: PT5S ``` ```bash #!/bin/bash sleep 100 ```
[ "core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java" ]
[ "core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java" ]
[]
diff --git a/core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java b/core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java index b3281a01ff..5669b063fa 100644 --- a/core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java +++ b/core/src/main/java/io/kestra/core/tasks/scripts/runners/ProcessBuilderScriptRunner.java @@ -72,8 +72,17 @@ public RunResult run( return new RunResult(exitCode, stdOut, stdErr); } catch (InterruptedException e) { logger.warn("Killing process {} for InterruptedException", pid); + killDescendantsOf(process.toHandle(), logger); process.destroy(); throw e; } } + + private void killDescendantsOf(ProcessHandle process, Logger logger) { + process.descendants().forEach(processHandle -> { + if (!processHandle.destroy()) { + logger.warn("Descendant process {} of {} couldn't be killed", processHandle.pid(), process.pid()); + } + }); + } }
null
test
train
2023-04-05T13:50:15
"2023-04-05T17:49:24Z"
yuri1969
train
kestra-io/kestra/1140_1142
kestra-io/kestra
kestra-io/kestra/1140
kestra-io/kestra/1142
[ "keyword_pr_to_issue" ]
4c96adf2f57f66ab3c73a0e3a1e11675f63efef4
43ab765da11d9d6802449958edf0fe91a9c30b0a
[]
[]
"2023-04-08T07:00:02Z"
[ "bug" ]
Key of null value missing in the webhook
### Expected Behavior { "creditHeader":{ "idNum":"", "idType":"a", "reason":"a", "serialNo":"a", "reportTime":"a", "otherIdInfo":[ { "type":"a", "idNum":"a" } ], "antiHackInfo":{ "dueDate":"a", "effectDate":"a", "warningInfo":"a" }, "organization":"a", "objectionInfo":"a", "whoWasChecked":"a" }, "personBasicInfo":{ "personInfo":{ "gender":{ "value":"a", "organization":"a" } } } } ### Actual Behaviour { "creditHeader":{ "idType":"a", "reason":"a", "serialNo":"a", "reportTime":"a", "otherIdInfo":[ { "type":"a", "idNum":"a" } ], "antiHackInfo":{ "dueDate":"a", "effectDate":"a", "warningInfo":"a" }, "organization":"a", "objectionInfo":"a", "whoWasChecked":"a" }, "personBasicInfo":{ "personInfo":{ "gender":{ "value":"a", "organization":"a" } } } } ### Steps To Reproduce 1、use the webhook to trigger a flow 2、In the webhook, use a json struct as the body of the http request 3、some values are null in the json 4、getting the json in the execution, and find that the keys of the null value disappear ### Environment Information - Kestra Version: 0.6.0 - Operating System (OS / Docker / Kubernetes): Kubernetes - Java Version (If not docker):openjdk version "11.0.2" ### Example flow id: webhook_weipu namespace: io.weipu revision: 25 inputs: - type: STRING name: credit_report_ocr tasks: - id: log type: io.kestra.core.tasks.debugs.Return format: "{{ trigger.body.credit_report_ocr | json }}" - id: kafka type: io.kestra.plugin.kafka.Produce from: key: "{{ trigger.body.seq_no }}" value: "{{ trigger.body.credit_report_ocr | json }}" keySerializer: STRING properties: bootstrap.servers: 172.16.104.52:6667,172.16.104.53:6667 topic: testbill valueSerializer: STRING triggers: - id: trigger_webhook type: io.kestra.core.models.triggers.types.Webhook key: testtesttesttest
[ "core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java" ]
[ "core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java b/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java index 63b766fefb..33d09f27c0 100644 --- a/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java +++ b/core/src/main/java/io/kestra/core/models/triggers/types/Webhook.java @@ -1,5 +1,6 @@ package io.kestra.core.models.triggers.types; +import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import io.kestra.core.models.annotations.PluginProperty; @@ -79,7 +80,7 @@ public class Webhook extends AbstractTrigger implements TriggerOutput<Webhook.Ou public Optional<Execution> evaluate(HttpRequest<String> request, io.kestra.core.models.flows.Flow flow) { String body = request.getBody().orElse(null); - ObjectMapper mapper = JacksonMapper.ofJson(); + ObjectMapper mapper = JacksonMapper.ofJson().setSerializationInclusion(JsonInclude.Include.USE_DEFAULTS); Execution.ExecutionBuilder builder = Execution.builder() .id(IdUtils.create())
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java index badc8e316c..90e7d85910 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java @@ -482,5 +482,18 @@ void webhook() { Execution.class ); assertThat(execution.getTrigger().getVariables().get("body"), is(nullValue())); + + execution = client.toBlocking().retrieve( + HttpRequest + .POST( + "/api/v1/executions/webhook/" + TESTS_FLOW_NS + "/webhook/" + key, + "{\\\"a\\\":\\\"\\\",\\\"b\\\":{\\\"c\\\":{\\\"d\\\":{\\\"e\\\":\\\"\\\",\\\"f\\\":\\\"1\\\"}}}}" + ), + Execution.class + ); + assertThat(execution.getTrigger().getVariables().get("body"), is("{\\\"a\\\":\\\"\\\",\\\"b\\\":{\\\"c\\\":{\\\"d\\\":{\\\"e\\\":\\\"\\\",\\\"f\\\":\\\"1\\\"}}}}")); + } + + }
test
train
2023-04-06T21:32:48
"2023-04-07T09:47:42Z"
yangkailc
train
kestra-io/kestra/1159_1195
kestra-io/kestra
kestra-io/kestra/1159
kestra-io/kestra/1195
[ "connected" ]
c618684e4205f4eb749e0f3f29b2dae8bc39a7b3
d183c941f88475fbd6e7f9b6a92d061772b07b90
[ "I think this is a duplicate of #1146 ?", "Yep, I'm closing https://github.com/kestra-io/kestra/issues/1146" ]
[]
"2023-04-25T13:54:34Z"
[ "enhancement" ]
Add slider in Editor view to manage windows size
### Feature description On the editor, I want to be able to resize the block content when Topology/Docs with Source are displayed: manage the size of each window. Add a slider (example https://elfsight.com/fr/before-and-after-slider-widget/examples/) ![image](https://user-images.githubusercontent.com/46634684/231766321-76defb1d-5135-4ce4-b225-46eb294f4d42.png)
[ "ui/src/components/graph/Topology.vue", "ui/src/components/plugins/PluginDocumentation.vue" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/components/plugins/PluginDocumentation.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 19e06722e5..043bc084a1 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -1,7 +1,7 @@ <script setup> - import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount} from "vue"; - import {mapState, useStore} from "vuex" - import {VueFlow, Panel, useVueFlow, Position, MarkerType, PanelPosition} from "@vue-flow/core" +import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, computed} from "vue"; + import {useStore} from "vuex" + import {VueFlow, useVueFlow, Position, MarkerType} from "@vue-flow/core" import {Controls, ControlButton} from "@vue-flow/controls" import dagre from "dagre" import ArrowCollapseRight from "vue-material-design-icons/ArrowCollapseRight.vue"; @@ -29,14 +29,12 @@ import permission from "../../models/permission"; import action from "../../models/action"; import YamlUtils from "../../utils/yamlUtils"; - import {getElement} from "bootstrap/js/src/util"; import Utils from "../../utils/utils"; import taskEditor from "../flows/TaskEditor.vue"; import metadataEditor from "../flows/MetadataEditor.vue"; import editor from "../inputs/Editor.vue"; import yamlUtils from "../../utils/yamlUtils"; import {pageFromRoute} from "../../utils/eventsRouter"; - import {canSaveFlowTemplate} from "../../utils/flowTemplate"; const { id, @@ -107,9 +105,10 @@ type: String, default: undefined } - }) + const editorWidthStorageKey = "editor-width"; + const editorWidthPercentage = ref(localStorage.getItem(editorWidthStorageKey)); const isHorizontal = ref(localStorage.getItem("topology-orientation") !== "0"); const isLoading = ref(false); const elements = ref([]) @@ -407,6 +406,12 @@ return undefined; } + const persistEditorWidth = () => { + if (editorWidthPercentage.value !== null) { + localStorage.setItem(editorWidthStorageKey, editorWidthPercentage.value); + } + } + onMounted(() => { if (props.isCreating) { store.commit("flow/setFlowGraph", undefined); @@ -429,6 +434,7 @@ window.addEventListener("popstate", () => { stopTour(); }); + window.addEventListener("beforeunload", persistEditorWidth); }) onBeforeUnmount(() => { @@ -437,6 +443,10 @@ document.removeEventListener("popstate", () => { stopTour(); }); + + window.removeEventListener("beforeunload", persistEditorWidth); + + persistEditorWidth(); }) @@ -744,6 +754,9 @@ updatedFromEditor.value = false; } } + if (event == "source") { + window.document.getElementById("editor").style = null; + } } const save = (e) => { @@ -855,10 +868,43 @@ }); } + const combinedEditor = computed(() => ['doc','combined'].includes(showTopology.value)); + + const dragEditor = (e) => { + let editorDomElement = document.getElementById("editor"); + + let dragX = e.clientX; + let blockWidth = editorDomElement.offsetWidth; + let parentWidth = editorDomElement.parentNode.offsetWidth; + let blockWidthPercent = (blockWidth / parentWidth) * 100; + + document.onmousemove = function onMouseMove(e) { + editorWidthPercentage.value = (blockWidthPercent + ((e.clientX - dragX) / parentWidth) * 100) + "%" + } + + document.onmouseup = () => { + document.onmousemove = document.onmouseup = null; + } + } </script> <template> <el-card shadow="never" v-loading="isLoading"> + <editor + id="editor" + v-if="['doc', 'combined', 'source'].includes(showTopology)" + :class="combinedEditor ? 'editor-combined' : ''" + :style="combinedEditor ? {width: editorWidthPercentage} : {}" + @save="save" + v-model="flowYaml" + schema-type="flow" + lang="yaml" + @update:model-value="editorUpdate($event)" + @cursor="updatePluginDocumentation($event)" + :creating="isCreating" + @restartGuidedTour="() => showTopology = 'source'" + /> + <div class="slider" @mousedown="dragEditor" v-if="combinedEditor" /> <div :class="showTopology === 'combined'? 'vueflow-combined' : showTopology === 'topology' ? 'vueflow': 'vueflow-hide'" id="el-col-vueflow" @@ -923,18 +969,6 @@ </Controls> </VueFlow> </div> - <editor - v-if="['doc', 'combined', 'source'].includes(showTopology)" - :class="['doc','combined'].includes(showTopology) ? 'editor-combined' : ''" - @save="save" - v-model="flowYaml" - schema-type="flow" - lang="yaml" - @update:model-value="editorUpdate($event)" - @cursor="updatePluginDocumentation($event)" - :creating="isCreating" - @restartGuidedTour="() => showTopology = 'source'" - /> <PluginDocumentation v-if="showTopology === 'doc'" class="plugin-doc" @@ -1113,6 +1147,7 @@ :deep(.el-card__body) { height: 100%; + display: flex; } } @@ -1122,15 +1157,9 @@ right: 30px; } - .editor { - height: 100%; - width: 100%; - } - .editor-combined { height: 100%; width: 50%; - float: left; } .vueflow { @@ -1139,9 +1168,7 @@ } .vueflow-combined { - height: 100%; - width: 50%; - float: right; + flex-grow: 1; } .vueflow-hide { @@ -1150,10 +1177,7 @@ .plugin-doc { overflow-x: hidden; - padding: calc(var(--spacer) * 3); - height: 100%; - width: 50%; - float: right; + flex-grow: 1; overflow-y: scroll; padding: calc(var(--spacer) * 1.5); background-color: var(--bs-gray-300); @@ -1168,4 +1192,14 @@ flex-direction: column; width: 20rem; } + + .slider { + width: calc(1rem/3); + border-radius: 0.25rem; + margin: 0 0.25rem; + background-color: var(--bs-secondary); + border: none; + cursor: col-resize; + user-select: none; /* disable selection */ + } </style> diff --git a/ui/src/components/plugins/PluginDocumentation.vue b/ui/src/components/plugins/PluginDocumentation.vue index 1b32c0abd8..fe4b1ea13c 100644 --- a/ui/src/components/plugins/PluginDocumentation.vue +++ b/ui/src/components/plugins/PluginDocumentation.vue @@ -23,6 +23,7 @@ <style scoped lang="scss"> .plugin-documentation-div { + width: 0; } ::-webkit-scrollbar {
null
val
train
2023-05-05T11:47:44
"2023-04-13T13:03:32Z"
Ben8t
train
kestra-io/kestra/1145_1211
kestra-io/kestra
kestra-io/kestra/1145
kestra-io/kestra/1211
[ "keyword_pr_to_issue" ]
44f1168564847929c3b3705bdf3d745c9799e21f
bd968c315c24d19333ee46b9602f3c857d4bc007
[]
[ "maybe a little unit test ? to validate future non regression ? ", "As it's boolean it's more logical to use `&&` instead of `==` but you can keep it if you want." ]
"2023-04-28T11:20:57Z"
[ "bug", "documentation", "enhancement" ]
Required properties should be listed first in Editor doc (webapp)
### Expected Behavior Required properties should be listed first in doc for better visibility of what I should absolutely add to my task ### Actual Behaviour Properties are listed as in POJO I guess ### Steps To Reproduce 1. Create a task with required & non-required properties (eg. https://kestra.io/plugins/plugin-azure/tasks/batch.job/io.kestra.plugin.azure.batch.job.Create.html) 2. job is listed after some non-required properties ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): Mac - Java Version (If not docker): 11 ### Example flow id: a-flow namespace: some.namespace tasks: - id: taskOne type: io.kestra.plugin.azure.batch.job.Create
[ "core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java", "core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java", "core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java", "core/src/main/java/io/kestra/core/plugins/PluginScanner.java" ]
[ "core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java", "core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java", "core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java", "core/src/main/java/io/kestra/core/plugins/PluginScanner.java" ]
[ "cli/src/test/java/io/kestra/cli/commands/plugins/PluginDocCommandTest.java", "cli/src/test/java/io/kestra/cli/commands/plugins/PluginListCommandTest.java", "core/src/test/java/io/kestra/core/docs/DocumentationGeneratorTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java b/core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java index 0231f3fbb5..6530fc5029 100644 --- a/core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java +++ b/core/src/main/java/io/kestra/core/docs/ClassPluginDocumentation.java @@ -125,7 +125,13 @@ private static Map<String, Object> flatten(Map<String, Object> map, List<String> @SuppressWarnings("unchecked") private static Map<String, Object> flatten(Map<String, Object> map, List<String> required, String parentName) { - Map<String, Object> result = new TreeMap<>(); + Map<String, Object> result = new TreeMap<>((key1, key2) -> { + boolean key1Required = required.contains(key1); + boolean key2Required = required.contains(key2); + if(key1Required == key2Required) return key1.compareTo(key2); + + return key1Required ? -1 : 1; + }); for (Map.Entry<String, Object> current : map.entrySet()) { Map<String, Object> finalValue = (Map<String, Object>) current.getValue(); diff --git a/core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java b/core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java index 534dfd78aa..67e0fa6a5f 100644 --- a/core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java +++ b/core/src/main/java/io/kestra/core/docs/DocumentationGenerator.java @@ -128,6 +128,7 @@ private static List<Document> guides(RegisteredPlugin plugin) throws IOException try (var stream = Files.walk(root, 1)) { return stream .skip(1) // first element is the root element + .sorted(Comparator.comparing(path -> path.getName(path.getParent().getNameCount()).toString())) .map(throwFunction(path -> new Document( pluginName + "/guides/" + path.getName(path.getParent().getNameCount()), new String(Files.readAllBytes(path)), diff --git a/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java b/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java index 88c22c9718..adcef0b9ae 100644 --- a/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java +++ b/core/src/main/java/io/kestra/core/docs/JsonSchemaGenerator.java @@ -175,6 +175,7 @@ protected <T> void build(SchemaGeneratorConfigBuilder builder, Class<? extends T builder .with(new JavaxValidationModule( + JavaxValidationOption.NOT_NULLABLE_METHOD_IS_REQUIRED, JavaxValidationOption.NOT_NULLABLE_FIELD_IS_REQUIRED, JavaxValidationOption.INCLUDE_PATTERN_EXPRESSIONS )) diff --git a/core/src/main/java/io/kestra/core/plugins/PluginScanner.java b/core/src/main/java/io/kestra/core/plugins/PluginScanner.java index 189557cc3a..873a5fd7b4 100644 --- a/core/src/main/java/io/kestra/core/plugins/PluginScanner.java +++ b/core/src/main/java/io/kestra/core/plugins/PluginScanner.java @@ -1,6 +1,5 @@ package io.kestra.core.plugins; -import io.kestra.core.docs.Document; import io.kestra.core.models.conditions.Condition; import io.kestra.core.models.tasks.Task; import io.kestra.core.models.triggers.AbstractTrigger; @@ -20,16 +19,11 @@ import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; +import java.util.*; import java.util.jar.JarFile; import java.util.jar.Manifest; import java.util.stream.Collectors; -import static io.kestra.core.utils.Rethrow.throwFunction; - @Slf4j public class PluginScanner { ClassLoader parent; @@ -146,6 +140,7 @@ private RegisteredPlugin scanClassLoader(final ClassLoader classLoader, External try (var stream = Files.walk(root, 1)) { stream .skip(1) // first element is the root element + .sorted(Comparator.comparing(path -> path.getName(path.getParent().getNameCount()).toString())) .forEach(guide -> { var guideName = guide.getName(guide.getParent().getNameCount()).toString(); guides.add(guideName.substring(0, guideName.lastIndexOf('.')));
diff --git a/cli/src/test/java/io/kestra/cli/commands/plugins/PluginDocCommandTest.java b/cli/src/test/java/io/kestra/cli/commands/plugins/PluginDocCommandTest.java index 1d594d0f39..0e91ecf9eb 100644 --- a/cli/src/test/java/io/kestra/cli/commands/plugins/PluginDocCommandTest.java +++ b/cli/src/test/java/io/kestra/cli/commands/plugins/PluginDocCommandTest.java @@ -36,8 +36,8 @@ void run() throws IOException, URISyntaxException { FileUtils.copyFile( new File(Objects.requireNonNull(PluginListCommandTest.class.getClassLoader() - .getResource("plugins/plugin-template-test-0.6.0-SNAPSHOT.jar")).toURI()), - new File(URI.create("file://" + pluginsPath.toAbsolutePath() + "/plugin-template-test-0.6.0-SNAPSHOT.jar")) + .getResource("plugins/plugin-template-test-0.9.0-SNAPSHOT.jar")).toURI()), + new File(URI.create("file://" + pluginsPath.toAbsolutePath() + "/plugin-template-test-0.9.0-SNAPSHOT.jar")) ); Path docPath = Files.createTempDirectory(PluginInstallCommandTest.class.getSimpleName()); @@ -84,7 +84,8 @@ void run() throws IOException, URISyntaxException { // check @PluginProperty from an interface var task = directory.toPath().resolve("tasks/io.kestra.plugin.templates.ExampleTask.md"); - assertThat(new String(Files.readAllBytes(task)), containsString("### `example`\n" + + String taskDoc = new String(Files.readAllBytes(task)); + assertThat(taskDoc, containsString("### `example`\n" + "\n" + "* **Type:** ==string==\n" + "* **Dynamic:** ✔️\n" + @@ -93,6 +94,16 @@ void run() throws IOException, URISyntaxException { "\n" + "\n" + "> Example interface\n")); + assertThat(taskDoc, containsString("### `requiredExample`\n" + + "\n" + + "* **Type:** ==string==\n" + + "* **Dynamic:** ❌\n" + + "* **Required:** ✔️\n" + + "* **Min length:** `1`\n" + + "\n" + + "\n" + + "\n" + + "> Required Example interface\n")); var authenticationGuide = directory.toPath().resolve("guides/authentication.md"); assertThat(new String(Files.readAllBytes(authenticationGuide)), containsString("This is how to authenticate for this plugin:")); diff --git a/cli/src/test/java/io/kestra/cli/commands/plugins/PluginListCommandTest.java b/cli/src/test/java/io/kestra/cli/commands/plugins/PluginListCommandTest.java index 90b894d5fd..a7c2ca7b2d 100644 --- a/cli/src/test/java/io/kestra/cli/commands/plugins/PluginListCommandTest.java +++ b/cli/src/test/java/io/kestra/cli/commands/plugins/PluginListCommandTest.java @@ -36,8 +36,8 @@ void run() throws IOException, URISyntaxException { FileUtils.copyFile( new File(Objects.requireNonNull(PluginListCommandTest.class.getClassLoader() - .getResource("plugins/plugin-template-test-0.6.0-SNAPSHOT.jar")).toURI()), - new File(URI.create("file://" + pluginsPath.toAbsolutePath() + "/plugin-template-test-0.6.0-SNAPSHOT.jar")) + .getResource("plugins/plugin-template-test-0.9.0-SNAPSHOT.jar")).toURI()), + new File(URI.create("file://" + pluginsPath.toAbsolutePath() + "/plugin-template-test-0.9.0-SNAPSHOT.jar")) ); ByteArrayOutputStream out = new ByteArrayOutputStream(); diff --git a/core/src/test/java/io/kestra/core/docs/DocumentationGeneratorTest.java b/core/src/test/java/io/kestra/core/docs/DocumentationGeneratorTest.java index 51aec2ed8a..e4d82aadf9 100644 --- a/core/src/test/java/io/kestra/core/docs/DocumentationGeneratorTest.java +++ b/core/src/test/java/io/kestra/core/docs/DocumentationGeneratorTest.java @@ -1,23 +1,25 @@ package io.kestra.core.docs; +import io.kestra.core.models.tasks.Task; +import io.kestra.core.plugins.PluginScanner; +import io.kestra.core.plugins.RegisteredPlugin; import io.kestra.core.tasks.debugs.Echo; import io.kestra.core.tasks.debugs.Return; import io.kestra.core.tasks.flows.Flow; +import io.kestra.core.tasks.scripts.Bash; import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import jakarta.inject.Inject; import org.junit.jupiter.api.Test; -import io.kestra.core.models.tasks.Task; -import io.kestra.core.plugins.PluginScanner; -import io.kestra.core.plugins.RegisteredPlugin; -import io.kestra.core.tasks.scripts.Bash; import java.io.IOException; import java.net.URISyntaxException; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.Arrays; import java.util.List; +import java.util.Map; import java.util.Objects; - -import jakarta.inject.Inject; +import java.util.stream.Stream; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; @@ -61,6 +63,29 @@ void bash() throws IOException { assertThat(render, containsString("Bash")); assertThat(render, containsString("**Required:** ✔️")); + + assertThat(render, containsString("`exitOnFailed`")); + + int propertiesIndex = render.indexOf("Properties"); + int outputsIndex = render.indexOf("Outputs"); + int definitionsIndex = render.indexOf("Definitions"); + + assertRequiredPropsAreFirst(render.substring(propertiesIndex, outputsIndex)); + assertRequiredPropsAreFirst(render.substring(outputsIndex, definitionsIndex)); + + String definitionsDoc = render.substring(definitionsIndex); + Arrays.stream(definitionsDoc.split("[^#]### ")) + // first is 'Definitions' header + .skip(1) + .forEach(DocumentationGeneratorTest::assertRequiredPropsAreFirst); + } + + private static void assertRequiredPropsAreFirst(String propertiesDoc) { + int lastRequiredPropIndex = propertiesDoc.lastIndexOf("* **Required:** ✔️"); + int firstOptionalPropIndex = propertiesDoc.indexOf("* **Required:** ❌"); + if (lastRequiredPropIndex != -1 && firstOptionalPropIndex != -1) { + assertThat(lastRequiredPropIndex, lessThanOrEqualTo(firstOptionalPropIndex)); + } } @SuppressWarnings({"rawtypes", "unchecked"})
val
train
2023-05-04T16:30:46
"2023-04-12T10:47:32Z"
brian-mulier-p
train
kestra-io/kestra/1182_1229
kestra-io/kestra
kestra-io/kestra/1182
kestra-io/kestra/1229
[ "keyword_pr_to_issue" ]
64446f22794ab02289f319b134c1098e80915d27
c618684e4205f4eb749e0f3f29b2dae8bc39a7b3
[]
[]
"2023-05-04T09:31:32Z"
[ "bug" ]
UI task documentation dispays generic task proprties
### Expected Behavior Inside the plugin documentation site, the task generic properties (like description, disabled, ...) are not displayed to avoid having too many properties that will clutter the documentation. For example for the XmlReadre task: ![image](https://user-images.githubusercontent.com/1819009/233577581-55c1f2d8-1814-4cfc-a136-e2e27ad5772f.png) Inside the UI flow editor, the documentation contains all the properties which make it hard to read and find useful information. ![image](https://user-images.githubusercontent.com/1819009/233577828-a371d832-b132-46d1-8e63-7cdefaaa4998.png) Both should display the same properties ### Actual Behaviour Inside the UI flow editor, task default properties are displayd. ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8.1-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/stores/plugins.js", "webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java" ]
[ "ui/src/stores/plugins.js", "webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java" ]
[]
diff --git a/ui/src/stores/plugins.js b/ui/src/stores/plugins.js index dd60a855e5..3632434a79 100644 --- a/ui/src/stores/plugins.js +++ b/ui/src/stores/plugins.js @@ -21,7 +21,7 @@ export default { throw new Error("missing required cls"); } - return this.$http.get(`/api/v1/plugins/${options.cls}?all=true`, {}).then(response => { + return this.$http.get(`/api/v1/plugins/${options.cls}`, {}).then(response => { commit("setPlugin", response.data) return response.data; diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java b/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java index 00bcb0aec2..7d4b416eab 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java @@ -122,7 +122,7 @@ public Map<String, PluginIcon> icons() { @Operation(tags = {"Plugins"}, summary = "Get plugin documentation") public HttpResponse<Doc> pluginDocumentation( @Parameter(description = "The plugin full class name") @PathVariable String cls, - @Parameter(description = "Include all the properties") @QueryValue(value = "all", defaultValue = "false") boolean allProperties + @Parameter(description = "Include all the properties") @QueryValue(value = "all", defaultValue = "false") Boolean allProperties ) throws IOException { ClassPluginDocumentation classPluginDocumentation = pluginDocumentation( pluginService.allPlugins(),
null
val
train
2023-05-04T11:13:09
"2023-04-21T07:57:59Z"
loicmathieu
train
kestra-io/kestra/1157_1230
kestra-io/kestra
kestra-io/kestra/1157
kestra-io/kestra/1230
[ "keyword_pr_to_issue" ]
44f1168564847929c3b3705bdf3d745c9799e21f
43b73a9b11138bcdbfcf395a26fdf33c84c33479
[]
[]
"2023-05-04T09:36:47Z"
[ "bug", "enhancement" ]
Flow Validation not triggered
### Expected Behavior In the flow editor, within the source/doc view, the validation is not being triggered; if you swap to the source/topology view, it is, and your error appears. ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 128216ee8d..19e06722e5 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -732,10 +732,8 @@ flowYaml.value = event; haveChange.value = true; - if (showTopology.value === "combined") { - clearTimeout(timer.value); - timer.value = setTimeout(() => onEdit(event), 500); - } + clearTimeout(timer.value); + timer.value = setTimeout(() => onEdit(event), 500); } const switchView = (event) => { @@ -1170,4 +1168,4 @@ flex-direction: column; width: 20rem; } -</style> \ No newline at end of file +</style>
null
train
train
2023-05-04T16:30:46
"2023-04-13T08:57:41Z"
Skraye
train
kestra-io/kestra/1220_1231
kestra-io/kestra
kestra-io/kestra/1220
kestra-io/kestra/1231
[ "keyword_pr_to_issue" ]
94ae9559b96a73f4e02f5b9c5304dfeb12cd32e6
38901da1e5afb1209917914dfda4fd0a3cf1bfbd
[]
[]
"2023-05-04T11:48:44Z"
[ "bug" ]
UI - Alert block in the documentation are not rendered
### Expected Behavior When using an alert block in the documentation of a task it should be properly rendered. ### Actual Behaviour The alert block is not properly rendered. For example, from the Documentation page: ![image](https://user-images.githubusercontent.com/1819009/235880329-0de1a35e-5699-4e3f-9bce-dabe68fb0cad.png) And from the editor documentation pane: ![image](https://user-images.githubusercontent.com/1819009/235880583-cd6490d0-471f-454c-b5c1-225d16d2b7a1.png) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/package-lock.json", "ui/package.json", "ui/src/components/layout/Markdown.vue", "ui/src/utils/markdown.js", "webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java" ]
[ "ui/package-lock.json", "ui/package.json", "ui/src/components/layout/Markdown.vue", "ui/src/utils/markdown.js", "webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java" ]
[]
diff --git a/ui/package-lock.json b/ui/package-lock.json index 0a2b263357..4b8a9d17a5 100644 --- a/ui/package-lock.json +++ b/ui/package-lock.json @@ -25,6 +25,7 @@ "lodash": "4.17.21", "markdown-it": "^13.0.1", "markdown-it-anchor": "^8.6.6", + "markdown-it-container": "^3.0.0", "markdown-it-mark": "^3.0.1", "markdown-it-meta": "0.0.1", "md5": "^2.3.0", @@ -3007,6 +3008,11 @@ "markdown-it": "*" } }, + "node_modules/markdown-it-container": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/markdown-it-container/-/markdown-it-container-3.0.0.tgz", + "integrity": "sha512-y6oKTq4BB9OQuY/KLfk/O3ysFhB3IMYoIWhGJEidXt1NQFocFK2sA2t0NYZAMyMShAGL6x5OPIbrmXPIqaN9rw==" + }, "node_modules/markdown-it-mark": { "version": "3.0.1", "resolved": "https://registry.npmjs.org/markdown-it-mark/-/markdown-it-mark-3.0.1.tgz", diff --git a/ui/package.json b/ui/package.json index 0b9ab82a63..697ccd25ac 100644 --- a/ui/package.json +++ b/ui/package.json @@ -29,6 +29,7 @@ "markdown-it-anchor": "^8.6.6", "markdown-it-mark": "^3.0.1", "markdown-it-meta": "0.0.1", + "markdown-it-container": "^3.0.0", "md5": "^2.3.0", "moment": "^2.29.4", "moment-range": "4.0.2", diff --git a/ui/src/components/layout/Markdown.vue b/ui/src/components/layout/Markdown.vue index 7fd2b18546..d03f11d790 100644 --- a/ui/src/components/layout/Markdown.vue +++ b/ui/src/components/layout/Markdown.vue @@ -54,6 +54,18 @@ font-size: var(--font-size-md); font-weight: normal; } + + .warning { + background-color: var(--el-color-warning-light-9); + border: 1px solid var(--el-color-warning-light-5); + padding: 8px 16px; + color: var(--el-color-warning); + border-radius: var(--el-border-radius-base); + + p:last-child { + margin-bottom: 0; + } + } } .markdown-tooltip { diff --git a/ui/src/utils/markdown.js b/ui/src/utils/markdown.js index b4262d3230..5915c17e84 100644 --- a/ui/src/utils/markdown.js +++ b/ui/src/utils/markdown.js @@ -2,6 +2,7 @@ import markdownIt from "markdown-it"; import mark from "markdown-it-mark"; import meta from "markdown-it-meta"; import anchor from "markdown-it-anchor"; +import container from "markdown-it-container"; export default class Markdown { static render(markdown, options) { @@ -16,6 +17,8 @@ export default class Markdown { placement: "before" }) : undefined }) + // if more alert types are used inside the task documentation, they need to be configured here also + .use(container, 'warning') md.set({ html: true, diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java b/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java index 7d4b416eab..9c2bac52d6 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/PluginController.java @@ -130,9 +130,13 @@ public HttpResponse<Doc> pluginDocumentation( allProperties ); + var doc = DocumentationGenerator.render(classPluginDocumentation); + doc = doc.replaceAll("\n::alert\\{type=\"(.*)\"\\}\n", "\n::: $1\n"); + doc = doc.replaceAll("\n::\n", "\n:::\n"); + return HttpResponse.ok() .body(new Doc( - DocumentationGenerator.render(classPluginDocumentation), + doc, new Schema( classPluginDocumentation.getPropertiesSchema(), classPluginDocumentation.getOutputsSchema(),
null
train
train
2023-05-13T23:54:22
"2023-05-03T09:31:12Z"
loicmathieu
train
kestra-io/kestra/1221_1232
kestra-io/kestra
kestra-io/kestra/1221
kestra-io/kestra/1232
[ "keyword_pr_to_issue" ]
64446f22794ab02289f319b134c1098e80915d27
6e11a2087e4a8072922791faf9c0bd57ba777e37
[]
[ "```suggestion\r\n```" ]
"2023-05-04T12:48:49Z"
[ "enhancement" ]
Rearrange the order of columns in the Metrics tab
### Feature description Here is an example flow to reproduce the issue: ```yaml id: partitions namespace: dev description: Process partitions in parallel tasks: - id: getPartitions type: io.kestra.core.tasks.scripts.Python inputFiles: main.py: | from kestra import Kestra partitions = [f"file_{nr}.parquet" for nr in range(1, 10)] Kestra.outputs({'partitions': partitions}) - id: processPartitions type: io.kestra.core.tasks.flows.EachParallel value: '{{outputs.getPartitions.vars.partitions}}' tasks: - id: partition type: io.kestra.core.tasks.scripts.Python inputFiles: main.py: | import random import time from kestra import Kestra filename = '{{ taskrun.value }}' print(f"Reading and processing partition {filename}") nr_rows = random.randint(1, 1000) processing_time = random.randint(1, 20) time.sleep(processing_time) Kestra.counter('nr_rows', nr_rows, {'partition': filename}) Kestra.timer('processing_time', processing_time, {'partition': filename}) ``` This flow processes data in parallel from multiple partitions and stores the result metadata as metrics. It would be more readable/understandable if the Tags column was at the end so that name of the metric and its value are next to each other: ![image](https://user-images.githubusercontent.com/86264395/235889740-fee2a6a0-28f5-4d2d-9ca3-dfd8e66b285d.png)
[ "ui/src/components/executions/MetricsTable.vue" ]
[ "ui/src/components/executions/MetricsTable.vue" ]
[]
diff --git a/ui/src/components/executions/MetricsTable.vue b/ui/src/components/executions/MetricsTable.vue index 02a86809e7..103d347084 100644 --- a/ui/src/components/executions/MetricsTable.vue +++ b/ui/src/components/executions/MetricsTable.vue @@ -36,6 +36,18 @@ </template> </el-table-column> + <el-table-column prop="value" sortable :label="$t('value')"> + <template #default="scope"> + <span v-if="scope.row.type === 'timer'"> + {{ $filters.humanizeDuration(scope.row.value / 1000) }} + </span> + <span v-else> + {{ $filters.humanizeNumber(scope.row.value) }} + </span> + </template> + </el-table-column> + + <el-table-column prop="tags" :label="$t('tags')"> <template #default="scope"> <el-tag @@ -50,17 +62,6 @@ </el-tag> </template> </el-table-column> - - <el-table-column prop="value" sortable :label="$t('value')"> - <template #default="scope"> - <span v-if="scope.row.type === 'timer'"> - {{ $filters.humanizeDuration(scope.row.value / 1000) }} - </span> - <span v-else> - {{ $filters.humanizeNumber(scope.row.value) }} - </span> - </template> - </el-table-column> </el-table> </template> </data-table>
null
train
train
2023-05-04T11:13:09
"2023-05-03T10:15:45Z"
anna-geller
train
kestra-io/kestra/1151_1235
kestra-io/kestra
kestra-io/kestra/1151
kestra-io/kestra/1235
[ "keyword_pr_to_issue" ]
3cf551cd0f490a2d45c3c5291a222836f439e754
56283097e61896ef333e3340cb4c0b0ef1f815fd
[]
[ "Check if readOnly before", "Sure, forgot about this part" ]
"2023-05-04T19:00:55Z"
[ "enhancement" ]
Save flow as draft
### Feature description As a Kestra beginner, I imagined I could start a flow and leave it as a draft, But I couldn’t save something with syntax errors As a result, I spent more time than expected fixing my flow, So I end up being late for other activities in my day. *What would have helped?* → A way to save in draft. *Maybe in a deactivated mode?*
[ "ui/src/components/graph/Topology.vue", "ui/src/components/templates/TemplateEdit.vue", "ui/src/mixins/flowTemplateEdit.js", "ui/src/stores/flow.js", "ui/src/translations.json", "ui/src/utils/axios.js", "ui/src/utils/toast.js" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/components/templates/TemplateEdit.vue", "ui/src/mixins/flowTemplateEdit.js", "ui/src/stores/flow.js", "ui/src/translations.json", "ui/src/utils/axios.js", "ui/src/utils/toast.js" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 043bc084a1..4696dd861f 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -1,5 +1,5 @@ <script setup> -import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, computed} from "vue"; + import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, computed} from "vue"; import {useStore} from "vuex" import {VueFlow, useVueFlow, Position, MarkerType} from "@vue-flow/core" import {Controls, ControlButton} from "@vue-flow/controls" @@ -128,6 +128,10 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co const taskError = ref(store.getters["flow/taskError"]) const user = store.getters["auth/user"]; + const localStorageKey = computed(() => { + return (props.isCreating ? "creation" : `${flow.namespace}.${flow.id}`) + "_draft"; + }) + watch(() => store.getters["flow/taskError"], async () => { taskError.value = store.getters["flow/taskError"]; }); @@ -177,7 +181,19 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co id: props.flowId, namespace: props.namespace }); - return flowYaml.value; + generateGraph(); + + if(!props.isReadOnly) { + const sourceFromLocalStorage = localStorage.getItem(localStorageKey.value); + if (sourceFromLocalStorage !== null) { + toast.confirm(props.isCreating ? t("save draft.retrieval.creation") : t("save draft.retrieval.existing", {flowFullName: `${flow.namespace}.${flow.id}`}), () => { + flowYaml.value = sourceFromLocalStorage; + onEdit(flowYaml.value); + }) + + localStorage.removeItem(localStorageKey.value); + } + } } const isTaskNode = (node) => { @@ -209,13 +225,15 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co }; const regenerateGraph = () => { - removeEdges(getEdges.value) - removeNodes(getNodes.value) - removeSelectedElements(getElements.value) - elements.value = [] - nextTick(() => { - generateGraph(); - }) + if(!props.flowError) { + removeEdges(getEdges.value) + removeNodes(getNodes.value) + removeSelectedElements(getElements.value) + elements.value = [] + nextTick(() => { + generateGraph(); + }) + } } const toggleOrientation = () => { @@ -417,7 +435,6 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co store.commit("flow/setFlowGraph", undefined); } initYamlSource(); - generateGraph(); // Regenerate graph on window resize observeWidth(); // Save on ctrl+s in topology @@ -535,30 +552,56 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co } }; + const showDraftPopup = (draftReason, refreshAfterSelect = false) => { + toast.confirm(draftReason + " " + (props.isCreating ? t("save draft.prompt.creation") : t("save draft.prompt.existing", { + namespace: flow.namespace, + id: flow.id + })), + () => { + localStorage.setItem(localStorageKey.value, flowYaml.value); + store.dispatch("core/isUnsaved", false); + if(refreshAfterSelect){ + router.go(); + }else { + router.push({ + name: "flows/list" + }) + } + }, + () => { + if(refreshAfterSelect) { + store.dispatch("core/isUnsaved", false); + router.go(); + } + } + ) + } + const onEdit = (event) => { - store.dispatch("flow/validateFlow", {flow: event}) + return store.dispatch("flow/validateFlow", {flow: event}) .then(value => { - if (value[0].constraints && !flowHaveTasks(event)) { - flowYaml.value = event; - haveChange.value = true; - } else { + flowYaml.value = event; + haveChange.value = true; + store.dispatch("core/isUnsaved", true); + + if (!value[0].constraints) { // flowYaml need to be update before // loadGraphFromSource to avoid // generateGraph to be triggered with the old value - flowYaml.value = event; store.dispatch("flow/loadGraphFromSource", { flow: event, config: { validateStatus: (status) => { return status === 200 || status === 422; } } - }).then(response => { - haveChange.value = true; - store.dispatch("core/isUnsaved", true); }) } - }) + return value; + }).catch(e => { + showDraftPopup(t("save draft.prompt.http_error"), true); + return Promise.reject(e); + }) } const onDelete = (event) => { @@ -740,7 +783,6 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co const editorUpdate = (event) => { updatedFromEditor.value = true; flowYaml.value = event; - haveChange.value = true; clearTimeout(timer.value); timer.value = setTimeout(() => onEdit(event), 500); @@ -780,9 +822,18 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co tours["guidedTour"].nextStep(); return; } - if (props.isCreating) { - const flowParsed = YamlUtils.parse(flowYaml.value); - if (flowParsed.id && flowParsed.namespace) { + + onEdit(flowYaml.value).then(validation => { + let flowParsed; + try { + flowParsed = YamlUtils.parse(flowYaml.value); + } catch (_) {} + if (validation[0].constraints) { + showDraftPopup(t("save draft.prompt.base")); + return; + } + + if (props.isCreating) { store.dispatch("flow/createFlow", {flow: flowYaml.value}) .then((response) => { toast.saved(response.id); @@ -792,22 +843,17 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co params: {id: flowParsed.id, namespace: flowParsed.namespace, tab: "editor"} }); }) - return; - } else { - store.dispatch("core/showMessage", { - variant: "error", - title: t("can not save"), - message: t("flow must have id and namespace") - }); - return; + }else { + store + .dispatch("flow/saveFlow", {flow: flowYaml.value}) + .then((response) => { + toast.saved(response.id); + store.dispatch("core/isUnsaved", false); + }) } - } - store - .dispatch("flow/saveFlow", {flow: flowYaml.value}) - .then((response) => { - toast.saved(response.id); - store.dispatch("core/isUnsaved", false); - }) + + haveChange.value = false; + }) }; const canExecute = () => { @@ -1129,8 +1175,8 @@ import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, co size="large" @click="save" v-if="isAllowedEdit" - :disabled="!haveChange || !flowHaveTasks()" - type="primary" + :type="flowError || !haveChange ? 'danger' : 'primary'" + :disabled="!haveChange" class="edit-flow-save-button" > {{ $t("save") }} diff --git a/ui/src/components/templates/TemplateEdit.vue b/ui/src/components/templates/TemplateEdit.vue index a030274b56..aa647d6a61 100644 --- a/ui/src/components/templates/TemplateEdit.vue +++ b/ui/src/components/templates/TemplateEdit.vue @@ -56,6 +56,9 @@ .dispatch("template/loadTemplate", this.$route.params) .then(this.loadFile); } + }, + onChange() { + this.$store.dispatch("core/isUnsaved", this.previousContent !== this.content); } } }; diff --git a/ui/src/mixins/flowTemplateEdit.js b/ui/src/mixins/flowTemplateEdit.js index c15c12f3dd..fdd1f4c34b 100644 --- a/ui/src/mixins/flowTemplateEdit.js +++ b/ui/src/mixins/flowTemplateEdit.js @@ -177,9 +177,6 @@ export default { }); } }, - onChange() { - this.$store.dispatch("core/isUnsaved", this.previousContent !== this.content); - }, save() { if (this.$tours["guidedTour"].isRunning.value && !this.guidedProperties.saveFlow) { this.$store.dispatch("api/events", { diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 9425e7017a..936b5a4c62 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -211,7 +211,7 @@ export default { return this.$http.delete("/api/v1/flows/delete/by-query", options, {params: options}) }, validateFlow({commit}, options) { - return axios.post(`${apiRoot}flows/validate`, options.flow, textYamlHeader) + return this.$http.post(`${apiRoot}flows/validate`, options.flow, textYamlHeader) .then(response => { commit("setFlowError", response.data[0] ? response.data[0].constraints : undefined) return response.data diff --git a/ui/src/translations.json b/ui/src/translations.json index f2c2d283b6..46eea6692d 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -406,7 +406,19 @@ "error in editor": "An error have been found in the editor", "delete task confirm": "Do you want to delete the task <code>{taskId}</code> ?", "can not save": "Can not save", - "flow must have id and namespace": "Flow must have an id and a namespace." + "flow must have id and namespace": "Flow must have an id and a namespace.", + "save draft": { + "prompt": { + "base": "The current Flow is not valid. Do you still want to save it as a draft ?", + "http_error": "Unable to validate the Flow due to an HTTP error. Do you want to save the current Flow as draft ?", + "creation": "You will retrieve it on your next Flow creation.", + "existing": "You will retrieve it on your next <code>{namespace}.{id}</code> Flow edition." + }, + "retrieval": { + "creation": "A Flow creation draft was retrieved, do you want to resume its edition ?", + "existing": "A <code>{flowFullName}</code> Flow draft was retrieved, do you want to resume its edition ?" + } + } }, "fr": { "id": "Identifiant", @@ -816,6 +828,18 @@ "error in editor": "Une erreur a été trouvé dans l'éditeur", "delete task confirm": "Êtes-vous sûr de vouloir supprimer la tâche <code>{taskId}</code> ?", "can not save": "Impossible de sauvegarder", - "flow must have id and namespace": "Le flow doit avoir un id et un namespace." + "flow must have id and namespace": "Le flow doit avoir un id et un namespace.", + "save draft": { + "prompt": { + "base": "Le Flow actuel est invalide. Voulez-vous le sauvegarder en tant que brouillon ?", + "http_error": "Impossible de valider le Flow en raison d'une erreur HTTP. Voulez-vous sauvegarder le Flow actuel en tant que brouillon ?", + "creation": "Vous le récupérerez à votre prochaine création de Flow.", + "existing": "Vous le récupérerez à votre prochaine édition du Flow <code>{namespace}.{id}</code>." + }, + "retrieval": { + "creation": "Un brouillon de création de Flow existe, voulez-vous reprendre son édition ?", + "existing": "Un brouillon pour le Flow <code>{flowFullName}</code> existe, voulez-vous reprendre son édition?" + } + } } } diff --git a/ui/src/utils/axios.js b/ui/src/utils/axios.js index 714abd3d34..57dfe048af 100644 --- a/ui/src/utils/axios.js +++ b/ui/src/utils/axios.js @@ -96,10 +96,9 @@ export default (callback, store, router) => { return Promise.reject(errorResponse); } - if (errorResponse.response.status === 401 && !store.getters["auth/isLogged"]) { + if (errorResponse.response.status === 401 && (!store.getters["auth/isLogged"] || store.getters["auth/expired"])) { window.location = "/ui/login?from=" + window.location.pathname + (window.location.search ? "?" + window.location.search : "") - } if (errorResponse.response.status === 401 && @@ -111,6 +110,7 @@ export default (callback, store, router) => { return Promise.reject(errorResponse); } + if (errorResponse.response.status === 400){ return Promise.reject(errorResponse.response.data) } @@ -122,6 +122,11 @@ export default (callback, store, router) => { variant: "error" }) + if(errorResponse.response.status === 401 && + store.getters["auth/isLogged"]){ + store.commit("auth/setExpired", true); + } + return Promise.reject(errorResponse); } diff --git a/ui/src/utils/toast.js b/ui/src/utils/toast.js index cc7e307dd5..cd7de19296 100644 --- a/ui/src/utils/toast.js +++ b/ui/src/utils/toast.js @@ -27,7 +27,7 @@ export default { return h("span", {innerHTML: message}); } }, - confirm: function(message, callback) { + confirm: function(message, callback, callbackIfCancel = () => {}) { ElMessageBox.confirm( this._wrap(message || self.$t("toast confirm")), self.$t("confirmation"), @@ -39,7 +39,7 @@ export default { callback(); }) .catch(() => { - + callbackIfCancel() }) }, saved: function(name, title, options) {
null
train
train
2023-05-12T09:32:08
"2023-04-12T14:10:33Z"
Ben8t
train
kestra-io/kestra/1225_1239
kestra-io/kestra
kestra-io/kestra/1225
kestra-io/kestra/1239
[ "keyword_pr_to_issue" ]
94ae9559b96a73f4e02f5b9c5304dfeb12cd32e6
423faa30ec91d1097badf54c1bb98c449bd84eeb
[]
[]
"2023-05-05T14:08:57Z"
[ "bug" ]
Filter on namespace
### Expected Behavior When we filter on a namepace we must only see the selected namespace. Ex: If I have 2 namespace com.test and com.test2 If I select com.test, the 2 namespaces will be displayed. ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8 - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java", "repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java" ]
[ "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java", "repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java" ]
[ "core/src/test/java/io/kestra/core/Helpers.java", "core/src/test/java/io/kestra/core/repositories/AbstractFlowRepositoryTest.java", "core/src/test/resources/flows/valids/minimal2.yaml", "webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java" ]
diff --git a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java index 181cf5dca5..2f6160076a 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java +++ b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcExecutionRepository.java @@ -340,7 +340,7 @@ private <T extends Record> SelectConditionStep<T> filteringQuery( select = select.and(field("namespace").eq(namespace)); select = select.and(field("flow_id").eq(flowId)); } else if (namespace != null) { - select = select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select = select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } if (query != null) { diff --git a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java index 1613cc730e..e15ea66112 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java +++ b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcFlowRepository.java @@ -232,7 +232,7 @@ public ArrayListTotal<Flow> find( select.and(this.findCondition(query, labels)); if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } return this.jdbcRepository.fetchPage(context, select, pageable); @@ -255,7 +255,7 @@ public List<FlowWithSource> findWithSource( select.and(this.findCondition(query, labels)); if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } return select.fetch().map(record -> FlowWithSource.of( @@ -282,7 +282,7 @@ public ArrayListTotal<SearchResult<Flow>> findSourceCode(Pageable pageable, @Nul } if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } return this.jdbcRepository.fetchPage( diff --git a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java index c31f63d524..c5c0ba2149 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java +++ b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcLogRepository.java @@ -47,7 +47,7 @@ public ArrayListTotal<LogEntry> find( .where(this.defaultFilter()); if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } if (flowId != null) { diff --git a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java index 7ebf923b5f..e7f51c2272 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java +++ b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcTemplateRepository.java @@ -90,7 +90,7 @@ public ArrayListTotal<Template> find( } if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } return this.jdbcRepository.fetchPage(context, select, pageable); @@ -117,7 +117,7 @@ public List<Template> find(@Nullable String query, @Nullable String namespace) { } if (namespace != null) { - select.and(field("namespace").likeIgnoreCase(namespace + "%")); + select.and(DSL.or(field("namespace").eq(namespace), field("namespace").likeIgnoreCase(namespace + ".%"))); } return this.jdbcRepository.fetch(select); diff --git a/repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java b/repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java index 5f3db19442..143eaf4905 100644 --- a/repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java +++ b/repository-memory/src/main/java/io/kestra/repository/memory/MemoryFlowRepository.java @@ -131,7 +131,7 @@ public ArrayListTotal<Flow> find( //TODO Non used query, just returns all flow and filter by namespace if set List<Flow> results = flows.values() .stream() - .filter(flow -> namespace == null || flow.getNamespace().startsWith(namespace)) + .filter(flow -> namespace == null || flow.getNamespace().equals(namespace) || flow.getNamespace().startsWith(namespace + ".")) .collect(Collectors.toList()); return ArrayListTotal.of(pageable, results); } @@ -145,7 +145,7 @@ public List<FlowWithSource> findWithSource( //TODO Non used query, just returns all flow and filter by namespace if set return flows.values() .stream() - .filter(flow -> namespace == null || flow.getNamespace().startsWith(namespace)) + .filter(flow -> namespace == null || flow.getNamespace().equals(namespace) || flow.getNamespace().startsWith(namespace + ".")) .sorted(Comparator.comparingInt(Flow::getRevision)) .map(flow -> findByIdWithSource(flow.getNamespace(), flow.getId(), Optional.of(flow.getRevision())).get()) .collect(Collectors.toList());
diff --git a/core/src/test/java/io/kestra/core/Helpers.java b/core/src/test/java/io/kestra/core/Helpers.java index 82bd964bb3..9c297da7a8 100644 --- a/core/src/test/java/io/kestra/core/Helpers.java +++ b/core/src/test/java/io/kestra/core/Helpers.java @@ -19,7 +19,7 @@ import java.util.function.Consumer; public class Helpers { - public static long FLOWS_COUNT = 63; + public static long FLOWS_COUNT = 64; public static ApplicationContext applicationContext() throws URISyntaxException { return applicationContext( diff --git a/core/src/test/java/io/kestra/core/repositories/AbstractFlowRepositoryTest.java b/core/src/test/java/io/kestra/core/repositories/AbstractFlowRepositoryTest.java index 7640ee857d..eaae927074 100644 --- a/core/src/test/java/io/kestra/core/repositories/AbstractFlowRepositoryTest.java +++ b/core/src/test/java/io/kestra/core/repositories/AbstractFlowRepositoryTest.java @@ -212,7 +212,10 @@ void findAll() { @Test void findByNamespace() { List<Flow> save = flowRepository.findByNamespace("io.kestra.tests"); - assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 1)); + assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 2)); + + save = flowRepository.findByNamespace("io.kestra.tests2"); + assertThat((long) save.size(), is(1L)); save = flowRepository.findByNamespace("io.kestra.tests.minimal.bis"); assertThat((long) save.size(), is(1L)); @@ -230,7 +233,10 @@ void find() { @Test void findWithSource() { List<FlowWithSource> save = flowRepository.findWithSource(null, "io.kestra.tests", Collections.emptyMap()); - assertThat((long) save.size(), is(Helpers.FLOWS_COUNT)); + assertThat((long) save.size(), is(Helpers.FLOWS_COUNT - 1)); + + save = flowRepository.findWithSource(null, "io.kestra.tests2", Collections.emptyMap()); + assertThat((long) save.size(), is(1L)); save = flowRepository.findWithSource(null, "io.kestra.tests.minimal.bis", Collections.emptyMap()); assertThat((long) save.size(), is(1L)); @@ -368,7 +374,7 @@ void removeTriggerDelete() throws InterruptedException { @Test void findDistinctNamespace() { List<String> distinctNamespace = flowRepository.findDistinctNamespace(); - assertThat((long) distinctNamespace.size(), is(2L)); + assertThat((long) distinctNamespace.size(), is(3L)); } @Singleton diff --git a/core/src/test/resources/flows/valids/minimal2.yaml b/core/src/test/resources/flows/valids/minimal2.yaml new file mode 100644 index 0000000000..1689ef77e0 --- /dev/null +++ b/core/src/test/resources/flows/valids/minimal2.yaml @@ -0,0 +1,7 @@ +id: minimal +namespace: io.kestra.tests2 + +tasks: +- id: date + type: io.kestra.core.tasks.debugs.Return + format: "{{taskrun.startDate}}" diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java index 9bbd8b9493..946c96339d 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java @@ -393,7 +393,7 @@ void listDistinctNamespace() { List<String> namespaces = client.toBlocking().retrieve( HttpRequest.GET("/api/v1/flows/distinct-namespaces"), Argument.listOf(String.class)); - assertThat(namespaces.size(), is(2)); + assertThat(namespaces.size(), is(3)); } @Test @@ -496,7 +496,7 @@ void exportByQuery() throws IOException { Files.write(file.toPath(), zip); try (ZipFile zipFile = new ZipFile(file)) { - assertThat(zipFile.stream().count(), is(Helpers.FLOWS_COUNT)); + assertThat(zipFile.stream().count(), is(Helpers.FLOWS_COUNT -1)); } file.delete();
val
train
2023-05-13T23:54:22
"2023-05-04T06:48:37Z"
aurelienWls
train
kestra-io/kestra/1151_1248
kestra-io/kestra
kestra-io/kestra/1151
kestra-io/kestra/1248
[ "connected" ]
56283097e61896ef333e3340cb4c0b0ef1f815fd
73d9ec181cad566b1b12c130518109dec71fe197
[]
[]
"2023-05-09T19:40:24Z"
[ "enhancement" ]
Save flow as draft
### Feature description As a Kestra beginner, I imagined I could start a flow and leave it as a draft, But I couldn’t save something with syntax errors As a result, I spent more time than expected fixing my flow, So I end up being late for other activities in my day. *What would have helped?* → A way to save in draft. *Maybe in a deactivated mode?*
[ "ui/src/components/graph/Topology.vue", "ui/src/utils/axios.js", "ui/src/utils/toast.js" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/utils/axios.js", "ui/src/utils/toast.js" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 4696dd861f..8bff2a8b29 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -132,11 +132,14 @@ return (props.isCreating ? "creation" : `${flow.namespace}.${flow.id}`) + "_draft"; }) + const autoRestorelocalStorageKey = computed(() => { + return "autoRestore-"+localStorageKey.value; + }) + watch(() => store.getters["flow/taskError"], async () => { taskError.value = store.getters["flow/taskError"]; }); - const flowables = () => { return props.flowGraph && props.flowGraph.flowables ? props.flowGraph.flowables : []; } @@ -184,14 +187,18 @@ generateGraph(); if(!props.isReadOnly) { - const sourceFromLocalStorage = localStorage.getItem(localStorageKey.value); + let restoredLocalStorageKey; + const sourceFromLocalStorage = localStorage.getItem((restoredLocalStorageKey = autoRestorelocalStorageKey.value)) ?? localStorage.getItem((restoredLocalStorageKey = localStorageKey.value)); if (sourceFromLocalStorage !== null) { - toast.confirm(props.isCreating ? t("save draft.retrieval.creation") : t("save draft.retrieval.existing", {flowFullName: `${flow.namespace}.${flow.id}`}), () => { - flowYaml.value = sourceFromLocalStorage; - onEdit(flowYaml.value); - }) + if(restoredLocalStorageKey === autoRestorelocalStorageKey.value){ + onEdit(sourceFromLocalStorage); + }else { + toast.confirm(props.isCreating ? t("save draft.retrieval.creation") : t("save draft.retrieval.existing", {flowFullName: `${flow.namespace}.${flow.id}`}), () => { + onEdit(sourceFromLocalStorage); + }) + } - localStorage.removeItem(localStorageKey.value); + localStorage.removeItem(restoredLocalStorageKey); } } } @@ -463,7 +470,10 @@ window.removeEventListener("beforeunload", persistEditorWidth); - persistEditorWidth(); + // Will get redirected to login page + if (!store.getters["auth/isLogged"] && haveChange.value) { + persistEditorContent(true); + } }) @@ -552,38 +562,33 @@ } }; - const showDraftPopup = (draftReason, refreshAfterSelect = false) => { + const persistEditorContent = (autoRestore) => { + if(autoRestore && localStorage.getItem(localStorageKey.value)) { + return; + } + + localStorage.setItem(autoRestore ? autoRestorelocalStorageKey.value : localStorageKey.value, flowYaml.value); + store.dispatch("core/isUnsaved", false); + haveChange.value = false; + } + + const showDraftPopup = (draftReason) => { toast.confirm(draftReason + " " + (props.isCreating ? t("save draft.prompt.creation") : t("save draft.prompt.existing", { namespace: flow.namespace, id: flow.id })), () => { - localStorage.setItem(localStorageKey.value, flowYaml.value); - store.dispatch("core/isUnsaved", false); - if(refreshAfterSelect){ - router.go(); - }else { - router.push({ - name: "flows/list" - }) - } - }, - () => { - if(refreshAfterSelect) { - store.dispatch("core/isUnsaved", false); - router.go(); - } + persistEditorContent(false); } - ) + ); } const onEdit = (event) => { + flowYaml.value = event; + haveChange.value = true; + store.dispatch("core/isUnsaved", true); return store.dispatch("flow/validateFlow", {flow: event}) .then(value => { - flowYaml.value = event; - haveChange.value = true; - store.dispatch("core/isUnsaved", true); - if (!value[0].constraints) { // flowYaml need to be update before // loadGraphFromSource to avoid @@ -598,10 +603,7 @@ } return value; - }).catch(e => { - showDraftPopup(t("save draft.prompt.http_error"), true); - return Promise.reject(e); - }) + }); } const onDelete = (event) => { diff --git a/ui/src/utils/axios.js b/ui/src/utils/axios.js index 57dfe048af..e25e4b01bc 100644 --- a/ui/src/utils/axios.js +++ b/ui/src/utils/axios.js @@ -96,9 +96,14 @@ export default (callback, store, router) => { return Promise.reject(errorResponse); } - if (errorResponse.response.status === 401 && (!store.getters["auth/isLogged"] || store.getters["auth/expired"])) { - window.location = "/ui/login?from=" + window.location.pathname + - (window.location.search ? "?" + window.location.search : "") + if (errorResponse.response.status === 401 + && !store.getters["auth/isLogged"]) { + if(window.location.pathname === "/ui/login"){ + return Promise.reject(errorResponse); + } + + window.location = `/ui/login?from=${window.location.pathname + + (window.location.search ?? "")}` } if (errorResponse.response.status === 401 && @@ -111,6 +116,23 @@ export default (callback, store, router) => { return Promise.reject(errorResponse); } + // Authentication expired + if (errorResponse.response.status === 401 && + store.getters["auth/isLogged"]) { + document.body.classList.add("login") + + store.dispatch("core/isUnsaved", false); + store.commit("auth/setUser", undefined); + store.commit("layout/setTopNavbar", undefined); + router.push({ + name: "login", + query: { + expired: 1, + from: window.location.pathname + (window.location.search ?? "") + } + }) + } + if (errorResponse.response.status === 400){ return Promise.reject(errorResponse.response.data) } diff --git a/ui/src/utils/toast.js b/ui/src/utils/toast.js index cd7de19296..a67f20c439 100644 --- a/ui/src/utils/toast.js +++ b/ui/src/utils/toast.js @@ -38,9 +38,6 @@ export default { .then(() => { callback(); }) - .catch(() => { - callbackIfCancel() - }) }, saved: function(name, title, options) { ElNotification.closeAll();
null
test
train
2023-05-12T11:12:38
"2023-04-12T14:10:33Z"
Ben8t
train
kestra-io/kestra/1249_1250
kestra-io/kestra
kestra-io/kestra/1249
kestra-io/kestra/1250
[ "keyword_pr_to_issue" ]
bebfd8f8b314fe898315049167f0d3cdd76c6761
3cf551cd0f490a2d45c3c5291a222836f439e754
[]
[]
"2023-05-10T07:53:58Z"
[ "bug" ]
Refreshing editor page make title disappear
### Expected Behavior When refreshing on the editor page, should not remove title. ### Actual Behaviour ![image](https://github.com/kestra-io/kestra/assets/37600690/5a21f2a8-6b09-41cf-9e50-19b7a8b9c840) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8.1 SNAPSHOT ### Example flow _No response_
[ "ui/src/components/flows/FlowCreate.vue" ]
[ "ui/src/components/flows/FlowCreate.vue" ]
[]
diff --git a/ui/src/components/flows/FlowCreate.vue b/ui/src/components/flows/FlowCreate.vue index 9482878481..ca26a77258 100644 --- a/ui/src/components/flows/FlowCreate.vue +++ b/ui/src/components/flows/FlowCreate.vue @@ -17,8 +17,10 @@ <script> import Topology from "../graph/Topology.vue"; import {mapGetters, mapState} from "vuex"; + import RouteContext from "../../mixins/routeContext"; export default { + mixins: [RouteContext], components: { Topology }, @@ -37,6 +39,11 @@ ...mapState("plugin", ["pluginSingleList", "pluginsDocumentation"]), ...mapGetters("core", ["guidedProperties"]), ...mapGetters("flow", ["flowError"]), + routeInfo() { + return { + title: this.$t("flows") + }; + }, }, beforeRouteLeave(to, from, next) { this.$store.commit("flow/setFlow", null);
null
val
train
2023-05-10T07:39:04
"2023-05-10T06:50:40Z"
Skraye
train
kestra-io/kestra/1118_1256
kestra-io/kestra
kestra-io/kestra/1118
kestra-io/kestra/1256
[ "keyword_pr_to_issue" ]
bebfd8f8b314fe898315049167f0d3cdd76c6761
434e2273b9d705e637ba1297cc3f825b87803549
[ "An example of a broken execution duration via `/api/v1/executions/{executionId}`:\r\n\r\n[4Dxtymd4UR4yQUjqTs3MSG.json.txt](https://github.com/kestra-io/kestra/files/11109546/4Dxtymd4UR4yQUjqTs3MSG.json.txt)\r\n\r\n![image](https://user-images.githubusercontent.com/13468636/228778339-78c89202-4bfe-497c-8650-8de070fef7f5.png)" ]
[]
"2023-05-10T12:48:14Z"
[ "bug" ]
Broken execution duration/gantt chart when running under load
### Expected Behavior The Gantt chart displaying an execution of a sequential flow has (almost) no overlaps. The rendered execution duration matches the data. ### Actual Behaviour In some cases execution's duration doesn't get updated correctly. This happens mainly when the Kestra cluster is under load. The issue manifests itself in Gantt chart displaying an execution of _a sequential process_ contains strange overlaps. Execution of the second task on the chart displayed below states its duration was zero seconds and the chart illustrates a 1+ hour runtime. This is clearly wrong as both the tool tip and the rest of the chart show real duration sub-timings. ![image](https://user-images.githubusercontent.com/13468636/228749566-1168724b-0391-4c98-9fa2-fac04fbf3440.png) This issue also affects the Executions table. The list of executions sorted by their duration gets sorted correctly but displaying odd duration for those executions having broken duration/Gantt chart. ![image (1)](https://user-images.githubusercontent.com/13468636/228752069-cbf2d2aa-97d9-4bcb-b05d-c46d60854513.png) ### Steps To Reproduce 1. Create the attached `io.kestra.tests.ATF0P0test` flow 2. Load Kestra with a stream of new executions of the flow 3. Sort the Executions table by Duration 4. Observe & pick executions having an odd value of Duration ### Environment Information - Kestra Version: 0.7.1 - Operating System (OS / Docker / Kubernetes): CentOS - Java Version (If not docker): openjdk version "11.0.18" 2023-01-17 LTS - Persistence/Queues: PostgreSQL 14.5 Timezone info: > `$ timedatectl` > Local time: Wed 2023-03-29 10:53:16 CEST > Universal time: Wed 2023-03-29 08:53:16 UTC > RTC time: Wed 2023-03-29 08:53:15 > Time zone: Europe/Prague (CEST, +0200) > NTP enabled: yes > NTP synchronized: yes > RTC in local TZ: no > DST active: yes > Last DST change: DST began at > Sun 2023-03-26 01:59:59 CET > Sun 2023-03-26 03:00:00 CEST > Next DST change: DST ends (the clock jumps one hour backwards) at > Sun 2023-10-29 02:59:59 CEST > Sun 2023-10-29 02:00:00 CET ### Example flow ```yaml id: ATF0P0test namespace: io.kestra.tests description: Model of test workflow. disabled: false labels: connector: test mode: transformation inputs: - type: FILE description: Current input file - mandatory. name: inputMessage - type: STRING description: Current CLE ID - mandatory. name: CLEID - type: STRING description: Current TDID - mandatory. name: TDID - type: STRING description: Current reference ID - mandatory. name: REF_NR - type: STRING description: Current COV DEID - mandatory. name: COV_DEID - type: STRING description: Path to the XSLT sheet - mandatory. name: xsltPath - type: STRING description: Path to the input serv resource - optional. name: servInputResourcePath required: false - type: STRING description: The input serv service - dependent. name: servInputService required: false - type: STRING description: The encoding of the flat input serv - dependent. name: servInputEncoding defaults: ISO-8859-1 required: false - type: STRING description: Path to the output serv resource - optional. name: servOutputResourcePath required: false - type: STRING description: The output serv service name - dependent. name: servOutputService required: false - type: STRING description: The encoding of the flat output serv - dependent. name: servOutputEncoding defaults: ISO-8859-1 required: false - type: BOOLEAN description: Is this execution treated as a test or not - mandatory. name: test defaults: "false" - type: JSON description: JSON struct - mandatory. name: sender variables: customScriptsDirPath: "/opt/custom" tasks: - id: archivate-input type: io.kestra.core.tasks.scripts.Bash description: "Archive input" commands: - > "{{ vars.customScriptsDirPath }}/common-tools/archive.sh" "FILE_TO_AR={{ inputs.inputMessage }}" "SENDER={{ inputs.CLEID }}" "RECEIVER=test" "OBJ_CLASS={{ flow.id }}" "JOB_ID={{ execution.id }}" "TDID={{ inputs.TDID }}" "STAGE=INPUT" - id: validate-input type: io.kestra.core.tasks.scripts.Bash description: "Validate input" commands: - > "{{ vars.customScriptsDirPath }}/validation/validate-CIV.sh" "VALIDATION_CONFIG=" "JOBID={{ execution.id }}" "TDID={{ inputs.TDID }}" "VALIDATION_INPUT={{ inputs.inputMessage }}" "VALIDATION_TEMP={{ inputs.inputMessage ~ ".valtf" }}" "REACTION_OBJ_CLASS=" "SENDER=test" "RECEIVER={{ inputs.CLEID }}" "OBJ_CLASS={{ flow.id }}" "COV_DEID={{ inputs.COV_DEID }}" "WF_WARNING=" - id: run-input-serv-when-necessary type: io.kestra.core.tasks.flows.Switch value: "{{ inputs contains 'servInputResourcePath' ? 'RUN' : 'SKIP' }}" cases: RUN: - id: run-input-serv type: io.kestra.core.tasks.scripts.Bash description: "Run serv on the input" outputFiles: - xmlMessage commands: - > "{{ vars.customScriptsDirPath }}/call_serv.sh" "{{ inputs.servInputResourcePath }}" "{{ inputs.inputMessage }}" "{{ outputFiles.xmlMessage }}" "service={{ inputs.servInputService }}" "{{ "encoding=" ~ inputs.servInputEncoding }}" defaults: - id: skipping-input-serv type: io.kestra.core.tasks.debugs.Echo description: "Switch requires to have a task to execute" format: "Skipping input serv" - id: transform-file-using-XSLT type: io.kestra.core.tasks.scripts.Bash description: "Transform the input using given XLST transformation" outputFiles: - transformedMessage - tferrFile commands: - > "{{ vars.customScriptsDirPath }}/transform/transform-xslt.sh" "XSL_FILE={{ inputs.xsltPath }}" "INPUT_FILE={{ outputs contains "run-input-serv" ? outputs["run-input-serv"].outputFiles.xmlMessage : inputs.inputMessage }}" "OUTPUT_FILE={{ outputFiles.transformedMessage }}" "STRICT_PARSE=true" "NAN_VALIDATION=true" "TFERR={{ outputFiles.tferrFile }}" "REF_NR={{ inputs.REF_NR }}" - id: run-output-serv-when-necessary type: io.kestra.core.tasks.flows.Switch value: "{{ inputs contains 'servOutputResourcePath' ? 'RUN' : 'SKIP' }}" cases: RUN: - id: run-output-serv type: io.kestra.core.tasks.scripts.Bash description: "Run serv on the output" outputFiles: - flatMessage commands: - > "{{ vars.customScriptsDirPath }}/call_serv.sh" "{{ inputs.servOutputResourcePath }}" "{{ outputs["transform-file-using-XSLT"].outputFiles.transformedMessage }}" "{{ outputFiles.flatMessage }}" "service={{ inputs.servOutputService }}" "{{ "encoding=" ~ inputs.servOutputEncoding }}" defaults: - id: skipping-output-serv type: io.kestra.core.tasks.debugs.Echo description: "Switch requires to have a task to execute" format: "Skipping output serv" - id: archivate-output type: io.kestra.core.tasks.scripts.Bash description: "Archive output" commands: - > "{{ vars.customScriptsDirPath }}/common-tools/archive.sh" "FILE_TO_AR={{ outputs contains "run-output-serv" ? outputs["run-output-serv"].outputFiles.flatMessage : outputs["transform-file-using-XSLT"].outputFiles.transformedMessage }}" "SENDER={{ inputs.CLEID }}" "RECEIVER=test" "OBJ_CLASS={{ flow.id }}" "JOB_ID={{ execution.id }}" "TDID={{ inputs.TDID }}" "STAGE=OUTPUT" - id: validate-output type: io.kestra.core.tasks.scripts.Bash description: "Validate output" commands: - > "{{ vars.customScriptsDirPath }}/validation/validate-COV.sh" "VALIDATION_CONFIG=" "JOBID={{ execution.id }}" "TDID={{ inputs.TDID }}" "VALIDATION_INPUT={{ outputs contains "run-output-serv" ? outputs["run-output-serv"].outputFiles.flatMessage : outputs["transform-file-using-XSLT"].outputFiles.transformedMessage }}" "VALIDATION_TEMP={{ inputs.inputMessage ~ ".valtf" }}" "REACTION_OBJ_CLASS=" "SENDER=test" "RECEIVER={{ inputs.CLEID }}" "OBJ_CLASS={{ flow.id }}" "COV_DEID={{ inputs.COV_DEID }}" "WF_WARNING=" - id: sent-to-test type: io.kestra.core.tasks.scripts.Bash description: "Send the ultimate payload" commands: - > "{{ vars.customScriptsDirPath }}/connectors/test/call-test-send.sh" "JOB_ID={{ execution.id }}" "FILE={{ outputs contains "run-output-serv" ? outputs["run-output-serv"].outputFiles.flatMessage : outputs["transform-file-using-XSLT"].outputFiles.transformedMessage }}" "RECEIVER_SID={{ inputs.sender.RECEIVER_SID }}" "VFN={{ inputs.sender.VFN }}" "SENDER_SID={{ inputs.sender.SENDER_SID }}" "IN_EBCDIC={{ inputs.sender.IN_EBCDIC }}" "FORMAT={{ inputs.sender.FORMAT }}" "SECURITY={{ inputs.sender.SECURITY }}" "SERIALIZE={{ inputs.sender.SERIALIZE }}" "LABEL={{ inputs.sender.LABEL }}" "PRIORITY={{ inputs.sender.PRIORITY }}" "ENCRYPTION={{ inputs.sender.ENCRYPTION }}" "COMPRESSION={{ inputs.sender.COMPRESSION }}" "SIGN={{ inputs.sender.SIGN }}" "REQ_SIGNED_RESPONSE={{ inputs.sender.REQ_SIGNED_RESPONSE }}" - id: wait-for-DN type: io.kestra.core.tasks.flows.Pause description: "Wait 20 sec for the DN delivery notification to arrive from test" delay: PT20S tasks: - id: check-test type: io.kestra.core.tasks.scripts.Bash description: "Check whether the DN arrived" commands: - > "{{ vars.customScriptsDirPath }}/connectors/rvs/call-rvs-eerp.sh" "JOB_ID={{ execution.id }}" "FILE={{ outputs contains "run-output-serv" ? outputs["run-output-serv"].outputFiles.flatMessage : outputs["transform-file-using-XSLT"].outputFiles.transformedMessage }}" "EERP_FILE={{ outputs contains "run-output-serv" ? outputs["run-output-serv"].outputFiles.flatMessage ~ ".eerp" : outputs["transform-file-using-XSLT"].outputFiles.transformedMessage ~ ".eerp" }}" "CLEID={{ inputs.CLEID }}" "SENDER={{ inputs.CLEID }}" "RECEIVER=test" "OBJ_CLASS=IFTS97_DAIM_BE" taskDefaults: - type: io.kestra.core.tasks.scripts.Bash values: interpreter: /bin/bash # always use Bash timeout: PT15S retry: maxAttempt: 4 type: exponential interval: PT2S delayFactor: 2 maxInterval: PT2M - type: io.kestra.core.tasks.debugs.Echo values: timeout: PT15S retry: maxAttempt: 4 type: exponential interval: PT2S delayFactor: 2 maxInterval: PT2M ```
[ "ui/src/components/executions/Gantt.vue" ]
[ "ui/src/components/executions/Gantt.vue" ]
[]
diff --git a/ui/src/components/executions/Gantt.vue b/ui/src/components/executions/Gantt.vue index 8afa9cf33f..38596f8038 100644 --- a/ui/src/components/executions/Gantt.vue +++ b/ui/src/components/executions/Gantt.vue @@ -31,7 +31,7 @@ </span> </template> <div - :style="{left: Math.max(1, (currentTaskRun.start - 1)) + '%', width: currentTaskRun.width - 1 + '%'}" + :style="{left: currentTaskRun.start + '%', width: currentTaskRun.width + '%'}" class="task-progress" @click="onTaskSelect(currentTaskRun.task)" >
null
test
train
2023-05-10T07:39:04
"2023-03-30T06:54:06Z"
yuri1969
train
kestra-io/kestra/1243_1259
kestra-io/kestra
kestra-io/kestra/1243
kestra-io/kestra/1259
[ "keyword_pr_to_issue" ]
bebfd8f8b314fe898315049167f0d3cdd76c6761
22d7febfcde250ee7ec98e359d7adb0b30eff71c
[ "Can't reproduce on my side (either from Flow page or Revision tab 🤔). Do you have any steps to reproduce ?", "on the execution page, execute a flow, delete the flow and go back on the execution page of this deleted flow. ", "indeed\r\n\r\n![image](https://github.com/kestra-io/kestra/assets/46634684/8c567b39-e21c-424e-a362-0442b75f57ce)\r\n![image](https://github.com/kestra-io/kestra/assets/46634684/edf8af5c-33be-426a-9bcf-6f1a9e6b9b15)\r\n\r\n" ]
[]
"2023-05-10T13:34:12Z"
[ "bug" ]
Deleted flow led to a 404 on execution page
And it's seems that revision is not passed on call from this page
[ "ui/src/stores/flow.js", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "ui/src/stores/flow.js", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[]
diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 334fd0f9a0..065bdc644d 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -52,6 +52,7 @@ export default { loadFlow({commit}, options) { return this.$http.get(`/api/v1/flows/${options.namespace}/${options.id}?source=true`, { + params: options, validateStatus: (status) => { return options.deleted ? status === 200 || status === 404 : status === 200; } diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index eb4514ead5..301996e8fa 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -111,14 +111,15 @@ public FlowGraph flowGraphSource( public Flow index( @Parameter(description = "The flow namespace") @PathVariable String namespace, @Parameter(description = "The flow id") @PathVariable String id, - @Parameter(description = "Include the source code") @QueryValue(defaultValue = "false") boolean source + @Parameter(description = "Include the source code") @QueryValue(defaultValue = "false") boolean source, + @Parameter(description = "Get latest revision by default") @Nullable @QueryValue Integer revision ) { return source ? flowRepository - .findByIdWithSource(namespace, id) + .findByIdWithSource(namespace, id, Optional.ofNullable(revision)) .orElse(null) : flowRepository - .findById(namespace, id) + .findById(namespace, id, Optional.ofNullable(revision)) .orElse(null); }
null
train
train
2023-05-10T07:39:04
"2023-05-07T19:29:23Z"
tchiotludo
train
kestra-io/kestra/1236_1266
kestra-io/kestra
kestra-io/kestra/1236
kestra-io/kestra/1266
[ "keyword_pr_to_issue" ]
419bf58ac290ece375b157a3f6257b18534ffa7c
844823a5b5a9aa10206f9c9e2d678cbcf7ee7b58
[ "@tchiotludo precise the flow pls", "https://demo.kestra.io/ui/flows/edit/io.kestra.demo.scripts/bash-docker-with-files/editor" ]
[]
"2023-05-10T15:24:30Z"
[ "bug" ]
Low code failed to open subobject
![image](https://user-images.githubusercontent.com/2064609/236322787-d5c002ee-30e3-4d7e-a130-53d38685c3e1.png)
[ "ui/src/components/flows/tasks/TaskComplex.vue" ]
[ "ui/src/components/flows/tasks/TaskComplex.vue" ]
[]
diff --git a/ui/src/components/flows/tasks/TaskComplex.vue b/ui/src/components/flows/tasks/TaskComplex.vue index 29405dcca0..6a6a73030a 100644 --- a/ui/src/components/flows/tasks/TaskComplex.vue +++ b/ui/src/components/flows/tasks/TaskComplex.vue @@ -4,7 +4,7 @@ :disabled="true" > <template #append> - <el-button :icon="Eye" @click="this.isOpen = true" /> + <el-button :icon="Eye" @click="isOpen = true" /> </template> </el-input>
null
train
train
2023-05-10T17:06:47
"2023-05-04T20:33:44Z"
tchiotludo
train
kestra-io/kestra/1219_1268
kestra-io/kestra
kestra-io/kestra/1219
kestra-io/kestra/1268
[ "keyword_pr_to_issue" ]
419bf58ac290ece375b157a3f6257b18534ffa7c
35662f173144c3ce9973f02fdd4bde9151e25674
[]
[]
"2023-05-10T16:19:03Z"
[ "bug", "enhancement" ]
Discrepancies while changing color "Theme" and "Editor Theme"
### Expected Behavior Color themes should be applied ### Actual Behaviour ![image](https://user-images.githubusercontent.com/46634684/235871398-06399375-6fe4-41bc-a287-87e81d4c6fb4.png) Themes are not applied when Theme = Dark and Editor Theme = Light. ![image](https://user-images.githubusercontent.com/46634684/235871322-db593e7e-2c98-45b6-961f-b8ee4529551f.png) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8.1 - Operating System (OS / Docker / Kubernetes): Docker - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/inputs/Editor.vue" ]
[ "ui/src/components/inputs/Editor.vue" ]
[]
diff --git a/ui/src/components/inputs/Editor.vue b/ui/src/components/inputs/Editor.vue index e88e9ef218..74687420c9 100644 --- a/ui/src/components/inputs/Editor.vue +++ b/ui/src/components/inputs/Editor.vue @@ -113,7 +113,8 @@ !this.input ? "" : "single-line", !this.fullHeight ? "" : "full-height", !this.original ? "" : "diff", - "theme-" + this.themeComputed + "theme-" + this.themeComputed, + this.themeComputed === "dark" ? "custom-dark-vs-theme" : "" ] }, showPlaceholder() { @@ -436,7 +437,7 @@ } } - html.dark { + .custom-dark-vs-theme { .monaco-editor, .monaco-editor-background { background-color: var(--input-bg); --vscode-editor-background: var(--input-bg);
null
test
train
2023-05-10T17:06:47
"2023-05-03T08:51:11Z"
Ben8t
train
kestra-io/kestra/1228_1269
kestra-io/kestra
kestra-io/kestra/1228
kestra-io/kestra/1269
[ "keyword_pr_to_issue" ]
434e2273b9d705e637ba1297cc3f825b87803549
748ec1149c0ab64c5e316a7a2ac53e65b1ad8de8
[]
[ "Tooltip are always dark even on light theme. \r\nPlease just add some style for the text ", "prefect :+1: " ]
"2023-05-11T07:45:27Z"
[ "bug", "enhancement" ]
[Topology - Task Editor] Task validation tooltip is unreadable while in Light Editor / Theme
### Expected Behavior We should be able to read tooltip even in Light theme ### Actual Behaviour ![image](https://user-images.githubusercontent.com/37618489/236160158-f4a66da2-02b5-47d8-b38a-5ab132f390f9.png) ![image](https://user-images.githubusercontent.com/37618489/236160423-2003e0e5-7c1b-4c68-a558-af100509996f.png) ### Steps To Reproduce Light mode editor Go to Topology Edit a task Tooltip is unreadable ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT ### Example flow _No response_
[ "ui/src/components/flows/ValidationError.vue" ]
[ "ui/src/components/flows/ValidationError.vue" ]
[]
diff --git a/ui/src/components/flows/ValidationError.vue b/ui/src/components/flows/ValidationError.vue index 7a169d62a9..91efd35cfc 100644 --- a/ui/src/components/flows/ValidationError.vue +++ b/ui/src/components/flows/ValidationError.vue @@ -37,6 +37,10 @@ max-width: 40vw; white-space: pre-wrap; background: transparent; + color: var(--bs-gray-100); + html.dark & { + color: var(--bs-gray-900); + } padding: 0; }
null
train
train
2023-05-10T21:26:59
"2023-05-04T09:10:09Z"
brian-mulier-p
train
kestra-io/kestra/1208_1272
kestra-io/kestra
kestra-io/kestra/1208
kestra-io/kestra/1272
[ "keyword_pr_to_issue" ]
e3c5da6614bcd87365699e3a81d1dd9b06620422
694af59ee5de07687c222d1e0556636183ee6607
[]
[]
"2023-05-11T12:55:01Z"
[ "enhancement" ]
Allow to re-execute a flow
### Feature description It would be great to be able to re-run a job with the exact same parameters on the interface. It would be useful for a flow with inputs (like a file). Currently, we need to download the file and click "new execution" on a killed job for example. We just had a bug with BigQuery not sending back any data, and had to kill our flow. As they were curl called flows with a file and a second parameter, the procedure to execute it again was a bit long and boring. A button, like the "restart" button on failed execution would help greatly, but it would have to start the job from the very beginning instead of restarting at the failed step. ![image](https://user-images.githubusercontent.com/50616421/234864867-0e39d4ab-1866-4a69-bfb1-c4b47479f6a1.png)
[ "core/src/main/java/io/kestra/core/services/ExecutionService.java", "ui/src/components/executions/Overview.vue", "ui/src/components/executions/Restart.vue", "ui/src/components/flows/FlowRun.vue", "ui/src/components/flows/TriggerFlow.vue", "ui/src/components/inputs/Editor.vue", "ui/src/components/logs/LogList.vue", "ui/src/translations.json", "ui/src/utils/submitTask.js" ]
[ "core/src/main/java/io/kestra/core/services/ExecutionService.java", "ui/src/components/executions/Overview.vue", "ui/src/components/executions/Restart.vue", "ui/src/components/flows/FlowRun.vue", "ui/src/components/flows/TriggerFlow.vue", "ui/src/components/inputs/Editor.vue", "ui/src/components/logs/LogList.vue", "ui/src/translations.json", "ui/src/utils/submitTask.js" ]
[ "core/src/test/java/io/kestra/core/runners/ExecutionServiceTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/services/ExecutionService.java b/core/src/main/java/io/kestra/core/services/ExecutionService.java index 7ec700ad0c..f889369396 100644 --- a/core/src/main/java/io/kestra/core/services/ExecutionService.java +++ b/core/src/main/java/io/kestra/core/services/ExecutionService.java @@ -124,60 +124,59 @@ private Set<String> taskRunToRestart(Execution execution, Predicate<TaskRun> pre return finalTaskRunToRestart; } - public Execution replay(final Execution execution, String taskRunId, @Nullable Integer revision) throws Exception { - if (!(execution.getState().isTerminated() || !(execution.getState().isTerminated() ))) { - throw new IllegalStateException("Execution must be terminated to be restarted, " + - "current state is '" + execution.getState().getCurrent() + "' !" - ); - } - - final Flow flow = flowRepositoryInterface.findByExecution(execution); - GraphCluster graphCluster = GraphService.of(flow, execution); - - Set<String> taskRunToRestart = this.taskRunToRestart( - execution, - taskRun -> taskRun.getId().equals(taskRunId) - ); - - Map<String, String> mappingTaskRunId = this.mapTaskRunId(execution, false); + public Execution replay(final Execution execution, @Nullable String taskRunId, @Nullable Integer revision) throws Exception { final String newExecutionId = IdUtils.create(); + List<TaskRun> newTaskRuns = new ArrayList<>(); + if(taskRunId != null){ + final Flow flow = flowRepositoryInterface.findByExecution(execution); - List<TaskRun> newTaskRuns = execution - .getTaskRunList() - .stream() - .map(throwFunction(originalTaskRun -> this.mapTaskRun( - flow, - originalTaskRun, - mappingTaskRunId, - newExecutionId, - State.Type.RESTARTED, - taskRunToRestart.contains(originalTaskRun.getId())) - )) - .collect(Collectors.toList()); + GraphCluster graphCluster = GraphService.of(flow, execution); - // remove all child for replay task id - Set<String> taskRunToRemove = GraphService.successors(graphCluster, List.of(taskRunId)) - .stream() - .filter(task -> task instanceof AbstractGraphTask) - .map(task -> ((AbstractGraphTask) task)) - .filter(task -> task.getTaskRun() != null) - .filter(task -> !task.getTaskRun().getId().equals(taskRunId)) - .filter(task -> !taskRunToRestart.contains(task.getTaskRun().getId())) - .map(s -> mappingTaskRunId.get(s.getTaskRun().getId())) - .collect(Collectors.toSet()); + Set<String> taskRunToRestart = this.taskRunToRestart( + execution, + taskRun -> taskRun.getId().equals(taskRunId) + ); - taskRunToRemove - .forEach(r -> newTaskRuns.removeIf(taskRun -> taskRun.getId().equals(r))); + Map<String, String> mappingTaskRunId = this.mapTaskRunId(execution, false); + + newTaskRuns.addAll( + execution.getTaskRunList() + .stream() + .map(throwFunction(originalTaskRun -> this.mapTaskRun( + flow, + originalTaskRun, + mappingTaskRunId, + newExecutionId, + State.Type.RESTARTED, + taskRunToRestart.contains(originalTaskRun.getId())) + )) + .collect(Collectors.toList()) + ); - // Worker task, we need to remove all child in order to be restarted - this.removeWorkerTask(flow, execution, taskRunToRestart, mappingTaskRunId) - .forEach(r -> newTaskRuns.removeIf(taskRun -> taskRun.getId().equals(r))); + // remove all child for replay task id + Set<String> taskRunToRemove = GraphService.successors(graphCluster, List.of(taskRunId)) + .stream() + .filter(task -> task instanceof AbstractGraphTask) + .map(task -> ((AbstractGraphTask) task)) + .filter(task -> task.getTaskRun() != null) + .filter(task -> !task.getTaskRun().getId().equals(taskRunId)) + .filter(task -> !taskRunToRestart.contains(task.getTaskRun().getId())) + .map(s -> mappingTaskRunId.get(s.getTaskRun().getId())) + .collect(Collectors.toSet()); + + taskRunToRemove + .forEach(r -> newTaskRuns.removeIf(taskRun -> taskRun.getId().equals(r))); + + // Worker task, we need to remove all child in order to be restarted + this.removeWorkerTask(flow, execution, taskRunToRestart, mappingTaskRunId) + .forEach(r -> newTaskRuns.removeIf(taskRun -> taskRun.getId().equals(r))); + } // Build and launch new execution Execution newExecution = execution.childExecution( newExecutionId, newTaskRuns, - execution.withState(State.Type.RESTARTED).getState() + taskRunId == null ? new State() : execution.withState(State.Type.RESTARTED).getState() ); return revision != null ? newExecution.withFlowRevision(revision) : newExecution; diff --git a/ui/src/components/executions/Overview.vue b/ui/src/components/executions/Overview.vue index 039733569f..baf7f334fe 100644 --- a/ui/src/components/executions/Overview.vue +++ b/ui/src/components/executions/Overview.vue @@ -5,6 +5,7 @@ <crud type="CREATE" permission="EXECUTION" :detail="{executionId: execution.id}" /> </el-col> <el-col :span="12" class="text-end"> + <restart is-replay :execution="execution" @follow="forwardEvent('follow', $event)" /> <restart :execution="execution" @follow="forwardEvent('follow', $event)" /> <kill :execution="execution" /> <status :status="execution.state.current" /> diff --git a/ui/src/components/executions/Restart.vue b/ui/src/components/executions/Restart.vue index 93c9c3046e..31f8ded728 100644 --- a/ui/src/components/executions/Restart.vue +++ b/ui/src/components/executions/Restart.vue @@ -1,15 +1,34 @@ <template> - <component - :is="component" - :icon="!isReplay ? RestartIcon : PlayBoxMultiple" - @click="isOpen = !isOpen" - v-if="isReplay || enabled" - :disabled="!enabled" - :class="!isReplay ? 'restart me-1' : ''" + <el-tooltip + :persistent="false" + transition="" + :hide-after="0" + :content="tooltip" + raw-content + :placement="tooltipPosition" > - {{ $t(replayOrRestart) }} - </component> - + <component + :is="component" + :icon="!isReplay ? RestartIcon : PlayBoxMultiple" + @click="isOpen = !isOpen" + v-if="component !== 'el-dropdown-item' && (isReplay || enabled)" + :disabled="!enabled" + :class="!isReplay ? 'restart me-1' : ''" + > + {{ $t(replayOrRestart) }} + </component> + <span v-else-if="component === 'el-dropdown-item' && (isReplay || enabled)"> + <component + :is="component" + :icon="!isReplay ? RestartIcon : PlayBoxMultiple" + @click="isOpen = !isOpen" + :disabled="!enabled" + :class="!isReplay ? 'restart me-1' : ''" + > + {{ $t(replayOrRestart) }} + </component> + </span> + </el-tooltip> <el-dialog v-if="enabled && isOpen" v-model="isOpen" destroy-on-close :append-to-body="true"> <template #header> <h5>{{ $t("confirmation") }}</h5> @@ -84,6 +103,10 @@ type: Number, required: false, default: undefined + }, + tooltipPosition: { + type: String, + default: "bottom" } }, emits: ["follow"], @@ -163,7 +186,7 @@ return false; } - if (this.isReplay && (this.taskRun.attempts !== undefined && this.taskRun.attempts.length - 1 !== this.attemptIndex)) { + if (this.isReplay && (this.taskRun?.attempts !== undefined && this.taskRun.attempts.length - 1 !== this.attemptIndex)) { return false; } @@ -173,6 +196,13 @@ return (this.isReplay && !State.isRunning(this.execution.state.current)) || (!this.isReplay && this.execution.state.current === State.FAILED); + }, + tooltip(){ + if(this.isReplay){ + return this?.taskRun?.id ? this.$t("replay from task tooltip", {taskId: this.taskRun.taskId}) : this.$t("replay from beginning tooltip"); + } + + return this.$t("restart tooltip", {state: this.execution.state.current}) } }, data() { diff --git a/ui/src/components/flows/FlowRun.vue b/ui/src/components/flows/FlowRun.vue index e2df8e7f8f..99001427eb 100644 --- a/ui/src/components/flows/FlowRun.vue +++ b/ui/src/components/flows/FlowRun.vue @@ -53,11 +53,15 @@ <div class="el-input el-input-file"> <div class="el-input__wrapper" v-if="input.type === 'FILE'"> <input + :id="input.name+'-file'" class="el-input__inner" type="file" @change="onFileChange(input, $event)" autocomplete="off" + :style="{display: typeof(this.inputs[input.name]) === 'string' && this.inputs[input.name].startsWith('kestra:///') ? 'none': ''}" > + <label v-if="typeof(this.inputs[input.name]) === 'string' && this.inputs[input.name].startsWith('kestra:///')" + :for="input.name+'-file'">Kestra Internal Storage File</label> </div> </div> <editor @@ -71,16 +75,28 @@ <small v-if="input.description" class="text-muted">{{ input.description }}</small> </el-form-item> - <el-form-item class="submit"> - <el-button :icon="Flash" class="flow-run-trigger-button" @click="onSubmit($refs.form)" type="primary" :disabled="flow.disabled"> - {{ $t('launch execution') }} - </el-button> - </el-form-item> + <div class="bottom-buttons"> + <div class="left-align"> + <el-form-item> + <el-button v-if="execution && execution.inputs" :icon="ContentCopy" @click="fillInputsFromExecution"> + {{ $t('prefill inputs') }} + </el-button> + </el-form-item> + </div> + <div class="right-align"> + <el-form-item class="submit"> + <el-button :icon="Flash" class="flow-run-trigger-button" @click="onSubmit($refs.form)" type="primary" :disabled="flow.disabled"> + {{ $t('launch execution') }} + </el-button> + </el-form-item> + </div> + </div> </el-form> </div> </template> <script setup> + import ContentCopy from "vue-material-design-icons/ContentCopy.vue"; import Flash from "vue-material-design-icons/Flash.vue"; </script> @@ -98,21 +114,22 @@ default: true } }, - emits: ["executionTrigger"], data() { return { - inputs: {}, + inputs: {} }; }, - mounted() { + emits: ["executionTrigger"], + created() { for (const input of this.flow.inputs || []) { this.inputs[input.name] = input.defaults; - if (input.type === "DATETIME" && input.defaults) { - this.inputs[input.name] = new Date(input.defaults); + if(input.type === "BOOLEAN" && input.defaults){ + this.inputs[input.name] = (/true/i).test(input.defaults); } } - + }, + mounted() { setTimeout(() => { const input = this.$el && this.$el.querySelector && this.$el.querySelector("input") if (input && !input.className.includes("mx-input")) { @@ -135,8 +152,29 @@ computed: { ...mapState("flow", ["flow"]), ...mapState("core", ["guidedProperties"]), + ...mapState("execution", ["execution"]), }, methods: { + fillInputsFromExecution(){ + const nonEmptyInputNames = Object.keys(this.execution.inputs); + this.inputs = Object.fromEntries( + this.flow.inputs.filter(input => nonEmptyInputNames.includes(input.name)) + .map(input => { + const inputName = input.name; + const inputType = input.type; + let inputValue = this.execution.inputs[inputName]; + if (inputType === 'DATE' || inputType === 'DATETIME') { + inputValue = this.$moment(inputValue).toISOString() + }else if (inputType === 'DURATION' || inputType === 'TIME') { + inputValue = this.$moment().startOf("day").add(inputValue, "seconds").toString() + }else if (inputType === 'JSON') { + inputValue = JSON.stringify(inputValue).toString() + } + + return [inputName, inputValue] + }) + ); + }, onSubmit(formRef) { if (this.$tours["guidedTour"].isRunning.value) { this.finishTour(); @@ -226,3 +264,26 @@ } }; </script> + +<style scoped lang="scss"> +.bottom-buttons { + margin-top: 36px; + display: flex; + + > * { + flex: 1; + + * { + margin: 0; + } + } + + .left-align :deep(div) { + flex-direction: row + } + + .right-align :deep(div) { + flex-direction: row-reverse; + } +} +</style> \ No newline at end of file diff --git a/ui/src/components/flows/TriggerFlow.vue b/ui/src/components/flows/TriggerFlow.vue index 845c54b12e..5f65ab7369 100644 --- a/ui/src/components/flows/TriggerFlow.vue +++ b/ui/src/components/flows/TriggerFlow.vue @@ -4,7 +4,7 @@ {{ $t('New execution') }} </el-button> <el-dialog v-if="isOpen" v-model="isOpen" destroy-on-close :append-to-body="true"> - <template #title> + <template #header> <span v-html="$t('execute the flow', {id: flowId})" /> </template> <flow-run @execution-trigger="closeModal" :redirect="true" /> @@ -42,7 +42,7 @@ type: { type: String, default: "primary" - }, + } }, data() { return { diff --git a/ui/src/components/inputs/Editor.vue b/ui/src/components/inputs/Editor.vue index 74687420c9..b09e8fc3d7 100644 --- a/ui/src/components/inputs/Editor.vue +++ b/ui/src/components/inputs/Editor.vue @@ -33,7 +33,7 @@ :original="original" @change="onInput" @editor-did-mount="editorDidMount" - :language="lang" + :language="lang ?? 'undefined'" :schema-type="schemaType" class="position-relative" /> diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 113cd7dbce..48d4fbca91 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -68,7 +68,8 @@ <restart component="el-dropdown-item" :key="`restart-${index}-${attempt.state.startDate}`" - :is-replay="true" + is-replay + tooltip-position="left" :execution="execution" :task-run="currentTaskRun" :attempt-index="index" diff --git a/ui/src/translations.json b/ui/src/translations.json index 413e6f4654..250e79b145 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -101,13 +101,17 @@ "start datetime": "Start datetime", "end datetime": "End datetime", "restart": "Restart", + "restart tooltip": "Restart the execution from the <code>{state}</code> task", "restarted": "Execution is restarted", "restart confirm": "Are you sure to restart execution <code>{id}</code>?", "restart change revision": "You can change the revision that will be used for the new execution.", "replay": "Replay", + "replay from task tooltip": "Create a similar execution starting from task <code>{taskId}</code>", + "replay from beginning tooltip": "Create a similar execution starting from the beginning", "replay latest revision": "Replay using latest revision", "replayed": "Execution is replayed", "replay confirm": "Are you sure to replay this execution <code>{id}</code> and create a new one?", + "prefill inputs": "Prefill", "current": "current", "change status": "Change status", "change status done": "Task status has been updated", @@ -531,13 +535,17 @@ "start datetime": "Date de départ", "end datetime": "Date de fin", "restart": "Relancer", + "restart tooltip": "Relancer l'exécution depuis la tâche dans l'état <code>{state}</code>", "restarted": "L'exécution est relancée", "restart confirm": "Êtes-vous sur de vouloir relancer <code>{id}</code> ?", "restart change revision": "Vous pouvez changer la révision qui sera utilisé pour la nouvelle execution relancée.", "replay": "Rejouer", + "replay from task tooltip": "Créer une nouvelle exécution similaire démarrant de la tâche <code>{taskId}</code>", + "replay from beginning tooltip": "Créer une nouvelle exécution similaire depuis le début", "replay latest revision": "Rejouer avec la dernière révision", "replayed": "Execution est rejouée", "replay confirm": "Êtes-vous sur de vouloir relancer l'exécution <code>{id}</code> et créer une nouvelle execution ?", + "prefill inputs": "Pré-remplir", "current": "actuel", "change status": "Changer le statut", "change status done": "Le statut de la tâche a était mis à jour", diff --git a/ui/src/utils/submitTask.js b/ui/src/utils/submitTask.js index ef42aeb57e..604512a71b 100644 --- a/ui/src/utils/submitTask.js +++ b/ui/src/utils/submitTask.js @@ -1,23 +1,29 @@ export const executeTask = (submitor, flow, values, options) => { const formData = new FormData(); for (let input of flow.inputs || []) { - if (values[input.name] !== undefined) { + const inputName = input.name; + const inputValue = values[inputName]; + if (inputValue !== undefined) { if (input.type === "DATETIME") { - formData.append(input.name, values[input.name].toISOString()); + formData.append(inputName, submitor.$moment(inputValue).toISOString()); } else if (input.type === "DATE") { - formData.append(input.name, submitor.$moment(values[input.name]).format("YYYY-MM-DD")); + formData.append(inputName, submitor.$moment(inputValue).format("YYYY-MM-DD")); } else if (input.type === "TIME") { - formData.append(input.name, submitor.$moment(values[input.name]).format("hh:mm:ss")); + formData.append(inputName, submitor.$moment(inputValue).format("hh:mm:ss")); } else if (input.type === "DURATION") { - formData.append(input.name, submitor.$moment.duration(submitor.$moment(values[input.name]).format("hh:mm:ss"))); + formData.append(inputName, submitor.$moment.duration(submitor.$moment(inputValue).format("hh:mm:ss"))); } else if (input.type === "FILE") { - formData.append("files", values[input.name], input.name); + if(typeof(inputValue) === "string"){ + formData.append(inputName, inputValue); + }else { + formData.append("files", inputValue, inputName); + } } else { - formData.append(input.name, values[input.name]); + formData.append(inputName, inputValue); } } else if (input.required) { submitor.$toast().error( - submitor.$t("invalid field", {name: input.name}), + submitor.$t("invalid field", {name: inputName}), submitor.$t("form error") )
diff --git a/core/src/test/java/io/kestra/core/runners/ExecutionServiceTest.java b/core/src/test/java/io/kestra/core/runners/ExecutionServiceTest.java index eb18f687b1..7c337770e5 100644 --- a/core/src/test/java/io/kestra/core/runners/ExecutionServiceTest.java +++ b/core/src/test/java/io/kestra/core/runners/ExecutionServiceTest.java @@ -121,6 +121,26 @@ void restartDynamic() throws Exception { assertThat(restart.getTaskRunList().get(0).getState().getHistories(), hasSize(4)); } + @Test + void replayFromBeginning() throws Exception { + Execution execution = runnerUtils.runOne("io.kestra.tests", "logs"); + assertThat(execution.getTaskRunList(), hasSize(3)); + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + + Execution restart = executionService.replay(execution, null, null); + + assertThat(restart.getId(), not(execution.getId())); + assertThat(restart.getNamespace(), is("io.kestra.tests")); + assertThat(restart.getFlowId(), is("logs")); + + assertThat(restart.getState().getCurrent(), is(State.Type.CREATED)); + assertThat(restart.getState().getHistories(), hasSize(1)); + assertThat(restart.getState().getHistories().get(0).getDate(), not(is(execution.getState().getStartDate()))); + assertThat(restart.getTaskRunList(), hasSize(0)); + + assertThat(restart.getId(), not(execution.getId())); + } + @Test void replaySimple() throws Exception { Execution execution = runnerUtils.runOne("io.kestra.tests", "logs");
val
train
2023-05-22T12:58:31
"2023-04-27T12:41:56Z"
srichelle
train
kestra-io/kestra/1176_1277
kestra-io/kestra
kestra-io/kestra/1176
kestra-io/kestra/1277
[ "keyword_pr_to_issue" ]
3a6c5ff5589816c32bca4c4ca49a5ab2396b857d
c7955d12b56b92ac18860c45fe65fa2eccc902cb
[ "This is caused by the BigQuery trigger re-using the Query task.\r\nIn this case, the storage files are created without execution prefix like:\r\n```\r\nkestra:///io/kestra/tests/trigger-wikipedia/10807484584123982691.ion\r\n```\r\n\r\nA correct file created by a trigger would be like:\r\n```\r\nkestra:///io/kestra/tests/gcs-listen/executions/4WxaKPGmyHzQcTocTwrafP/trigger/watch/5816538197308626077.tmp\r\n```\r\n\r\nWhich would be accepted by the `ExecutionController.validateFile()` methods that otherwise return a 422 status code.", "@tchiotludo what will be the best way to fix that issue ?\n\nWe can allow accessing files that didn't contain `/executions/{executionId}/trigger/{triggerName}`, but maybe it's a security risk, or we can update the BigQuery trigger (and maybe ten other that should have the same issue) to create a file with a proper name (it may be hard as Trigger use the Query task so we loose the trigger context).", "We can allow acces on to `/executions/{executionId}/trigger/{triggerName}` but we need to control the flow behind to if user is allow to download" ]
[ "use IdUtils.create() " ]
"2023-05-12T08:40:21Z"
[ "bug" ]
Trigger files from internal storage cannot be retrieved from the Execution Overview
### Expected Behavior On the execution Overview tab, if a triggre produces a file there is a link to the file on the tab that should works. ### Actual Behaviour The link didn't works ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow ``` id: trigger-wikipedia namespace: io.kestra.tests triggers: - id: wikipedia type: io.kestra.plugin.gcp.bigquery.Trigger sql: | SELECT DATETIME(datehour) as date, title, views FROM `bigquery-public-data.wikipedia.pageviews_2023` WHERE DATE(datehour) = current_date() and wiki = 'fr' and title not in ('Cookie_(informatique)', 'Wikipédia:Accueil_principal', 'Spécial:Recherche') ORDER BY datehour desc, views desc LIMIT 10 store: true interval: PT1M tasks: - id: write-csv type: io.kestra.plugin.serdes.csv.CsvWriter from: "{{trigger.uri}}" ```
[ "core/src/main/java/io/kestra/core/runners/RunContext.java", "core/src/main/java/io/kestra/core/storages/StorageInterface.java" ]
[ "core/src/main/java/io/kestra/core/runners/RunContext.java", "core/src/main/java/io/kestra/core/storages/StorageInterface.java" ]
[]
diff --git a/core/src/main/java/io/kestra/core/runners/RunContext.java b/core/src/main/java/io/kestra/core/runners/RunContext.java index bf93486822..c94e8c2e54 100644 --- a/core/src/main/java/io/kestra/core/runners/RunContext.java +++ b/core/src/main/java/io/kestra/core/runners/RunContext.java @@ -51,6 +51,8 @@ public class RunContext { protected transient Path temporaryDirectory; + private String triggerExecutionId; + /** * Only used by {@link io.kestra.core.models.triggers.types.Flow} * @@ -87,7 +89,8 @@ public RunContext(ApplicationContext applicationContext, Flow flow, Task task, E public RunContext(ApplicationContext applicationContext, Flow flow, AbstractTrigger trigger) { this.initBean(applicationContext); - this.storageOutputPrefix = this.storageInterface.outputPrefix(flow); + this.triggerExecutionId = IdUtils.create(); + this.storageOutputPrefix = this.storageInterface.outputPrefix(flow, trigger, triggerExecutionId); this.variables = this.variables(flow, null, null, null, trigger); this.initLogger(flow, trigger); } @@ -162,6 +165,10 @@ private void initLogger(Flow flow, AbstractTrigger trigger) { ); } + public String getTriggerExecutionId() { + return triggerExecutionId; + } + public Map<String, Object> getVariables() { return variables; } diff --git a/core/src/main/java/io/kestra/core/storages/StorageInterface.java b/core/src/main/java/io/kestra/core/storages/StorageInterface.java index d7240dbe36..e81fcce7b0 100644 --- a/core/src/main/java/io/kestra/core/storages/StorageInterface.java +++ b/core/src/main/java/io/kestra/core/storages/StorageInterface.java @@ -8,6 +8,7 @@ import io.kestra.core.models.flows.Flow; import io.kestra.core.models.flows.Input; import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.triggers.AbstractTrigger; import io.kestra.core.utils.Slugify; import io.micronaut.core.annotation.Introspected; import io.micronaut.core.annotation.Nullable; @@ -158,7 +159,7 @@ default URI outputPrefix(Flow flow) { } } - default URI outputPrefix(Flow flow, Task task, Execution execution, TaskRun taskRun) { + default URI outputPrefix(Flow flow, Task task, Execution execution, TaskRun taskRun) { try { return new URI("/" + String.join( "/", @@ -176,4 +177,22 @@ default URI outputPrefix(Flow flow, Task task, Execution execution, TaskRun task throw new IllegalArgumentException(e); } } + + default URI outputPrefix(Flow flow, AbstractTrigger trigger, String triggerExecutionId) { + try { + return new URI("/" + String.join( + "/", + Arrays.asList( + flow.getNamespace().replace(".", "/"), + Slugify.of(flow.getId()), + "executions", + triggerExecutionId, + "trigger", + Slugify.of(trigger.getId()) + ) + )); + } catch (URISyntaxException e) { + throw new IllegalArgumentException(e); + } + } }
null
test
train
2023-05-17T13:49:18
"2023-04-18T11:41:35Z"
loicmathieu
train
kestra-io/kestra/1162_1298
kestra-io/kestra
kestra-io/kestra/1162
kestra-io/kestra/1298
[ "keyword_pr_to_issue" ]
544d4db26d77a980d60d68b5287788492dcd02cf
fa52d5e5b8cd313c935f8fb8b3c1812911f3b76e
[]
[ "Not right way, you only inverse on the whole application, please pass a props that : \r\n- force the orientation \r\n- remove the button" ]
"2023-05-15T16:35:50Z"
[ "enhancement" ]
Default vertical position for topology view in editor tab
### Feature description It could be nice to get topology directly in the vertical position while in the editor tab ![image](https://user-images.githubusercontent.com/46634684/231774170-9003193e-c18d-4211-915a-096166d7e29a.png)
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 8bff2a8b29..a9e903fd3f 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -109,7 +109,6 @@ const editorWidthStorageKey = "editor-width"; const editorWidthPercentage = ref(localStorage.getItem(editorWidthStorageKey)); - const isHorizontal = ref(localStorage.getItem("topology-orientation") !== "0"); const isLoading = ref(false); const elements = ref([]) const haveChange = ref(false) @@ -135,7 +134,7 @@ const autoRestorelocalStorageKey = computed(() => { return "autoRestore-"+localStorageKey.value; }) - + watch(() => store.getters["flow/taskError"], async () => { taskError.value = store.getters["flow/taskError"]; }); @@ -147,7 +146,7 @@ const generateDagreGraph = () => { const dagreGraph = new dagre.graphlib.Graph({compound: true}) dagreGraph.setDefaultEdgeLabel(() => ({})) - dagreGraph.setGraph({rankdir: isHorizontal.value ? "LR" : "TB"}) + dagreGraph.setGraph({rankdir: showTopology.value === "topology" ? "LR" : "TB"}) for (const node of props.flowGraph.nodes) { dagreGraph.setNode(node.uid, { @@ -216,7 +215,7 @@ }; const getNodeHeight = (node) => { - return isTaskNode(node) || isTriggerNode(node) ? 55 : (isHorizontal.value ? 55 : 5); + return isTaskNode(node) || isTriggerNode(node) ? 55 : (showTopology.value === "topology" ? 55 : 5); }; const getNodePosition = (n, parent, alignTo) => { @@ -243,16 +242,6 @@ } } - const toggleOrientation = () => { - localStorage.setItem( - "topology-orientation", - localStorage.getItem("topology-orientation") !== "0" ? "0" : "1" - ); - isHorizontal.value = localStorage.getItem("topology-orientation") === "1"; - regenerateGraph(); - fitView(); - }; - const generateGraph = () => { isLoading.value = true; if (!props.flowGraph) { @@ -265,8 +254,8 @@ width: "5px", height: "5px" }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, + sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, + targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, parentNode: undefined, draggable: false, }) @@ -274,13 +263,13 @@ id: "end", label: "", type: "dot", - position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, + position: showTopology.value === "topology" ? {x: 50, y: 0} : {x: 0, y: 50}, style: { width: "5px", height: "5px" }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, + sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, + targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, parentNode: undefined, draggable: false, }) @@ -325,8 +314,8 @@ parentNode: parentNode, position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), style: { - width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", - height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", + width: clusterUid === "Triggers" && showTopology.value === "topology" ? "400px" : dagreNode.width + "px", + height: clusterUid === "Triggers" && !showTopology.value === "topology" ? "250px" : dagreNode.height + "px", }, }) } @@ -352,8 +341,8 @@ width: getNodeWidth(node) + "px", height: getNodeHeight(node) + "px" }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, + sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, + targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, draggable: nodeType === "task" && !props.isReadOnly, data: { @@ -574,12 +563,12 @@ const showDraftPopup = (draftReason) => { toast.confirm(draftReason + " " + (props.isCreating ? t("save draft.prompt.creation") : t("save draft.prompt.existing", { - namespace: flow.namespace, - id: flow.id - })), - () => { - persistEditorContent(false); - } + namespace: flow.namespace, + id: flow.id + })), + () => { + persistEditorContent(false); + } ); } @@ -916,7 +905,7 @@ }); } - const combinedEditor = computed(() => ['doc','combined'].includes(showTopology.value)); + const combinedEditor = computed(() => ["doc","combined"].includes(showTopology.value)); const dragEditor = (e) => { let editorDomElement = document.getElementById("editor"); @@ -1008,13 +997,7 @@ :is-allowed-edit="isAllowedEdit()" /> </template> - - <Controls :show-interactive="false"> - <ControlButton @click="toggleOrientation"> - <ArrowCollapseDown v-if="!isHorizontal" /> - <ArrowCollapseRight v-if="isHorizontal" /> - </ControlButton> - </Controls> + <Controls :show-interactive="false" /> </VueFlow> </div> <PluginDocumentation
null
train
train
2023-05-15T21:32:00
"2023-04-13T13:31:16Z"
Ben8t
train
kestra-io/kestra/1297_1312
kestra-io/kestra
kestra-io/kestra/1297
kestra-io/kestra/1312
[ "keyword_pr_to_issue" ]
acc7426395b423897a75ddb20ef144067b5a466a
9aced7d6d687523a4f83c8dedf66fa453a8d48d9
[]
[ "A unit test please? no controller entry point should always have one :sweat_smile: " ]
"2023-05-16T09:21:24Z"
[ "bug" ]
Nested metrics don't show up in Flow Metric tab
### Expected Behavior All metrics should be available at the Flow Metric levels, even nested one ### Actual Behaviour When an execution have nested tasks (for example if task), sub task don't show up in the main Metric dashboard. ![image](https://github.com/kestra-io/kestra/assets/46634684/5eab7a83-5418-4842-8715-5305017c57ee) ![image](https://github.com/kestra-io/kestra/assets/46634684/6db6e531-c5af-4c39-8043-7767d42b0f07) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 - Operating System (OS / Docker / Kubernetes): Docker - Java Version (If not docker): ### Example flow ``` - id: isLoading type: io.kestra.core.tasks.flows.If condition: "{{ inputs.is_load == 'true' }}" then: - id: load type: io.kestra.plugin.gcp.bigquery.LoadFromGcs from: - '{{ outputs.extract.uri}}' destinationTable: "kestra-dev.scraping_demo.cars_data_{{ taskrun.startDate | date('YYYYMMdd') }}" autodetect: true format: JSON ```
[ "core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java", "repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java", "ui/src/components/flows/FlowMetrics.vue", "ui/src/stores/flow.js", "webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java" ]
[ "core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java", "jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java", "repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java", "ui/src/components/flows/FlowMetrics.vue", "ui/src/stores/flow.js", "webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java" ]
[ "core/src/test/java/io/kestra/core/repositories/AbstractMetricRepositoryTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java b/core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java index f76eb0394b..722b17b765 100644 --- a/core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java +++ b/core/src/main/java/io/kestra/core/repositories/MetricRepositoryInterface.java @@ -21,6 +21,8 @@ public interface MetricRepositoryInterface extends SaveRepositoryInterface<Metri List<String> taskMetrics(String namespace, String flowId, String taskId); + List<String> tasksWithMetrics(String namespace, String flowId); + MetricAggregations aggregateByFlowId(String namespace, String flowId, @Nullable String taskId, String metric, ZonedDateTime startDate, ZonedDateTime endDate, String aggregation); Integer purge(Execution execution); diff --git a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java index e0b9055b38..964a41441d 100644 --- a/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java +++ b/jdbc/src/main/java/io/kestra/jdbc/repository/AbstractJdbcMetricRepository.java @@ -64,9 +64,10 @@ public List<String> flowMetrics( String namespace, String flowId ) { - return this.queryMetrics( + return this.queryDistinct( field("flow_id").eq(flowId) - .and(field("namespace").eq(namespace)) + .and(field("namespace").eq(namespace)), + "metric_name" ); } @@ -76,10 +77,23 @@ public List<String> taskMetrics( String flowId, String taskId ) { - return this.queryMetrics( + return this.queryDistinct( field("flow_id").eq(flowId) .and(field("namespace").eq(namespace)) - .and(field("task_id").eq(taskId)) + .and(field("task_id").eq(taskId)), + "metric_name" + ); + } + + @Override + public List<String> tasksWithMetrics( + String namespace, + String flowId + ) { + return this.queryDistinct( + field("flow_id").eq(flowId) + .and(field("namespace").eq(namespace)), + "task_id" ); } @@ -141,20 +155,20 @@ public MetricEntry save(DSLContext dslContext, MetricEntry metric) { return metric; } - private List<String> queryMetrics(Condition condition) { + private List<String> queryDistinct(Condition condition, String field) { return this.jdbcRepository .getDslContextWrapper() .transactionResult(configuration -> { DSLContext context = DSL.using(configuration); SelectConditionStep<Record1<Object>> select = DSL .using(configuration) - .selectDistinct(field("metric_name")) + .selectDistinct(field(field)) .from(this.jdbcRepository.getTable()) .where(this.defaultFilter()); select = select.and(condition); - return select.fetch().map(record -> record.get("metric_name", String.class)); + return select.fetch().map(record -> record.get(field, String.class)); }); } diff --git a/repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java b/repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java index c0271a6870..cf5e44c470 100644 --- a/repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java +++ b/repository-memory/src/main/java/io/kestra/repository/memory/MemoryMetricRepository.java @@ -45,6 +45,11 @@ public List<String> taskMetrics(String namespace, String flowId, String taskId) throw new UnsupportedOperationException(); } + @Override + public List<String> tasksWithMetrics(String namespace, String flowId) { + throw new UnsupportedOperationException(); + } + @Override public MetricAggregations aggregateByFlowId(String namespace, String flowId, @Nullable String taskId, String metric, @Nullable ZonedDateTime startDate, @Nullable ZonedDateTime endDate, String aggregation) { throw new UnsupportedOperationException(); diff --git a/ui/src/components/flows/FlowMetrics.vue b/ui/src/components/flows/FlowMetrics.vue index db8a7b8c1f..440f4411e9 100644 --- a/ui/src/components/flows/FlowMetrics.vue +++ b/ui/src/components/flows/FlowMetrics.vue @@ -11,7 +11,7 @@ @update:model-value="updateQuery('task', $event)" > <el-option - v-for="item in tasks" + v-for="item in tasksWithMetrics" :key="item" :label="item" :value="item" @@ -83,12 +83,11 @@ <BarChart ref="chartRef" :chart-data="chartData" :options="options" v-if="aggregatedMetric" /> </el-tooltip> <span v-else> - <el-alert type="info" :closable="false"> - {{ $t("metric choice") }} - </el-alert> - </span> + <el-alert type="info" :closable="false"> + {{ $t("metric choice") }} + </el-alert> + </span> </el-card> - </div> </template> @@ -118,7 +117,7 @@ } }, computed: { - ...mapState("flow", ["flow", "metrics", "aggregatedMetric"]), + ...mapState("flow", ["flow", "metrics", "aggregatedMetric","tasksWithMetrics"]), theme() { return localStorage.getItem("theme") || "light"; }, @@ -192,9 +191,6 @@ } }) }, - tasks() { - return this.flow.tasks.map(e => e.id); - }, display() { return this.$route.query.metric && this.$route.query.aggregation; } @@ -207,6 +203,7 @@ }, methods: { loadMetrics() { + this.$store.dispatch("flow/loadTasksWithMetrics",{...this.$route.params}) this.$store .dispatch(this.$route.query.task ? "flow/loadTaskMetrics" : "flow/loadFlowMetrics", { ...this.$route.params, diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 30b82ff066..fad564b447 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -23,7 +23,8 @@ export default { flowError: undefined, taskError: undefined, metrics: [], - aggregatedMetrics: undefined + aggregatedMetrics: undefined, + tasksWithMetrics: [] }, actions: { @@ -240,6 +241,13 @@ export default { return response.data }) }, + loadTasksWithMetrics({commit}, options) { + return axios.get(`${apiRoot}metrics/tasks/${options.namespace}/${options.id}`) + .then(response => { + commit("setTasksWithMetrics", response.data) + return response.data + }) + }, loadFlowAggregatedMetrics({commit}, options) { return axios.get(`${apiRoot}metrics/aggregates/${options.namespace}/${options.id}/${options.metric}`, {params: options}) .then(response => { @@ -335,6 +343,9 @@ export default { setAggregatedMetric(state, aggregatedMetric) { state.aggregatedMetric = aggregatedMetric }, + setTasksWithMetrics(state, tasksWithMetrics) { + state.tasksWithMetrics = tasksWithMetrics + } }, getters: { flow(state) { diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java b/webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java index c1eeeb1943..08d8ab3852 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/MetricController.java @@ -79,6 +79,16 @@ public List<String> taskMetrics( return metricsRepository.taskMetrics(namespace, flowId, taskId); } + @ExecuteOn(TaskExecutors.IO) + @Get(uri = "/tasks/{namespace}/{flowId}", produces = MediaType.TEXT_JSON) + @Operation(tags = {"Metrics"}, summary = "Get tasks id that have metrics for a specific flow, include deleted or renamed tasks") + public List<String> tasks( + @Parameter(description = "The namespace") @PathVariable String namespace, + @Parameter(description = "The flow Id") @PathVariable String flowId + ) { + return metricsRepository.tasksWithMetrics(namespace, flowId); + } + @ExecuteOn(TaskExecutors.IO) @Get(uri = "/aggregates/{namespace}/{flowId}/{metric}", produces = MediaType.TEXT_JSON) @Operation(tags = {"Metrics"}, summary = "Get metrics aggregations for a specific flow")
diff --git a/core/src/test/java/io/kestra/core/repositories/AbstractMetricRepositoryTest.java b/core/src/test/java/io/kestra/core/repositories/AbstractMetricRepositoryTest.java index ef16429353..008f0f8e74 100644 --- a/core/src/test/java/io/kestra/core/repositories/AbstractMetricRepositoryTest.java +++ b/core/src/test/java/io/kestra/core/repositories/AbstractMetricRepositoryTest.java @@ -26,9 +26,9 @@ public abstract class AbstractMetricRepositoryTest { @Test void all() { String executionId = FriendlyId.createFriendlyId(); - TaskRun taskRun1 = taskRun(executionId); - MetricEntry counter = MetricEntry.of(taskRun1, counter()); - TaskRun taskRun2 = taskRun(executionId); + TaskRun taskRun1 = taskRun(executionId, "task"); + MetricEntry counter = MetricEntry.of(taskRun1, counter("counter")); + TaskRun taskRun2 = taskRun(executionId, "task"); MetricEntry timer = MetricEntry.of(taskRun2, timer()); metricRepository.save(counter); metricRepository.save(timer); @@ -70,20 +70,42 @@ void all() { } - private Counter counter() { - return Counter.of("counter", 1); + @Test + void names() { + String executionId = FriendlyId.createFriendlyId(); + TaskRun taskRun1 = taskRun(executionId, "task"); + MetricEntry counter = MetricEntry.of(taskRun1, counter("counter")); + + TaskRun taskRun2 = taskRun(executionId, "task2"); + MetricEntry counter2 = MetricEntry.of(taskRun2, counter("counter2")); + + metricRepository.save(counter); + metricRepository.save(counter2); + + + List<String> flowMetricsNames = metricRepository.flowMetrics("namespace", "flow"); + List<String> taskMetricsNames = metricRepository.taskMetrics("namespace", "flow", "task"); + List<String> tasksWithMetrics = metricRepository.tasksWithMetrics("namespace", "flow"); + + assertThat(flowMetricsNames.size(), is(2)); + assertThat(taskMetricsNames.size(), is(1)); + assertThat(tasksWithMetrics.size(), is(2)); + } + + private Counter counter(String metricName) { + return Counter.of(metricName, 1); } private Timer timer() { return Timer.of("counter", Duration.ofSeconds(5)); } - private TaskRun taskRun(String executionId) { + private TaskRun taskRun(String executionId, String taskId) { return TaskRun.builder() .flowId("flow") .namespace("namespace") .executionId(executionId) - .taskId("task") + .taskId(taskId) .id(FriendlyId.createFriendlyId()) .build(); }
val
train
2023-05-16T12:48:14
"2023-05-15T16:14:38Z"
Ben8t
train
kestra-io/kestra/1306_1313
kestra-io/kestra
kestra-io/kestra/1306
kestra-io/kestra/1313
[ "keyword_pr_to_issue" ]
e467c2b934d87b85bcdb1636efe8ab923eafdfc0
269b5df2103fad81eb11a33be256eae66ebb1d07
[ "In fact only killByQuery (search) filter on running execution on the backend side." ]
[]
"2023-05-16T09:59:23Z"
[ "bug" ]
CREATED issue is not killable
Right Now, we have a control on the `RUNNING` [state](https://github.com/kestra-io/kestra/blob/6e6c3334be5405807a547e42b5306a049c35ada9/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java#L822) that prevent killing an execution in `CREATED`. Created must be killable as running on each king of killing (for one, for ids, and for search)
[ "ui/src/utils/state.js", "webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java" ]
[ "ui/src/utils/state.js", "webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java" ]
[]
diff --git a/ui/src/utils/state.js b/ui/src/utils/state.js index eec9d59648..ca85642157 100644 --- a/ui/src/utils/state.js +++ b/ui/src/utils/state.js @@ -47,7 +47,7 @@ const STATE = Object.freeze({ colorClass: "yellow", icon: CloseCircle, isRunning: true, - isKillable: false, + isKillable: true, isFailed: true, }, KILLED: { @@ -79,7 +79,7 @@ const STATE = Object.freeze({ colorClass: "indigo", icon: PauseCircle, isRunning: true, - isKillable: false, + isKillable: true, isFailed: false, } }); diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java b/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java index a5e350ea51..2a105e793e 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/ExecutionController.java @@ -800,7 +800,7 @@ public MutableHttpResponse<?> killByIds( @ExecuteOn(TaskExecutors.IO) @Delete(uri = "executions/kill/by-query", produces = MediaType.TEXT_JSON) @Operation(tags = {"Executions"}, summary = "Kill executions filter by query parameters") - public HttpResponse<BulkResponse> killByQuery( + public HttpResponse<?> killByQuery( @Parameter(description = "A string filter") @Nullable @QueryValue(value = "q") String query, @Parameter(description = "A namespace filter prefix") @Nullable @QueryValue String namespace, @Parameter(description = "A flow id filter") @Nullable @QueryValue String flowId, @@ -808,7 +808,7 @@ public HttpResponse<BulkResponse> killByQuery( @Parameter(description = "The end datetime") @Nullable @Format("yyyy-MM-dd'T'HH:mm[:ss][.SSS][XXX]") @QueryValue ZonedDateTime endDate, @Parameter(description = "A state filter") @Nullable @QueryValue List<State.Type> state ) { - Integer count = executionRepository + var ids = executionRepository .find( query, namespace, @@ -817,23 +817,11 @@ public HttpResponse<BulkResponse> killByQuery( endDate, state ) - .map(e -> { - if (!e.getState().isRunning()) { - throw new IllegalStateException("Execution must be running to be killed, " + - "current state is '" + e.getState().getCurrent() + "' !" - ); - } - - killQueue.emit(ExecutionKilled - .builder() - .executionId(e.getId()) - .build()); - return 1; - }) - .reduce(Integer::sum) + .map(execution -> execution.getId()) + .toList() .blockingGet(); - return HttpResponse.ok(BulkResponse.builder().count(count).build()); + return killByIds(ids); } private boolean isStopFollow(Flow flow, Execution execution) {
null
train
train
2023-05-16T11:43:29
"2023-05-15T18:31:20Z"
tchiotludo
train
kestra-io/kestra/1309_1314
kestra-io/kestra
kestra-io/kestra/1309
kestra-io/kestra/1314
[ "keyword_pr_to_issue" ]
d0e9f21c0ac84076b00bd5640217a033c2ef5877
acc7426395b423897a75ddb20ef144067b5a466a
[]
[]
"2023-05-16T10:10:40Z"
[ "bug" ]
Validate If task return 500 instead of 422
### Expected Behavior When writing a flow, if a write a `If task` and there is no `then` properties, it return 500 instead of 422. This lead to a pop-up spamming. ### Actual Behaviour It should return 422 and not be displayed in a pop-up but only in the tooltip. ### Steps To Reproduce Write if task ### Environment Information - Kestra Version: 0.8.1 ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/tasks/flows/If.java" ]
[ "core/src/main/java/io/kestra/core/tasks/flows/If.java" ]
[]
diff --git a/core/src/main/java/io/kestra/core/tasks/flows/If.java b/core/src/main/java/io/kestra/core/tasks/flows/If.java index b0153d71a9..f23b1c9319 100644 --- a/core/src/main/java/io/kestra/core/tasks/flows/If.java +++ b/core/src/main/java/io/kestra/core/tasks/flows/If.java @@ -129,7 +129,7 @@ public GraphCluster tasksTree(Execution execution, TaskRun taskRun, List<String> public List<Task> allChildTasks() { return Stream .concat( - this.then.stream(), + this.then != null ? this.then.stream() : Stream.empty(), Stream.concat( this._else != null ? this._else.stream() : Stream.empty(), this.errors != null ? this.errors.stream() : Stream.empty())
null
val
train
2023-05-16T12:04:31
"2023-05-16T08:05:48Z"
Skraye
train
kestra-io/kestra/1278_1322
kestra-io/kestra
kestra-io/kestra/1278
kestra-io/kestra/1322
[ "keyword_pr_to_issue" ]
dd4be3fa8eb8cfe1326b42f88cfe2248d77cf7cc
3a6c5ff5589816c32bca4c4ca49a5ab2396b857d
[]
[]
"2023-05-17T07:01:41Z"
[ "bug" ]
Documentation does not appear correctly in editor
### Expected Behavior When I'm writing a task, I should be able to see the task documentation (if doc view is selected) ### Actual Behaviour If my cursor is at the end of the task, documentation is not displayed ![image](https://github.com/kestra-io/kestra/assets/37600690/09f74e16-1dc3-4827-a4c0-c46c504e479f) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8.1 ### Example flow _No response_
[ "ui/src/utils/yamlUtils.js" ]
[ "ui/src/utils/yamlUtils.js" ]
[]
diff --git a/ui/src/utils/yamlUtils.js b/ui/src/utils/yamlUtils.js index 23c3c184c5..fdd6cda190 100644 --- a/ui/src/utils/yamlUtils.js +++ b/ui/src/utils/yamlUtils.js @@ -163,7 +163,7 @@ export default class YamlUtils { static getTaskType(source, position) { const lineCounter = new LineCounter(); const yamlDoc = yaml.parseDocument(source, {lineCounter}); - if (yamlDoc.contents && yamlDoc.contents.items && yamlDoc.contents.items.find(e => e.key.value === "tasks")) { + if (yamlDoc.contents && yamlDoc.contents.items && yamlDoc.contents.items.find(e => ["tasks", "triggers", "errors"].includes(e.key.value))) { const cursorIndex = lineCounter.lineStarts[position.lineNumber - 1] + position.column; if (yamlDoc.contents) { for (const item of yamlDoc.contents.items) { @@ -179,14 +179,16 @@ export default class YamlUtils { static _getTaskType(element, cursorIndex, previousTaskType) { let taskType = previousTaskType for (const item of element.items) { + // Every -1 & +1 allows catching cursor + // that is just behind or just after a task if (item instanceof Pair) { - if (item.key.value === "type" && element.range[0] <= cursorIndex && element.range[1] >= cursorIndex) { + if (item.key.value === "type" && element.range[0]-1 <= cursorIndex && element.range[1]+1 >= cursorIndex) { taskType = item.value.value } - if ((item.value instanceof YAMLSeq || item.value instanceof YAMLMap) && item.value.range[0] <= cursorIndex && item.value.range[1] >= cursorIndex) { + if ((item.value instanceof YAMLSeq || item.value instanceof YAMLMap) && item.value.range[0]-1 <= cursorIndex && item.value.range[1]+1 >= cursorIndex) { taskType = this._getTaskType(item.value, cursorIndex, taskType) } - } else if (item.range[0] <= cursorIndex && item.range[1] >= cursorIndex) { + } else if (item.range[0]-1 <= cursorIndex && item.range[1]+1 >= cursorIndex) { if (item.items instanceof Array) { taskType = this._getTaskType(item, cursorIndex) }
null
train
train
2023-05-16T22:32:40
"2023-05-12T08:45:44Z"
Skraye
train
kestra-io/kestra/1318_1323
kestra-io/kestra
kestra-io/kestra/1318
kestra-io/kestra/1323
[ "keyword_pr_to_issue" ]
dd4be3fa8eb8cfe1326b42f88cfe2248d77cf7cc
dbd7725bea3e154d59e9670b7f281bd6e160a5db
[]
[]
"2023-05-17T07:16:42Z"
[ "frontend" ]
Change icon topology vertically/horizontally.
### Expected Behavior ![image](https://github.com/kestra-io/kestra/assets/125994028/ef7b39b6-04f6-415b-881e-8b81e561d5fb) Change the icons for a better understanding of the display mode of the topology. Thank you. ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/assets/icons/SplitCellsHorizontal.vue", "ui/src/assets/icons/SplitCellsVertical.vue", "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/assets/icons/SplitCellsHorizontal.vue b/ui/src/assets/icons/SplitCellsHorizontal.vue new file mode 100644 index 0000000000..f9701ecb7b --- /dev/null +++ b/ui/src/assets/icons/SplitCellsHorizontal.vue @@ -0,0 +1,24 @@ +<template> + <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> + <g clip-path="url(#clip0_796_3996)"> + <path d="M13.367 1.979C13.7368 1.979 14.0366 2.27881 14.0366 2.64863V13.3626C14.0366 13.7324 13.7368 14.0322 13.367 14.0322H2.65302C2.2832 14.0322 1.9834 13.7324 1.9834 13.3626V2.64863C1.9834 2.27881 2.2832 1.979 2.65302 1.979H13.367ZM7.34039 3.31825H3.32265V12.693H7.34039V10.0145H8.67963V12.693H12.6974V3.31825H8.67963V5.99675H7.34039V3.31825ZM10.0189 5.99675L12.0278 8.00562L10.0189 10.0145V8.67524H6.00114V10.0145L3.99227 8.00562L6.00114 5.99675V7.33599H10.0189V5.99675Z" fill="#CAC5DA" /> + </g> + <defs> + <clipPath id="clip0_796_3996"> + <rect width="16" height="16" fill="white" /> + </clipPath> + </defs> + </svg> +</template> + +<script> + export default { + name: "SplitCellsHorizontalIcon", + emits: ["click"] + } +</script> +<style scoped> + svg { + transform: scale(1.5); + } +</style> \ No newline at end of file diff --git a/ui/src/assets/icons/SplitCellsVertical.vue b/ui/src/assets/icons/SplitCellsVertical.vue new file mode 100644 index 0000000000..5da0ddf729 --- /dev/null +++ b/ui/src/assets/icons/SplitCellsVertical.vue @@ -0,0 +1,24 @@ +<template> + <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"> + <g clip-path="url(#clip0_1111_7266)"> + <path d="M1.97852 2.63349C1.97852 2.26366 2.27832 1.96387 2.64814 1.96387L13.3621 1.96387C13.7319 1.96387 14.0317 2.26366 14.0317 2.63349L14.0317 13.3475C14.0317 13.7173 13.7319 14.0171 13.3621 14.0171L2.64814 14.0171C2.27832 14.0171 1.97852 13.7173 1.97852 13.3475L1.97852 2.63349ZM3.31776 8.6601L3.31776 12.6778L12.6925 12.6778L12.6925 8.6601L10.014 8.6601L10.014 7.32085L12.6925 7.32085L12.6925 3.30311L3.31776 3.30311L3.31776 7.32086L5.99626 7.32085L5.99626 8.6601L3.31776 8.6601ZM5.99626 5.98161L8.00513 3.97274L10.014 5.98161L8.67475 5.98161L8.67475 9.99935L10.014 9.99935L8.00513 12.0082L5.99626 9.99935L7.3355 9.99935L7.3355 5.98161L5.99626 5.98161Z" fill="#CAC5DA" /> + </g> + <defs> + <clipPath id="clip0_1111_7266"> + <rect width="16" height="16" fill="white" transform="translate(0 16) rotate(-90)" /> + </clipPath> + </defs> + </svg> +</template> + +<script> + export default { + name: "SplitCellsVerticalIcon", + emits: ["click"] + } +</script> +<style scoped> + svg { + transform: scale(1.5); + } +</style> diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index a9e903fd3f..e8292207bf 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -13,6 +13,8 @@ import DotsVertical from "vue-material-design-icons/DotsVertical.vue"; import ContentCopy from "vue-material-design-icons/ContentCopy.vue"; import Delete from "vue-material-design-icons/Delete.vue"; + import SplitCellsHorizontal from "../../assets/icons/SplitCellsHorizontal.vue" + import SplitCellsVertical from "../../assets/icons/SplitCellsVertical.vue" import BottomLine from "../../components/layout/BottomLine.vue"; import TriggerFlow from "../../components/flows/TriggerFlow.vue"; @@ -109,6 +111,7 @@ const editorWidthStorageKey = "editor-width"; const editorWidthPercentage = ref(localStorage.getItem(editorWidthStorageKey)); + const isHorizontal = ref(localStorage.getItem("topology-orientation") !== "0"); const isLoading = ref(false); const elements = ref([]) const haveChange = ref(false) @@ -146,7 +149,7 @@ const generateDagreGraph = () => { const dagreGraph = new dagre.graphlib.Graph({compound: true}) dagreGraph.setDefaultEdgeLabel(() => ({})) - dagreGraph.setGraph({rankdir: showTopology.value === "topology" ? "LR" : "TB"}) + dagreGraph.setGraph({rankdir: isHorizontal.value ? "LR" : "TB"}) for (const node of props.flowGraph.nodes) { dagreGraph.setNode(node.uid, { @@ -215,7 +218,7 @@ }; const getNodeHeight = (node) => { - return isTaskNode(node) || isTriggerNode(node) ? 55 : (showTopology.value === "topology" ? 55 : 5); + return isTaskNode(node) || isTriggerNode(node) ? 55 : (isHorizontal.value ? 55 : 5); }; const getNodePosition = (n, parent, alignTo) => { @@ -242,6 +245,16 @@ } } + const toggleOrientation = () => { + localStorage.setItem( + "topology-orientation", + localStorage.getItem("topology-orientation") !== "0" ? "0" : "1" + ); + isHorizontal.value = localStorage.getItem("topology-orientation") === "1"; + regenerateGraph(); + fitView(); + }; + const generateGraph = () => { isLoading.value = true; if (!props.flowGraph) { @@ -254,8 +267,8 @@ width: "5px", height: "5px" }, - sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, - targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, parentNode: undefined, draggable: false, }) @@ -263,13 +276,13 @@ id: "end", label: "", type: "dot", - position: showTopology.value === "topology" ? {x: 50, y: 0} : {x: 0, y: 50}, + position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, style: { width: "5px", height: "5px" }, - sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, - targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, parentNode: undefined, draggable: false, }) @@ -314,8 +327,8 @@ parentNode: parentNode, position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), style: { - width: clusterUid === "Triggers" && showTopology.value === "topology" ? "400px" : dagreNode.width + "px", - height: clusterUid === "Triggers" && !showTopology.value === "topology" ? "250px" : dagreNode.height + "px", + width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", + height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", }, }) } @@ -341,8 +354,8 @@ width: getNodeWidth(node) + "px", height: getNodeHeight(node) + "px" }, - sourcePosition: showTopology.value === "topology" ? Position.Right : Position.Bottom, - targetPosition: showTopology.value === "topology" ? Position.Left : Position.Top, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, draggable: nodeType === "task" && !props.isReadOnly, data: { @@ -782,6 +795,7 @@ const switchView = (event) => { showTopology.value = event if (["topology", "combined"].includes(showTopology.value)) { + isHorizontal.value = showTopology.value === "combined" ? false : localStorage.getItem("topology-orientation") === "1"; if (updatedFromEditor.value) { onEdit(flowYaml.value) updatedFromEditor.value = false; @@ -997,7 +1011,13 @@ :is-allowed-edit="isAllowedEdit()" /> </template> - <Controls :show-interactive="false" /> + + <Controls :show-interactive="false"> + <ControlButton @click="toggleOrientation" v-if="showTopology === 'topology'"> + <SplitCellsVertical :size="48" v-if="!isHorizontal" /> + <SplitCellsHorizontal v-if="isHorizontal" /> + </ControlButton> + </Controls> </VueFlow> </div> <PluginDocumentation
null
train
train
2023-05-16T22:32:40
"2023-05-16T13:48:35Z"
Nico-Kestra
train
kestra-io/kestra/1152_1329
kestra-io/kestra
kestra-io/kestra/1152
kestra-io/kestra/1329
[ "keyword_pr_to_issue" ]
c7955d12b56b92ac18860c45fe65fa2eccc902cb
9bd52c4129e9a50af851fcf3229126e94e85f0fd
[ "Would it be better to add the possibility to change a flow's namespace ? @tchiotludo ", "closing it, and move specs to https://github.com/kestra-io/kestra/issues/60", "Reopen it to avoid the not found right now, that will be easy to fix" ]
[]
"2023-05-17T13:06:44Z"
[ "backend", "enhancement" ]
Add/Improve error message while changing a flow namespace
### Feature description As a **non-developer** I created a **first flow with my first idea** But I wanted to **change the namespace** As a result, **I encountered multiple “Page not found” before understanding that it wasn’t possible** So I end up **duplicating the flow and deleting the initial one** *What would have helped?* → An error notification.
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json", "ui/src/utils/yamlUtils.js" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json", "ui/src/utils/yamlUtils.js" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index e8292207bf..1af02db939 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -129,6 +129,7 @@ const dragging = ref(false); const taskError = ref(store.getters["flow/taskError"]) const user = store.getters["auth/user"]; + const routeParams = router.currentRoute.value.params; const localStorageKey = computed(() => { return (props.isCreating ? "creation" : `${flow.namespace}.${flow.id}`) + "_draft"; @@ -849,8 +850,16 @@ }); }) }else { - store - .dispatch("flow/saveFlow", {flow: flowYaml.value}) + if(routeParams.id !== flowParsed.id || routeParams.namespace !== flowParsed.namespace){ + store.dispatch("core/showMessage", { + variant: "error", + title: t("can not save"), + message: t("namespace and id readonly"), + }) + flowYaml.value = YamlUtils.replaceIdAndNamespace(flowYaml.value, routeParams.id, routeParams.namespace); + return; + } + store.dispatch("flow/saveFlow", {flow: flowYaml.value}) .then((response) => { toast.saved(response.id); store.dispatch("core/isUnsaved", false); diff --git a/ui/src/translations.json b/ui/src/translations.json index c0f252dcb4..413e6f4654 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -407,6 +407,7 @@ "delete task confirm": "Do you want to delete the task <code>{taskId}</code> ?", "can not save": "Can not save", "flow must have id and namespace": "Flow must have an id and a namespace.", + "namespace and id readonly": "Namespace and id are read-only. They were reinitialized to their initial value.", "avg": "Average", "sum": "Sum", "min": "Min", @@ -837,6 +838,7 @@ "delete task confirm": "Êtes-vous sûr de vouloir supprimer la tâche <code>{taskId}</code> ?", "can not save": "Impossible de sauvegarder", "flow must have id and namespace": "Le flow doit avoir un id et un namespace.", + "namespace and id readonly": "Le namespace et l'id ne sont pas modifiables. Ils ont été réinitialisés à leur valeur initiale.", "avg": "Moyenne", "sum": "Somme", "min": "Minimum", diff --git a/ui/src/utils/yamlUtils.js b/ui/src/utils/yamlUtils.js index fdd6cda190..956555e373 100644 --- a/ui/src/utils/yamlUtils.js +++ b/ui/src/utils/yamlUtils.js @@ -402,6 +402,10 @@ export default class YamlUtils { return isChildrenOf; } + static replaceIdAndNamespace(source, id, namespace) { + return source.replace(/^(id\s*:\s*(["']?))\S*/m, "$1"+id+"$2").replace(/^(namespace\s*:\s*(["']?))\S*/m, "$1"+namespace+"$2") + } + static updateMetadata(source, metadata) { // TODO: check how to keep comments const yamlDoc = yaml.parseDocument(source);
null
train
train
2023-05-17T15:00:21
"2023-04-12T14:14:42Z"
Ben8t
train
kestra-io/kestra/1300_1335
kestra-io/kestra
kestra-io/kestra/1300
kestra-io/kestra/1335
[ "keyword_pr_to_issue" ]
c7955d12b56b92ac18860c45fe65fa2eccc902cb
594c1da918361ea66a4fbefdcb7dbd53970957c3
[]
[]
"2023-05-17T14:36:34Z"
[ "bug" ]
Flow Save button is red now
![image](https://github.com/kestra-io/kestra/assets/2064609/4d23679a-8b60-413f-9bb0-ca367b0a897e) Actually, if the flow have no unsaved change, the button is red. The button: - should be purple without any change - should be red if there is an error - should display a proper tooltip with the error message if any
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index e8292207bf..c2dec6824a 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -1180,7 +1180,7 @@ size="large" @click="save" v-if="isAllowedEdit" - :type="flowError || !haveChange ? 'danger' : 'primary'" + :type="flowError ? 'danger' : 'primary'" :disabled="!haveChange" class="edit-flow-save-button" >
null
train
train
2023-05-17T15:00:21
"2023-05-15T16:53:01Z"
tchiotludo
train
kestra-io/kestra/1302_1336
kestra-io/kestra
kestra-io/kestra/1302
kestra-io/kestra/1336
[ "keyword_pr_to_issue" ]
c7955d12b56b92ac18860c45fe65fa2eccc902cb
32fa5122e209358c9766abcc4099e644dc600c05
[]
[]
"2023-05-17T15:03:49Z"
[ "bug" ]
Tooltip on charts, should hide properly on mouseout
On chart, we have tooltip that is not always removed on when the mouse leave the charts. We should hide it when leaving totally the charts area
[ "ui/src/components/flows/FlowMetrics.vue", "ui/src/components/home/NamespaceTreeMap.vue", "ui/src/components/home/StatusPie.vue", "ui/src/components/stats/StateChart.vue" ]
[ "ui/src/components/flows/FlowMetrics.vue", "ui/src/components/home/NamespaceTreeMap.vue", "ui/src/components/home/StatusPie.vue", "ui/src/components/stats/StateChart.vue" ]
[]
diff --git a/ui/src/components/flows/FlowMetrics.vue b/ui/src/components/flows/FlowMetrics.vue index 440f4411e9..f9acb2ccc7 100644 --- a/ui/src/components/flows/FlowMetrics.vue +++ b/ui/src/components/flows/FlowMetrics.vue @@ -74,7 +74,7 @@ :persistent="false" :hide-after="0" transition="" - :visible="tooltipContent !== undefined" + :popper-class="tooltipContent === '' ? 'd-none' : 'tooltip-stats'" v-if="aggregatedMetric" > <template #content> diff --git a/ui/src/components/home/NamespaceTreeMap.vue b/ui/src/components/home/NamespaceTreeMap.vue index 22ddb54f82..5107282be0 100644 --- a/ui/src/components/home/NamespaceTreeMap.vue +++ b/ui/src/components/home/NamespaceTreeMap.vue @@ -5,6 +5,7 @@ :persistent="false" :hide-after="0" transition="" + :popper-class="tooltipContent === '' ? 'd-none' : 'tooltip-stats'" > <template #content> <span v-html="tooltipContent" /> diff --git a/ui/src/components/home/StatusPie.vue b/ui/src/components/home/StatusPie.vue index c4c857b6fc..c1cfd8cee5 100644 --- a/ui/src/components/home/StatusPie.vue +++ b/ui/src/components/home/StatusPie.vue @@ -6,6 +6,7 @@ :persistent="false" :hide-after="0" transition="" + :popper-class="tooltipContent === '' ? 'd-none' : 'tooltip-stats'" > <template #content> <span v-html="tooltipContent" /> diff --git a/ui/src/components/stats/StateChart.vue b/ui/src/components/stats/StateChart.vue index f41317805b..e09e570e00 100644 --- a/ui/src/components/stats/StateChart.vue +++ b/ui/src/components/stats/StateChart.vue @@ -1,12 +1,11 @@ <template> <div :class="'executions-charts' + (global ? (this.big ? ' big' : '') : ' mini')" v-if="dataReady"> <el-tooltip - popper-class="tooltip-stats" :placement="(global ? 'bottom' : 'left')" :persistent="false" :hide-after="0" transition="" - :visible="tooltipContent !== ''" + :popper-class="tooltipContent === '' ? 'd-none' : 'tooltip-stats'" > <template #content> <span v-html="tooltipContent" /> @@ -22,7 +21,6 @@ import {BarChart} from "vue-chart-3"; import Utils from "../../utils/utils.js"; import {defaultConfig, tooltip, chartClick, backgroundFromState} from "../../utils/charts.js"; - import State from "../../utils/state"; import {useI18n} from "vue-i18n"; export default defineComponent({ @@ -71,7 +69,7 @@ const options = computed(() => defaultConfig({ onClick: (e, elements) => { - if (elements.length > 0 && elements[0].index !== undefined && elements[0].datasetIndex !== undefined ) { + if (elements.length > 0 && elements[0].index !== undefined && elements[0].datasetIndex !== undefined) { chartClick( moment, router, @@ -172,4 +170,5 @@ }; }, }); -</script> \ No newline at end of file +</script> +
null
val
train
2023-05-17T15:00:21
"2023-05-15T16:56:57Z"
tchiotludo
train
kestra-io/kestra/1344_1346
kestra-io/kestra
kestra-io/kestra/1344
kestra-io/kestra/1346
[ "keyword_pr_to_issue" ]
00cb4e81d5415bb4f93ef9ba1a8d657e05926a9c
ed1dc8b2c0e2ce530e65d4582113585e531058b6
[]
[]
"2023-05-19T09:25:17Z"
[ "bug" ]
UI - No outputs displayed after selecting a task then clearing the select
### Expected Behavior All outputs are displayed after selecting a task then clearing the select. ### Actual Behaviour When you goes to the outputs tab of an execution and select one task, the list of outputs is filter with the tasks outputs, When you clear the select no outputs are shown. All outputs should have been displayed instead. ![screen-capture](https://github.com/kestra-io/kestra/assets/1819009/86e2829b-a509-461a-ac6b-adb44460027d) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/executions/ExecutionOutput.vue" ]
[ "ui/src/components/executions/ExecutionOutput.vue" ]
[]
diff --git a/ui/src/components/executions/ExecutionOutput.vue b/ui/src/components/executions/ExecutionOutput.vue index a2eb80b9a3..113c6979e2 100644 --- a/ui/src/components/executions/ExecutionOutput.vue +++ b/ui/src/components/executions/ExecutionOutput.vue @@ -8,6 +8,7 @@ :persistent="false" v-model="filter" @input="onSearch" + @clear="onClear" :placeholder="$t('display output for specific task') + '...'" > <el-option @@ -134,6 +135,9 @@ this.$router.push(newRoute); } }, + onClear() { + this.filter = undefined; + }, onDebugExpression(taskRunId, expression) { this.$http.post(`/api/v1/executions/${this.execution.id}/eval/${taskRunId}`, expression, { headers: {
null
test
train
2023-05-18T23:13:04
"2023-05-19T09:03:50Z"
loicmathieu
train
kestra-io/kestra/1348_1350
kestra-io/kestra
kestra-io/kestra/1348
kestra-io/kestra/1350
[ "keyword_pr_to_issue" ]
00cb4e81d5415bb4f93ef9ba1a8d657e05926a9c
e3c5da6614bcd87365699e3a81d1dd9b06620422
[]
[]
"2023-05-19T10:26:13Z"
[ "bug" ]
Themes/Editor discrepancies
### Expected Behavior _No response_ ### Actual Behaviour when Theme = light and editor=dark, editor is not dark <img width="1101" alt="Screenshot 2023-05-19 at 11 41 00" src="https://github.com/kestra-io/kestra/assets/46634684/9f4ec602-2b30-4e5f-a7dc-1a19c502269c"> ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 - Operating System (OS / Docker / Kubernetes): docker - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/inputs/Editor.vue" ]
[ "ui/src/components/inputs/Editor.vue" ]
[]
diff --git a/ui/src/components/inputs/Editor.vue b/ui/src/components/inputs/Editor.vue index 74687420c9..c4b340968d 100644 --- a/ui/src/components/inputs/Editor.vue +++ b/ui/src/components/inputs/Editor.vue @@ -357,6 +357,7 @@ </script> <style lang="scss"> + @import "../../styles/layout/root-dark.scss"; .ks-editor { width: 100%; @@ -439,14 +440,14 @@ .custom-dark-vs-theme { .monaco-editor, .monaco-editor-background { - background-color: var(--input-bg); - --vscode-editor-background: var(--input-bg); - --vscode-breadcrumb-background: var(--input-bg); - --vscode-editorGutter-background: var(--input-bg); + background-color: $input-bg; + --vscode-editor-background: $input-bg; + --vscode-breadcrumb-background: $input-bg; + --vscode-editorGutter-background: $input-bg; } .monaco-editor .margin { - background-color: var(--input-bg); + background-color: $input-bg; } }
null
train
train
2023-05-18T23:13:04
"2023-05-19T09:41:58Z"
Ben8t
train
kestra-io/kestra/1343_1362
kestra-io/kestra
kestra-io/kestra/1343
kestra-io/kestra/1362
[ "keyword_pr_to_issue" ]
2803b7135a485d2d1c2139f43b6a942474ed03fb
24d93dca0519588aa63437579b6281c07c1d2422
[]
[]
"2023-05-22T09:20:46Z"
[ "bug" ]
bug with vertical/horizontal topology in editor
### Expected Behavior _No response_ ### Actual Behaviour Some rendering bug when switching view https://github.com/kestra-io/kestra/assets/46634684/d8a563cf-5b2f-47a9-8274-589c9686f217 ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 - Operating System (OS / Docker / Kubernetes): Docker - Java Version (If not docker): ### Example flow _No response_
[ "ui/package.json" ]
[ "ui/package.json" ]
[]
diff --git a/ui/package.json b/ui/package.json index 023e92e2da..17551e15cd 100644 --- a/ui/package.json +++ b/ui/package.json @@ -11,7 +11,7 @@ }, "dependencies": { "@vue-flow/controls": "^1.0.6", - "@vue-flow/core": "1.20.0", + "@vue-flow/core": "1.14.3", "ansi-to-html": "^0.7.2", "axios": "^1.4.0", "bootstrap": "^5.2.3",
null
val
train
2023-05-22T11:01:01
"2023-05-19T08:45:58Z"
Ben8t
train
kestra-io/kestra/1342_1363
kestra-io/kestra
kestra-io/kestra/1342
kestra-io/kestra/1363
[ "keyword_pr_to_issue" ]
2803b7135a485d2d1c2139f43b6a942474ed03fb
ce2c16c5741f808503ac285f4169cab2a7293f16
[]
[]
"2023-05-22T09:31:02Z"
[ "bug" ]
Exporting flows and templates from the Settings page works but generates a JS error
### Expected Behavior No JS error on the console. ### Actual Behaviour When exporting flow or templates from the Settings page, the export works but there is exceptions in the JS console. ![image](https://github.com/kestra-io/kestra/assets/1819009/92b1707f-db01-487f-a1e6-eb3ef2fb50a7) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/settings/Settings.vue" ]
[ "ui/src/components/settings/Settings.vue" ]
[]
diff --git a/ui/src/components/settings/Settings.vue b/ui/src/components/settings/Settings.vue index 6ed9e248ba..bf80a6d923 100644 --- a/ui/src/components/settings/Settings.vue +++ b/ui/src/components/settings/Settings.vue @@ -153,7 +153,21 @@ this.editorDocumentation = value; this.$toast().saved(); - } + }, + exportFlows() { + return this.$store + .dispatch("flow/exportFlowByQuery", {}) + .then(_ => { + this.$toast().success(this.$t("flows exported")); + }) + }, + exportTemplates() { + return this.$store + .dispatch("template/exportTemplateByQuery", {}) + .then(_ => { + this.$toast().success(this.$t("templates exported")); + }) + }, }, computed: { ...mapGetters("core", ["guidedProperties"]), @@ -187,20 +201,6 @@ canReadTemplates() { return this.user && this.user.isAllowed(permission.TEMPLATE, action.READ); }, - exportFlows() { - return this.$store - .dispatch("flow/exportFlowByQuery", {}) - .then(_ => { - this.$toast().success(this.$t("flows exported")); - }) - }, - exportTemplates() { - return this.$store - .dispatch("template/exportTemplateByQuery", {}) - .then(_ => { - this.$toast().success(this.$t("templates exported")); - }) - }, } }; </script>
null
test
train
2023-05-22T11:01:01
"2023-05-19T08:44:58Z"
loicmathieu
train
kestra-io/kestra/1315_1364
kestra-io/kestra
kestra-io/kestra/1315
kestra-io/kestra/1364
[ "keyword_pr_to_issue" ]
2803b7135a485d2d1c2139f43b6a942474ed03fb
5b3fffc04359960ff10420d6f051d816a992bdbe
[]
[]
"2023-05-22T09:44:55Z"
[]
Template ctrl+s not working
[ "ui/src/components/templates/TemplateEdit.vue" ]
[ "ui/src/components/templates/TemplateEdit.vue" ]
[]
diff --git a/ui/src/components/templates/TemplateEdit.vue b/ui/src/components/templates/TemplateEdit.vue index aa647d6a61..074194ff15 100644 --- a/ui/src/components/templates/TemplateEdit.vue +++ b/ui/src/components/templates/TemplateEdit.vue @@ -1,6 +1,6 @@ <template> <div> - <editor @on-save="save" v-model="content" schema-type="template" lang="yaml" @update:model-value="onChange($event)" @cursor="updatePluginDocumentation" /> + <editor @save="save" v-model="content" schema-type="template" lang="yaml" @update:model-value="onChange($event)" @cursor="updatePluginDocumentation" /> <bottom-line v-if="canSave || canDelete"> <ul> <li>
null
test
train
2023-05-22T11:01:01
"2023-05-16T11:02:07Z"
tchiotludo
train
kestra-io/kestra/1281_1367
kestra-io/kestra
kestra-io/kestra/1281
kestra-io/kestra/1367
[ "keyword_pr_to_issue" ]
e3c5da6614bcd87365699e3a81d1dd9b06620422
626372b40ced7b3efca5b285a655be90b21743fa
[ "This is due to the fact that we are not setting taskrun in the state for the Logs view while we do it on the Gantt tab" ]
[]
"2023-05-22T09:58:41Z"
[ "bug", "enhancement", "frontend" ]
Metrics view from logs lead to undefined
### Expected Behavior Clicking on "Metrics" from the dropdown menu in logs tab should display metrics for this taskrun ### Actual Behaviour Greyed screen with nothing displayed due to undefined: ![image](https://github.com/kestra-io/kestra/assets/37618489/4936cc0d-c5dd-4068-b4bf-1f7ddb51e428) ### Steps To Reproduce Create an execution of flow Go to Logs tab Click on "Metrics" dropdown of any taskrun ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT ### Example flow _No response_
[ "ui/src/components/executions/Gantt.vue", "ui/src/components/graph/TreeTaskNode.vue", "ui/src/components/logs/LogList.vue" ]
[ "ui/src/components/executions/Gantt.vue", "ui/src/components/graph/TreeTaskNode.vue", "ui/src/components/logs/LogList.vue" ]
[]
diff --git a/ui/src/components/executions/Gantt.vue b/ui/src/components/executions/Gantt.vue index 38596f8038..28afff99f9 100644 --- a/ui/src/components/executions/Gantt.vue +++ b/ui/src/components/executions/Gantt.vue @@ -54,6 +54,7 @@ :exclude-metas="['namespace', 'flowId', 'taskId', 'executionId']" level="TRACE" @follow="forwardEvent('follow', $event)" + :hide-others-on-select="true" /> </td> </tr> @@ -101,7 +102,7 @@ this.paint(); }, computed: { - ...mapState("execution", ["taskRun", "execution"]), + ...mapState("execution", ["execution", "taskRun"]), taskRunsCount() { return this.execution && this.execution.taskRunList ? this.execution.taskRunList.length : 0 }, diff --git a/ui/src/components/graph/TreeTaskNode.vue b/ui/src/components/graph/TreeTaskNode.vue index 90d0799ca1..c5d8756aa2 100644 --- a/ui/src/components/graph/TreeTaskNode.vue +++ b/ui/src/components/graph/TreeTaskNode.vue @@ -130,6 +130,7 @@ :exclude-metas="['namespace', 'flowId', 'taskId', 'executionId']" :level="logLevel" @follow="forwardEvent('follow', $event)" + :hide-others-on-select="true" /> </el-drawer> </template> diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 113cd7dbce..fa0b89ea27 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -45,7 +45,7 @@ <status :status="attempt.state.current" /> </div> - <el-dropdown trigger="click"> + <el-dropdown trigger="click" @visibleChange="onTaskSelect($event, currentTaskRun)"> <el-button type="default"> <DotsVertical title="" /> </el-button> @@ -173,6 +173,10 @@ type: Array, default: () => [], }, + hideOthersOnSelect: { + type: Boolean, + default: false + } }, data() { return { @@ -217,6 +221,10 @@ this.$emit(type, event); }, displayTaskRun(currentTaskRun) { + if(!this.hideOthersOnSelect){ + return true; + } + if (this.taskRun && this.taskRun.id !== currentTaskRun.id) { return false; } @@ -224,7 +232,8 @@ if (this.task && this.task.id !== currentTaskRun.taskId) { return false; } - return true; + + return true; }, toggleShowOutput(taskRun) { this.showOutputs[taskRun.id] = !this.showOutputs[taskRun.id]; @@ -292,6 +301,11 @@ log.attemptNumber === attemptNumber ); }); + }, + onTaskSelect(dropdownVisible, task){ + if(dropdownVisible && this.taskRun?.id !== task.id) { + this.$store.commit("execution/setTaskRun", task); + } } }, beforeUnmount() {
null
test
train
2023-05-22T12:58:31
"2023-05-12T10:18:14Z"
brian-mulier-p
train
kestra-io/kestra/1301_1370
kestra-io/kestra
kestra-io/kestra/1301
kestra-io/kestra/1370
[ "keyword_pr_to_issue" ]
e3c5da6614bcd87365699e3a81d1dd9b06620422
ad7786586c7d7e8905f7aa438577b11cec94ea28
[ "I check and I don't think it's the case anymore.\n\nCan you validate that you didn't see any progress bar anymore ?", "@loicmathieu It is displayed: \r\n![image](https://github.com/kestra-io/kestra/assets/37618489/85a68fc9-1c91-4650-ba70-0f9e86277d60)\r\nIt is an issue now that the flow validation occurs again after every input of the user (if he stops its input for 500ms).", "@brian-mulier-p you are right, I didn't notice it as in dark mode this bar is not very visible." ]
[]
"2023-05-22T12:18:38Z"
[ "bug" ]
Flow validation should not display a progress bar
The top n-progress bar is diplayed on every flow validation. We should hide this progress bar for flow validation
[ "ui/src/stores/flow.js" ]
[ "ui/src/stores/flow.js" ]
[]
diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 141c5347ae..5ea9dc3b9e 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -214,7 +214,7 @@ export default { return this.$http.delete("/api/v1/flows/delete/by-query", options, {params: options}) }, validateFlow({commit}, options) { - return this.$http.post(`${apiRoot}flows/validate`, options.flow, textYamlHeader) + return axios.post(`${apiRoot}flows/validate`, options.flow, textYamlHeader) .then(response => { commit("setFlowError", response.data[0] ? response.data[0].constraints : undefined) return response.data @@ -228,35 +228,35 @@ export default { }) }, loadFlowMetrics({commit}, options) { - return axios.get(`${apiRoot}metrics/names/${options.namespace}/${options.id}`) + return this.$http.get(`${apiRoot}metrics/names/${options.namespace}/${options.id}`) .then(response => { commit("setMetrics", response.data) return response.data }) }, loadTaskMetrics({commit}, options) { - return axios.get(`${apiRoot}metrics/names/${options.namespace}/${options.id}/${options.taskId}`) + return this.$http.get(`${apiRoot}metrics/names/${options.namespace}/${options.id}/${options.taskId}`) .then(response => { commit("setMetrics", response.data) return response.data }) }, loadTasksWithMetrics({commit}, options) { - return axios.get(`${apiRoot}metrics/tasks/${options.namespace}/${options.id}`) + return this.$http.get(`${apiRoot}metrics/tasks/${options.namespace}/${options.id}`) .then(response => { commit("setTasksWithMetrics", response.data) return response.data }) }, loadFlowAggregatedMetrics({commit}, options) { - return axios.get(`${apiRoot}metrics/aggregates/${options.namespace}/${options.id}/${options.metric}`, {params: options}) + return this.$http.get(`${apiRoot}metrics/aggregates/${options.namespace}/${options.id}/${options.metric}`, {params: options}) .then(response => { commit("setAggregatedMetric", response.data) return response.data }) }, loadTaskAggregatedMetrics({commit}, options) { - return axios.get(`${apiRoot}metrics/aggregates/${options.namespace}/${options.id}/${options.taskId}/${options.metric}`, {params: options}) + return this.$http.get(`${apiRoot}metrics/aggregates/${options.namespace}/${options.id}/${options.taskId}/${options.metric}`, {params: options}) .then(response => { commit("setAggregatedMetric", response.data) return response.data
null
train
train
2023-05-22T12:58:31
"2023-05-15T16:54:34Z"
tchiotludo
train
kestra-io/kestra/1369_1371
kestra-io/kestra
kestra-io/kestra/1369
kestra-io/kestra/1371
[ "keyword_pr_to_issue" ]
e3c5da6614bcd87365699e3a81d1dd9b06620422
a3444347167c4eb60b3861e61cea617dc0280f4e
[]
[]
"2023-05-22T12:28:38Z"
[ "bug" ]
Editor Panel resize must be constrain
![image](https://github.com/kestra-io/kestra/assets/2064609/9a4b8849-eb4d-44bb-9f4b-55b25b527a65) ![image](https://github.com/kestra-io/kestra/assets/2064609/a5de36f6-0799-4cf9-9e23-860c4d78c140) We shouldn't allow such edge case resize, don't allow less than 200 px large
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 7512eea7ef..89349eb09f 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -936,7 +936,14 @@ let blockWidthPercent = (blockWidth / parentWidth) * 100; document.onmousemove = function onMouseMove(e) { - editorWidthPercentage.value = (blockWidthPercent + ((e.clientX - dragX) / parentWidth) * 100) + "%" + const percent = (blockWidthPercent + ((e.clientX - dragX) / parentWidth) * 100); + if(percent > 75 ){ + editorWidthPercentage.value = 75 + "%"; + } else if(percent < 25){ + editorWidthPercentage.value = 25 + "%"; + } else { + editorWidthPercentage.value = percent + "%"; + } } document.onmouseup = () => {
null
train
train
2023-05-22T12:58:31
"2023-05-22T11:04:46Z"
tchiotludo
train
kestra-io/kestra/1349_1374
kestra-io/kestra
kestra-io/kestra/1349
kestra-io/kestra/1374
[ "keyword_pr_to_issue" ]
626372b40ced7b3efca5b285a655be90b21743fa
a6dc76cb481c66046d9f776200255bde29204ecc
[]
[]
"2023-05-22T13:41:56Z"
[ "bug", "frontend" ]
Long time loading task source & form
### Expected Behavior Fast task edit loading ### Actual Behaviour Usage of Monaco editor instead of traditional input combined with the fact that now each Monaco editor has his own schema loaded independently leads to multiple useless queries of "/plugin", adding delay to the component : ![image](https://github.com/kestra-io/kestra/assets/37600690/cd6a2f70-2a45-4a53-a510-51554683f26a) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 ### Example flow _No response_
[ "ui/src/components/inputs/Editor.vue" ]
[ "ui/src/components/inputs/Editor.vue" ]
[]
diff --git a/ui/src/components/inputs/Editor.vue b/ui/src/components/inputs/Editor.vue index c4b340968d..7b3005beca 100644 --- a/ui/src/components/inputs/Editor.vue +++ b/ui/src/components/inputs/Editor.vue @@ -193,7 +193,6 @@ } }, created() { - this.$store.dispatch("plugin/list"); this.editorDocumentation = localStorage.getItem("editorDocumentation") !== "false" && this.navbar; }, methods: {
null
train
train
2023-05-22T14:49:59
"2023-05-19T10:09:08Z"
Skraye
train
kestra-io/kestra/1201_1376
kestra-io/kestra
kestra-io/kestra/1201
kestra-io/kestra/1376
[ "keyword_pr_to_issue" ]
fb269a3b6b7984fb5b504ed88f5c5eaf651ec8ca
2998a15920898a361f24117b08c2d530edf2eb22
[]
[]
"2023-05-22T16:14:23Z"
[ "bug" ]
UI - Documentation menu item is not highlighted when on a plugin page
### Expected Behavior When browsing the navigation from the UI, the menu item Documentation should stay highlighted > ### Actual Behaviour From the UI "Documentation" item, then Plugins, then select a plugin on the right navigation. Then the "Documentation" menu item is no more highlighted. ![12-Documentation-Plugins-Plugin](https://user-images.githubusercontent.com/1819009/234593171-28647a7f-49b1-4601-bb70-f715ee2db708.png) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.8.1-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/override/components/LeftMenu.vue" ]
[ "ui/src/override/components/LeftMenu.vue" ]
[]
diff --git a/ui/src/override/components/LeftMenu.vue b/ui/src/override/components/LeftMenu.vue index 182c39d800..5e1c88aacb 100644 --- a/ui/src/override/components/LeftMenu.vue +++ b/ui/src/override/components/LeftMenu.vue @@ -4,6 +4,7 @@ :menu="menu" @update:collapsed="onToggleCollapse" :show-one-child="true" + :show-child="showChildren" width="268px" :collapsed="collapsed" > @@ -69,6 +70,17 @@ r.class = "vsm--link_active" } + // special case for plugins, were parents have no href to set active + // Could be adapted to all routes to have something more generic + if(r.routes?.includes(this.$route.name)){ + r.class = "vsm--link_active" + + if(r.child){ + this.showChildren = true + r.child = this.disabledCurrentRoute(r.child) + } + } + return r; }) }, @@ -84,9 +96,6 @@ }, { href: "/flows", - alias: [ - "/flows*" - ], title: this.$t("flows"), icon: { element: FileTreeOutline, @@ -96,9 +105,6 @@ }, { href: "/templates", - alias: [ - "/templates*" - ], title: this.$t("templates"), icon: { element: ContentCopy, @@ -107,9 +113,6 @@ }, { href: "/executions", - alias: [ - "/executions*" - ], title: this.$t("executions"), icon: { element: TimelineClockOutline, @@ -118,7 +121,6 @@ }, { href: "/taskruns", - alias: ["/taskruns*"], title: this.$t("taskruns"), icon: { element: TimelineTextOutline, @@ -128,9 +130,6 @@ }, { href: "/logs", - alias: [ - "/logs*" - ], title: this.$t("logs"), icon: { element: NotebookOutline, @@ -138,14 +137,12 @@ }, }, { - alias: [ - "/plugins*" - ], title: this.$t("documentation.documentation"), icon: { element: BookMultipleOutline, class: "menu-icon" }, + routes: ["plugins/view"], child: [ { href: "https://kestra.io/docs/", @@ -159,6 +156,7 @@ { href: "/plugins", title: this.$t("plugins.names"), + routes: ["plugins/view"], icon: { element: GoogleCirclesExtended, class: "menu-icon" @@ -196,9 +194,6 @@ }, { href: "/settings", - alias: [ - "/settings*" - ], title: this.$t("settings"), icon: { element: CogOutline, @@ -212,17 +207,19 @@ watch: { menu: { handler() { - this.$el.querySelectorAll(".vsm--item span").forEach(e => { - //empty icon name on mouseover - e.setAttribute("title", "") - }); + this.$el.querySelectorAll(".vsm--item span").forEach(e => { + //empty icon name on mouseover + e.setAttribute("title", "") + }); + this.showChildren = false }, flush: 'post' } }, data() { return { - collapsed: localStorage.getItem("menuCollapsed") === "true" + collapsed: localStorage.getItem("menuCollapsed") === "true", + showChildren: false }; }, computed: {
null
test
train
2023-05-23T14:47:26
"2023-04-26T13:38:12Z"
loicmathieu
train
kestra-io/kestra/1167_1377
kestra-io/kestra
kestra-io/kestra/1167
kestra-io/kestra/1377
[ "keyword_pr_to_issue" ]
694af59ee5de07687c222d1e0556636183ee6607
fb269a3b6b7984fb5b504ed88f5c5eaf651ec8ca
[ "@brian-mulier-p if you replace the . with that white space unicode I think it will do the trick\n```js\ntext.replaceAll('.' '&#x200B;.')\n``` ", "Imma try that, thanks :)" ]
[]
"2023-05-22T17:11:21Z"
[ "enhancement" ]
Bad namespace hyphenation (in table)
### Issue description Namespace should be clearer in table - break line at each point ? ![image](https://user-images.githubusercontent.com/46634684/231785604-f479b6e0-a2e2-492d-adfe-83bc0b202b3b.png)
[ "ui/src/components/executions/Executions.vue", "ui/src/components/flows/Flows.vue", "ui/src/components/templates/Templates.vue", "ui/src/styles/layout/element-plus-overload.scss", "ui/src/utils/filters.js" ]
[ "ui/src/components/executions/Executions.vue", "ui/src/components/flows/Flows.vue", "ui/src/components/templates/Templates.vue", "ui/src/styles/layout/element-plus-overload.scss", "ui/src/utils/filters.js" ]
[]
diff --git a/ui/src/components/executions/Executions.vue b/ui/src/components/executions/Executions.vue index 4c7f0795a0..971a04fbb3 100644 --- a/ui/src/components/executions/Executions.vue +++ b/ui/src/components/executions/Executions.vue @@ -79,12 +79,12 @@ </template> </el-table-column> - <el-table-column v-if="$route.name !== 'flows/update' && !hidden.includes('namespace')" prop="namespace" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('namespace')" /> + <el-table-column v-if="$route.name !== 'flows/update' && !hidden.includes('namespace')" prop="namespace" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('namespace')" :formatter="(_, __, cellValue) => $filters.invisibleSpace(cellValue)"/> <el-table-column v-if="$route.name !== 'flows/update' && !hidden.includes('flowId')" prop="flowId" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('flow')"> <template #default="scope"> <router-link :to="{name: 'flows/update', params: {namespace: scope.row.namespace, id: scope.row.flowId}}"> - {{ scope.row.flowId }} + {{ $filters.invisibleSpace(scope.row.flowId) }} </router-link> </template> </el-table-column> diff --git a/ui/src/components/flows/Flows.vue b/ui/src/components/flows/Flows.vue index aaf3d4054a..2d0f055d98 100644 --- a/ui/src/components/flows/Flows.vue +++ b/ui/src/components/flows/Flows.vue @@ -47,7 +47,7 @@ <router-link :to="{name: 'flows/update', params: {namespace: scope.row.namespace, id: scope.row.id}}" > - {{ scope.row.id }} + {{ $filters.invisibleSpace(scope.row.id) }} </router-link> &nbsp;<markdown-tooltip :id="scope.row.namespace + '-' + scope.row.id" @@ -63,7 +63,7 @@ </template> </el-table-column> - <el-table-column prop="namespace" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('namespace')" /> + <el-table-column prop="namespace" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('namespace')" :formatter="(_, __, cellValue) => $filters.invisibleSpace(cellValue)" /> <el-table-column prop="state" @@ -104,19 +104,21 @@ <bottom-line> <ul> - <ul v-if="flowsSelection.length !== 0 && canRead"> - <bottom-line-counter v-model="queryBulkAction" :selections="flowsSelection" :total="total" @update:model-value="selectAll()"> - <el-button v-if="canRead" :icon="Download" size="large" @click="exportFlows()"> - {{ $t('export') }} - </el-button> - <el-button v-if="canDelete" @click="deleteFlows" size="large" :icon="TrashCan"> - {{ $t('delete') }} - </el-button> - <el-button v-if="canDisable" @click="disableFlows" size="large" :icon="FileDocumentRemoveOutline"> - {{ $t('disable') }} - </el-button> - </bottom-line-counter> - </ul> + <li> + <ul v-if="flowsSelection.length !== 0 && canRead"> + <bottom-line-counter v-model="queryBulkAction" :selections="flowsSelection" :total="total" @update:model-value="selectAll()"> + <el-button v-if="canRead" :icon="Download" size="large" @click="exportFlows()"> + {{ $t('export') }} + </el-button> + <el-button v-if="canDelete" @click="deleteFlows" size="large" :icon="TrashCan"> + {{ $t('delete') }} + </el-button> + <el-button v-if="canDisable" @click="disableFlows" size="large" :icon="FileDocumentRemoveOutline"> + {{ $t('disable') }} + </el-button> + </bottom-line-counter> + </ul> + </li> <li class="spacer" /> <li> <div class="el-input el-input-file el-input--large custom-upload"> diff --git a/ui/src/components/templates/Templates.vue b/ui/src/components/templates/Templates.vue index 49f8e9653d..e94535cb97 100644 --- a/ui/src/components/templates/Templates.vue +++ b/ui/src/components/templates/Templates.vue @@ -32,6 +32,7 @@ @selection-change="handleSelectionChange" > <el-table-column type="selection" v-if="(canRead)" /> + <el-table-column prop="id" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('id')"> <template #default="scope"> <router-link @@ -47,6 +48,8 @@ </template> </el-table-column> + <el-table-column prop="namespace" sortable="custom" :sort-orders="['ascending', 'descending']" :label="$t('namespace')" :formatter="(_, __, cellValue) => $filters.invisibleSpace(cellValue)" /> + <el-table-column column-key="action" class-name="row-action"> <template #default="scope"> <router-link :to="{name: 'templates/update', params : {namespace: scope.row.namespace, id: scope.row.id}}"> diff --git a/ui/src/styles/layout/element-plus-overload.scss b/ui/src/styles/layout/element-plus-overload.scss index 66877d09b0..7923971196 100644 --- a/ui/src/styles/layout/element-plus-overload.scss +++ b/ui/src/styles/layout/element-plus-overload.scss @@ -62,7 +62,7 @@ } label { - displabey: flex; + display: flex; cursor: pointer; margin-left: 10px; line-height: 30px; @@ -207,6 +207,7 @@ form.ks-horizontal { .cell { padding: 0 8px; + word-break: break-word; } .el-table__cell { diff --git a/ui/src/utils/filters.js b/ui/src/utils/filters.js index bd0cf4cd5e..5f5db2063e 100644 --- a/ui/src/utils/filters.js +++ b/ui/src/utils/filters.js @@ -2,6 +2,9 @@ import Utils from "./utils"; import {getCurrentInstance} from "vue"; export default { + invisibleSpace: (value) => { + return value.replaceAll(".", "\u200B" + "."); + }, humanizeDuration: (value, options) => { return Utils.humanDuration(value, options); },
null
train
train
2023-05-22T17:06:40
"2023-04-13T14:11:12Z"
Ben8t
train
kestra-io/kestra/1386_1387
kestra-io/kestra
kestra-io/kestra/1386
kestra-io/kestra/1387
[ "keyword_pr_to_issue" ]
694af59ee5de07687c222d1e0556636183ee6607
59b1017479413a6d1b0390a4504dfc1dd46c953d
[]
[]
"2023-05-23T10:29:51Z"
[ "bug", "frontend" ]
File inputs no longer working in production mode
### Expected Behavior File inputs should be displayed ### Actual Behaviour File inputs are not displayed with an undefined error in console (due to `this.` usage in template) ### Steps To Reproduce Create a flow with a file inputs Create a new execution File inputs are not displayed ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT ### Example flow _No response_
[ "ui/src/components/flows/FlowRun.vue" ]
[ "ui/src/components/flows/FlowRun.vue" ]
[]
diff --git a/ui/src/components/flows/FlowRun.vue b/ui/src/components/flows/FlowRun.vue index 99001427eb..ea2584bf03 100644 --- a/ui/src/components/flows/FlowRun.vue +++ b/ui/src/components/flows/FlowRun.vue @@ -58,9 +58,9 @@ type="file" @change="onFileChange(input, $event)" autocomplete="off" - :style="{display: typeof(this.inputs[input.name]) === 'string' && this.inputs[input.name].startsWith('kestra:///') ? 'none': ''}" + :style="{display: typeof(inputs[input.name]) === 'string' && inputs[input.name].startsWith('kestra:///') ? 'none': ''}" > - <label v-if="typeof(this.inputs[input.name]) === 'string' && this.inputs[input.name].startsWith('kestra:///')" + <label v-if="typeof(inputs[input.name]) === 'string' && inputs[input.name].startsWith('kestra:///')" :for="input.name+'-file'">Kestra Internal Storage File</label> </div> </div>
null
test
train
2023-05-22T17:06:40
"2023-05-23T10:27:03Z"
brian-mulier-p
train
kestra-io/kestra/1388_1390
kestra-io/kestra
kestra-io/kestra/1388
kestra-io/kestra/1390
[ "keyword_pr_to_issue" ]
2998a15920898a361f24117b08c2d530edf2eb22
2c949e057ef5f01b308cdd4de8e83632631b83a2
[]
[]
"2023-05-23T13:18:09Z"
[]
Host somewhere the tutorial/guided tour data file
### Feature description Both the guided tour inside the UI and the tutorial on the website use a data file from the French OpenData website: https://www.data.gouv.fr/fr/datasets/r/d33eabc9-e2fd-4787-83e5-a5fcfb5af66d Unfortunately, this file may not be available everywhere; we have reports from users that cannot access it while we can access it simultaneously. We may want to host this file by ourself, or rely on a different data set.
[ "ui/src/components/onboarding/VueTour.vue" ]
[ "ui/src/components/onboarding/VueTour.vue" ]
[]
diff --git a/ui/src/components/onboarding/VueTour.vue b/ui/src/components/onboarding/VueTour.vue index 1179b59b5e..5bdaa45d4f 100644 --- a/ui/src/components/onboarding/VueTour.vue +++ b/ui/src/components/onboarding/VueTour.vue @@ -310,7 +310,7 @@ " # " + this.$t("onboarding-flow.inputsDetails2") + "\n" + " - name: csvUrl\n" + " type: STRING\n" + - " defaults: https://www.data.gouv.fr/fr/datasets/r/d33eabc9-e2fd-4787-83e5-a5fcfb5af66d", + " defaults: https://gist.githubusercontent.com/tchiotludo/2b7f28f4f507074e60150aedb028e074/raw/6b6348c4f912e79e3ffccaf944fd019bf51cba30/conso-elec-gaz-annuelle-par-naf-agregee-region.csv", "# " + this.$t("onboarding-flow.tasks1") + "\n" + "# " + this.$t("onboarding-flow.tasks2") + "\n" + "# " + this.$t("onboarding-flow.tasks3") + "\n" +
null
train
train
2023-05-23T15:07:13
"2023-05-23T11:47:17Z"
loicmathieu
train
kestra-io/kestra/1341_1404
kestra-io/kestra
kestra-io/kestra/1341
kestra-io/kestra/1404
[ "keyword_pr_to_issue" ]
cbce23c7f32c94cb5abb6ea8ea285519bcbcd5fa
45e0bd414a06d7732d69f7ce9860cae6cfaf8863
[]
[]
"2023-05-25T09:31:05Z"
[ "enhancement", "frontend" ]
Error message is not really visible
### Feature description With the new "Save Draft" feature, error messages when the flow is wrong are a bit hided <img width="1166" alt="Screenshot 2023-05-19 at 10 30 25" src="https://github.com/kestra-io/kestra/assets/46634684/49048a07-8978-4c61-82a8-4ae7c5c6f082">
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 89349eb09f..e7c8d31a7f 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -1,5 +1,5 @@ <script setup> - import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, computed} from "vue"; + import {ref, onMounted, nextTick, watch, getCurrentInstance, onBeforeUnmount, computed, h} from "vue"; import {useStore} from "vuex" import {VueFlow, useVueFlow, Position, MarkerType} from "@vue-flow/core" import {Controls, ControlButton} from "@vue-flow/controls" @@ -37,6 +37,7 @@ import editor from "../inputs/Editor.vue"; import yamlUtils from "../../utils/yamlUtils"; import {pageFromRoute} from "../../utils/eventsRouter"; + import {ElNotification, ElTable, ElTableColumn} from "element-plus"; const { id, @@ -573,15 +574,32 @@ haveChange.value = false; } - const showDraftPopup = (draftReason) => { - toast.confirm(draftReason + " " + (props.isCreating ? t("save draft.prompt.creation") : t("save draft.prompt.existing", { - namespace: flow.namespace, - id: flow.id - })), - () => { - persistEditorContent(false); - } - ); + const saveAsDraft = (errorMessage) => { + const errorToastDom = [h("span", {innerHTML: t("invalid flow")}), + h( + ElTable, + { + stripe: true, + tableLayout: "auto", + fixed: true, + data: [{errorMessage}], + class: ["mt-2"], + size: "small", + }, + [ + h(ElTableColumn, {prop: "errorMessage", label: "Message"}) + ] + )]; + + ElNotification({ + title: t("save draft.message"), + message: h("div", errorToastDom), + type: "error", + duration: 0, + dangerouslyUseHTMLString: true, + customClass: "large" + }); + persistEditorContent(false); } const onEdit = (event) => { @@ -832,7 +850,7 @@ flowParsed = YamlUtils.parse(flowYaml.value); } catch (_) {} if (validation[0].constraints) { - showDraftPopup(t("save draft.prompt.base")); + saveAsDraft(validation[0].constraints); return; } diff --git a/ui/src/translations.json b/ui/src/translations.json index 250e79b145..cfb6001ae2 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -421,12 +421,7 @@ "metric choice": "Please choose a metric and an aggregation", "of": "of", "save draft": { - "prompt": { - "base": "The current Flow is not valid. Do you still want to save it as a draft ?", - "http_error": "Unable to validate the Flow due to an HTTP error. Do you want to save the current Flow as draft ?", - "creation": "You will retrieve it on your next Flow creation.", - "existing": "You will retrieve it on your next <code>{namespace}.{id}</code> Flow edition." - }, + "message": "Draft saved", "retrieval": { "creation": "A Flow creation draft was retrieved, do you want to resume its edition ?", "existing": "A <code>{flowFullName}</code> Flow draft was retrieved, do you want to resume its edition ?" @@ -856,12 +851,7 @@ "metric choice": "Merci de sélectionner une métrique et une agrégation", "of": "de", "save draft": { - "prompt": { - "base": "Le Flow actuel est invalide. Voulez-vous le sauvegarder en tant que brouillon ?", - "http_error": "Impossible de valider le Flow en raison d'une erreur HTTP. Voulez-vous sauvegarder le Flow actuel en tant que brouillon ?", - "creation": "Vous le récupérerez à votre prochaine création de Flow.", - "existing": "Vous le récupérerez à votre prochaine édition du Flow <code>{namespace}.{id}</code>." - }, + "message": "Brouillon sauvegardé", "retrieval": { "creation": "Un brouillon de création de Flow existe, voulez-vous reprendre son édition ?", "existing": "Un brouillon pour le Flow <code>{flowFullName}</code> existe, voulez-vous reprendre son édition?"
null
val
train
2023-05-26T17:00:51
"2023-05-19T08:34:36Z"
Ben8t
train
kestra-io/kestra/1406_1420
kestra-io/kestra
kestra-io/kestra/1406
kestra-io/kestra/1420
[ "keyword_pr_to_issue" ]
45e0bd414a06d7732d69f7ce9860cae6cfaf8863
83c7bffcfe668c8f5e45b1ea0136be976731d731
[]
[]
"2023-05-29T09:40:08Z"
[ "bug" ]
Cannot edit an existing invalid flow
### Expected Behavior If a flow is invalid in the database (this is an edge case but it can happen), I should still be able to edit it. ### Actual Behaviour The flow is not editable as the editor loads forever. ![image](https://github.com/kestra-io/kestra/assets/1819009/3207eab7-28ac-4b38-9469-b005d7f7b352) The following JavScript error is shown: ``` index-9958380e.js:1 TypeError: n.flowGraph.edges is not iterable at ue (index-9958380e.js:1074:259649) at ge (index-9958380e.js:1074:261791) at X (index-9958380e.js:1074:260077) at index-9958380e.js:1074:263820 at index-9958380e.js:1:26652 at lm (index-9958380e.js:1:14864) at Nu (index-9958380e.js:1:14943) at e.__weh.e.__weh (index-9958380e.js:1:26532) at Wge (index-9958380e.js:1:16251) at Uge (index-9958380e.js:1:16561) ``` ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json" ]
[ "ui/src/components/graph/Topology.vue", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index e7c8d31a7f..42cd4d4e7c 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -183,11 +183,17 @@ return flow ? YamlUtils.flowHaveTasks(flow) : false; } - const initYamlSource = () => { + const initYamlSource = async () => { flowYaml.value = flow ? flow.source : YamlUtils.stringify({ id: props.flowId, namespace: props.namespace }); + + const validation = await store.dispatch("flow/validateFlow", {flow: flowYaml.value}); + const validationErrors = validation[0].constraints; + if(validationErrors){ + errorToast(t("cannot create topology"), t("invalid flow"), validationErrors); + } generateGraph(); if(!props.isReadOnly) { @@ -257,133 +263,137 @@ const generateGraph = () => { isLoading.value = true; - if (!props.flowGraph || !flowHaveTasks()) { - elements.value.push({ - id: "start", - label: "", - type: "dot", - position: {x: 0, y: 0}, - style: { - width: "5px", - height: "5px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: undefined, - draggable: false, - }) - elements.value.push({ - id: "end", - label: "", - type: "dot", - position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, - style: { - width: "5px", - height: "5px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: undefined, - draggable: false, - }) - elements.value.push({ - id: "start|end", - source: "start", - target: "end", - type: "edge", - markerEnd: MarkerType.ArrowClosed, - data: { - edge: { - relation: { - relationType: "SEQUENTIAL" - } + try { + if (!props.flowGraph || !flowHaveTasks()) { + elements.value.push({ + id: "start", + label: "", + type: "dot", + position: {x: 0, y: 0}, + style: { + width: "5px", + height: "5px" }, - isFlowable: false, - initTask: true, - } - }) - isLoading.value = false; - return; - } - if (props.flowGraph === undefined) { - isLoading.value = false; - return; - } - const dagreGraph = generateDagreGraph(); - const clusters = {}; - for (let cluster of (props.flowGraph.clusters || [])) { - for (let nodeUid of cluster.nodes) { - clusters[nodeUid] = cluster.cluster; + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: undefined, + draggable: false, + }) + elements.value.push({ + id: "end", + label: "", + type: "dot", + position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, + style: { + width: "5px", + height: "5px" + }, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: undefined, + draggable: false, + }) + elements.value.push({ + id: "start|end", + source: "start", + target: "end", + type: "edge", + markerEnd: MarkerType.ArrowClosed, + data: { + edge: { + relation: { + relationType: "SEQUENTIAL" + } + }, + isFlowable: false, + initTask: true, + } + }) + isLoading.value = false; + return; } + if (props.flowGraph === undefined) { + isLoading.value = false; + return; + } + const dagreGraph = generateDagreGraph(); + const clusters = {}; + for (let cluster of (props.flowGraph.clusters || [])) { + for (let nodeUid of cluster.nodes) { + clusters[nodeUid] = cluster.cluster; + } - const dagreNode = dagreGraph.node(cluster.cluster.uid) - const parentNode = cluster.parents ? cluster.parents[cluster.parents.length - 1] : undefined; - - const clusterUid = cluster.cluster.uid; - elements.value.push({ - id: clusterUid, - label: clusterUid, - type: "cluster", - parentNode: parentNode, - position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), - style: { - width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", - height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", - }, - }) - } - - for (const node of props.flowGraph.nodes) { - const dagreNode = dagreGraph.node(node.uid); - let nodeType = "task"; - if (node.type.includes("GraphClusterEnd")) { - nodeType = "dot"; - } else if (clusters[node.uid] === undefined && node.type.includes("GraphClusterRoot")) { - nodeType = "dot"; - } else if (node.type.includes("GraphClusterRoot")) { - nodeType = "dot"; - } else if (node.type.includes("GraphTrigger")) { - nodeType = "trigger"; + const dagreNode = dagreGraph.node(cluster.cluster.uid) + const parentNode = cluster.parents ? cluster.parents[cluster.parents.length - 1] : undefined; + + const clusterUid = cluster.cluster.uid; + elements.value.push({ + id: clusterUid, + label: clusterUid, + type: "cluster", + parentNode: parentNode, + position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), + style: { + width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", + height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", + }, + }) } - elements.value.push({ - id: node.uid, - label: isTaskNode(node) ? node.task.id : "", - type: nodeType, - position: getNodePosition(dagreNode, clusters[node.uid] ? dagreGraph.node(clusters[node.uid].uid) : undefined), - style: { - width: getNodeWidth(node) + "px", - height: getNodeHeight(node) + "px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, - draggable: nodeType === "task" && !props.isReadOnly, - data: { - node: node, - namespace: props.namespace, - flowId: props.flowId, - revision: props.execution ? props.execution.flowRevision : undefined, - isFlowable: isTaskNode(node) ? flowables().includes(node.task.id) : false - }, - }) - } - for (const edge of props.flowGraph.edges) { - elements.value.push({ - id: edge.source + "|" + edge.target, - source: edge.source, - target: edge.target, - type: "edge", - markerEnd: MarkerType.ArrowClosed, - data: { - edge: edge, - haveAdd: complexEdgeHaveAdd(edge), - isFlowable: flowables().includes(edge.source) || flowables().includes(edge.target), - nextTaskId: getNextTaskId(edge.target) + for (const node of props.flowGraph.nodes) { + const dagreNode = dagreGraph.node(node.uid); + let nodeType = "task"; + if (node.type.includes("GraphClusterEnd")) { + nodeType = "dot"; + } else if (clusters[node.uid] === undefined && node.type.includes("GraphClusterRoot")) { + nodeType = "dot"; + } else if (node.type.includes("GraphClusterRoot")) { + nodeType = "dot"; + } else if (node.type.includes("GraphTrigger")) { + nodeType = "trigger"; } - }) + elements.value.push({ + id: node.uid, + label: isTaskNode(node) ? node.task.id : "", + type: nodeType, + position: getNodePosition(dagreNode, clusters[node.uid] ? dagreGraph.node(clusters[node.uid].uid) : undefined), + style: { + width: getNodeWidth(node) + "px", + height: getNodeHeight(node) + "px" + }, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, + draggable: nodeType === "task" && !props.isReadOnly, + data: { + node: node, + namespace: props.namespace, + flowId: props.flowId, + revision: props.execution ? props.execution.flowRevision : undefined, + isFlowable: isTaskNode(node) ? flowables().includes(node.task.id) : false + }, + }) + } + + for (const edge of props.flowGraph.edges) { + elements.value.push({ + id: edge.source + "|" + edge.target, + source: edge.source, + target: edge.target, + type: "edge", + markerEnd: MarkerType.ArrowClosed, + data: { + edge: edge, + haveAdd: complexEdgeHaveAdd(edge), + isFlowable: flowables().includes(edge.source) || flowables().includes(edge.target), + nextTaskId: getNextTaskId(edge.target) + } + }) + } + } catch (e) {} + finally { + isLoading.value = false; } - isLoading.value = false; } const getFirstTaskId = () => { @@ -439,11 +449,11 @@ } } - onMounted(() => { + onMounted(async () => { if (props.isCreating) { store.commit("flow/setFlowGraph", undefined); } - initYamlSource(); + await initYamlSource(); // Regenerate graph on window resize observeWidth(); // Save on ctrl+s in topology @@ -574,31 +584,35 @@ haveChange.value = false; } - const saveAsDraft = (errorMessage) => { - const errorToastDom = [h("span", {innerHTML: t("invalid flow")}), + const errorToast = (title, message, detailedError) => { + const errorToastDom = [h("span", {innerHTML: message}), h( - ElTable, - { - stripe: true, - tableLayout: "auto", - fixed: true, - data: [{errorMessage}], - class: ["mt-2"], - size: "small", - }, - [ - h(ElTableColumn, {prop: "errorMessage", label: "Message"}) - ] - )]; + ElTable, + { + stripe: true, + tableLayout: "auto", + fixed: true, + data: [{detailedError}], + class: ["mt-2"], + size: "small", + }, + [ + h(ElTableColumn, {prop: "detailedError", label: "Message"}) + ] + )]; ElNotification({ - title: t("save draft.message"), - message: h("div", errorToastDom), + title: title, + message: h("div", errorToastDom), type: "error", duration: 0, dangerouslyUseHTMLString: true, customClass: "large" }); + } + + const saveAsDraft = (errorMessage) => { + errorToast(t("save draft.message"), t("invalid flow"), errorMessage); persistEditorContent(false); } diff --git a/ui/src/translations.json b/ui/src/translations.json index cfb6001ae2..7700d6528d 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -94,6 +94,7 @@ "form": "Form", "form error": "Form error", "display topology for flow": "Display topology for flow", + "cannot create topology": "Unable to create topology for flow", "start date": "Start date", "end date": "End date", "creation": "Creation", @@ -523,6 +524,7 @@ "form": "Formulaire", "form error": "Formulaire invalid", "display topology for flow": "Afficher la topologie du flow", + "cannot create topology": "Impossible de créer la topologie du flow", "start date": "Date de début", "end date": "Date de fin", "creation": "Création",
null
train
train
2023-05-29T10:12:42
"2023-05-25T10:04:32Z"
loicmathieu
train
kestra-io/kestra/1406_1431
kestra-io/kestra
kestra-io/kestra/1406
kestra-io/kestra/1431
[ "keyword_pr_to_issue" ]
bd18f8cd83295dfe05363a5887ca5445a2e2464c
02457530a918b6d173e2d6ff15f6eeeb95921fc6
[]
[]
"2023-05-30T12:52:44Z"
[ "bug" ]
Cannot edit an existing invalid flow
### Expected Behavior If a flow is invalid in the database (this is an edge case but it can happen), I should still be able to edit it. ### Actual Behaviour The flow is not editable as the editor loads forever. ![image](https://github.com/kestra-io/kestra/assets/1819009/3207eab7-28ac-4b38-9469-b005d7f7b352) The following JavScript error is shown: ``` index-9958380e.js:1 TypeError: n.flowGraph.edges is not iterable at ue (index-9958380e.js:1074:259649) at ge (index-9958380e.js:1074:261791) at X (index-9958380e.js:1074:260077) at index-9958380e.js:1074:263820 at index-9958380e.js:1:26652 at lm (index-9958380e.js:1:14864) at Nu (index-9958380e.js:1:14943) at e.__weh.e.__weh (index-9958380e.js:1:26532) at Wge (index-9958380e.js:1:16251) at Uge (index-9958380e.js:1:16561) ``` ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/graph/Topology.vue" ]
[ "ui/src/components/graph/Topology.vue" ]
[]
diff --git a/ui/src/components/graph/Topology.vue b/ui/src/components/graph/Topology.vue index 42cd4d4e7c..c67fe9ec25 100644 --- a/ui/src/components/graph/Topology.vue +++ b/ui/src/components/graph/Topology.vue @@ -189,12 +189,17 @@ namespace: props.namespace }); - const validation = await store.dispatch("flow/validateFlow", {flow: flowYaml.value}); - const validationErrors = validation[0].constraints; - if(validationErrors){ - errorToast(t("cannot create topology"), t("invalid flow"), validationErrors); + if(!props.isCreating) { + const validation = await store.dispatch("flow/validateFlow", {flow: flowYaml.value}); + const validationErrors = validation[0].constraints; + if (validationErrors) { + singleErrorToast(t("cannot create topology"), t("invalid flow"), validationErrors); + }else { + generateGraph(); + } + } else { + generateGraph(); } - generateGraph(); if(!props.isReadOnly) { let restoredLocalStorageKey; @@ -584,35 +589,21 @@ haveChange.value = false; } - const errorToast = (title, message, detailedError) => { - const errorToastDom = [h("span", {innerHTML: message}), - h( - ElTable, - { - stripe: true, - tableLayout: "auto", - fixed: true, - data: [{detailedError}], - class: ["mt-2"], - size: "small", - }, - [ - h(ElTableColumn, {prop: "detailedError", label: "Message"}) - ] - )]; - - ElNotification({ + const singleErrorToast = (title, message, detailedError) => { + store.dispatch("core/showMessage", { title: title, - message: h("div", errorToastDom), - type: "error", - duration: 0, - dangerouslyUseHTMLString: true, - customClass: "large" + message: message, + content: { + _embedded: { + errors: [{message: detailedError}] + } + }, + variant: "error" }); } const saveAsDraft = (errorMessage) => { - errorToast(t("save draft.message"), t("invalid flow"), errorMessage); + singleErrorToast(t("save draft.message"), t("invalid flow"), errorMessage); persistEditorContent(false); }
null
train
train
2023-05-30T14:28:34
"2023-05-25T10:04:32Z"
loicmathieu
train
kestra-io/kestra/1092_1454
kestra-io/kestra
kestra-io/kestra/1092
kestra-io/kestra/1454
[ "keyword_pr_to_issue" ]
c326b32678652288f9f173f7c6d6f5f74f644ed8
0d7e768d75c6bf54747501cd378f40263f3ffb86
[]
[]
"2023-06-05T12:43:50Z"
[ "bug" ]
Inputs can have duplicated name
### Expected Behavior An error should be thrown when two inputs are defined with the same name (before execution). ### Actual Behaviour Inputs can have duplicated name ### Steps To Reproduce ```yaml id: a-flow namespace: some.namespace inputs: - name: first_input required: true type: STRING - name: first_input required: true type: INT tasks: - id: taskOne type: io.kestra.core.tasks.log.Log message: "{{ inputs.first_input }}" ``` ### Environment Information - Kestra Version: 0.8.0-SNAPSHOT ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/validations/ValidationFactory.java" ]
[ "core/src/main/java/io/kestra/core/validations/ValidationFactory.java" ]
[ "core/src/test/java/io/kestra/core/models/flows/FlowTest.java", "core/src/test/resources/flows/invalids/duplicate-inputs.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java index 7c54c83b65..21289099d4 100644 --- a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java +++ b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java @@ -123,21 +123,35 @@ ConstraintValidator<FlowValidation, Flow> flowValidation() { } List<String> violations = new ArrayList<>(); - List<Task> allTasks = value.allTasksWithChilds(); - // unique id - List<String> ids = allTasks + // task unique id + List<String> taskIds = value.allTasksWithChilds() .stream() .map(Task::getId) - .collect(Collectors.toList()); - - List<String> duplicates = ids + .toList(); + List<String> taskDuplicates = taskIds .stream() .distinct() - .filter(entry -> Collections.frequency(ids, entry) > 1).collect(Collectors.toList()); + .filter(entry -> Collections.frequency(taskIds, entry) > 1) + .toList(); + if (taskDuplicates.size() > 0) { + violations.add("Duplicate task id with name [" + String.join(", ", taskDuplicates) + "]"); + } - if (duplicates.size() > 0) { - violations.add("Duplicate task id with name [" + String.join(", ", duplicates) + "]"); + // input unique name + if (value.getInputs() != null) { + List<String> inputNames = value.getInputs() + .stream() + .map(Input::getName) + .toList(); + List<String> inputDuplicates = inputNames + .stream() + .distinct() + .filter(entry -> Collections.frequency(inputNames, entry) > 1) + .toList(); + if (inputDuplicates.size() > 0) { + violations.add("Duplicate input with name [" + String.join(", ", inputDuplicates) + "]"); + } } if (violations.size() > 0) {
diff --git a/core/src/test/java/io/kestra/core/models/flows/FlowTest.java b/core/src/test/java/io/kestra/core/models/flows/FlowTest.java index 1935de5566..4eb7f1cbb9 100644 --- a/core/src/test/java/io/kestra/core/models/flows/FlowTest.java +++ b/core/src/test/java/io/kestra/core/models/flows/FlowTest.java @@ -39,6 +39,17 @@ void duplicate() { assertThat(validate.get().getMessage(), containsString("Duplicate task id with name [date]")); } + @Test + void duplicateInputs() { + Flow flow = this.parse("flows/invalids/duplicate-inputs.yaml"); + Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); + + assertThat(validate.isPresent(), is(true)); + assertThat(validate.get().getConstraintViolations().size(), is(1)); + + assertThat(validate.get().getMessage(), containsString("Duplicate input with name [first_input]")); + } + @Test void duplicateParallel() { Flow flow = this.parse("flows/invalids/duplicate-parallel.yaml"); diff --git a/core/src/test/resources/flows/invalids/duplicate-inputs.yaml b/core/src/test/resources/flows/invalids/duplicate-inputs.yaml new file mode 100644 index 0000000000..d2b57df6ce --- /dev/null +++ b/core/src/test/resources/flows/invalids/duplicate-inputs.yaml @@ -0,0 +1,14 @@ +id: duplicate-inputs +namespace: io.kestra.tests + +inputs: + - name: first_input + required: true + type: STRING + - name: first_input + required: true + type: STRING +tasks: + - id: taskOne + type: io.kestra.core.tasks.log.Log + message: "{{ inputs.first_input }}" \ No newline at end of file
val
train
2023-06-05T15:29:27
"2023-03-21T15:29:32Z"
Skraye
train
kestra-io/kestra/1288_1463
kestra-io/kestra
kestra-io/kestra/1288
kestra-io/kestra/1463
[ "keyword_pr_to_issue" ]
9d6fbbe14e6f5afb2641f086f604db90c6951319
c4955f7180d647cba0fce1dd31218d5670cf95d6
[ "> [batuhanfaik](/batuhanfaik) [ May 15, 2023 ](https://github.com/kestra-io/kestra/discussions/1143#discussioncomment-5904698)\r\n> LGTM, thanks a lot for opening this! Maybe we can add the code of whole solution to the sample tree as it involves most of the edge cases that people (including myself) face when solving DAGs :)\r\n\r\n@batuhanfaik, didn't understand your comment? \r\n", "Sorry, I could've been more clear. Your suggestion looks good to me. I wanted to say that we can add the sample code which would actually solve the tree presented in the figure. However, with the introduction of simple \"dependsOn\" keyword, we don't need to write the whole thing. It's pretty self explanatory " ]
[ "default to `Runtime.availableProcessor() * 2` as it's a sane default (I have a PR somewhere to do the same for the Parallel tasks)", "I'll rename TaskDepend to DagTask and move the class inside this one.", "```suggestion\r\n @NotEmpty\r\n```", "return an empty list instead of null", "you can return a list as it may be multiple cyclic dependencies", "```suggestion\r\n private List<String> nestedDependencies(TaskDepend taskDepend, List<TaskDepend> tasks, List<String> visited) {\r\n```", "I think this can be an array list as you only use the list at index 0", "Why do you check on last created ?", "This is really hard to read", "It's part of the parallel task on which the dag task is based" ]
"2023-06-06T13:48:23Z"
[ "backend", "enhancement" ]
Create a Flowable task type Dag with dependsOn
### Discussed in https://github.com/kestra-io/kestra/discussions/1143 This kind of heavy dependent graph is complicated to do in Kestra: ![SimpleGraph](https://g.gravizo.com/svg?%20digraph%20G%20{%20start%20-%3E%20a0;%20start%20-%3E%20b0;%20start%20-%3E%20c0;%20start%20-%3E%20d0;%20start%20-%3E%20e0;%20a0%20-%3E%20a1_0;%20a0%20-%3E%20a1_1;%20a0%20-%3E%20a1_2;%20a1_1%20-%3E%20a2_0;%20a1_1%20-%3E%20a2_1;%20b0%20-%3E%20bc1_0;%20c0%20-%3E%20bc1_0;%20bc1_0%20-%3E%20bc2;%20c0%20-%3E%20c1_1;%20c1_1%20-%3E%20e2;%20e0%20-%3E%20e1;%20e1%20-%3E%20e2;%20start%20[shape=Mdiamond];%20}%20)) My suggest is to create a [Flowable task](https://kestra.io/docs/concepts/flows#flowable-task) is will have this structure : ```yaml type: io.kestra.core.tasks.flows.Dag tasks: - task: id: a type: io.kestra.core.tasks.debugs.Return - task: id: b type: io.kestra.core.tasks.debugs.Return - task: id: c type: io.kestra.core.tasks.debugs.Return dependsOn : - a - b - task: id: d type: io.kestra.core.tasks.debugs.Return dependsOn : - c ``` That will allow more complex dag to be created with out the pain of build manually dependencies.
[ "core/src/main/java/io/kestra/core/runners/FlowableUtils.java", "core/src/main/java/io/kestra/core/services/GraphService.java", "core/src/main/java/io/kestra/core/validations/ValidationFactory.java", "ui/src/components/flows/tasks/Task.js", "ui/src/components/graph/nodes/Edge.vue", "ui/src/components/inputs/LowCodeEditor.vue", "ui/src/utils/yamlUtils.js", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "core/src/main/java/io/kestra/core/runners/FlowableUtils.java", "core/src/main/java/io/kestra/core/services/GraphService.java", "core/src/main/java/io/kestra/core/tasks/flows/Dag.java", "core/src/main/java/io/kestra/core/validations/DagTaskValidation.java", "core/src/main/java/io/kestra/core/validations/ValidationFactory.java", "ui/src/components/flows/tasks/Task.js", "ui/src/components/graph/nodes/Edge.vue", "ui/src/components/inputs/LowCodeEditor.vue", "ui/src/utils/yamlUtils.js", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "core/src/test/java/io/kestra/core/tasks/flows/DagTest.java", "core/src/test/resources/flows/invalids/dag-cyclicdependency.yaml", "core/src/test/resources/flows/invalids/dag-notexist-task.yaml", "core/src/test/resources/flows/valids/dag.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/runners/FlowableUtils.java b/core/src/main/java/io/kestra/core/runners/FlowableUtils.java index 03acf3c25b..f93fe7b6d9 100644 --- a/core/src/main/java/io/kestra/core/runners/FlowableUtils.java +++ b/core/src/main/java/io/kestra/core/runners/FlowableUtils.java @@ -11,8 +11,11 @@ import io.kestra.core.models.tasks.ResolvedTask; import io.kestra.core.models.tasks.Task; import io.kestra.core.serializers.JacksonMapper; +import io.kestra.core.tasks.flows.Dag; import java.util.*; +import java.util.function.BiFunction; +import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -134,13 +137,68 @@ public static List<ResolvedTask> resolveTasks(List<Task> tasks, TaskRun parentTa .collect(Collectors.toList()); } - public static List<NextTaskRun> resolveParallelNexts( Execution execution, List<ResolvedTask> tasks, List<ResolvedTask> errors, TaskRun parentTaskRun, Integer concurrency + ) { + return resolveParallelNexts( + execution, + tasks, errors, + parentTaskRun, + concurrency, + (nextTaskRunStream, taskRuns) -> nextTaskRunStream + ); + } + + public static List<NextTaskRun> resolveDagNexts( + Execution execution, + List<ResolvedTask> tasks, + List<ResolvedTask> errors, + TaskRun parentTaskRun, + Integer concurrency, + List<Dag.DagTask> taskDependencies + ) { + return resolveParallelNexts( + execution, + tasks, errors, + parentTaskRun, + concurrency, + (nextTaskRunStream, taskRuns) -> nextTaskRunStream + .filter(nextTaskRun -> { + Task task = nextTaskRun.getTask(); + List<String> taskDependIds = taskDependencies + .stream() + .filter(taskDepend -> taskDepend + .getTask() + .getId() + .equals(task.getId()) + ) + .findFirst() + .get() + .getDependsOn(); + + // Check if have no dependencies OR all dependencies are terminated + return taskDependIds == null || + new HashSet<>(taskRuns + .stream() + .filter(taskRun -> taskRun.getState().isTerminated()) + .map(TaskRun::getTaskId).toList() + ) + .containsAll(taskDependIds); + }) + ); + } + + public static List<NextTaskRun> resolveParallelNexts( + Execution execution, + List<ResolvedTask> tasks, + List<ResolvedTask> errors, + TaskRun parentTaskRun, + Integer concurrency, + BiFunction<Stream<NextTaskRun>, List<TaskRun>, Stream<NextTaskRun>> nextTaskRunFunction ) { if (execution.getState().getCurrent() == State.Type.KILLING) { return Collections.emptyList(); @@ -182,51 +240,51 @@ public static List<NextTaskRun> resolveParallelNexts( .stream() .map(resolvedTask -> resolvedTask.toNextTaskRun(execution)); + nextTaskRunStream = nextTaskRunFunction.apply(nextTaskRunStream, taskRuns); + if (concurrency > 0) { nextTaskRunStream = nextTaskRunStream.limit(concurrency - runningCount); } + return nextTaskRunStream.collect(Collectors.toList()); } return Collections.emptyList(); } - private final static TypeReference<List<Object>> TYPE_REFERENCE = new TypeReference<>() {}; + private final static TypeReference<List<Object>> TYPE_REFERENCE = new TypeReference<>() { + }; private final static ObjectMapper MAPPER = JacksonMapper.ofJson(); @SuppressWarnings({"unchecked", "rawtypes"}) public static List<ResolvedTask> resolveEachTasks(RunContext runContext, TaskRun parentTaskRun, List<Task> tasks, Object value) throws IllegalVariableEvaluationException { List<Object> values; - if(value instanceof String) { + if (value instanceof String) { String renderValue = runContext.render((String) value); try { values = MAPPER.readValue(renderValue, TYPE_REFERENCE); } catch (JsonProcessingException e) { throw new IllegalVariableEvaluationException(e); } - } - else if(value instanceof List) { + } else if (value instanceof List) { values = new ArrayList<>(((List<?>) value).size()); - for(Object obj: (List<Object>) value) { - if(obj instanceof String){ + for (Object obj : (List<Object>) value) { + if (obj instanceof String) { values.add(runContext.render((String) obj)); } else if(obj instanceof Map<?, ?>) { //JSON or YAML map values.add(runContext.render((Map) obj)); - } - else { + } else { throw new IllegalVariableEvaluationException("Unknown value element type: " + obj.getClass()); } } - } - else { + } else { throw new IllegalVariableEvaluationException("Unknown value type: " + value.getClass()); } - List<Object> distinctValue = values .stream() .distinct() @@ -245,10 +303,10 @@ else if(obj instanceof Map<?, ?>) { ArrayList<ResolvedTask> result = new ArrayList<>(); - for (Object current: distinctValue) { - for( Task task: tasks) { + for (Object current : distinctValue) { + for (Task task : tasks) { try { - String resolvedValue = current instanceof String ? (String)current : MAPPER.writeValueAsString(current); + String resolvedValue = current instanceof String ? (String) current : MAPPER.writeValueAsString(current); result.add(ResolvedTask.builder() .task(task) diff --git a/core/src/main/java/io/kestra/core/services/GraphService.java b/core/src/main/java/io/kestra/core/services/GraphService.java index 7e6dc78f2a..25d302a093 100644 --- a/core/src/main/java/io/kestra/core/services/GraphService.java +++ b/core/src/main/java/io/kestra/core/services/GraphService.java @@ -8,6 +8,7 @@ import io.kestra.core.models.tasks.FlowableTask; import io.kestra.core.models.tasks.Task; import io.kestra.core.models.triggers.AbstractTrigger; +import io.kestra.core.tasks.flows.Dag; import org.apache.commons.lang3.tuple.Pair; import org.apache.commons.lang3.tuple.Triple; @@ -194,6 +195,21 @@ public static void ifElse( } } + public static void dag( + GraphCluster graph, + List<Dag.DagTask> tasks, + List<Task> errors, + TaskRun parent, + Execution execution + ) throws IllegalVariableEvaluationException { + fillGraphDag(graph, tasks, parent, execution); + + // error cases + if (errors != null && errors.size() > 0) { + fillGraph(graph, errors, RelationType.ERROR, parent, execution, null); + } + } + private static void iterate( GraphCluster graph, List<Task> tasks, @@ -253,7 +269,7 @@ private static void fillGraph( parentValues = execution.findChildsValues(currentTaskRun, true); } - // detect kind + // detect kids if (currentTask instanceof FlowableTask) { FlowableTask<?> flowableTask = ((FlowableTask<?>) currentTask); currentGraph = flowableTask.tasksTree(execution, currentTaskRun, parentValues); @@ -316,6 +332,143 @@ private static void fillGraph( } } + + private static void fillGraphDag( + GraphCluster graph, + List<Dag.DagTask> tasks, + TaskRun parent, + Execution execution + ) throws IllegalVariableEvaluationException { + List<GraphTask> nodeTaskCreated = new ArrayList<>(); + List<String> nodeCreatedIds = new ArrayList<>(); + Set<String> dependencies = tasks.stream().filter(taskDepend -> taskDepend.getDependsOn() != null).map(Dag.DagTask::getDependsOn).flatMap(Collection::stream).collect(Collectors.toSet()); + AbstractGraph previous; + + // we validate a GraphTask based on 3 nodes (root/ task / end) + if (graph.getGraph().nodes().size() >= 3 && new ArrayList<>(graph.getGraph().nodes()).get(2) instanceof GraphTask) { + previous = new ArrayList<>(graph.getGraph().nodes()).get(2); + } else { + previous = graph.getRoot(); + } + + while(nodeCreatedIds.size() < tasks.size()) { + Iterator<Dag.DagTask> iterator = tasks.stream().filter(taskDepend -> + // Check if the task has no dependencies OR all if its dependencies have been treated + (taskDepend.getDependsOn() == null || new HashSet<>(nodeCreatedIds).containsAll(taskDepend.getDependsOn())) + // AND if the task has not been treated yet + && !nodeCreatedIds.contains(taskDepend.getTask().getId())).iterator(); + while (iterator.hasNext()) { + Dag.DagTask currentTask = iterator.next(); + for (TaskRun currentTaskRun : findTaskRuns(currentTask.getTask(), execution, parent)) { + AbstractGraph currentGraph; + List<String> parentValues = null; + + RelationType newRelation = RelationType.PARALLEL; + + Relation relation = new Relation( + newRelation, + currentTaskRun == null ? null : currentTaskRun.getValue() + ); + + if (execution != null && currentTaskRun != null) { + parentValues = execution.findChildsValues(currentTaskRun, true); + } + + // detect kids + if (currentTask.getTask() instanceof FlowableTask<?> flowableTask) { + currentGraph = flowableTask.tasksTree(execution, currentTaskRun, parentValues); + } else { + currentGraph = new GraphTask(currentTask.getTask(), currentTaskRun, parentValues, RelationType.SEQUENTIAL); + } + + // add the node + graph.getGraph().addNode(currentGraph); + + // link to previous one + if(currentTask.getDependsOn() == null) { + graph.getGraph().addEdge( + previous, + currentGraph instanceof GraphCluster ? ((GraphCluster) currentGraph).getRoot() : currentGraph, + relation + ); + } else { + for (String dependsOn : currentTask.getDependsOn()) { + GraphTask previousNode = nodeTaskCreated.stream().filter(node -> node.getTask().getId().equals(dependsOn)).findFirst().orElse(null); + if(previousNode!= null && !previousNode.getTask().isFlowable()) { + graph.getGraph().addEdge( + previousNode, + currentGraph instanceof GraphCluster ? ((GraphCluster) currentGraph).getRoot() : currentGraph, + relation + ); + } else { + graph.getGraph() + .nodes() + .stream() + .filter(node -> node.getUid().equals("cluster_" + dependsOn)) + .findFirst() + .ifPresent(previousClusterNodeEnd -> graph.getGraph().addEdge( + ((GraphCluster) previousClusterNodeEnd).getEnd(), + currentGraph instanceof GraphCluster ? ((GraphCluster) currentGraph).getRoot() : currentGraph, + relation + )); + } + } + } + // link to last one if task isn't a dependency + if (!dependencies.contains(currentTask.getTask().getId())) { + if(currentTask.getTask() instanceof FlowableTask<?> flowableTask) { + graph.getGraph().addEdge( + ((GraphCluster) currentGraph).getEnd(), + graph.getEnd(), + new Relation() + ); + } else { + graph.getGraph().addEdge( + currentGraph, + graph.getEnd(), + new Relation() + ); + } + } + + if(currentGraph instanceof GraphTask) { + nodeTaskCreated.add((GraphTask) currentGraph); + } + nodeCreatedIds.add(currentTask.getTask().getId()); + } + } + } + } + + + private static void generatePath(Dag.DagTask task, Map<String, Dag.DagTask> taskMap, List<Dag.DagTask> currentPath, + List<List<Task>> allPaths, Set<String> visited) { + currentPath.add(task); + visited.add(task.getTask().getId()); + + if (taskMap.containsKey(task.getTask().getId())) { + List<String> dependsOnIds = task.getDependsOn(); + + if(dependsOnIds != null) { + for (String dependencyId : dependsOnIds) { + Dag.DagTask dependencyTask = taskMap.get(dependencyId); + if (!visited.contains(dependencyId)) { + generatePath(dependencyTask, taskMap, currentPath, allPaths, visited); + } + } + } + } + + if (task.getDependsOn() == null) { + Collections.reverse(currentPath); + allPaths.add(currentPath.stream().map(Dag.DagTask::getTask).collect(Collectors.toList())); + } + + currentPath.remove(currentPath.size() - 1); + visited.remove(task.getTask().getId()); + } + + private static boolean isAllLinkToEnd(RelationType relationType) { return relationType == RelationType.PARALLEL || relationType == RelationType.CHOICE; } diff --git a/core/src/main/java/io/kestra/core/tasks/flows/Dag.java b/core/src/main/java/io/kestra/core/tasks/flows/Dag.java new file mode 100644 index 0000000000..cd6fffd892 --- /dev/null +++ b/core/src/main/java/io/kestra/core/tasks/flows/Dag.java @@ -0,0 +1,181 @@ +package io.kestra.core.tasks.flows; + +import io.kestra.core.exceptions.IllegalVariableEvaluationException; +import io.kestra.core.models.annotations.PluginProperty; +import io.kestra.core.models.executions.Execution; +import io.kestra.core.models.executions.NextTaskRun; +import io.kestra.core.models.executions.TaskRun; +import io.kestra.core.models.hierarchies.GraphCluster; +import io.kestra.core.models.hierarchies.RelationType; +import io.kestra.core.models.tasks.*; +import io.kestra.core.runners.FlowableUtils; +import io.kestra.core.runners.RunContext; +import io.kestra.core.services.GraphService; +import io.kestra.core.validations.DagTaskValidation; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; +import lombok.experimental.SuperBuilder; + +import javax.validation.Valid; +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.NotEmpty; +import javax.validation.constraints.NotNull; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +@SuperBuilder +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@DagTaskValidation +@Schema( + title = "Create a directed acyclic graph (DAG) flow without bothering with the graph structure.", + description = "List your tasks and their dependencies, and Kestra will figure out the rest.\n" + + "Task can only depends on task from the DAG tasks.\n" + + "For technical reasons, low-code interaction with this Task is disabled for now." +) +public class Dag extends Task implements FlowableTask<VoidOutput> { + @NotNull + @NotBlank + @Builder.Default + @Schema( + title = "Number of concurrent parallel tasks", + description = "If the value is `0`, no limit exist and all the tasks will start at the same time" + ) + @PluginProperty + private final Integer concurrent = 0; + + @NotEmpty + private List<DagTask> tasks; + + @Valid + @PluginProperty + protected List<Task> errors; + + @Override + public GraphCluster tasksTree(Execution execution, TaskRun taskRun, List<String> parentValues) throws IllegalVariableEvaluationException { + GraphCluster subGraph = new GraphCluster(this, taskRun, parentValues, RelationType.DYNAMIC); + + this.controlTask(); + + GraphService.dag( + subGraph, + this.getTasks(), + this.errors, + taskRun, + execution + ); + + return subGraph; + } + + private void controlTask() throws IllegalVariableEvaluationException { + List<String> dagCheckNotExistTasks = this.dagCheckNotExistTask(this.tasks); + if (!dagCheckNotExistTasks.isEmpty()) { + throw new IllegalVariableEvaluationException("Some task doesn't exists on task '" + this.id + "': " + String.join(", ", dagCheckNotExistTasks)); + } + + ArrayList<String> cyclicDependenciesTasks = this.dagCheckCyclicDependencies(this.tasks); + if (!cyclicDependenciesTasks.isEmpty()) { + throw new IllegalVariableEvaluationException("Infinite loop detected on task '" + this.id + "': " + String.join(", ", cyclicDependenciesTasks)); + } + } + + @Override + public List<Task> allChildTasks() { + return Stream + .concat( + this.tasks != null ? this.tasks.stream().map(DagTask::getTask) : Stream.empty(), + this.errors != null ? this.errors.stream() : Stream.empty() + ) + .collect(Collectors.toList()); + } + + @Override + public List<ResolvedTask> childTasks(RunContext runContext, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + return FlowableUtils.resolveTasks(this.tasks.stream().map(DagTask::getTask).toList(), parentTaskRun); + } + + @Override + public List<NextTaskRun> resolveNexts(RunContext runContext, Execution execution, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + this.controlTask(); + + return FlowableUtils.resolveDagNexts( + execution, + this.childTasks(runContext, parentTaskRun), + FlowableUtils.resolveTasks(this.errors, parentTaskRun), + parentTaskRun, + this.concurrent, + this.tasks + ); + } + + public List<String> dagCheckNotExistTask(List<DagTask> taskDepends) { + List<String> dependenciesIds = taskDepends + .stream() + .map(DagTask::getDependsOn) + .filter(Objects::nonNull) + .flatMap(Collection::stream) + .toList(); + + List<String> tasksIds = taskDepends + .stream() + .map(taskDepend -> taskDepend.getTask().getId()) + .toList(); + + return dependenciesIds.stream() + .filter(dependencyId -> !tasksIds.contains(dependencyId)) + .collect(Collectors.toList()); + } + + public ArrayList<String> dagCheckCyclicDependencies(List<DagTask> taskDepends) { + ArrayList<String> cyclicDependency = new ArrayList<>(); + taskDepends.forEach(taskDepend -> { + if (taskDepend.getDependsOn() != null) { + List<String> nestedDependencies = this.nestedDependencies(taskDepend, taskDepends, new ArrayList<>()); + if (nestedDependencies.contains(taskDepend.getTask().getId())) { + cyclicDependency.add(taskDepend.getTask().getId()); + } + } + }); + + return cyclicDependency; + } + + private ArrayList<String> nestedDependencies(DagTask taskDepend, List<DagTask> tasks, List<String> visited) { + final ArrayList<String> localVisited = new ArrayList<>(visited); + if (taskDepend.getDependsOn() != null) { + taskDepend.getDependsOn() + .stream() + .filter(depend -> !localVisited.contains(depend)) + .forEach(depend -> { + localVisited.add(depend); + Optional<DagTask> task = tasks + .stream() + .filter(t -> t.getTask().getId().equals(depend)) + .findFirst(); + + if (task.isPresent()) { + localVisited.addAll(this.nestedDependencies(task.get(), tasks, localVisited)); + } + }); + } + return localVisited; + } + + @SuperBuilder + @ToString + @EqualsAndHashCode + @Getter + @NoArgsConstructor + public static class DagTask { + @NotNull + @PluginProperty + private Task task; + + @PluginProperty + private List<String> dependsOn; + } +} diff --git a/core/src/main/java/io/kestra/core/validations/DagTaskValidation.java b/core/src/main/java/io/kestra/core/validations/DagTaskValidation.java new file mode 100644 index 0000000000..6a391c6c4b --- /dev/null +++ b/core/src/main/java/io/kestra/core/validations/DagTaskValidation.java @@ -0,0 +1,11 @@ +package io.kestra.core.validations; + +import javax.validation.Constraint; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +@Retention(RetentionPolicy.RUNTIME) +@Constraint(validatedBy = { }) +public @interface DagTaskValidation { + String message() default "invalid Dag task"; +} diff --git a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java index 32faf52460..54218041a1 100644 --- a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java +++ b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java @@ -6,6 +6,7 @@ import io.kestra.core.models.flows.Input; import io.kestra.core.models.tasks.RunnableTask; import io.kestra.core.models.tasks.Task; +import io.kestra.core.tasks.flows.Dag; import io.kestra.core.models.tasks.WorkerGroup; import io.kestra.core.tasks.flows.Switch; import io.kestra.core.tasks.flows.WorkingDirectory; @@ -14,6 +15,7 @@ import jakarta.inject.Named; import jakarta.inject.Singleton; +import javax.validation.ConstraintViolation; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; @@ -116,6 +118,42 @@ ConstraintValidator<SwitchTaskValidation, Switch> switchTaskValidation() { }; } + @Singleton + ConstraintValidator<DagTaskValidation, Dag> dagTaskValidation() { + return (value, annotationMetadata, context) -> { + if (value == null) { + return true; + } + + if (value.getTasks() == null || value.getTasks().isEmpty()) { + context.messageTemplate("No task defined"); + + return false; + } + + List<Dag.DagTask> taskDepends = value.getTasks(); + + // Check for not existing taskId + List<String> invalidDependencyIds = value.dagCheckNotExistTask(taskDepends); + if (!invalidDependencyIds.isEmpty()) { + String errorMessage = "Not existing task id in dependency: " + String.join(", ", invalidDependencyIds); + context.messageTemplate(errorMessage); + + return false; + } + + // Check for cyclic dependencies + ArrayList<String> cyclicDependency = value.dagCheckCyclicDependencies(taskDepends); + if (!cyclicDependency.isEmpty()) { + context.messageTemplate("Cyclic dependency detected: " + String.join(", ", cyclicDependency)); + + return false; + } + + return true; + }; + } + @Singleton ConstraintValidator<WorkingDirectoryTaskValidation, WorkingDirectory> workingDirectoryTaskValidation() { return (value, annotationMetadata, context) -> { diff --git a/ui/src/components/flows/tasks/Task.js b/ui/src/components/flows/tasks/Task.js index 0253555156..81cf131868 100644 --- a/ui/src/components/flows/tasks/Task.js +++ b/ui/src/components/flows/tasks/Task.js @@ -39,7 +39,7 @@ export default { } if (Object.prototype.hasOwnProperty.call(property, "$ref")) { - if (property.$ref.includes("Task")) { + if (property.$ref.includes("tasks.Task")) { return "task" } diff --git a/ui/src/components/graph/nodes/Edge.vue b/ui/src/components/graph/nodes/Edge.vue index 8be14a7057..b52e704d74 100644 --- a/ui/src/components/graph/nodes/Edge.vue +++ b/ui/src/components/graph/nodes/Edge.vue @@ -209,7 +209,7 @@ <EdgeLabelRenderer style="z-index: 10"> <div - v-if="getEdgeLabel(props.data.edge.relation) !== ''" + v-if="getEdgeLabel(props.data.edge.relation) !== '' && !props.data.disabled" @mouseover="onMouseOver" @mouseleave="onMouseLeave" :style="{ diff --git a/ui/src/components/inputs/LowCodeEditor.vue b/ui/src/components/inputs/LowCodeEditor.vue index 7af6157efe..12df1a0122 100644 --- a/ui/src/components/inputs/LowCodeEditor.vue +++ b/ui/src/components/inputs/LowCodeEditor.vue @@ -449,6 +449,8 @@ }) } + let disabledLowCode = []; + for (const node of props.flowGraph.nodes) { const dagreNode = dagreGraph.node(node.uid); let nodeType = "task"; @@ -461,6 +463,15 @@ } else if (node.type.includes("GraphTrigger")) { nodeType = "trigger"; } + // Disable interaction for Dag task + // because our low code editor can not handle it for now + if (isTaskNode(node) && node.task.type === "io.kestra.core.tasks.flows.Dag") { + disabledLowCode.push(node.task.id); + YamlUtils.getChildrenTasks(props.source, node.task.id).forEach(child => { + disabledLowCode.push(child); + }) + } + elements.value.push({ id: node.uid, label: isTaskNode(node) ? node.task.id : "", @@ -473,7 +484,7 @@ sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, targetPosition: isHorizontal.value ? Position.Left : Position.Top, parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, - draggable: nodeType === "task" && !props.isReadOnly, + draggable: nodeType === "task" && !props.isReadOnly && isTaskNode(node) ? !disabledLowCode.includes(node.task.id) : false, data: { node: node, namespace: props.namespace, @@ -495,7 +506,8 @@ edge: edge, haveAdd: complexEdgeHaveAdd(edge), isFlowable: flowables().includes(edge.source) || flowables().includes(edge.target), - nextTaskId: getNextTaskId(edge.target) + nextTaskId: getNextTaskId(edge.target), + disabled: disabledLowCode.includes(edge.source) } }) } diff --git a/ui/src/utils/yamlUtils.js b/ui/src/utils/yamlUtils.js index 7c6b484cdc..cfc91337d7 100644 --- a/ui/src/utils/yamlUtils.js +++ b/ui/src/utils/yamlUtils.js @@ -403,6 +403,19 @@ export default class YamlUtils { return isChildrenOf; } + static getChildrenTasks(source, taskId) { + const yamlDoc = yaml.parseDocument(YamlUtils.extractTask(source, taskId)); + const children = []; + yaml.visit(yamlDoc, { + Map(_, map) { + if (map.get("id") !== taskId) { + children.push(map.get("id")); + } + } + }) + return children; + } + static replaceIdAndNamespace(source, id, namespace) { return source.replace(/^(id\s*:\s*(["']?))\S*/m, "$1"+id+"$2").replace(/^(namespace\s*:\s*(["']?))\S*/m, "$1"+namespace+"$2") } diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index af3e7aac0b..2118132719 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -472,7 +472,7 @@ public List<ValidateConstraintViolation> validateFlows( @Operation(tags = {"Flows"}, summary = "Validate a list of flows") public ValidateConstraintViolation validateTask( @Parameter(description = "A list of flows") @Body String task, - @Parameter(description = "Type of task") TaskValidationType section + @Parameter(description = "Type of task") @QueryValue TaskValidationType section ) { ValidateConstraintViolation.ValidateConstraintViolationBuilder<?, ?> validateConstraintViolationBuilder = ValidateConstraintViolation.builder();
diff --git a/core/src/test/java/io/kestra/core/tasks/flows/DagTest.java b/core/src/test/java/io/kestra/core/tasks/flows/DagTest.java new file mode 100644 index 0000000000..44f352395c --- /dev/null +++ b/core/src/test/java/io/kestra/core/tasks/flows/DagTest.java @@ -0,0 +1,75 @@ +package io.kestra.core.tasks.flows; + +import io.kestra.core.models.executions.Execution; +import io.kestra.core.models.flows.Flow; +import io.kestra.core.models.flows.State; +import io.kestra.core.models.validations.ModelValidator; +import io.kestra.core.runners.AbstractMemoryRunnerTest; +import io.kestra.core.serializers.YamlFlowParser; +import io.kestra.core.utils.TestsUtils; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import javax.validation.ConstraintViolationException; +import java.io.File; +import java.net.URL; +import java.util.Optional; +import java.util.concurrent.TimeoutException; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; + +public class DagTest extends AbstractMemoryRunnerTest { + @Inject + YamlFlowParser yamlFlowParser = new YamlFlowParser(); + + @Inject + ModelValidator modelValidator; + + @Test + void dag() throws TimeoutException { + Execution execution = runnerUtils.runOne( + "io.kestra.tests", + "dag", + null, + null + ); + + assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); + assertThat(execution.getTaskRunList().size(), is(7)); + assertThat(execution.getTaskRunList().get(1).getTaskId(), is("task1")); + assertThat(execution.getTaskRunList().get(6).getTaskId(), is("task5")); + } + + @Test + void dagCyclicDependencies() throws TimeoutException { + Flow flow = this.parse("flows/invalids/dag-cyclicdependency.yaml"); + Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); + + assertThat(validate.isPresent(), is(true)); + assertThat(validate.get().getConstraintViolations().size(), is(1)); + + assertThat(validate.get().getMessage(), containsString("tasks[0]: Cyclic dependency detected: task1, task2")); + } + + @Test + void dagNotExistTask() throws TimeoutException { + Flow flow = this.parse("flows/invalids/dag-notexist-task.yaml"); + Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); + + assertThat(validate.isPresent(), is(true)); + assertThat(validate.get().getConstraintViolations().size(), is(1)); + + assertThat(validate.get().getMessage(), containsString("tasks[0]: Not existing task id in dependency: taskX")); + } + + private Flow parse(String path) { + URL resource = TestsUtils.class.getClassLoader().getResource(path); + assert resource != null; + + File file = new File(resource.getFile()); + + return yamlFlowParser.parse(file, Flow.class); + } +} diff --git a/core/src/test/resources/flows/invalids/dag-cyclicdependency.yaml b/core/src/test/resources/flows/invalids/dag-cyclicdependency.yaml new file mode 100644 index 0000000000..54cc832d00 --- /dev/null +++ b/core/src/test/resources/flows/invalids/dag-cyclicdependency.yaml @@ -0,0 +1,38 @@ +id: "dag-cyclicdependency" +namespace: io.kestra.tests +tasks: + - id: dag + description: "my task" + type: io.kestra.core.tasks.flows.Dag + tasks: + - task: + id: task1 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task2 + - task: + id: task2 + type: io.kestra.core.tasks.log.Log + message: "2 !" + dependsOn: + - task1 + - task: + id: task3 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task2 + - task: + id: task4 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task2 + - task: + id: task5 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task4 + - task3 diff --git a/core/src/test/resources/flows/invalids/dag-notexist-task.yaml b/core/src/test/resources/flows/invalids/dag-notexist-task.yaml new file mode 100644 index 0000000000..b45f734c84 --- /dev/null +++ b/core/src/test/resources/flows/invalids/dag-notexist-task.yaml @@ -0,0 +1,36 @@ +id: "dag-notexist-task" +namespace: io.kestra.tests +tasks: + - id: dag + description: "my task" + type: io.kestra.core.tasks.flows.Dag + tasks: + - task: + id: task1 + type: io.kestra.core.tasks.log.Log + message: "1 !" + - task: + id: task2 + type: io.kestra.core.tasks.log.Log + message: "2 !" + dependsOn: + - taskX + - task: + id: task3 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task2 + - task: + id: task4 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task2 + - task: + id: task5 + type: io.kestra.core.tasks.log.Log + message: "1 !" + dependsOn: + - task4 + - task3 diff --git a/core/src/test/resources/flows/valids/dag.yaml b/core/src/test/resources/flows/valids/dag.yaml new file mode 100644 index 0000000000..6ddb6f732f --- /dev/null +++ b/core/src/test/resources/flows/valids/dag.yaml @@ -0,0 +1,51 @@ +id: "dag" +namespace: "io.kestra.tests" +tasks: + - id: dag + description: "my task" + type: io.kestra.core.tasks.flows.Dag + tasks: + - task: + id: task1 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + - task: + id: task2 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + - echo '::{"outputs":{"test":"value","int":2,"bool":true,"float":3.65}}::' + dependsOn: + - task1 + - task: + id: task3 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + dependsOn: + - task1 + - task: + id: task4 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + dependsOn: + - task2 + - task: + id: task5 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + dependsOn: + - task4 + - task3 + - task: + id: task6 + type: io.kestra.core.tasks.scripts.Bash + commands: + - sleep 1 + - echo {{ outputs.task2.vars.test }} + dependsOn: + - task2 + - task3
test
train
2023-06-14T23:09:28
"2023-05-12T21:28:01Z"
tchiotludo
train
kestra-io/kestra/1503_1504
kestra-io/kestra
kestra-io/kestra/1503
kestra-io/kestra/1504
[ "keyword_pr_to_issue" ]
6f04187a9ea4aede1488f2b42b26b04c0c7a80cf
5f22d614dfb04535ccc12293685bd7898f3210c1
[]
[]
"2023-06-12T18:45:54Z"
[ "bug" ]
MySQL repo - /daily displays an error message saying it misses a full text index when searching a flow
### Expected Behavior _No response_ ### Actual Behaviour Go to Flow list and start typing something. Once you have typed at least 3 characters (see #1502 for the current full text limitation), an error message talking about full-text index missing appears. ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.10.0-SNAPSHOT ### Example flow _No response_
[ "jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java" ]
[ "jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java" ]
[]
diff --git a/jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java b/jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java index cff8542a14..367450e30e 100644 --- a/jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java +++ b/jdbc-mysql/src/main/java/io/kestra/repository/mysql/MysqlExecutionRepositoryService.java @@ -16,7 +16,7 @@ public static Condition findCondition(AbstractJdbcRepository<Execution> jdbcRepo List<Condition> conditions = new ArrayList<>(); if (query != null) { - conditions.add(jdbcRepository.fullTextCondition(Arrays.asList("namespace", "id"), query)); + conditions.add(jdbcRepository.fullTextCondition(Arrays.asList("namespace", "flow_id", "id"), query)); } if (labels != null) {
null
train
train
2023-06-12T17:50:01
"2023-06-12T18:43:04Z"
brian-mulier-p
train
kestra-io/kestra/1505_1510
kestra-io/kestra
kestra-io/kestra/1505
kestra-io/kestra/1510
[ "keyword_pr_to_issue" ]
961e72e57845c1d6cdb249057b273aa4d78510ae
e91dbe1180af04b8b9c8531e5246d94a52511baf
[ "We configured Flyway to ignore missing migrations to be able to remove old migrations file (or buggy ones).\r\nSo we configure it like ` flyway.ignore-migration-patterns: \"*:missing\"` which replace the default of `flyway. ignore-migration-patterns: \"*:future\"`.\r\n\r\nSo \"future\" migrations now trigger an error.\r\n\r\nWe should be able to configure it with ` flyway.ignore-migration-patterns: \"*:missing,*:future\"` to ignore both missing and future migrations.", "We can also propose an option to repare the schema but un-supervised this can be dangerous." ]
[]
"2023-06-13T08:03:22Z"
[ "enhancement" ]
flyway migration for version rollback
If people downgrade kesta and there is some migration on the latest version, the user can start the server and will receive this breaking error: ``` 2023-06-12 10:31:03 Caused by: org.flywaydb.core.api.exception.FlywayValidateException: Validate failed: Migrations have failed validation 2023-06-12 10:31:03 Detected applied migration not resolved locally: 14. 2023-06-12 10:31:03 If you removed this migration intentionally, run repair to mark the migration as deleted. 2023-06-12 10:31:03 Need more flexibility with validation rules? Learn more: https://rd.gt/3AbJUZE ``` Define a proper path for downgrading: - the best transparently - if not possible, add some tooling to help - if not possible, document how to do it
[ "cli/src/main/resources/application.yml" ]
[ "cli/src/main/resources/application.yml" ]
[ "jdbc-postgres/src/test/resources/application.yml" ]
diff --git a/cli/src/main/resources/application.yml b/cli/src/main/resources/application.yml index 32731072ae..7d3ceb27aa 100644 --- a/cli/src/main/resources/application.yml +++ b/cli/src/main/resources/application.yml @@ -58,7 +58,7 @@ flyway: locations: - classpath:migrations/postgres # We must ignore missing migrations as a V6 wrong migration was created and replaced by the V11 - ignore-migration-patterns: "*:missing" + ignore-migration-patterns: "*:missing,*:future" mysql: enabled: true locations: @@ -68,7 +68,7 @@ flyway: locations: - classpath:migrations/h2 # We must ignore missing migrations as a V8 wrong migration was created and replaced by the V11 - ignore-migration-patterns: "*:missing" + ignore-migration-patterns: "*:missing,*:future" kestra: retries:
diff --git a/jdbc-postgres/src/test/resources/application.yml b/jdbc-postgres/src/test/resources/application.yml index 6f9f61c0af..db3f240d1d 100644 --- a/jdbc-postgres/src/test/resources/application.yml +++ b/jdbc-postgres/src/test/resources/application.yml @@ -13,7 +13,7 @@ flyway: locations: - classpath:migrations/postgres # We must ignore missing migrations as a V6 wrong migration was created and replaced by the V11 - ignore-migration-patterns: "*:missing" + ignore-migration-patterns: "*:missing,*:future" kestra: queue:
train
train
2023-06-12T22:56:41
"2023-06-12T18:46:00Z"
tchiotludo
train
kestra-io/kestra/1437_1514
kestra-io/kestra
kestra-io/kestra/1437
kestra-io/kestra/1514
[ "keyword_pr_to_issue" ]
6cdefb6e41f7824ccaf9399cf3ec470c786cd411
9d6fbbe14e6f5afb2641f086f604db90c6951319
[]
[]
"2023-06-13T10:36:06Z"
[ "bug", "frontend" ]
Invalid yaml don't have any error message
```yaml id: "valid" namespace: "com.kestra.lde" tasks: - id: "plan" type: "io.kestra.core.tasks.scripts.Bash" inputFiles: variables.tf: | test variables.tf: | test commands: - ls ```
[ "core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java" ]
[ "core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java" ]
[ "core/src/test/java/io/kestra/core/serializers/YamlFlowParserTest.java", "core/src/test/resources/flows/invalids/duplicate-key.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java b/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java index c0eea39dec..3f2e4e4523 100644 --- a/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java +++ b/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java @@ -1,5 +1,6 @@ package io.kestra.core.serializers; +import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.InjectableValues; @@ -13,19 +14,20 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; +import javax.validation.ConstraintViolationException; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collections; import java.util.Set; -import javax.validation.ConstraintViolationException; @Singleton public class YamlFlowParser { public static final String CONTEXT_FLOW_DIRECTORY = "flowDirectory"; private static final ObjectMapper mapper = JacksonMapper.ofYaml() + .enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) .disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE) .registerModule(new SimpleModule("HandleBarDeserializer") .addDeserializer(String.class, new HandleBarDeserializer())
diff --git a/core/src/test/java/io/kestra/core/serializers/YamlFlowParserTest.java b/core/src/test/java/io/kestra/core/serializers/YamlFlowParserTest.java index b1354e0916..2b5d36caa9 100644 --- a/core/src/test/java/io/kestra/core/serializers/YamlFlowParserTest.java +++ b/core/src/test/java/io/kestra/core/serializers/YamlFlowParserTest.java @@ -1,18 +1,20 @@ package io.kestra.core.serializers; import com.fasterxml.jackson.databind.ObjectMapper; +import io.kestra.core.models.flows.Flow; import io.kestra.core.models.flows.Input; import io.kestra.core.models.flows.input.StringInput; -import io.kestra.core.models.validations.ModelValidator; -import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import org.junit.jupiter.api.Test; -import io.kestra.core.models.flows.Flow; import io.kestra.core.models.tasks.Task; import io.kestra.core.models.tasks.retrys.Constant; import io.kestra.core.models.triggers.types.Schedule; +import io.kestra.core.models.validations.ModelValidator; import io.kestra.core.tasks.debugs.Return; import io.kestra.core.utils.TestsUtils; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; +import javax.validation.ConstraintViolationException; import java.io.File; import java.io.IOException; import java.net.URL; @@ -24,10 +26,6 @@ import java.util.ArrayList; import java.util.Optional; -import jakarta.inject.Inject; - -import javax.validation.ConstraintViolationException; - import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -241,6 +239,17 @@ void invalidParallel() { assertThat(new ArrayList<>(valid.get().getConstraintViolations()).stream().filter(r -> r.getMessage().contains("must not be empty")).count(), is(3L)); } + @Test + void duplicateKey() { + ConstraintViolationException exception = assertThrows( + ConstraintViolationException.class, + () -> this.parse("flows/invalids/duplicate-key.yaml") + ); + + assertThat(exception.getConstraintViolations().size(), is(1)); + assertThat(new ArrayList<>(exception.getConstraintViolations()).get(0).getMessage(), containsString("Duplicate field 'variables.tf'")); + } + private Flow parse(String path) { URL resource = TestsUtils.class.getClassLoader().getResource(path); assert resource != null; diff --git a/core/src/test/resources/flows/invalids/duplicate-key.yaml b/core/src/test/resources/flows/invalids/duplicate-key.yaml new file mode 100644 index 0000000000..9889bcac57 --- /dev/null +++ b/core/src/test/resources/flows/invalids/duplicate-key.yaml @@ -0,0 +1,13 @@ +id: duplicate-key +namespace: io.kestra.tests + +tasks: + - id: bad-task + type: "io.kestra.core.tasks.scripts.Bash" + inputFiles: + variables.tf: | + test + variables.tf: | + test + commands: + - ls \ No newline at end of file
test
train
2023-06-14T22:41:15
"2023-05-31T14:05:19Z"
tchiotludo
train
kestra-io/kestra/1303_1531
kestra-io/kestra
kestra-io/kestra/1303
kestra-io/kestra/1531
[ "keyword_pr_to_issue" ]
9d6fbbe14e6f5afb2641f086f604db90c6951319
b99162d0bd96aa986d0f0322ac892e9fbfac2e12
[]
[]
"2023-06-15T09:46:50Z"
[ "bug", "frontend" ]
Kill button on execution is the same than status button
people will not understand that the button will allow killing the execution
[ "ui/src/components/executions/Kill.vue" ]
[ "ui/src/components/executions/Kill.vue" ]
[]
diff --git a/ui/src/components/executions/Kill.vue b/ui/src/components/executions/Kill.vue index 789fcdac03..a825a7d772 100644 --- a/ui/src/components/executions/Kill.vue +++ b/ui/src/components/executions/Kill.vue @@ -1,21 +1,36 @@ <template> - <status status="KILLING" :title="$t('kill')" v-if="enabled" @click="kill" class="me-1" /> + <component + :is="component" + :icon="StopCircleOutline" + @click="kill" + v-if="enabled" + class="me-1" + > + {{ $t('kill') }} + </component> </template> -<script> + +<script setup> import StopCircleOutline from "vue-material-design-icons/StopCircleOutline.vue"; +</script> + +<script> + import {mapState} from "vuex"; import permission from "../../models/permission"; import action from "../../models/action"; import State from "../../utils/state"; - import Status from "../Status.vue"; export default { - components: {StopCircleOutline, Status}, props: { execution: { type: Object, required: true - } + }, + component: { + type: String, + default: "el-button" + }, }, methods: { kill() {
null
test
train
2023-06-14T23:09:28
"2023-05-15T16:59:40Z"
tchiotludo
train
kestra-io/kestra/1382_1536
kestra-io/kestra
kestra-io/kestra/1382
kestra-io/kestra/1536
[ "keyword_pr_to_issue" ]
57569bfcff69b410992e558cd328cd994ed5a39d
c39712c5dfe01d2d173de83a88ff8e12356084ed
[]
[]
"2023-06-15T13:30:07Z"
[ "bug" ]
Plugin Documentation: Definitions section is displayed even when no definitions
### Expected Behavior When no definitions for a task, the definitions section must not be visible ### Actual Behaviour An empty definitions section is displayed, for ex: https://kestra.io/plugins/core/tasks/flows/io.kestra.core.tasks.flows.worker#definitions ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0-SNAPSHOT - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java" ]
[ "core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java" ]
[ "core/src/test/java/io/kestra/core/docs/ClassPluginDocumentationTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java b/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java index 94b9091208..6fc592c42b 100644 --- a/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java +++ b/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java @@ -37,6 +37,9 @@ protected AbstractClassDocumentation(JsonSchemaGenerator jsonSchemaGenerator, Cl this.defs = this.getDefs() .entrySet() .stream() + // Remove the Task entry as it only contains a reference that is filtered in the doc template, + // which prevent the Definitions section to be empty if no other def exist. + .filter(entry -> !entry.getKey().equals("io.kestra.core.models.tasks.Task")) .map(entry -> { Map<String, Object> value = (Map<String, Object>) entry.getValue(); value.put("properties", flatten(properties(value), required(value)));
diff --git a/core/src/test/java/io/kestra/core/docs/ClassPluginDocumentationTest.java b/core/src/test/java/io/kestra/core/docs/ClassPluginDocumentationTest.java index 03d5a6daeb..dec16b3476 100644 --- a/core/src/test/java/io/kestra/core/docs/ClassPluginDocumentationTest.java +++ b/core/src/test/java/io/kestra/core/docs/ClassPluginDocumentationTest.java @@ -46,6 +46,9 @@ void tasks() throws URISyntaxException { assertThat(((Map<String, String>) doc.getInputs().get("format")).get("pattern"), is(".*")); assertThat(((Map<String, String>) doc.getInputs().get("format")).get("description"), containsString("of this input")); + // definitions + assertThat(doc.getDefs().size(), is(5)); + // enum Map<String, Object> enumProperties = (Map<String, Object>) ((Map<String, Object>) ((Map<String, Object>) doc.getDefs().get("io.kestra.plugin.templates.ExampleTask-PropertyChildInput")).get("properties")).get("childEnum"); assertThat(((List<String>) enumProperties.get("enum")).size(), is(2));
train
train
2023-06-16T11:35:36
"2023-05-23T08:00:38Z"
loicmathieu
train
kestra-io/kestra/1486_1542
kestra-io/kestra
kestra-io/kestra/1486
kestra-io/kestra/1542
[ "keyword_pr_to_issue" ]
c39712c5dfe01d2d173de83a88ff8e12356084ed
3bcaab879c0f900e38dba5f789a545ce7abf40d7
[]
[]
"2023-06-16T11:09:25Z"
[ "bug" ]
Dashboard on flow without executions should not be displayed
normally we have this page: ![image](https://github.com/kestra-io/kestra/assets/2064609/d5bf29b0-fc20-48f7-b6e0-1ffc37980eba) it's not working anymore
[ "ui/src/components/Tabs.vue", "ui/src/components/home/Home.vue" ]
[ "ui/src/components/Tabs.vue", "ui/src/components/home/Home.vue" ]
[]
diff --git a/ui/src/components/Tabs.vue b/ui/src/components/Tabs.vue index 294ebe7c7d..7ea025851a 100644 --- a/ui/src/components/Tabs.vue +++ b/ui/src/components/Tabs.vue @@ -51,13 +51,13 @@ $route() { this.setActiveName(); }, - activeName() { + activeTab() { this.$nextTick(() => { this.setActiveName(); }); } }, - created() { + mounted() { this.setActiveName(); }, methods: { diff --git a/ui/src/components/home/Home.vue b/ui/src/components/home/Home.vue index 0de27a1fb2..93e44881ef 100644 --- a/ui/src/components/home/Home.vue +++ b/ui/src/components/home/Home.vue @@ -208,7 +208,17 @@ return _merge(base, queryFilter) }, haveExecutions() { - this.$store.dispatch("execution/findExecutions", {limit: 1}) + let params = { + size: 1 + }; + if (this.selectedNamespace) { + params["namespace"] = this.selectedNamespace; + } + + if (this.flowId) { + params["flowId"] = this.flowId; + } + this.$store.dispatch("execution/findExecutions", params ) .then(executions => { this.executionCounts = executions.total; }); @@ -301,13 +311,13 @@ if (this.executionCounts > 0) { return true } - // not flow home if (!this.flowId) { if (!this.$route.query.namespace && this.executionCounts === 0) { return false; } - } else if (this.executionCounts === 0) { + } + if (this.executionCounts === 0) { return false; }
null
train
train
2023-06-19T13:23:10
"2023-06-09T21:12:48Z"
tchiotludo
train
kestra-io/kestra/1511_1548
kestra-io/kestra
kestra-io/kestra/1511
kestra-io/kestra/1548
[ "keyword_pr_to_issue" ]
ae94fbd5519d94b69556bc67ab609351817db5e0
1834d8b5de482047fc49cf3774291e3df95b0cd1
[ "- [x] separate tags by spaces rather than dots\r\n\r\natm this looks like a hierarchy, but all tags seem equally important, right?\r\n\r\n![image](https://github.com/kestra-io/kestra/assets/86264395/c8420b87-8af7-4b93-933d-ed278909746f)\r\n", "one easy item checked :) https://github.com/kestra-io/kestra/pull/1518 ", " Regarding `Move \"About this blueprint\" text at the top of blueprint page`\r\n\r\nAfter using blueprints, it actually seems more convenient to have the source code first and a description below", "WDYT @Ben8t ? This would lead to lesser visibility of topology but I'm okay with that", "to add: the description is usually just a summary of what's already visible in the topology and source code (i.e. less important), so the way it's currently presented seems intuitive\r\n\r\nAtm you can see the blueprint's source code directly in the editor. However, if the description moves to the top, the source code, which is the most important part, won't be visible \r\n\r\n![image](https://github.com/kestra-io/kestra/assets/86264395/de4c69b0-988f-418e-aa02-6f99d6f268cb)\r\n", "Don't have a opinion, it was asked by Manu. But kinda agree with both of you, so let it keep things as they are" ]
[ "You can move on the `element-plus-overload.scss` since it a global layout for breadcrumb ", "I made the change however I had to add !important on every property since element plus adds a file called breadcrumb.scss which takes precedence over everything since it is no more scoped to a component so selectors are less precise :'(", "Another workaround is to add '#app .el-breadcrumb' instead of '.el-breadcrumb' and it will take precedence but I don't know if that's better...\r\nbreadcrumb.scss (which is an element plus stylesheet which takes the precedence) comes from vendor.scss which imports element plus index which imports breadcrumb.scss. Not sure there is a way to prevent this import so idk" ]
"2023-06-19T12:13:03Z"
[ "bug", "frontend" ]
Blueprints adjustements
### Issue description - [x] Markdown not rendered in blueprint description - [x] Use purple for "Use" button (dark theme) - [x] keep the breadcrumb on main blueprint page (from left side section) - [x] move the Flow Gallery section above the Documentation section in the left bar menu ~- [ ] Move "About this blueprint" text at the top of blueprint page~ - [x] Rename Flow Gallery by Blueprints
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue", "ui/src/components/layout/TopNavBar.vue", "ui/src/styles/layout/element-plus-overload.scss" ]
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue", "ui/src/components/layout/TopNavBar.vue", "ui/src/styles/layout/element-plus-overload.scss" ]
[]
diff --git a/ui/src/components/flows/blueprints/BlueprintDetail.vue b/ui/src/components/flows/blueprints/BlueprintDetail.vue index 277b3da68b..0bbe7197a3 100644 --- a/ui/src/components/flows/blueprints/BlueprintDetail.vue +++ b/ui/src/components/flows/blueprints/BlueprintDetail.vue @@ -1,22 +1,36 @@ <template> <div v-loading="!blueprint"> <template v-if="blueprint"> - <div class="header"> - <button class="back-button"> - <el-icon size="medium" @click="goBack"> - <KeyboardBackspace /> - </el-icon> - </button> - <h4 class="blueprint-title"> - {{ blueprint.title }} - </h4> - <div class="ms-auto"> - <router-link :to="{name: 'flows/create'}" @click="asAutoRestoreDraft"> - <el-button size="large" v-if="!embed"> - {{ $t('use') }} - </el-button> - </router-link> + <div class="header-wrapper"> + <div class="header d-flex"> + <button class="back-button align-self-center"> + <el-icon size="medium" @click="goBack"> + <KeyboardBackspace /> + </el-icon> + </button> + <h4 class="blueprint-title align-self-center"> + {{ blueprint.title }} + </h4> + <div class="ms-auto align-self-center"> + <router-link :to="{name: 'flows/create'}" @click="asAutoRestoreDraft"> + <el-button size="large" v-if="!embed"> + {{ $t('use') }} + </el-button> + </router-link> + </div> </div> + <el-breadcrumb v-if="!embed"> + <el-breadcrumb-item> + <router-link :to="{name: 'home'}"> + <home-outline /> {{ $t('home') }} + </router-link> + </el-breadcrumb-item> + <el-breadcrumb-item> + <router-link :to="{name: 'blueprints', params: $route.params}"> + {{ $t('blueprints.title') }} + </router-link> + </el-breadcrumb-item> + </el-breadcrumb> </div> <div class="blueprint-container"> @@ -60,6 +74,7 @@ import Editor from "../../inputs/Editor.vue"; import LowCodeEditor from "../../inputs/LowCodeEditor.vue"; import TaskIcon from "../../plugins/TaskIcon.vue"; + import HomeOutline from "vue-material-design-icons/HomeOutline.vue"; </script> <script> import YamlUtils from "../../../utils/yamlUtils"; @@ -129,25 +144,27 @@ <style scoped lang="scss"> @import "../../../styles/variable"; - .header { - display: flex; + .header-wrapper { + margin-bottom: $spacer; - > * { - margin-top: auto; - margin-bottom: auto; - } + .header { + margin-bottom: calc(var(--spacer) * 0.5); - .back-button { - cursor: pointer; - padding: $spacer; - height: calc(1em + (var(--spacer) * 2)); - width: calc(1em + (var(--spacer) * 2)); - border: none; - background: none; - } + > * { + margin: 0; + } - .blueprint-title { - font-weight: bold; + .back-button { + cursor: pointer; + height: calc(1em + (var(--spacer) * 2)); + width: calc(1em + (var(--spacer) * 2)); + border: none; + background: none; + } + + .blueprint-title { + font-weight: bold; + } } } diff --git a/ui/src/components/layout/TopNavBar.vue b/ui/src/components/layout/TopNavBar.vue index e6f97ee918..69daae4c79 100644 --- a/ui/src/components/layout/TopNavBar.vue +++ b/ui/src/components/layout/TopNavBar.vue @@ -74,42 +74,6 @@ color: var(--bs-white); } } - - :deep(.el-breadcrumb) { - display: flex; - - a { - font-weight: normal; - color: var(--bs-gray-500); - white-space: nowrap; - } - - .el-breadcrumb__separator { - color: var(--bs-gray-500); - } - - .el-breadcrumb__item { - display: flex; - flex-wrap: nowrap; - float: none; - } - - .material-design-icon { - height: 0.75rem; - width: 0.75rem; - margin-right: calc(var(--spacer) / 2); - } - - a { - cursor: pointer !important; - } - - html.dark & { - a, .el-breadcrumb__separator { - color: var(--bs-gray-700); - } - } - } } .side { diff --git a/ui/src/styles/layout/element-plus-overload.scss b/ui/src/styles/layout/element-plus-overload.scss index 7923971196..24d19685ff 100644 --- a/ui/src/styles/layout/element-plus-overload.scss +++ b/ui/src/styles/layout/element-plus-overload.scss @@ -640,4 +640,37 @@ form.ks-horizontal { .el-date-table th { border-bottom-color: var(--bs-border-color); } +} + +.el-breadcrumb { + display: flex; + + a { + font-weight: normal; + color: var(--bs-gray-500) !important; + white-space: nowrap; + cursor: pointer !important; + } + + .el-breadcrumb__separator { + color: var(--bs-gray-500); + } + + .el-breadcrumb__item { + display: flex; + flex-wrap: nowrap; + float: none; + } + + .material-design-icon { + height: 0.75rem; + width: 0.75rem; + margin-right: calc(var(--spacer) / 2); + } + + html.dark & { + a, .el-breadcrumb__separator { + color: var(--bs-gray-700) !important; + } + } } \ No newline at end of file
null
train
train
2023-06-20T14:02:53
"2023-06-13T08:13:02Z"
Ben8t
train
kestra-io/kestra/1461_1551
kestra-io/kestra
kestra-io/kestra/1461
kestra-io/kestra/1551
[ "keyword_pr_to_issue" ]
c58d11a20c2b92fa489b77ecb7b858869d5b549f
18531555353d516abfaa84ffad8c88ab9e85f146
[ "The key is still generated, just not included in the flow, as we no longer edit user flow. (And note that actually, we can't edit it from the backend)\n\nBut you can still find it in the flow list in the trigger column. \n\n![Image](https://github.com/kestra-io/kestra/assets/37600690/2d4fa038-b0ce-4f73-86c8-434a80796adf)\n\nShouldn't we add those triggers' information to the flow overview? \n\n@tchiotludo @anna-geller @Ben8t wdyt ?\n", "trigger column that are on the flows listo only ?", "The trigger details in this image are coming from the Execution page -- the key must be assigned to the flow's webhook trigger _before_ the flow can get triggered via a webhook. So the issue is still open unless we remove this info about generated hash from the docs and recommend creating custom keys?", "The trigger details I sent arn't coming from the Execution page :\n> you can still find it in the flow list in the trigger column\n\nThe key is assigned right after the flow is saved with the webhook, just not displayed. It's not an issue of not being generated, it's an issue of not being displayed correctly.", "you're, right @Skraye! \r\n\r\n![image](https://github.com/kestra-io/kestra/assets/86264395/ba368a2b-40d4-42f6-966d-93cf1cb890cc)\r\n\r\nshould we then only clarify in the docs? ", "I think we should add that information in the flow details page", "That makes sense, thanks. I assigned you since you know it best " ]
[ "```suggestion\r\n <home-trigger v-if=\"flow?.triggers\" :triggers=\"flow.triggers\" class=\"mb-4\" />\r\n```", "```suggestion\r\n <el-table :data=\"triggers\" stripe table-layout=\"auto\">\r\n <el-table-column v-for=\"prop in columns\" :key=\"prop\" :prop=\"prop\" :label=\"getLabel(prop)\" />\r\n <el-table-column :label=\"$t('description')\">\r\n <template #default=\"scope\">\r\n <Markdown :source=\"scope.row.description\" />\r\n </template>\r\n </el-table-column>\r\n </el-table>\r\n```" ]
"2023-06-19T14:10:13Z"
[ "bug" ]
Add the autogenerated webhook key to the Flow details page
### Expected Behavior According to the documentation, a webhook secret key would be generated automatically based on a generated hash. Mimimum example: ```yaml id: ci-cd namespace: prod tasks: - id: log type: io.kestra.core.tasks.log.Log message: test triggers: - id: github-webhook type: io.kestra.core.models.triggers.types.Webhook key: "thisIsASecretKey123" # using "{{secret('WEBHOOK_KEY')}}" doesn't work atm ``` ### Actual Behaviour Currently, this doesn't happen. Passing the key from a secret also currently doesn't work. ![image](https://github.com/kestra-io/kestra/assets/86264395/8a621b0b-90df-45e2-815d-78533b0397d1) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.3 develop-full image, EE also ### Example flow _No response_
[ "ui/src/components/flows/FlowRoot.vue" ]
[ "ui/src/components/flows/FlowRoot.vue", "ui/src/components/flows/FlowTriggers.vue" ]
[]
diff --git a/ui/src/components/flows/FlowRoot.vue b/ui/src/components/flows/FlowRoot.vue index 2a9c2f8860..1a9f0604d2 100644 --- a/ui/src/components/flows/FlowRoot.vue +++ b/ui/src/components/flows/FlowRoot.vue @@ -40,6 +40,7 @@ import FlowDependencies from "./FlowDependencies.vue"; import FlowMetrics from "./FlowMetrics.vue"; import FlowEditor from "./FlowEditor.vue"; + import FlowTriggers from "./FlowTriggers.vue"; export default { mixins: [RouteContext], @@ -133,6 +134,14 @@ }); } + if (this.user && this.flow && this.user.isAllowed(permission.FLOW, action.READ, this.flow.namespace)) { + tabs.push({ + name: "triggers", + component: FlowTriggers, + title: this.$t("triggers") + }); + } + if (this.user && this.flow && this.user.isAllowed(permission.EXECUTION, action.READ, this.flow.namespace)) { tabs.push({ name: "logs", diff --git a/ui/src/components/flows/FlowTriggers.vue b/ui/src/components/flows/FlowTriggers.vue new file mode 100644 index 0000000000..f706d3b786 --- /dev/null +++ b/ui/src/components/flows/FlowTriggers.vue @@ -0,0 +1,95 @@ +<template> + <el-table + v-loading="flowData === undefined" + :data="flowData ? flowData.triggers : []" + stripe + table-layout="auto" + @row-dblclick="triggerId = $event.id; isOpen = true" + > + <el-table-column prop="id" :label="$t('id')"> + <template #default="scope"> + <code> + {{ scope.row.id }} + </code> + </template> + </el-table-column> + <el-table-column prop="type" :label="$t('type')" /> + <el-table-column :label="$t('description')"> + <template #default="scope"> + <Markdown :source="scope.row.description" /> + </template> + </el-table-column> + + <el-table-column column-key="action" class-name="row-action"> + <template #default="scope"> + <a href="#" @click="triggerId = scope.row.id; isOpen = true"> + <kicon :tooltip="$t('details')" placement="left"> + <eye /> + </kicon> + </a> + </template> + </el-table-column> + </el-table> + + <el-drawer + v-if="isOpen" + v-model="isOpen" + destroy-on-close + lock-scroll + size="" + :append-to-body="true" + > + <template #header> + <code>{{ triggerId }}</code> + </template> + <el-table stripe table-layout="auto" :data="triggerData"> + <el-table-column prop="key" :label="$t('key')" /> + <el-table-column prop="value" :label="$t('value')"> + <template #default="scope"> + <vars v-if="scope.row.value instanceof Array || scope.row.value instanceof Object " :data="scope.row.value" /> + </template> + </el-table-column> + </el-table> + </el-drawer> + +</template> + +<script setup> + import Eye from "vue-material-design-icons/Eye.vue"; + import Vars from "../executions/Vars.vue"; +</script> + +<script> + import Markdown from "../layout/Markdown.vue"; + import {mapGetters} from "vuex"; + import Kicon from "../Kicon.vue" + + export default { + components: {Markdown, Kicon}, + data() { + return { + triggerId: undefined, + flowData: undefined, + isOpen: false + } + }, + created() { + this.$http + .get(`/api/v1/flows/${this.flow.namespace}/${this.flow.id}?source=false`) + .then(value => this.flowData = value.data); + }, + computed: { + ...mapGetters("flow", ["flow"]), + triggerData() { + return Object + .entries(this.flowData.triggers.filter(trigger => trigger.id === this.triggerId)[0]) + .map(([key, value]) => { + return { + key, + value + }; + }); + }, + } + }; +</script> \ No newline at end of file
null
train
train
2023-07-04T13:31:46
"2023-06-06T10:13:53Z"
anna-geller
train
kestra-io/kestra/1204_1553
kestra-io/kestra
kestra-io/kestra/1204
kestra-io/kestra/1553
[ "keyword_pr_to_issue" ]
896777a05d5d37cade175117a1ada3294cdc1b30
767e1fb4209874623e6d8b951f0b9bc909f21dbf
[]
[ "Rename canDisable var to canUpdate", "```suggestion\r\n String regex = \"^disabled\\\\s*:\\\\s*\" + String.valueOf(!disabled) + \"\\\\s*\";\r\n```", "Idk if that's really an issue but maybe we should remove the disabled property entirely instead of creating or updating it when we enable back the flow ?", "When we enable a flow, we filter by flows that are disabled so they already have the property (or the flow has been edited directly in the DB)" ]
"2023-06-19T15:07:13Z"
[ "enhancement" ]
"Enable" Options for enabling disabled flow
### Feature description When we select multiple flow, there are "Disable" option but do not have "Enable" option. To enable the disabled flow, we need to enter each flow and remove the disabled line. Thank you
[ "core/src/main/java/io/kestra/core/services/FlowService.java", "ui/src/components/flows/Flows.vue", "ui/src/stores/flow.js", "ui/src/translations.json", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "core/src/main/java/io/kestra/core/services/FlowService.java", "ui/src/components/flows/Flows.vue", "ui/src/stores/flow.js", "ui/src/translations.json", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/services/FlowService.java b/core/src/main/java/io/kestra/core/services/FlowService.java index 56210c2c11..f0c080f9af 100644 --- a/core/src/main/java/io/kestra/core/services/FlowService.java +++ b/core/src/main/java/io/kestra/core/services/FlowService.java @@ -222,13 +222,15 @@ public static String cleanupSource(String source) { return source.replaceFirst("(?m)^revision: \\d+\n?",""); } - public static String injectDisabledTrue(String source) { - Pattern p = Pattern.compile("^disabled\\s*:\\s*false\\s*", Pattern.MULTILINE); + public static String injectDisabled(String source, Boolean disabled) { + String regex = disabled ? "^disabled\\s*:\\s*false\\s*" : "^disabled\\s*:\\s*true\\s*"; + + Pattern p = Pattern.compile(regex, Pattern.MULTILINE); if (p.matcher(source).find()) { - return p.matcher(source).replaceAll("disabled: true\n"); + return p.matcher(source).replaceAll(String.format("disabled: %s\n", disabled)); } - return source + "\ndisabled: true"; + return source + String.format("\ndisabled: %s", disabled); } public static String generateSource(Flow flow, @Nullable String source) { diff --git a/ui/src/components/flows/Flows.vue b/ui/src/components/flows/Flows.vue index 2d0f055d98..4a7f623ed3 100644 --- a/ui/src/components/flows/Flows.vue +++ b/ui/src/components/flows/Flows.vue @@ -113,7 +113,10 @@ <el-button v-if="canDelete" @click="deleteFlows" size="large" :icon="TrashCan"> {{ $t('delete') }} </el-button> - <el-button v-if="canDisable" @click="disableFlows" size="large" :icon="FileDocumentRemoveOutline"> + <el-button v-if="canUpdate" @click="enableFlows" size="large" :icon="FileDocumentCheckOutline"> + {{ $t('enable') }} + </el-button> + <el-button v-if="canUpdate" @click="disableFlows" size="large" :icon="FileDocumentRemoveOutline"> {{ $t('disable') }} </el-button> </bottom-line-counter> @@ -162,6 +165,7 @@ import Download from "vue-material-design-icons/Download.vue"; import TrashCan from "vue-material-design-icons/TrashCan.vue"; import FileDocumentRemoveOutline from "vue-material-design-icons/FileDocumentRemoveOutline.vue"; + import FileDocumentCheckOutline from "vue-material-design-icons/FileDocumentCheckOutline.vue"; </script> <script> @@ -232,7 +236,7 @@ .toDate(); }, canCheck() { - return this.canRead || this.canDelete || this.canDisable; + return this.canRead || this.canDelete || this.canUpdate; }, canRead() { return this.user && this.user.isAllowed(permission.FLOW, action.READ, this.$route.query.namespace); @@ -240,7 +244,7 @@ canDelete() { return this.user && this.user.isAllowed(permission.FLOW, action.DELETE, this.$route.query.namespace); }, - canDisable() { + canUpdate() { return this.user && this.user.isAllowed(permission.FLOW, action.UPDATE, this.$route.query.namespace); }, }, @@ -311,6 +315,32 @@ () => {} ) }, + enableFlows(){ + this.$toast().confirm( + this.$t("flow enable", {"flowCount": this.queryBulkAction ? this.total : this.flowsSelection.length}), + () => { + if (this.queryBulkAction) { + return this.$store + .dispatch("flow/enableFlowByQuery", this.loadQuery({ + namespace: this.$route.query.namespace ? [this.$route.query.namespace] : undefined, + q: this.$route.query.q ? [this.$route.query.q] : undefined, + }, false)) + .then(r => { + this.$toast().success(this.$t("flows enabled", {count: r.data.count})); + this.loadData(() => {}) + }) + } else { + return this.$store + .dispatch("flow/enableFlowByIds", {ids: this.flowsSelection}) + .then(r => { + this.$toast().success(this.$t("flows enabled", {count: r.data.count})); + this.loadData(() => {}) + }) + } + }, + () => {} + ) + }, deleteFlows(){ this.$toast().confirm( this.$t("flow delete", {"flowCount": this.queryBulkAction ? this.total : this.flowsSelection.length}), diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 504db76399..16a73ba749 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -217,6 +217,12 @@ export default { disableFlowByQuery(_, options) { return this.$http.post("/api/v1/flows/disable/by-query", options, {params: options}) }, + enableFlowByIds(_, options) { + return this.$http.post("/api/v1/flows/enable/by-ids", options.ids) + }, + enableFlowByQuery(_, options) { + return this.$http.post("/api/v1/flows/enable/by-query", options, {params: options}) + }, deleteFlowByIds(_, options) { return this.$http.delete("/api/v1/flows/delete/by-ids", {data: options.ids}) }, diff --git a/ui/src/translations.json b/ui/src/translations.json index a53412893e..b85fe3fc27 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -300,12 +300,15 @@ "export all flows": "Export all flows", "import": "Import", "disable": "Disable", + "enable": "Enable", "template delete": "Are you sure you want to delete <code>{templateCount}</code> template(s)?", "flow delete": "Are you sure you want to delete <code>{flowCount}</code> flow(s)?", "templates deleted": "<code>{count}</code> Template(s) deleted", "flows deleted": "<code>{count}</code> Flow(s) deleted", "flow disable": "Are you sure you want to disable <code>{flowCount}</code> flow(s)?", + "flow enable": "Are you sure you want to enable <code>{flowCount}</code> flow(s)?", "flows disabled": "<code>{count}</code> Flow(s) disabled", + "flows enabled": "<code>{count}</code> Flow(s) enabled", "dependencies": "Dependencies", "see dependencies": "See dependencies", "dependencies missing acls": "No permissions on this flow", @@ -748,12 +751,15 @@ "export all flows": "Exporter tous les flows", "import": "Importer", "disable": "Désactiver", + "enable": "Activer", "template delete": "Êtes vous sûr de vouloir supprimer <code>{templateCount}</code> template(s)?", "flow delete": "Êtes vous sûr de vouloir supprimer <code>{flowCount}</code> flow(s)?", "templates deleted": "<code>{count}</code> Template(s) supprimé(s)", "flows deleted": "<code>{count}</code> Flow(s) supprimé(s)", "flow disable": "Êtes vous sûr de vouloir désactiver <code>{flowCount}</code> flow(s)?", + "flow enable": "Êtes vous sûr de vouloir activer <code>{flowCount}</code> flow(s)?", "flows disabled": "<code>{count}</code> Flow(s) désactivé(s)", + "flows enable": "<code>{count}</code> Flow(s) activé(s)", "dependencies": "Dépendances", "see dependencies": "Voir les dépendances", "dependencies missing acls": "Aucune permission sur ce flow", diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index 2118132719..c9221ed3d7 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -593,26 +593,8 @@ public HttpResponse<BulkResponse> disableByQuery( @Parameter(description = "A namespace filter prefix") @Nullable @QueryValue String namespace, @Parameter(description = "A labels filter") @Nullable @QueryValue List<String> labels ) { - List<FlowWithSource> list = flowRepository - .findWithSource(query, namespace, RequestUtils.toMap(labels)) - .stream() - .filter(flowWithSource -> !flowWithSource.isDisabled()) - .peek(flow -> { - FlowWithSource flowUpdated = flow.toBuilder() - .disabled(true) - .source(FlowService.injectDisabledTrue(flow.getSource())) - .build(); - - flowRepository.update( - flowUpdated, - flow, - flowUpdated.getSource(), - taskDefaultService.injectDefaults(flowUpdated) - ); - }) - .collect(Collectors.toList()); - return HttpResponse.ok(BulkResponse.builder().count(list.size()).build()); + return HttpResponse.ok(BulkResponse.builder().count(setFlowsDisableByQuery(query, namespace, labels, true).size()).build()); } @ExecuteOn(TaskExecutors.IO) @@ -624,28 +606,39 @@ public HttpResponse<BulkResponse> disableByQuery( public HttpResponse<BulkResponse> disableByIds( @Parameter(description = "A list of tuple flow ID and namespace as flow identifiers") @Body List<IdWithNamespace> ids ) { - List<FlowWithSource> list = ids - .stream() - .map(id -> flowRepository.findByIdWithSource(id.getNamespace(), id.getId()).orElseThrow()) - .filter(flowWithSource -> !flowWithSource.isDisabled()) - .peek(flow -> { - FlowWithSource flowUpdated = flow.toBuilder() - .disabled(true) - .source(FlowService.injectDisabledTrue(flow.getSource())) - .build(); - flowRepository.update( - flowUpdated, - flow, - flowUpdated.getSource(), - taskDefaultService.injectDefaults(flowUpdated) - ); - }) - .collect(Collectors.toList()); + return HttpResponse.ok(BulkResponse.builder().count(setFlowsDisableByIds(ids, true).size()).build()); + } - return HttpResponse.ok(BulkResponse.builder().count(list.size()).build()); + @ExecuteOn(TaskExecutors.IO) + @Post(uri = "/enable/by-query") + @Operation( + tags = {"Flows"}, + summary = "Enable flows returned by the query parameters." + ) + public HttpResponse<BulkResponse> enableByQuery( + @Parameter(description = "A string filter") @Nullable @QueryValue(value = "q") String query, + @Parameter(description = "A namespace filter prefix") @Nullable @QueryValue String namespace, + @Parameter(description = "A labels filter") @Nullable @QueryValue List<String> labels + ) { + + return HttpResponse.ok(BulkResponse.builder().count(setFlowsDisableByQuery(query, namespace, labels, false).size()).build()); + } + + @ExecuteOn(TaskExecutors.IO) + @Post(uri = "/enable/by-ids") + @Operation( + tags = {"Flows"}, + summary = "Enable flows by their IDs." + ) + public HttpResponse<BulkResponse> enableByIds( + @Parameter(description = "A list of tuple flow ID and namespace as flow identifiers") @Body List<IdWithNamespace> ids + ) { + + return HttpResponse.ok(BulkResponse.builder().count(setFlowsDisableByIds(ids, false).size()).build()); } + @ExecuteOn(TaskExecutors.IO) @Post(uri = "/import", consumes = MediaType.MULTIPART_FORM_DATA) @Operation( @@ -692,4 +685,46 @@ protected void importFlow(String source, Flow parsed) { () -> flowRepository.create(parsed, source, taskDefaultService.injectDefaults(parsed)) ); } + + protected List<FlowWithSource> setFlowsDisableByIds(List<IdWithNamespace> ids, boolean disable) { + return ids + .stream() + .map(id -> flowRepository.findByIdWithSource(id.getNamespace(), id.getId()).orElseThrow()) + .filter(flowWithSource -> disable != flowWithSource.isDisabled()) + .peek(flow -> { + FlowWithSource flowUpdated = flow.toBuilder() + .disabled(disable) + .source(FlowService.injectDisabled(flow.getSource(), disable)) + .build(); + + flowRepository.update( + flowUpdated, + flow, + flowUpdated.getSource(), + taskDefaultService.injectDefaults(flowUpdated) + ); + }) + .toList(); + } + + protected List<FlowWithSource> setFlowsDisableByQuery(String query, String namespace,List<String> labels, boolean disable) { + return flowRepository + .findWithSource(query, namespace, RequestUtils.toMap(labels)) + .stream() + .filter(flowWithSource -> disable != flowWithSource.isDisabled()) + .peek(flow -> { + FlowWithSource flowUpdated = flow.toBuilder() + .disabled(disable) + .source(FlowService.injectDisabled(flow.getSource(), disable)) + .build(); + + flowRepository.update( + flowUpdated, + flow, + flowUpdated.getSource(), + taskDefaultService.injectDefaults(flowUpdated) + ); + }) + .toList(); + } }
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java index b159b19c90..cf7246c3bb 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java @@ -555,7 +555,7 @@ void importFlowsWithZip() throws IOException { } @Test - void disableFlowsByIds() { + void disableEnableFlowsByIds() { List<IdWithNamespace> ids = List.of( new IdWithNamespace("io.kestra.tests", "each-object"), new IdWithNamespace("io.kestra.tests", "webhook"), @@ -575,10 +575,24 @@ void disableFlowsByIds() { assertThat(eachObject.isDisabled(), is(true)); assertThat(webhook.isDisabled(), is(true)); assertThat(taskFlow.isDisabled(), is(true)); + + response = client + .toBlocking() + .exchange(POST("/api/v1/flows/enable/by-ids", ids), BulkResponse.class); + + assertThat(response.getBody().get().getCount(), is(3)); + + eachObject = parseFlow(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/io.kestra.tests/each-object"), String.class)); + webhook = parseFlow(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/io.kestra.tests/webhook"), String.class)); + taskFlow = parseFlow(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/io.kestra.tests/task-flow"), String.class)); + + assertThat(eachObject.isDisabled(), is(false)); + assertThat(webhook.isDisabled(), is(false)); + assertThat(taskFlow.isDisabled(), is(false)); } @Test - void disableFlowsByQuery() throws InterruptedException { + void disableEnableFlowsByQuery() throws InterruptedException { Flow flow = generateFlow("toDisable","io.kestra.unittest.disabled", "a"); client.toBlocking().retrieve(POST("/api/v1/flows", flow), String.class); @@ -591,6 +605,16 @@ void disableFlowsByQuery() throws InterruptedException { Flow toDisable = parseFlow(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/io.kestra.unittest.disabled/toDisable"), String.class)); assertThat(toDisable.isDisabled(), is(true)); + + response = client + .toBlocking() + .exchange(POST("/api/v1/flows/enable/by-query?namespace=io.kestra.unittest.disabled", Map.of()), BulkResponse.class); + + assertThat(response.getBody().get().getCount(), is(1)); + + toDisable = parseFlow(client.toBlocking().retrieve(HttpRequest.GET("/api/v1/flows/io.kestra.unittest.disabled/toDisable"), String.class)); + + assertThat(toDisable.isDisabled(), is(false)); } @Test
train
train
2023-06-21T22:06:57
"2023-04-27T04:18:18Z"
hamrio
train
kestra-io/kestra/1271_1554
kestra-io/kestra
kestra-io/kestra/1271
kestra-io/kestra/1554
[ "keyword_pr_to_issue" ]
896777a05d5d37cade175117a1ada3294cdc1b30
e2b71bda02de648a6be0e3b456ab624d2290dbdd
[ "\\+ removing quotes by default", "+1 to quotes and also it would be nice to have it prefilled to make it even easier e.g. \r\n\r\n```yaml\r\nid: helloThere\r\nnamespace: dev\r\ntasks:\r\n - id: hello\r\n type: io.kestra.core.tasks.log.Log\r\n message: Kestra team wishes you a great day! 👋\r\n```\r\nwhat do you think? this way, opening the editor would be even more encouraging! :) ", "+1 for the prefill" ]
[ "not necessary?", "This is false; only a not existing task type can prevent creating a graph.\r\n ", "Oups, I was testing something, good spot :+1: \r\nIn fact I was wondering why this was red and was ensuring array had this method. \r\n![image](https://github.com/kestra-io/kestra/assets/37618489/ff51891a-5695-4c7b-b668-2cc6633f0aa3)\r\n\r\nLooks to be related to this but idk if we should add something to the compiler https://github.com/Microsoft/TypeScript/issues/2340\r\n", "I don't have the issue; maybe you have some dependencies that are not up to date? ", "I feel like we weren't handling that case unless in creation mode. Is that intended ? Should we create another issue ? We may need to add another validate then or should we simply call fetchGraph and handle the error case ?", "I just npm installed and still have the issue, looks strange :thinking: ", "I guess I will try to live along with this compiler error" ]
"2023-06-19T15:39:11Z"
[ "enhancement", "frontend" ]
Provide more comprehensive template for flow creation init
### Feature description It would be great to have this template instead of the existing one since flows need at least one task to be valid ``` id: "" namespace: "" tasks: - id: "" type: "" ```
[ "ui/src/components/flows/FlowCreate.vue", "ui/src/components/graph/nodes/Edge.vue", "ui/src/components/inputs/EditorView.vue", "ui/src/components/inputs/LowCodeEditor.vue" ]
[ "ui/src/components/flows/FlowCreate.vue", "ui/src/components/graph/nodes/Edge.vue", "ui/src/components/inputs/EditorView.vue", "ui/src/components/inputs/LowCodeEditor.vue" ]
[]
diff --git a/ui/src/components/flows/FlowCreate.vue b/ui/src/components/flows/FlowCreate.vue index 3d62e96d57..a12306fc95 100644 --- a/ui/src/components/flows/FlowCreate.vue +++ b/ui/src/components/flows/FlowCreate.vue @@ -1,39 +1,51 @@ <template> <div> - <Topology - :flow-id="flowId" - :namespace="namespace" + <editor-view + :flow-id="defaultFlowTemplate.id" + :namespace="defaultFlowTemplate.namespace" :is-creating="true" :flow-graph="flowGraph" :is-read-only="false" :total="total" :guided-properties="guidedProperties" :flow-error="flowError" + :flow="flowWithSource" /> </div> <div id="guided-right" /> </template> <script> - import Topology from "../inputs/EditorView.vue"; + import EditorView from "../inputs/EditorView.vue"; import {mapGetters, mapState} from "vuex"; import RouteContext from "../../mixins/routeContext"; + import YamlUtils from "../../utils/yamlUtils"; export default { mixins: [RouteContext], components: { - Topology + EditorView }, data() { return { - flowId: "", - namespace: "", + defaultFlowTemplate: { + id: "hello-world", + namespace: "dev", + tasks: [{ + id: "hello", + type: "io.kestra.core.tasks.log.Log", + message: "Kestra team wishes you a great day! 👋" + }] + } } }, beforeUnmount() { this.$store.commit("flow/setFlowError", undefined); }, computed: { + flowWithSource() { + return {source: YamlUtils.stringify(this.defaultFlowTemplate)}; + }, ...mapState("flow", ["flowGraph", "total"]), ...mapState("auth", ["user"]), ...mapState("plugin", ["pluginSingleList", "pluginsDocumentation"]), diff --git a/ui/src/components/graph/nodes/Edge.vue b/ui/src/components/graph/nodes/Edge.vue index b52e704d74..35d0f7030e 100644 --- a/ui/src/components/graph/nodes/Edge.vue +++ b/ui/src/components/graph/nodes/Edge.vue @@ -106,11 +106,11 @@ const path = computed(() => getSmoothStepPath(props)) - const onMouseOver = (edge) => { + const onMouseOver = () => { isHover.value = true; } - const onMouseLeave = (edge) => { + const onMouseLeave = () => { isHover.value = false; } @@ -118,7 +118,7 @@ taskYaml.value = task; clearTimeout(timer.value); timer.value = setTimeout(() => { - store.dispatch("flow/validateTask", {task: task}) + store.dispatch("flow/validateTask", {task: task, section: SECTIONS.TASKS}) }, 500); } @@ -142,7 +142,7 @@ } const taskHaveId = () => { - return taskYaml.value.length > 0 ? YamlUtils.parse(taskYaml.value).id ? true : false : false; + return taskYaml.value.length > 0 ? !!YamlUtils.parse(taskYaml.value).id : false; } const checkTaskExist = () => { diff --git a/ui/src/components/inputs/EditorView.vue b/ui/src/components/inputs/EditorView.vue index f9dc1f669c..ac38d6b54c 100644 --- a/ui/src/components/inputs/EditorView.vue +++ b/ui/src/components/inputs/EditorView.vue @@ -20,9 +20,9 @@ import permission from "../../models/permission"; import action from "../../models/action"; import YamlUtils from "../../utils/yamlUtils"; - import taskEditor from "../flows/TaskEditor.vue"; - import metadataEditor from "../flows/MetadataEditor.vue"; - import editor from "./Editor.vue"; + import TaskEditor from "../flows/TaskEditor.vue"; + import MetadataEditor from "../flows/MetadataEditor.vue"; + import Editor from "./Editor.vue"; import yamlUtils from "../../utils/yamlUtils"; import {pageFromRoute} from "../../utils/eventsRouter"; import {SECTIONS} from "../../utils/constants.js"; @@ -163,22 +163,9 @@ } const initYamlSource = async () => { - flowYaml.value = props.flow ? props.flow.source : YamlUtils.stringify({ - id: props.flowId, - namespace: props.namespace - }); + flowYaml.value = props.flow.source; - if(!props.isCreating && !props.isReadOnly) { - const validation = await store.dispatch("flow/validateFlow", {flow: flowYaml.value}); - const validationErrors = validation[0].constraints; - if (validationErrors) { - singleErrorToast(t("cannot create topology"), t("invalid flow"), validationErrors); - }else { - generateGraph(); - } - } else { - generateGraph(); - } + await generateGraph(); if(!props.isReadOnly) { let restoredLocalStorageKey; @@ -204,9 +191,6 @@ } onMounted(async () => { - if (props.isCreating) { - store.commit("flow/setFlowGraph", undefined); - } await initYamlSource(); // Save on ctrl+s in topology document.addEventListener("keydown", save); @@ -343,6 +327,16 @@ persistEditorContent(false); } + const fetchGraph = async (yaml) => { + await store.dispatch("flow/loadGraphFromSource", { + flow: yaml, config: { + validateStatus: (status) => { + return status === 200 || status === 422; + } + } + }) + } + const onEdit = (event) => { flowYaml.value = event; haveChange.value = true; @@ -350,33 +344,20 @@ return store.dispatch("flow/validateFlow", {flow: event}) .then(value => { if (flowHaveTasks() && ["topology", "source-topology"].includes(viewType.value)) { - store.dispatch("flow/loadGraphFromSource", { - flow: event, config: { - validateStatus: (status) => { - return status === 200 || status === 422; - } - } - }) - } else { - regenerateGraph(); + generateGraph() } return value; }); } - const generateGraph = () => { + const generateGraph = async () => { + await fetchGraph(flowYaml.value); if (props.flowGraph) { lowCodeEditorRef.value.generateGraph(); } } - const regenerateGraph = () => { - if (props.flowGraph) { - lowCodeEditorRef.value.regenerateGraph(); - } - } - const loadingState = (value) => { isLoading.value = value; } @@ -821,7 +802,7 @@ @click="save" v-if="isAllowedEdit" :type="flowError ? 'danger' : 'primary'" - :disabled="!haveChange" + :disabled="!haveChange && !isCreating" class="edit-flow-save-button" > {{ $t("save") }} diff --git a/ui/src/components/inputs/LowCodeEditor.vue b/ui/src/components/inputs/LowCodeEditor.vue index 65e905c9d7..b1790eaffe 100644 --- a/ui/src/components/inputs/LowCodeEditor.vue +++ b/ui/src/components/inputs/LowCodeEditor.vue @@ -105,7 +105,7 @@ }) watch(() => props.flowGraph, () => { - regenerateGraph(); + generateGraph(); }) // Event listeners & Watchers @@ -113,7 +113,7 @@ const resizeObserver = new ResizeObserver(function () { clearTimeout(timer.value); timer.value = setTimeout(() => { - regenerateGraph(); + generateGraph(); nextTick(() => { fitView() }) @@ -258,7 +258,7 @@ localStorage.getItem("topology-orientation") !== "0" ? "0" : "1" ); isHorizontal.value = localStorage.getItem("topology-orientation") === "1"; - regenerateGraph(); + generateGraph(); fitView(); }; @@ -370,171 +370,170 @@ return target } + const cleanGraph = () => { + removeEdges(getEdges.value) + removeNodes(getNodes.value) + removeSelectedElements(getElements.value) + elements.value = [] + } + const generateGraph = () => { - emit("loading", true); - try { - if (!props.flowGraph || !flowHaveTasks()) { - elements.value.push({ - id: "start", - label: "", - type: "dot", - position: {x: 0, y: 0}, - style: { - width: "5px", - height: "5px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: undefined, - draggable: false, - }) - elements.value.push({ - id: "end", - label: "", - type: "dot", - position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, - style: { - width: "5px", - height: "5px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: undefined, - draggable: false, - }) - elements.value.push({ - id: "start|end", - source: "start", - target: "end", - type: "edge", - markerEnd: MarkerType.ArrowClosed, - data: { - edge: { - relation: { - relationType: "SEQUENTIAL" - } + cleanGraph(); + + nextTick(() => { + emit("loading", true); + try { + if (!props.flowGraph || !flowHaveTasks()) { + elements.value.push({ + id: "start", + label: "", + type: "dot", + position: {x: 0, y: 0}, + style: { + width: "5px", + height: "5px" }, - isFlowable: false, - initTask: true, - } - }) + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: undefined, + draggable: false, + }) + elements.value.push({ + id: "end", + label: "", + type: "dot", + position: isHorizontal.value ? {x: 50, y: 0} : {x: 0, y: 50}, + style: { + width: "5px", + height: "5px" + }, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: undefined, + draggable: false, + }) + elements.value.push({ + id: "start|end", + source: "start", + target: "end", + type: "edge", + markerEnd: MarkerType.ArrowClosed, + data: { + edge: { + relation: { + relationType: "SEQUENTIAL" + } + }, + isFlowable: false, + initTask: true, + } + }) - emit("loading", false); - return; - } - if (props.flowGraph === undefined) { + emit("loading", false); + return; + } + if (props.flowGraph === undefined) { + emit("loading", false); + return; + } + const dagreGraph = generateDagreGraph(); + const clusters = {}; + for (let cluster of (props.flowGraph.clusters || [])) { + for (let nodeUid of cluster.nodes) { + clusters[nodeUid] = cluster.cluster; + } - emit("loading", false); - return; - } - const dagreGraph = generateDagreGraph(); - const clusters = {}; - for (let cluster of (props.flowGraph.clusters || [])) { - for (let nodeUid of cluster.nodes) { - clusters[nodeUid] = cluster.cluster; + const dagreNode = dagreGraph.node(cluster.cluster.uid) + const parentNode = cluster.parents ? cluster.parents[cluster.parents.length - 1] : undefined; + + const clusterUid = cluster.cluster.uid; + elements.value.push({ + id: clusterUid, + label: clusterUid, + type: "cluster", + parentNode: parentNode, + position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), + style: { + width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", + height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", + }, + }) } - const dagreNode = dagreGraph.node(cluster.cluster.uid) - const parentNode = cluster.parents ? cluster.parents[cluster.parents.length - 1] : undefined; - - const clusterUid = cluster.cluster.uid; - elements.value.push({ - id: clusterUid, - label: clusterUid, - type: "cluster", - parentNode: parentNode, - position: getNodePosition(dagreNode, parentNode ? dagreGraph.node(parentNode) : undefined), - style: { - width: clusterUid === "Triggers" && isHorizontal.value ? "400px" : dagreNode.width + "px", - height: clusterUid === "Triggers" && !isHorizontal.value ? "250px" : dagreNode.height + "px", - }, - }) - } + let disabledLowCode = []; + + for (const node of props.flowGraph.nodes) { + const dagreNode = dagreGraph.node(node.uid); + let nodeType = "task"; + if (node.type.includes("GraphClusterEnd")) { + nodeType = "dot"; + } else if (clusters[node.uid] === undefined && node.type.includes("GraphClusterRoot")) { + nodeType = "dot"; + } else if (node.type.includes("GraphClusterRoot")) { + nodeType = "dot"; + } else if (node.type.includes("GraphTrigger")) { + nodeType = "trigger"; + } + // Disable interaction for Dag task + // because our low code editor can not handle it for now + if (isTaskNode(node) && node.task.type === "io.kestra.core.tasks.flows.Dag") { + disabledLowCode.push(node.task.id); + YamlUtils.getChildrenTasks(props.source, node.task.id).forEach(child => { + disabledLowCode.push(child); + }) + } - let disabledLowCode = []; - - for (const node of props.flowGraph.nodes) { - const dagreNode = dagreGraph.node(node.uid); - let nodeType = "task"; - if (node.type.includes("GraphClusterEnd")) { - nodeType = "dot"; - } else if (clusters[node.uid] === undefined && node.type.includes("GraphClusterRoot")) { - nodeType = "dot"; - } else if (node.type.includes("GraphClusterRoot")) { - nodeType = "dot"; - } else if (node.type.includes("GraphTrigger")) { - nodeType = "trigger"; - } - // Disable interaction for Dag task - // because our low code editor can not handle it for now - if (isTaskNode(node) && node.task.type === "io.kestra.core.tasks.flows.Dag") { - disabledLowCode.push(node.task.id); - YamlUtils.getChildrenTasks(props.source, node.task.id).forEach(child => { - disabledLowCode.push(child); + elements.value.push({ + id: node.uid, + label: isTaskNode(node) ? node.task.id : "", + type: nodeType, + position: getNodePosition(dagreNode, clusters[node.uid] ? dagreGraph.node(clusters[node.uid].uid) : undefined), + style: { + width: getNodeWidth(node) + "px", + height: getNodeHeight(node) + "px" + }, + sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, + targetPosition: isHorizontal.value ? Position.Left : Position.Top, + parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, + draggable: nodeType === "task" && !props.isReadOnly && isTaskNode(node) ? !disabledLowCode.includes(node.task.id) : false, + data: { + node: node, + namespace: props.namespace, + flowId: props.flowId, + revision: props.execution ? props.execution.flowRevision : undefined, + isFlowable: isTaskNode(node) ? flowables().includes(node.task.id) : false + }, }) } - elements.value.push({ - id: node.uid, - label: isTaskNode(node) ? node.task.id : "", - type: nodeType, - position: getNodePosition(dagreNode, clusters[node.uid] ? dagreGraph.node(clusters[node.uid].uid) : undefined), - style: { - width: getNodeWidth(node) + "px", - height: getNodeHeight(node) + "px" - }, - sourcePosition: isHorizontal.value ? Position.Right : Position.Bottom, - targetPosition: isHorizontal.value ? Position.Left : Position.Top, - parentNode: clusters[node.uid] ? clusters[node.uid].uid : undefined, - draggable: nodeType === "task" && !props.isReadOnly && isTaskNode(node) ? !disabledLowCode.includes(node.task.id) : false, - data: { - node: node, - namespace: props.namespace, - flowId: props.flowId, - revision: props.execution ? props.execution.flowRevision : undefined, - isFlowable: isTaskNode(node) ? flowables().includes(node.task.id) : false - }, - }) + for (const edge of props.flowGraph.edges) { + elements.value.push({ + id: edge.source + "|" + edge.target, + source: edge.source, + target: edge.target, + type: "edge", + markerEnd: MarkerType.ArrowClosed, + data: { + edge: edge, + haveAdd: complexEdgeHaveAdd(edge), + isFlowable: flowables().includes(edge.source) || flowables().includes(edge.target), + nextTaskId: getNextTaskId(edge.target), + disabled: disabledLowCode.includes(edge.source) + } + }) + } + } catch (e) { + console.error("Error while creating topology graph: " + e); } - - for (const edge of props.flowGraph.edges) { - elements.value.push({ - id: edge.source + "|" + edge.target, - source: edge.source, - target: edge.target, - type: "edge", - markerEnd: MarkerType.ArrowClosed, - data: { - edge: edge, - haveAdd: complexEdgeHaveAdd(edge), - isFlowable: flowables().includes(edge.source) || flowables().includes(edge.target), - nextTaskId: getNextTaskId(edge.target), - disabled: disabledLowCode.includes(edge.source) - } - }) + finally { + emit("loading", false); } - } catch (e) { - console.error("Error while creating topology graph: " + e); - } - finally { - emit("loading", false); - } - } - - const regenerateGraph = () => { - removeEdges(getEdges.value) - removeNodes(getNodes.value) - removeSelectedElements(getElements.value) - elements.value = [] - nextTick(() => { - generateGraph(); }) } // Expose method to be triggered by parents defineExpose({ - generateGraph, - regenerateGraph + generateGraph }) </script>
null
val
train
2023-06-21T22:06:57
"2023-05-11T08:59:20Z"
brian-mulier-p
train
kestra-io/kestra/1399_1558
kestra-io/kestra
kestra-io/kestra/1399
kestra-io/kestra/1558
[ "keyword_pr_to_issue" ]
ae94fbd5519d94b69556bc67ab609351817db5e0
fb39ece01dbb74ace10b703b1b67b5bbbc5a0289
[ "Please provide the content that goes with + adds comments to the code.", "Updated YAML content in main comment above.\r\n\r\nHere are the different steps :\r\n\r\n0. same as before\r\n1. same as before\r\n2. same as before\r\n3. same as before\r\n4. same as before\r\n5.\r\n**Logs some information**\r\nFirst, let's start by adding a task that will log some information. This task will be executed when the flow is triggered and log \"Hey there, Kestra user\".\r\n\r\n6.\r\n**Run Bash command**\r\nSometimes, you want to run specific scripts, Python, Node, Bash, etc. Here we run a bash command to display a message.\r\n\r\n7.\r\n**Schedule**\r\nTo schedule a flow we add a 'trigger'. Here we schedule the Flow every minute.\r\n\r\n8. same as before\r\n9. same as before\r\n10. same as before\r\n\r\n\r\n\r\n\r\n" ]
[]
"2023-06-20T09:17:38Z"
[ "backend", "enhancement" ]
Update guided tour Flow
### Feature description ```yaml # Flow declaration with a mandatory unique identifier, a namespace, and an optional description. # Flow identifier are unique inside a namespace. id: welcomeKestra namespace: demo description: Welcome to Kestra! # Flow inputs: each input has a name, a type, and an optional default value. inputs: # We define one input of name 'user' with a default value 'Data Engineer' - name: user type: STRING defaults: Kestra user # List of tasks that will be executed one after the other. # Each task must have an identifier unique for the flow and a type. # Depending on the type of the task, you may have to pass additional attributes. tasks: # This is one of the simplest task: it display a message in the log. # The message is passed thanks to the 'message' attribute. # We use the variable from the 'input' : {{ and }} are separator of a Pebble expression in which we can access variables. - id: hello type: io.kestra.core.tasks.log.Log message: Hey there, {{ inputs.user }}! # This is task run a bash command # Here we just 'echo' a message, using again the input variable - id: goodbye type: io.kestra.core.tasks.scripts.Bash commands: - echo See you soon, {{ inputs.user }}! # To trigger the Flow we use the 'triggers' property triggers: # Here we use a special trigger type 'Schedule' to schedule the Flow every minute - id: everyMinute type: io.kestra.core.models.triggers.types.Schedule cron: "*/1 * * * *" inputs: name: Kestra master user ```
[ "ui/src/components/onboarding/VueTour.vue", "ui/src/translations.json" ]
[ "ui/src/components/onboarding/VueTour.vue", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/onboarding/VueTour.vue b/ui/src/components/onboarding/VueTour.vue index 5bdaa45d4f..6610cc0f93 100644 --- a/ui/src/components/onboarding/VueTour.vue +++ b/ui/src/components/onboarding/VueTour.vue @@ -301,51 +301,39 @@ flowParts: [ "# " + this.$t("onboarding-flow.onboardComment1") + "\n" + "# " + this.$t("onboarding-flow.onboardComment2") + "\n" + - "id: kestra-tour\n" + + "id: welcomeKestra" + "\n" + "namespace: io.kestra.tour\n" + - "description: Kestra guided tour", + "description: Welcome to Kestra!" + "\n", "# " + this.$t("onboarding-flow.inputs") + "\n" + - "inputs:\n" + + "inputs:" + "\n" + " # " + this.$t("onboarding-flow.inputsDetails1") + "\n" + - " # " + this.$t("onboarding-flow.inputsDetails2") + "\n" + - " - name: csvUrl\n" + - " type: STRING\n" + - " defaults: https://gist.githubusercontent.com/tchiotludo/2b7f28f4f507074e60150aedb028e074/raw/6b6348c4f912e79e3ffccaf944fd019bf51cba30/conso-elec-gaz-annuelle-par-naf-agregee-region.csv", + "- name: user" + "\n" + + " type: STRING" + "\n" + + " defaults: Kestra user" + "\n", "# " + this.$t("onboarding-flow.tasks1") + "\n" + "# " + this.$t("onboarding-flow.tasks2") + "\n" + "# " + this.$t("onboarding-flow.tasks3") + "\n" + "tasks:", " # " + this.$t("onboarding-flow.taskLog1") + "\n" + " # " + this.$t("onboarding-flow.taskLog2") + "\n" + - " - id: log\n" + - " type: io.kestra.core.tasks.log.Log\n" + - " message: The flow starts", - " # " + this.$t("onboarding-flow.taskDL") + "\n" + - " - id: downloadData\n" + - " type: io.kestra.plugin.fs.http.Download\n" + - " # " + this.$t("onboarding-flow.taskDLUri1") + "\n" + - " # " + this.$t("onboarding-flow.taskDLUri2") + "\n" + - " uri: \"{{inputs.csvUrl}}\"", - " # " + this.$t("onboarding-flow.taskPython") + "\n" + - " - id: analyseData\n" + - " type: io.kestra.core.tasks.scripts.Python\n" + - " inputFiles:\n" + - " # " + this.$t("onboarding-flow.taskPythonCSV1") + "\n" + - " # " + this.$t("onboarding-flow.taskPythonCSV2") + "\n" + - " data.csv: \"{{outputs.downloadData.uri}}\"\n" + - " # " + this.$t("onboarding-flow.taskPythonMain1") + "\n" + - " # " + this.$t("onboarding-flow.taskPythonMain2") + "\n" + - " # " + this.$t("onboarding-flow.taskPythonMain3") + "\n" + - " main.py: |\n" + - " import pandas as pd\n" + - " from kestra import Kestra\n" + - " data = pd.read_csv(\"data.csv\", sep=\";\")\n" + - " data.info()\n" + - " sumOfConsumption = data['conso'].sum()\n" + - " Kestra.outputs({'sumOfConsumption': int(sumOfConsumption)})\n" + - " # " + this.$t("onboarding-flow.taskPythonRequirements") + "\n" + - " requirements:\n" + - " - pandas" + " # " + this.$t("onboarding-flow.taskLog3") + "\n" + + "- id: hello" + "\n" + + " type: io.kestra.core.tasks.log.Log" + "\n" + + " message: Hey there, {{ inputs.user }}!" + "\n", + " # " + this.$t("onboarding-flow.taskBash1") + "\n" + + " # " + this.$t("onboarding-flow.taskBash2") + "\n" + + "- id: goodbye" + "\n" + + " type: io.kestra.core.tasks.scripts.Bash" + "\n" + + " commands:" + "\n" + + " - echo See you soon, {{ inputs.user }}!" + "\n", + " # " + this.$t("onboarding-flow.triggers") + "\n" + + "triggers:" + "\n" + + " # " + this.$t("onboarding-flow.triggerSchedule1") + "\n" + + " - id: everyMinute" + "\n" + + " type: io.kestra.core.models.triggers.types.Schedule" + "\n" + + " cron: \"*/1 * * * *\"" + "\n" + + " inputs:" + "\n" + + " name: Kestra master user" + "\n" ] } }, diff --git a/ui/src/translations.json b/ui/src/translations.json index a53412893e..59f189df71 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -336,15 +336,15 @@ }, "step6": { "title": "Logs some information", - "content": "First, let's start by adding a task that will log some information. This task will be executed when the flow is triggered and log <code>The flow starts</code>." + "content": "First, let's start by adding a task that will log some information. This task will be executed when the flow is triggered and log \"Hey there, Kestra user\"" }, "step7": { - "title": "Download a file", - "content": "Sometimes, you want to download a file from a remote server. This can be done by using the Download task. This task will download the file into Kestra's internal storage." + "title": "Run Bash command", + "content": "Sometimes, you want to run specific scripts, Python, Node, Bash, etc. Here we run a bash command to display a message." }, "step8": { - "title": "Use Python to do analytics", - "content": "Maybe this file contains some interesting data? Let's use Python and Pandas to do some analytics on it! This task uses the output of the previous task via the <code>outputs.downloadData.uri</code> variable and defines an output named <code>sumOfConsumption</code> thanks to the Kestra Python library." + "title": "Schedule", + "content": "To schedule a flow we add a 'trigger'. Here we schedule the Flow every minute." }, "step9": { "title": "Save your flow", @@ -363,23 +363,17 @@ "onboardComment1": "Flow declaration with a mandatory unique identifier, a namespace, and an optional description.", "onboardComment2": "Flow identifier are unique inside a namespace.", "inputs": "Flow inputs: each input has a name, a type, and an optional default value.", - "inputsDetails1": "We define one input of name 'csvUrl' with as default value the URL of the test data file.", - "inputsDetails2": "This test data is from the France Open Data portal and contains french electricity consumptions in CSV.", + "inputsDetails1": "We define one input of name 'user' with a default value 'Data Engineer'", "tasks1": "List of tasks that will be executed one after the other.", "tasks2": "Each task must have an identifier unique for the flow and a type.", "tasks3": "Depending on the type of the task, you may have to pass additional attributes.", "taskLog1": "This is one of the simplest task: it echos a message in the log, like the 'echo' command.", "taskLog2": "The message is passed thanks to the 'format' attribute.", - "taskDL": "This task will download the CSV, it will be sent to Kestra's internal storage and available from the task output.", - "taskDLUri1": "Here we use a variable from an input: {'{{'} and {'}}'} are separator of a Pebble expression in which we can access variables.", - "taskDLUri2": "All inputs are available from the 'inputs' variable using there name.", - "taskPython": "This task will analyse the CSV data using a Python script with the Pandas library.", - "taskPythonCSV1": "Here we define a file named 'data.csv' that will be available in the Python task working directory.", - "taskPythonCSV2": "This file is fetched from the internal storage by using the 'uri' output of the 'downloadData' task.", - "taskPythonMain1": "'main.py' is the Python script that will be executed.", - "taskPythonMain2": "It uses Pandas to read the CSV file, compute the sum of the 'conso' column, ", - "taskPythonMain3": "and set it as task output thanks to the Kestra Python library.", - "taskPythonRequirements": "As the script require the Pandas library, we must list it in the requirements." + "taskLog3": "We use the variable from the 'inputs' : {'{{'} and {'}}'} are separator of a Pebble expression in which we can access variables.", + "taskBash1": "This task runs a bash command.", + "taskBash2": "Here we just 'echo' a message, using again the input variable.", + "triggers": "To trigger the Flow we use the 'triggers' property.", + "triggerSchedule1": "Here we use the 'schedule' trigger to run the flow every minute." }, "Skip tour": "Skip tour", "Next step": "Next step", @@ -784,15 +778,15 @@ }, "step6": { "title": "Afficher des informations", - "content": "En premier, commençons par ajouter une tâche qui affiche quelques informations. Cette tâche sera exécutée quand le flow est déclenché et affichera <code>The flow starts</code>." + "content": "En premier, commençons par ajouter une tâche qui affiche quelques informations. Cette tâche sera exécutée quand le flow est déclenché et affichera <code>Hey there, Kestra user</code>." }, "step7": { - "title": "Télécharger un fichier", - "content": "Parfois, vous voudrez télécharger un fichier depuis un serveur distant. Ceci peut être fait grâce à la tâche 'Download'. Cette tâche téléchargera le fichier dans le stockage interne de Kestra." + "title": "Exécuter une commande bash", + "content": "Parfois, vous souhaiterez exécuter des scripts spécifiques, Python, Node, Bash, etc. Ici, nous lançons une commande bash pour afficher un message." }, "step8": { - "title": "Python pour l'analytique", - "content": "Peut-être que ce fichier contient des données intéressantes ? Utilisons Python et Pandas pour faire quelques analyses dessus! Cette tâche utilise la sortie de la tâche précédente via la variable <code>>outputs.downloadData.uri</code> et définit une nouvelle sortie nommée <code>sumOfConsumption</code> grâce à la librairie Python de Kestra." + "title": "Programmer", + "content": "Pour planifier un flux, nous ajoutons un \"déclencheur\". Ici, nous programmons le flux toutes les minutes." }, "step9": { "title": "Sauvegarde de votre flow", @@ -818,16 +812,11 @@ "tasks3": "En fonction du type de tâche, vous devrez peut-être passer des attributs supplémentaires.", "taskLog1": "Il s'agit de l'une des tâches les plus simples : elle affiche un message dans le journal, comme la commande 'echo'.", "taskLog2": "Le message est transmis grâce à l'attribut 'format'.", - "taskDL": "Cette tâche permettra de télécharger le CSV, qui sera envoyé vers le stockage interne de Kestra et disponible à partir de la sortie de la tâche.", - "taskDLUri1": "Ici, nous utilisons une variable d'entrée : {'{{'} et {'}}'} sont les séparateurs d'une expression Pebble dans laquelle nous pouvons accéder aux variables.", - "taskDLUri2": "Toutes les entrées sont disponibles à partir de la variable 'inputs' en utilisant leur nom.", - "taskPython": "Cette tâche analysera les données CSV à l'aide d'un script Python avec la librairie Pandas.", - "taskPythonCSV1": "Ici, nous définissons un fichier nommé 'data.csv' qui sera disponible dans le répertoire de travail de la tâche Python.", - "taskPythonCSV2": "Ce fichier est récupéré depuis le stockage interne en utilisant la sortie 'uri' de la tâche 'downloadData'.", - "taskPythonMain1": "'main.py' est le script Python qui sera exécuté.", - "taskPythonMain2": "Il utilise Pandas pour lire le fichier CSV, calculer la somme de la colonne 'conso',", - "taskPythonMain3": "et la définir en tant que sortie de tâche grâce à la librairie Python de Kestra.", - "taskPythonRequirements": "Comme le script nécessite la librairie Pandas, nous devons la lister dans les requirements." + "taskLog3": "Nous utiliserons la variable de 'inputs' : {'{{'} et {'}}'} sont des séparateurs d'une expression Pebble dans laquelle nous pouvons accéder à des variables.", + "taskBash1": "Cette tâche exécute une commande bash.", + "taskBash2": "Ici, nous nous contentons d'afficher un message, en utilisant à nouveau la variable d'entrée.", + "triggers": "Pour déclencher le flux, nous utilisons la propriété \"triggers\".", + "triggerSchedule1": "Ici, nous utilisons le déclencheur \"schedule\" pour exécuter le flux toutes les minutes." }, "Skip tour": "Passer", "Next step": "Étape suivante",
null
test
train
2023-06-20T14:02:53
"2023-05-24T12:51:54Z"
Ben8t
train
kestra-io/kestra/1557_1560
kestra-io/kestra
kestra-io/kestra/1557
kestra-io/kestra/1560
[ "keyword_pr_to_issue" ]
896777a05d5d37cade175117a1ada3294cdc1b30
54ac36c7becbe65643938b1315bdbe3ab17c31ab
[ "cc @Skraye " ]
[ "```suggestion\r\n const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : (this.attempt ?? 0)\r\n```\r\nshould work", "```suggestion\r\n this?.$refs?.[`${taskRun.id}-${attemptNumber}`]?.[0]?.scrollToBottom();\r\n```", "```suggestion\r\n return this.execution.state.current === State.RUNNING ? taskRun.attempts : [taskRun.attempts[this.attempt]] ;\r\n```" ]
"2023-06-20T10:13:22Z"
[ "bug", "frontend" ]
Gantt chart logs are slower
### Expected Behavior _No response_ ### Actual Behaviour Since #360 it seems the display of logs in the Gantt view is slower ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/logs/LogList.vue" ]
[ "ui/src/components/logs/LogList.vue" ]
[]
diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 990cedc9f2..3f985a3d50 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -121,7 +121,7 @@ </div> </div> <DynamicScroller - :items="indexedLogsList.filter((logline) => logline.taskRunId === currentTaskRun.id)" + :items="indexedLogsList.filter((logline) => logline.taskRunId === currentTaskRun.id && logline.attemptNumber === taskAttempt(index))" :min-item-size="50" key-field="index" class="log-lines" @@ -242,9 +242,11 @@ logsList: [], threshold: 200, showLogs: [], - count: 0, followLogs: [], - logsTotal: 0 + logsTotal: 0, + timer: undefined, + timeout: undefined, + logsToOpen: [State.FAILED, State.CREATED, State.RUNNING] }; }, watch: { @@ -257,20 +259,17 @@ if (this.execution && this.execution.state.current !== State.RUNNING && this.execution.state.current !== State.PAUSED) { this.closeSSE(); } + }, + currentTaskRuns: function () { + this.openTaskRun(); } }, mounted() { if (!this.fullScreenModal) { this.loadLogs(); } - if (this.execution.state.current === State.FAILED || this.execution.state.current === State.RUNNING) { - this.currentTaskRuns.forEach((taskRun) => { - if (taskRun.state.current === State.FAILED || taskRun.state.current === State.RUNNING) { - const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : 0 - this.showLogs.push(`${taskRun.id}-${attemptNumber}`) - this.$refs[`${taskRun.id}-${attemptNumber}`][0].scrollToBottom(); - } - }); + if (this.logsToOpen.includes(this.execution.state.current)) { + this.openTaskRun(); } }, computed: { @@ -317,13 +316,22 @@ } }, methods: { + openTaskRun(){ + this.currentTaskRuns.forEach((taskRun) => { + if (this.logsToOpen.includes(taskRun.state.current)) { + const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : 0 + this.showLogs.push(`${taskRun.id}-${attemptNumber}`) + this?.$refs?.[`${taskRun.id}-${attemptNumber}`]?.[0]?.scrollToBottom(); + } + }); + }, scrollToBottomFailedTask() { - if (this.execution.state.current === State.FAILED || this.execution.state.current === State.RUNNING) { + if (this.logsToOpen.includes(this.execution.state.current)) { this.currentTaskRuns.forEach((taskRun) => { if (taskRun.state.current === State.FAILED || taskRun.state.current === State.RUNNING) { - const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : 0 + const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : (this.attempt ?? 0) if (this.showLogs.includes(`${taskRun.id}-${attemptNumber}`)) { - this.$refs[`${taskRun.id}-${attemptNumber}`][0].scrollToBottom(); + this?.$refs?.[`${taskRun.id}-${attemptNumber}`]?.[0]?.scrollToBottom(); } } }); @@ -391,10 +399,17 @@ } this.$store.commit("execution/appendFollowedLogs", JSON.parse(event.data)); this.followLogs = this.followLogs.concat(JSON.parse(event.data)); + + clearTimeout(this.timeout); + this.timeout = setTimeout(() => { + this.timer = moment() + this.logsList = JSON.parse(JSON.stringify(this.followLogs)) + this.scrollToBottomFailedTask(); + }, 100); if(moment().diff(this.timer, "seconds") > 0.5){ + clearTimeout(this.timeout); this.timer = moment() - this.logsList = JSON.parse(JSON.stringify(this.followLogs)) - this.count++; + this.logsList = JSON.parse(JSON.stringify(this.followLogs)) this.scrollToBottomFailedTask(); } } @@ -418,9 +433,7 @@ } }, attempts(taskRun) { - return this.attempt ? [taskRun.attempts[this.attempt]] : taskRun.attempts || [{ - state: taskRun.state - }]; + return this.execution.state.current === State.RUNNING ? taskRun.attempts : [taskRun.attempts[this.attempt]] ; }, onTaskSelect(dropdownVisible, task) { if (dropdownVisible && this.taskRun?.id !== task.id) {
null
train
train
2023-06-21T22:06:57
"2023-06-20T09:10:05Z"
Ben8t
train
kestra-io/kestra/1566_1570
kestra-io/kestra
kestra-io/kestra/1566
kestra-io/kestra/1570
[ "keyword_pr_to_issue" ]
b34e1aa5cf34304f3390a772294005f982c55ef7
01ef6fedde37904685074b376ca7b0cad4b7a1a2
[ "I think it was sorted this way before, and for me it's more logical to saw logs in ascending date order than in reverse date are logs are a kind of \"story\" of what happened in a flow." ]
[]
"2023-06-21T09:10:12Z"
[ "bug", "frontend" ]
Log on flow tabs on not sorted by reverse date
![image](https://github.com/kestra-io/kestra/assets/2064609/09d25e4d-e6a1-4954-8b9e-bf8b80a124be)
[ "ui/src/components/logs/LogsWrapper.vue" ]
[ "ui/src/components/logs/LogsWrapper.vue" ]
[]
diff --git a/ui/src/components/logs/LogsWrapper.vue b/ui/src/components/logs/LogsWrapper.vue index 28130890a2..fe36aeb9e5 100644 --- a/ui/src/components/logs/LogsWrapper.vue +++ b/ui/src/components/logs/LogsWrapper.vue @@ -123,7 +123,8 @@ .dispatch("log/findLogs", this.loadQuery({ page: this.$route.query.page || this.internalPageNumber, size: this.$route.query.size || this.internalPageSize, - minLevel: this.selectedLogLevel + minLevel: this.selectedLogLevel, + sort: "timestamp:desc" })) .finally(() => { this.isLoading = false
null
train
train
2023-06-20T23:07:22
"2023-06-20T16:21:18Z"
tchiotludo
train
kestra-io/kestra/1402_1574
kestra-io/kestra
kestra-io/kestra/1402
kestra-io/kestra/1574
[ "keyword_pr_to_issue" ]
896777a05d5d37cade175117a1ada3294cdc1b30
9b6bff1e8743dd76a093d40b619cfb039a9ca421
[]
[]
"2023-06-21T12:24:41Z"
[ "bug" ]
Show max rather than sum when using the `EachParallel` task
### Expected Behavior When running 3 script tasks in parallel, I'd expect the aggregated `pandasTransform` task to show the MAX runtime i.e. the time of the longest task, rather than the sum of all tasks, because they were running in parallel: ![image](https://github.com/kestra-io/kestra/assets/86264395/757bba67-b853-487e-882b-fcb02808cb4d) ### Actual Behaviour flow ```yaml id: pandas namespace: dev tasks: - id: csv type: io.kestra.core.tasks.flows.EachParallel value: ["https://raw.githubusercontent.com/dbt-labs/jaffle_shop/main/seeds/raw_customers.csv", "https://raw.githubusercontent.com/dbt-labs/jaffle_shop/main/seeds/raw_orders.csv", "https://raw.githubusercontent.com/dbt-labs/jaffle_shop/main/seeds/raw_payments.csv"] tasks: - id: pandasTransform type: io.kestra.core.tasks.scripts.Python inputFiles: data.csv: "{{taskrun.value}}" main.py: | import pandas as pd df = pd.read_csv("data.csv") df.info() requirements: - pandas ``` ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 ### Example flow _No response_
[ "ui/src/components/graph/TreeTaskNode.vue" ]
[ "ui/src/components/graph/TreeTaskNode.vue" ]
[]
diff --git a/ui/src/components/graph/TreeTaskNode.vue b/ui/src/components/graph/TreeTaskNode.vue index 8bba19a1b4..8488992b93 100644 --- a/ui/src/components/graph/TreeTaskNode.vue +++ b/ui/src/components/graph/TreeTaskNode.vue @@ -312,8 +312,8 @@ .filter(value => value.state.histories && value.state.histories.length > 0) .map(value => new Date(value.state.histories[value.state.histories.length -1].date).getTime())); - const duration = this.taskRuns - .reduce((inc, taskRun) => inc + this.$moment.duration(taskRun.state.duration).asMilliseconds() / 1000, 0); + const duration = Math.max(...this.taskRuns + .map((taskRun) => this.$moment.duration(taskRun.state.duration).asMilliseconds() / 1000, 0)); return [ {date: this.$moment(max).subtract(duration, "second"), state: "CREATED"},
null
val
train
2023-06-21T22:06:57
"2023-05-24T21:44:26Z"
anna-geller
train
kestra-io/kestra/1568_1575
kestra-io/kestra
kestra-io/kestra/1568
kestra-io/kestra/1575
[ "keyword_pr_to_issue" ]
6fac45459e84de0f9e0c0e9dc2d499c9972f9575
325485e7e68c902d6689e0b76f3ef28cab559e4b
[ "it would be great to also add this:\r\n\r\n- [x] open a blueprint in a new tab - currently, you can only open it on the same page, making it difficult to inspect/browse blueprints", "@Ben8t regarding the \"too many space\" between source code and editor, that's because there's a copy button in the editor header which creates this offsets. Should I overlap the copy button in top-right corner of the actual editor (eventually hiding part of the id / namespace if it is a really long one) ?\r\n\r\nFor the topology orientation, I replicated the behaviour of the topology view: if on blueprints standalone page you are able to switch your orientation but when side-by-side with the editor you can't change the orientation and it is taken from your local storage (ie your preferences)", "> it would be great to also add this:\r\n> \r\n> * [x] open a blueprint in a new tab - currently, you can only open it on the same page, making it difficult to inspect/browse blueprints\r\n\r\nDo you mean CTRL click to open in a new browser tab ?", "@brian-mulier-p \r\n\r\n> regarding the \"too many space\" between source code and editor, that's because there's a copy button in the editor header which creates this offsets. Should I overlap the copy button in top-right corner of the actual editor (eventually hiding part of the id / namespace if it is a really long one) ?\r\n\r\nYes go for it, so long id/namespace would be something very rare coming from internal blueprint (so it's 0.0001% chance of occurring atm)" ]
[ "We should have native link only, we should not decided for the user to open or not a blank and let them decide with a normal link " ]
"2023-06-21T13:40:07Z"
[ "bug", "backend", "frontend" ]
Blueprint adjustments (2)
### Feature description - [x] When clicking on the "back" arrow, users are moved to the blueprints homepage -> would be nice that when the user search, the "go back" button goes back to the search results. Same if he filtered on a tag. - [x] In a similar way, in the editor view, users should be able to get back their blueprint page whenever they click on another view button (doc, topo, etc.). Atm it's coming back to the blueprint default page (home) - [x] Too many space between source code and corresponding title ![image](https://github.com/kestra-io/kestra/assets/46634684/ab5071bb-3422-4f59-afc0-8fd4e65e184b) - [x] add the possibility to move the topology horizontaly/verticically. If possible always set horizontal in Blueprints main section. - [x] Keep the breadcrumb (like in other page headers)
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue", "ui/src/components/inputs/EditorView.vue", "ui/src/components/inputs/LowCodeEditor.vue", "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/styles/components/blueprints/blueprints.scss" ]
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue", "ui/src/components/inputs/EditorView.vue", "ui/src/components/inputs/LowCodeEditor.vue", "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/styles/components/blueprints/blueprints.scss" ]
[]
diff --git a/ui/src/components/flows/blueprints/BlueprintDetail.vue b/ui/src/components/flows/blueprints/BlueprintDetail.vue index f2aad90431..9687cd7e6e 100644 --- a/ui/src/components/flows/blueprints/BlueprintDetail.vue +++ b/ui/src/components/flows/blueprints/BlueprintDetail.vue @@ -42,15 +42,15 @@ :namespace="parsedFlow.namespace" :flow-graph="flowGraph" :source="blueprint.flow" + :view-type="embed ? 'source-blueprints' : 'blueprints'" is-read-only - graph-only /> </div> </el-card> <h5>{{ $t("source") }}</h5> - <editor :read-only="true" :full-height="false" :minimap="false" :model-value="blueprint.flow" lang="yaml"> + <editor class="position-relative" :read-only="true" :full-height="false" :minimap="false" :model-value="blueprint.flow" lang="yaml"> <template #nav> - <div style="text-align: right"> + <div class="position-absolute copy-wrapper"> <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> <el-button text round :icon="icon.ContentCopy" @click="copy(blueprint.flow)" /> </el-tooltip> @@ -112,7 +112,7 @@ if (this.embed) { this.$emit("back"); } else { - this.$router.push({name: "blueprints", params: this.$route.params}) + this.$router.push({name: "blueprints"}) } }, copy(text) { @@ -187,6 +187,12 @@ } } + .copy-wrapper { + right: $spacer; + top: $spacer; + z-index: 1 + } + .blueprint-container { height: 100%; diff --git a/ui/src/components/inputs/EditorView.vue b/ui/src/components/inputs/EditorView.vue index 52b7c1b0d7..154d512425 100644 --- a/ui/src/components/inputs/EditorView.vue +++ b/ui/src/components/inputs/EditorView.vue @@ -621,7 +621,7 @@ @restartGuidedTour="() => persistViewType('source')" /> <div class="slider" @mousedown="dragEditor" v-if="combinedEditor" /> - <Blueprints v-if="viewType === 'source-blueprints'" embed class="combined-right-view enhance-readability" :top-navbar="false" prevent-route-info /> + <Blueprints :class="{'d-none': viewType !== 'source-blueprints'}" embed class="combined-right-view enhance-readability" :top-navbar="false" prevent-route-info /> <div :class="viewType === 'source-topology' ? 'combined-right-view' : viewType === 'topology' ? 'vueflow': 'hide-view'" > diff --git a/ui/src/components/inputs/LowCodeEditor.vue b/ui/src/components/inputs/LowCodeEditor.vue index b1790eaffe..8abeddb14e 100644 --- a/ui/src/components/inputs/LowCodeEditor.vue +++ b/ui/src/components/inputs/LowCodeEditor.vue @@ -592,7 +592,7 @@ </template> <Controls :show-interactive="false"> - <ControlButton @click="toggleOrientation" v-if="viewType === 'topology'"> + <ControlButton @click="toggleOrientation" v-if="['topology', 'blueprints'].includes(viewType)"> <SplitCellsVertical :size="48" v-if="!isHorizontal" /> <SplitCellsHorizontal v-if="isHorizontal" /> </ControlButton> diff --git a/ui/src/override/components/flows/blueprints/Blueprints.vue b/ui/src/override/components/flows/blueprints/Blueprints.vue index f5cc86d4bb..d7bbcc9f2c 100644 --- a/ui/src/override/components/flows/blueprints/Blueprints.vue +++ b/ui/src/override/components/flows/blueprints/Blueprints.vue @@ -41,24 +41,26 @@ </template> <template #table> <el-card class="blueprint-card hoverable" v-for="blueprint in blueprints" @click="goToDetail(blueprint.id)"> - <div class="side"> - <div class="title"> - {{ blueprint.title }} + <component class="blueprint-link" :is="embed ? 'div' : 'router-link'" :to="embed ? undefined : {name: 'blueprints/view', params: {blueprintId: blueprint.id}}"> + <div class="side"> + <div class="title"> + {{ blueprint.title }} + </div> + <div class="tags text-uppercase"> + {{ tagsToString(blueprint.tags) }} + </div> + <div class="tasks-container"> + <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> + </div> </div> - <div class="tags text-uppercase"> - {{ tagsToString(blueprint.tags) }} + <div class="side buttons ms-auto"> + <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> + <el-button class="hoverable" @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> + {{ $t('copy') }} + </el-button> + </el-tooltip> </div> - <div class="tasks-container"> - <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> - </div> - </div> - <div class="side buttons ms-auto"> - <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> - <el-button class="hoverable" @click.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> - {{ $t('copy') }} - </el-button> - </el-tooltip> - </div> + </component> </el-card> </template> </data-table> @@ -67,6 +69,7 @@ <script> import RouteContext from "../../../../mixins/routeContext"; import DataTableActions from "../../../../mixins/dataTableActions"; + import RestoreUrl from "../../../../mixins/restoreUrl"; import SearchField from "../../../../components/layout/SearchField.vue"; import DataTable from "../../../../components/layout/DataTable.vue"; import BlueprintDetail from "../../../../components/flows/blueprints/BlueprintDetail.vue"; @@ -75,7 +78,7 @@ import TaskIcon from "../../../../components/plugins/TaskIcon.vue"; export default { - mixins: [DataTableActions, RouteContext], + mixins: [DataTableActions, RouteContext, RestoreUrl], inheritAttrs: false, components: { TaskIcon, @@ -104,8 +107,6 @@ goToDetail(blueprintId) { if (this.embed) { this.selectedBlueprintId = blueprintId; - } else { - this.$router.push({name: "blueprints/view", params: {blueprintId}}) } }, loadTags(beforeLoadBlueprintBaseUri) { diff --git a/ui/src/styles/components/blueprints/blueprints.scss b/ui/src/styles/components/blueprints/blueprints.scss index c9283afa9f..40ac5adeb9 100644 --- a/ui/src/styles/components/blueprints/blueprints.scss +++ b/ui/src/styles/components/blueprints/blueprints.scss @@ -107,64 +107,67 @@ border-bottom-right-radius: $border-radius; } - > :deep(.el-card__body) { + .blueprint-link { display: flex; - } - - .side { - margin: auto 0; + color: inherit; + text-decoration: inherit; + width: 100%; - &:first-child { - overflow: hidden; + .side { + margin: auto 0; - & > * { + &:first-child { overflow: hidden; - text-overflow: ellipsis; + + & > * { + overflow: hidden; + text-overflow: ellipsis; + } } - } - &.buttons { - white-space: nowrap; - } + &.buttons { + white-space: nowrap; + } - .title { - font-weight: bold; - font-size: $small-font-size; - } + .title { + font-weight: bold; + font-size: $small-font-size; + } - .tags { - font-family: $font-family-monospace; - font-weight: bold; - font-size: $sub-sup-font-size; - margin-bottom: calc(var(--spacer) / 2); - color: $primary; + .tags { + font-family: $font-family-monospace; + font-weight: bold; + font-size: $sub-sup-font-size; + margin-bottom: calc(var(--spacer) / 2); + color: $primary; - html.dark & { - color: $pink; + html.dark & { + color: $pink; + } } - } - .tasks-container { - $plugin-icon-size: calc(var(--font-size-base) + 0.4rem); + .tasks-container { + $plugin-icon-size: calc(var(--font-size-base) + 0.4rem); - display: flex; - flex-wrap: wrap; - flex-direction: column; - gap: calc(var(--spacer) / 4); - width: fit-content; - height: $plugin-icon-size; + display: flex; + flex-wrap: wrap; + flex-direction: column; + gap: calc(var(--spacer) / 4); + width: fit-content; + height: $plugin-icon-size; - :deep(> *) { - width: $plugin-icon-size; - padding: 0.2rem; - border-radius: $border-radius; + :deep(> *) { + width: $plugin-icon-size; + padding: 0.2rem; + border-radius: $border-radius; - html.dark & { - background-color: var(--bs-gray-900); - } + html.dark & { + background-color: var(--bs-gray-900); + } - & * { - margin-top: 0; + & * { + margin-top: 0; + } } } }
null
train
train
2023-06-22T14:34:11
"2023-06-21T07:37:37Z"
Ben8t
train
kestra-io/kestra/1468_1576
kestra-io/kestra
kestra-io/kestra/1468
kestra-io/kestra/1576
[ "keyword_pr_to_issue" ]
896777a05d5d37cade175117a1ada3294cdc1b30
ddd2793d74e01890163bb1de89f94e75197137af
[]
[]
"2023-06-21T15:21:43Z"
[ "bug", "frontend" ]
Execution stats are not refresh correctly
- have at least 2 flows with one without any execution - go on the flows list - go on the flow detail - hit new execution - go on the flows list - go on the flow detail for the one that don't have any executions - see the stats from the previous flows
[ "ui/src/components/home/Home.vue" ]
[ "ui/src/components/home/Home.vue" ]
[]
diff --git a/ui/src/components/home/Home.vue b/ui/src/components/home/Home.vue index d1b657be6a..d8c090b1a8 100644 --- a/ui/src/components/home/Home.vue +++ b/ui/src/components/home/Home.vue @@ -133,7 +133,6 @@ import action from "../../models/action"; import OnboardingBottom from "../onboarding/OnboardingBottom.vue"; import DateRange from "../layout/DateRange.vue"; - import {getFormat} from "../../utils/charts"; export default { mixins: [RouteContext, RestoreUrl], @@ -173,6 +172,10 @@ if (oldValue.name === newValue.name && newValue.query !== oldValue.query) { this.loadStats(); } + }, + flowId() { + this.loadStats(); + this.haveExecutions(); } }, data() {
null
train
train
2023-06-21T22:06:57
"2023-06-07T20:14:08Z"
tchiotludo
train
kestra-io/kestra/1579_1580
kestra-io/kestra
kestra-io/kestra/1579
kestra-io/kestra/1580
[ "keyword_pr_to_issue" ]
54ac36c7becbe65643938b1315bdbe3ab17c31ab
582d271c7cb176402b5337a5827203415268d85f
[]
[ "I don't think it's a good idea to add this in the Worker only for testing purpose.\r\nMoreover it's a memory leak as the list is never purged.", "I don't really understand why we don't have this mechanism already in place tbh. I think that's wrong to say that the Worker right now is closing himself, looks more like he is shutting down the whole app so imo we should have this and cancel our subscription instead of shutting down the topic, WDYT ?", "Here I did this for the tests since some tests need to be retried but their assert is in the receive method. So I have to stop this continuous assertion for the next test to work, but yeah I'm not a big fan either of adding test-specific code in production code.\r\nStill I think this should be a productionwise thing", "I didn't want to break anything here that's why I didn't add the cleanup in the worker itself but it should definitely be done I think", "Should be package private", "please add a comment explaining why it is needed to use it on tests" ]
"2023-06-21T17:45:56Z"
[ "bug" ]
[TESTING] Flaky log assertions
### Expected Behavior We should wait for specific logs since the log buffering is asynchronous due to the queue system. We need an util to assert it properly ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information // ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/runners/Worker.java", "core/src/main/java/io/kestra/core/utils/TestsUtils.java" ]
[ "core/src/main/java/io/kestra/core/runners/Worker.java", "core/src/main/java/io/kestra/core/utils/TestsUtils.java" ]
[ "core/src/test/java/io/kestra/core/runners/RunContextTest.java", "core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java", "core/src/test/java/io/kestra/core/runners/TestMethodScopedWorker.java", "core/src/test/java/io/kestra/core/schedulers/AbstractSchedulerTest.java", "core/src/test/java/io/kestra/core/schedulers/SchedulerThreadTest.java", "core/src/test/java/io/kestra/core/services/ConditionServiceTest.java", "core/src/test/java/io/kestra/core/tasks/flows/EachSequentialTest.java", "core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java", "core/src/test/java/io/kestra/core/tasks/flows/TimeoutTest.java", "core/src/test/java/io/kestra/core/tasks/flows/VariablesTest.java", "jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/runners/Worker.java b/core/src/main/java/io/kestra/core/runners/Worker.java index 567e5bde7a..881cf91231 100644 --- a/core/src/main/java/io/kestra/core/runners/Worker.java +++ b/core/src/main/java/io/kestra/core/runners/Worker.java @@ -7,46 +7,34 @@ import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.hash.Hashing; -import io.kestra.core.exceptions.InternalException; -import io.kestra.core.models.conditions.ConditionContext; -import io.kestra.core.models.executions.Execution; -import io.kestra.core.models.executions.MetricEntry; -import io.kestra.core.models.executions.TaskRun; -import io.kestra.core.models.flows.Flow; -import io.kestra.core.models.tasks.Task; -import io.kestra.core.tasks.flows.WorkingDirectory; -import io.kestra.core.services.WorkerGroupService; -import io.kestra.core.models.triggers.AbstractTrigger; -import io.kestra.core.models.triggers.PollingTriggerInterface; -import io.kestra.core.models.triggers.TriggerContext; -import io.micronaut.context.ApplicationContext; -import io.micronaut.core.annotation.Introspected; -import io.micronaut.inject.qualifiers.Qualifiers; -import lombok.Getter; -import lombok.NoArgsConstructor; -import lombok.Synchronized; -import lombok.experimental.SuperBuilder; -import lombok.extern.slf4j.Slf4j; -import net.jodah.failsafe.Failsafe; -import net.jodah.failsafe.Timeout; import io.kestra.core.exceptions.TimeoutExceededException; import io.kestra.core.metrics.MetricRegistry; -import io.kestra.core.models.executions.ExecutionKilled; -import io.kestra.core.models.executions.TaskRunAttempt; +import io.kestra.core.models.executions.*; import io.kestra.core.models.flows.State; import io.kestra.core.models.tasks.Output; import io.kestra.core.models.tasks.RunnableTask; +import io.kestra.core.models.tasks.Task; import io.kestra.core.models.tasks.retrys.AbstractRetry; +import io.kestra.core.models.triggers.PollingTriggerInterface; import io.kestra.core.queues.QueueException; import io.kestra.core.queues.QueueFactoryInterface; import io.kestra.core.queues.QueueInterface; import io.kestra.core.queues.WorkerTaskQueueInterface; import io.kestra.core.serializers.JacksonMapper; +import io.kestra.core.services.WorkerGroupService; +import io.kestra.core.tasks.flows.WorkingDirectory; import io.kestra.core.utils.Await; import io.kestra.core.utils.ExecutorsUtils; +import io.micronaut.context.ApplicationContext; +import io.micronaut.core.annotation.Introspected; +import io.micronaut.inject.qualifiers.Qualifiers; +import lombok.Getter; +import lombok.Synchronized; +import lombok.extern.slf4j.Slf4j; +import net.jodah.failsafe.Failsafe; +import net.jodah.failsafe.Timeout; import org.slf4j.Logger; -import java.io.Closeable; import java.io.IOException; import java.time.Duration; import java.time.ZonedDateTime; @@ -60,7 +48,7 @@ @Slf4j @Introspected -public class Worker implements Runnable, Closeable { +public class Worker implements Runnable, AutoCloseable { private final static ObjectMapper MAPPER = JacksonMapper.ofJson(); private final ApplicationContext applicationContext; @@ -74,7 +62,9 @@ public class Worker implements Runnable, Closeable { private final MetricRegistry metricRegistry; private final Set<String> killedExecution = ConcurrentHashMap.newKeySet(); - private final ExecutorService executors; + + // package private to allow its usage within tests + final ExecutorService executors; @Getter private final Map<Long, AtomicInteger> metricRunningCount = new ConcurrentHashMap<>(); @@ -113,7 +103,7 @@ public Worker(ApplicationContext applicationContext, int thread, String workerGr this.metricRegistry = applicationContext.getBean(MetricRegistry.class); ExecutorsUtils executorsUtils = applicationContext.getBean(ExecutorsUtils.class); - this.executors = executorsUtils.maxCachedThreadPool(thread,"worker"); + this.executors = executorsUtils.maxCachedThreadPool(thread, "worker"); WorkerGroupService workerGroupService = applicationContext.getBean(WorkerGroupService.class); this.workerGroup = workerGroupService.resolveGroupFromKey(workerGroupKey); @@ -165,8 +155,7 @@ public void run() { } finally { runContext.cleanup(); } - } - else { + } else { throw new RuntimeException("Unable to process the task '" + workerTask.getTask().getId() + "' as it's not a runnable task"); } }); @@ -412,7 +401,7 @@ private void logTerminated(WorkerTask workerTask) { ); } - private void logError(WorkerTrigger workerTrigger, Throwable e) { + private void logError(WorkerTrigger workerTrigger, Throwable e) { Logger logger = workerTrigger.getConditionContext().getRunContext().logger(); logger.warn( @@ -437,7 +426,7 @@ private WorkerTask runAttempt(WorkerTask workerTask) { Logger logger = runContext.logger(); - if(!(workerTask.getTask() instanceof RunnableTask)) { + if (!(workerTask.getTask() instanceof RunnableTask)) { // This should never happen but better to deal with it than crashing the Worker TaskRunAttempt attempt = TaskRunAttempt.builder().state(new State().withState(State.Type.FAILED)).build(); List<TaskRunAttempt> attempts = this.addAttempt(workerTask, attempt); @@ -545,18 +534,18 @@ public AtomicInteger getMetricRunningCount(WorkerTask workerTask) { @SuppressWarnings("ResultOfMethodCallIgnored") @Override - public void close() throws IOException { + public void close() throws Exception { workerTaskQueue.pause(); executionKilledQueue.pause(); new Thread( () -> { - try { - this.executors.shutdown(); - this.executors.awaitTermination(5, TimeUnit.MINUTES); - } catch (InterruptedException e) { - log.error("Failed to shutdown workers executors", e); - } - }, + try { + this.executors.shutdown(); + this.executors.awaitTermination(5, TimeUnit.MINUTES); + } catch (InterruptedException e) { + log.error("Failed to shutdown workers executors", e); + } + }, "worker-shutdown" ).start(); diff --git a/core/src/main/java/io/kestra/core/utils/TestsUtils.java b/core/src/main/java/io/kestra/core/utils/TestsUtils.java index 2e4f1857aa..9159ed871a 100644 --- a/core/src/main/java/io/kestra/core/utils/TestsUtils.java +++ b/core/src/main/java/io/kestra/core/utils/TestsUtils.java @@ -21,11 +21,12 @@ import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; +import java.time.Duration; import java.time.ZonedDateTime; -import java.util.AbstractMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; +import java.util.*; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Predicate; import java.util.stream.Collectors; abstract public class TestsUtils { @@ -55,6 +56,32 @@ public static List<LogEntry> filterLogs(List<LogEntry> logs, TaskRun taskRun) { .collect(Collectors.toList()); } + public static LogEntry awaitLog(List<LogEntry> logs, Predicate<LogEntry> logMatcher) { + List<LogEntry> matchingLogs = awaitLogs(logs, logMatcher, (Predicate<Integer>) null); + return matchingLogs.isEmpty() ? null : matchingLogs.get(0); + } + + public static List<LogEntry> awaitLogs(List<LogEntry> logs, Predicate<LogEntry> logMatcher, Integer exactCount) { + return awaitLogs(logs, logMatcher, exactCount::equals); + } + + public static List<LogEntry> awaitLogs(List<LogEntry> logs, Predicate<LogEntry> logMatcher, Predicate<Integer> countMatcher) { + AtomicReference<List<LogEntry>> matchingLogs = new AtomicReference<>(); + try { + Await.until(() -> { + matchingLogs.set(logs.stream().filter(logMatcher).collect(Collectors.toList())); + if(countMatcher == null){ + return !matchingLogs.get().isEmpty(); + } + + int matchingLogsCount = matchingLogs.get().size(); + return countMatcher.test(matchingLogsCount); + }, Duration.ofMillis(10), Duration.ofMillis(500)); + } catch (TimeoutException e) {} + + return matchingLogs.get(); + } + public static Flow mockFlow() { return TestsUtils.mockFlow(Thread.currentThread().getStackTrace()[2]); }
diff --git a/core/src/test/java/io/kestra/core/runners/RunContextTest.java b/core/src/test/java/io/kestra/core/runners/RunContextTest.java index 06ee5f74c0..a435faf3db 100644 --- a/core/src/test/java/io/kestra/core/runners/RunContextTest.java +++ b/core/src/test/java/io/kestra/core/runners/RunContextTest.java @@ -3,7 +3,6 @@ import io.kestra.core.metrics.MetricRegistry; import io.kestra.core.models.executions.Execution; import io.kestra.core.models.executions.LogEntry; -import io.kestra.core.models.executions.TaskRunAttempt; import io.kestra.core.models.executions.metrics.Counter; import io.kestra.core.models.executions.metrics.Timer; import io.kestra.core.models.flows.State; @@ -12,6 +11,8 @@ import io.kestra.core.storages.StorageInterface; import io.kestra.core.utils.TestsUtils; import io.micronaut.context.annotation.Property; +import jakarta.inject.Inject; +import jakarta.inject.Named; import org.exparity.hamcrest.date.ZonedDateTimeMatchers; import org.junit.jupiter.api.Test; import org.slf4j.event.Level; @@ -26,13 +27,9 @@ import java.util.*; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; -import java.util.stream.Collectors; -import jakarta.inject.Inject; -import jakarta.inject.Named; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; -import static org.hamcrest.number.OrderingComparison.greaterThan; @Property(name = "kestra.tasks.tmp-dir.path", value = "/tmp/sub/dir/tmp/") class RunContextTest extends AbstractMemoryRunnerTest { @@ -55,36 +52,35 @@ class RunContextTest extends AbstractMemoryRunnerTest { @Test void logs() throws TimeoutException { List<LogEntry> logs = new ArrayList<>(); - List<LogEntry> filters; + LogEntry matchingLog; workerTaskLogQueue.receive(logs::add); Execution execution = runnerUtils.runOne("io.kestra.tests", "logs"); assertThat(execution.getTaskRunList(), hasSize(3)); - filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(0)); - assertThat(filters, hasSize(1)); - assertThat(filters.get(0).getLevel(), is(Level.TRACE)); - assertThat(filters.get(0).getMessage(), is("first t1")); - - filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(1)); - assertThat(filters, hasSize(1)); - assertThat(filters.get(0).getLevel(), is(Level.WARN)); - assertThat(filters.get(0).getMessage(), is("second io.kestra.core.tasks.log.Log")); + matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(0).getId())); + assertThat(matchingLog, notNullValue()); + assertThat(matchingLog.getLevel(), is(Level.TRACE)); + assertThat(matchingLog.getMessage(), is("first t1")); + matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(1).getId())); + assertThat(matchingLog, notNullValue()); + assertThat(matchingLog.getLevel(), is(Level.WARN)); + assertThat(matchingLog.getMessage(), is("second io.kestra.core.tasks.log.Log")); - filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(2)); - assertThat(filters, hasSize(1)); - assertThat(filters.get(0).getLevel(), is(Level.ERROR)); - assertThat(filters.get(0).getMessage(), is("third logs")); + matchingLog = TestsUtils.awaitLog(logs, log -> Objects.equals(log.getTaskRunId(), execution.getTaskRunList().get(2).getId())); + assertThat(matchingLog, notNullValue()); + assertThat(matchingLog.getLevel(), is(Level.ERROR)); + assertThat(matchingLog.getMessage(), is("third logs")); } @Test - void inputsLarge() throws TimeoutException, InterruptedException { + void inputsLarge() throws TimeoutException { List<LogEntry> logs = new ArrayList<>(); workerTaskLogQueue.receive(logs::add); - char[] chars = new char[1024*11]; + char[] chars = new char[1024 * 11]; Arrays.fill(chars, 'a'); Map<String, String> inputs = new HashMap<>(InputsTest.inputs); @@ -101,12 +97,9 @@ void inputsLarge() throws TimeoutException, InterruptedException { assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); assertThat(execution.getTaskRunList().get(0).getState().getCurrent(), is(State.Type.SUCCESS)); - List<LogEntry> logEntries = logs.stream() - .filter(logEntry -> logEntry.getTaskRunId() != null && logEntry.getTaskRunId().equals(execution.getTaskRunList().get(1).getId())) - .sorted(Comparator.comparingLong(value -> value.getTimestamp().toEpochMilli())) - .collect(Collectors.toList()); + List<LogEntry> logEntries = TestsUtils.awaitLogs(logs, logEntry -> logEntry.getTaskRunId() != null && logEntry.getTaskRunId().equals(execution.getTaskRunList().get(1).getId()), count -> count > 1); + logEntries.sort(Comparator.comparingLong(value -> value.getTimestamp().toEpochMilli())); - Thread.sleep(100); assertThat(logEntries.get(0).getTimestamp().toEpochMilli() + 1, is(logEntries.get(1).getTimestamp().toEpochMilli())); } @@ -150,7 +143,7 @@ void largeInput() throws IOException, InterruptedException { p.destroy(); URI uri = runContext.putTempFile(path.toFile()); - assertThat(storageInterface.size(uri), is(size+1)); + assertThat(storageInterface.size(uri), is(size + 1)); } @Test diff --git a/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java b/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java index 9755880766..379b54d037 100644 --- a/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java +++ b/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java @@ -13,6 +13,7 @@ import io.kestra.core.queues.QueueFactoryInterface; import io.kestra.core.queues.QueueInterface; import io.kestra.core.services.GraphService; +import io.kestra.core.utils.TestsUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; @@ -22,6 +23,7 @@ import java.time.Duration; import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import java.util.stream.Stream; @@ -70,7 +72,8 @@ public void invalidTaskDefaults() throws TimeoutException { Execution execution = runnerUtils.runOne("io.kestra.tests", "invalid-task-defaults", Duration.ofSeconds(60)); assertThat(execution.getTaskRunList(), hasSize(1)); - assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().contains("Unrecognized field \"invalid\"")).count(), greaterThan(0L)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, log -> log.getMessage().contains("Unrecognized field \"invalid\"")); + assertThat(matchingLog, notNullValue()); } @SuperBuilder diff --git a/core/src/test/java/io/kestra/core/runners/TestMethodScopedWorker.java b/core/src/test/java/io/kestra/core/runners/TestMethodScopedWorker.java new file mode 100644 index 0000000000..9ab405e36b --- /dev/null +++ b/core/src/test/java/io/kestra/core/runners/TestMethodScopedWorker.java @@ -0,0 +1,25 @@ +package io.kestra.core.runners; + +import io.micronaut.context.ApplicationContext; + +import java.util.concurrent.TimeUnit; + +/** + * This worker is a special worker which won't close every queue allowing it to be ran and closed within a test without + * preventing the Micronaut context to be used for further tests with queues still being up + */ +public class TestMethodScopedWorker extends Worker { + public TestMethodScopedWorker(ApplicationContext applicationContext, int thread, String workerGroupKey) { + super(applicationContext, thread, workerGroupKey); + } + + /** + * Override is done to prevent closing the queue. However please note that this is not failsafe because we ideally need + * to stop worker's subscriptions to every queue before cutting of the executors pool. + */ + @Override + public void close() throws InterruptedException { + this.executors.shutdown(); + this.executors.awaitTermination(60, TimeUnit.SECONDS); + } +} \ No newline at end of file diff --git a/core/src/test/java/io/kestra/core/schedulers/AbstractSchedulerTest.java b/core/src/test/java/io/kestra/core/schedulers/AbstractSchedulerTest.java index 05353827cb..9a194332c0 100644 --- a/core/src/test/java/io/kestra/core/schedulers/AbstractSchedulerTest.java +++ b/core/src/test/java/io/kestra/core/schedulers/AbstractSchedulerTest.java @@ -2,16 +2,12 @@ import com.google.common.collect.ImmutableMap; import io.kestra.core.models.conditions.ConditionContext; -import io.kestra.core.models.flows.Input; -import io.kestra.core.models.flows.TaskDefault; -import io.kestra.core.models.flows.input.StringInput; -import io.micronaut.context.ApplicationContext; -import io.micronaut.test.extensions.junit5.annotation.MicronautTest; -import lombok.*; -import lombok.experimental.SuperBuilder; import io.kestra.core.models.executions.Execution; import io.kestra.core.models.flows.Flow; +import io.kestra.core.models.flows.Input; import io.kestra.core.models.flows.State; +import io.kestra.core.models.flows.TaskDefault; +import io.kestra.core.models.flows.input.StringInput; import io.kestra.core.models.triggers.AbstractTrigger; import io.kestra.core.models.triggers.PollingTriggerInterface; import io.kestra.core.models.triggers.TriggerContext; @@ -19,12 +15,19 @@ import io.kestra.core.queues.QueueInterface; import io.kestra.core.tasks.debugs.Return; import io.kestra.core.utils.IdUtils; +import io.micronaut.context.ApplicationContext; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import lombok.*; +import lombok.experimental.SuperBuilder; import java.time.Duration; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Optional; + import jakarta.inject.Inject; import jakarta.inject.Named; @@ -37,11 +40,11 @@ abstract public class AbstractSchedulerTest { @Named(QueueFactoryInterface.EXECUTION_NAMED) protected QueueInterface<Execution> executionQueue; - protected static Flow createFlow(List<AbstractTrigger> triggers) { + protected static Flow createFlow(List<AbstractTrigger> triggers) { return createFlow(triggers, null); } - protected static Flow createFlow(List<AbstractTrigger> triggers, List<TaskDefault> list) { + protected static Flow createFlow(List<AbstractTrigger> triggers, List<TaskDefault> list) { Flow.FlowBuilder<?, ?> flow = Flow.builder() .id(IdUtils.create()) .namespace("io.kestra.unittest") diff --git a/core/src/test/java/io/kestra/core/schedulers/SchedulerThreadTest.java b/core/src/test/java/io/kestra/core/schedulers/SchedulerThreadTest.java index 1b7e87ba86..ce4412bd2f 100644 --- a/core/src/test/java/io/kestra/core/schedulers/SchedulerThreadTest.java +++ b/core/src/test/java/io/kestra/core/schedulers/SchedulerThreadTest.java @@ -5,9 +5,10 @@ import io.kestra.core.models.flows.State; import io.kestra.core.models.flows.TaskDefault; import io.kestra.core.runners.FlowListeners; +import io.kestra.core.runners.TestMethodScopedWorker; import io.kestra.core.runners.Worker; import jakarta.inject.Inject; -import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.RetryingTest; import java.util.Collections; import java.util.List; @@ -46,7 +47,7 @@ public static Flow createThreadFlow() { )); } - @Test + @RetryingTest(5) void thread() throws Exception { // mock flow listeners FlowListeners flowListenersServiceSpy = spy(this.flowListenersService); @@ -64,21 +65,20 @@ void thread() throws Exception { .when(schedulerExecutionStateSpy) .findById(any()); - // start the worker as it execute polling triggers - Worker worker = new Worker(applicationContext, 8, null); - worker.run(); - // scheduler - try (AbstractScheduler scheduler = new DefaultScheduler( - applicationContext, - flowListenersServiceSpy, - schedulerExecutionStateSpy, - triggerState - )) { + try ( + AbstractScheduler scheduler = new DefaultScheduler( + applicationContext, + flowListenersServiceSpy, + schedulerExecutionStateSpy, + triggerState + ); + Worker worker = new TestMethodScopedWorker(applicationContext, 8, null); + ) { AtomicReference<Execution> last = new AtomicReference<>(); // wait for execution - executionQueue.receive(SchedulerThreadTest.class, execution -> { + Runnable assertionStop = executionQueue.receive(SchedulerThreadTest.class, execution -> { last.set(execution); assertThat(execution.getFlowId(), is(flow.getId())); @@ -89,8 +89,12 @@ void thread() throws Exception { } }); + // start the worker as it execute polling triggers + worker.run(); scheduler.run(); queueCount.await(1, TimeUnit.MINUTES); + // needed for RetryingTest to work since there is no context cleaning between method => we have to clear assertion receiver manually + assertionStop.run(); assertThat(last.get().getVariables().get("defaultInjected"), is("done")); assertThat(last.get().getVariables().get("counter"), is(3)); @@ -99,5 +103,4 @@ void thread() throws Exception { AbstractSchedulerTest.COUNTER = 0; } } - } diff --git a/core/src/test/java/io/kestra/core/services/ConditionServiceTest.java b/core/src/test/java/io/kestra/core/services/ConditionServiceTest.java index da6de410fd..ba212b093c 100644 --- a/core/src/test/java/io/kestra/core/services/ConditionServiceTest.java +++ b/core/src/test/java/io/kestra/core/services/ConditionServiceTest.java @@ -85,9 +85,7 @@ void exception() throws InterruptedException { conditionService.valid(flow, conditions, conditionContext); - Thread.sleep( 250); - - assertThat(logs.stream().filter(logEntry -> logEntry.getNamespace().equals("io.kestra.core.services.ConditionServiceTest")).count(), greaterThan(0L)); - assertThat(logs.stream().filter(logEntry -> logEntry.getFlowId().equals("exception")).count(), greaterThan(0L)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, logEntry -> logEntry.getNamespace().equals("io.kestra.core.services.ConditionServiceTest") && logEntry.getFlowId().equals("exception")); + assertThat(matchingLog, notNullValue()); } } diff --git a/core/src/test/java/io/kestra/core/tasks/flows/EachSequentialTest.java b/core/src/test/java/io/kestra/core/tasks/flows/EachSequentialTest.java index c9dfd78a04..ea00035541 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/EachSequentialTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/EachSequentialTest.java @@ -1,5 +1,6 @@ package io.kestra.core.tasks.flows; +import io.kestra.core.utils.TestsUtils; import org.junit.jupiter.api.Test; import io.kestra.core.exceptions.InternalException; import io.kestra.core.models.executions.Execution; @@ -95,7 +96,8 @@ public static void eachNullTest(RunnerUtils runnerUtils, QueueInterface<LogEntry assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); - assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().contains("Found '1' null values on Each, with values=[1, null, {key=my-key, value=my-value}]")).count(), greaterThan(0L)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, logEntry -> logEntry.getMessage().contains("Found '1' null values on Each, with values=[1, null, {key=my-key, value=my-value}]")); + assertThat(matchingLog, notNullValue()); } @Test diff --git a/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java b/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java index 439dbed4ed..664a935780 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/TemplateTest.java @@ -12,6 +12,7 @@ import io.kestra.core.runners.ListenersTest; import io.kestra.core.runners.RunnerUtils; import io.kestra.core.tasks.log.Log; +import io.kestra.core.utils.TestsUtils; import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.jupiter.api.Test; @@ -27,8 +28,7 @@ import java.util.concurrent.TimeoutException; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.hasSize; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; public class TemplateTest extends AbstractMemoryRunnerTest { @Inject @@ -65,7 +65,8 @@ public static void withTemplate(RunnerUtils runnerUtils, TemplateRepositoryInter assertThat(execution.getTaskRunList(), hasSize(4)); assertThat(execution.getState().getCurrent(), is(State.Type.SUCCESS)); - assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().equals("myString")).findFirst().orElseThrow().getLevel(), is(Level.ERROR)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, logEntry -> logEntry.getMessage().equals("myString") && logEntry.getLevel() == Level.ERROR); + assertThat(matchingLog, notNullValue()); } @Test @@ -84,7 +85,8 @@ public static void withFailedTemplate(RunnerUtils runnerUtils, TemplateRepositor assertThat(execution.getTaskRunList(), hasSize(1)); assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); - assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().equals("Can't find flow template 'io.kestra.tests.invalid'")).findFirst().orElseThrow().getLevel(), is(Level.ERROR)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, logEntry -> logEntry.getMessage().equals("Can't find flow template 'io.kestra.tests.invalid'") && logEntry.getLevel() == Level.ERROR); + assertThat(matchingLog, notNullValue()); } @Test diff --git a/core/src/test/java/io/kestra/core/tasks/flows/TimeoutTest.java b/core/src/test/java/io/kestra/core/tasks/flows/TimeoutTest.java index 50fc2c44d0..fe93ceb7ad 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/TimeoutTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/TimeoutTest.java @@ -11,6 +11,7 @@ import io.kestra.core.services.TaskDefaultService; import io.kestra.core.tasks.scripts.Bash; import io.kestra.core.utils.IdUtils; +import io.kestra.core.utils.TestsUtils; import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.jupiter.api.Test; @@ -22,7 +23,7 @@ import java.util.concurrent.TimeoutException; import static org.hamcrest.MatcherAssert.assertThat; -import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.*; class TimeoutTest extends AbstractMemoryRunnerTest { @Inject @@ -57,6 +58,7 @@ void timeout() throws TimeoutException { Execution execution = runnerUtils.runOne(flow.getNamespace(), flow.getId()); assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); - assertThat(logs.stream().filter(logEntry -> logEntry.getMessage().contains("Timeout")).count(), is(2L)); + List<LogEntry> matchingLogs = TestsUtils.awaitLogs(logs, logEntry -> logEntry.getMessage().contains("Timeout"), 2); + assertThat(matchingLogs.size(), is(2)); } } diff --git a/core/src/test/java/io/kestra/core/tasks/flows/VariablesTest.java b/core/src/test/java/io/kestra/core/tasks/flows/VariablesTest.java index 62d9009314..2fde7e8bb2 100644 --- a/core/src/test/java/io/kestra/core/tasks/flows/VariablesTest.java +++ b/core/src/test/java/io/kestra/core/tasks/flows/VariablesTest.java @@ -11,6 +11,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Objects; import java.util.concurrent.TimeoutException; import jakarta.inject.Inject; @@ -46,11 +47,14 @@ void invalidVars() throws TimeoutException { Execution execution = runnerUtils.runOne("io.kestra.tests", "variables-invalid"); - List<LogEntry> filters = TestsUtils.filterLogs(logs, execution.getTaskRunList().get(1)); assertThat(execution.getTaskRunList(), hasSize(2)); assertThat(execution.getTaskRunList().get(1).getState().getCurrent(), is(State.Type.FAILED)); - assertThat(filters.stream().filter(logEntry -> logEntry.getMessage().contains("Missing variable: 'inputs' on '{{inputs.invalid}}'")).count(), greaterThan(0L)); + LogEntry matchingLog = TestsUtils.awaitLog(logs, logEntry -> + Objects.equals(logEntry.getTaskRunId(), execution.getTaskRunList().get(1).getId()) && + logEntry.getMessage().contains("Missing variable: 'inputs' on '{{inputs.invalid}}'") + ); + assertThat(matchingLog, notNullValue()); assertThat(execution.getState().getCurrent(), is(State.Type.FAILED)); } diff --git a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java index d524b1271b..4c0151ab57 100644 --- a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java +++ b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java @@ -15,9 +15,9 @@ import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.jupiter.api.BeforeAll; -import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; +import org.junitpioneer.jupiter.RetryingTest; import java.io.IOException; import java.net.URISyntaxException; @@ -116,7 +116,7 @@ void parallel() throws TimeoutException, QueueException { assertThat(execution.getTaskRunList(), hasSize(8)); } - @Test + @RetryingTest(5) void parallelNested() throws TimeoutException, QueueException { Execution execution = runnerUtils.runOne("io.kestra.tests", "parallel-nested", null, null, Duration.ofSeconds(60));
train
train
2023-06-22T23:06:59
"2023-06-21T17:43:58Z"
brian-mulier-p
train
kestra-io/kestra/1464_1586
kestra-io/kestra
kestra-io/kestra/1464
kestra-io/kestra/1586
[ "keyword_pr_to_issue" ]
767e1fb4209874623e6d8b951f0b9bc909f21dbf
4c9589667bc0b3b97519905cbf7f6fbc9fddf65a
[ "Agree, linked to #1399 ", "It seems that your page miss the title, that's the root of the issue" ]
[]
"2023-06-22T09:40:17Z"
[ "bug" ]
Minor bug: the onboarding tour window doesn't close after "Save" flow step
### Expected Behavior _No response_ ### Actual Behaviour ![image](https://github.com/kestra-io/kestra/assets/86264395/2f91a86f-9e1d-495a-aad8-6af878cf15ed) could be just window placement, after clicking Execute now, the window is back ![image](https://github.com/kestra-io/kestra/assets/86264395/2ebaee89-b62f-4f6e-ad82-6f4ff731e995) An easy fix would be to finish the tour after the Save step - instead of "Save" it could be "Save and execute the flow" maybe? @Ben8t ### Environment Information - Kestra Version: latest 0.9.3 ### Example flow _No response_
[ "ui/src/components/onboarding/VueTour.vue" ]
[ "ui/src/components/onboarding/VueTour.vue" ]
[]
diff --git a/ui/src/components/onboarding/VueTour.vue b/ui/src/components/onboarding/VueTour.vue index 6610cc0f93..212df802e4 100644 --- a/ui/src/components/onboarding/VueTour.vue +++ b/ui/src/components/onboarding/VueTour.vue @@ -277,7 +277,7 @@ this.dispatchEvent(this.$tours["guidedTour"].currentStep._value, "created") setTimeout(() => { resolve(true); - }, 300); + }, 500); }), }, { @@ -294,7 +294,7 @@ localStorage.setItem("tourDoneOrSkip", "true"); setTimeout(() => { resolve(true); - }, 300); + }, 500); }), } ],
null
val
train
2023-06-22T09:18:49
"2023-06-06T14:00:49Z"
anna-geller
train
kestra-io/kestra/1592_1593
kestra-io/kestra
kestra-io/kestra/1592
kestra-io/kestra/1593
[ "keyword_pr_to_issue" ]
e786f1b8598e906870b9f06810dcbb9a1016cb37
e28a0e24ca251608a3e03ad4d303ac08d04b18c4
[]
[]
"2023-06-22T14:14:54Z"
[]
PR build should build the JavDoc
### Issue description PR build should build the JavDoc to avoid merging PR that will crash the build on master as it builds the JavaDoc.
[ ".github/workflows/main.yml", "build.gradle" ]
[ ".github/workflows/main.yml", "build.gradle" ]
[ "jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java", "webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java" ]
diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml index 542efa225e..1b1cb43d0d 100644 --- a/.github/workflows/main.yml +++ b/.github/workflows/main.yml @@ -91,7 +91,7 @@ jobs: python3 -m pip install virtualenv echo $GOOGLE_SERVICE_ACCOUNT | base64 -d > ~/.gcp-service-account.json export GOOGLE_APPLICATION_CREDENTIALS=$HOME/.gcp-service-account.json - ./gradlew check jacoco --no-daemon --priority=normal + ./gradlew check jacoco javadoc --no-daemon --priority=normal # Codecov - uses: codecov/codecov-action@v3 diff --git a/build.gradle b/build.gradle index dc057b2e59..c37ecf0c06 100644 --- a/build.gradle +++ b/build.gradle @@ -349,6 +349,7 @@ subprojects { options { locale = 'en_US' encoding = 'UTF-8' + addStringOption("Xdoclint:none", "-quiet") } }
diff --git a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java index 4c0151ab57..51ae829afb 100644 --- a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java +++ b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java @@ -15,6 +15,7 @@ import jakarta.inject.Inject; import jakarta.inject.Named; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.RepeatedTest; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.junitpioneer.jupiter.RetryingTest; @@ -179,7 +180,7 @@ void withTemplate() throws Exception { TemplateTest.withTemplate(runnerUtils, templateRepository, repositoryLoader, logsQueue); } - @Test + @RetryingTest(5) void withFailedTemplate() throws Exception { TemplateTest.withFailedTemplate(runnerUtils, templateRepository, repositoryLoader, logsQueue); } diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java index e5a7a4d195..32d2c0935c 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java @@ -241,7 +241,7 @@ void restartFromUnknownTaskId() throws TimeoutException { assertThat(e.getResponse().getBody(String.class).get(), containsString("No task found")); } - @Test + @RetryingTest(5) void restartWithNoFailure() throws TimeoutException { final String flowId = "restart_with_inputs";
train
train
2023-06-28T12:22:10
"2023-06-22T13:41:52Z"
loicmathieu
train
kestra-io/kestra/1594_1597
kestra-io/kestra
kestra-io/kestra/1594
kestra-io/kestra/1597
[ "keyword_pr_to_issue" ]
ce3dbc3058c37ed2b3bee88aab867d507a8ea6d6
c10a83ba2c39e51ddff9721ef8b79c8289ea2350
[]
[]
"2023-06-22T15:25:37Z"
[ "bug" ]
Blueprint title overlap with editor views button
### Expected Behavior _No response_ ### Actual Behaviour ![image](https://github.com/kestra-io/kestra/assets/46634684/8cbc4911-8bb0-4f1e-8d4f-9fb13453186b) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue" ]
[ "ui/src/components/flows/blueprints/BlueprintDetail.vue" ]
[]
diff --git a/ui/src/components/flows/blueprints/BlueprintDetail.vue b/ui/src/components/flows/blueprints/BlueprintDetail.vue index 9687cd7e6e..5359708886 100644 --- a/ui/src/components/flows/blueprints/BlueprintDetail.vue +++ b/ui/src/components/flows/blueprints/BlueprintDetail.vue @@ -164,6 +164,10 @@ .header-wrapper { margin-bottom: $spacer; + .el-card & { + margin-top: 2.5rem; + } + .header { margin-bottom: calc(var(--spacer) * 0.5);
null
test
train
2023-06-22T15:41:46
"2023-06-22T14:44:34Z"
Ben8t
train
kestra-io/kestra/1438_1601
kestra-io/kestra
kestra-io/kestra/1438
kestra-io/kestra/1601
[ "keyword_pr_to_issue" ]
54ac36c7becbe65643938b1315bdbe3ab17c31ab
6034f3a5031c4c81785154a555dc4ba54e4921be
[]
[]
"2023-06-23T10:14:46Z"
[ "bug", "frontend" ]
Backend error on save don't provide any feedback on ui
![image](https://github.com/kestra-io/kestra/assets/2064609/6e0d5aaa-5cfb-42c0-960c-df92d6a93f97)
[ "ui/src/utils/axios.js" ]
[ "ui/src/utils/axios.js" ]
[]
diff --git a/ui/src/utils/axios.js b/ui/src/utils/axios.js index d2f52880af..a6eed9c48d 100644 --- a/ui/src/utils/axios.js +++ b/ui/src/utils/axios.js @@ -76,7 +76,7 @@ export default (callback, store, router) => { response => { return response }, errorResponse => { - if (errorResponse.code && errorResponse.code === "ECONNABORTED") { + if (errorResponse.code && (errorResponse.code === "ECONNABORTED" || errorResponse.code === "ERR_BAD_RESPONSE")) { store.dispatch("core/showMessage", { response: errorResponse, content: errorResponse,
null
train
train
2023-06-22T23:06:59
"2023-05-31T14:16:14Z"
tchiotludo
train
kestra-io/kestra/1562_1602
kestra-io/kestra
kestra-io/kestra/1562
kestra-io/kestra/1602
[ "keyword_pr_to_issue" ]
54ac36c7becbe65643938b1315bdbe3ab17c31ab
4802ca3cb1d658cf20476b82570041b45c71326e
[]
[]
"2023-06-23T10:42:36Z"
[ "frontend" ]
Allow to pass execution labels via web UI
### Feature description Users should be able to pass execution labels through the web UI. The labels might be passed via the existing `TriggerFlow` modal. ```[tasklist] ### Tasks ```
[ "ui/src/components/flows/FlowRun.vue", "ui/src/components/flows/TriggerFlow.vue", "ui/src/components/labels/LabelFilter.vue", "ui/src/stores/executions.js", "ui/src/translations.json" ]
[ "ui/src/components/flows/FlowRun.vue", "ui/src/components/flows/TriggerFlow.vue", "ui/src/components/labels/LabelFilter.vue", "ui/src/stores/executions.js", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/flows/FlowRun.vue b/ui/src/components/flows/FlowRun.vue index ea2584bf03..ff230ed36a 100644 --- a/ui/src/components/flows/FlowRun.vue +++ b/ui/src/components/flows/FlowRun.vue @@ -4,7 +4,8 @@ <strong>{{ $t('disabled flow title') }}</strong><br> {{ $t('disabled flow desc') }} </el-alert> - <el-form label-position="top" :model="inputs" ref="form"> + + <el-form label-position="top" :model="inputs" ref="form" @submit.prevent> <el-form-item v-for="input in flow.inputs || []" :key="input.id" @@ -60,8 +61,10 @@ autocomplete="off" :style="{display: typeof(inputs[input.name]) === 'string' && inputs[input.name].startsWith('kestra:///') ? 'none': ''}" > - <label v-if="typeof(inputs[input.name]) === 'string' && inputs[input.name].startsWith('kestra:///')" - :for="input.name+'-file'">Kestra Internal Storage File</label> + <label + v-if="typeof(inputs[input.name]) === 'string' && inputs[input.name].startsWith('kestra:///')" + :for="input.name+'-file'" + >Kestra Internal Storage File</label> </div> </div> <editor @@ -75,6 +78,13 @@ <small v-if="input.description" class="text-muted">{{ input.description }}</small> </el-form-item> + <el-form-item + :label="$t('execution labels')" + > + <label-filter + v-model:model-value="executionLabels" + /> + </el-form-item> <div class="bottom-buttons"> <div class="left-align"> <el-form-item> @@ -85,7 +95,7 @@ </div> <div class="right-align"> <el-form-item class="submit"> - <el-button :icon="Flash" class="flow-run-trigger-button" @click="onSubmit($refs.form)" type="primary" :disabled="flow.disabled"> + <el-button :icon="Flash" class="flow-run-trigger-button" @click="onSubmit($refs.form)" type="primary" :disabled="flow.disabled || haveBadLabels"> {{ $t('launch execution') }} </el-button> </el-form-item> @@ -104,10 +114,11 @@ import {mapState} from "vuex"; import {executeTask} from "../../utils/submitTask" import Editor from "../../components/inputs/Editor.vue"; + import LabelFilter from "../../components/labels/LabelFilter.vue"; import {pageFromRoute} from "../../utils/eventsRouter"; export default { - components: {Editor}, + components: {Editor, LabelFilter}, props: { redirect: { type: Boolean, @@ -116,7 +127,10 @@ }, data() { return { - inputs: {} + inputs: {}, + inputNewLabel: "", + executionLabels: [], + inputVisible: false }; }, emits: ["executionTrigger"], @@ -153,8 +167,14 @@ ...mapState("flow", ["flow"]), ...mapState("core", ["guidedProperties"]), ...mapState("execution", ["execution"]), + haveBadLabels() { + return this.executionLabels.some(label => label.split(":").length !== 2) + } }, methods: { + isBadLabel(tag) { + return tag.split(":").length !== 2 + }, fillInputsFromExecution(){ const nonEmptyInputNames = Object.keys(this.execution.inputs); this.inputs = Object.fromEntries( @@ -163,11 +183,11 @@ const inputName = input.name; const inputType = input.type; let inputValue = this.execution.inputs[inputName]; - if (inputType === 'DATE' || inputType === 'DATETIME') { + if (inputType === "DATE" || inputType === "DATETIME") { inputValue = this.$moment(inputValue).toISOString() - }else if (inputType === 'DURATION' || inputType === 'TIME') { + }else if (inputType === "DURATION" || inputType === "TIME") { inputValue = this.$moment().startOf("day").add(inputValue, "seconds").toString() - }else if (inputType === 'JSON') { + }else if (inputType === "JSON") { inputValue = JSON.stringify(inputValue).toString() } @@ -188,7 +208,8 @@ executeTask(this, this.flow, this.inputs, { redirect: this.redirect, id: this.flow.id, - namespace: this.flow.namespace + namespace: this.flow.namespace, + labels: this.executionLabels }) this.$emit("executionTrigger"); }); @@ -250,6 +271,19 @@ } return true; + }, + handleClose(label) { + this.executionLabels.splice(this.executionLabels.indexOf(label), 1) + }, + showInput() { + this.inputVisible = true; + }, + handleInputConfirm() { + if (this.inputNewLabel) { + this.executionLabels.push(this.inputNewLabel) + } + this.inputVisible = false + this.inputNewLabel = "" } }, watch: { @@ -285,5 +319,6 @@ .right-align :deep(div) { flex-direction: row-reverse; } + } </style> \ No newline at end of file diff --git a/ui/src/components/flows/TriggerFlow.vue b/ui/src/components/flows/TriggerFlow.vue index 5f65ab7369..f9bc660afc 100644 --- a/ui/src/components/flows/TriggerFlow.vue +++ b/ui/src/components/flows/TriggerFlow.vue @@ -16,11 +16,9 @@ <script> import FlowRun from "./FlowRun.vue"; import {mapState} from "vuex"; - import {executeTask} from "../../utils/submitTask" import Flash from "vue-material-design-icons/Flash.vue"; import {shallowRef} from "vue"; import {pageFromRoute} from "../../utils/eventsRouter"; - import action from "../../models/action"; export default { components: { @@ -76,20 +74,7 @@ this.$tours["guidedTour"].nextStep(); return; } - - if (!this.flow.inputs || this.flow.inputs.length === 0) { - this.$toast().confirm( - this.$t("execute flow now ?"), - () => executeTask(this, this.flow, {}, { - id: this.flowId, - namespace: this.namespace, - redirect: true - }), - () => this.isOpen = false - ) - } else { - this.isOpen = !this.isOpen - } + this.isOpen = !this.isOpen }, closeModal() { diff --git a/ui/src/components/labels/LabelFilter.vue b/ui/src/components/labels/LabelFilter.vue index 14bbfa2128..afea33abad 100644 --- a/ui/src/components/labels/LabelFilter.vue +++ b/ui/src/components/labels/LabelFilter.vue @@ -6,7 +6,7 @@ filterable allow-create clearable - collapse-tags + :collapse-tags="collapseTags" default-first-option :persistent="false" :reserve-keyword="false" diff --git a/ui/src/stores/executions.js b/ui/src/stores/executions.js index 2b24d2f923..a293f9b544 100644 --- a/ui/src/stores/executions.js +++ b/ui/src/stores/executions.js @@ -94,6 +94,9 @@ export default { timeout: 60 * 60 * 1000, headers: { "content-type": "multipart/form-data" + }, + params: { + labels: options.labels ?? [] } }) }, diff --git a/ui/src/translations.json b/ui/src/translations.json index e83c85b869..a96739f6fd 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -260,6 +260,7 @@ "label": "Label", "labels": "Labels", "label filter placeholder": "Label as 'key:value'", + "execution labels": "Execution labels", "feeds": { "title": "What's new at Kestra" }, @@ -711,6 +712,7 @@ "label": "Label", "labels": "Labels", "label filter placeholder": "Label as 'key:value'", + "execution labels": "Labels d'exécution", "feeds": { "title": "Quoi de neuf sur Kestra" },
null
train
train
2023-06-22T23:06:59
"2023-06-20T12:06:30Z"
yuri1969
train
kestra-io/kestra/1606_1609
kestra-io/kestra
kestra-io/kestra/1606
kestra-io/kestra/1609
[ "keyword_pr_to_issue" ]
4802ca3cb1d658cf20476b82570041b45c71326e
77851d153d48957828b0f6abfdde973971d55528
[]
[]
"2023-06-23T17:15:30Z"
[ "frontend" ]
Blueprint Improvement (3)
### Feature description - [ ] task icons in editor view should have the same background [as in Figma ](https://www.figma.com/file/4tLhsoCsh9yVzYRY1N70kS/App-Kestra?type=design&node-id=147-784&mode=design&t=ggl0xR6zBXTpP1De-0) - [ ] tasks icon in standalone should be on the right side of the source code ([like in figma](https://www.figma.com/file/4tLhsoCsh9yVzYRY1N70kS/App-Kestra?type=design&node-id=147-784&mode=design&t=ggl0xR6zBXTpP1De-0)) to fill large space allowed in this screen - [ ] Space between Source title and editor in light theme is too big (in light theme the editor doesn't have borders...) - [ ] topology is not vertically aligned + it should be horizontal by default in the standalone view - [x] Keep filters when going back from Blueprint detail - [x] Weird border on left of "All Tags" when another tag is selected
[ "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue" ]
[ "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue" ]
[]
diff --git a/ui/src/override/components/flows/blueprints/Blueprints.vue b/ui/src/override/components/flows/blueprints/Blueprints.vue index 4493bf0f67..1922590001 100644 --- a/ui/src/override/components/flows/blueprints/Blueprints.vue +++ b/ui/src/override/components/flows/blueprints/Blueprints.vue @@ -2,12 +2,11 @@ <blueprints-page-header v-if="!embed" /> <div class="main-container" v-bind="$attrs"> <blueprint-detail v-if="selectedBlueprintId" :embed="embed" :blueprint-id="selectedBlueprintId" @back="selectedBlueprintId = undefined" /> - <blueprints-browser v-else :embed="embed" blueprint-base-uri="/api/v1/blueprints/community" @go-to-detail="blueprintId => selectedBlueprintId = blueprintId"/> + <blueprints-browser :class="{'d-none': !!selectedBlueprintId}" :embed="embed" blueprint-base-uri="/api/v1/blueprints/community" @go-to-detail="blueprintId => selectedBlueprintId = blueprintId" /> </div> </template> <script> import RouteContext from "../../../../mixins/routeContext"; - import RestoreUrl from "../../../../mixins/restoreUrl"; import SearchField from "../../../../components/layout/SearchField.vue"; import DataTable from "../../../../components/layout/DataTable.vue"; import BlueprintDetail from "../../../../components/flows/blueprints/BlueprintDetail.vue"; @@ -16,7 +15,7 @@ import TaskIcon from "../../../../components/plugins/TaskIcon.vue"; export default { - mixins: [RouteContext, RestoreUrl], + mixins: [RouteContext], inheritAttrs: false, components: { TaskIcon, @@ -31,9 +30,6 @@ selectedBlueprintId: undefined } }, - async created() { - this.selectedTag = this.$route?.query?.selectedTag ?? 0; - }, props: { embed: { type: Boolean, diff --git a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue index abdd9bd0fc..fedeb8c119 100644 --- a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue +++ b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue @@ -1,59 +1,61 @@ <template> - <data-table class="blueprints" @page-changed="onPageChanged" ref="dataTable" :total="total" divider> - <template #navbar> - <div class="d-flex sub-nav"> - <slot name="nav" /> - <el-form-item> - <search-field :embed="embed" placeholder="search blueprint" @search="s => q = s" /> - </el-form-item> - </div> - <el-radio-group v-if="ready" v-model="selectedTag" class="tags-selection"> - <el-radio-button - :key="0" - :label="0" - class="hoverable" - > - {{ $t("all tags") }} - </el-radio-button> - <el-radio-button - v-for="tag in Object.values(tags)" - :key="tag.id" - :label="tag.id" - class="hoverable" - > - {{ tag.name }} - </el-radio-button> - </el-radio-group> - - <el-divider /> - </template> - <template #table> - <el-card class="blueprint-card hoverable" v-for="blueprint in blueprints" @click="goToDetail(blueprint.id)"> - <component class="blueprint-link" :is="embed ? 'div' : 'router-link'" :to="embed ? undefined : {name: 'blueprints/view', params: {blueprintId: blueprint.id}}"> - <div class="side"> - <div class="title"> - {{ blueprint.title }} + <div> + <data-table class="blueprints" @page-changed="onPageChanged" ref="dataTable" :total="total" divider> + <template #navbar> + <div class="d-flex sub-nav"> + <slot name="nav" /> + <el-form-item> + <search-field :embed="embed" placeholder="search blueprint" @search="s => q = s" /> + </el-form-item> + </div> + <el-radio-group v-if="ready" v-model="selectedTag" class="tags-selection"> + <el-radio-button + :key="0" + :label="0" + class="hoverable" + > + {{ $t("all tags") }} + </el-radio-button> + <el-radio-button + v-for="tag in Object.values(tags)" + :key="tag.id" + :label="tag.id" + class="hoverable" + > + {{ tag.name }} + </el-radio-button> + </el-radio-group> + + <el-divider /> + </template> + <template #table> + <el-card class="blueprint-card hoverable" v-for="blueprint in blueprints" @click="goToDetail(blueprint.id)"> + <component class="blueprint-link" :is="embed ? 'div' : 'router-link'" :to="embed ? undefined : {name: 'blueprints/view', params: {blueprintId: blueprint.id}}"> + <div class="side"> + <div class="title"> + {{ blueprint.title }} + </div> + <div class="tags text-uppercase"> + {{ tagsToString(blueprint.tags) }} + </div> + <div class="tasks-container"> + <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> + </div> </div> - <div class="tags text-uppercase"> - {{ tagsToString(blueprint.tags) }} + <div class="side buttons ms-auto"> + <slot name="buttons" :blueprint="blueprint" /> + <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> + <el-button class="hoverable" @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> + {{ $t('copy') }} + </el-button> + </el-tooltip> </div> - <div class="tasks-container"> - <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> - </div> - </div> - <div class="side buttons ms-auto"> - <slot name="buttons" :blueprint="blueprint" /> - <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> - <el-button class="hoverable" @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> - {{ $t('copy') }} - </el-button> - </el-tooltip> - </div> - </component> - </el-card> - </template> - </data-table> - <slot name="bottom-bar" /> + </component> + </el-card> + </template> + </data-table> + <slot name="bottom-bar" /> + </div> </template> <script> @@ -63,9 +65,10 @@ import DataTableActions from "../../../../mixins/dataTableActions"; import {shallowRef} from "vue"; import ContentCopy from "vue-material-design-icons/ContentCopy.vue"; + import RestoreUrl from "../../../../mixins/restoreUrl"; export default { - mixins: [DataTableActions], + mixins: [RestoreUrl, DataTableActions], components: {TaskIcon, DataTable, SearchField}, emits: ["goToDetail"], props: { @@ -85,7 +88,7 @@ data() { return { q: undefined, - selectedTag: 0, + selectedTag: this.initSelectedTag(), tags: undefined, blueprints: undefined, total: 0, @@ -95,6 +98,9 @@ } }, methods: { + initSelectedTag() { + return this.$route?.query?.selectedTag ?? 0 + }, async copy(blueprintId) { await navigator.clipboard.writeText( (await this.$http.get(`${this.blueprintBaseUri}/${blueprintId}/flow`)).data @@ -135,8 +141,8 @@ } - if (this.$route.query.tags || this.selectedTag) { - query.tags = this.$route.query.tags || this.selectedTag; + if (this.$route.query.selectedTag || this.selectedTag) { + query.tags = this.$route.query.selectedTag || this.selectedTag; } return this.$http @@ -178,6 +184,11 @@ } }, watch: { + $route(newValue, oldValue) { + if (oldValue.name === newValue.name) { + this.selectedTag = this.initSelectedTag(); + } + }, q() { if (this.embed) { this.load(this.onDataLoaded); @@ -264,7 +275,7 @@ // Embedded tabs looks weird without cancelling the margin (this brings a top-left tabs with bottom-right search) - > :nth-child(1){ + > :nth-child(1) { margin-top: calc(-1.5 * var(--spacer)); } } @@ -374,8 +385,8 @@ flex: 1; :deep(span) { - border: 1px solid var(--bs--gray-300); - border-radius: $border-radius; + border: none !important; + border-radius: $border-radius !important; width: 100%; font-weight: bold; box-shadow: none;
null
train
train
2023-06-23T18:10:11
"2023-06-23T15:11:27Z"
Ben8t
train
kestra-io/kestra/1608_1609
kestra-io/kestra
kestra-io/kestra/1608
kestra-io/kestra/1609
[ "keyword_pr_to_issue" ]
4802ca3cb1d658cf20476b82570041b45c71326e
77851d153d48957828b0f6abfdde973971d55528
[]
[]
"2023-06-23T17:15:30Z"
[ "bug" ]
Pagination component doesn't work properly with RestoreUrl
### Expected Behavior _No response_ ### Actual Behaviour When changing page or size for eg. from a pagination component with restoreUrl feature (for eg. being on page 2) If I go away and come back on this component I get a wrong visual feedback: my data loaded page 2 but the pagination component displays that it is on page 1. Due to loading state from route only when creating component which cannot work as restoreUrl asks router to add query params which takes place after component creation. Must also watch route to update it accordingly ### Steps To Reproduce go to Logs, page 2 go to another tab come back to Logs and looks like it's on page 1 while query param says page 2 and data is loaded from page 2 ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue" ]
[ "ui/src/override/components/flows/blueprints/Blueprints.vue", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue" ]
[]
diff --git a/ui/src/override/components/flows/blueprints/Blueprints.vue b/ui/src/override/components/flows/blueprints/Blueprints.vue index 4493bf0f67..1922590001 100644 --- a/ui/src/override/components/flows/blueprints/Blueprints.vue +++ b/ui/src/override/components/flows/blueprints/Blueprints.vue @@ -2,12 +2,11 @@ <blueprints-page-header v-if="!embed" /> <div class="main-container" v-bind="$attrs"> <blueprint-detail v-if="selectedBlueprintId" :embed="embed" :blueprint-id="selectedBlueprintId" @back="selectedBlueprintId = undefined" /> - <blueprints-browser v-else :embed="embed" blueprint-base-uri="/api/v1/blueprints/community" @go-to-detail="blueprintId => selectedBlueprintId = blueprintId"/> + <blueprints-browser :class="{'d-none': !!selectedBlueprintId}" :embed="embed" blueprint-base-uri="/api/v1/blueprints/community" @go-to-detail="blueprintId => selectedBlueprintId = blueprintId" /> </div> </template> <script> import RouteContext from "../../../../mixins/routeContext"; - import RestoreUrl from "../../../../mixins/restoreUrl"; import SearchField from "../../../../components/layout/SearchField.vue"; import DataTable from "../../../../components/layout/DataTable.vue"; import BlueprintDetail from "../../../../components/flows/blueprints/BlueprintDetail.vue"; @@ -16,7 +15,7 @@ import TaskIcon from "../../../../components/plugins/TaskIcon.vue"; export default { - mixins: [RouteContext, RestoreUrl], + mixins: [RouteContext], inheritAttrs: false, components: { TaskIcon, @@ -31,9 +30,6 @@ selectedBlueprintId: undefined } }, - async created() { - this.selectedTag = this.$route?.query?.selectedTag ?? 0; - }, props: { embed: { type: Boolean, diff --git a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue index abdd9bd0fc..fedeb8c119 100644 --- a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue +++ b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue @@ -1,59 +1,61 @@ <template> - <data-table class="blueprints" @page-changed="onPageChanged" ref="dataTable" :total="total" divider> - <template #navbar> - <div class="d-flex sub-nav"> - <slot name="nav" /> - <el-form-item> - <search-field :embed="embed" placeholder="search blueprint" @search="s => q = s" /> - </el-form-item> - </div> - <el-radio-group v-if="ready" v-model="selectedTag" class="tags-selection"> - <el-radio-button - :key="0" - :label="0" - class="hoverable" - > - {{ $t("all tags") }} - </el-radio-button> - <el-radio-button - v-for="tag in Object.values(tags)" - :key="tag.id" - :label="tag.id" - class="hoverable" - > - {{ tag.name }} - </el-radio-button> - </el-radio-group> - - <el-divider /> - </template> - <template #table> - <el-card class="blueprint-card hoverable" v-for="blueprint in blueprints" @click="goToDetail(blueprint.id)"> - <component class="blueprint-link" :is="embed ? 'div' : 'router-link'" :to="embed ? undefined : {name: 'blueprints/view', params: {blueprintId: blueprint.id}}"> - <div class="side"> - <div class="title"> - {{ blueprint.title }} + <div> + <data-table class="blueprints" @page-changed="onPageChanged" ref="dataTable" :total="total" divider> + <template #navbar> + <div class="d-flex sub-nav"> + <slot name="nav" /> + <el-form-item> + <search-field :embed="embed" placeholder="search blueprint" @search="s => q = s" /> + </el-form-item> + </div> + <el-radio-group v-if="ready" v-model="selectedTag" class="tags-selection"> + <el-radio-button + :key="0" + :label="0" + class="hoverable" + > + {{ $t("all tags") }} + </el-radio-button> + <el-radio-button + v-for="tag in Object.values(tags)" + :key="tag.id" + :label="tag.id" + class="hoverable" + > + {{ tag.name }} + </el-radio-button> + </el-radio-group> + + <el-divider /> + </template> + <template #table> + <el-card class="blueprint-card hoverable" v-for="blueprint in blueprints" @click="goToDetail(blueprint.id)"> + <component class="blueprint-link" :is="embed ? 'div' : 'router-link'" :to="embed ? undefined : {name: 'blueprints/view', params: {blueprintId: blueprint.id}}"> + <div class="side"> + <div class="title"> + {{ blueprint.title }} + </div> + <div class="tags text-uppercase"> + {{ tagsToString(blueprint.tags) }} + </div> + <div class="tasks-container"> + <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> + </div> </div> - <div class="tags text-uppercase"> - {{ tagsToString(blueprint.tags) }} + <div class="side buttons ms-auto"> + <slot name="buttons" :blueprint="blueprint" /> + <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> + <el-button class="hoverable" @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> + {{ $t('copy') }} + </el-button> + </el-tooltip> </div> - <div class="tasks-container"> - <task-icon :cls="task" only-icon v-for="task in [...new Set(blueprint.includedTasks)]" /> - </div> - </div> - <div class="side buttons ms-auto"> - <slot name="buttons" :blueprint="blueprint" /> - <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> - <el-button class="hoverable" @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> - {{ $t('copy') }} - </el-button> - </el-tooltip> - </div> - </component> - </el-card> - </template> - </data-table> - <slot name="bottom-bar" /> + </component> + </el-card> + </template> + </data-table> + <slot name="bottom-bar" /> + </div> </template> <script> @@ -63,9 +65,10 @@ import DataTableActions from "../../../../mixins/dataTableActions"; import {shallowRef} from "vue"; import ContentCopy from "vue-material-design-icons/ContentCopy.vue"; + import RestoreUrl from "../../../../mixins/restoreUrl"; export default { - mixins: [DataTableActions], + mixins: [RestoreUrl, DataTableActions], components: {TaskIcon, DataTable, SearchField}, emits: ["goToDetail"], props: { @@ -85,7 +88,7 @@ data() { return { q: undefined, - selectedTag: 0, + selectedTag: this.initSelectedTag(), tags: undefined, blueprints: undefined, total: 0, @@ -95,6 +98,9 @@ } }, methods: { + initSelectedTag() { + return this.$route?.query?.selectedTag ?? 0 + }, async copy(blueprintId) { await navigator.clipboard.writeText( (await this.$http.get(`${this.blueprintBaseUri}/${blueprintId}/flow`)).data @@ -135,8 +141,8 @@ } - if (this.$route.query.tags || this.selectedTag) { - query.tags = this.$route.query.tags || this.selectedTag; + if (this.$route.query.selectedTag || this.selectedTag) { + query.tags = this.$route.query.selectedTag || this.selectedTag; } return this.$http @@ -178,6 +184,11 @@ } }, watch: { + $route(newValue, oldValue) { + if (oldValue.name === newValue.name) { + this.selectedTag = this.initSelectedTag(); + } + }, q() { if (this.embed) { this.load(this.onDataLoaded); @@ -264,7 +275,7 @@ // Embedded tabs looks weird without cancelling the margin (this brings a top-left tabs with bottom-right search) - > :nth-child(1){ + > :nth-child(1) { margin-top: calc(-1.5 * var(--spacer)); } } @@ -374,8 +385,8 @@ flex: 1; :deep(span) { - border: 1px solid var(--bs--gray-300); - border-radius: $border-radius; + border: none !important; + border-radius: $border-radius !important; width: 100%; font-weight: bold; box-shadow: none;
null
test
train
2023-06-23T18:10:11
"2023-06-23T17:04:35Z"
brian-mulier-p
train
kestra-io/kestra/1577_1614
kestra-io/kestra
kestra-io/kestra/1577
kestra-io/kestra/1614
[ "keyword_pr_to_issue" ]
1e33d6dc421fa38e6583f80a02831ccdcabc1a0f
a38ab3b37de029010e82e15e57b3921d6ff877cd
[]
[]
"2023-06-26T09:14:34Z"
[ "bug" ]
Remove top progress bar during flow typing
ERROR: type should be string, got "\r\nhttps://github.com/kestra-io/kestra/assets/2064609/d9c6d5bd-fa91-47a1-99d8-b1d64f3c7146\r\n\r\n"
[ "ui/src/stores/flow.js" ]
[ "ui/src/stores/flow.js" ]
[]
diff --git a/ui/src/stores/flow.js b/ui/src/stores/flow.js index 16a73ba749..dc7fd5317f 100644 --- a/ui/src/stores/flow.js +++ b/ui/src/stores/flow.js @@ -159,7 +159,7 @@ export default { if (!flowParsed.id || !flowParsed.namespace) { flowSource = YamlUtils.updateMetadata(flowSource, {id: "default", namespace: "default"}) } - return this.$http.post("/api/v1/flows/graph", flowSource, {...config}) + return axios.post("/api/v1/flows/graph", flowSource, {...config}) .then(response => { if (response.status === 422) { return response;
null
train
train
2023-06-26T09:28:24
"2023-06-21T15:41:11Z"
tchiotludo
train
kestra-io/kestra/1613_1615
kestra-io/kestra
kestra-io/kestra/1613
kestra-io/kestra/1615
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
3595089c019f00415bb12abba922a4a92041cd3f
[]
[]
"2023-06-26T09:27:58Z"
[ "bug", "frontend" ]
Gantt chart doesn't show anything
### Expected Behavior _No response_ ### Actual Behaviour When clicking on logs nothing is showing up ![image](https://github.com/kestra-io/kestra/assets/46634684/0e6899df-7457-44d8-a6ca-26064a4a24f7) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/executions/Logs.vue", "ui/src/components/logs/LogList.vue" ]
[ "ui/src/components/executions/Logs.vue", "ui/src/components/logs/LogList.vue" ]
[]
diff --git a/ui/src/components/executions/Logs.vue b/ui/src/components/executions/Logs.vue index 31ab01384e..1b247494dd 100644 --- a/ui/src/components/executions/Logs.vue +++ b/ui/src/components/executions/Logs.vue @@ -41,7 +41,7 @@ v-for="taskRun in taskRunList" :key="taskRun.id" :task-run-id="taskRun.id" - :attempt="taskRun.attempt" + :attempt-number="taskRun.attempt" :level="level" :exclude-metas="['namespace', 'flowId', 'taskId', 'executionId']" :filter="filter" diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 3f985a3d50..99a625738e 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -225,7 +225,7 @@ type: Boolean, default: false }, - attempt: { + attemptNumber: { type: Number, default: undefined } @@ -293,8 +293,8 @@ if (this.taskRunId) { params.taskRunId = this.taskRunId; - if (this.attempt) { - params.attempt = this.attempt; + if (this.attemptNumber) { + params.attempt = this.attemptNumber; } } @@ -329,7 +329,7 @@ if (this.logsToOpen.includes(this.execution.state.current)) { this.currentTaskRuns.forEach((taskRun) => { if (taskRun.state.current === State.FAILED || taskRun.state.current === State.RUNNING) { - const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : (this.attempt ?? 0) + const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : (this.attemptNumber ?? 0) if (this.showLogs.includes(`${taskRun.id}-${attemptNumber}`)) { this?.$refs?.[`${taskRun.id}-${attemptNumber}`]?.[0]?.scrollToBottom(); } @@ -433,7 +433,7 @@ } }, attempts(taskRun) { - return this.execution.state.current === State.RUNNING ? taskRun.attempts : [taskRun.attempts[this.attempt]] ; + return this.execution.state.current === State.RUNNING || !this.attemptNumber ? taskRun.attempts : [taskRun.attempts[this.attemptNumber]] ; }, onTaskSelect(dropdownVisible, task) { if (dropdownVisible && this.taskRun?.id !== task.id) { @@ -444,7 +444,7 @@ this.showLogs = _xor(this.showLogs, [currentTaskRunId]) }, taskAttempt(index) { - return this.attempt || index + return this.attemptNumber || index } }, beforeUnmount() {
null
train
train
2023-06-26T21:47:15
"2023-06-26T08:19:35Z"
Ben8t
train
kestra-io/kestra/1616_1617
kestra-io/kestra
kestra-io/kestra/1616
kestra-io/kestra/1617
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
f8578d4f5dd7f20dc2afe1cff2c2f9368cc98c7f
[]
[]
"2023-06-26T10:55:08Z"
[ "bug" ]
Invalid props in taskDefaults doesn't show validation error (save looks unresponsive)
### Expected Behavior When we provide wrong taskDefaults we want to have a feedback of which property is wrong to be able to correct them ### Actual Behaviour Save still in purple but is unresponsive and provide no feedback about the error (see #1610) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java", "core/src/main/java/io/kestra/core/services/TaskDefaultService.java" ]
[ "core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java", "core/src/main/java/io/kestra/core/services/TaskDefaultService.java" ]
[ "core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java b/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java index 3f2e4e4523..a321458fc7 100644 --- a/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java +++ b/core/src/main/java/io/kestra/core/serializers/YamlFlowParser.java @@ -20,6 +20,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collections; +import java.util.Map; import java.util.Set; @Singleton @@ -41,6 +42,18 @@ public <T> T parse(String input, Class<T> cls) { return readFlow(mapper, input, cls, type(cls)); } + public <T> T parse(Map<String, Object> input, Class<T> cls) { + try { + return mapper.convertValue(input, cls); + } catch (IllegalArgumentException e) { + if(e.getCause() instanceof JsonProcessingException jsonProcessingException) { + jsonProcessingExceptionHandler(input, type(cls), jsonProcessingException); + } + + throw e; + } + } + private static <T> String type(Class<T> cls) { return cls.getSimpleName().toLowerCase(); } @@ -78,59 +91,66 @@ private <T> T readFlow(ObjectMapper mapper, String input, Class<T> objectClass, try { return mapper.readValue(input, objectClass); } catch (JsonProcessingException e) { - if (e.getCause() instanceof ConstraintViolationException constraintViolationException) { - throw constraintViolationException; - } - else if (e instanceof InvalidTypeIdException invalidTypeIdException) { - // This error is thrown when a non-existing task is used - throw new ConstraintViolationException( - "Invalid type: " + invalidTypeIdException.getTypeId(), - Set.of( - ManualConstraintViolation.of( - "Invalid type: " + invalidTypeIdException.getTypeId(), - input, - String.class, - invalidTypeIdException.getPathReference(), - null - ), - ManualConstraintViolation.of( - e.getMessage(), - input, - String.class, - invalidTypeIdException.getPathReference(), - null - ) + jsonProcessingExceptionHandler(input, resource, e); + } + + return null; + } + + @SuppressWarnings("unchecked") + private static <T> void jsonProcessingExceptionHandler(T target, String resource, JsonProcessingException e) throws ConstraintViolationException { + if (e.getCause() instanceof ConstraintViolationException constraintViolationException) { + throw constraintViolationException; + } + else if (e instanceof InvalidTypeIdException invalidTypeIdException) { + // This error is thrown when a non-existing task is used + throw new ConstraintViolationException( + "Invalid type: " + invalidTypeIdException.getTypeId(), + Set.of( + ManualConstraintViolation.of( + "Invalid type: " + invalidTypeIdException.getTypeId(), + target, + (Class<T>) target.getClass(), + invalidTypeIdException.getPathReference(), + null + ), + ManualConstraintViolation.of( + e.getMessage(), + target, + (Class<T>) target.getClass(), + invalidTypeIdException.getPathReference(), + null ) - ); - } - else if (e instanceof UnrecognizedPropertyException unrecognizedPropertyException) { - var message = unrecognizedPropertyException.getOriginalMessage() + unrecognizedPropertyException.getMessageSuffix(); - throw new ConstraintViolationException( - message, - Collections.singleton( - ManualConstraintViolation.of( - e.getCause() == null ? message : message + "\nCaused by: " + e.getCause().getMessage(), - input, - String.class, - unrecognizedPropertyException.getPathReference(), - null - ) - )); - } - else { - throw new ConstraintViolationException( - "Illegal "+ resource +" yaml: " + e.getMessage(), - Collections.singleton( - ManualConstraintViolation.of( - e.getCause() == null ? e.getMessage() : e.getMessage() + "\nCaused by: " + e.getCause().getMessage(), - input, - String.class, - "flow", - null - ) + ) + ); + } + else if (e instanceof UnrecognizedPropertyException unrecognizedPropertyException) { + var message = unrecognizedPropertyException.getOriginalMessage() + unrecognizedPropertyException.getMessageSuffix(); + throw new ConstraintViolationException( + message, + Collections.singleton( + ManualConstraintViolation.of( + e.getCause() == null ? message : message + "\nCaused by: " + e.getCause().getMessage(), + target, + (Class<T>) target.getClass(), + unrecognizedPropertyException.getPathReference(), + null ) - ); - } + )); + } + else { + throw new ConstraintViolationException( + "Illegal "+ resource +" yaml: " + e.getMessage(), + Collections.singleton( + ManualConstraintViolation.of( + e.getCause() == null ? e.getMessage() : e.getMessage() + "\nCaused by: " + e.getCause().getMessage(), + target, + (Class<T>) target.getClass(), + "flow", + null + ) + ) + ); } } } diff --git a/core/src/main/java/io/kestra/core/services/TaskDefaultService.java b/core/src/main/java/io/kestra/core/services/TaskDefaultService.java index ba387749de..b8b9fe3b21 100644 --- a/core/src/main/java/io/kestra/core/services/TaskDefaultService.java +++ b/core/src/main/java/io/kestra/core/services/TaskDefaultService.java @@ -10,6 +10,7 @@ import io.kestra.core.queues.QueueInterface; import io.kestra.core.runners.RunContextLogger; import io.kestra.core.serializers.JacksonMapper; +import io.kestra.core.serializers.YamlFlowParser; import io.kestra.core.utils.MapUtils; import io.micronaut.core.annotation.Nullable; import org.slf4j.Logger; @@ -28,6 +29,9 @@ public class TaskDefaultService { @Inject protected TaskGlobalDefaultConfiguration globalDefault; + @Inject + protected YamlFlowParser yamlFlowParser; + @Inject @Named(QueueFactoryInterface.WORKERTASKLOG_NAMED) protected QueueInterface<LogEntry> logQueue; @@ -116,7 +120,7 @@ public Flow injectDefaults(Flow flow) throws ConstraintViolationException { flowAsMap.put("taskDefaults", taskDefaults); } - return JacksonMapper.toMap(flowAsMap, Flow.class); + return yamlFlowParser.parse(flowAsMap, Flow.class); } private static Object recursiveDefaults(Object object, Map<String, List<TaskDefault>> defaults) {
diff --git a/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java b/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java index 379b54d037..57e1dc513d 100644 --- a/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java +++ b/core/src/test/java/io/kestra/core/runners/TaskDefaultsCaseTest.java @@ -12,35 +12,45 @@ import io.kestra.core.models.tasks.Task; import io.kestra.core.queues.QueueFactoryInterface; import io.kestra.core.queues.QueueInterface; +import io.kestra.core.repositories.FlowRepositoryInterface; import io.kestra.core.services.GraphService; +import io.kestra.core.services.TaskDefaultService; import io.kestra.core.utils.TestsUtils; +import jakarta.inject.Inject; +import jakarta.inject.Named; +import jakarta.inject.Singleton; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.SuperBuilder; +import javax.validation.ConstraintViolationException; +import javax.validation.Valid; +import javax.validation.constraints.NotEmpty; import java.time.Duration; import java.util.ArrayList; import java.util.List; -import java.util.Objects; +import java.util.Optional; import java.util.concurrent.TimeoutException; import java.util.stream.Collectors; import java.util.stream.Stream; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import jakarta.inject.Singleton; -import javax.validation.Valid; -import javax.validation.constraints.NotEmpty; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; +import static org.junit.jupiter.api.Assertions.assertThrows; @Singleton public class TaskDefaultsCaseTest { @Inject private RunnerUtils runnerUtils; + @Inject + private TaskDefaultService taskDefaultService; + + @Inject + private FlowRepositoryInterface flowRepository; + @Inject @Named(QueueFactoryInterface.WORKERTASKLOG_NAMED) private QueueInterface<LogEntry> logQueue; @@ -74,6 +84,13 @@ public void invalidTaskDefaults() throws TimeoutException { assertThat(execution.getTaskRunList(), hasSize(1)); LogEntry matchingLog = TestsUtils.awaitLog(logs, log -> log.getMessage().contains("Unrecognized field \"invalid\"")); assertThat(matchingLog, notNullValue()); + + ConstraintViolationException constraintViolationException = assertThrows(ConstraintViolationException.class, () -> taskDefaultService.injectDefaults(flowRepository + .findById("io.kestra.tests", "invalid-task-defaults", Optional.empty()) + .orElseThrow())); + + assertThat(constraintViolationException.getConstraintViolations().size(), is(1)); + assertThat(constraintViolationException.getMessage(), containsString("Unrecognized field \"invalid\"")); } @SuperBuilder @@ -117,7 +134,7 @@ public List<Task> allChildTasks() { } @Override - public List<ResolvedTask> childTasks(RunContext runContext, TaskRun parentTaskRun) throws IllegalVariableEvaluationException { + public List<ResolvedTask> childTasks(RunContext runContext, TaskRun parentTaskRun) { return FlowableUtils.resolveTasks(this.tasks, parentTaskRun); }
val
train
2023-06-26T21:47:15
"2023-06-26T09:48:21Z"
brian-mulier-p
train
kestra-io/kestra/1572_1619
kestra-io/kestra
kestra-io/kestra/1572
kestra-io/kestra/1619
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
24eee77bf5b70544df121a9a9a7648d55fa642d6
[ "it was an intended feature and flow will expand only on failed tasks now (like GHA), WDYT ?", "I want to see my logs, this is the most important aspect. \r\n\r\nHaving to expand/collapse is quite inconvenient. Imagine you want to quickly scan the logs from the entire workflow that has 20 tasks. You would need to click on expand 20 times...\r\n\r\nWould it be possible to provide that as a UI Setting that can be configured? I can imagine some people might prefer this behavior that exists now, but I think the vast majority would believe that something must be wrong with the workflow because the logs are not showing up \r\n\r\nLogs streaming in by default are especially useful to see the status of a workflow being in progress", "I think we should keep the collapsed by default (new intended feature) as it definitely keep things tidy. Logs are mostly a debugging feature (in any tools) - when you flow works you don't look at the logs, it's mostly for debugging error (and so you want to quickly find the ERROR log, hence the new behavior)\r\n\r\nBut agree with a settings where you can we set \"Expand all logs\" = true | false (false by default)", "but I don't see the progress... this makes iterating on building workflows way more difficult. Troubleshooting is not only if something failed, but also the flow may succeed but the log shows something unexpected, or not showing some logs\r\n\r\nthis seems like a big regression in developer productivity\r\n\r\nto see a tidy view of task structure, I would go to the topology or Gantt view. Logs tab is to see the logs.\r\n\r\n", "to find a middle ground, perhaps we may consider adding a button allowing users to expand all @Ben8t?\r\n\r\n![image](https://github.com/kestra-io/kestra/assets/86264395/4d4a1564-69fe-489f-9e45-18a54cf702ce)\r\n", "Yes I think it's good compromise !\r\nChanging the issue title to be clearer", "I too prefer logs to be openned by default, easier when building a workflow.\r\nMy opinion is that the logs tab should display ... logs, today it displays tasks status with call to action, one of these call to action is to show the task log.", "Add a settings with : \r\n- Expands logs (default one)\r\n- Collapse logs\r\n- Expands only error \r\n\r\nAdd a collapse all / expand all on the logs page (that will not affect the settings) " ]
[ "indent" ]
"2023-06-26T13:30:18Z"
[ "bug" ]
Add a setting for log collapsing
### Expected Behavior ![image](https://github.com/kestra-io/kestra/assets/86264395/142ea710-6a5e-4956-99b0-e7f74f1530e8) I need to manually click on each task to expand and show the logs -- this seems like a regression bug ![image](https://github.com/kestra-io/kestra/assets/86264395/ec209dc1-59a1-46a3-8b5e-2a648b3c4285) ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.10.0 ### Example flow _No response_
[ "ui/src/components/executions/Logs.vue", "ui/src/components/logs/LogList.vue", "ui/src/components/settings/Settings.vue", "ui/src/translations.json", "ui/src/utils/constants.js", "ui/src/utils/state.js" ]
[ "ui/src/components/executions/Logs.vue", "ui/src/components/logs/LogList.vue", "ui/src/components/settings/Settings.vue", "ui/src/translations.json", "ui/src/utils/constants.js", "ui/src/utils/state.js" ]
[ "core/src/test/java/io/kestra/core/schedulers/SchedulerScheduleTest.java" ]
diff --git a/ui/src/components/executions/Logs.vue b/ui/src/components/executions/Logs.vue index 31ab01384e..2121520737 100644 --- a/ui/src/components/executions/Logs.vue +++ b/ui/src/components/executions/Logs.vue @@ -18,6 +18,11 @@ @update:model-value="onChange" /> </el-form-item> + <el-form-item> + <el-button @click="handleLogDisplay()"> + {{ logDisplayButtonText }} + </el-button> + </el-form-item> <el-form-item> <el-button-group> <el-button @click="downloadContent()"> @@ -35,6 +40,7 @@ :exclude-metas="['namespace', 'flowId', 'taskId', 'executionId']" :filter="filter" @follow="forwardEvent('follow', $event)" + :logs-to-open-parent="logsToOpen" /> <div v-else-if="execution.state.current !== State.RUNNING"> <log-list @@ -46,6 +52,7 @@ :exclude-metas="['namespace', 'flowId', 'taskId', 'executionId']" :filter="filter" @follow="forwardEvent('follow', $event)" + :logs-to-open-parent="logsToOpen" /> </div> </div> @@ -60,6 +67,7 @@ import LogLevelSelector from "../logs/LogLevelSelector.vue"; import Collapse from "../layout/Collapse.vue"; import State from "../../utils/state"; + import {logDisplayTypes} from "../../utils/constants"; export default { components: { @@ -74,7 +82,8 @@ return { fullscreen: false, level: undefined, - filter: undefined + filter: undefined, + logsToOpen: undefined }; }, created() { @@ -100,7 +109,15 @@ } } return fullList - } + }, + logDisplayButtonText() { + if (this.logsToOpen) { + return this.logsToOpen.length !== 0 ? this.$t("collapse all") : this.$t("expand all") + } else { + const logDisplay = localStorage.getItem("logDisplay") || logDisplayTypes.DEFAULT; + return logDisplay === logDisplayTypes.HIDDEN ? this.$t("expand all") : this.$t("collapse all") + } + }, }, methods: { downloadContent() { @@ -127,6 +144,18 @@ onChange() { this.$router.push({query: {...this.$route.query, q: this.filter, level: this.level, page: 1}}); }, + handleLogDisplay() { + const logDisplay = localStorage.getItem("logDisplay") || logDisplayTypes.DEFAULT; + if (this.logsToOpen) { + this.logsToOpen.length === 0 ? this.logsToOpen = State.arrayAllStates().map(s => s.name) : this.logsToOpen = [] + return; + } + if (logDisplay === logDisplayTypes.HIDDEN ) { + this.logsToOpen = State.arrayAllStates().map(s => s.name) + } else { + this.logsToOpen = [] + } + } } }; </script> diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 3f985a3d50..4c42263237 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -177,6 +177,7 @@ import FlowUtils from "../../utils/flowUtils.js"; import moment from "moment"; import "vue-virtual-scroller/dist/vue-virtual-scroller.css" + import {logDisplayTypes} from "../../utils/constants"; export default { @@ -228,6 +229,10 @@ attempt: { type: Number, default: undefined + }, + logsToOpenParent: { + type: Array, + default: undefined } }, data() { @@ -245,8 +250,7 @@ followLogs: [], logsTotal: 0, timer: undefined, - timeout: undefined, - logsToOpen: [State.FAILED, State.CREATED, State.RUNNING] + timeout: undefined }; }, watch: { @@ -261,7 +265,10 @@ } }, currentTaskRuns: function () { - this.openTaskRun(); + this.openTaskRun(this.logsToOpen); + }, + logsToOpenParent: function () { + this.openTaskRun(this.logsToOpenParent); } }, mounted() { @@ -269,7 +276,7 @@ this.loadLogs(); } if (this.logsToOpen.includes(this.execution.state.current)) { - this.openTaskRun(); + this.openTaskRun(this.logsToOpen); } }, computed: { @@ -313,12 +320,31 @@ .map((e, index) => { return {...e, index: index} }) - } + }, + logsToOpen() { + if (this.logsToOpenParent) { + return this.logsToOpenParent + } + switch(localStorage.getItem("logDisplay") || logDisplayTypes.DEFAULT){ + case logDisplayTypes.ERROR: + return [State.FAILED, State.RUNNING, State.PAUSED] + case logDisplayTypes.ALL: + return State.arrayAllStates().map(s => s.name) + case logDisplayTypes.HIDDEN: + return [] + default: + return State.arrayAllStates().map(s => s.name) + } + }, }, methods: { - openTaskRun(){ + openTaskRun(logsToOpen){ this.currentTaskRuns.forEach((taskRun) => { - if (this.logsToOpen.includes(taskRun.state.current)) { + if (logsToOpen.length === 0) { + this.showLogs = [] + return; + } + if (logsToOpen.includes(taskRun.state.current)) { const attemptNumber = taskRun.attempts ? taskRun.attempts.length - 1 : 0 this.showLogs.push(`${taskRun.id}-${attemptNumber}`) this?.$refs?.[`${taskRun.id}-${attemptNumber}`]?.[0]?.scrollToBottom(); diff --git a/ui/src/components/settings/Settings.vue b/ui/src/components/settings/Settings.vue index bf80a6d923..412afa8ebf 100644 --- a/ui/src/components/settings/Settings.vue +++ b/ui/src/components/settings/Settings.vue @@ -55,8 +55,15 @@ </el-button> </el-form-item> - <el-form-item :label="$t('show documentation')"> - <el-checkbox :label="$t('show task documentation in editor')" :model-value="editorDocumentation" @update:model-value="onEditorDocumentation" /> + <el-form-item :label="$t('log expand setting')"> + <el-select :model-value="logDisplay" @update:model-value="onLogDisplayChange"> + <el-option + v-for="item in logDisplayOptions" + :key="item.value" + :label="item.text" + :value="item.value" + /> + </el-select> </el-form-item> </el-form> </div> @@ -74,6 +81,7 @@ import {mapGetters, mapState} from "vuex"; import permission from "../../models/permission"; import action from "../../models/action"; + import {logDisplayTypes} from "../../utils/constants"; export default { mixins: [RouteContext], @@ -90,7 +98,7 @@ editorTheme: undefined, autofoldTextEditor: undefined, guidedTour: undefined, - editorDocumentation: undefined + logDisplay: undefined }; }, created() { @@ -103,7 +111,7 @@ this.editorTheme = localStorage.getItem("editorTheme") || (darkTheme ? "dark" : "vs"); this.autofoldTextEditor = localStorage.getItem("autofoldTextEditor") === "true"; this.guidedTour = localStorage.getItem("tourDoneOrSkip") === "true"; - this.editorDocumentation = localStorage.getItem("editorDocumentation") !== "false"; + this.logDisplay = localStorage.getItem("logDisplay") || logDisplayTypes.DEFAULT; }, methods: { onNamespaceSelect(value) { @@ -148,12 +156,6 @@ this.autofoldTextEditor = value; this.$toast().saved(); }, - onEditorDocumentation(value){ - localStorage.setItem("editorDocumentation", value); - this.editorDocumentation = value; - this.$toast().saved(); - - }, exportFlows() { return this.$store .dispatch("flow/exportFlowByQuery", {}) @@ -168,6 +170,11 @@ this.$toast().success(this.$t("templates exported")); }) }, + onLogDisplayChange(value) { + localStorage.setItem("logDisplay", value); + this.logDisplay = value; + this.$toast().saved(); + } }, computed: { ...mapGetters("core", ["guidedProperties"]), @@ -201,6 +208,13 @@ canReadTemplates() { return this.user && this.user.isAllowed(permission.TEMPLATE, action.READ); }, + logDisplayOptions() { + return [ + {value: logDisplayTypes.ERROR, text: this.$t("expand error")}, + {value: logDisplayTypes.ALL, text: this.$t("expand all")}, + {value: logDisplayTypes.HIDDEN, text: this.$t("collapse all")} + ] + }, } }; </script> diff --git a/ui/src/translations.json b/ui/src/translations.json index f32c75b834..20cb3087f7 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -449,7 +449,11 @@ "existing": "A <code>{flowFullName}</code> Flow draft was retrieved, do you want to resume its edition ?" } }, - "title": "Title" + "title": "Title", + "expand error": "Expand only failed task", + "expand all": "Expand all", + "collapse all": "Collapse all", + "log expand setting": "Log default display" }, "fr": { "id": "Identifiant", @@ -903,6 +907,10 @@ "existing": "Un brouillon pour le Flow <code>{flowFullName}</code> existe, voulez-vous reprendre son édition?" } }, - "title": "Titre" + "title": "Titre", + "expand error": "Afficher uniquement les erreurs", + "expand all": "Afficher tout", + "collapse all": "Masquer tout", + "log expand setting": "Affichage par défaut des journaux" } } diff --git a/ui/src/utils/constants.js b/ui/src/utils/constants.js index b16ffc85e6..af4cbe71c1 100644 --- a/ui/src/utils/constants.js +++ b/ui/src/utils/constants.js @@ -6,4 +6,11 @@ export const SECTIONS = { export const stateGlobalChartTypes = { EXECUTIONS: "executions", TASKRUNS: "taskruns" +} + +export const logDisplayTypes = { + ALL: "all", + ERROR: "error", + HIDDEN: "hidden", + DEFAULT: "all" } \ No newline at end of file diff --git a/ui/src/utils/state.js b/ui/src/utils/state.js index eab93b3fea..6fb690b8c5 100644 --- a/ui/src/utils/state.js +++ b/ui/src/utils/state.js @@ -147,6 +147,10 @@ export default class State { }); } + static arrayAllStates() { + return Object.values(STATE); + } + static colorClass() { return _mapValues(STATE, state => state.colorClass); }
diff --git a/core/src/test/java/io/kestra/core/schedulers/SchedulerScheduleTest.java b/core/src/test/java/io/kestra/core/schedulers/SchedulerScheduleTest.java index 86a3639931..989a99198a 100644 --- a/core/src/test/java/io/kestra/core/schedulers/SchedulerScheduleTest.java +++ b/core/src/test/java/io/kestra/core/schedulers/SchedulerScheduleTest.java @@ -7,7 +7,7 @@ import io.kestra.core.runners.FlowListeners; import io.kestra.core.runners.Worker; import jakarta.inject.Inject; -import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.RetryingTest; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; @@ -62,7 +62,7 @@ protected AbstractScheduler scheduler(FlowListeners flowListenersServiceSpy, Sch ); } - @Test + @RetryingTest(5) void schedule() throws Exception { // mock flow listeners FlowListeners flowListenersServiceSpy = spy(this.flowListenersService);
test
train
2023-06-26T21:47:15
"2023-06-21T10:34:17Z"
anna-geller
train
kestra-io/kestra/1478_1621
kestra-io/kestra
kestra-io/kestra/1478
kestra-io/kestra/1621
[ "keyword_pr_to_issue" ]
ed80eb5c06244f00736daf3e01ad07004d321bfc
64c9b22489ac91d38be84d0ce1448f5f388e8fc7
[ "I would not add a localfile to an output as outputs are not meant to store large piece of data.\r\nMy ideas was:\r\n- `inputFiles` allow to create a file inside the local filesystem\r\n- `outputFiles` allow to send a local file to Kestra's internal storage\r\n\r\nOutputFiles will still be usable in other tasks that handle Kestra's internal storage files.", "In fact we may need three things:\n- A way to create a local file (inline file)\n- A way to create a file inside the internal storage (inline file)\n- A way to send an existing local file inside the internal storage" ]
[ "I think it is missing a check on what was actually created in storage from the inputs as for eg. execution.txt contains a wrong pebble expression (toto instead of inputs.toto) ?", "Same for storage file as content which should result in a duplicate content inside the newly created file ?", "Assert the error message", "Assert the error message" ]
"2023-06-26T13:41:03Z"
[ "backend" ]
[SCRIPT 🐍] `LocalFiles` task
### Feature description _Part of the the Script Workflow revamp_ `LocalFiles` is a task that let users write "inline" files in Kestra. It can used in `WorkingDirectory` or to pass complex files to other tasks (see DSL and example). Also it can expose files to Kestra Outputs (see DSL and example). ## DSL ```yaml type: LocalFiles inputs: [Array of files] accessible from {{ outputs.<taskid>.inputs.<filename>}} outputs: [Array of files] accessible from {{ outputs.<taskid>.outputs.<filename> }} ``` ## Examples 1. Inside a `WorkingDirectory` - inputs are accessible directly as part of the working directory ```yaml id: working_directory type: WorkingDirectory tasks: - id: local_file type: LocalFile inputs: main.py: | print("Hello World!") - id: run_python type: RunPython commands: - python main.py ``` 2. Through outputs ```yaml - id: local_file type: LocalFile inputs: main.py: | print("Hello World!") - id: run_python type: RunPython commands: - python {{ outputs.local_file.inputs['main.py'] }} ``` 3. Exposing files. In this example a Python task create a files inside a `WorkingDirectory`then outputs are exposed through `outputDir` ```yaml id: working_directory type: WorkingDirectory tasks: - id: run_python type: RunPython commands: - pip install requests pandas script: | import requests import pandas as pd import io data = requests.get("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv").content df = pd.read_csv(io.StringIO(data.decode('utf-8'))) df.assign(d='2023-06-01').to_csv("{{outputDir()}}/processed_data.csv", index=False) ``` Here data is written to the task outputDir in a file names "processed_data.csv" (so all files written in `outputDir` are exposed in outputs, so users could retrieve them with `outputs.my_task.outputDir["data.csv"]` for example) --- 💡 This feature could be directly linked to the a Multifile Editor feature. We could imagine each time the user click on the task, the right pane open a full editor where he can edit his files smoothly.
[]
[ "core/src/main/java/io/kestra/core/tasks/storages/LocalFiles.java" ]
[ "core/src/test/java/io/kestra/core/tasks/storages/LocalFilesTest.java", "jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java" ]
diff --git a/core/src/main/java/io/kestra/core/tasks/storages/LocalFiles.java b/core/src/main/java/io/kestra/core/tasks/storages/LocalFiles.java new file mode 100644 index 0000000000..a2eb25ff18 --- /dev/null +++ b/core/src/main/java/io/kestra/core/tasks/storages/LocalFiles.java @@ -0,0 +1,168 @@ +package io.kestra.core.tasks.storages; + +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.tasks.Output; +import io.kestra.core.models.tasks.RunnableTask; +import io.kestra.core.models.tasks.Task; +import io.kestra.core.runners.RunContext; +import io.kestra.core.tasks.scripts.BashService; +import io.kestra.core.utils.ListUtils; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.*; +import lombok.experimental.SuperBuilder; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.net.URI; +import java.nio.file.FileSystems; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.PathMatcher; +import java.util.AbstractMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static io.kestra.core.utils.Rethrow.throwBiConsumer; +import static io.kestra.core.utils.Rethrow.throwFunction; + +@SuperBuilder +@ToString +@EqualsAndHashCode +@Getter +@NoArgsConstructor +@Schema( + title = "Allow to create files in the local filesystem or to send files from the local filesystem to the internal storage.", + description = "This task should be used with the WorkingDirectory task to be able to access the same local filesystem within multiple tasks." +) +@Plugin(examples = { + @Example( + full = true, + title = "Create a local file that will be accessible to a bash task", + code = """ + id: "local-files" + namespace: "io.kestra.tests" + + tasks: + - id: workingDir + type: io.kestra.core.tasks.flows.WorkingDirectory + tasks: + - id: inputFiles + type: io.kestra.core.tasks.storages.LocalFiles + inputs: + hello.txt: "Hello World\\n" + addresse.json: "{{ outputs.myTaskId.uri }}" + - id: bash + type: io.kestra.core.tasks.scripts.Bash + commands: + - cat hello.txt + """ + ), + @Example( + full = true, + title = "Send local files to Kestra's internal storage", + code = """ + id: "local-files" + namespace: "io.kestra.tests" + + tasks: + - id: workingDir + type: io.kestra.core.tasks.flows.WorkingDirectory + tasks: + - id: bash + type: io.kestra.core.tasks.scripts.Bash + commands: + - mkdir -p sub/dir + - echo "Hello from Bash" >> sub/dir/bash1.txt + - echo "Hello from Bash" >> sub/dir/bash2.txt + - id: outputFiles + type: io.kestra.core.tasks.storages.LocalFiles + outputs: + - sub/** + """ + ) +}) +public class LocalFiles extends Task implements RunnableTask<LocalFiles.LocalFilesOutput> { + @Schema(title = "The files to create on the local filesystem") + @PluginProperty(dynamic = true) + private Object inputs; + + @Schema( + title = "The files from the local filesystem to send to the internal storage", + description = "must be a [Glob expression](https://en.wikipedia.org/wiki/Glob_(programming)) relative to current working directory, some examples: `my-dir/**`, `my-dir/*/**` or `my-dir/my-file.txt`" + ) + @PluginProperty(dynamic = true) + private List<String> outputs; + + @Override + public LocalFilesOutput run(RunContext runContext) throws Exception { + Logger logger = runContext.logger(); + + Map<String, String> inputFiles = this.inputs == null ? Map.of() : BashService.transformInputFiles(runContext, this.inputs); + + inputFiles + .forEach(throwBiConsumer((fileName, input) -> { + var file = new File(runContext.tempDir().toString(), fileName); + if (file.exists()) { + throw new IllegalVariableEvaluationException("File '" + fileName + "' already exist!"); + } + + if (!file.getParentFile().exists()) { + //noinspection ResultOfMethodCallIgnored + file.getParentFile().mkdirs(); + } + + var fileContent = runContext.render(input); + if (fileContent.startsWith("kestra://")) { + try (var is = runContext.uriToInputStream(URI.create(fileContent)); + var out = new FileOutputStream(file)) { + IOUtils.copyLarge(is, out); + } + } else { + Files.write(file.toPath(), fileContent.getBytes()); + } + })); + + var outputFiles = ListUtils.emptyOnNull(outputs) + .stream() + .flatMap(throwFunction(output -> this.outputMatcher(runContext, output))) + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + + logger.info("Provide {} input(s) and capture {} output(s).", inputFiles.size(), outputFiles.size()); + + return LocalFilesOutput.builder() + .uris(outputFiles) + .build(); + } + + private Stream<AbstractMap.SimpleEntry<String, URI>> outputMatcher(RunContext runContext, String output) throws IllegalVariableEvaluationException, IOException { + var glob = runContext.render(output); + final PathMatcher pathMatcher = FileSystems.getDefault().getPathMatcher("glob:" + glob); + + try (Stream<Path> walk = Files.walk(runContext.tempDir())) { + return walk + .filter(Files::isRegularFile) + .filter(path -> pathMatcher.matches(runContext.tempDir().relativize(path))) + .map(throwFunction(path -> new AbstractMap.SimpleEntry<>( + runContext.tempDir().relativize(path).toString(), + runContext.putTempFile(path.toFile()) + ))) + .toList() + .stream(); + } + } + + @Builder + @Getter + public static class LocalFilesOutput implements Output { + @Schema(title = "The URI of the files that have been sent to the internal storage") + private Map<String, URI> uris; + } +}
diff --git a/core/src/test/java/io/kestra/core/tasks/storages/LocalFilesTest.java b/core/src/test/java/io/kestra/core/tasks/storages/LocalFilesTest.java new file mode 100644 index 0000000000..600b76961e --- /dev/null +++ b/core/src/test/java/io/kestra/core/tasks/storages/LocalFilesTest.java @@ -0,0 +1,131 @@ +package io.kestra.core.tasks.storages; + +import io.kestra.core.exceptions.IllegalVariableEvaluationException; +import io.kestra.core.runners.RunContextFactory; +import io.kestra.core.storages.StorageInterface; +import io.kestra.core.utils.IdUtils; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.notNullValue; +import static org.junit.jupiter.api.Assertions.assertThrows; + +@MicronautTest +class LocalFilesTest { + @Inject + RunContextFactory runContextFactory; + + @Inject + StorageInterface storageInterface; + + private URI internalFiles() throws IOException, URISyntaxException { + var resource = ConcatTest.class.getClassLoader().getResource("application.yml"); + + return storageInterface.put( + new URI("/file/storage/get.yml"), + new FileInputStream(Objects.requireNonNull(resource).getFile()) + ); + } + + + @Test + void run() throws Exception { + var runContext = runContextFactory.of(Map.of("toto", "tata")); + var storageFile = internalFiles(); + + var task = LocalFiles.builder() + .id(IdUtils.create()) + .type(LocalFiles.class.getName()) + .inputs(Map.of( + "hello-input.txt", "Hello Input", + "execution.txt", "{{toto}}", + "application.yml", storageFile.toString() + )) + .outputs(List.of("hello-input.txt")) + .build(); + var outputs = task.run(runContext); + + assertThat(outputs, notNullValue()); + assertThat(outputs.getUris(), notNullValue()); + assertThat(outputs.getUris().size(), is(1)); + assertThat( + new String(storageInterface.get(outputs.getUris().get("hello-input.txt")).readAllBytes()), + is("Hello Input") + ); + assertThat(runContext.tempDir().toFile().list().length, is(2)); + assertThat(Files.readString(runContext.tempDir().resolve("execution.txt")), is("tata")); + assertThat( + Files.readString(runContext.tempDir().resolve("application.yml")), + is(new String(storageInterface.get(storageFile).readAllBytes())) + ); + + runContext.cleanup(); + } + + @Test + void recursive() throws Exception { + var runContext = runContextFactory.of(Map.of("toto", "tata")); + var storageFile = internalFiles(); + + var task = LocalFiles.builder() + .id(IdUtils.create()) + .type(LocalFiles.class.getName()) + .inputs(Map.of( + "test/hello-input.txt", "Hello Input", + "test/sub/dir/2/execution.txt", "{{toto}}", + "test/sub/dir/3/application.yml", storageFile.toString() + )) + .outputs(List.of("test/**")) + .build(); + var outputs = task.run(runContext); + + assertThat(outputs, notNullValue()); + assertThat(outputs.getUris(), notNullValue()); + assertThat(outputs.getUris().size(), is(3)); + assertThat( + new String(storageInterface.get(outputs.getUris().get("test/hello-input.txt")).readAllBytes()), + is("Hello Input") + ); + assertThat( + new String(storageInterface.get(outputs.getUris().get("test/sub/dir/2/execution.txt")) + .readAllBytes()), + is("tata") + ); + assertThat( + new String(storageInterface.get(outputs.getUris().get("test/sub/dir/3/application.yml")) + .readAllBytes()), + is(new String(storageInterface.get(storageFile).readAllBytes())) + ); + runContext.cleanup(); + } + + @Test + void failWithExistingInputFile() throws IOException { + var runContext = runContextFactory.of(); + Files.createFile(Path.of(runContext.tempDir().toString(), "hello-input.txt")); + + var task = LocalFiles.builder() + .id(IdUtils.create()) + .type(LocalFiles.class.getName()) + .inputs(Map.of( + "hello-input.txt", "Hello Input", + "execution.txt", "{{toto}}" + )) + .build(); + + assertThrows(IllegalVariableEvaluationException.class, () -> task.run(runContext)); + } +} diff --git a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java index 51ae829afb..ba2253d3fb 100644 --- a/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java +++ b/jdbc/src/test/java/io/kestra/jdbc/runner/JdbcRunnerTest.java @@ -180,7 +180,7 @@ void withTemplate() throws Exception { TemplateTest.withTemplate(runnerUtils, templateRepository, repositoryLoader, logsQueue); } - @RetryingTest(5) + @RetryingTest(5) // flaky on MySQL void withFailedTemplate() throws Exception { TemplateTest.withFailedTemplate(runnerUtils, templateRepository, repositoryLoader, logsQueue); }
test
train
2023-07-05T12:33:30
"2023-06-09T13:49:27Z"
Ben8t
train
kestra-io/kestra/1607_1624
kestra-io/kestra
kestra-io/kestra/1607
kestra-io/kestra/1624
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
997b02d54ee240a9ee896352038ca532c79d4543
[]
[]
"2023-06-26T13:48:49Z"
[ "frontend" ]
Logs dropdown arrow should be inversed
### Feature description When collapsed the arrow should be "down" (and not the opposite) ![image](https://github.com/kestra-io/kestra/assets/46634684/e84b501e-709d-499a-9900-3afa83714929)
[ "ui/src/components/logs/LogList.vue" ]
[ "ui/src/components/logs/LogList.vue" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java" ]
diff --git a/ui/src/components/logs/LogList.vue b/ui/src/components/logs/LogList.vue index 3f985a3d50..c53916c469 100644 --- a/ui/src/components/logs/LogList.vue +++ b/ui/src/components/logs/LogList.vue @@ -16,8 +16,8 @@ </div> <div v-if="!hideOthersOnSelect"> <el-button type="default" @click="() => toggleShowLogs(`${currentTaskRun.id}-${taskAttempt(index)}`)"> - <ChevronUp v-if="!showLogs.includes(`${currentTaskRun.id}-${taskAttempt(index)}`)" /> - <ChevronDown v-else /> + <ChevronDown v-if="!showLogs.includes(`${currentTaskRun.id}-${taskAttempt(index)}`)" /> + <ChevronUp v-else /> </el-button> </div> <div
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java index e5a7a4d195..5f9f86f903 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/ExecutionControllerTest.java @@ -26,16 +26,16 @@ import io.micronaut.runtime.server.EmbeddedServer; import io.micronaut.rxjava2.http.client.RxHttpClient; import io.micronaut.rxjava2.http.client.sse.RxSseClient; +import jakarta.inject.Inject; +import jakarta.inject.Named; import org.junit.jupiter.api.Test; +import org.junitpioneer.jupiter.RetryingTest; import java.io.File; import java.time.Duration; import java.util.*; import java.util.concurrent.TimeoutException; import java.util.stream.IntStream; -import jakarta.inject.Inject; -import jakarta.inject.Named; -import org.junitpioneer.jupiter.RetryingTest; import static io.kestra.core.utils.Rethrow.throwRunnable; import static org.hamcrest.MatcherAssert.assertThat; @@ -503,7 +503,7 @@ void webhook() { } - @Test + @RetryingTest(5) void resumePaused() throws TimeoutException, InterruptedException { // Run execution until it is paused Execution pausedExecution = runnerUtils.runOneUntilPaused(TESTS_FLOW_NS, "pause");
train
train
2023-06-26T21:47:15
"2023-06-23T15:20:40Z"
Ben8t
train
kestra-io/kestra/1596_1625
kestra-io/kestra
kestra-io/kestra/1596
kestra-io/kestra/1625
[ "keyword_pr_to_issue" ]
aeab342363e880f7b3f6455fed4497214376abb1
f8369ae540b591ff65acddd72ed35071ec7bb52e
[]
[ "Put it in a json file as it's json content and format it if possible for more readability" ]
"2023-06-26T14:07:46Z"
[ "backend" ]
Add an "execution dump" button on the execution overview page.
### Feature description Add an "execution dump" button on the execution overview page. This will download the execution object so it can be analyzed for debugging purposes.
[ "ui/src/components/executions/ExecutionRoot.vue", "ui/src/translations.json" ]
[ "ui/src/components/executions/ExecutionRoot.vue", "ui/src/translations.json" ]
[]
diff --git a/ui/src/components/executions/ExecutionRoot.vue b/ui/src/components/executions/ExecutionRoot.vue index c07100f188..ab09a66064 100644 --- a/ui/src/components/executions/ExecutionRoot.vue +++ b/ui/src/components/executions/ExecutionRoot.vue @@ -1,10 +1,17 @@ <template> <div> <div v-if="ready"> - <tabs :route-name="$route.param && $route.param.id ? 'executions/update': ''" @follow="follow" :tabs="tabs" /> + <tabs :route-name="$route.params && $route.params.id ? 'executions/update': ''" @follow="follow" :tabs="tabs" /> </div> <bottom-line v-if="canDelete || isAllowedTrigger || isAllowedEdit"> <ul> + <li> + <a :href="`${apiRoot}executions/${execution.id}`" target="_blank"> + <el-button :icon="Api" size="large" type="default"> + {{ $t('api') }} + </el-button> + </a> + </li> <li> <el-button :icon="Delete" size="large" type="default" v-if="canDelete" @click="deleteExecution"> {{ $t('delete') }} @@ -28,8 +35,10 @@ </template> <script setup> + import Api from "vue-material-design-icons/Api.vue"; import Delete from "vue-material-design-icons/Delete.vue"; import Pencil from "vue-material-design-icons/Pencil.vue"; + import {apiRoot} from "../../utils/axios" </script> <script> diff --git a/ui/src/translations.json b/ui/src/translations.json index dcf29e2661..0b48723973 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -450,6 +450,7 @@ } }, "title": "Title", + "api": "Api", "expand error": "Expand only failed task", "expand all": "Expand all", "collapse all": "Collapse all", @@ -909,6 +910,7 @@ } }, "title": "Titre", + "api": "Api", "expand error": "Afficher uniquement les erreurs", "expand all": "Afficher tout", "collapse all": "Masquer tout",
null
train
train
2023-06-30T09:51:58
"2023-06-22T15:23:20Z"
loicmathieu
train
kestra-io/kestra/1620_1627
kestra-io/kestra
kestra-io/kestra/1620
kestra-io/kestra/1627
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
bdd86b7f39cfefbf29f6dc1b1c91e61e858b1ef3
[]
[]
"2023-06-26T14:34:12Z"
[ "bug" ]
Blueprint graph does not load
### Expected Behavior Blueprint graph does not load when you don't have the plugin : ![image](https://github.com/kestra-io/kestra/assets/37600690/c520a7f3-1713-4cc7-9d5d-5402554fc387) ![image](https://github.com/kestra-io/kestra/assets/37600690/c5452f56-2e06-4ce8-8a8a-a6d5f049738b) ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.10.0-SNAPSHOT ### Example flow _No response_
[ "webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java" ]
[ "webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/BlueprintControllerTest.java", "webserver/src/test/resources/__files/blueprint-graph.json" ]
diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java b/webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java index 8c57325cb8..b4bb57b6c3 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/BlueprintController.java @@ -27,6 +27,7 @@ import java.net.URISyntaxException; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Optional; @Validated @@ -64,11 +65,11 @@ public String blueprintFlow( @ExecuteOn(TaskExecutors.IO) @Get(value = "{id}/graph") @Operation(tags = {"blueprints"}, summary = "Get a blueprint graph") - public FlowGraph blueprintGraph( + public Map<String, Object> blueprintGraph( @Parameter(description = "The blueprint id") String id, HttpRequest<?> httpRequest ) throws URISyntaxException { - return fastForwardToKestraApi(httpRequest, "/v1/blueprints/" + id + "/graph", Argument.of(FlowGraph.class)); + return fastForwardToKestraApi(httpRequest, "/v1/blueprints/" + id + "/graph", Argument.mapOf(String.class, Object.class)); } @ExecuteOn(TaskExecutors.IO)
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/BlueprintControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/BlueprintControllerTest.java index 7d1399e562..d772420214 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/BlueprintControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/BlueprintControllerTest.java @@ -16,6 +16,7 @@ import java.time.Instant; import java.util.List; +import java.util.Map; import static com.github.tomakehurst.wiremock.client.WireMock.*; import static org.hamcrest.MatcherAssert.assertThat; @@ -84,15 +85,18 @@ void blueprintGraph(WireMockRuntimeInfo wmRuntimeInfo) { .withBodyFile("blueprint-graph.json")) ); - FlowGraph graph = client.toBlocking().retrieve( + Map<String, Object> graph = client.toBlocking().retrieve( HttpRequest.GET("/api/v1/blueprints/community/id_1/graph"), - FlowGraph.class + Argument.mapOf(String.class, Object.class) ); - assertThat(graph.getNodes().size(), is(12)); - assertThat(graph.getNodes().stream().filter(abstractGraph -> abstractGraph.getUid().equals("3mTDtNoUxYIFaQtgjEg28_root")).count(), is(1L)); - assertThat(graph.getEdges().size(), is(16)); - assertThat(graph.getClusters().size(), is(1)); + List<Map<String, Object>> nodes = (List<Map<String, Object>>) graph.get("nodes"); + List<Map<String, Object>> edges = (List<Map<String, Object>>) graph.get("edges"); + List<Map<String, Object>> clusters = (List<Map<String, Object>>) graph.get("clusters"); + assertThat(nodes.size(), is(12)); + assertThat(nodes.stream().filter(abstractGraph -> abstractGraph.get("uid").equals("3mTDtNoUxYIFaQtgjEg28_root")).count(), is(1L)); + assertThat(edges.size(), is(16)); + assertThat(clusters.size(), is(1)); WireMock wireMock = wmRuntimeInfo.getWireMock(); wireMock.verifyThat(getRequestedFor(urlEqualTo("/v1/blueprints/id_1/graph"))); diff --git a/webserver/src/test/resources/__files/blueprint-graph.json b/webserver/src/test/resources/__files/blueprint-graph.json index c2438f5f34..8aedd6c72d 100644 --- a/webserver/src/test/resources/__files/blueprint-graph.json +++ b/webserver/src/test/resources/__files/blueprint-graph.json @@ -25,7 +25,7 @@ "tasks": [ { "id": "t1", - "type": "io.kestra.core.tasks.scripts.Bash", + "type": "io.kestra.core.tasks.scripts.UnknownTask", "commands": [ "echo \"{{task.id}} > $(date +\"%T.%N\")\"" ]
train
train
2023-06-26T21:47:15
"2023-06-26T13:40:49Z"
Skraye
train
kestra-io/kestra/1603_1628
kestra-io/kestra
kestra-io/kestra/1603
kestra-io/kestra/1628
[ "keyword_pr_to_issue" ]
217b82657d61758e83d6e5d40d94efbea67f5178
42558771f77bffca852e6b27b388ee8784c5f16d
[]
[]
"2023-06-26T16:46:12Z"
[]
Promote form on lowcode editor
- Remove the alpha on the form - Make it the first visible
[ "ui/src/components/flows/TaskEdit.vue" ]
[ "ui/src/components/flows/TaskEdit.vue" ]
[]
diff --git a/ui/src/components/flows/TaskEdit.vue b/ui/src/components/flows/TaskEdit.vue index 0748d780ab..a337a56ca5 100644 --- a/ui/src/components/flows/TaskEdit.vue +++ b/ui/src/components/flows/TaskEdit.vue @@ -30,6 +30,17 @@ </template> <el-tabs v-if="taskYaml" v-model="activeTabs"> + <el-tab-pane name="form"> + <template #label> + <span>{{ $t('form') }}</span> + </template> + <task-editor + ref="editor" + v-model="taskYaml" + :section="section" + @update:model-value="onInput" + /> + </el-tab-pane> <el-tab-pane name="source"> <template #label> <span>{{ $t('source') }}</span> @@ -47,20 +58,6 @@ @update:model-value="onInput" /> </el-tab-pane> - <el-tab-pane name="form"> - <template #label> - <span> - {{ $t('form') }} - <el-badge type="primary" value="Alpha" /> - </span> - </template> - <task-editor - ref="editor" - v-model="taskYaml" - :section="section" - @update:model-value="onInput" - /> - </el-tab-pane> <el-tab-pane v-if="pluginMardown" name="documentation"> <template #label> <span> @@ -200,7 +197,7 @@ uuid: Utils.uid(), taskYaml: undefined, isModalOpen: false, - activeTabs: "source", + activeTabs: "form", }; }, created() {
null
train
train
2023-06-26T21:47:15
"2023-06-23T12:12:48Z"
tchiotludo
train
kestra-io/kestra/1584_1631
kestra-io/kestra
kestra-io/kestra/1584
kestra-io/kestra/1631
[ "keyword_pr_to_issue" ]
8a4695664e6a30d3ead79eeea8112b231d61eba8
66f2aaa65c2d1c4d3108bfe6ee451fb561890825
[]
[]
"2023-06-27T08:34:31Z"
[ "bug" ]
Low code Editor, change task type produce invalid task definition
- Choose a type type (s3 upload in my screenshot), fill the required properties, hit save - Change task type to echo, fill the format props - see an error about unknown fields `accessKey` ![image](https://github.com/kestra-io/kestra/assets/2064609/0b70a65e-2436-4d12-aea1-f5447a42eee0)
[ "ui/src/components/flows/TaskEditor.vue" ]
[ "ui/src/components/flows/TaskEditor.vue" ]
[]
diff --git a/ui/src/components/flows/TaskEditor.vue b/ui/src/components/flows/TaskEditor.vue index 5851e49040..cc010668b2 100644 --- a/ui/src/components/flows/TaskEditor.vue +++ b/ui/src/components/flows/TaskEditor.vue @@ -87,11 +87,11 @@ }, onInput(value) { + this.taskObject = value; this.$emit("update:modelValue", YamlUtils.stringify(value)); }, onTaskTypeSelect() { this.load(); - this.taskObject.type = this.selectedTaskType; const value = { type: this.selectedTaskType };
null
test
train
2023-06-27T09:09:20
"2023-06-22T06:34:16Z"
tchiotludo
train
kestra-io/kestra/1634_1638
kestra-io/kestra
kestra-io/kestra/1634
kestra-io/kestra/1638
[ "keyword_pr_to_issue" ]
f7d3d0bcd47bf0069acacb72aa6eca9bc09505a9
0d06d3d37b594ba22bbc63e1250577ab04f5aa86
[ "See this https://kestra-io.slack.com/archives/C03FQKXRK3K/p1687858331341749" ]
[ "Directly returns the list\r\n\r\nhowever, lgtm", "Ups, was for testing forgot it :+1: " ]
"2023-06-27T10:57:42Z"
[ "bug" ]
Triple dash in attribute value can lead to incorrect validation
### Expected Behavior Wrong regex leading to parsing --- everywhere instead of on a new line only ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java", "webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml", "webserver/src/test/resources/flows/validateMultipleValidFlows.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java b/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java index 175d901471..891981bd5c 100644 --- a/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java +++ b/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java @@ -1,5 +1,6 @@ package io.kestra.core.models.validations; +import com.fasterxml.jackson.annotation.JsonIgnore; import io.micronaut.core.annotation.Introspected; import lombok.AllArgsConstructor; import lombok.Getter; @@ -31,14 +32,17 @@ public class ValidateConstraintViolation { private String constraints; + @JsonIgnore public String getIdentity(){ return flow != null & namespace != null ? getFlowId() : flow != null ? flow : String.valueOf(index); } + @JsonIgnore public String getIdentity(Path directory) throws IOException { return flow != null & namespace != null ? getFlowId() : flow != null ? flow : String.valueOf(Files.walk(directory).collect(Collectors.toList()).get(index)); } + @JsonIgnore public String getFlowId(){ return namespace+"."+flow; } diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index c9221ed3d7..4fc46e515e 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -446,7 +446,7 @@ public List<ValidateConstraintViolation> validateFlows( ) { AtomicInteger index = new AtomicInteger(0); return Stream - .of(flows.split("---")) + .of(flows.split("\\n+---\\n*?")) .map(flow -> { ValidateConstraintViolation.ValidateConstraintViolationBuilder<?, ?> validateConstraintViolationBuilder = ValidateConstraintViolation.builder(); validateConstraintViolationBuilder.index(index.getAndIncrement());
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java index cf7246c3bb..596630f4b4 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java @@ -9,6 +9,7 @@ import io.kestra.core.models.flows.input.StringInput; import io.kestra.core.models.hierarchies.FlowGraph; import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.validations.ValidateConstraintViolation; import io.kestra.core.runners.AbstractMemoryRunnerTest; import io.kestra.core.serializers.YamlFlowParser; import io.kestra.core.tasks.debugs.Return; @@ -30,6 +31,7 @@ import io.micronaut.http.hateoas.JsonError; import io.micronaut.rxjava2.http.client.RxHttpClient; import jakarta.inject.Inject; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,10 +42,7 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.zip.ZipFile; import static io.micronaut.http.HttpRequest.*; @@ -664,6 +663,30 @@ void deleteFlowsByIds(){ assertThat(e.getStatus(), is(HttpStatus.NOT_FOUND)); } + @Test + void validateFlows() throws IOException { + URL resource = TestsUtils.class.getClassLoader().getResource("flows/validateMultipleValidFlows.yaml"); + String flow = Files.readString(Path.of(Objects.requireNonNull(resource).getPath()), Charset.defaultCharset()); + + HttpResponse<List<ValidateConstraintViolation>> response = client.toBlocking().exchange(POST("/api/v1/flows/validate", flow).contentType(MediaType.APPLICATION_YAML), Argument.listOf(ValidateConstraintViolation.class)); + + List<ValidateConstraintViolation> body = response.body(); + assertThat(body.size(), is(2)); + assertThat(body, everyItem( + Matchers.hasProperty("constraints", is(nullValue())) + )); + + resource = TestsUtils.class.getClassLoader().getResource("flows/validateMultipleInvalidFlows.yaml"); + flow = Files.readString(Path.of(Objects.requireNonNull(resource).getPath()), Charset.defaultCharset()); + + response = client.toBlocking().exchange(POST("/api/v1/flows/validate", flow).contentType(MediaType.APPLICATION_YAML), Argument.listOf(ValidateConstraintViolation.class)); + + body = response.body(); + assertThat(body.size(), is(2)); + assertThat(body.get(0).getConstraints(), containsString("Unrecognized field \"unknownProp\"")); + assertThat(body.get(1).getConstraints(), containsString("Invalid type: io.kestra.core.tasks.debugs.UnknownTask")); + } + private Flow generateFlow(String namespace, String inputName) { return generateFlow(IdUtils.create(), namespace, inputName); } diff --git a/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml b/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml new file mode 100644 index 0000000000..7a5c502450 --- /dev/null +++ b/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml @@ -0,0 +1,19 @@ +id: "first_flow" +namespace: "validation" +tasks: + - id: task_one + type: io.kestra.core.tasks.scripts.Bash + commands: + - 'echo strange---string' + unknownProp: unknownValue + +--- + +id: "second_flow" +namespace: "validation" +tasks: + - id: task-two + type: io.kestra.core.tasks.debugs.UnknownTask + - id: task-three + type: io.kestra.core.tasks.debugs.Return + format: strangestring--- \ No newline at end of file diff --git a/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml b/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml new file mode 100644 index 0000000000..55513373cc --- /dev/null +++ b/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml @@ -0,0 +1,19 @@ +id: "first_flow" +namespace: "validation" +tasks: + - id: task_one + type: io.kestra.core.tasks.scripts.Bash + commands: + - 'echo strange---string' + +--- + +id: "second_flow" +namespace: "validation" +tasks: + - id: task-two + type: io.kestra.core.tasks.debugs.Return + format: strangestring--- + - id: task-three + type: io.kestra.core.tasks.debugs.Return + format: ---strangestring \ No newline at end of file
train
train
2023-06-27T12:59:05
"2023-06-27T10:09:06Z"
brian-mulier-p
train
kestra-io/kestra/1630_1642
kestra-io/kestra
kestra-io/kestra/1630
kestra-io/kestra/1642
[ "keyword_pr_to_issue" ]
97fbc93655fc333232b2c9b1947b97c431cf84f9
3d83bb1b6409ef567f975a97adacd810b63f4b79
[]
[]
"2023-06-27T13:47:52Z"
[ "bug", "frontend" ]
label dropdown hide execution button
### Expected Behavior Could it be a simple text box ? ### Actual Behaviour <img width="751" alt="Screenshot 2023-06-27 at 10 30 14" src="https://github.com/kestra-io/kestra/assets/46634684/46690267-af15-425b-8eeb-1117658f9e62"> ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: - Operating System (OS / Docker / Kubernetes): - Java Version (If not docker): ### Example flow _No response_
[ "ui/src/components/flows/FlowRun.vue", "ui/src/translations.json" ]
[ "ui/src/components/flows/FlowRun.vue", "ui/src/components/labels/LabelInput.vue", "ui/src/translations.json" ]
[ "core/src/test/java/io/kestra/core/schedulers/SchedulerConditionTest.java" ]
diff --git a/ui/src/components/flows/FlowRun.vue b/ui/src/components/flows/FlowRun.vue index 726a8fa656..8111b5c150 100644 --- a/ui/src/components/flows/FlowRun.vue +++ b/ui/src/components/flows/FlowRun.vue @@ -82,8 +82,8 @@ <el-form-item :label="$t('execution labels')" > - <label-filter - v-model:model-value="executionLabels" + <label-input + v-model:labels="executionLabels" /> </el-form-item> <div class="bottom-buttons"> @@ -99,6 +99,9 @@ <el-button :icon="Flash" class="flow-run-trigger-button" @click="onSubmit($refs.form)" type="primary" :disabled="flow.disabled || haveBadLabels"> {{ $t('launch execution') }} </el-button> + <el-text v-if="haveBadLabels" type="danger" size="small"> + {{ $t('wrong labels') }} + </el-text> </el-form-item> </div> </div> @@ -115,11 +118,11 @@ import {mapState} from "vuex"; import {executeTask} from "../../utils/submitTask" import Editor from "../../components/inputs/Editor.vue"; - import LabelFilter from "../../components/labels/LabelFilter.vue"; + import LabelInput from "../../components/labels/LabelInput.vue"; import {pageFromRoute} from "../../utils/eventsRouter"; export default { - components: {Editor, LabelFilter}, + components: {Editor, LabelInput}, props: { redirect: { type: Boolean, @@ -169,13 +172,10 @@ ...mapState("core", ["guidedProperties"]), ...mapState("execution", ["execution"]), haveBadLabels() { - return this.executionLabels.some(label => label.split(":").length !== 2) + return this.executionLabels.some(label => (label.key && !label.value) || (!label.key && label.value)); } }, methods: { - isBadLabel(tag) { - return tag.split(":").length !== 2 - }, fillInputsFromExecution(){ const nonEmptyInputNames = Object.keys(this.execution.inputs); this.inputs = Object.fromEntries( @@ -211,6 +211,8 @@ id: this.flow.id, namespace: this.flow.namespace, labels: this.executionLabels + .filter(label => label.key && label.value) + .map(label => `${label.key}:${label.value}`) }) this.$emit("executionTrigger"); }); @@ -273,19 +275,6 @@ return true; }, - handleClose(label) { - this.executionLabels.splice(this.executionLabels.indexOf(label), 1) - }, - showInput() { - this.inputVisible = true; - }, - handleInputConfirm() { - if (this.inputNewLabel) { - this.executionLabels.push(this.inputNewLabel) - } - this.inputVisible = false - this.inputNewLabel = "" - } }, watch: { guidedProperties: { diff --git a/ui/src/components/labels/LabelInput.vue b/ui/src/components/labels/LabelInput.vue new file mode 100644 index 0000000000..519a86e1e9 --- /dev/null +++ b/ui/src/components/labels/LabelInput.vue @@ -0,0 +1,68 @@ +<template> + <div class="d-flex w-100 mb-2" v-for="(label, index) in locals" :key="index"> + <div class="flex-grow-1 d-flex align-items-center"> + <el-input + class="form-control me-2" + :placeholder="$t('key')" + v-model="label.key" + @update:model-value="update(index, $event, 'key')" + /> + <el-input + class="form-control me-2" + :placeholder="$t('value')" + v-model="label.value" + @update:model-value="update(index, $event, 'value')" + /> + </div> + <div class="flex-shrink-1"> + <el-button-group class="d-flex"> + <el-button :icon="Plus" @click="addItem" /> + <el-button :icon="Minus" @click="removeItem(index)" :disabled="index === 0 && locals.length === 1" /> + </el-button-group> + </div> + </div> +</template> + +<script setup> + import Plus from "vue-material-design-icons/Plus.vue"; + import Minus from "vue-material-design-icons/Minus.vue"; +</script> + + +<script> + export default { + props: { + labels: { + type: Array, + required: true + } + }, + data() { + return { + locals: [] + } + }, + emits: ["update:labels"], + created() { + if (this.labels.length === 0) { + this.addItem(); + } else { + this.locals = this.labels + } + }, + methods: { + addItem() { + this.locals.push({key: null, value: null}); + this.$emit("update:labels", this.locals); + }, + removeItem(index) { + this.locals.splice(index, 1); + this.$emit("update:labels", this.locals); + }, + update(index, value, prop) { + this.locals[index][prop] = value; + this.$emit("update:labels", this.locals); + }, + }, + } +</script> \ No newline at end of file diff --git a/ui/src/translations.json b/ui/src/translations.json index 5e08e2fe1a..a1542a1c93 100644 --- a/ui/src/translations.json +++ b/ui/src/translations.json @@ -262,6 +262,7 @@ "labels": "Labels", "label filter placeholder": "Label as 'key:value'", "execution labels": "Execution labels", + "wrong labels": "Empty key or value is not allowed in labels", "feeds": { "title": "What's new at Kestra" }, @@ -719,8 +720,9 @@ "disabled flow desc": "Ce flow est désactivé, veuillez le réactiver pour l'exécuter.", "label": "Label", "labels": "Labels", - "label filter placeholder": "Label as 'key:value'", + "label filter placeholder": "Label au format 'clé:valeur'", "execution labels": "Labels d'exécution", + "wrong labels": "Clé ou valeur vide détecté dans les labels", "feeds": { "title": "Quoi de neuf sur Kestra" },
diff --git a/core/src/test/java/io/kestra/core/schedulers/SchedulerConditionTest.java b/core/src/test/java/io/kestra/core/schedulers/SchedulerConditionTest.java index c445713315..afbc9f8232 100644 --- a/core/src/test/java/io/kestra/core/schedulers/SchedulerConditionTest.java +++ b/core/src/test/java/io/kestra/core/schedulers/SchedulerConditionTest.java @@ -51,7 +51,7 @@ private static Flow createScheduleFlow() { return createFlow(Collections.singletonList(schedule)); } - @RetryingTest(5) + @RetryingTest(10) void schedule() throws Exception { // mock flow listeners FlowListeners flowListenersServiceSpy = spy(this.flowListenersService);
train
train
2023-06-30T20:59:49
"2023-06-27T08:30:26Z"
Ben8t
train
kestra-io/kestra/1639_1643
kestra-io/kestra
kestra-io/kestra/1639
kestra-io/kestra/1643
[ "keyword_pr_to_issue" ]
e786f1b8598e906870b9f06810dcbb9a1016cb37
941ea7e8abf8595dde60c63cd33f978e5939a5d0
[]
[]
"2023-06-27T13:53:15Z"
[ "frontend" ]
Blueprint - Replace Copy by Use button
### Feature description In the blueprint standalone view, replace the "copy" button by a "use" redirecting to the Editor where you user start using the selected Blueprint in a new flow.
[ "core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java", "ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue", "webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java" ]
[ "webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java", "webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml", "webserver/src/test/resources/flows/validateMultipleValidFlows.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java b/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java index 175d901471..891981bd5c 100644 --- a/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java +++ b/core/src/main/java/io/kestra/core/models/validations/ValidateConstraintViolation.java @@ -1,5 +1,6 @@ package io.kestra.core.models.validations; +import com.fasterxml.jackson.annotation.JsonIgnore; import io.micronaut.core.annotation.Introspected; import lombok.AllArgsConstructor; import lombok.Getter; @@ -31,14 +32,17 @@ public class ValidateConstraintViolation { private String constraints; + @JsonIgnore public String getIdentity(){ return flow != null & namespace != null ? getFlowId() : flow != null ? flow : String.valueOf(index); } + @JsonIgnore public String getIdentity(Path directory) throws IOException { return flow != null & namespace != null ? getFlowId() : flow != null ? flow : String.valueOf(Files.walk(directory).collect(Collectors.toList()).get(index)); } + @JsonIgnore public String getFlowId(){ return namespace+"."+flow; } diff --git a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue index 5be2060bdd..394e560e02 100644 --- a/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue +++ b/ui/src/override/components/flows/blueprints/BlueprintsBrowser.vue @@ -50,12 +50,15 @@ </div> <div class="side buttons ms-auto"> <slot name="buttons" :blueprint="blueprint" /> - <el-tooltip trigger="click" content="Copied" placement="left" :auto-close="2000"> + <el-tooltip v-if="embed" trigger="click" content="Copied" placement="left" :auto-close="2000"> <el-button @click.prevent.stop="copy(blueprint.id)" :icon="icon.ContentCopy" size="large" text bg> {{ $t('copy') }} </el-button> </el-tooltip> + <el-button v-else size="large" text bg @click="blueprintToEditor(blueprint.id)"> + {{ $t('use') }} + </el-button> </div> </component> </el-card> @@ -113,6 +116,10 @@ (await this.$http.get(`${this.blueprintBaseUri}/${blueprintId}/flow`)).data ); }, + async blueprintToEditor(blueprintId) { + localStorage.setItem("autoRestore-creation_draft", (await this.$http.get(`${this.blueprintBaseUri}/${blueprintId}/flow`)).data); + this.$router.push({name: 'flows/create'}); + }, tagsToString(blueprintTags) { return blueprintTags?.map(id => this.tags?.[id]?.name).join(" ") }, diff --git a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java index c9221ed3d7..4fc46e515e 100644 --- a/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java +++ b/webserver/src/main/java/io/kestra/webserver/controllers/FlowController.java @@ -446,7 +446,7 @@ public List<ValidateConstraintViolation> validateFlows( ) { AtomicInteger index = new AtomicInteger(0); return Stream - .of(flows.split("---")) + .of(flows.split("\\n+---\\n*?")) .map(flow -> { ValidateConstraintViolation.ValidateConstraintViolationBuilder<?, ?> validateConstraintViolationBuilder = ValidateConstraintViolation.builder(); validateConstraintViolationBuilder.index(index.getAndIncrement());
diff --git a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java index cf7246c3bb..596630f4b4 100644 --- a/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java +++ b/webserver/src/test/java/io/kestra/webserver/controllers/FlowControllerTest.java @@ -9,6 +9,7 @@ import io.kestra.core.models.flows.input.StringInput; import io.kestra.core.models.hierarchies.FlowGraph; import io.kestra.core.models.tasks.Task; +import io.kestra.core.models.validations.ValidateConstraintViolation; import io.kestra.core.runners.AbstractMemoryRunnerTest; import io.kestra.core.serializers.YamlFlowParser; import io.kestra.core.tasks.debugs.Return; @@ -30,6 +31,7 @@ import io.micronaut.http.hateoas.JsonError; import io.micronaut.rxjava2.http.client.RxHttpClient; import jakarta.inject.Inject; +import org.hamcrest.Matchers; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -40,10 +42,7 @@ import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; +import java.util.*; import java.util.zip.ZipFile; import static io.micronaut.http.HttpRequest.*; @@ -664,6 +663,30 @@ void deleteFlowsByIds(){ assertThat(e.getStatus(), is(HttpStatus.NOT_FOUND)); } + @Test + void validateFlows() throws IOException { + URL resource = TestsUtils.class.getClassLoader().getResource("flows/validateMultipleValidFlows.yaml"); + String flow = Files.readString(Path.of(Objects.requireNonNull(resource).getPath()), Charset.defaultCharset()); + + HttpResponse<List<ValidateConstraintViolation>> response = client.toBlocking().exchange(POST("/api/v1/flows/validate", flow).contentType(MediaType.APPLICATION_YAML), Argument.listOf(ValidateConstraintViolation.class)); + + List<ValidateConstraintViolation> body = response.body(); + assertThat(body.size(), is(2)); + assertThat(body, everyItem( + Matchers.hasProperty("constraints", is(nullValue())) + )); + + resource = TestsUtils.class.getClassLoader().getResource("flows/validateMultipleInvalidFlows.yaml"); + flow = Files.readString(Path.of(Objects.requireNonNull(resource).getPath()), Charset.defaultCharset()); + + response = client.toBlocking().exchange(POST("/api/v1/flows/validate", flow).contentType(MediaType.APPLICATION_YAML), Argument.listOf(ValidateConstraintViolation.class)); + + body = response.body(); + assertThat(body.size(), is(2)); + assertThat(body.get(0).getConstraints(), containsString("Unrecognized field \"unknownProp\"")); + assertThat(body.get(1).getConstraints(), containsString("Invalid type: io.kestra.core.tasks.debugs.UnknownTask")); + } + private Flow generateFlow(String namespace, String inputName) { return generateFlow(IdUtils.create(), namespace, inputName); } diff --git a/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml b/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml new file mode 100644 index 0000000000..7a5c502450 --- /dev/null +++ b/webserver/src/test/resources/flows/validateMultipleInvalidFlows.yaml @@ -0,0 +1,19 @@ +id: "first_flow" +namespace: "validation" +tasks: + - id: task_one + type: io.kestra.core.tasks.scripts.Bash + commands: + - 'echo strange---string' + unknownProp: unknownValue + +--- + +id: "second_flow" +namespace: "validation" +tasks: + - id: task-two + type: io.kestra.core.tasks.debugs.UnknownTask + - id: task-three + type: io.kestra.core.tasks.debugs.Return + format: strangestring--- \ No newline at end of file diff --git a/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml b/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml new file mode 100644 index 0000000000..55513373cc --- /dev/null +++ b/webserver/src/test/resources/flows/validateMultipleValidFlows.yaml @@ -0,0 +1,19 @@ +id: "first_flow" +namespace: "validation" +tasks: + - id: task_one + type: io.kestra.core.tasks.scripts.Bash + commands: + - 'echo strange---string' + +--- + +id: "second_flow" +namespace: "validation" +tasks: + - id: task-two + type: io.kestra.core.tasks.debugs.Return + format: strangestring--- + - id: task-three + type: io.kestra.core.tasks.debugs.Return + format: ---strangestring \ No newline at end of file
train
train
2023-06-28T12:22:10
"2023-06-27T12:37:33Z"
Ben8t
train
kestra-io/kestra/1474_1646
kestra-io/kestra
kestra-io/kestra/1474
kestra-io/kestra/1646
[ "keyword_pr_to_issue" ]
aeab342363e880f7b3f6455fed4497214376abb1
467003be0f94c78a21708037d578e6b4beabb98d
[ "I'm not sure it is our responsability to prevent this kind of behaviour ? I don't think it is a good thing to cut off the ability to do recursive flows since there could be a stop condition or something. I see this as a while loop in Java and they are not preventing us from doing an infinite loop. WDYT ?\r\nOr maybe we need to provide a way to stop any child of a given execution recursively instead ?", "Right now, we don't the tooling to support flow loop (aka: prevent infinite loop) .\r\nWe need at first to block to protect breaking the production env and think later if there is usecase (I almost sure no real use case). " ]
[ "You also need to check the namespace.", "If we cannot create a revursive flow, no need to check this at runtime.\r\nMoreover it seems that this is always true!", "Dont we care about possibly existing recursive flow ? ", "I would say no, let's keep it simple for now" ]
"2023-06-27T15:41:21Z"
[ "bug" ]
Infinite loop with subflow
### Expected Behavior Created a recursive flow create an infinite loop : ``` id: "flow-a" namespace: "dev" tasks: - id: log type: io.kestra.core.tasks.log.Log message: hello - id: subflow type: io.kestra.core.tasks.flows.Flow flowId: flow-a namespace: dev ``` ### Actual Behaviour _No response_ ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.10.0-snapshot ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/tasks/flows/Flow.java", "core/src/main/java/io/kestra/core/validations/ValidationFactory.java" ]
[ "core/src/main/java/io/kestra/core/tasks/flows/Flow.java", "core/src/main/java/io/kestra/core/validations/ValidationFactory.java" ]
[ "core/src/test/java/io/kestra/core/validations/FlowValidationTest.java", "core/src/test/resources/flows/invalids/recursive-flow.yaml" ]
diff --git a/core/src/main/java/io/kestra/core/tasks/flows/Flow.java b/core/src/main/java/io/kestra/core/tasks/flows/Flow.java index ef1221806f..bcea3e58ed 100644 --- a/core/src/main/java/io/kestra/core/tasks/flows/Flow.java +++ b/core/src/main/java/io/kestra/core/tasks/flows/Flow.java @@ -15,11 +15,11 @@ import lombok.*; import lombok.experimental.SuperBuilder; +import javax.annotation.Nullable; +import javax.validation.constraints.NotNull; import java.util.HashMap; import java.util.Map; import java.util.Optional; -import javax.annotation.Nullable; -import javax.validation.constraints.NotNull; @SuperBuilder @ToString diff --git a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java index 54218041a1..813bf43d6d 100644 --- a/core/src/main/java/io/kestra/core/validations/ValidationFactory.java +++ b/core/src/main/java/io/kestra/core/validations/ValidationFactory.java @@ -15,7 +15,6 @@ import jakarta.inject.Named; import jakarta.inject.Singleton; -import javax.validation.ConstraintViolation; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; @@ -193,6 +192,18 @@ ConstraintValidator<FlowValidation, Flow> flowValidation() { violations.add("Duplicate task id with name [" + String.join(", ", taskDuplicates) + "]"); } + value.allTasksWithChilds() + .stream() + .forEach( + task -> { + if (task instanceof io.kestra.core.tasks.flows.Flow taskFlow + && taskFlow.getFlowId().equals(value.getId()) + && taskFlow.getNamespace().equals(value.getNamespace())) { + violations.add("Recursive call to flow [" + value.getId() + "]"); + } + } + ); + // input unique name if (value.getInputs() != null) { List<String> inputNames = value.getInputs()
diff --git a/core/src/test/java/io/kestra/core/validations/FlowValidationTest.java b/core/src/test/java/io/kestra/core/validations/FlowValidationTest.java new file mode 100644 index 0000000000..12747c8668 --- /dev/null +++ b/core/src/test/java/io/kestra/core/validations/FlowValidationTest.java @@ -0,0 +1,44 @@ +package io.kestra.core.validations; + +import io.kestra.core.models.flows.Flow; +import io.kestra.core.models.validations.ModelValidator; +import io.kestra.core.serializers.YamlFlowParser; +import io.kestra.core.utils.TestsUtils; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import jakarta.inject.Inject; +import org.junit.jupiter.api.Test; + +import javax.validation.ConstraintViolationException; +import java.io.File; +import java.net.URL; +import java.util.Optional; + +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; + +@MicronautTest +class FlowValidationTest { + @Inject + private ModelValidator modelValidator; + @Inject + YamlFlowParser yamlFlowParser = new YamlFlowParser(); + + @Test + void invalidRecursiveFlow() { + Flow flow = this.parse("flows/invalids/recursive-flow.yaml"); + Optional<ConstraintViolationException> validate = modelValidator.isValid(flow); + + assertThat(validate.isPresent(), is(true)); + assertThat(validate.get().getMessage(), containsString(": Invalid Flow: Recursive call to flow [recursive-flow]")); + } + + private Flow parse(String path) { + URL resource = TestsUtils.class.getClassLoader().getResource(path); + assert resource != null; + + File file = new File(resource.getFile()); + + return yamlFlowParser.parse(file, Flow.class); + } +} diff --git a/core/src/test/resources/flows/invalids/recursive-flow.yaml b/core/src/test/resources/flows/invalids/recursive-flow.yaml new file mode 100644 index 0000000000..47c80ae769 --- /dev/null +++ b/core/src/test/resources/flows/invalids/recursive-flow.yaml @@ -0,0 +1,8 @@ +id: recursive-flow +namespace: io.kestra.tests + +tasks: + - id: taskInvalid + type: io.kestra.core.tasks.flows.Flow + flowId: recursive-flow + namespace: io.kestra.tests \ No newline at end of file
train
train
2023-06-30T09:51:58
"2023-06-08T13:45:49Z"
Skraye
train
kestra-io/kestra/1383_1650
kestra-io/kestra
kestra-io/kestra/1383
kestra-io/kestra/1650
[ "keyword_pr_to_issue" ]
fdd1579926c0c6225de72938915324d9f069eed6
c5c683aeae54f82368dedb5502a55c4368b659d7
[]
[ "Required for class like Retry where they have a \"type\" property that we want to keep", "It is a bit tricky here, we must force default value if the property is required because, however, even if the property is visually filled in the input, it will not be in the javascript object that represents the task ", "Cast is necessary because we have now two `flatten` method with 3 params that could works with a null as a 3rd parameter", "There may be multiple `type` that we will need to keep, better to extract that in a dedicated method like `isTypeToKeep(entry.getKey)` I also think that if there is a class related exception we should just goes with the default (so returning null)", "The `onInput` method has been removed, are you sure it's correct here?", "This class is for the documentation but the validation should occurs on the JsonSchema so I have mixed feelings here ...", "Yes because we use the mixins Task that already have the `onInput` method which is the good one for this component, the `onInput` on this component was overriding the other one.", "Well, I just ask to be extracted to a method, not need to create a list with one element this seems overcomplicated ;)", "@Skraye can you explain why it is in the documentation part and not on the jsonschema?", "Well, if we face another issue similar with a type property, we just need to add `Class.class` and its done", "If we face another issue we just nee to switch to a list and iterate over it.\r\nKISS, don't optimize for a potential future that will never happen" ]
"2023-06-27T19:39:08Z"
[ "bug" ]
Retry not handle as an object and can't be edited in task editor
### Expected Behavior Should be able to edit retry ### Actual Behaviour If a retry exists, it will not be displayed as an object. Also, it cannot be edited. ![image](https://github.com/kestra-io/kestra/assets/37600690/8d525b06-21dc-4914-9751-9aa556e9f9f0) ### Steps To Reproduce _No response_ ### Environment Information - Kestra Version: 0.9.0 ### Example flow _No response_
[ "core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java", "ui/src/components/flows/tasks/Task.js", "ui/src/components/flows/tasks/TaskObject.vue", "ui/src/utils/init.js" ]
[ "core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java", "ui/src/components/flows/tasks/Task.js", "ui/src/components/flows/tasks/TaskAnyOf.vue", "ui/src/components/flows/tasks/TaskObject.vue", "ui/src/utils/init.js" ]
[]
diff --git a/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java b/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java index 6fc592c42b..541cc2a006 100644 --- a/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java +++ b/core/src/main/java/io/kestra/core/docs/AbstractClassDocumentation.java @@ -1,7 +1,12 @@ package io.kestra.core.docs; import com.google.common.base.CaseFormat; -import lombok.*; +import io.kestra.core.models.tasks.retrys.AbstractRetry; +import lombok.AllArgsConstructor; +import lombok.EqualsAndHashCode; +import lombok.Getter; +import lombok.ToString; +import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang3.ArrayUtils; import java.util.*; @@ -10,6 +15,7 @@ @Getter @EqualsAndHashCode @ToString +@Slf4j public abstract class AbstractClassDocumentation<T> { protected Boolean deprecated; protected String cls; @@ -42,7 +48,7 @@ protected AbstractClassDocumentation(JsonSchemaGenerator jsonSchemaGenerator, Cl .filter(entry -> !entry.getKey().equals("io.kestra.core.models.tasks.Task")) .map(entry -> { Map<String, Object> value = (Map<String, Object>) entry.getValue(); - value.put("properties", flatten(properties(value), required(value))); + value.put("properties", flatten(properties(value), required(value), isTypeToKeep(entry.getKey()))); return new AbstractMap.SimpleEntry<>( entry.getKey(), @@ -80,7 +86,14 @@ protected AbstractClassDocumentation(JsonSchemaGenerator jsonSchemaGenerator, Cl protected static Map<String, Object> flatten(Map<String, Object> map, List<String> required) { map.remove("type"); - return flatten(map, required, null); + return flatten(map, required, (String) null); + } + + protected static Map<String, Object> flatten(Map<String, Object> map, List<String> required, Boolean keepType) { + if (!keepType) { + map.remove("type"); + } + return flatten(map, required, (String) null); } @SuppressWarnings("unchecked") @@ -114,6 +127,19 @@ protected static Map<String, Object> flatten(Map<String, Object> map, List<Strin return result; } + // Some task can have the `type` property but not to represent the task + // so we cant to keep it in the doc + private Boolean isTypeToKeep(String key){ + try { + if (AbstractRetry.class.isAssignableFrom(Class.forName(key))) { + return true; + } + } catch (ClassNotFoundException ignored) { + log.debug(ignored.getMessage(), ignored); + } + return false; + } + protected static String flattenKey(String current, String parent) { return (parent != null ? parent + "." : "") + current; } diff --git a/ui/src/components/flows/tasks/Task.js b/ui/src/components/flows/tasks/Task.js index 81cf131868..2ec5a4a846 100644 --- a/ui/src/components/flows/tasks/Task.js +++ b/ui/src/components/flows/tasks/Task.js @@ -58,6 +58,10 @@ export default { return "number"; } + if (Object.prototype.hasOwnProperty.call(property, "anyOf")) { + return "anyOf"; + } + return property.type || "dynamic"; }, // eslint-disable-next-line no-unused-vars diff --git a/ui/src/components/flows/tasks/TaskAnyOf.vue b/ui/src/components/flows/tasks/TaskAnyOf.vue new file mode 100644 index 0000000000..f2bdc65da3 --- /dev/null +++ b/ui/src/components/flows/tasks/TaskAnyOf.vue @@ -0,0 +1,113 @@ +<template> + <el-input + :model-value="JSON.stringify(values)" + :disabled="true" + > + <template #append> + <el-button :icon="Eye" @click="isOpen = true"/> + </template> + </el-input> + + + <el-drawer + v-if="isOpen" + v-model="isOpen" + destroy-on-close + size="" + :append-to-body="true" + > + <template #header> + <code>{{ root }}</code> + </template> + <el-form-item> + <template #label> + <span class="d-flex flex-grow-1"> + <span class="me-auto"> + <code> Any of</code>&nbsp; + </span> + </span> + </template> + <el-select + :model-value="selectedSchema" + @update:model-value="onSelect" + > + <el-option + v-for="schema in schemaOptions" + :key="schema.label" + :label="schema.label" + :value="schema.value" + /> + </el-select> + </el-form-item> + <el-form label-position="top" v-if="selectedSchema"> + <component + :is="`task-${getType(currentSchema)}`" + v-if="currentSchema" + :model-value="modelValue" + @update:model-value="onInput" + :schema="currentSchema" + :definitions="definitions" + /> + </el-form> + <template #footer> + <el-button :icon="ContentSave" @click="isOpen = false" type="primary"> + {{ $t("save") }} + </el-button> + </template> + </el-drawer> +</template> + +<script setup> + import Eye from "vue-material-design-icons/Eye.vue"; + import ContentSave from "vue-material-design-icons/ContentSave.vue"; + import Markdown from "../../layout/Markdown.vue"; + import Help from "vue-material-design-icons/HelpBox.vue"; + import TaskObject from "./TaskObject.vue"; +</script> + +<script> + import Task from "./Task" + + export default { + mixins: [Task], + data() { + return { + isOpen: false, + schemas: [], + selectedSchema: undefined + }; + }, + created() { + this.schemas = this.schema?.anyOf ?? [] + }, + methods: { + onSelect(value) { + this.selectedSchema = value + // Set up default values + if (this.currentSchema.properties && this.modelValue === undefined) { + const defaultValues = {}; + for (let prop in this.currentSchema.properties) { + if(this.currentSchema.properties[prop].$required && this.currentSchema.properties[prop].default) { + defaultValues[prop] = this.currentSchema.properties[prop].default + } + } + this.onInput(defaultValues); + } + } + }, + computed: { + currentSchema() { + return this.definitions[this.selectedSchema] ?? {type: this.selectedSchema} + }, + schemaOptions() { + return this.schemas.map(schema => { + const label = schema.$ref ? schema.$ref.split("/").pop() : schema.type + return { + label: label.capitalize(), + value: label + } + }) + } + }, + }; +</script> diff --git a/ui/src/components/flows/tasks/TaskObject.vue b/ui/src/components/flows/tasks/TaskObject.vue index 7da04dbdd6..9188034965 100644 --- a/ui/src/components/flows/tasks/TaskObject.vue +++ b/ui/src/components/flows/tasks/TaskObject.vue @@ -26,7 +26,7 @@ <component :is="`task-${getType(schema)}`" :model-value="getPropertiesValue(key)" - @update:model-value="onInput(key, $event)" + @update:model-value="onObjectInput(key, $event)" :root="getKey(key)" :schema="schema" :required="isRequired(key)" @@ -40,6 +40,7 @@ :root="root" :schema="schema" :definitions="definitions" + @update:model-value="onInput" /> </template> </template> @@ -69,16 +70,11 @@ properties() { if (this.schema) { const properties = this.schema.properties - return this.sortProperties(properties) } return undefined; - }, - editorValue() { - const stringify = YamlUtils.stringify(toRaw(this.modelValue)); - return stringify.trim() === "{}" ? "" : stringify; - }, + } }, methods: { getPropertiesValue(properties) { @@ -125,7 +121,7 @@ return result }, {}); }, - onInput(properties, value) { + onObjectInput(properties, value) { const currentValue = this.modelValue || {}; currentValue[properties] = value; this.$emit("update:modelValue", currentValue); diff --git a/ui/src/utils/init.js b/ui/src/utils/init.js index f7ed873c78..5f4a98982c 100644 --- a/ui/src/utils/init.js +++ b/ui/src/utils/init.js @@ -43,6 +43,7 @@ import TaskNumber from "../components/flows/tasks/TaskNumber.vue"; import TaskObject from "../components/flows/tasks/TaskObject.vue"; import TaskString from "../components/flows/tasks/TaskString.vue"; import TaskTask from "../components/flows/tasks/TaskTask.vue"; +import TaskAnyOf from "../components/flows/tasks/TaskAnyOf.vue"; export default (app, routes, stores, translations) => { // charts @@ -137,6 +138,7 @@ export default (app, routes, stores, translations) => { app.component("TaskComplex", TaskComplex) app.component("TaskString", TaskString) app.component("TaskTask", TaskTask) + app.component("TaskAnyOf", TaskAnyOf) return {store, router}; }
null
train
train
2023-11-17T16:48:11
"2023-05-23T09:09:09Z"
Skraye
train