-
Notifications
You must be signed in to change notification settings - Fork 462
/
app.go
323 lines (280 loc) · 11.8 KB
/
app.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
// 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"
"io/fs"
"net"
"net/http"
"os"
"path/filepath"
goruntime "runtime"
"strconv"
"time"
"github.com/go-logr/logr"
"github.com/spf13/afero"
"github.com/spf13/cobra"
coordinationv1 "k8s.io/api/coordination/v1"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/client-go/rest"
"k8s.io/component-base/version/verflag"
"k8s.io/utils/ptr"
"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"
"sigs.k8s.io/controller-runtime/pkg/manager"
metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server"
"github.com/gardener/gardener/cmd/gardener-node-agent/app/bootstrappers"
"github.com/gardener/gardener/cmd/utils"
resourcesv1alpha1 "github.com/gardener/gardener/pkg/apis/resources/v1alpha1"
"github.com/gardener/gardener/pkg/client/kubernetes"
"github.com/gardener/gardener/pkg/component/extensions/operatingsystemconfig/downloader"
"github.com/gardener/gardener/pkg/controllerutils"
"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/nodeagent"
"github.com/gardener/gardener/pkg/nodeagent/apis/config"
nodeagentv1alpha1 "github.com/gardener/gardener/pkg/nodeagent/apis/config/v1alpha1"
"github.com/gardener/gardener/pkg/nodeagent/bootstrap"
"github.com/gardener/gardener/pkg/nodeagent/controller"
"github.com/gardener/gardener/pkg/nodeagent/dbus"
gardenerutils "github.com/gardener/gardener/pkg/utils/gardener"
)
// 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, _ []string) error {
log, err := utils.InitRun(cmd, opts, Name)
if err != nil {
return err
}
ctx, cancel := context.WithCancel(cmd.Context())
return run(ctx, cancel, log, opts.config)
},
}
flags := cmd.Flags()
verflag.AddFlags(flags)
opts.addFlags(flags)
cmd.AddCommand(getBootstrapCommand(opts))
return cmd
}
func getBootstrapCommand(opts *options) *cobra.Command {
bootstrapCmd := &cobra.Command{
Use: "bootstrap",
Short: "Bootstrap the " + Name,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, _ []string) error {
log, err := utils.InitRun(cmd, opts, "gardener-node-init")
if err != nil {
return err
}
return bootstrap.Bootstrap(cmd.Context(), log, afero.Afero{Fs: afero.NewOsFs()}, dbus.New(log), opts.config.Bootstrap)
},
}
flags := bootstrapCmd.Flags()
verflag.AddFlags(flags)
opts.addFlags(flags)
return bootstrapCmd
}
func run(ctx context.Context, cancel context.CancelFunc, log logr.Logger, cfg *config.NodeAgentConfiguration) error {
log.Info("Feature Gates", "featureGates", features.DefaultFeatureGate)
if kubeconfig := os.Getenv("KUBECONFIG"); kubeconfig != "" {
cfg.ClientConnection.Kubeconfig = kubeconfig
}
log.Info("Getting rest config")
var (
restConfig *rest.Config
err error
)
if len(cfg.ClientConnection.Kubeconfig) > 0 {
restConfig, err = kubernetes.RESTConfigFromClientConnectionConfiguration(&cfg.ClientConnection, nil, kubernetes.AuthTokenFile)
if err != nil {
return fmt.Errorf("failed getting REST config from client connection configuration: %w", err)
}
} else {
var mustFetchAccessToken bool
restConfig, mustFetchAccessToken, err = getRESTConfig(log, cfg)
if err != nil {
return fmt.Errorf("failed getting REST config: %w", err)
}
if mustFetchAccessToken {
log.Info("Fetching access token")
if err := fetchAccessToken(ctx, log, restConfig); err != nil {
return fmt.Errorf("failed fetching access 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("Fetching hostname")
hostName, err := nodeagent.GetHostName()
if err != nil {
return fmt.Errorf("failed fetching hostname: %w", err)
}
log.Info("Fetched hostname", "hostname", hostName)
log.Info("Fetching name of node (if already registered)")
nodeName, err := fetchNodeName(ctx, restConfig, hostName)
if err != nil {
return fmt.Errorf("failed fetching name of node: %w", err)
}
leaseCacheOptions := cache.ByObject{Namespaces: map[string]cache.Config{metav1.NamespaceSystem: {}}}
if nodeName != "" {
log.Info("Node already registered, found name", "nodeName", nodeName)
leaseCacheOptions.Field = fields.SelectorFromSet(fields.Set{metav1.ObjectNameField: gardenerutils.NodeAgentLeaseName(nodeName)})
}
log.Info("Setting up manager")
mgr, err := manager.New(restConfig, manager.Options{
Logger: log,
Scheme: kubernetes.SeedScheme,
GracefulShutdownTimeout: ptr.To(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: {}},
Field: fields.SelectorFromSet(fields.Set{metav1.ObjectNameField: cfg.Controllers.OperatingSystemConfig.SecretName}),
},
&coordinationv1.Lease{}: leaseCacheOptions,
}},
LeaderElection: false,
Controller: controllerconfig.Controller{
RecoverPanic: ptr.To(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
}
var (
fs = afero.Afero{Fs: afero.NewOsFs()}
dbus = dbus.New(log)
)
log.Info("Creating directory for temporary files", "path", nodeagentv1alpha1.TempDir)
if err := fs.MkdirAll(nodeagentv1alpha1.TempDir, os.ModeDir); err != nil {
return fmt.Errorf("unable to create directory for temporary files %q: %w", nodeagentv1alpha1.TempDir, err)
}
log.Info("Adding runnables to manager")
if err := mgr.Add(&controllerutils.ControlledRunner{
Manager: mgr,
BootstrapRunnables: []manager.Runnable{
&bootstrappers.KubeletBootstrapKubeconfig{Log: log.WithName("kubelet-bootstrap-kubeconfig-creator"), FS: fs, APIServerConfig: cfg.APIServer},
},
ActualRunnables: []manager.Runnable{
manager.RunnableFunc(func(ctx context.Context) error { return controller.AddToManager(ctx, cancel, mgr, cfg, hostName) }),
&bootstrappers.CloudConfigDownloaderCleaner{Log: log.WithName("legacy-cloud-config-downloader-cleaner"), FS: fs, DBus: dbus},
},
}); err != nil {
return fmt.Errorf("failed adding runnables to manager: %w", err)
}
log.Info("Starting manager")
return mgr.Start(ctx)
}
func getRESTConfig(log logr.Logger, cfg *config.NodeAgentConfiguration) (*rest.Config, bool, error) {
restConfig := &rest.Config{
Burst: int(cfg.ClientConnection.Burst),
QPS: cfg.ClientConnection.QPS,
ContentConfig: rest.ContentConfig{
AcceptContentTypes: cfg.ClientConnection.AcceptContentTypes,
ContentType: cfg.ClientConnection.ContentType,
},
Host: cfg.APIServer.Server,
TLSClientConfig: rest.TLSClientConfig{CAData: cfg.APIServer.CABundle},
BearerTokenFile: nodeagentv1alpha1.TokenFilePath,
}
if _, err := os.Stat(restConfig.BearerTokenFile); err != nil && !os.IsNotExist(err) {
return nil, false, fmt.Errorf("failed checking whether token file %q exists: %w", restConfig.BearerTokenFile, err)
} else if err == nil {
log.Info("Token file already exists, nothing to be done", "path", restConfig.BearerTokenFile)
return restConfig, false, nil
}
if _, err := os.Stat(downloader.PathCredentialsToken); err != nil && !os.IsNotExist(err) {
return nil, false, fmt.Errorf("failed checking whether cloud-config-downloader token file %q exists: %w", downloader.PathCredentialsToken, err)
} else if err == nil {
log.Info("Token file does not exist, but legacy cloud-config-downloader token file does - using it", "path", downloader.PathCredentialsToken)
restConfig.BearerTokenFile = downloader.PathCredentialsToken
return restConfig, true, nil
}
if _, err := os.Stat(nodeagentv1alpha1.BootstrapTokenFilePath); err != nil && !os.IsNotExist(err) {
return nil, false, fmt.Errorf("failed checking whether bootstrap token file %q exists: %w", nodeagentv1alpha1.BootstrapTokenFilePath, err)
} else if err == nil {
log.Info("Token file does not exist, but bootstrap token file does - using it", "path", nodeagentv1alpha1.BootstrapTokenFilePath)
restConfig.BearerTokenFile = nodeagentv1alpha1.BootstrapTokenFilePath
return restConfig, true, nil
}
return nil, false, fmt.Errorf("unable to construct REST config (neither token file %q nor bootstrap token file %q exist)", nodeagentv1alpha1.TokenFilePath, nodeagentv1alpha1.BootstrapTokenFilePath)
}
func fetchAccessToken(ctx context.Context, log logr.Logger, restConfig *rest.Config) 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: nodeagentv1alpha1.AccessSecretName, Namespace: metav1.NamespaceSystem}}
log.Info("Reading 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)
}
log.Info("Writing downloaded access token to disk", "path", nodeagentv1alpha1.TokenFilePath)
if err := os.MkdirAll(filepath.Dir(nodeagentv1alpha1.TokenFilePath), fs.ModeDir); err != nil {
return fmt.Errorf("unable to create directory %q: %w", filepath.Dir(nodeagentv1alpha1.TokenFilePath), err)
}
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")
restConfig.BearerTokenFile = nodeagentv1alpha1.TokenFilePath
return nil
}
func fetchNodeName(ctx context.Context, restConfig *rest.Config, hostName string) (string, error) {
c, err := client.New(restConfig, client.Options{})
if err != nil {
return "", fmt.Errorf("unable to create client: %w", err)
}
node, err := nodeagent.FetchNodeByHostName(ctx, c, hostName)
if err != nil {
return "", err
}
if node == nil {
return "", nil
}
return node.Name, nil
}