Skip to content

Commit

Permalink
Add logs
Browse files Browse the repository at this point in the history
  • Loading branch information
Gchbg committed Mar 25, 2024
1 parent c7e396e commit ef7eb35
Show file tree
Hide file tree
Showing 10 changed files with 430 additions and 209 deletions.
17 changes: 1 addition & 16 deletions .golangci.yml
Original file line number Diff line number Diff line change
@@ -1,21 +1,7 @@
run:
deadline: 5m
allow-parallel-runners: true
timeout: 5m

issues:
# don't skip warning about doc comments
# don't exclude the default set of lint
exclude-use-default: false
# restore some of the defaults
# (fill in the rest as needed)
exclude-rules:
- path: "api/*"
linters:
- lll
- path: "internal/*"
linters:
- dupl
- lll
linters:
disable-all: true
enable:
Expand All @@ -29,7 +15,6 @@ linters:
- gosimple
- govet
- ineffassign
- lll
- misspell
- nakedret
- prealloc
Expand Down
287 changes: 193 additions & 94 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,132 +4,231 @@
package main

import (
"context"
"crypto/tls"
"flag"
"fmt"
"os"
"os/signal"
"path/filepath"
"strings"
"syscall"

"github.com/go-logr/logr"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"k8s.io/apimachinery/pkg/runtime"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
kscheme "k8s.io/client-go/kubernetes/scheme"
_ "k8s.io/client-go/plugin/pkg/client/auth"
"k8s.io/client-go/rest"
"k8s.io/klog/v2"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/healthz"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/manager"
"sigs.k8s.io/controller-runtime/pkg/metrics/server"
"sigs.k8s.io/controller-runtime/pkg/webhook"

metalv1alpha1 "github.com/ironcore-dev/metal/api/v1alpha1"
"github.com/ironcore-dev/metal/internal/controller"
"github.com/ironcore-dev/metal/internal/log"
//+kubebuilder:scaffold:imports
)

var (
scheme = runtime.NewScheme()
setupLog = ctrl.Log.WithName("setup")
)
type params struct {
dev bool
leaderElection bool
healthProbeBindAddress string
metricsBindAddress string
secureMetrics bool
enableHTTP2 bool
kubeconfig string
enableMachineController bool
enableMachineClaimController bool
enableOOBController bool
enableOOBSecretController bool
}

func init() {
utilruntime.Must(clientgoscheme.AddToScheme(scheme))
utilruntime.Must(metalv1alpha1.AddToScheme(scheme))
//+kubebuilder:scaffold:scheme
func parseCmdLine() params {
pflag.Usage = usage
pflag.ErrHelp = nil
pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ContinueOnError)

pflag.Bool("dev", false, "Log human-readable messages at debug level.")
pflag.Bool("leader-elect", false, "Enable leader election to ensure there is only one active controller manager.")
pflag.String("health-probe-bind-address", "", "The address that the health probe server binds to.")
pflag.String("metrics-bind-address", "0", "The address that the metrics server binds to.")
pflag.Bool("metrics-secure", false, "Serve metrics securely.")
pflag.Bool("enable-http2", false, "Enable HTTP2 for the metrics and webhook servers.")
pflag.String("kubeconfig", "", "Use a kubeconfig to run out of cluster.")
pflag.Bool("enable-machine-controller", true, "Enable the Machine controller.")
pflag.Bool("enable-machineclaim-controller", true, "Enable the MachineClaim controller.")
pflag.Bool("enable-oob-controller", true, "Enable the OOB controller.")
pflag.Bool("enable-oobsecret-controller", true, "Enable the OOBSecret controller.")

var help bool
pflag.BoolVarP(&help, "help", "h", false, "Show this help message.")
err := viper.BindPFlags(pflag.CommandLine)
if err != nil {
exitUsage(err)
}
viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_"))
viper.AutomaticEnv()
err = pflag.CommandLine.Parse(os.Args[1:])
if err != nil {
exitUsage(err)
}
if help {
exitUsage(nil)
}

return params{
dev: viper.GetBool("dev"),
leaderElection: viper.GetBool("leader-elect"),
healthProbeBindAddress: viper.GetString("health-probe-bind-address"),
metricsBindAddress: viper.GetString("metrics-bind-address"),
secureMetrics: viper.GetBool("metrics-secure"),
enableHTTP2: viper.GetBool("enable-http2"),
kubeconfig: viper.GetString("kubeconfig"),
enableMachineController: viper.GetBool("enable-machine-controller"),
enableMachineClaimController: viper.GetBool("enable-machineclaim-controller"),
enableOOBController: viper.GetBool("enable-oob-controller"),
enableOOBSecretController: viper.GetBool("enable-oobsecret-controller"),
}
}

func usage() {
name := filepath.Base(os.Args[0])
_, _ = fmt.Fprintf(os.Stderr, "Usage: %s [--option]...\n", name)
_, _ = fmt.Fprintf(os.Stderr, "Options:\n")
pflag.PrintDefaults()
}

func exitUsage(err error) {
if err != nil {
_, _ = fmt.Fprintf(os.Stderr, "%s: %s\n", filepath.Base(os.Args[0]), err)
}
pflag.Usage()
os.Exit(2)
}

func main() {
var metricsAddr string
var enableLeaderElection bool
var probeAddr string
var secureMetrics bool
var enableHTTP2 bool
flag.StringVar(&metricsAddr, "metrics-bind-address", ":8080", "The address the metric endpoint binds to.")
flag.StringVar(&probeAddr, "health-probe-bind-address", ":8081", "The address the probe endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "leader-elect", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.BoolVar(&secureMetrics, "metrics-secure", false,
"If set the metrics endpoint is served securely")
flag.BoolVar(&enableHTTP2, "enable-http2", false,
"If set, HTTP/2 will be enabled for the metrics and webhook servers")
opts := zap.Options{
Development: true,
}
opts.BindFlags(flag.CommandLine)
flag.Parse()

ctrl.SetLogger(zap.New(zap.UseFlagOptions(&opts)))

disableHTTP2 := func(c *tls.Config) {
setupLog.Info("disabling http/2")
c.NextProtos = []string{"http/1.1"}
p := parseCmdLine()

var exitCode int
defer func() {
os.Exit(exitCode)
}()

ctx, stop := signal.NotifyContext(log.Setup(context.Background(), p.dev, false, os.Stderr), syscall.SIGTERM, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGHUP)
defer stop()
log.Info(ctx, "Starting OOB operator")

defer func() {
log.Info(ctx, "Exiting", "exitCode", exitCode)
}()

l := logr.FromContextOrDiscard(ctx)
klog.SetLogger(l)
ctrl.SetLogger(l)

scheme := runtime.NewScheme()
err := kscheme.AddToScheme(scheme)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create type scheme: %w", err))
exitCode = 1
return
}
err = metalv1alpha1.AddToScheme(scheme)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create type scheme: %w", err))
exitCode = 1
return
}
//+kubebuilder:scaffold:scheme

var tlsOpts []func(*tls.Config)
if !enableHTTP2 {
tlsOpts = append(tlsOpts, disableHTTP2)
var kcfg *rest.Config
kcfg, err = ctrl.GetConfig()
if err != nil {
log.Error(ctx, fmt.Errorf("cannot get kubeconfig: %w", err))
exitCode = 1
return
}

webhookServer := webhook.NewServer(webhook.Options{
TLSOpts: tlsOpts,
})
var tlsOpts []func(*tls.Config)
if !p.enableHTTP2 {
tlsOpts = append(tlsOpts, func(c *tls.Config) {
c.NextProtos = []string{"http/1.1"}
})
}

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
Metrics: metricsserver.Options{
BindAddress: metricsAddr,
SecureServing: secureMetrics,
var mgr manager.Manager
mgr, err = ctrl.NewManager(kcfg, ctrl.Options{
Scheme: scheme,
LeaderElection: p.leaderElection,
LeaderElectionID: "metal.ironcore.dev",
Metrics: server.Options{
BindAddress: p.metricsBindAddress,
SecureServing: p.secureMetrics,
TLSOpts: tlsOpts,
},
WebhookServer: webhookServer,
HealthProbeBindAddress: probeAddr,
LeaderElection: enableLeaderElection,
LeaderElectionID: "metal.ironcore.dev",
HealthProbeBindAddress: p.healthProbeBindAddress,
WebhookServer: webhook.NewServer(webhook.Options{
TLSOpts: tlsOpts,
}),
BaseContext: func() context.Context {
return ctx
},
})
if err != nil {
setupLog.Error(err, "unable to start manager")
os.Exit(1)
}

if err = (&controller.MachineReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "Machine")
os.Exit(1)
}
if err = (&controller.MachineClaimReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "MachineClaim")
os.Exit(1)
}
if err = (&controller.OOBReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "OOB")
os.Exit(1)
}
if err = (&controller.OOBSecretReconciler{
Client: mgr.GetClient(),
Scheme: mgr.GetScheme(),
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "OOBSecret")
os.Exit(1)
log.Error(ctx, fmt.Errorf("cannot create manager: %w", err))
exitCode = 1
return
}

err = controller.NewMachineReconciler().SetupWithManager(mgr)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create controller: %w", err), "controller", "Machine")
exitCode = 1
return
}
err = controller.NewMachineClaimReconciler().SetupWithManager(mgr)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create controller: %w", err), "controller", "MachineClaim")
exitCode = 1
return
}
err = controller.NewOOBReconciler().SetupWithManager(mgr)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create controller: %w", err), "controller", "OOB")
exitCode = 1
return
}
err = controller.NewOOBSecretReconciler().SetupWithManager(mgr)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot create controller: %w", err), "controller", "OOBSecret")
exitCode = 1
return
}
//+kubebuilder:scaffold:builder

if err = mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
err = mgr.AddHealthzCheck("health", healthz.Ping)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot set up health check: %w", err))
exitCode = 1
return
}
if err = mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
setupLog.Error(err, "unable to set up ready check")
os.Exit(1)

err = mgr.AddReadyzCheck("check", healthz.Ping)
if err != nil {
log.Error(ctx, fmt.Errorf("cannot set up ready check: %w", err))
exitCode = 1
return
}

setupLog.Info("starting manager")
if err = mgr.Start(ctrl.SetupSignalHandler()); err != nil {
setupLog.Error(err, "problem running manager")
os.Exit(1)
log.Info(ctx, "Starting manager")
err = mgr.Start(ctx)
if err != nil {
log.Error(ctx, err)
exitCode = 1
return
}
}
Loading

0 comments on commit ef7eb35

Please sign in to comment.