-
Notifications
You must be signed in to change notification settings - Fork 170
Expand file tree
/
Copy pathmain.go
More file actions
319 lines (278 loc) · 9.81 KB
/
Copy pathmain.go
File metadata and controls
319 lines (278 loc) · 9.81 KB
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
/*
Copyright The Kubernetes Authors
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
https://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 (
"context"
"errors"
"fmt"
"os"
"os/signal"
"path/filepath"
"syscall"
"github.com/urfave/cli/v2"
"k8s.io/component-base/logs"
"k8s.io/dynamic-resource-allocation/kubeletplugin"
"k8s.io/klog/v2"
"sigs.k8s.io/nvidia-dra-driver-gpu/internal/common"
"sigs.k8s.io/nvidia-dra-driver-gpu/internal/info"
"sigs.k8s.io/nvidia-dra-driver-gpu/pkg/featuregates"
pkgflags "sigs.k8s.io/nvidia-dra-driver-gpu/pkg/flags"
)
const (
DriverName = "gpu.nvidia.com"
DriverPluginCheckpointFileBasename = "checkpoint.json"
)
type Flags struct {
kubeClientConfig pkgflags.KubeClientConfig
nodeName string
namespace string
cdiRoot string
containerDriverRoot string
hostDriverRoot string
nvidiaCDIHookPath string
imageName string
kubeletRegistrarDirectoryPath string
kubeletPluginsDirectoryPath string
healthcheckPort int
klogVerbosity int
additionalXidsToIgnore string
}
type Config struct {
flags *Flags
clientsets pkgflags.ClientSets
}
func (c Config) DriverPluginPath() string {
return filepath.Join(c.flags.kubeletPluginsDirectoryPath, DriverName)
}
func main() {
if err := common.MaskNvidiaDriverParams(); err != nil {
fmt.Fprintf(os.Stderr, "Error masking NVIDIA driver params: %v\n", err)
}
if len(os.Args) > 1 && os.Args[1] == "prestart" {
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer cancel()
if err := runPrestart(ctx); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
os.Exit(0)
}
if err := newApp().Run(os.Args); err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
}
func newApp() *cli.App {
loggingConfig := pkgflags.NewLoggingConfig()
featureGateConfig := pkgflags.NewFeatureGateConfig()
flags := &Flags{}
cliFlags := []cli.Flag{
&cli.StringFlag{
Name: "node-name",
Usage: "The name of the node to be worked on.",
Required: true,
Destination: &flags.nodeName,
EnvVars: []string{"NODE_NAME"},
},
&cli.StringFlag{
Name: "namespace",
Usage: "The namespace used for the custom resources.",
Value: "default",
Destination: &flags.namespace,
EnvVars: []string{"NAMESPACE"},
},
&cli.StringFlag{
Name: "cdi-root",
Usage: "Absolute path to the directory where CDI files will be generated.",
Value: "/etc/cdi",
Destination: &flags.cdiRoot,
EnvVars: []string{"CDI_ROOT"},
},
&cli.StringFlag{
Name: "nvidia-driver-root",
Aliases: []string{"host_driver-root"},
Value: "/",
Usage: "the root path for the NVIDIA driver installation on the host (typical values are '/' or '/run/nvidia/driver')",
Destination: &flags.hostDriverRoot,
EnvVars: []string{"NVIDIA_DRIVER_ROOT", "HOST_DRIVER_ROOT"},
},
&cli.StringFlag{
Name: "container-driver-root",
Value: "/driver-root",
Usage: "the path where the NVIDIA driver root is mounted in the container; used for generating CDI specifications",
Destination: &flags.containerDriverRoot,
EnvVars: []string{"DRIVER_ROOT_CTR_PATH"},
},
&cli.StringFlag{
Name: "nvidia-cdi-hook-path",
Usage: "Absolute path to the nvidia-cdi-hook executable in the host file system. Used in the generated CDI specification.",
Destination: &flags.nvidiaCDIHookPath,
EnvVars: []string{"NVIDIA_CDI_HOOK_PATH"},
},
&cli.StringFlag{
Name: "image-name",
Usage: "The full image name to use for rendering templates.",
Required: true,
Destination: &flags.imageName,
EnvVars: []string{"IMAGE_NAME"},
},
&cli.StringFlag{
Name: "kubelet-registrar-directory-path",
Usage: "Absolute path to the directory where kubelet stores plugin registrations.",
Value: kubeletplugin.KubeletRegistryDir,
Destination: &flags.kubeletRegistrarDirectoryPath,
EnvVars: []string{"KUBELET_REGISTRAR_DIRECTORY_PATH"},
},
&cli.StringFlag{
Name: "kubelet-plugins-directory-path",
Usage: "Absolute path to the directory where kubelet stores plugin data.",
Value: kubeletplugin.KubeletPluginsDir,
Destination: &flags.kubeletPluginsDirectoryPath,
EnvVars: []string{"KUBELET_PLUGINS_DIRECTORY_PATH"},
},
&cli.IntFlag{
Name: "healthcheck-port",
Usage: "Port to start a gRPC healthcheck service. When positive, a literal port number. When zero, a random port is allocated. When negative, the healthcheck service is disabled.",
Value: -1,
Destination: &flags.healthcheckPort,
EnvVars: []string{"HEALTHCHECK_PORT"},
},
// TODO: change to StringSliceFlag.
&cli.StringFlag{
Name: "additional-xids-to-ignore",
Usage: "A comma-separated list of additional XIDs to ignore.",
Value: "",
Destination: &flags.additionalXidsToIgnore,
EnvVars: []string{"ADDITIONAL_XIDS_TO_IGNORE"},
},
}
cliFlags = append(cliFlags, flags.kubeClientConfig.Flags()...)
cliFlags = append(cliFlags, featureGateConfig.Flags()...)
cliFlags = append(cliFlags, loggingConfig.Flags()...)
app := &cli.App{
Name: "gpu-kubelet-plugin",
Usage: "gpu-kubelet-plugin implements a DRA driver plugin for NVIDIA GPUs.",
ArgsUsage: " ",
HideHelpCommand: true,
Flags: cliFlags,
Before: func(c *cli.Context) error {
if c.Args().Len() > 0 {
return fmt.Errorf("arguments not supported: %v", c.Args().Slice())
}
// `loggingConfig` must be applied before doing any logging
err := loggingConfig.Apply()
// Store klog's log verbosity setting in this program's config for
// later runtime inspection (it's otherwise not accessible anymore
// because we do not expose the raw `cliFlags`.
flags.klogVerbosity = int(loggingConfig.Config.Verbosity)
pkgflags.LogStartupConfig(flags, loggingConfig)
return err
},
Action: func(c *cli.Context) error {
if err := featuregates.ValidateFeatureGates(); err != nil {
return fmt.Errorf("feature gate validation failed: %w", err)
}
clientSets, err := flags.kubeClientConfig.NewClientSets()
if err != nil {
return fmt.Errorf("create client: %w", err)
}
config := &Config{
flags: flags,
clientsets: clientSets,
}
return RunPlugin(c.Context, config)
},
After: func(c *cli.Context) error {
// Runs after `Action` (regardless of success/error). In urfave cli
// v2, the final error reported will be from either Action, Before,
// or After (whichever is non-nil and last executed).
klog.Infof("shutdown")
logs.FlushLogs()
return nil
},
Version: info.GetVersionString(),
}
// We remove the -v alias for the version flag so as to not conflict with the -v flag used for klog.
f, ok := cli.VersionFlag.(*cli.BoolFlag)
if ok {
f.Aliases = nil
}
return app
}
// RunPlugin initializes and runs the GPU kubelet plugin.
func RunPlugin(ctx context.Context, config *Config) error {
common.StartDebugSignalHandlers()
// Create the plugin directory
err := os.MkdirAll(config.DriverPluginPath(), 0750)
if err != nil {
return err
}
// Setup nvidia-cdi-hook binary
if err := config.setNvidiaCDIHookPath(); err != nil {
return fmt.Errorf("error setting up nvidia-cdi-hook: %w", err)
}
// Initialize CDI root directory
info, err := os.Stat(config.flags.cdiRoot)
switch {
case err != nil && os.IsNotExist(err):
err := os.MkdirAll(config.flags.cdiRoot, 0750)
if err != nil {
return err
}
case err != nil:
return err
case !info.IsDir():
return fmt.Errorf("path for cdi file generation is not a directory: '%v'", config.flags.cdiRoot)
}
ctx, cancel := signal.NotifyContext(ctx, syscall.SIGHUP, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
defer cancel()
// Create and start the driver
driver, err := NewDriver(ctx, config)
if err != nil {
return fmt.Errorf("error creating driver: %w", err)
}
<-ctx.Done()
if err := ctx.Err(); err != nil && !errors.Is(err, context.Canceled) {
// A canceled context is the normal case here when the process receives
// a signal. Only log the error for more interesting cases.
klog.Errorf("error from context: %v", err)
}
err = driver.Shutdown()
if err != nil {
klog.Errorf("unable to cleanly shutdown driver: %v", err)
}
return nil
}
// change to config
// If 'f.nvidiaCDIHookPath' is already set (from the command line), do nothing.
// If 'f.nvidiaCDIHookPath' is empty, it copies the nvidia-cdi-hook binary from
// /usr/bin/nvidia-cdi-hook to DriverPluginPath and sets 'f.nvidiaCDIHookPath'
// to this path. The /usr/bin/nvidia-cdi-hook is present in the current
// container image because it is copied from the toolkit image into this
// container at build time.
func (c Config) setNvidiaCDIHookPath() error {
if c.flags.nvidiaCDIHookPath != "" {
return nil
}
sourcePath := "/usr/bin/nvidia-cdi-hook"
targetPath := filepath.Join(c.DriverPluginPath(), "nvidia-cdi-hook")
input, err := os.ReadFile(sourcePath)
if err != nil {
return fmt.Errorf("error reading nvidia-cdi-hook: %w", err)
}
if err := os.WriteFile(targetPath, input, 0755); err != nil {
return fmt.Errorf("error copying nvidia-cdi-hook: %w", err)
}
c.flags.nvidiaCDIHookPath = targetPath
return nil
}