feat: parse register arguments and do register when non-interactive mode

This commit is contained in:
fuxiaohei
2022-11-17 19:43:26 +08:00
committed by Jason Song
parent ab4e06f977
commit 45de6199d1
2 changed files with 59 additions and 13 deletions

View File

@ -3,6 +3,7 @@ package cmd
import (
"bufio"
"context"
"fmt"
"os"
"os/signal"
"runtime"
@ -41,18 +42,24 @@ func runRegister(ctx context.Context, regArgs *registerArgs, envFile string) fun
log.Warnf("Runner in user-mode.")
}
go func() {
if err := registerInteractive(envFile); err != nil {
// log.Errorln(err)
os.Exit(2)
return
if regArgs.NoInteractive {
if err := registerNoInteractive(envFile, regArgs); err != nil {
return err
}
os.Exit(0)
}()
} else {
go func() {
if err := registerInteractive(envFile); err != nil {
// log.Errorln(err)
os.Exit(2)
return
}
os.Exit(0)
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
}
return nil
}
@ -63,6 +70,8 @@ type registerArgs struct {
NoInteractive bool
InstanceAddr string
Token string
RunnerName string
Labels string
}
type registerStage int8
@ -85,6 +94,16 @@ type registerInputs struct {
CustomLabels []string
}
func (r *registerInputs) validate() error {
if r.InstanceAddr == "" {
return fmt.Errorf("instance address is empty")
}
if r.Token == "" {
return fmt.Errorf("token is empty")
}
return nil
}
func (r *registerInputs) assignToNext(stage registerStage, value string) registerStage {
// must set instance address and token.
@ -191,6 +210,31 @@ func printStageHelp(stage registerStage) {
}
}
func registerNoInteractive(envFile string, regArgs *registerArgs) error {
_ = godotenv.Load(envFile)
cfg, _ := config.FromEnviron()
inputs := &registerInputs{
InstanceAddr: regArgs.InstanceAddr,
Token: regArgs.Token,
RunnerName: regArgs.RunnerName,
CustomLabels: strings.Split(regArgs.Labels, ","),
}
if inputs.RunnerName == "" {
inputs.RunnerName, _ = os.Hostname()
log.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.")
return nil
}
if err := doRegister(&cfg, inputs); err != nil {
log.Errorf("Failed to register runner: %v", err)
return err
}
log.Infof("Runner registered successfully.")
return nil
}
func doRegister(cfg *config.Config, inputs *registerInputs) error {
ctx := context.Background()