Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove dependency on packethost/pkg #677

Merged
merged 2 commits into from
Mar 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 5 additions & 15 deletions cmd/tink-controller/main.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
package main

import (
"context"
"fmt"
"os"
"strings"

"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/packethost/pkg/log"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
Expand Down Expand Up @@ -44,28 +42,20 @@ func (c *Config) AddFlags(fs *pflag.FlagSet) {
}

func main() {
// Init the packet logger as its used throughout the codebase.
logger, err := log.Init("github.com/tinkerbell/tink")
if err != nil {
panic(err)
}

cmd := NewRootCommand()
if err := cmd.ExecuteContext(context.Background()); err != nil {
logger.Close()
fmt.Fprint(os.Stderr, err.Error())
if err := cmd.Execute(); err != nil {
os.Exit(1)
}
logger.Close()
}

func NewRootCommand() *cobra.Command {
config := &Config{}
zapLogger, err := zap.NewProduction()
var config Config

zlog, err := zap.NewProduction()
if err != nil {
panic(err)
}
logger := zapr.NewLogger(zapLogger)
logger := zapr.NewLogger(zlog).WithName("github.com/tinkerbell/tink")

cmd := &cobra.Command{
Use: "tink-controller",
Expand Down
72 changes: 36 additions & 36 deletions cmd/tink-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ import (
"syscall"

"github.com/equinix-labs/otel-init-go/otelinit"
"github.com/packethost/pkg/env"
"github.com/packethost/pkg/log"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/tinkerbell/tink/internal/grpcserver"
"github.com/tinkerbell/tink/internal/httpserver"
"github.com/tinkerbell/tink/internal/server"
"go.uber.org/zap"
)

// version is set at build time.
var version = "devel"

// DaemonConfig represents all the values you can configure as part of the tink-server.
// Config represents all the values you can configure as part of the tink-server.
// You can change the configuration via environment variable, or file, or command flags.
type DaemonConfig struct {
Facility string
type Config struct {
GRPCAuthority string
HTTPAuthority string
Backend string
Expand All @@ -41,8 +41,7 @@ func backends() []string {
return []string{backendKubernetes}
}

func (c *DaemonConfig) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.Facility, "facility", "deprecated", "This is temporary. It will be removed")
func (c *Config) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.GRPCAuthority, "grpc-authority", ":42113", "The address used to expose the gRPC server")
fs.StringVar(&c.HTTPAuthority, "http-authority", ":42114", "The address used to expose the HTTP server")
fs.StringVar(&c.Backend, "backend", backendKubernetes, fmt.Sprintf("The backend datastore to use. Must be one of %s", strings.Join(backends(), ", ")))
Expand All @@ -51,33 +50,32 @@ func (c *DaemonConfig) AddFlags(fs *pflag.FlagSet) {
fs.StringVar(&c.KubeNamespace, "kube-namespace", "", "The Kubernetes namespace to target")
}

func (c *DaemonConfig) PopulateFromLegacyEnvVar() {
c.Facility = env.Get("FACILITY", c.Facility)
c.GRPCAuthority = env.Get("TINKERBELL_GRPC_AUTHORITY", c.GRPCAuthority)
c.HTTPAuthority = env.Get("TINKERBELL_HTTP_AUTHORITY", c.HTTPAuthority)
func (c *Config) PopulateFromLegacyEnvVar() {
if v, ok := os.LookupEnv("TINKERBELL_GRPC_AUTHORITY"); ok {
c.GRPCAuthority = v
}

if v, ok := os.LookupEnv("TINKERBELL_HTTP_AUTHORITY"); ok {
c.HTTPAuthority = v
}
}

func main() {
logger, err := log.Init("github.com/tinkerbell/tink")
if err != nil {
panic(err)
if err := NewRootCommand().Execute(); err != nil {
fmt.Fprint(os.Stderr, err.Error())
os.Exit(1)
}
}

ctx := context.Background()
ctx, otelShutdown := otelinit.InitOpenTelemetry(ctx, "github.com/tinkerbell/tink")

config := &DaemonConfig{}
func NewRootCommand() *cobra.Command {
var config Config

cmd := NewRootCommand(config, logger)
if err := cmd.ExecuteContext(ctx); err != nil {
os.Exit(1)
zlog, err := zap.NewProduction()
if err != nil {
panic(err)
}
logger := zapr.NewLogger(zlog).WithName("github.com/tinkerbell/tink")

logger.Close()
otelShutdown(ctx)
}

func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command {
cmd := &cobra.Command{
Use: "tink-server",
PreRunE: func(cmd *cobra.Command, args []string) error {
Expand All @@ -95,11 +93,14 @@ func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command {
// the old way works as before.
config.PopulateFromLegacyEnvVar()

logger.Info("starting version " + version)
logger.Info("Starting version " + version)

ctx, oshutdown := otelinit.InitOpenTelemetry(cmd.Context(), "github.com/tinkerbell/tink")
defer oshutdown(context.Background())

sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGTERM)
ctx, closer := context.WithCancel(cmd.Context())
ctx, closer := context.WithCancel(ctx)
defer closer()
// TODO(gianarb): I think we can do better in terms of
// graceful shutdown and error management but I want to
Expand Down Expand Up @@ -133,15 +134,15 @@ func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command {
if err != nil {
return err
}
logger.With("address", addr).Info("started listener")
logger.Info("started listener", "address", addr)

httpserver.SetupHTTP(ctx, logger, config.HTTPAuthority, errCh)

select {
case err := <-errCh:
logger.Error(err)
logger.Error(err, "")
case sig := <-sigs:
logger.With("signal", sig.String()).Info("signal received, stopping servers")
logger.Info("signal received, stopping servers", "signal", sig.String())
closer()
}

Expand All @@ -161,7 +162,7 @@ func NewRootCommand(config *DaemonConfig, logger log.Logger) *cobra.Command {
return cmd
}

func createViper(logger log.Logger) (*viper.Viper, error) {
func createViper(log logr.Logger) (*viper.Viper, error) {
v := viper.New()
v.AutomaticEnv()
v.SetConfigName("tink-server")
Expand All @@ -172,12 +173,11 @@ func createViper(logger log.Logger) (*viper.Viper, error) {
// If a config file is found, read it in.
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
logger.With("configFile", v.ConfigFileUsed()).Error(err, "could not load config file")
return nil, err
return nil, fmt.Errorf("could not load config file: %w", err)
}
logger.Info("no config file found")
log.Info("No config file found")
} else {
logger.With("configFile", v.ConfigFileUsed()).Info("loaded config file")
log.Info("Loaded config file", "path", v.ConfigFileUsed())
}

return v, nil
Expand Down
22 changes: 15 additions & 7 deletions cmd/tink-worker/cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,16 @@ import (
"time"

dockercli "github.com/docker/docker/client"
"github.com/packethost/pkg/log"
"github.com/go-logr/logr"
"github.com/go-logr/zapr"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/tinkerbell/tink/cmd/tink-worker/worker"
"github.com/tinkerbell/tink/internal/client"
"github.com/tinkerbell/tink/internal/proto"
"go.uber.org/zap"
)

const (
Expand All @@ -24,7 +26,13 @@ const (
)

// NewRootCommand creates a new Tink Worker Cobra root command.
func NewRootCommand(version string, logger log.Logger) *cobra.Command {
func NewRootCommand(version string) *cobra.Command {
zlog, err := zap.NewProduction()
if err != nil {
panic(err)
}
logger := zapr.NewLogger(zlog).WithName("github.com/tinkerbell/tink")

rootCmd := &cobra.Command{
Use: "tink-worker",
Short: "Tink Worker",
Expand All @@ -42,7 +50,7 @@ func NewRootCommand(version string, logger log.Logger) *cobra.Command {
registry := viper.GetString("docker-registry")
captureActionLogs := viper.GetBool("capture-action-logs")

logger.With("version", version).Info("starting")
logger.Info("starting", "version", version)

conn, err := client.NewClientConn(
viper.GetString("tinkerbell-grpc-authority"),
Expand Down Expand Up @@ -99,7 +107,7 @@ func NewRootCommand(version string, logger log.Logger) *cobra.Command {

must := func(err error) {
if err != nil {
logger.Fatal(err)
logger.Error(err, "")
}
}

Expand All @@ -117,7 +125,7 @@ func NewRootCommand(version string, logger log.Logger) *cobra.Command {
// initViper initializes Viper configured to read in configuration files
// (from various paths with content type specific filename extensions) and loads
// environment variables.
func initViper(logger log.Logger, cmd *cobra.Command) error {
func initViper(logger logr.Logger, cmd *cobra.Command) error {
viper.AutomaticEnv()
viper.SetConfigName("tink-worker")
viper.AddConfigPath("/etc/tinkerbell")
Expand All @@ -127,11 +135,11 @@ func initViper(logger log.Logger, cmd *cobra.Command) error {
// If a config file is found, read it in.
if err := viper.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
logger.With("configFile", viper.ConfigFileUsed()).Error(err, "could not load config file")
logger.Error(err, "could not load config file", "configFile", viper.ConfigFileUsed())
return err
}
} else {
logger.With("configFile", viper.ConfigFileUsed()).Info("loaded config file")
logger.Info("loaded config file", "configFile", viper.ConfigFileUsed())
}

cmd.Flags().VisitAll(func(f *pflag.Flag) {
Expand Down
19 changes: 1 addition & 18 deletions cmd/tink-worker/main.go
Original file line number Diff line number Diff line change
@@ -1,34 +1,17 @@
package main

import (
"context"
"os"

"github.com/equinix-labs/otel-init-go/otelinit"
"github.com/packethost/pkg/log"
"github.com/tinkerbell/tink/cmd/tink-worker/cmd"
)

const (
serviceKey = "github.com/tinkerbell/tink"
)

// version is set at build time.
var version = "devel"

func main() {
logger, err := log.Init(serviceKey)
if err != nil {
panic(err)
}

ctx, otelShutdown := otelinit.InitOpenTelemetry(context.Background(), "github.com/tinkerbell/tink")

rootCmd := cmd.NewRootCommand(version, logger)
rootCmd := cmd.NewRootCommand(version)
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}

logger.Close()
otelShutdown(ctx)
}
23 changes: 11 additions & 12 deletions cmd/tink-worker/worker/container_manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import (
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/client"
"github.com/packethost/pkg/log"
"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/tinkerbell/tink/internal/proto"
)
Expand All @@ -28,24 +28,23 @@ type DockerClient interface {
}

type containerManager struct {
logger log.Logger
logger logr.Logger
cli DockerClient
registryDetails RegistryConnDetails
}

// getLogger is a helper function to get logging out of a context, or use the default logger.
func (m *containerManager) getLogger(ctx context.Context) *log.Logger {
func (m *containerManager) getLogger(ctx context.Context) logr.Logger {
loggerIface := ctx.Value(loggingContextKey)
if loggerIface == nil {
return &m.logger
return m.logger
}
l, _ := loggerIface.(*log.Logger)

l, _ := loggerIface.(logr.Logger)
return l
}

// NewContainerManager returns a new container manager.
func NewContainerManager(logger log.Logger, cli DockerClient, registryDetails RegistryConnDetails) ContainerManager {
func NewContainerManager(logger logr.Logger, cli DockerClient, registryDetails RegistryConnDetails) ContainerManager {
return &containerManager{logger, cli, registryDetails}
}

Expand Down Expand Up @@ -76,7 +75,7 @@ func (m *containerManager) CreateContainer(ctx context.Context, cmd []string, wf
}

hostConfig.Binds = append(hostConfig.Binds, action.GetVolumes()...)
l.With("command", cmd).Info("creating container")
l.Info("creating container", "command", cmd)
name := makeValidContainerName(action.GetName())
resp, err := m.cli.ContainerCreate(ctx, config, hostConfig, nil, nil, name)
if err != nil {
Expand All @@ -94,7 +93,7 @@ func makeValidContainerName(name string) string {
}

func (m *containerManager) StartContainer(ctx context.Context, id string) error {
m.getLogger(ctx).With("containerID", id).Debug("starting container")
m.getLogger(ctx).Info("starting container", "containerID", id)
return errors.Wrap(m.cli.ContainerStart(ctx, id, types.ContainerStartOptions{}), "DOCKER START")
}

Expand Down Expand Up @@ -133,10 +132,10 @@ func (m *containerManager) WaitForFailedContainer(ctx context.Context, id string
}
failedActionStatus <- proto.State_STATE_FAILED
case err := <-errC:
l.Error(err)
l.Error(err, "")
failedActionStatus <- proto.State_STATE_FAILED
case <-ctx.Done():
l.Error(ctx.Err())
l.Error(ctx.Err(), "")
failedActionStatus <- proto.State_STATE_TIMEOUT
}
}
Expand All @@ -148,7 +147,7 @@ func (m *containerManager) RemoveContainer(ctx context.Context, id string) error
RemoveLinks: false,
RemoveVolumes: true,
}
m.getLogger(ctx).With("containerID", id).Info("removing container")
m.getLogger(ctx).Info("removing container", "containerID", id)

// send API call to remove the container
return errors.Wrap(m.cli.ContainerRemove(ctx, id, opts), "DOCKER STOP")
Expand Down
Loading