Skip to content

Commit

Permalink
fixup! tink worker command line args
Browse files Browse the repository at this point in the history
Signed-off-by: Marques Johansson <[email protected]>
  • Loading branch information
displague committed Sep 16, 2020
1 parent 4e424ea commit 3cf8bdb
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 82 deletions.
98 changes: 27 additions & 71 deletions cmd/tink-worker/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,10 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"google.golang.org/grpc"

"github.com/tinkerbell/tink/client"
"github.com/tinkerbell/tink/cmd/tink-worker/internal"
pb "github.com/tinkerbell/tink/protos/workflow"
"google.golang.org/grpc"
)

const (
Expand Down Expand Up @@ -46,28 +45,14 @@ func NewRootCommand(version string, logger *logrus.Logger) *cobra.Command {
RunE: func(cmd *cobra.Command, args []string) error {
retryInterval, _ := cmd.PersistentFlags().GetDuration("retry-interval")
retries, _ := cmd.PersistentFlags().GetInt("retries")
logLevel, _ := cmd.PersistentFlags().GetString("worker-log-level")
workerID, _ := cmd.PersistentFlags().GetString("worker-id")
logLevel, _ := cmd.PersistentFlags().GetString("log-level")
workerID, _ := cmd.PersistentFlags().GetString("id")
maxSize, _ := cmd.PersistentFlags().GetInt64("max-size")
timeOut, _ := cmd.PersistentFlags().GetDuration("worker-timeout")
timeOut, _ := cmd.PersistentFlags().GetDuration("timeout")
user, _ := cmd.PersistentFlags().GetString("registry-username")
pwd, _ := cmd.PersistentFlags().GetString("registry-password")
registry, _ := cmd.PersistentFlags().GetString("docker-registry")

/* param debugging
fmt.Println(map[string]interface{}{
"retryInterval": retryInterval,
"retries": retries,
"logLevel": logLevel,
"workerID": workerID,
"maxSize": maxSize,
"timeOut": timeOut,
"user": user,
"pwd": pwd,
"registry": registry,
})
*/

initializeLogger(logger, logLevel)
logger.Debug("Starting version " + version)
if setupErr := client.Setup(); setupErr != nil {
Expand Down Expand Up @@ -99,18 +84,18 @@ func NewRootCommand(version string, logger *logrus.Logger) *cobra.Command {
},
}

rootCmd.PersistentFlags().DurationP("retry-interval", "i", retryIntervalDefault, "Retry interval in seconds")
rootCmd.PersistentFlags().Duration("retry-interval", retryIntervalDefault, "Retry interval in seconds")

rootCmd.PersistentFlags().DurationP("worker-timeout", "t", 0, "Max duration to wait for worker to complete")
rootCmd.PersistentFlags().Duration("timeout", 0, "Max duration to wait for worker to complete")

rootCmd.PersistentFlags().IntP("max-retry", "m", retryCountDefault, "Maximum number of retries to attempt")
rootCmd.PersistentFlags().Int("max-retry", retryCountDefault, "Maximum number of retries to attempt")

rootCmd.PersistentFlags().Int64P("max-file-size", "s", defaultMaxFileSize, "Maximum file size in bytes")
rootCmd.PersistentFlags().Int64("max-file-size", defaultMaxFileSize, "Maximum file size in bytes")

rootCmd.PersistentFlags().StringP("worker-log-level", "l", "info", "Sets the worker log level (panic, fatal, error, warn, info, debug, trace)")
rootCmd.PersistentFlags().String("log-level", "info", "Sets the worker log level (panic, fatal, error, warn, info, debug, trace)")

rootCmd.PersistentFlags().StringP("worker-id", "w", "", "Sets the worker id")
must(rootCmd.MarkPersistentFlagRequired("worker-id"))
rootCmd.PersistentFlags().StringP("id", "i", "", "Sets the worker id")
must(rootCmd.MarkPersistentFlagRequired("id"))

rootCmd.PersistentFlags().StringP("docker-registry", "r", "", "Sets the Docker registry")
must(rootCmd.MarkPersistentFlagRequired("docker-registry"))
Expand All @@ -124,14 +109,17 @@ func NewRootCommand(version string, logger *logrus.Logger) *cobra.Command {
return rootCmd
}

// createViper creates a Viper object configured to read in configuration files
// (from various paths with content type specific filename extensions) and load
// environment variables that start with TINK_WORKER.
func createViper() (*viper.Viper, error) {
v := viper.New()
v.AutomaticEnv() // read in environment variables that match
v.SetConfigName(".tinkerbell")
v.AutomaticEnv()
v.SetConfigName("tink-worker")
v.AddConfigPath("/etc/tinkerbell")
v.AddConfigPath("$HOME/.config/tinkerbell")
v.AddConfigPath(".")
v.SetEnvPrefix("TINK_WORKER")
v.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))

// If a config file is found, read it in.
if err := v.ReadInConfig(); err != nil {
Expand All @@ -146,26 +134,9 @@ func createViper() (*viper.Viper, error) {
}

func applyViper(v *viper.Viper, cmd *cobra.Command) error {
/*
if err := v.BindPFlags(cmd.PersistentFlags()); err != nil {
return err
}
*/
errors := []error{}

cmd.PersistentFlags().VisitAll(func(f *pflag.Flag) {
// Bind flag names to proper env var name, unhyphenated are handled by AutomaticEnv
if strings.Contains(f.Name, "-") {
envVar := strings.ToUpper(strings.ReplaceAll(f.Name, "-", "_"))
f.Usage = f.Usage + " (" + envVar + ")"
err := v.BindEnv(f.Name, envVar)
if err != nil {
errors = append(errors, err)
return
}
}

// Apply viper config values when cobra has no value and viper does
if !f.Changed && v.IsSet(f.Name) {
val := v.Get(f.Name)
if err := cmd.Flags().Set(f.Name, fmt.Sprintf("%v", val)); err != nil {
Expand All @@ -182,43 +153,27 @@ func applyViper(v *viper.Viper, cmd *cobra.Command) error {
}
return fmt.Errorf(strings.Join(errs, ", "))
}

return nil
}

func initializeLogger(logger *logrus.Logger, level string) {
if level != "" {
switch strings.ToLower(level) {
case "panic":
logger.SetLevel(logrus.PanicLevel)
case "fatal":
logger.SetLevel(logrus.FatalLevel)
case "error":
logger.SetLevel(logrus.ErrorLevel)
case "warn", "warning":
logger.SetLevel(logrus.WarnLevel)
case "info":
logger.SetLevel(logrus.InfoLevel)
case "debug":
logger.SetLevel(logrus.DebugLevel)
case "trace":
logger.SetLevel(logrus.TraceLevel)
default:
logger.SetLevel(logrus.InfoLevel)
logger.Warningln("Invalid value for WORKER_LOG_LEVEL", level, " .Setting it to default(Info)")
if lvl, err := logrus.ParseLevel(level); err == nil {
logger.SetLevel(lvl)
return
}

logger.Warningln("Invalid value for WORKER_LOG_LEVEL", level, " .Setting it to default(Info)")
} else {
logger.SetLevel(logrus.InfoLevel)
logger.Warningln("Variable WORKER_LOG_LEVEL is not set. Default is Info")
}

logger.SetLevel(logrus.InfoLevel)
}

func tryClientConnection(logger *logrus.Logger, retryInterval time.Duration, retries int) (*grpc.ClientConn, error) {
for {
if retries <= 0 {
return nil, fmt.Errorf("retries exceeded")
}
retries--

for ; retries > 0; retries-- {
c, err := client.GetConnection()
if err != nil {
logger.Errorln(err)
Expand All @@ -229,4 +184,5 @@ func tryClientConnection(logger *logrus.Logger, retryInterval time.Duration, ret

return c, nil
}
return nil, fmt.Errorf("retries exceeded")
}
7 changes: 3 additions & 4 deletions cmd/tink-worker/internal/action.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
package internal // import "github.com/tinkerbell/tink/cmd/tink-worker/internal"
package internal

import (
"context"
"os"
"path/filepath"

"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/pkg/errors"

pb "github.com/tinkerbell/tink/protos/workflow"
)

Expand All @@ -26,7 +25,7 @@ func (w *Worker) createContainer(ctx context.Context, cmd []string, wfID string,
config.Cmd = cmd
}

wfDir := dataDir + string(os.PathSeparator) + wfID
wfDir := filepath.Join(dataDir, wfID)
hostConfig := &container.HostConfig{
Privileged: true,
Binds: []string{wfDir + ":/workflow"},
Expand Down
5 changes: 2 additions & 3 deletions cmd/tink-worker/internal/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (r *RegistryConnDetails) NewClient() (*client.Client, error) {
if r.registry == "" {
return nil, errors.New("required DOCKER_REGISTRY")
}
c, err := client.NewClientWithOpts(client.FromEnv, client.WithAPIVersionNegotiation())
c, err := client.NewClientWithOpts(client.FromEnv, client.WithHost(r.registry), client.WithAPIVersionNegotiation())

if err != nil {
return nil, errors.Wrap(err, "DOCKER CLIENT")
Expand All @@ -51,7 +51,6 @@ func (r *RegistryConnDetails) NewClient() (*client.Client, error) {

// pullImage outputs to stdout the contents of the requested image (relative to the registry)
func (w *RegistryConnDetails) pullImage(ctx context.Context, cli *client.Client, image string) error {
registry := w.registry
authConfig := types.AuthConfig{
Username: w.user,
Password: w.pwd,
Expand All @@ -63,7 +62,7 @@ func (w *RegistryConnDetails) pullImage(ctx context.Context, cli *client.Client,
}
authStr := base64.URLEncoding.EncodeToString(encodedJSON)

out, err := cli.ImagePull(ctx, registry+"/"+image, types.ImagePullOptions{RegistryAuth: authStr})
out, err := cli.ImagePull(ctx, w.registry+"/"+image, types.ImagePullOptions{RegistryAuth: authStr})
if err != nil {
return errors.Wrap(err, "DOCKER PULL")
}
Expand Down
5 changes: 2 additions & 3 deletions cmd/tink-worker/internal/worker.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package internal // import "github.com/tinkerbell/tink/cmd/tink-worker/internal"
package internal

import (
"bufio"
Expand All @@ -16,9 +16,8 @@ import (
"github.com/docker/docker/client"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"google.golang.org/grpc/status"

pb "github.com/tinkerbell/tink/protos/workflow"
"google.golang.org/grpc/status"
)

const (
Expand Down
1 change: 0 additions & 1 deletion cmd/tink-worker/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"os"

"github.com/sirupsen/logrus"

"github.com/tinkerbell/tink/cmd/tink-worker/cmd"
)

Expand Down

0 comments on commit 3cf8bdb

Please sign in to comment.