Skip to content

Commit

Permalink
[node-agent] Introduce cmd/gardener-node-agent/app.go with `manager…
Browse files Browse the repository at this point in the history
….Manager` initialization (gardener#8627)

* Add `Server` configuration to `node-agent` config API

* Introduce `main()` function for `gardener-node-agent`

If it will be started with a kubeconfig pointing to the well-known location of the bootstrap token file, it will use it to fetch the access token and write it to the disk. Afterwards, it will overwrite the kubeconfig to point to the access token file instead of the bootstrap token file. The rest config will be modified ad-hoc, hence, the bootstrap token will only be used for fetching the "real" access token.

* Drop validation regarding kubeconfig

Otherwise, it's not possible to specify the kubeconfig via the `KUBECONFIG` environment variable

* Add GNA to `Dockerfile` and `Makefile`

* Address PR review feedback
  • Loading branch information
rfranzke authored Oct 9, 2023
1 parent 5577346 commit b9ecd0b
Show file tree
Hide file tree
Showing 15 changed files with 622 additions and 39 deletions.
6 changes: 6 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,12 @@ COPY --from=builder /go/bin/gardener-resource-manager /gardener-resource-manager
WORKDIR /
ENTRYPOINT ["/gardener-resource-manager"]

# node-agent
FROM distroless-static AS node-agent
COPY --from=builder /go/bin/gardener-node-agent /gardener-node-agent
WORKDIR /
ENTRYPOINT ["/gardener-node-agent"]

# operator
FROM distroless-static AS operator
COPY --from=builder /go/bin/gardener-operator /gardener-operator
Expand Down
5 changes: 5 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ CONTROLLER_MANAGER_IMAGE_REPOSITORY := $(REGISTRY)/controller-manager
SCHEDULER_IMAGE_REPOSITORY := $(REGISTRY)/scheduler
ADMISSION_IMAGE_REPOSITORY := $(REGISTRY)/admission-controller
RESOURCE_MANAGER_IMAGE_REPOSITORY := $(REGISTRY)/resource-manager
NODE_AGENT_IMAGE_REPOSITORY := $(REGISTRY)/node-agent
OPERATOR_IMAGE_REPOSITORY := $(REGISTRY)/operator
GARDENLET_IMAGE_REPOSITORY := $(REGISTRY)/gardenlet
EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY := $(REGISTRY)/extensions/provider-local
Expand Down Expand Up @@ -96,6 +97,7 @@ docker-images:
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(SCHEDULER_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(SCHEDULER_IMAGE_REPOSITORY):latest -f Dockerfile --target scheduler .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(ADMISSION_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(ADMISSION_IMAGE_REPOSITORY):latest -f Dockerfile --target admission-controller .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(RESOURCE_MANAGER_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(RESOURCE_MANAGER_IMAGE_REPOSITORY):latest -f Dockerfile --target resource-manager .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(NODE_AGENT_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(NODE_AGENT_IMAGE_REPOSITORY):latest -f Dockerfile --target node-agent .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(OPERATOR_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(OPERATOR_IMAGE_REPOSITORY):latest -f Dockerfile --target operator .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(GARDENLET_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(GARDENLET_IMAGE_REPOSITORY):latest -f Dockerfile --target gardenlet .
@docker build --build-arg EFFECTIVE_VERSION=$(EFFECTIVE_VERSION) -t $(EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION) -t $(EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY):latest -f Dockerfile --target gardener-extension-provider-local .
Expand All @@ -107,6 +109,7 @@ docker-push:
@if ! docker images $(SCHEDULER_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(SCHEDULER_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@if ! docker images $(ADMISSION_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(ADMISSION_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@if ! docker images $(RESOURCE_MANAGER_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(RESOURCE_MANAGER_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@if ! docker images $(NODE_AGENT_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(NODE_AGENT_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@if ! docker images $(GARDENLET_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(GARDENLET_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@if ! docker images $(EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY) | awk '{ print $$2 }' | grep -q -F $(EFFECTIVE_VERSION); then echo "$(EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY) version $(EFFECTIVE_VERSION) is not yet built. Please run 'make docker-images'"; false; fi
@docker push $(APISERVER_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION)
Expand All @@ -119,6 +122,8 @@ docker-push:
@if [[ "$(PUSH_LATEST_TAG)" == "true" ]]; then docker push $(ADMISSION_IMAGE_REPOSITORY):latest; fi
@docker push $(RESOURCE_MANAGER_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION)
@if [[ "$(PUSH_LATEST_TAG)" == "true" ]]; then docker push $(RESOURCE_MANAGER_IMAGE_REPOSITORY):latest; fi
@docker push $(NODE_AGENT_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION)
@if [[ "$(PUSH_LATEST_TAG)" == "true" ]]; then docker push $(NODE_AGENT_IMAGE_REPOSITORY):latest; fi
@docker push $(GARDENLET_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION)
@if [[ "$(PUSH_LATEST_TAG)" == "true" ]]; then docker push $(GARDENLET_IMAGE_REPOSITORY):latest; fi
@docker push $(EXTENSION_PROVIDER_LOCAL_IMAGE_REPOSITORY):$(EFFECTIVE_VERSION)
Expand Down
226 changes: 226 additions & 0 deletions cmd/gardener-node-agent/app/app.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
// Copyright 2023 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package app

import (
"context"
"fmt"
"net"
"net/http"
"os"
goruntime "runtime"
"strconv"
"time"

"github.com/go-logr/logr"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/client-go/rest"
clientcmdlatest "k8s.io/client-go/tools/clientcmd/api/latest"
clientcmdv1 "k8s.io/client-go/tools/clientcmd/api/v1"
"k8s.io/component-base/version"
"k8s.io/component-base/version/verflag"
"k8s.io/klog/v2"
"k8s.io/utils/pointer"
"sigs.k8s.io/controller-runtime/pkg/cache"
"sigs.k8s.io/controller-runtime/pkg/client"
controllerconfig "sigs.k8s.io/controller-runtime/pkg/config"
"sigs.k8s.io/controller-runtime/pkg/healthz"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/manager"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"

resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/controllerutils/routes"
"github.com/gardener/gardener/pkg/features"
gardenerhealthz "github.com/gardener/gardener/pkg/healthz"
"github.com/gardener/gardener/pkg/logger"
"github.com/gardener/gardener/pkg/nodeagent/apis/config"
nodeagentv1alpha1 "github.com/gardener/gardener/pkg/nodeagent/apis/config/v1alpha1"
"github.com/gardener/gardener/pkg/nodeagent/controller"
kubernetesutils "github.com/gardener/gardener/pkg/utils/kubernetes"
)

// Name is a const for the name of this component.
const Name = "gardener-node-agent"

// NewCommand creates a new cobra.Command for running gardener-node-agent.
func NewCommand() *cobra.Command {
opts := &options{}

cmd := &cobra.Command{
Use: Name,
Short: "Launch the " + Name,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
verflag.PrintAndExitIfRequested()

if err := opts.complete(); err != nil {
return err
}
if err := opts.validate(); err != nil {
return err
}

log, err := logger.NewZapLogger(opts.config.LogLevel, opts.config.LogFormat)
if err != nil {
return fmt.Errorf("error instantiating zap logger: %w", err)
}

logf.SetLogger(log)
klog.SetLogger(log)

log.Info("Starting "+Name, "version", version.Get())
cmd.Flags().VisitAll(func(flag *pflag.Flag) {
log.Info(fmt.Sprintf("FLAG: --%s=%s", flag.Name, flag.Value)) //nolint:logcheck
})

// don't output usage on further errors raised during execution
cmd.SilenceUsage = true
// further errors will be logged properly, don't duplicate
cmd.SilenceErrors = true

return run(cmd.Context(), log, opts.config)
},
}

flags := cmd.Flags()
verflag.AddFlags(flags)
opts.addFlags(flags)

return cmd
}

func run(ctx context.Context, log logr.Logger, cfg *config.NodeAgentConfiguration) error {
log.Info("Feature Gates", "featureGates", features.DefaultFeatureGate)

log.Info("Getting rest config")
if kubeconfig := os.Getenv("KUBECONFIG"); kubeconfig != "" {
cfg.ClientConnection.Kubeconfig = kubeconfig
}
if cfg.ClientConnection.Kubeconfig == "" {
return fmt.Errorf("must specify path to a kubeconfig (either via \"KUBECONFIG\" environment variable of via .clientConnection.kubeconfig in component config)")
}

restConfig, err := kubernetes.RESTConfigFromClientConnectionConfiguration(&cfg.ClientConnection, nil, kubernetes.AuthTokenFile)
if err != nil {
return err
}

if restConfig.BearerTokenFile == nodeagentv1alpha1.BootstrapTokenFilePath {
log.Info("Kubeconfig points to the bootstrap token file")
if err := fetchAccessTokenViaBootstrapToken(ctx, log, restConfig, cfg); err != nil {
return fmt.Errorf("failed fetching access token via bootstrap token: %w", err)
}
}

var extraHandlers map[string]http.Handler
if cfg.Debugging != nil && cfg.Debugging.EnableProfiling {
extraHandlers = routes.ProfilingHandlers
if cfg.Debugging.EnableContentionProfiling {
goruntime.SetBlockProfileRate(1)
}
}

log.Info("Setting up manager")
mgr, err := manager.New(restConfig, manager.Options{
Logger: log,
Scheme: kubernetes.SeedScheme,
GracefulShutdownTimeout: pointer.Duration(5 * time.Second),

HealthProbeBindAddress: net.JoinHostPort(cfg.Server.HealthProbes.BindAddress, strconv.Itoa(cfg.Server.HealthProbes.Port)),
Metrics: metricsserver.Options{
BindAddress: net.JoinHostPort(cfg.Server.Metrics.BindAddress, strconv.Itoa(cfg.Server.Metrics.Port)),
ExtraHandlers: extraHandlers,
},

Cache: cache.Options{
ByObject: map[client.Object]cache.ByObject{
&corev1.Secret{}: {
Namespaces: map[string]cache.Config{metav1.NamespaceSystem: {}},
},
},
},
LeaderElection: false,
Controller: controllerconfig.Controller{
RecoverPanic: pointer.Bool(true),
},
})
if err != nil {
return err
}

log.Info("Setting up health check endpoints")
if err := mgr.AddHealthzCheck("ping", healthz.Ping); err != nil {
return err
}
if err := mgr.AddReadyzCheck("informer-sync", gardenerhealthz.NewCacheSyncHealthz(mgr.GetCache())); err != nil {
return err
}

log.Info("Adding controllers to manager")
if err := controller.AddToManager(mgr, cfg); err != nil {
return fmt.Errorf("failed adding controllers to manager: %w", err)
}

log.Info("Starting manager")
return mgr.Start(ctx)
}

func fetchAccessTokenViaBootstrapToken(ctx context.Context, log logr.Logger, restConfig *rest.Config, cfg *config.NodeAgentConfiguration) error {
c, err := client.New(restConfig, client.Options{})
if err != nil {
return fmt.Errorf("unable to create client with bootstrap token: %w", err)
}

secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: cfg.AccessTokenSecretName, Namespace: metav1.NamespaceSystem}}
log.Info("Fetching access token secret", "secret", client.ObjectKeyFromObject(secret))
if err := c.Get(ctx, client.ObjectKeyFromObject(secret), secret); err != nil {
return fmt.Errorf("failed fetching access token from API server: %w", err)
}

token := secret.Data[resourcesv1alpha1.DataKeyToken]
if len(token) == 0 {
return fmt.Errorf("secret key %q does not exist or empty", resourcesv1alpha1.DataKeyToken)
}

restConfig.BearerTokenFile = nodeagentv1alpha1.TokenFilePath
kubeconfigRaw, err := runtime.Encode(clientcmdlatest.Codec, kubernetesutils.NewKubeconfig(
Name,
clientcmdv1.Cluster{Server: restConfig.Host, CertificateAuthorityData: restConfig.CAData},
clientcmdv1.AuthInfo{TokenFile: nodeagentv1alpha1.TokenFilePath},
))
if err != nil {
return fmt.Errorf("failed encoding kubeconfig: %w", err)
}

log.Info("Writing downloaded access token to disk", "path", nodeagentv1alpha1.TokenFilePath)
if err := os.WriteFile(nodeagentv1alpha1.TokenFilePath, token, 0600); err != nil {
return fmt.Errorf("unable to write access token to %s: %w", nodeagentv1alpha1.TokenFilePath, err)
}
log.Info("Token written to disk")

log.Info("Overwriting kubeconfig on disk to no longer use bootstrap token file", "path", cfg.ClientConnection.Kubeconfig)
if err := os.WriteFile(cfg.ClientConnection.Kubeconfig, kubeconfigRaw, 0600); err != nil {
return fmt.Errorf("unable to write kubeconfig to %s: %w", cfg.ClientConnection.Kubeconfig, err)
}
log.Info("Kubeconfig written to disk")

return nil
}
78 changes: 78 additions & 0 deletions cmd/gardener-node-agent/app/options.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// Copyright 2023 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package app

import (
"fmt"
"os"

"github.com/spf13/pflag"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/serializer"
utilruntime "k8s.io/apimachinery/pkg/util/runtime"

"github.com/gardener/gardener/pkg/features"
"github.com/gardener/gardener/pkg/nodeagent/apis/config"
nodeagentv1alpha1 "github.com/gardener/gardener/pkg/nodeagent/apis/config/v1alpha1"
nodeagentvalidation "github.com/gardener/gardener/pkg/nodeagent/apis/config/validation"
)

var configDecoder runtime.Decoder

func init() {
configScheme := runtime.NewScheme()
schemeBuilder := runtime.NewSchemeBuilder(
config.AddToScheme,
nodeagentv1alpha1.AddToScheme,
)
utilruntime.Must(schemeBuilder.AddToScheme(configScheme))
configDecoder = serializer.NewCodecFactory(configScheme).UniversalDecoder()
}

type options struct {
configFile string
config *config.NodeAgentConfiguration
}

func (o *options) addFlags(fs *pflag.FlagSet) {
fs.StringVar(&o.configFile, "config", o.configFile, "Path to configuration file.")
}

func (o *options) complete() error {
if len(o.configFile) == 0 {
return fmt.Errorf("missing config file")
}

data, err := os.ReadFile(o.configFile)
if err != nil {
return fmt.Errorf("error reading config file: %w", err)
}

o.config = &config.NodeAgentConfiguration{}
if err = runtime.DecodeInto(configDecoder, data, o.config); err != nil {
return fmt.Errorf("error decoding config: %w", err)
}

// Set feature gates immediately after decoding the config.
// Feature gates might influence the next steps, e.g., validating the config.
return features.DefaultFeatureGate.SetFromMap(o.config.FeatureGates)
}

func (o *options) validate() error {
if errs := nodeagentvalidation.ValidateNodeAgentConfiguration(o.config); len(errs) > 0 {
return errs.ToAggregate()
}
return nil
}
36 changes: 36 additions & 0 deletions cmd/gardener-node-agent/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// Copyright 2023 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
"fmt"
"os"

"sigs.k8s.io/controller-runtime/pkg/manager/signals"

"github.com/gardener/gardener/cmd/gardener-node-agent/app"
"github.com/gardener/gardener/cmd/utils"
"github.com/gardener/gardener/pkg/nodeagent/features"
)

func main() {
utils.DeduplicateWarnings()
features.RegisterFeatureGates()

if err := app.NewCommand().ExecuteContext(signals.SetupSignalHandler()); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
Loading

0 comments on commit b9ecd0b

Please sign in to comment.