Files
zeekay ed0990d4d2 Speak ZAP to the forge, not JSON shaped like it
The forge serves its runner surface as five typed zip operations. This is the
half that calls them: zip.Dial and zip.Call by op name, so the body carries the
same bytes both ends hold in memory, and the address is derived rather than
spelled — the forge registers POST /v1/runner/<name>, zip derives
post_runner_<name>, and TestOpNames pins our five literals against zip.ID so
the two cannot drift.

The types moved with the wire, and both moves were forced by it rather than
chosen. A map is refused at encode, so secrets, vars, needs and a job's outputs
cross as []Pair and are indexed once, at the boundary act wants a map at. A
time.Time is accepted and then arrives as the zero time with no error anywhere,
so every instant is an int64 of unix nanoseconds.

Falling out of it:

- Task.Context is a struct. As a map the forge wrote git_runtime_token while
  this runner read gitea_runtime_token and quietly fell back to the task token,
  so ACTIONS_RUNTIME_TOKEN was the wrong secret and the mask that keeps a
  runtime token out of a job's log covered nothing. A field is a compile error.
- A transport timeout is an error again. It was read as "the designed idle path
  for a long poll" — fiction, the forge has never blocked — which counted it as
  an empty response AND reset the error counter, so a forge answering in six
  seconds against a five second wait was indistinguishable from an idle one in
  every log line and every metric, with the counter that would have raised the
  alarm suppressed. There is no long poll: task answers immediately and
  TaskIn.Queue is what makes an idle ask cost nothing.
- fetch_timeout is now the ceiling on the wire. A zip.Call cannot be cancelled
  once it has left, so a per-request context bounds nothing and the wait has to
  sit on the transport, where it bounds every call.
- The credential is a field, so header.go is gone. client.Forge stamps it and
  no caller carries it.
- logs -> log, Row -> Line, NoMore -> Last, SentOutputs -> Stored. You append
  to a log, and the other four addresses are singular.
- Insecure() had no caller.

client.take copies every string and []byte out of a reply, and it is not
belt-and-braces. ZAP reads text zero-copy — zap.Object.Text is an unsafe.String
over the message — and zip.Call hands the response back to fasthttp's pool as
it returns, so a reply's strings point at memory the next call writes over. A
token registered as "runner-secret" read back "1.2.3r-secret" one call later,
the version string of the call in between laid over its first five bytes, and
the forge answered 401 to a runner that was registered. TestOwn fails without
the copy. Delete it when zip copies on decode.

client.dial declares its own transport scheme rather than taking http and
https: declaring a scheme REPLACES what is registered under that name, and
zip's own entries carry a Serve half this one does not — taking them left the
process able to dial plain HTTP through zip and no longer able to serve it.

.runner is untouched. Its uuid and token are exactly the credential the new
wire sends, so a registration made before the cutover keeps working after it,
and a runner only has to be rebuilt.

Requires github.com/hanzoai/git at 92b2e84dba or later. Nothing here has been
exercised against a live forge.
2026-09-06 13:50:41 -07:00

270 lines
7.8 KiB
Go

// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT
package cmd
import (
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"time"
"github.com/hanzoai/git-runner/internal/app/poll"
"github.com/hanzoai/git-runner/internal/app/run"
"github.com/hanzoai/git-runner/internal/pkg/client"
"github.com/hanzoai/git-runner/internal/pkg/config"
"github.com/hanzoai/git-runner/internal/pkg/envcheck"
"github.com/hanzoai/git-runner/internal/pkg/labels"
"github.com/hanzoai/git-runner/internal/pkg/metrics"
"github.com/hanzoai/git-runner/internal/pkg/ver"
forge "github.com/hanzoai/git/modules/actions/runner"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
cfg, err := config.LoadDefault(*configFile)
if err != nil {
return fmt.Errorf("invalid configuration: %w", err)
}
initLogging(cfg)
log.Infoln("Starting runner daemon")
reg, err := config.LoadRegistration(cfg.Runner.File)
if os.IsNotExist(err) {
log.Error("registration file not found, please register the runner first")
return err
} else if err != nil {
return fmt.Errorf("failed to load registration file: %w", err)
}
lbls := reg.Labels
if len(cfg.Runner.Labels) > 0 {
lbls = cfg.Runner.Labels
}
ls := labels.Labels{}
for _, l := range lbls {
label, err := labels.Parse(l)
if err != nil {
log.WithError(err).Warnf("ignored invalid label %q", l)
continue
}
ls = append(ls, label)
}
if len(ls) == 0 {
log.Warn("no labels configured, runner may not be able to pick up jobs")
}
if ls.RequireDocker() || cfg.Container.RequireDocker {
// Wait for dockerd be ready
if timeout := cfg.Container.DockerTimeout; timeout > 0 {
tctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
keepRunning := true
for keepRunning {
dockerSocketPath, err := getDockerSocketPath(cfg.Container.DockerHost)
if err != nil {
log.Errorf("Failed to get socket path: %s", err.Error())
} else if err = envcheck.CheckIfDockerRunning(tctx, dockerSocketPath); errors.Is(err, context.Canceled) {
log.Infof("Docker wait timeout of %s expired", timeout.String())
break
} else if err != nil {
log.Errorf("Docker connection failed: %s", err.Error())
} else {
log.Infof("Docker is ready")
break
}
select {
case <-time.After(time.Second):
case <-tctx.Done():
log.Infof("Docker wait timeout of %s expired", timeout.String())
keepRunning = false
}
}
}
// Require dockerd be ready
dockerSocketPath, err := getDockerSocketPath(cfg.Container.DockerHost)
if err != nil {
return err
}
if err := envcheck.CheckIfDockerRunning(ctx, dockerSocketPath); err != nil {
return err
}
// if dockerSocketPath passes the check, override DOCKER_HOST with dockerSocketPath
os.Setenv("DOCKER_HOST", dockerSocketPath)
// empty cfg.Container.DockerHost means git-runner need to find an available docker host automatically
// and assign the path to cfg.Container.DockerHost
if cfg.Container.DockerHost == "" {
cfg.Container.DockerHost = dockerSocketPath
}
// check the scheme, if the scheme is not npipe or unix
// set cfg.Container.DockerHost to "-" because it can't be mounted to the job container
if protoIndex := strings.Index(cfg.Container.DockerHost, "://"); protoIndex != -1 {
scheme := cfg.Container.DockerHost[:protoIndex]
if !strings.EqualFold(scheme, "npipe") && !strings.EqualFold(scheme, "unix") {
cfg.Container.DockerHost = "-"
}
}
}
if !slices.Equal(reg.Labels, ls.ToStrings()) {
reg.Labels = ls.ToStrings()
if err := config.SaveRegistration(cfg.Runner.File, reg); err != nil {
return fmt.Errorf("failed to save runner config: %w", err)
}
log.Infof("labels updated to: %v", reg.Labels)
}
cli, err := client.New(reg.Address, forge.Credential{UUID: reg.UUID, Token: reg.Token}, cfg.Runner.Insecure, cfg.Runner.FetchTimeout)
if err != nil {
return err
}
runner := run.NewRunner(cfg, reg, cli)
// declare the labels of the runner before fetching tasks
declared, err := runner.Declare(ctx, ls.Names())
if err != nil {
log.WithError(err).Error("fail to invoke Declare")
return err
}
log.Infof("runner: %s, with version: %s, with labels: %v, declare successfully",
declared.Runner.Name, declared.Runner.Version, declared.Runner.Labels)
if cfg.Metrics.Enabled {
metrics.Init()
metrics.RunnerInfo.WithLabelValues(ver.Version(), declared.Runner.Name).Set(1)
metrics.RunnerCapacity.Set(float64(cfg.Runner.Capacity))
metrics.RegisterUptimeFunc(time.Now())
metrics.RegisterRunningJobsFunc(runner.RunningCount, cfg.Runner.Capacity)
metrics.StartServer(ctx, cfg.Metrics.Addr)
}
poller := poll.New(cfg, cli, runner)
if daemArgs.Once || reg.Ephemeral {
done := make(chan struct{})
go func() {
defer close(done)
poller.PollOnce()
}()
// shutdown when we complete a job or cancel is requested
select {
case <-ctx.Done():
case <-done:
}
} else {
go poller.Poll()
<-ctx.Done()
}
log.Infof("runner: %s shutdown initiated, waiting %s for running jobs to complete before shutting down", declared.Runner.Name, cfg.Runner.ShutdownTimeout)
ctx, cancel := context.WithTimeout(context.Background(), cfg.Runner.ShutdownTimeout)
defer cancel()
err = poller.Shutdown(ctx)
if err != nil {
log.Warnf("runner: %s cancelled in progress jobs during shutdown", declared.Runner.Name)
}
return nil
}
}
type daemonArgs struct {
Once bool
}
// initLogging setup the global logrus logger.
func initLogging(cfg *config.Config) {
callPrettyfier := func(f *runtime.Frame) (string, string) {
// get function name
s := strings.Split(f.Function, ".")
funcname := "[" + s[len(s)-1] + "]"
// get file name and line number
_, filename := path.Split(f.File)
filename = "[" + filename + ":" + strconv.Itoa(f.Line) + "]"
return funcname, filename
}
isTerm := isatty.IsTerminal(os.Stdout.Fd())
format := &log.TextFormatter{
DisableColors: !isTerm,
FullTimestamp: true,
CallerPrettyfier: callPrettyfier,
}
log.SetFormatter(format)
l := cfg.Log.Level
if l == "" {
log.Infof("Log level not set, sticking to info")
return
}
level, err := log.ParseLevel(l)
if err != nil {
log.WithError(err).
Errorf("invalid log level: %q", l)
}
// debug level
switch level {
case log.DebugLevel, log.TraceLevel:
log.SetReportCaller(true) // Only in debug or trace because it takes a performance toll
log.Infof("Log level %s requested, setting up report caller for further debugging", level)
}
if log.GetLevel() != level {
log.Infof("log level set to %v", level)
log.SetLevel(level)
}
}
var commonSocketPaths = []string{
"/var/run/docker.sock",
"/run/podman/podman.sock",
"$HOME/.colima/docker.sock",
"$XDG_RUNTIME_DIR/docker.sock",
"$XDG_RUNTIME_DIR/podman/podman.sock",
`\\.\pipe\docker_engine`,
"$HOME/.docker/run/docker.sock",
}
func getDockerSocketPath(configDockerHost string) (string, error) {
// a `-` means don't mount the docker socket to job containers
if configDockerHost != "" && configDockerHost != "-" {
return configDockerHost, nil
}
socket, found := os.LookupEnv("DOCKER_HOST")
if found {
return socket, nil
}
for _, p := range commonSocketPaths {
if _, err := os.Lstat(os.ExpandEnv(p)); err == nil {
if strings.HasPrefix(p, `\\.\`) {
return "npipe://" + filepath.ToSlash(os.ExpandEnv(p)), nil
}
return "unix://" + filepath.ToSlash(os.ExpandEnv(p)), nil
}
}
return "", errors.New("daemon Docker Engine socket not found and docker_host config was invalid")
}