my-homelab-configs/internal/jeannieworkflow/workflow.go

86 lines
2.1 KiB
Go

package jeannieworkflow
import (
"context"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
"go.temporal.io/sdk/temporal"
"go.temporal.io/sdk/workflow"
)
const (
TaskQueue = "jeannie"
WorkflowName = "JeannieCommandWorkflow"
)
type CommandInput struct {
RepoRoot string
Command string
Args []string
}
type CommandResult struct {
Output string
ExitCode int
}
// A new API/Temporal execution follows the saved selection. Only descendants
// of that execution inherit its resolved profile pin.
func CommandEnvironment() []string {
var result []string
for _, entry := range os.Environ() {
if strings.HasPrefix(entry, "JEANNIE_CLUSTER_PROFILE_PIN=") || strings.HasPrefix(entry, "JEANNIE_REMOTE_SERVER=") {
continue
}
result = append(result, entry)
}
return append(result, "JEANNIE_REMOTE_SERVER=true")
}
// Long-running lab builds and suites need more than the normal command limit.
func CommandTimeout(command string, args []string) time.Duration {
if command == "ai-lab" && len(args) > 0 {
switch args[0] {
case "suite", "install", "colibri-install", "colibri-prepare":
return 2 * time.Hour
}
}
return 30 * time.Minute
}
func Workflow(ctx workflow.Context, input CommandInput) (CommandResult, error) {
options := workflow.ActivityOptions{
StartToCloseTimeout: CommandTimeout(input.Command, input.Args),
RetryPolicy: &temporal.RetryPolicy{
MaximumAttempts: 1,
},
}
ctx = workflow.WithActivityOptions(ctx, options)
var result CommandResult
if err := workflow.ExecuteActivity(ctx, Run, input).Get(ctx, &result); err != nil {
return result, err
}
return result, nil
}
func Run(ctx context.Context, input CommandInput) (CommandResult, error) {
args := append([]string{input.Command}, input.Args...)
command := exec.CommandContext(ctx, filepath.Join(input.RepoRoot, "jeannie"), args...)
command.Dir = input.RepoRoot
command.Env = CommandEnvironment()
output, err := command.CombinedOutput()
result := CommandResult{Output: string(output)}
if err == nil {
return result, nil
}
if exitErr, ok := err.(*exec.ExitError); ok {
result.ExitCode = exitErr.ExitCode()
return result, nil
}
return result, err
}