mirror of
https://github.com/dagucloud/dagu.git
synced 2026-12-05 21:34:48 +00:00
771 lines
20 KiB
Go
771 lines
20 KiB
Go
// Copyright (C) 2026 Yota Hamada
|
|
// SPDX-License-Identifier: GPL-3.0-or-later
|
|
|
|
package engine
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"maps"
|
|
"os"
|
|
"path/filepath"
|
|
goruntime "runtime"
|
|
"sort"
|
|
"strings"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/artifactpath"
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/config"
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/fileutil"
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/logger"
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/logger/tag"
|
|
"github.com/dagucloud/dagu/v2/internal/cmn/logpath"
|
|
"github.com/dagucloud/dagu/v2/internal/dagrun"
|
|
"github.com/dagucloud/dagu/v2/internal/dispatch"
|
|
"github.com/dagucloud/dagu/v2/internal/ir"
|
|
"github.com/dagucloud/dagu/v2/internal/persis"
|
|
filematerialization "github.com/dagucloud/dagu/v2/internal/persis/file/materialization"
|
|
"github.com/dagucloud/dagu/v2/internal/proc"
|
|
rtagent "github.com/dagucloud/dagu/v2/internal/runtime/agent"
|
|
runtimeexec "github.com/dagucloud/dagu/v2/internal/runtime/executor"
|
|
"github.com/dagucloud/dagu/v2/internal/spec"
|
|
"github.com/dagucloud/dagu/v2/internal/workspace"
|
|
)
|
|
|
|
func (e *Engine) RunFile(ctx context.Context, path string, opts RunOptions) (*Run, error) {
|
|
ctx = e.context(ctx)
|
|
dag, err := e.loadFile(ctx, path, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return e.runLoaded(ctx, dag, opts)
|
|
}
|
|
|
|
func (e *Engine) RunYAML(ctx context.Context, data []byte, opts RunOptions) (*Run, error) {
|
|
ctx = e.context(ctx)
|
|
dag, err := e.loadYAML(ctx, data, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return e.runLoaded(ctx, dag, opts)
|
|
}
|
|
|
|
func (e *Engine) Status(ctx context.Context, ref RunRef) (*Status, error) {
|
|
ctx = e.context(ctx)
|
|
if ref.Name == "" || ref.ID == "" {
|
|
return nil, fmt.Errorf("run name and ID are required")
|
|
}
|
|
status, err := e.readStatus(ctx, ir.NewDAGRunRef(ref.Name, ref.ID))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return runStatusToPublic(status)
|
|
}
|
|
|
|
func (e *Engine) Outputs(ctx context.Context, ref RunRef) (map[string]string, error) {
|
|
ctx = e.context(ctx)
|
|
if ref.Name == "" || ref.ID == "" {
|
|
return nil, fmt.Errorf("run name and ID are required")
|
|
}
|
|
outputs, err := e.readOutputs(ctx, ir.NewDAGRunRef(ref.Name, ref.ID))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if outputs == nil {
|
|
return nil, nil
|
|
}
|
|
return cloneStringMap(outputs.Outputs), nil
|
|
}
|
|
|
|
func (e *Engine) Stop(ctx context.Context, ref RunRef) error {
|
|
ctx = e.context(ctx)
|
|
if ref.Name == "" || ref.ID == "" {
|
|
return fmt.Errorf("run name and ID are required")
|
|
}
|
|
runRef := ir.NewDAGRunRef(ref.Name, ref.ID)
|
|
if e.runStateStore != nil {
|
|
attempt, err := e.runStateStore.OpenAttempt(ctx, runRef)
|
|
if err == nil {
|
|
return attempt.RequestCancel(ctx)
|
|
}
|
|
if !e.shouldFallbackToDAGRunRepository(err) {
|
|
return err
|
|
}
|
|
}
|
|
if e.dagRunRepository == nil {
|
|
return fmt.Errorf("DAG-run repository is not configured")
|
|
}
|
|
return e.stopDAGRunRepository(ctx, ref.ID, runRef)
|
|
}
|
|
|
|
func (e *Engine) readStatus(ctx context.Context, ref ir.DAGRunRef) (*ir.DAGRunStatus, error) {
|
|
if e.runStateStore != nil {
|
|
status, err := e.readRunStateStatus(ctx, ref)
|
|
if err == nil {
|
|
return status, nil
|
|
}
|
|
if !e.shouldFallbackToDAGRunRepository(err) {
|
|
return nil, err
|
|
}
|
|
}
|
|
if e.dagRunRepository != nil {
|
|
return e.dagRunMgr.GetSavedStatus(ctx, ref)
|
|
}
|
|
return nil, fmt.Errorf("neither run-state store nor DAG-run repository is configured")
|
|
}
|
|
|
|
func (e *Engine) stopDAGRunRepository(ctx context.Context, dagRunID string, ref ir.DAGRunRef) error {
|
|
attempt, err := e.dagRunRepository.FindAttempt(ctx, ref)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
dag, err := attempt.ReadDAG(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return e.dagRunMgr.Stop(ctx, dag, dagRunID)
|
|
}
|
|
|
|
func (r *Run) Ref() RunRef {
|
|
return r.ref
|
|
}
|
|
|
|
func (r *Run) ID() string {
|
|
return r.ref.ID
|
|
}
|
|
|
|
func (r *Run) Name() string {
|
|
return r.ref.Name
|
|
}
|
|
|
|
func (r *Run) Wait(ctx context.Context) (*Status, error) {
|
|
if r.mode == ExecutionModeDistributed {
|
|
return r.waitDistributed(ctx)
|
|
}
|
|
return r.waitLocal(ctx)
|
|
}
|
|
|
|
func (r *Run) Status(ctx context.Context) (*Status, error) {
|
|
if r.mode == ExecutionModeDistributed {
|
|
result, err := r.coordinator.GetDAGRunStatus(ctx, r.ref.Name, r.ref.ID, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if result == nil || !result.Found || result.Status == nil {
|
|
return nil, nil
|
|
}
|
|
return runStatusToPublic(result.Status)
|
|
}
|
|
if r.agent != nil {
|
|
select {
|
|
case <-r.done:
|
|
default:
|
|
status := r.agent.Status(ctx)
|
|
return statusFromValue(status)
|
|
}
|
|
}
|
|
return r.engine.Status(ctx, r.ref)
|
|
}
|
|
|
|
func (r *Run) Outputs(ctx context.Context) (map[string]string, error) {
|
|
return r.engine.Outputs(ctx, r.ref)
|
|
}
|
|
|
|
func (r *Run) Stop(ctx context.Context) error {
|
|
if r.mode == ExecutionModeDistributed {
|
|
if r.cancel != nil {
|
|
r.cancel()
|
|
}
|
|
err := r.coordinator.RequestCancel(ctx, r.ref.Name, r.ref.ID, nil)
|
|
if cleanupErr := r.cleanupCoordinator(context.Background()); err == nil && cleanupErr != nil {
|
|
err = cleanupErr
|
|
}
|
|
return err
|
|
}
|
|
if r.agent != nil {
|
|
r.agent.Signal(ctx, syscall.SIGTERM)
|
|
}
|
|
if r.cancel != nil {
|
|
r.cancel()
|
|
}
|
|
return r.engine.Stop(ctx, r.ref)
|
|
}
|
|
|
|
func (e *Engine) readRunStateStatus(ctx context.Context, ref ir.DAGRunRef) (*ir.DAGRunStatus, error) {
|
|
attempt, err := e.runStateStore.OpenAttempt(ctx, ref)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
status, err := attempt.ReadStatus(ctx)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return status, nil
|
|
}
|
|
|
|
func (e *Engine) readOutputs(ctx context.Context, ref ir.DAGRunRef) (*ir.DAGRunOutputs, error) {
|
|
if e.runStateStore != nil {
|
|
outputs, err := e.readRunStateOutputs(ctx, ref)
|
|
if err == nil {
|
|
return outputs, nil
|
|
}
|
|
if !e.shouldFallbackToDAGRunRepository(err) {
|
|
return nil, err
|
|
}
|
|
}
|
|
if e.dagRunRepository != nil {
|
|
return e.readDAGRunOutputs(ctx, ref)
|
|
}
|
|
return nil, fmt.Errorf("neither run-state store nor DAG-run repository is configured")
|
|
}
|
|
|
|
func (e *Engine) readRunStateOutputs(ctx context.Context, ref ir.DAGRunRef) (*ir.DAGRunOutputs, error) {
|
|
attempt, err := e.runStateStore.OpenAttempt(ctx, ref)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return attempt.ReadOutputs(ctx)
|
|
}
|
|
|
|
func (e *Engine) readDAGRunOutputs(ctx context.Context, ref ir.DAGRunRef) (*ir.DAGRunOutputs, error) {
|
|
attempt, err := e.dagRunRepository.FindAttempt(ctx, ref)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return attempt.ReadOutputs(ctx)
|
|
}
|
|
|
|
func (e *Engine) shouldFallbackToDAGRunRepository(err error) bool {
|
|
return e.dagRunRepository != nil && errors.Is(err, dagrun.ErrDAGRunIDNotFound)
|
|
}
|
|
|
|
func (r *Run) waitLocal(ctx context.Context) (*Status, error) {
|
|
select {
|
|
case <-r.done:
|
|
err := r.doneError()
|
|
status, statusErr := r.statusWithFinalTimeout()
|
|
if statusErr != nil && err == nil {
|
|
err = statusErr
|
|
}
|
|
if err != nil {
|
|
return status, err
|
|
}
|
|
if !isSuccess(status) {
|
|
return status, fmt.Errorf("DAG run finished with status %s", status.Status)
|
|
}
|
|
return status, nil
|
|
case <-ctx.Done():
|
|
status, _ := r.statusWithFinalTimeout()
|
|
return status, ctx.Err()
|
|
}
|
|
}
|
|
|
|
func (r *Run) waitDistributed(ctx context.Context) (*Status, error) {
|
|
defer func() {
|
|
_ = r.cleanupCoordinator(context.Background())
|
|
}()
|
|
poll := r.engine.distributed.PollInterval
|
|
if poll <= 0 {
|
|
poll = time.Second
|
|
}
|
|
maxErrors := r.engine.distributed.MaxStatusErrors
|
|
if maxErrors <= 0 {
|
|
maxErrors = 10
|
|
}
|
|
ticker := time.NewTicker(poll)
|
|
defer ticker.Stop()
|
|
consecutiveErrors := 0
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
status, _ := r.statusWithFinalTimeout()
|
|
return status, ctx.Err()
|
|
case <-ticker.C:
|
|
status, err := r.Status(ctx)
|
|
if err != nil {
|
|
consecutiveErrors++
|
|
if consecutiveErrors >= maxErrors {
|
|
return nil, fmt.Errorf("lost connection to coordinator after %d attempts: %w", consecutiveErrors, err)
|
|
}
|
|
continue
|
|
}
|
|
consecutiveErrors = 0
|
|
if status == nil {
|
|
continue
|
|
}
|
|
if !isActiveStatus(status.Status) {
|
|
if isSuccess(status) {
|
|
r.markDone(nil)
|
|
return status, nil
|
|
}
|
|
if status.Error != "" {
|
|
err := fmt.Errorf("DAG run failed with status %s: %s", status.Status, status.Error)
|
|
r.markDone(err)
|
|
return status, err
|
|
}
|
|
err := fmt.Errorf("DAG run failed with status %s", status.Status)
|
|
r.markDone(err)
|
|
return status, err
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (r *Run) statusWithFinalTimeout() (*Status, error) {
|
|
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer cancel()
|
|
return r.Status(ctx)
|
|
}
|
|
|
|
func (e *Engine) loadFile(ctx context.Context, path string, opts RunOptions) (*ir.DAG, error) {
|
|
loadOpts := e.loadOptions(opts)
|
|
dag, err := spec.Load(ctx, path, loadOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if dag.SourceFile == "" {
|
|
dag.SourceFile = path
|
|
}
|
|
applyRunOverrides(dag, opts)
|
|
return dag, nil
|
|
}
|
|
|
|
func (e *Engine) loadYAML(ctx context.Context, data []byte, opts RunOptions) (*ir.DAG, error) {
|
|
loadOpts := e.loadOptions(opts)
|
|
dag, err := spec.LoadYAML(ctx, data, loadOpts...)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
applyRunOverrides(dag, opts)
|
|
return dag, nil
|
|
}
|
|
|
|
func (e *Engine) loadOptions(opts RunOptions) []spec.LoadOption {
|
|
loadOpts := []spec.LoadOption{
|
|
spec.WithBaseConfig(e.cfg.Paths.BaseConfig),
|
|
spec.WithWorkspaceBaseConfigDir(workspace.BaseConfigDir(e.cfg.Paths.DAGsDir)),
|
|
spec.WithDAGsDir(e.cfg.Paths.DAGsDir),
|
|
}
|
|
if opts.Name != "" {
|
|
loadOpts = append(loadOpts, spec.WithName(opts.Name))
|
|
}
|
|
if opts.DefaultWorkingDir != "" {
|
|
loadOpts = append(loadOpts, spec.WithDefaultWorkingDir(opts.DefaultWorkingDir))
|
|
}
|
|
if len(opts.ParamsList) > 0 {
|
|
loadOpts = append(loadOpts, spec.WithParams(opts.ParamsList))
|
|
} else {
|
|
loadOpts = append(loadOpts, spec.WithParams(paramsMapToList(opts.Params)))
|
|
}
|
|
return loadOpts
|
|
}
|
|
|
|
func applyRunOverrides(dag *ir.DAG, opts RunOptions) {
|
|
// Name, DefaultWorkingDir, and params are handled during loading; only
|
|
// overrides that must mutate the loaded DAG belong here.
|
|
if len(opts.WorkerSelector) > 0 {
|
|
dag.WorkerSelector = cloneStringMap(opts.WorkerSelector)
|
|
}
|
|
if len(opts.Labels) > 0 {
|
|
seen := make(map[string]struct{}, len(dag.Labels)+len(opts.Labels))
|
|
for _, existing := range dag.Labels {
|
|
seen[existing.String()] = struct{}{}
|
|
}
|
|
for _, candidate := range ir.NewLabels(opts.Labels) {
|
|
key := candidate.String()
|
|
if _, ok := seen[key]; ok {
|
|
continue
|
|
}
|
|
seen[key] = struct{}{}
|
|
dag.Labels = append(dag.Labels, candidate)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (e *Engine) runLoaded(ctx context.Context, dag *ir.DAG, opts RunOptions) (*Run, error) {
|
|
if err := dag.Validate(); err != nil {
|
|
return nil, err
|
|
}
|
|
runID := opts.RunID
|
|
if runID == "" {
|
|
id, err := ir.NewDAGRunID()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
runID = id
|
|
} else if err := ir.ValidateDAGRunID(runID); err != nil {
|
|
return nil, err
|
|
}
|
|
mode := opts.Mode
|
|
if mode == "" {
|
|
mode = e.defaultMode
|
|
}
|
|
if mode == "" {
|
|
mode = ExecutionModeLocal
|
|
}
|
|
switch mode {
|
|
case ExecutionModeLocal:
|
|
return e.runLocal(ctx, dag, runID, opts)
|
|
case ExecutionModeDistributed:
|
|
return e.runDistributed(ctx, dag, runID, opts)
|
|
default:
|
|
return nil, fmt.Errorf("unsupported execution mode %q", mode)
|
|
}
|
|
}
|
|
|
|
func (e *Engine) runLocal(ctx context.Context, dag *ir.DAG, runID string, opts RunOptions) (*Run, error) {
|
|
logFile, err := e.openLogFile(ctx, dag, runID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
artifactDir, err := e.artifactDir(ctx, dag, runID)
|
|
if err != nil {
|
|
_ = logFile.Close()
|
|
return nil, err
|
|
}
|
|
dagRepository, err := e.dagRepositoryFactory(ctx, e.cfg, DAGRepositoryFactoryOptions{
|
|
SearchPaths: []string{filepath.Dir(dag.Location)},
|
|
})
|
|
if err != nil {
|
|
_ = logFile.Close()
|
|
return nil, err
|
|
}
|
|
root := ir.NewDAGRunRef(dag.Name, runID)
|
|
var prepared *localPreparation
|
|
if !opts.DryRun {
|
|
prepared, err = e.prepareLocal(ctx, dag, runID, root)
|
|
if err != nil {
|
|
_ = logFile.Close()
|
|
return nil, err
|
|
}
|
|
}
|
|
|
|
stores := e.runtimeStores(ctx)
|
|
attempt := preparedAttempt(prepared)
|
|
runStateStore := e.runStateStore
|
|
if runStateStore == nil {
|
|
runStateStore = persis.NewRunStateStore(e.dagRunRepository, attempt)
|
|
}
|
|
attemptID := ""
|
|
if attempt != nil {
|
|
attemptID = attempt.ID()
|
|
}
|
|
agentInstance := rtagent.New(
|
|
runID,
|
|
dag,
|
|
filepath.Dir(logFile.Name()),
|
|
logFile.Name(),
|
|
e.dagRunMgr,
|
|
dagRepository,
|
|
rtagent.Options{
|
|
Dry: opts.DryRun,
|
|
WorkerID: "local",
|
|
AttemptID: attemptID,
|
|
RunStateStore: runStateStore,
|
|
StateStore: e.stateStore,
|
|
MaterializationStore: stores.MaterializationStore,
|
|
NoReuse: opts.NoReuse,
|
|
SecretStore: stores.SecretStore,
|
|
ProfileStore: stores.ProfileStore,
|
|
ServiceRegistry: e.serviceRegistry,
|
|
SubWorkflowRunnerFactory: e.subWorkflowRunnerFactory(stores),
|
|
RootDAGRun: root,
|
|
PeerConfig: e.cfg.Core.Peer,
|
|
TriggerType: ir.TriggerTypeManual,
|
|
DefaultExecMode: configExecutionMode(e.defaultMode),
|
|
ArtifactDir: artifactDir,
|
|
},
|
|
)
|
|
|
|
runCtx, cancel := context.WithCancel(ctx)
|
|
done := make(chan struct{})
|
|
run := &Run{
|
|
engine: e,
|
|
ref: RunRef{Name: dag.Name, ID: runID},
|
|
mode: ExecutionModeLocal,
|
|
cancel: cancel,
|
|
done: done,
|
|
agent: agentInstance,
|
|
dag: dag,
|
|
}
|
|
|
|
go func() {
|
|
var err error
|
|
defer func() {
|
|
_ = logFile.Close()
|
|
if prepared != nil && prepared.proc != nil {
|
|
_ = prepared.proc.Stop(context.Background())
|
|
}
|
|
run.markDone(err)
|
|
}()
|
|
runCtx = logger.WithLogger(config.WithConfig(runCtx, e.cfg), e.logger)
|
|
err = agentInstance.Run(runCtx)
|
|
if err != nil {
|
|
logger.Error(runCtx, "Embedded DAG run failed",
|
|
tag.DAG(dag.Name),
|
|
tag.RunID(runID),
|
|
tag.Error(err),
|
|
)
|
|
}
|
|
}()
|
|
|
|
return run, nil
|
|
}
|
|
|
|
func (e *Engine) runDistributed(ctx context.Context, dag *ir.DAG, runID string, opts RunOptions) (*Run, error) {
|
|
if dag.Type == ir.TypeBuild {
|
|
return nil, dispatch.ErrBuildRequiresLocal
|
|
}
|
|
dist := e.distributed
|
|
if len(opts.WorkerSelector) > 0 {
|
|
dist.WorkerSelector = cloneStringMap(opts.WorkerSelector)
|
|
}
|
|
client, err := e.coordinatorClient(dist)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
taskOpts := []runtimeexec.TaskOption{
|
|
runtimeexec.WithBaseConfig(runtimeexec.ResolveBaseConfig(dag.BaseConfigData, e.cfg.Paths.BaseConfig), dag.BaseConfigWorkspace),
|
|
}
|
|
if len(dist.WorkerSelector) > 0 {
|
|
taskOpts = append(taskOpts, runtimeexec.WithWorkerSelector(dist.WorkerSelector))
|
|
}
|
|
if len(dag.Labels) > 0 {
|
|
taskOpts = append(taskOpts, runtimeexec.WithLabels(strings.Join(dag.Labels.Strings(), ",")))
|
|
}
|
|
if dag.SourceFile != "" {
|
|
taskOpts = append(taskOpts, runtimeexec.WithSourceFile(dag.SourceFile))
|
|
} else if dag.WorkingDir != "" {
|
|
taskOpts = append(taskOpts, runtimeexec.WithSourceWorkDir(dag.WorkingDir))
|
|
}
|
|
task := runtimeexec.CreateTask(
|
|
dag.Name,
|
|
string(dag.YamlData),
|
|
dispatch.DispatchOperationStart,
|
|
runID,
|
|
taskOpts...,
|
|
)
|
|
if len(dag.Params) > 0 {
|
|
task.Params = strings.Join(dag.Params, " ")
|
|
}
|
|
if err := client.Dispatch(ctx, dispatch.DispatchRequest{Task: task}); err != nil {
|
|
_ = client.Cleanup(ctx)
|
|
return nil, fmt.Errorf("dispatch DAG run: %w", err)
|
|
}
|
|
run := &Run{
|
|
engine: e,
|
|
ref: RunRef{Name: dag.Name, ID: runID},
|
|
mode: ExecutionModeDistributed,
|
|
done: make(chan struct{}),
|
|
dag: dag,
|
|
coordinator: client,
|
|
}
|
|
goruntime.SetFinalizer(run, func(r *Run) {
|
|
_ = r.cleanupCoordinator(context.Background())
|
|
})
|
|
return run, nil
|
|
}
|
|
|
|
func (r *Run) markDone(err error) {
|
|
r.setDoneError(err)
|
|
if r.done == nil {
|
|
return
|
|
}
|
|
r.doneOnce.Do(func() {
|
|
close(r.done)
|
|
})
|
|
}
|
|
|
|
func (r *Run) cleanupCoordinator(ctx context.Context) error {
|
|
if r == nil || r.coordinator == nil {
|
|
return nil
|
|
}
|
|
err := r.coordinator.Cleanup(ctx)
|
|
goruntime.SetFinalizer(r, nil)
|
|
return err
|
|
}
|
|
|
|
func (r *Run) setDoneError(err error) {
|
|
r.doneErrMu.Lock()
|
|
defer r.doneErrMu.Unlock()
|
|
r.doneErr = err
|
|
}
|
|
|
|
func (r *Run) doneError() error {
|
|
r.doneErrMu.RLock()
|
|
defer r.doneErrMu.RUnlock()
|
|
return r.doneErr
|
|
}
|
|
|
|
func (e *Engine) prepareLocal(ctx context.Context, dag *ir.DAG, runID string, root ir.DAGRunRef) (*localPreparation, error) {
|
|
var preparation *localPreparation
|
|
err := e.procRepository.WithLock(ctx, dag.ProcGroup(), func() error {
|
|
var err error
|
|
preparation, err = e.prepareLocalLocked(ctx, dag, runID, root)
|
|
return err
|
|
})
|
|
if err != nil {
|
|
if persis.IsProcLockError(err) {
|
|
return nil, fmt.Errorf("lock process group: %w", err)
|
|
}
|
|
return nil, err
|
|
}
|
|
return preparation, nil
|
|
}
|
|
|
|
func (e *Engine) prepareLocalLocked(ctx context.Context, dag *ir.DAG, runID string, root ir.DAGRunRef) (*localPreparation, error) {
|
|
var attempt dagrun.Attempt
|
|
attemptID := runID
|
|
if e.dagRunRepository != nil {
|
|
created, err := e.dagRunRepository.CreateAttempt(ctx, dag, time.Now(), runID, persis.DAGRunCreateAttemptOptions{})
|
|
if err != nil {
|
|
if errors.Is(err, dagrun.ErrDAGRunAlreadyExists) {
|
|
return nil, fmt.Errorf("dag-run ID %s already exists for DAG %s: %w", runID, dag.Name, err)
|
|
}
|
|
return nil, fmt.Errorf("create DAG run attempt: %w", err)
|
|
}
|
|
attempt = created
|
|
attemptID = created.ID()
|
|
} else if e.runStateStore != nil {
|
|
if _, err := e.runStateStore.OpenAttempt(ctx, root); err == nil {
|
|
return nil, fmt.Errorf("%w: %s", dagrun.ErrDAGRunAlreadyExists, runID)
|
|
} else if !errors.Is(err, dagrun.ErrDAGRunIDNotFound) {
|
|
return nil, fmt.Errorf("check existing run-state attempt: %w", err)
|
|
}
|
|
}
|
|
handle, err := e.procRepository.Acquire(ctx, dag.ProcGroup(), proc.ProcMeta{
|
|
StartedAt: time.Now().Unix(),
|
|
Name: dag.Name,
|
|
DAGRunID: runID,
|
|
AttemptID: attemptID,
|
|
RootName: root.Name,
|
|
RootDAGRunID: root.ID,
|
|
})
|
|
if err != nil {
|
|
if attempt != nil {
|
|
_ = e.recordPreparedFailure(ctx, attempt, dag, runID, root, err)
|
|
}
|
|
return nil, fmt.Errorf("acquire process handle: %w", err)
|
|
}
|
|
return &localPreparation{attempt: attempt, proc: handle}, nil
|
|
}
|
|
|
|
func (e *Engine) recordPreparedFailure(
|
|
ctx context.Context,
|
|
attempt dagrun.Attempt,
|
|
dag *ir.DAG,
|
|
runID string,
|
|
root ir.DAGRunRef,
|
|
runErr error,
|
|
) error {
|
|
logFile, logErr := logpath.Generate(ctx, e.cfg.Paths.LogDir, dag.LogDir, dag.Name, runID)
|
|
if logErr != nil {
|
|
logger.Warn(ctx, "Failed to generate log path for prepared local execution failure", tag.Error(logErr))
|
|
}
|
|
artifactDir, artifactErr := e.artifactDir(ctx, dag, runID)
|
|
if artifactErr != nil {
|
|
logger.Warn(ctx, "Failed to generate artifact path for prepared local execution failure", tag.Error(artifactErr))
|
|
}
|
|
status := ir.NewStatusBuilder(dag).Create(
|
|
runID,
|
|
ir.Failed,
|
|
0,
|
|
time.Now(),
|
|
ir.WithAttemptID(attempt.ID()),
|
|
ir.WithHierarchyRefs(root, ir.DAGRunRef{}),
|
|
ir.WithLogFilePath(logFile),
|
|
ir.WithArchiveDir(artifactDir),
|
|
ir.WithFinishedAt(time.Now()),
|
|
ir.WithError(runErr.Error()),
|
|
ir.WithWorkerID("local"),
|
|
ir.WithTriggerType(ir.TriggerTypeManual),
|
|
)
|
|
if err := attempt.Open(ctx); err != nil {
|
|
return err
|
|
}
|
|
defer func() {
|
|
_ = attempt.Close(ctx)
|
|
}()
|
|
return attempt.Write(ctx, status)
|
|
}
|
|
|
|
func (e *Engine) openLogFile(ctx context.Context, dag *ir.DAG, runID string) (*os.File, error) {
|
|
path, err := logpath.Generate(ctx, e.cfg.Paths.LogDir, dag.LogDir, dag.Name, runID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return fileutil.OpenOrCreateFile(path)
|
|
}
|
|
|
|
func (e *Engine) artifactDir(ctx context.Context, dag *ir.DAG, runID string) (string, error) {
|
|
if dag == nil || !dag.ArtifactsEnabled() {
|
|
return "", nil
|
|
}
|
|
dagArtifactDir := ""
|
|
if dag.Artifacts != nil {
|
|
dagArtifactDir = dag.Artifacts.Dir
|
|
}
|
|
return artifactpath.NewRunDir(ctx, e.cfg.Paths.ArtifactDir, dagArtifactDir, dag.Name, runID, time.Now())
|
|
}
|
|
|
|
func (e *Engine) runtimeStores(ctx context.Context) RuntimeStores {
|
|
var stores RuntimeStores
|
|
if e.runtimeStoresFactory != nil {
|
|
stores = e.runtimeStoresFactory(ctx, e.cfg)
|
|
}
|
|
if stores.MaterializationStore == nil {
|
|
stores.MaterializationStore = filematerialization.New(filepath.Join(e.cfg.Paths.DataDir, "materializations"))
|
|
}
|
|
return stores
|
|
}
|
|
|
|
func preparedAttempt(prepared *localPreparation) dagrun.Attempt {
|
|
if prepared == nil {
|
|
return nil
|
|
}
|
|
return prepared.attempt
|
|
}
|
|
|
|
func paramsMapToList(params map[string]string) []string {
|
|
if len(params) == 0 {
|
|
return nil
|
|
}
|
|
keys := make([]string, 0, len(params))
|
|
for key := range params {
|
|
keys = append(keys, key)
|
|
}
|
|
sort.Strings(keys)
|
|
out := make([]string, 0, len(params))
|
|
for _, key := range keys {
|
|
out = append(out, key+"="+params[key])
|
|
}
|
|
return out
|
|
}
|
|
|
|
func cloneStringMap(values map[string]string) map[string]string {
|
|
if len(values) == 0 {
|
|
return nil
|
|
}
|
|
out := make(map[string]string, len(values))
|
|
maps.Copy(out, values)
|
|
return out
|
|
}
|
|
|
|
func configExecutionMode(mode ExecutionMode) config.ExecutionMode {
|
|
if mode == "" {
|
|
return config.ExecutionModeLocal
|
|
}
|
|
return config.ExecutionMode(mode)
|
|
}
|
|
|
|
func isActiveStatus(status string) bool {
|
|
switch status {
|
|
case ir.Running.String(), ir.Queued.String(), ir.Waiting.String(), ir.NotStarted.String():
|
|
return true
|
|
default:
|
|
return false
|
|
}
|
|
}
|