Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
386 changes: 386 additions & 0 deletions cmd/runtime.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,386 @@
package cmd

import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"

"github.com/spf13/cobra"
"gopkg.in/yaml.v3"

"github.com/uigraph-oss/uigraph-cli/pkg/autopilot"
"github.com/uigraph-oss/uigraph-cli/pkg/runtime"
)

var runtimeCmd = &cobra.Command{
Use: "runtime",
Short: "Detect and check a service's runtime profile (the runtime: section of .uigraph.yaml)",
Long: `The runtime: section of .uigraph.yaml says how to set up, build and test a service,
what it depends on, and which secrets (names only) its tests need. Autopilot drafts code
only for services whose profile has passed a check.`,
}

var (
rtConfig string
rtDetectConfig string
rtWrite bool
rtForce bool
rtRun bool
rtImage string
rtTimeout time.Duration
rtLogPath string
rtReport bool
rtAutopilotURL string
rtOrg string
rtJSON bool
)

var runtimeDetectCmd = &cobra.Command{
Use: "detect [dir]",
Short: "Propose a runtime: section from the repo's CI, Makefile, package.json, Dockerfile and compose files",
Long: `Inspects dir (default .) and prints a proposed runtime: section. Review it like any other
artifact. With --write it is added to the directory's .uigraph.yaml (--force replaces an existing one).
Secrets are listed by name only; set their values with uigraph secrets set, never in this file.`,
Args: cobra.MaximumNArgs(1),
RunE: runRuntimeDetect,
}

var runtimeCheckCmd = &cobra.Command{
Use: "check",
Short: "Validate the runtime: section, and with --run prove it in the sandbox base image",
Long: `Validates the runtime: section of .uigraph.yaml against the schema and the repo (make targets,
package scripts, compose files). With --run it runs setup, build, lint and tests in the sandbox base
image with local Docker, with sidecars for postgres and redis; secrets come from same-named environment
variables, and steps whose secrets are unset are reported as needing them rather than run.

--report sends the result to Autopilot as the service's readiness, with the commit it was checked at.
It needs --run, a clean working tree, and your own user token (UIGRAPH_USER_TOKEN); only the
service's owning team and org admins can report.`,
Args: cobra.NoArgs,
RunE: runRuntimeCheck,
}

func init() {
runtimeDetectCmd.Flags().StringVar(&rtDetectConfig, "config", "", "Config to write with --write (default <dir>/.uigraph.yaml)")
runtimeDetectCmd.Flags().BoolVar(&rtWrite, "write", false, "Add the proposal to .uigraph.yaml")
runtimeDetectCmd.Flags().BoolVar(&rtForce, "force", false, "With --write, replace an existing runtime: section")

f := runtimeCheckCmd.Flags()
f.StringVar(&rtConfig, "config", ".uigraph.yaml", "Path to config file")
f.BoolVar(&rtRun, "run", false, "Run the profile in the sandbox base image with local Docker")
f.StringVar(&rtImage, "image", "", "Base image for --run (default runtime.image, else "+runtime.DefaultBaseImage+")")
f.DurationVar(&rtTimeout, "timeout", 20*time.Minute, "Per-step timeout for --run")
f.StringVar(&rtLogPath, "log", "", "Write every step's output to this file (default: a temp file)")
f.BoolVar(&rtReport, "report", false, "Report the --run result to Autopilot as the service's readiness")
f.StringVar(&rtAutopilotURL, "autopilot-url", "", "UIGraph URL serving /api/v1/autopilot (default UIGRAPH_AUTOPILOT_URL)")
f.StringVar(&rtOrg, "org", "", "Org id (default UIGRAPH_ORG_ID)")
f.BoolVar(&rtJSON, "json", false, "Print the result as JSON")

runtimeCmd.AddCommand(runtimeDetectCmd, runtimeCheckCmd)
rootCmd.AddCommand(runtimeCmd)
}

const proposalHeader = "# Proposed by `uigraph runtime detect`; review before committing.\n" +
"# Secrets are names only: set values with `uigraph secrets set`, never here.\n"

func runRuntimeDetect(cmd *cobra.Command, args []string) error {
dir := "."
if len(args) == 1 {
dir = args[0]
}
det, err := runtime.Detect(dir)
if err != nil {
return err
}
out, err := det.Runtime.Marshal()
if err != nil {
return err
}
for _, n := range det.Notes {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), "note: "+n)
}
if !rtWrite {
_, _ = fmt.Fprint(cmd.OutOrStdout(), proposalHeader+string(out))
return nil
}
path := rtDetectConfig
if path == "" {
path = filepath.Join(dir, ".uigraph.yaml")
}
if err := writeRuntime(path, det.Runtime, rtForce); err != nil {
return err
}
_, _ = fmt.Fprintf(cmd.OutOrStdout(), "✓ runtime: section written to %s; run `uigraph-cli runtime check --config %s`\n", path, path)
return nil
}

// writeRuntime adds rt to the .uigraph.yaml at path. A file without a
// runtime: section gets it appended, leaving the rest byte for byte; an
// existing section is replaced only with force.
func writeRuntime(path string, rt *runtime.Runtime, force bool) error {
section, err := rt.Marshal()
if err != nil {
return err
}
cur, err := os.ReadFile(path)
if errors.Is(err, os.ErrNotExist) {
return os.WriteFile(path, append([]byte(proposalHeader), section...), 0o644)
}
if err != nil {
return err
}
var doc yaml.Node
if err := yaml.Unmarshal(cur, &doc); err != nil {
return fmt.Errorf("%s: %w", path, err)
}
var top *yaml.Node
if len(doc.Content) == 1 && doc.Content[0].Kind == yaml.MappingNode {
top = doc.Content[0]
}
if top == nil && len(bytes.TrimSpace(cur)) > 0 {
return fmt.Errorf("%s: not a YAML mapping", path)
}
idx := -1
if top != nil {
for i := 0; i+1 < len(top.Content); i += 2 {
if top.Content[i].Value == "runtime" {
idx = i + 1
}
}
}
if idx < 0 {
if len(cur) > 0 && !bytes.HasSuffix(cur, []byte("\n")) {
cur = append(cur, '\n')
}
return os.WriteFile(path, append(append(cur, '\n'), append([]byte(proposalHeader), section...)...), 0o644)
}
if !force {
return fmt.Errorf("%s already has a runtime: section; pass --force to replace it", path)
}
var fresh yaml.Node
if err := yaml.Unmarshal(section, &fresh); err != nil {
return err
}
top.Content[idx] = fresh.Content[0].Content[1]
var buf bytes.Buffer
enc := yaml.NewEncoder(&buf)
enc.SetIndent(2)
if err := enc.Encode(&doc); err != nil {
return err
}
_ = enc.Close()
return os.WriteFile(path, buf.Bytes(), 0o644)
}

type checkResult struct {
Config string `json:"config"`
Service string `json:"service"`
Valid bool `json:"valid"`
Problems []string `json:"problems,omitempty"`
Warnings []string `json:"warnings,omitempty"`
Ran bool `json:"ran"`
Steps []runtime.Step `json:"steps,omitempty"`
Readiness string `json:"readiness,omitempty"`
Reasons []runtime.Reason `json:"reasons,omitempty"`
Commit string `json:"commit,omitempty"`
Reported *autopilot.Readiness `json:"reported,omitempty"`
}

// Exit codes: 1 the profile is invalid, 3 a step failed. Steps that only
// need secret values do not fail the check.
func runRuntimeCheck(cmd *cobra.Command, _ []string) error {
cmd.SilenceUsage = true
ctx := cmd.Context()
out := cmd.OutOrStdout()
if rtJSON {
out = io.Discard
}
res := checkResult{Config: rtConfig}
raw, err := os.ReadFile(rtConfig)
if err != nil {
return err
}
f, err := runtime.Parse(raw)
if f != nil {
res.Service = f.Service
}
if err != nil {
res.Problems = splitErr(err)
return finishCheck(cmd, res, 1)
}
dir, err := filepath.Abs(filepath.Dir(rtConfig))
if err != nil {
return err
}
res.Problems, res.Warnings = runtime.Lint(f.Runtime, dir)
res.Valid = len(res.Problems) == 0
_, _ = fmt.Fprintf(out, "Runtime profile for %s (%s)\n", f.Service, rtConfig)
for _, w := range res.Warnings {
_, _ = fmt.Fprintln(out, " ! "+w)
}
if !res.Valid {
return finishCheck(cmd, res, 1)
}
_, _ = fmt.Fprintln(out, " ✓ valid")
if rtReport && !rtRun {
return errors.New("--report needs --run: readiness is what a run proves, not what the file says")
}
if !rtRun {
return finishCheck(cmd, res, 0)
}

root, commit, dirty := gitState(dir)
res.Commit = commit
var reportCfg *reportTarget
if rtReport {
// Check everything a report needs before spending minutes on a run.
if reportCfg, err = newReportTarget(commit, dirty); err != nil {
return err
}
}
serviceDir, err := filepath.Rel(root, dir)
if err != nil {
return err
}
logW, logName, err := openLog()
if err != nil {
return err
}
defer func() { _ = logW.Close() }()
_, _ = fmt.Fprintf(out, "Running in Docker (full log: %s)\n", logName)
steps, err := runtime.Run(ctx, f.Runtime, runtime.RunOptions{
RepoRoot: root, ServiceDir: serviceDir, Image: rtImage, StepTimeout: rtTimeout,
Log: logW, Progress: out,
})
if err != nil {
return err
}
res.Ran, res.Steps = true, steps
res.Readiness, res.Reasons = runtime.Outcome(f.Runtime, steps)
_, _ = fmt.Fprintf(out, "Readiness: %s\n", res.Readiness)
for _, r := range res.Reasons {
_, _ = fmt.Fprintf(out, " - %s: %s\n", r.Code, r.Detail)
}
code := 0
for _, s := range steps {
if s.Status == runtime.StepFailed {
code = 3
}
}
if reportCfg != nil {
section, err := f.Runtime.Marshal()
if err != nil {
return err
}
rep := runtime.Report{Status: res.Readiness, Reasons: res.Reasons, Commit: commit, Runtime: string(section), Steps: steps}
if rep.Reasons == nil {
rep.Reasons = []runtime.Reason{}
}
stored, err := reportCfg.client.ReportReadiness(ctx, reportCfg.org, f.Service, rep)
if err != nil {
return fmt.Errorf("report readiness: %w", err)
}
res.Reported = stored
_, _ = fmt.Fprintf(out, "✓ Reported to Autopilot: %s is %s at %.12s\n", stored.ServiceName, stored.Status, stored.Commit)
}
return finishCheck(cmd, res, code)
}

func finishCheck(cmd *cobra.Command, res checkResult, code int) error {
if rtJSON {
b, err := json.MarshalIndent(res, "", " ")
if err != nil {
return err
}
_, _ = fmt.Fprintln(cmd.OutOrStdout(), string(b))
} else {
for _, p := range res.Problems {
_, _ = fmt.Fprintln(cmd.ErrOrStderr(), " ✗ "+p)
}
}
if code != 0 {
os.Exit(code)
}
return nil
}

type reportTarget struct {
client *autopilot.Client
org string
}

func newReportTarget(commit string, dirty bool) (*reportTarget, error) {
switch {
case commit == "":
return nil, errors.New("--report: not a git checkout, so there is no commit to report the check at")
case dirty:
return nil, errors.New("--report: the working tree has uncommitted changes; commit or stash them so the result matches a commit")
}
base := firstNonEmpty(rtAutopilotURL, os.Getenv("UIGRAPH_AUTOPILOT_URL"))
org := firstNonEmpty(rtOrg, os.Getenv("UIGRAPH_ORG_ID"))
token := os.Getenv("UIGRAPH_USER_TOKEN")
switch {
case base == "":
return nil, errors.New("--report: set --autopilot-url or UIGRAPH_AUTOPILOT_URL")
case org == "":
return nil, errors.New("--report: set --org or UIGRAPH_ORG_ID")
case token == "":
return nil, errors.New("--report: set UIGRAPH_USER_TOKEN to your own UIGraph token (not the CI sync token)")
}
return &reportTarget{client: &autopilot.Client{BaseURL: base, Token: token}, org: org}, nil
}

// gitState is the repo root (or dir outside git), HEAD and whether the
// tree is dirty.
func gitState(dir string) (root, commit string, dirty bool) {
git := func(args ...string) (string, error) {
b, err := exec.Command("git", append([]string{"-C", dir}, args...)...).Output()
return strings.TrimSpace(string(b)), err
}
root, err := git("rev-parse", "--show-toplevel")
if err != nil {
abs, _ := filepath.Abs(dir)
return abs, "", false
}
commit, _ = git("rev-parse", "HEAD")
st, _ := git("status", "--porcelain")
return root, commit, st != ""
}

func openLog() (*os.File, string, error) {
if rtLogPath != "" {
f, err := os.Create(rtLogPath)
return f, rtLogPath, err
}
f, err := os.CreateTemp("", "uigraph-runtime-check-*.log")
if err != nil {
return nil, "", err
}
return f, f.Name(), nil
}

func splitErr(err error) []string {
var out []string
for _, l := range strings.Split(err.Error(), "\n") {
if l = strings.TrimSpace(l); l != "" {
out = append(out, l)
}
}
return out
}

func firstNonEmpty(v ...string) string {
for _, s := range v {
if s != "" {
return s
}
}
return ""
}
Loading
Loading