forked from kubernetes-sigs/dra-driver-nvidia-gpu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomputedomain.go
More file actions
410 lines (344 loc) · 11.6 KB
/
computedomain.go
File metadata and controls
410 lines (344 loc) · 11.6 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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
/*
* Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
*
* 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 (
"context"
"fmt"
"os"
"path/filepath"
"sync"
"time"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/tools/cache"
"k8s.io/klog/v2"
"k8s.io/utils/ptr"
cdiapi "tags.cncf.io/container-device-interface/pkg/cdi"
cdispec "tags.cncf.io/container-device-interface/specs-go"
nvapi "github.com/NVIDIA/k8s-dra-driver-gpu/api/nvidia.com/resource/v1beta1"
nvinformers "github.com/NVIDIA/k8s-dra-driver-gpu/pkg/nvidia.com/informers/externalversions"
)
const (
computeDomainLabelKey = "resource.nvidia.com/computeDomain"
informerResyncPeriod = 10 * time.Minute
cleanupInterval = 10 * time.Minute
ComputeDomainDaemonConfigFilesDirName = "domains"
ComputeDomainDaemonConfigTemplatePath = "/templates/compute-domain-daemon-config.tmpl.cfg"
)
type ComputeDomainManager struct {
config *Config
waitGroup sync.WaitGroup
cancelContext context.CancelFunc
factory nvinformers.SharedInformerFactory
informer cache.SharedIndexInformer
configFilesRoot string
cliqueID string
}
type ComputeDomainDaemonSettings struct {
manager *ComputeDomainManager
domain string
rootDir string
configTmplPath string
nodesConfigPath string
}
func NewComputeDomainManager(config *Config, cliqueID string) *ComputeDomainManager {
factory := nvinformers.NewSharedInformerFactory(config.clientsets.Nvidia, informerResyncPeriod)
informer := factory.Resource().V1beta1().ComputeDomains().Informer()
configFilesRoot := filepath.Join(config.DriverPluginPath(), ComputeDomainDaemonConfigFilesDirName)
m := &ComputeDomainManager{
config: config,
factory: factory,
informer: informer,
configFilesRoot: configFilesRoot,
cliqueID: cliqueID,
}
return m
}
func (m *ComputeDomainManager) Start(ctx context.Context) (rerr error) {
ctx, cancel := context.WithCancel(ctx)
m.cancelContext = cancel
defer func() {
if rerr != nil {
if err := m.Stop(); err != nil {
klog.Errorf("Error stopping ComputeDomainManager: %v", err)
}
}
}()
err := m.informer.AddIndexers(cache.Indexers{
"computeDomainUID": uidIndexer[*nvapi.ComputeDomain],
})
if err != nil {
return fmt.Errorf("error adding indexer for UIDs: %w", err)
}
m.waitGroup.Add(1)
go func() {
defer m.waitGroup.Done()
m.factory.Start(ctx.Done())
}()
m.waitGroup.Add(1)
go func() {
defer m.waitGroup.Done()
m.periodicCleanup(ctx)
}()
if !cache.WaitForCacheSync(ctx.Done(), m.informer.HasSynced) {
return fmt.Errorf("informer cache sync for ComputeDomains failed")
}
return nil
}
func (m *ComputeDomainManager) Stop() error {
if m.cancelContext != nil {
m.cancelContext()
}
m.waitGroup.Wait()
return nil
}
func (m *ComputeDomainManager) NewSettings(domain string) *ComputeDomainDaemonSettings {
return &ComputeDomainDaemonSettings{
manager: m,
domain: domain,
rootDir: fmt.Sprintf("%s/%s", m.configFilesRoot, domain),
configTmplPath: fmt.Sprintf("%s/%s/%s", m.configFilesRoot, domain, "config.tmpl.cfg"),
nodesConfigPath: fmt.Sprintf("%s/%s/%s", m.configFilesRoot, domain, "nodes_config.cfg"),
}
}
func (m *ComputeDomainManager) GetComputeDomainChannelContainerEdits(devRoot string, info *nvcapDeviceInfo) *cdiapi.ContainerEdits {
return &cdiapi.ContainerEdits{
ContainerEdits: &cdispec.ContainerEdits{
DeviceNodes: []*cdispec.DeviceNode{
{
Path: info.path,
Type: "c",
FileMode: ptr.To(os.FileMode(info.mode)),
Major: int64(info.major),
Minor: int64(info.minor),
},
},
},
}
}
func (s *ComputeDomainDaemonSettings) GetDomain() string {
return s.domain
}
func (s *ComputeDomainDaemonSettings) GetCDIContainerEdits(ctx context.Context, devRoot string, info *nvcapDeviceInfo) (*cdiapi.ContainerEdits, error) {
cd, err := s.manager.GetComputeDomain(ctx, s.domain)
if err != nil {
return nil, fmt.Errorf("error getting compute domain: %w", err)
}
if cd == nil {
return nil, fmt.Errorf("compute domain not found: %s", s.domain)
}
edits := &cdiapi.ContainerEdits{
ContainerEdits: &cdispec.ContainerEdits{
Env: []string{
fmt.Sprintf("CLIQUE_ID=%s", s.manager.cliqueID),
fmt.Sprintf("COMPUTE_DOMAIN_UUID=%s", cd.UID),
fmt.Sprintf("COMPUTE_DOMAIN_NAME=%s", cd.Name),
fmt.Sprintf("COMPUTE_DOMAIN_NAMESPACE=%s", cd.Namespace),
},
Mounts: []*cdispec.Mount{
{
ContainerPath: "/etc/nvidia-imex",
HostPath: s.rootDir,
Options: []string{"rw", "nosuid", "nodev", "bind"},
},
},
DeviceNodes: []*cdispec.DeviceNode{
{
Path: info.path,
Type: "c",
FileMode: ptr.To(os.FileMode(info.mode)),
Major: int64(info.major),
Minor: int64(info.minor),
},
},
},
}
return edits, nil
}
func (s *ComputeDomainDaemonSettings) Prepare(ctx context.Context) error {
if err := os.MkdirAll(s.rootDir, 0755); err != nil {
return fmt.Errorf("error creating directory %v: %w", s.rootDir, err)
}
if err := s.WriteConfigFile(ctx); err != nil {
return fmt.Errorf("error writing config file %v: %w", s.configTmplPath, err)
}
return nil
}
func (s *ComputeDomainDaemonSettings) Unprepare(ctx context.Context) error {
// TODO: Only actually remove this directory once the ComputeDomain has
// been deleted. There is a (rare) chance when a pod gets force deleted
// and a new pod associated with the same compute domain gets started
// that deleting this here will occur *after* the creation from the new
// pod, rendering this directory invalid when trying to be used by the
// new pod. For now, just wait for the cleanup loop to take care of
// this, but in the future let's do this cleanup on ComputeDomain
// deletion (in addition to the cleanup loop).
// err := os.RemoveAll(s.rootDir); err != nil {
// return fmt.Errorf("error removing directory %v: %w", s.rootDir, err)
//}
return nil
}
func (s *ComputeDomainDaemonSettings) WriteConfigFile(ctx context.Context) error {
configBytes, err := os.ReadFile(ComputeDomainDaemonConfigTemplatePath)
if err != nil {
return fmt.Errorf("error reading template file: %w", err)
}
if err := os.WriteFile(s.configTmplPath, configBytes, 0644); err != nil {
return fmt.Errorf("error writing config file %v: %w", s.configTmplPath, err)
}
return nil
}
func (m *ComputeDomainManager) AssertComputeDomainReady(ctx context.Context, cdUID string) error {
cd, err := m.GetComputeDomain(ctx, cdUID)
if err != nil {
return fmt.Errorf("error getting ComputeDomain: %w", err)
}
if cd == nil {
return fmt.Errorf("ComputeDomain not found: %s", cdUID)
}
// Check if the current node is ready in the ComputeDomain
if !m.isCurrentNodeReady(cd) {
return fmt.Errorf("current node not ready in ComputeDomain")
}
return nil
}
// isCurrentNodeReady checks if the current node is marked as ready in the ComputeDomain.
func (m *ComputeDomainManager) isCurrentNodeReady(cd *nvapi.ComputeDomain) bool {
for _, node := range cd.Status.Nodes {
if node.Name == m.config.flags.nodeName {
return node.Status == nvapi.ComputeDomainStatusReady
}
}
return false
}
func (m *ComputeDomainManager) AssertComputeDomainNamespace(ctx context.Context, claimNamespace, cdUID string) error {
cd, err := m.GetComputeDomain(ctx, cdUID)
if err != nil {
return fmt.Errorf("error getting ComputeDomain: %w", err)
}
if cd == nil {
return fmt.Errorf("ComputeDomain not found: %s", cdUID)
}
if cd.Namespace != claimNamespace {
return fmt.Errorf("the ResourceClaim's namespace is different than the ComputeDomain's namespace")
}
return nil
}
func (m *ComputeDomainManager) AddNodeLabel(ctx context.Context, cdUID string) error {
node, err := m.config.clientsets.Core.CoreV1().Nodes().Get(ctx, m.config.flags.nodeName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("error retrieving Node: %w", err)
}
currentValue, exists := node.Labels[computeDomainLabelKey]
if exists && currentValue != cdUID {
return fmt.Errorf("label already exists for a different ComputeDomain")
}
if exists && currentValue == cdUID {
return nil
}
newNode := node.DeepCopy()
if newNode.Labels == nil {
newNode.Labels = make(map[string]string)
}
newNode.Labels[computeDomainLabelKey] = cdUID
if _, err = m.config.clientsets.Core.CoreV1().Nodes().Update(ctx, newNode, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("error updating Node with label: %w", err)
}
return nil
}
// RemoveNodeLabel() attempts removal and returns no error if the label was
// removed or didn't exist in the first place.
func (m *ComputeDomainManager) RemoveNodeLabel(ctx context.Context, cdUID string) error {
node, err := m.config.clientsets.Core.CoreV1().Nodes().Get(ctx, m.config.flags.nodeName, metav1.GetOptions{})
if err != nil {
return fmt.Errorf("error retrieving Node: %w", err)
}
if _, exists := node.Labels[computeDomainLabelKey]; !exists {
return nil
}
if node.Labels[computeDomainLabelKey] != cdUID {
return nil
}
newNode := node.DeepCopy()
delete(newNode.Labels, computeDomainLabelKey)
if _, err := m.config.clientsets.Core.CoreV1().Nodes().Update(ctx, newNode, metav1.UpdateOptions{}); err != nil {
return fmt.Errorf("error updating Node to remove label: %w", err)
}
return nil
}
func (m *ComputeDomainManager) GetComputeDomain(ctx context.Context, cdUID string) (*nvapi.ComputeDomain, error) {
cds, err := m.informer.GetIndexer().ByIndex("computeDomainUID", cdUID)
if err != nil {
return nil, fmt.Errorf("error retrieving ComputeDomain by UID: %w", err)
}
if len(cds) == 0 {
return nil, nil
}
if len(cds) != 1 {
return nil, fmt.Errorf("multiple ComputeDomains with the same UID")
}
cd, ok := cds[0].(*nvapi.ComputeDomain)
if !ok {
return nil, fmt.Errorf("failed to cast to ComputeDomain")
}
return cd, nil
}
func (m *ComputeDomainManager) periodicCleanup(ctx context.Context) {
ticker := time.NewTicker(cleanupInterval)
defer ticker.Stop()
for {
select {
case <-ticker.C:
klog.V(6).Infof("Running periodic cleanup to remove stale ComputeDomain artifacts")
_, err := os.Stat(m.configFilesRoot)
if os.IsNotExist(err) {
continue
}
if err != nil {
klog.Errorf("Error checking for existence of directory '%s': %v", m.configFilesRoot, err)
continue
}
entries, err := os.ReadDir(m.configFilesRoot)
if err != nil {
klog.Errorf("Error reading entries under directory '%s': %v", m.configFilesRoot, err)
continue
}
for _, e := range entries {
if !e.IsDir() {
continue
}
// Convention: per-CD directory with CD UID as basename
uid := e.Name()
path := filepath.Join(m.configFilesRoot, e.Name())
computeDomain, err := m.GetComputeDomain(ctx, uid)
if err != nil {
klog.Errorf("Error getting ComputeDomain: %v", err)
continue
}
// CD still exists, do not clean up
if computeDomain != nil {
continue
}
klog.V(6).Infof("Stale directory found for ComputeDomain '%s', running cleanup", uid)
if err := os.RemoveAll(path); err != nil {
klog.Errorf("Error removing artifacts directory for ComputeDomain '%s': %v", uid, err)
continue
}
}
case <-ctx.Done():
return
}
}
}