|
| 1 | +package cli |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + "fmt" |
| 7 | + "io" |
| 8 | + "os" |
| 9 | + "os/exec" |
| 10 | + "path/filepath" |
| 11 | + "runtime" |
| 12 | + "sort" |
| 13 | + "strings" |
| 14 | + "sync" |
| 15 | + |
| 16 | + "github.com/spf13/cobra" |
| 17 | + "golang.org/x/sync/errgroup" |
| 18 | + |
| 19 | + "github.com/open-source-cloud/devstack/internal/config" |
| 20 | + "github.com/open-source-cloud/devstack/internal/generate" |
| 21 | + "github.com/open-source-cloud/devstack/internal/task" |
| 22 | +) |
| 23 | + |
| 24 | +// newRunCmd wires `run <task...>` (spec 31): execute a project's task graph. Tasks |
| 25 | +// are non-container commands with `deps` edges; they run in dependency order, |
| 26 | +// independent tasks in parallel (bounded by --parallel). `run: host` runs on the |
| 27 | +// host; `run: exec` runs inside a service container via compose exec. Streams each |
| 28 | +// task's output live, prefixed by task name. `devstack run` takes no flock — it |
| 29 | +// mutates no shared/ledger state. |
| 30 | +func newRunCmd(g *GlobalOpts) *cobra.Command { |
| 31 | + var project string |
| 32 | + var parallel int |
| 33 | + var dryRun bool |
| 34 | + cmd := &cobra.Command{ |
| 35 | + Use: "run <task> [task2 ...]", |
| 36 | + Short: "Run a project's task graph (deps-ordered, parallel; host or in-container)", |
| 37 | + Args: cobra.MinimumNArgs(1), |
| 38 | + RunE: func(cmd *cobra.Command, args []string) error { |
| 39 | + mgr, closeFn, err := buildManager(cmd) |
| 40 | + if err != nil { |
| 41 | + return err |
| 42 | + } |
| 43 | + defer closeFn() |
| 44 | + |
| 45 | + proj := project |
| 46 | + if proj == "" { |
| 47 | + proj = resolveActiveProject(mgr.Model, mgr.DB) |
| 48 | + } |
| 49 | + if proj == "" { |
| 50 | + return fmt.Errorf("no project selected (pass --project)") |
| 51 | + } |
| 52 | + p, ok := mgr.Model.Projects[proj] |
| 53 | + if !ok { |
| 54 | + return fmt.Errorf("unknown project %q", proj) |
| 55 | + } |
| 56 | + if len(p.Tasks) == 0 { |
| 57 | + return fmt.Errorf("project %q declares no tasks: (add a tasks: block to devstack.yaml)", proj) |
| 58 | + } |
| 59 | + layers, err := task.Plan(p.Tasks, args) |
| 60 | + if err != nil { |
| 61 | + return err |
| 62 | + } |
| 63 | + if dryRun { |
| 64 | + return renderRunPlan(cmd, g, proj, layers) |
| 65 | + } |
| 66 | + if parallel <= 0 { |
| 67 | + parallel = min(8, 2*runtime.NumCPU()) |
| 68 | + } |
| 69 | + projDir := mgr.Model.ProjectDir(proj) |
| 70 | + composeFile := filepath.Join(projDir, generate.GenDir, generate.ComposeFile) |
| 71 | + r := &taskExec{out: cmd.OutOrStdout(), projDir: projDir, composeFile: composeFile} |
| 72 | + return runLayers(cmd.Context(), r, p.Tasks, layers, parallel) |
| 73 | + }, |
| 74 | + } |
| 75 | + cmd.Flags().StringVar(&project, "project", "", "target project (default: the active/first project)") |
| 76 | + cmd.Flags().IntVar(¶llel, "parallel", 0, "max concurrent tasks (default min(8, 2*CPUs))") |
| 77 | + cmd.Flags().BoolVar(&dryRun, "dry-run", false, "print the resolved task DAG and exit") |
| 78 | + return cmd |
| 79 | +} |
| 80 | + |
| 81 | +func renderRunPlan(cmd *cobra.Command, g *GlobalOpts, project string, layers [][]string) error { |
| 82 | + if g.JSON { |
| 83 | + return writeJSON(cmd, map[string]any{"project": project, "layers": layers}) |
| 84 | + } |
| 85 | + w := cmd.OutOrStdout() |
| 86 | + fmt.Fprintf(w, "run plan for %q (%d layer(s)):\n", project, len(layers)) |
| 87 | + for i, l := range layers { |
| 88 | + fmt.Fprintf(w, " %d: %s\n", i+1, strings.Join(l, ", ")) |
| 89 | + } |
| 90 | + return nil |
| 91 | +} |
| 92 | + |
| 93 | +// runLayers executes each layer in order; tasks within a layer run concurrently |
| 94 | +// up to `parallel`. A failing task fails the run (its layer's siblings finish). |
| 95 | +func runLayers(ctx context.Context, r *taskExec, tasks map[string]config.Task, layers [][]string, parallel int) error { |
| 96 | + for _, layer := range layers { |
| 97 | + eg, ectx := errgroup.WithContext(ctx) |
| 98 | + eg.SetLimit(parallel) |
| 99 | + for _, name := range layer { |
| 100 | + name := name |
| 101 | + t := tasks[name] |
| 102 | + eg.Go(func() error { |
| 103 | + if err := r.run(ectx, name, t); err != nil { |
| 104 | + return fmt.Errorf("task %q: %w", name, err) |
| 105 | + } |
| 106 | + return nil |
| 107 | + }) |
| 108 | + } |
| 109 | + if err := eg.Wait(); err != nil { |
| 110 | + return err |
| 111 | + } |
| 112 | + } |
| 113 | + return nil |
| 114 | +} |
| 115 | + |
| 116 | +// taskExec runs a single task with live, name-prefixed output. Concurrent tasks |
| 117 | +// share one output writer, so emit serializes whole (prefix+line) writes under a |
| 118 | +// mutex to keep lines intact and race-free. |
| 119 | +type taskExec struct { |
| 120 | + mu sync.Mutex |
| 121 | + out io.Writer |
| 122 | + projDir string |
| 123 | + composeFile string |
| 124 | +} |
| 125 | + |
| 126 | +// emit writes prefix+data as one atomic unit under the lock. |
| 127 | +func (r *taskExec) emit(prefix string, data []byte) { |
| 128 | + r.mu.Lock() |
| 129 | + defer r.mu.Unlock() |
| 130 | + _, _ = io.WriteString(r.out, prefix) |
| 131 | + _, _ = r.out.Write(data) |
| 132 | +} |
| 133 | + |
| 134 | +func (r *taskExec) run(ctx context.Context, name string, t config.Task) error { |
| 135 | + prefix := name + " | " |
| 136 | + pw := &prefixWriter{emit: r.emit, prefix: prefix} |
| 137 | + env := append(os.Environ(), envKV(t.Env)...) |
| 138 | + |
| 139 | + var c *exec.Cmd |
| 140 | + if t.Run == "exec" { |
| 141 | + if t.Service == "" { |
| 142 | + return fmt.Errorf("run: exec requires a service") |
| 143 | + } |
| 144 | + args := []string{"compose", "-f", r.composeFile, "exec", "-T"} |
| 145 | + if t.Workdir != "" { |
| 146 | + args = append(args, "-w", t.Workdir) |
| 147 | + } |
| 148 | + for _, kv := range envKV(t.Env) { |
| 149 | + args = append(args, "-e", kv) |
| 150 | + } |
| 151 | + args = append(args, t.Service) |
| 152 | + args = append(args, t.Command...) |
| 153 | + c = exec.CommandContext(ctx, "docker", args...) |
| 154 | + c.Dir = r.projDir |
| 155 | + c.Env = env |
| 156 | + } else { |
| 157 | + c = exec.CommandContext(ctx, t.Command[0], t.Command[1:]...) |
| 158 | + c.Dir = taskWorkdir(r.projDir, t.Workdir) |
| 159 | + c.Env = env |
| 160 | + } |
| 161 | + c.Stdout = pw |
| 162 | + c.Stderr = pw |
| 163 | + r.emit(prefix, []byte("→ "+strings.Join(t.Command, " ")+"\n")) |
| 164 | + return c.Run() |
| 165 | +} |
| 166 | + |
| 167 | +func taskWorkdir(projDir, workdir string) string { |
| 168 | + if workdir == "" { |
| 169 | + return projDir |
| 170 | + } |
| 171 | + if filepath.IsAbs(workdir) { |
| 172 | + return workdir |
| 173 | + } |
| 174 | + return filepath.Join(projDir, workdir) |
| 175 | +} |
| 176 | + |
| 177 | +func envKV(m map[string]string) []string { |
| 178 | + if len(m) == 0 { |
| 179 | + return nil |
| 180 | + } |
| 181 | + out := make([]string, 0, len(m)) |
| 182 | + for k, v := range m { |
| 183 | + out = append(out, k+"="+v) |
| 184 | + } |
| 185 | + sort.Strings(out) |
| 186 | + return out |
| 187 | +} |
| 188 | + |
| 189 | +// prefixWriter buffers bytes and flushes each complete line through emit, so a |
| 190 | +// line and its prefix are written atomically even under concurrent tasks. |
| 191 | +type prefixWriter struct { |
| 192 | + emit func(prefix string, data []byte) |
| 193 | + prefix string |
| 194 | + buf []byte |
| 195 | +} |
| 196 | + |
| 197 | +func (p *prefixWriter) Write(b []byte) (int, error) { |
| 198 | + p.buf = append(p.buf, b...) |
| 199 | + for { |
| 200 | + i := bytes.IndexByte(p.buf, '\n') |
| 201 | + if i < 0 { |
| 202 | + break |
| 203 | + } |
| 204 | + line := make([]byte, i+1) |
| 205 | + copy(line, p.buf[:i+1]) |
| 206 | + p.emit(p.prefix, line) |
| 207 | + p.buf = p.buf[i+1:] |
| 208 | + } |
| 209 | + return len(b), nil |
| 210 | +} |
0 commit comments