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

[addon-operator] Replace Logrus with slog #516

Merged
merged 32 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 25 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
28 changes: 28 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ linters:
- nolintlint
- prealloc
- revive
- sloglint
- staticcheck
- stylecheck
- unconvert
Expand All @@ -36,6 +37,33 @@ linters-settings:
- prefix(github.com/flant/)
goimports:
local-prefixes: github.com/flant/
sloglint:
# Enforce not mixing key-value pairs and attributes.
no-mixed-args: true
# Enforce using key-value pairs only (overrides no-mixed-args, incompatible with attr-only).
kv-only: false
# Enforce using attributes only (overrides no-mixed-args, incompatible with kv-only).
attr-only: false
# Enforce not using global loggers.
no-global: ""
# Enforce using methods that accept a context.
context: ""
# Enforce using static values for log messages.
static-msg: false
# Enforce using constants instead of raw keys.
no-raw-keys: false
# Enforce a single key naming convention.
key-naming-case: ""
# Enforce not using specific keys.
forbidden-keys:
- level
- msg
- logger
- source
- stacktrace
- time
# Enforce putting arguments on separate lines.
args-on-sep-lines: false
depguard:
rules:
Main:
Expand Down
77 changes: 44 additions & 33 deletions cmd/addon-operator/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ package main
import (
"context"
"fmt"
"log/slog"
"os"
"strings"
"syscall"
"time"

log "github.com/sirupsen/logrus"
"github.com/deckhouse/deckhouse/pkg/log"
"gopkg.in/alecthomas/kingpin.v2"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/leaderelection"
Expand All @@ -17,8 +18,8 @@ import (
addon_operator "github.com/flant/addon-operator/pkg/addon-operator"
"github.com/flant/addon-operator/pkg/app"
"github.com/flant/addon-operator/pkg/kube_config_manager/backend/configmap"
"github.com/flant/addon-operator/pkg/utils/stdliblogtologrus"
"github.com/flant/kube-client/klogtologrus"
"github.com/flant/addon-operator/pkg/utils/stdliblogtolog"
"github.com/flant/kube-client/klogtolog"
sh_app "github.com/flant/shell-operator/pkg/app"
"github.com/flant/shell-operator/pkg/debug"
utils_signal "github.com/flant/shell-operator/pkg/utils/signal"
Expand All @@ -34,12 +35,15 @@ const (
func main() {
kpApp := kingpin.New(app.AppName, fmt.Sprintf("%s %s: %s", app.AppName, app.Version, app.AppDescription))

logger := log.NewLogger(log.Options{})
log.SetDefault(logger)

// override usage template to reveal additional commands with information about start command
kpApp.UsageTemplate(sh_app.OperatorUsageTemplate(app.AppName))

kpApp.Action(func(_ *kingpin.ParseContext) error {
klogtologrus.InitAdapter(sh_app.DebugKubernetesAPI)
stdliblogtologrus.InitAdapter()
klogtolog.InitAdapter(sh_app.DebugKubernetesAPI, logger.Named("klog"))
stdliblogtolog.InitAdapter(logger)
return nil
})

Expand All @@ -52,7 +56,7 @@ func main() {
// start main loop
startCmd := kpApp.Command("start", "Start events processing.").
Default().
Action(start)
Action(start(logger))

app.DefineStartCommandFlags(kpApp, startCmd)

Expand All @@ -62,39 +66,41 @@ func main() {
kingpin.MustParse(kpApp.Parse(os.Args[1:]))
}

func start(_ *kingpin.ParseContext) error {
sh_app.AppStartMessage = fmt.Sprintf("%s %s, shell-operator %s", app.AppName, app.Version, sh_app.Version)
func start(logger *log.Logger) func(_ *kingpin.ParseContext) error {
return func(_ *kingpin.ParseContext) error {
sh_app.AppStartMessage = fmt.Sprintf("%s %s, shell-operator %s", app.AppName, app.Version, sh_app.Version)

ctx := context.Background()
ctx := context.Background()

operator := addon_operator.NewAddonOperator(ctx)
operator := addon_operator.NewAddonOperator(ctx, addon_operator.WithLogger(logger.Named("addon-operator")))

operator.StartAPIServer()
operator.StartAPIServer()

if os.Getenv("ADDON_OPERATOR_HA") == "true" {
log.Info("Addon-operator is starting in HA mode")
runHAMode(ctx, operator)
return nil
}
if os.Getenv("ADDON_OPERATOR_HA") == "true" {
operator.Logger.Info("Addon-operator is starting in HA mode")
runHAMode(ctx, operator)
return nil
}

err := run(ctx, operator)
if err != nil {
log.Fatal(err)
}
err := run(ctx, operator)
if err != nil {
operator.Logger.Fatal("run operator", slog.String("error", err.Error()))
}

return nil
return nil
}
}

func run(ctx context.Context, operator *addon_operator.AddonOperator) error {
bk := configmap.New(log.StandardLogger(), operator.KubeClient(), app.Namespace, app.ConfigMapName)
bk := configmap.New(operator.Logger.Named("kube-config-manager"), operator.KubeClient(), app.Namespace, app.ConfigMapName)
operator.SetupKubeConfigManager(bk)

if err := operator.Setup(); err != nil {
log.Fatalf("setup failed: %s\n", err)
operator.Logger.Fatalf("setup failed: %s\n", err)
}

if err := operator.Start(ctx); err != nil {
log.Fatalf("start failed: %s\n", err)
operator.Logger.Fatalf("start failed: %s\n", err)
}

// Block action by waiting signals from OS.
Expand All @@ -109,22 +115,25 @@ func run(ctx context.Context, operator *addon_operator.AddonOperator) error {
func runHAMode(ctx context.Context, operator *addon_operator.AddonOperator) {
podName := os.Getenv("ADDON_OPERATOR_POD")
if len(podName) == 0 {
log.Fatal("ADDON_OPERATOR_POD env not set or empty")
operator.Logger.Info("ADDON_OPERATOR_POD env not set or empty")
os.Exit(1)
}

podIP := os.Getenv("ADDON_OPERATOR_LISTEN_ADDRESS")
if len(podIP) == 0 {
log.Fatal("ADDON_OPERATOR_LISTEN_ADDRESS env not set or empty")
operator.Logger.Info("ADDON_OPERATOR_LISTEN_ADDRESS env not set or empty")
os.Exit(1)
}

podNs := os.Getenv("ADDON_OPERATOR_NAMESPACE")
if len(podNs) == 0 {
log.Fatal("ADDON_OPERATOR_NAMESPACE env not set or empty")
operator.Logger.Info("ADDON_OPERATOR_NAMESPACE env not set or empty")
os.Exit(1)
}

identity := fmt.Sprintf("%s.%s.%s.pod", podName, strings.ReplaceAll(podIP, ".", "-"), podNs)

if err := operator.WithLeaderElector(&leaderelection.LeaderElectionConfig{
err := operator.WithLeaderElector(&leaderelection.LeaderElectionConfig{
// Create a leaderElectionConfig for leader election
Lock: &resourcelock.LeaseLock{
LeaseMeta: v1.ObjectMeta{
Expand All @@ -143,25 +152,27 @@ func runHAMode(ctx context.Context, operator *addon_operator.AddonOperator) {
OnStartedLeading: func(ctx context.Context) {
err := run(ctx, operator)
if err != nil {
log.Fatal(err)
operator.Logger.Info("run on stardet leading", slog.String("error", err.Error()))
os.Exit(1)
}
},
OnStoppedLeading: func() {
log.Info("Restarting because the leadership was handed over")
operator.Logger.Info("Restarting because the leadership was handed over")
operator.Stop()
os.Exit(0)
},
},
ReleaseOnCancel: true,
}); err != nil {
log.Fatal(err)
})
if err != nil {
operator.Logger.Fatal("with leader election", slog.String("error", err.Error()))
}

go func() {
<-ctx.Done()
log.Info("Context canceled received")
if err := syscall.Kill(1, syscall.SIGUSR2); err != nil {
log.Fatalf("Couldn't shutdown addon-operator: %s\n", err)
operator.Logger.Fatal("Couldn't shutdown addon-operator", slog.String("error", err.Error()))
}
}()

Expand Down
2 changes: 1 addition & 1 deletion examples/700-go-hook/global-hooks/global-go-hook.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ var _ = sdk.RegisterFunc(&go_hook.HookConfig{
}, handler)

func handler(input *go_hook.HookInput) error {
input.LogEntry.Infof("Start Global Go hook")
input.Logger.Infof("Start Global Go hook")
return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,10 +54,10 @@ func ObjFilter(obj *unstructured.Unstructured) (go_hook.FilterResult, error) {
func run(input *go_hook.HookInput) error {
for _, o := range input.Snapshots["pods"] {
podSpec := o.(*podSpecFilteredObj)
input.LogEntry.Infof("Got podSpec: %+v", podSpec)
input.Logger.Infof("Got podSpec: %+v", podSpec)
}

input.LogEntry.Infof("Hello from on_kube.pods2! I have %d snapshots\n",
input.Logger.Infof("Hello from on_kube.pods2! I have %d snapshots\n",
len(input.Snapshots))

input.MetricsCollector.Add("addon_go_hooks_total", 1.0, nil)
Expand Down
28 changes: 15 additions & 13 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
module github.com/flant/addon-operator

go 1.22.4
go 1.22.8

require (
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/deckhouse/deckhouse/pkg/log v0.0.0-20241102120041-7e44e3e22ab9
github.com/dominikbraun/graph v0.23.0
github.com/ettle/strcase v0.2.0
github.com/flant/kube-client v1.2.0
github.com/flant/shell-operator v1.4.15
github.com/flant/kube-client v1.2.1
github.com/flant/shell-operator v0.0.0-20241102194750-1f0d1f37165e
github.com/go-chi/chi/v5 v5.1.0
github.com/go-openapi/loads v0.19.5
github.com/go-openapi/spec v0.19.8
Expand All @@ -18,9 +19,8 @@ require (
github.com/gofrs/uuid/v5 v5.3.0
github.com/hashicorp/go-multierror v1.1.1
github.com/kennygrant/sanitize v1.2.4
github.com/onsi/gomega v1.34.1
github.com/onsi/gomega v1.34.2
github.com/pkg/errors v0.9.1
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.9.0
github.com/tidwall/gjson v1.14.4
gopkg.in/alecthomas/kingpin.v2 v2.2.6
Expand All @@ -41,6 +41,7 @@ require (
github.com/AdaLogics/go-fuzz-headers v0.0.0-20230811130428-ced1acdcaa24 // indirect
github.com/Azure/go-ansiterm v0.0.0-20210617225240-d185dfc1b5a1 // indirect
github.com/BurntSushi/toml v1.3.2 // indirect
github.com/DataDog/gostackparse v0.7.0 // indirect
github.com/MakeNowJust/heredoc v1.0.0 // indirect
github.com/Masterminds/goutils v1.1.1 // indirect
github.com/Masterminds/semver/v3 v3.2.1 // indirect
Expand Down Expand Up @@ -104,7 +105,7 @@ require (
github.com/jmoiron/sqlx v1.3.5 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.17.4 // indirect
github.com/klauspost/compress v1.17.9 // indirect
github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect
github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect
github.com/lib/pq v1.10.9 // indirect
Expand All @@ -129,13 +130,14 @@ require (
github.com/opencontainers/image-spec v1.1.0 // indirect
github.com/peterbourgon/diskv v2.0.1+incompatible // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/prometheus/client_golang v1.19.1 // indirect
github.com/prometheus/client_golang v1.20.5 // indirect
github.com/prometheus/client_model v0.6.1 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/rubenv/sql-migrate v1.5.2 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/shopspring/decimal v1.3.1 // indirect
github.com/sirupsen/logrus v1.9.3 // indirect
github.com/spf13/cast v1.5.0 // indirect
github.com/spf13/cobra v1.8.1 // indirect
github.com/spf13/pflag v1.0.5 // indirect
Expand All @@ -151,15 +153,15 @@ require (
go.opentelemetry.io/otel/metric v1.28.0 // indirect
go.opentelemetry.io/otel/trace v1.28.0 // indirect
go.starlark.net v0.0.0-20230525235612-a134d8f9ddca // indirect
golang.org/x/crypto v0.25.0 // indirect
golang.org/x/crypto v0.26.0 // indirect
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56 // indirect
golang.org/x/image v0.18.0 // indirect
golang.org/x/net v0.27.0 // indirect
golang.org/x/net v0.28.0 // indirect
golang.org/x/oauth2 v0.21.0 // indirect
golang.org/x/sync v0.7.0 // indirect
golang.org/x/sys v0.22.0 // indirect
golang.org/x/term v0.22.0 // indirect
golang.org/x/text v0.16.0 // indirect
golang.org/x/sync v0.8.0 // indirect
golang.org/x/sys v0.24.0 // indirect
golang.org/x/term v0.23.0 // indirect
golang.org/x/text v0.17.0 // indirect
golang.org/x/time v0.7.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240701130421-f6361c86f094 // indirect
google.golang.org/grpc v1.59.0 // indirect
Expand Down
Loading
Loading