refactor(logging): use the logging package in internal (#1302)

Move the log calls in `internal` onto `logging`, and add what the process-wide logger setup and its tests need: `SetTextFormat` with a line filter for secret masking (replacing `report.MaskingFormatter`), `SetReportCaller`, `SetDefault` and `logtest.SetDefault`. After this only the `logging` package imports logrus.

Stacked on https://gitea.com/gitea/runner/pulls/1301.

Assisted-by: Codet
Co-authored-by: bircni <[email protected]>
Reviewed-on: https://gitea.com/gitea/runner/pulls/1302
Reviewed-by: bircni <[email protected]>
This commit is contained in:
Lunny Xiaoandbircni committed 2026-10-12 00:19:01 +00:00
1 parent 76110557ab
commit 4e8037a93b
25 files changed
+308 -246

No files matched your search

+1 -2
View File
@@ -12,7 +12,6 @@ import (
"gitea.com/gitea/runner/internal/app/run"
"gitea.com/gitea/runner/internal/pkg/config"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -67,7 +66,7 @@ func runCacheServer(configFile *string, cacheArgs *cacheServerArgs) func(cmd *co
return err
}
log.Infof("cache server is listening on %v", cacheHandler.ExternalURL())
logging.Infof("cache server is listening on %v", cacheHandler.ExternalURL())
<-cmd.Context().Done()
+39 -39
View File
@@ -18,6 +18,7 @@ import (
"strings"
"time"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/internal/app/poll"
"gitea.com/gitea/runner/internal/app/run"
"gitea.com/gitea/runner/internal/pkg/client"
@@ -34,7 +35,6 @@ import (
runnerv1 "gitea.dev/actionslib/runner/v1"
"github.com/avast/retry-go/v5"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
@@ -46,11 +46,11 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
}
initLogging(cfg)
log.Infoln("Starting runner daemon")
logging.Info("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")
logging.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)
@@ -62,13 +62,13 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
releaseLock, err := lock.TryLock(cfg.Runner.File)
switch {
case errors.Is(err, lock.ErrLocked):
log.Errorf("another gitea-runner process is already using %q; each runner process needs its own runner file (runner.file)", cfg.Runner.File)
logging.Errorf("another gitea-runner process is already using %q; each runner process needs its own runner file (runner.file)", cfg.Runner.File)
return err
case err != nil:
// Best-effort guard: if the lock file can't be created (e.g. a
// read-only runner-file mount), warn and start anyway rather than
// refusing to run.
log.Warnf("could not lock runner file %q, continuing without the single-process guard: %v", cfg.Runner.File, err)
logging.Warnf("could not lock runner file %q, continuing without the single-process guard: %v", cfg.Runner.File, err)
default:
// Held until shutdown finishes: the draining runner still owns this
// identity on the server, so releasing early would let a restart
@@ -78,13 +78,13 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
shutdownTelemetry, err := telemetry.Setup(ctx, reg.UUID, reg.Name, metrics.Registry)
if err != nil {
log.WithError(err).Warn("OpenTelemetry export failed to start")
logging.WithError(err).Warn("OpenTelemetry export failed to start")
}
defer func() {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := shutdownTelemetry(ctx); err != nil {
log.WithError(err).Warn("OpenTelemetry export failed to flush")
logging.WithError(err).Warn("OpenTelemetry export failed to flush")
}
}()
@@ -94,13 +94,13 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
for _, l := range lbls {
label, err := labels.Parse(l)
if err != nil {
log.WithError(err).Warnf("ignored invalid label %q", l)
logging.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")
logging.Warn("no labels configured, runner may not be able to pick up jobs")
}
// Before the first Docker API call: the standard library resolves the proxy
@@ -108,7 +108,7 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
if dockerSocketPath, err := getDockerSocketPath(cfg.Container.DockerHost); err == nil {
run.BypassProxyForDockerHost(dockerSocketPath)
} else {
log.Debugf("cannot resolve the docker socket path, so Docker API calls are not exempted from the proxy: %v", err)
logging.Debugf("cannot resolve the docker socket path, so Docker API calls are not exempted from the proxy: %v", err)
}
if ls.RequireDocker() || cfg.Container.RequireDocker {
@@ -120,20 +120,20 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
for keepRunning {
dockerSocketPath, err := getDockerSocketPath(cfg.Container.DockerHost)
if err != nil {
log.Errorf("Failed to get socket path: %s", err.Error())
logging.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())
logging.Infof("Docker wait timeout of %s expired", timeout.String())
break
} else if err != nil {
log.Errorf("Docker connection failed: %s", err.Error())
logging.Errorf("Docker connection failed: %s", err.Error())
} else {
log.Infof("Docker is ready")
logging.Infof("Docker is ready")
break
}
select {
case <-time.After(time.Second):
case <-tctx.Done():
log.Infof("Docker wait timeout of %s expired", timeout.String())
logging.Infof("Docker wait timeout of %s expired", timeout.String())
keepRunning = false
}
}
@@ -169,7 +169,7 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
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)
logging.Infof("labels updated to: %v", reg.Labels)
}
cli := client.New(
@@ -184,7 +184,7 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
runner := run.NewRunner(cfg, reg, cli)
defer func() {
if err := runner.Close(); err != nil {
log.Warnf("runner %s: cache server shutdown: %v", reg.Name, err)
logging.Warnf("runner %s: cache server shutdown: %v", reg.Name, err)
}
}()
@@ -197,9 +197,9 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
retry.RetryIf(shouldRetryDeclare),
retry.OnRetry(func(attempt uint, err error) {
if attempt == 0 {
log.WithError(err).Warn("fail to invoke Declare, retrying until Gitea is reachable")
logging.WithError(err).Warn("fail to invoke Declare, retrying until Gitea is reachable")
} else {
log.WithError(err).Debug("fail to invoke Declare, retrying")
logging.WithError(err).Debug("fail to invoke Declare, retrying")
}
}),
).Do(func() (*connect.Response[runnerv1.DeclareResponse], error) {
@@ -209,16 +209,16 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
case err != nil && ctx.Err() != nil && !client.IsRegistrationRejected(err):
return nil
case err != nil && connect.CodeOf(err) == connect.CodeUnimplemented:
log.Errorf("Your Gitea version is too old to support runner declare, please upgrade to v1.21 or later")
logging.Errorf("Your Gitea version is too old to support runner declare, please upgrade to v1.21 or later")
return err
case err != nil:
log.WithError(err).Error("fail to invoke Declare")
logging.WithError(err).Error("fail to invoke Declare")
if client.IsRegistrationRejected(err) {
removeEphemeralRegistration(reg, cfg.Runner.File)
}
return err
default:
log.Infof("runner: %s, with version: %s, with labels: %v, declare successfully",
logging.Infof("runner: %s, with version: %s, with labels: %v, declare successfully",
resp.Msg.Runner.Name, resp.Msg.Runner.Version, resp.Msg.Runner.Labels)
}
runner.SetCapabilitiesFromDeclare(resp)
@@ -268,14 +268,14 @@ func runDaemon(ctx context.Context, daemArgs *daemonArgs, configFile *string) fu
}
}
log.Infof("runner: %s shutdown initiated, waiting %s for running jobs to complete before shutting down", resp.Msg.Runner.Name, cfg.Runner.ShutdownTimeout)
logging.Infof("runner: %s shutdown initiated, waiting %s for running jobs to complete before shutting down", resp.Msg.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", resp.Msg.Runner.Name)
logging.Warnf("runner: %s cancelled in progress jobs during shutdown", resp.Msg.Runner.Name)
}
if poller.RegistrationRejected() {
@@ -295,9 +295,9 @@ func removeEphemeralRegistration(reg *config.Registration, file string) {
return
}
if err := os.Remove(file); err == nil {
log.Infof("removed the spent ephemeral registration %q", file)
logging.Infof("removed the spent ephemeral registration %q", file)
} else if !os.IsNotExist(err) {
log.WithError(err).Warn("failed to remove the spent ephemeral registration")
logging.WithError(err).Warn("failed to remove the spent ephemeral registration")
}
}
@@ -328,7 +328,7 @@ func splitLabels(s string) []string {
return lbls
}
// initLogging setup the global logrus logger.
// initLogging sets up the process-wide logger.
func initLogging(cfg *config.Config) {
callPrettyfier := func(f *runtime.Frame) (string, string) {
// get function name
@@ -341,35 +341,35 @@ func initLogging(cfg *config.Config) {
}
isTerm := isatty.IsTerminal(os.Stdout.Fd())
format := &log.TextFormatter{
logging.SetTextFormat(logging.TextOptions{
DisableColors: !isTerm,
FullTimestamp: true,
CallerPrettyfier: callPrettyfier,
}
log.SetFormatter(report.MaskingFormatter(format))
Filter: report.MaskGlobal,
})
l := cfg.Log.Level
if l == "" {
log.Infof("Log level not set, sticking to info")
logging.Infof("Log level not set, sticking to info")
return
}
level, err := log.ParseLevel(l)
level, err := logging.ParseLevel(l)
if err != nil {
log.WithError(err).
logging.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)
case logging.LevelDebug, logging.LevelTrace:
logging.SetReportCaller(true) // Only in debug or trace because it takes a performance toll
logging.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)
if logging.GetLevel() != level {
logging.Infof("log level set to %v", level)
logging.SetLevel(level)
}
}
+12 -13
View File
@@ -11,17 +11,17 @@ import (
"net/http/httptest"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/internal/pkg/config"
"gitea.com/gitea/runner/internal/pkg/report"
"connectrpc.com/connect"
runnerv1 "gitea.dev/actionslib/runner/v1"
"gitea.dev/actionslib/runner/v1/runnerv1connect"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"google.golang.org/protobuf/types/known/structpb"
)
@@ -64,24 +64,23 @@ func TestGetDockerSocketPathUsesConfigAndEnvironment(t *testing.T) {
}
func TestInitLoggingSetsLevelAndCaller(t *testing.T) {
oldLevel := log.GetLevel()
oldReportCaller := log.StandardLogger().ReportCaller
oldLevel, oldOut := logging.GetLevel(), logging.Output()
t.Cleanup(func() {
log.SetLevel(oldLevel)
log.SetReportCaller(oldReportCaller)
logging.SetLevel(oldLevel)
logging.SetOutput(oldOut)
logging.SetReportCaller(false)
logging.SetTextFormat(logging.TextOptions{})
})
oldFormatter := log.StandardLogger().Formatter
t.Cleanup(func() { log.SetFormatter(oldFormatter) })
cfg := &config.Config{}
cfg.Log.Level = "debug"
initLogging(cfg)
require.Equal(t, log.DebugLevel, log.GetLevel())
require.True(t, log.StandardLogger().ReportCaller)
// act plans a job on this logger, so a live task's secrets have to be masked out of it
require.IsType(t, report.MaskingFormatter(nil), log.StandardLogger().Formatter)
require.Equal(t, logging.LevelDebug, logging.GetLevel())
var buf strings.Builder
logging.SetOutput(&buf)
logging.Debugf("line")
require.Contains(t, buf.String(), "[daemon_test.go:")
}
var errUnregisteredRunner = errors.New("rpc error: code = Unauthenticated desc = unregistered runner")
+19 -18
View File
@@ -31,7 +31,6 @@ import (
"gitea.dev/actionslib/pkg/model"
"github.com/joho/godotenv"
"github.com/moby/moby/api/types/container"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"golang.org/x/term"
)
@@ -106,7 +105,7 @@ func (i *executeArgs) LoadSecrets() map[string]string {
secretPairParts := strings.SplitN(secretPair, "=", 2)
secretPairParts[0] = strings.ToUpper(secretPairParts[0])
if strings.EqualFold(s[secretPairParts[0]], secretPairParts[0]) {
log.Errorf("Secret %s is already defined (secrets are case insensitive)", secretPairParts[0])
logging.Errorf("Secret %s is already defined (secrets are case insensitive)", secretPairParts[0])
}
if len(secretPairParts) == 2 {
s[secretPairParts[0]] = secretPairParts[1]
@@ -117,7 +116,7 @@ func (i *executeArgs) LoadSecrets() map[string]string {
val, err := term.ReadPassword(int(os.Stdin.Fd()))
fmt.Println()
if err != nil {
log.Errorf("failed to read input: %v", err)
logging.Errorf("failed to read input: %v", err)
os.Exit(1)
}
s[secretPairParts[0]] = string(val)
@@ -130,7 +129,8 @@ func readEnvs(path string, envs map[string]string) bool {
if _, err := os.Stat(path); err == nil {
env, err := godotenv.Read(path)
if err != nil {
log.Fatalf("Error loading from %s: %v", path, err)
logging.Errorf("Error loading from %s: %v", path, err)
os.Exit(1)
}
maps.Copy(envs, env)
return true
@@ -221,7 +221,8 @@ func (i *executeArgs) Workdir() string {
func (i *executeArgs) resolve(path string) string {
basedir, err := filepath.Abs(i.workdir)
if err != nil {
log.Fatal(err)
logging.Error(err)
os.Exit(1)
}
if path == "" {
return path
@@ -337,7 +338,7 @@ func runExecList(planner model.WorkflowPlanner, execArgs *executeArgs) error {
var filterEventName string
if len(execArgs.event) > 0 {
log.Infof("Using chosed event for filtering: %s", execArgs.event)
logging.Infof("Using chosed event for filtering: %s", execArgs.event)
filterEventName = execArgs.event
} else if execArgs.autodetectEvent {
// collect all events from loaded workflows
@@ -345,7 +346,7 @@ func runExecList(planner model.WorkflowPlanner, execArgs *executeArgs) error {
// set default event type to first event from many available
// this way user dont have to specify the event.
log.Infof("Using first detected workflow event for filtering: %s", events[0])
logging.Infof("Using first detected workflow event for filtering: %s", events[0])
filterEventName = events[0]
}
@@ -353,19 +354,19 @@ func runExecList(planner model.WorkflowPlanner, execArgs *executeArgs) error {
var err error
switch {
case execArgs.job != "":
log.Infof("Preparing plan with a job: %s", execArgs.job)
logging.Infof("Preparing plan with a job: %s", execArgs.job)
filterPlan, err = planner.PlanJob(execArgs.job)
if err != nil {
return err
}
case filterEventName != "":
log.Infof("Preparing plan for a event: %s", filterEventName)
logging.Infof("Preparing plan for a event: %s", filterEventName)
filterPlan, err = planner.PlanEvent(filterEventName)
if err != nil {
return err
}
default:
log.Infof("Preparing plan with all jobs")
logging.Infof("Preparing plan with all jobs")
filterPlan, err = planner.PlanAll()
if err != nil {
return err
@@ -445,30 +446,30 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
switch {
case len(execArgs.event) > 0:
log.Infof("Using chosed event for filtering: %s", execArgs.event)
logging.Infof("Using chosed event for filtering: %s", execArgs.event)
eventName = execArgs.event
case len(events) == 1 && len(events[0]) > 0:
log.Infof("Using the only detected workflow event: %s", events[0])
logging.Infof("Using the only detected workflow event: %s", events[0])
eventName = events[0]
case execArgs.autodetectEvent && len(events) > 0 && len(events[0]) > 0:
// set default event type to first event from many available
// this way user dont have to specify the event.
log.Infof("Using first detected workflow event: %s", events[0])
logging.Infof("Using first detected workflow event: %s", events[0])
eventName = events[0]
default:
log.Infof("Using default workflow event: push")
logging.Infof("Using default workflow event: push")
eventName = "push"
}
// build the plan for this run
if execArgs.job != "" {
log.Infof("Planning job: %s", execArgs.job)
logging.Infof("Planning job: %s", execArgs.job)
plan, err = planner.PlanJob(execArgs.job)
if err != nil {
return err
}
} else {
log.Infof("Planning jobs for event: %s", eventName)
logging.Infof("Planning jobs for event: %s", eventName)
plan, err = planner.PlanEvent(eventName)
if err != nil {
return err
@@ -488,7 +489,7 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
if err != nil {
return err
}
log.Infof("cache handler listens on: %v", handler.ExternalURL())
logging.Infof("cache handler listens on: %v", handler.ExternalURL())
execArgs.cacheHandler = handler
if len(execArgs.artifactServerAddr) == 0 {
@@ -564,7 +565,7 @@ func runExec(ctx context.Context, execArgs *executeArgs) func(cmd *cobra.Command
}
artifactCancel := artifacts.Serve(ctx, execArgs.artifactServerPath, execArgs.artifactServerAddr, execArgs.artifactServerPort)
log.Debugf("artifacts server started at %s:%s", execArgs.artifactServerPath, execArgs.artifactServerPort)
logging.Debugf("artifacts server started at %s:%s", execArgs.artifactServerPath, execArgs.artifactServerPort)
ctx = common.WithDryrun(ctx, execArgs.dryrun)
executor := r.NewPlanExecutor(plan).Finally(func(ctx context.Context) error {
+28 -27
View File
@@ -13,6 +13,7 @@ import (
goruntime "runtime"
"strings"
"gitea.com/gitea/runner/act/common/logging"
"gitea.com/gitea/runner/internal/app/run"
"gitea.com/gitea/runner/internal/pkg/client"
"gitea.com/gitea/runner/internal/pkg/config"
@@ -24,28 +25,27 @@ import (
pingv1 "gitea.dev/actionslib/ping/v1"
runnerv1 "gitea.dev/actionslib/runner/v1"
"github.com/mattn/go-isatty"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
)
// runRegister registers a runner to the server
func runRegister(ctx context.Context, regArgs *registerArgs, configFile *string) func(*cobra.Command, []string) error {
return func(cmd *cobra.Command, args []string) error {
log.SetReportCaller(false)
logging.SetReportCaller(false)
isTerm := isatty.IsTerminal(os.Stdout.Fd())
log.SetFormatter(&log.TextFormatter{
logging.SetTextFormat(logging.TextOptions{
DisableColors: !isTerm,
DisableTimestamp: true,
})
log.SetLevel(log.DebugLevel)
logging.SetLevel(logging.LevelDebug)
log.Infof("Registering runner, arch=%s, os=%s, version=%s.",
logging.Infof("Registering runner, arch=%s, os=%s, version=%s.",
goruntime.GOARCH, goruntime.GOOS, ver.Version())
// runner always needs root permission
if os.Getuid() != 0 {
// TODO: use a better way to check root permission
log.Warnf("Runner in user-mode.")
logging.Warnf("Runner in user-mode.")
}
if regArgs.NoInteractive {
@@ -55,7 +55,8 @@ func runRegister(ctx context.Context, regArgs *registerArgs, configFile *string)
} else {
go func() {
if err := registerInteractive(ctx, *configFile, regArgs); err != nil {
log.Fatal(err)
logging.Error(err)
os.Exit(1)
return
}
os.Exit(0)
@@ -182,13 +183,13 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co
for _, l := range cfg.Runner.Labels {
_, err := labels.Parse(l)
if err != nil {
log.WithError(err).Warnf("ignored invalid label %q", l)
logging.WithError(err).Warnf("ignored invalid label %q", l)
continue
}
ls = append(ls, l)
}
if len(ls) == 0 {
log.Warn("no valid labels configured in config file, runner may not be able to pick up jobs")
logging.Warn("no valid labels configured in config file, runner may not be able to pick up jobs")
}
r.Labels = ls
return StageWaitingForRegistration
@@ -201,7 +202,7 @@ func (r *registerInputs) assignToNext(stage registerStage, value string, cfg *co
}
if validateLabels(r.Labels) != nil {
log.Infoln("Invalid labels, please input again, leave blank to use the default labels (for example, ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest)")
logging.Info("Invalid labels, please input again, leave blank to use the default labels (for example, ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest)")
r.Labels = nil
return StageInputLabels
}
@@ -273,11 +274,11 @@ func registerInteractive(ctx context.Context, configFile string, regArgs *regist
stage = inputs.assignToNext(stage, strings.TrimSpace(cmdString), cfg)
if stage == StageWaitingForRegistration {
log.Infof("Registering runner, name=%s, instance=%s, labels=%v.", inputs.RunnerName, inputs.InstanceAddr, inputs.Labels)
logging.Infof("Registering runner, name=%s, instance=%s, labels=%v.", inputs.RunnerName, inputs.InstanceAddr, inputs.Labels)
if err := doRegister(ctx, cfg, inputs); err != nil {
return fmt.Errorf("failed to register runner: %w", err)
}
log.Infof("Runner registered successfully.")
logging.Infof("Runner registered successfully.")
return nil
}
@@ -286,7 +287,7 @@ func registerInteractive(ctx context.Context, configFile string, regArgs *regist
}
if stage <= StageUnknown {
log.Errorf("Invalid input, please re-run act command.")
logging.Errorf("Invalid input, please re-run act command.")
return nil
}
}
@@ -295,18 +296,18 @@ func registerInteractive(ctx context.Context, configFile string, regArgs *regist
func printStageHelp(stage registerStage) {
switch stage {
case StageOverwriteLocalConfig:
log.Infoln("Runner is already registered, overwrite local config? [y/N]")
logging.Info("Runner is already registered, overwrite local config? [y/N]")
case StageInputInstance:
log.Infoln("Enter the Gitea instance URL (for example, https://gitea.com/):")
logging.Info("Enter the Gitea instance URL (for example, https://gitea.com/):")
case StageInputToken:
log.Infoln("Enter the runner token:")
logging.Info("Enter the runner token:")
case StageInputRunnerName:
hostname, _ := os.Hostname()
log.Infof("Enter the runner name (if set empty, use hostname: %s):\n", hostname)
logging.Infof("Enter the runner name (if set empty, use hostname: %s):\n", hostname)
case StageInputLabels:
log.Infoln("Enter the runner labels, leave blank to use the default labels (comma-separated, for example, ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest):")
logging.Info("Enter the runner labels, leave blank to use the default labels (comma-separated, for example, ubuntu-latest:docker://docker.gitea.com/runner-images:ubuntu-latest):")
case StageWaitingForRegistration:
log.Infoln("Waiting for registration...")
logging.Info("Waiting for registration...")
}
}
@@ -322,7 +323,7 @@ func registerNoInteractive(ctx context.Context, configFile string, regArgs *regi
// specify labels in config file.
if len(cfg.Runner.Labels) > 0 {
if regArgs.Labels != "" {
log.Warn("Labels from command will be ignored, use labels defined in config file.")
logging.Warn("Labels from command will be ignored, use labels defined in config file.")
}
inputs.Labels = cfg.Runner.Labels
}
@@ -332,16 +333,16 @@ func registerNoInteractive(ctx context.Context, configFile string, regArgs *regi
if inputs.RunnerName == "" {
inputs.RunnerName, _ = os.Hostname()
log.Infof("Runner name is empty, use hostname '%s'.", inputs.RunnerName)
logging.Infof("Runner name is empty, use hostname '%s'.", inputs.RunnerName)
}
if err := inputs.validate(); err != nil {
log.WithError(err).Errorf("Invalid input, please re-run act command.")
logging.WithError(err).Errorf("Invalid input, please re-run act command.")
return err
}
if err := doRegister(ctx, cfg, inputs); err != nil {
return fmt.Errorf("failed to register runner: %w", err)
}
log.Infof("Runner registered successfully.")
logging.Infof("Runner registered successfully.")
return nil
}
@@ -355,7 +356,7 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
// Best-effort guard: if the lock file can't be created, warn and
// register anyway; writing the runner file will surface any real
// permission problem with a clearer error.
log.Warnf("could not lock runner file %q, continuing without the single-process guard: %v", cfg.Runner.File, err)
logging.Warnf("could not lock runner file %q, continuing without the single-process guard: %v", cfg.Runner.File, err)
default:
defer func() { _ = releaseLock() }()
}
@@ -375,7 +376,7 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
})); err != nil {
return fmt.Errorf("cannot ping the Gitea instance server: %w", err)
}
log.Debugln("Successfully pinged the Gitea instance server")
logging.Debug("Successfully pinged the Gitea instance server")
reg := &config.Registration{
Name: inputs.RunnerName,
@@ -403,7 +404,7 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
Capabilities: run.RunnerCapabilities(),
}))
if err != nil {
log.WithError(err).Error("poller: cannot register new runner")
logging.WithError(err).Error("poller: cannot register new runner")
return err
}
@@ -414,7 +415,7 @@ func doRegister(ctx context.Context, cfg *config.Config, inputs *registerInputs)
if inputs.Ephemeral != resp.Msg.Runner.Ephemeral {
// TODO we cannot remove the configuration via runner api, if we return an error here we just fill the database
log.Error("poller: cannot register new runner as ephemeral upgrade Gitea to gain security, run-once will be used automatically")
logging.Error("poller: cannot register new runner as ephemeral upgrade Gitea to gain security, run-once will be used automatically")
}
if err := config.SaveRegistration(cfg.Runner.File, reg); err != nil {