-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathsharing.go
391 lines (334 loc) · 11.3 KB
/
sharing.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
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
/*
* Copyright (c) 2023, 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 (
"bytes"
"context"
"fmt"
"os"
"os/exec"
"strings"
"text/template"
"time"
appsv1 "k8s.io/api/apps/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/apimachinery/pkg/util/yaml"
"k8s.io/client-go/util/retry"
"k8s.io/klog/v2"
"k8s.io/mount-utils"
cdiapi "tags.cncf.io/container-device-interface/pkg/cdi"
cdispec "tags.cncf.io/container-device-interface/specs-go"
nascrd "github.com/NVIDIA/k8s-dra-driver/api/nvidia.com/resource/gpu/nas/v1alpha1"
)
const (
MpsRoot = DriverPluginPath + "/mps"
MpsControlDaemonTemplatePath = "/templates/mps-control-daemon.tmpl.yaml"
MpsControlDaemonNameFmt = "mps-control-daemon-%v" // Fill with ClaimUID
)
type TimeSlicingManager struct {
nvdevlib *deviceLib
}
type MpsManager struct {
config *Config
controlFilesRoot string
hostDriverRoot string
templatePath string
nvdevlib *deviceLib
}
type MpsControlDaemon struct {
nodeName string
namespace string
name string
rootDir string
pipeDir string
shmDir string
logDir string
claim *nascrd.ClaimInfo
devices *PreparedDevices
config *nascrd.MpsConfig
manager *MpsManager
}
type MpsControlDaemonTemplateData struct {
NodeName string
MpsControlDaemonNamespace string
MpsControlDaemonName string
CUDA_VISIBLE_DEVICES string //nolint:stylecheck
DefaultActiveThreadPercentage string
DefaultPinnedDeviceMemoryLimits map[string]string
NvidiaDriverRoot string
MpsShmDirectory string
MpsPipeDirectory string
MpsLogDirectory string
}
func NewTimeSlicingManager(deviceLib *deviceLib) *TimeSlicingManager {
return &TimeSlicingManager{
nvdevlib: deviceLib,
}
}
func (t *TimeSlicingManager) SetTimeSlice(devices *PreparedDevices, config *nascrd.TimeSlicingConfig) error {
if devices.Mig != nil {
return fmt.Errorf("setting a TimeSlice duration on MIG devices is unsupported")
}
timeSlice := nascrd.DefaultTimeSlice
if config != nil && config.TimeSlice != nil {
timeSlice = *config.TimeSlice
}
err := t.nvdevlib.setComputeMode(devices.UUIDs(), "DEFAULT")
if err != nil {
return fmt.Errorf("error setting compute mode: %w", err)
}
err = t.nvdevlib.setTimeSlice(devices.UUIDs(), timeSlice.Int())
if err != nil {
return fmt.Errorf("error setting time slice: %w", err)
}
return nil
}
func NewMpsManager(config *Config, deviceLib *deviceLib, controlFilesRoot, hostDriverRoot, templatePath string) *MpsManager {
return &MpsManager{
controlFilesRoot: controlFilesRoot,
hostDriverRoot: hostDriverRoot,
templatePath: templatePath,
config: config,
nvdevlib: deviceLib,
}
}
func (m *MpsManager) NewMpsControlDaemon(claim *nascrd.ClaimInfo, devices *PreparedDevices, config *nascrd.MpsConfig) *MpsControlDaemon {
return &MpsControlDaemon{
nodeName: m.config.nascr.Name,
namespace: m.config.nascr.Namespace,
name: fmt.Sprintf(MpsControlDaemonNameFmt, claim.UID),
claim: claim,
rootDir: fmt.Sprintf("%s/%s", m.controlFilesRoot, claim.UID),
pipeDir: fmt.Sprintf("%s/%s/%s", m.controlFilesRoot, claim.UID, "pipe"),
shmDir: fmt.Sprintf("%s/%s/%s", m.controlFilesRoot, claim.UID, "shm"),
logDir: fmt.Sprintf("%s/%s/%s", m.controlFilesRoot, claim.UID, "log"),
devices: devices,
config: config,
manager: m,
}
}
func (m *MpsManager) IsControlDaemonStarted(ctx context.Context, claim *nascrd.ClaimInfo) (bool, error) {
name := fmt.Sprintf(MpsControlDaemonNameFmt, claim.UID)
_, err := m.config.clientsets.Core.AppsV1().Deployments(m.config.nascr.Namespace).Get(ctx, name, metav1.GetOptions{})
if errors.IsNotFound(err) {
return false, nil
}
if err != nil {
return false, fmt.Errorf("failed to get deployment: %w", err)
}
return true, nil
}
func (m *MpsManager) IsControlDaemonStopped(ctx context.Context, claim *nascrd.ClaimInfo) (bool, error) {
name := fmt.Sprintf(MpsControlDaemonNameFmt, claim.UID)
_, err := m.config.clientsets.Core.AppsV1().Deployments(m.config.nascr.Namespace).Get(ctx, name, metav1.GetOptions{})
if errors.IsNotFound(err) {
return true, nil
}
if err != nil {
return false, fmt.Errorf("failed to get deployment: %w", err)
}
return false, nil
}
func (m *MpsControlDaemon) Start(ctx context.Context) error {
isStarted, err := m.manager.IsControlDaemonStarted(ctx, m.claim)
if err != nil {
return fmt.Errorf("error checking if control daemon already started: %w", err)
}
if isStarted {
return nil
}
klog.Infof("Starting MPS control daemon for '%v', with settings: %+v", m.claim.UID, m.config)
deviceUUIDs := m.devices.UUIDs()
templateData := MpsControlDaemonTemplateData{
NodeName: m.nodeName,
MpsControlDaemonNamespace: m.namespace,
MpsControlDaemonName: m.name,
CUDA_VISIBLE_DEVICES: strings.Join(deviceUUIDs, ","),
DefaultActiveThreadPercentage: "",
DefaultPinnedDeviceMemoryLimits: nil,
NvidiaDriverRoot: m.manager.hostDriverRoot,
MpsShmDirectory: m.shmDir,
MpsPipeDirectory: m.pipeDir,
MpsLogDirectory: m.logDir,
}
if m.config != nil && m.config.DefaultActiveThreadPercentage != nil {
templateData.DefaultActiveThreadPercentage = fmt.Sprintf("%d", *m.config.DefaultActiveThreadPercentage)
}
if m.config != nil {
limits, err := m.config.DefaultPerDevicePinnedMemoryLimit.Normalize(deviceUUIDs, m.config.DefaultPinnedDeviceMemoryLimit)
if err != nil {
return fmt.Errorf("error transforming DefaultPerDevicePinnedMemoryLimit into string: %w", err)
}
templateData.DefaultPinnedDeviceMemoryLimits = limits
}
tmpl, err := template.ParseFiles(m.manager.templatePath)
if err != nil {
return fmt.Errorf("failed to parse template file: %w", err)
}
var deploymentYaml bytes.Buffer
if err := tmpl.Execute(&deploymentYaml, templateData); err != nil {
return fmt.Errorf("failed to execute template: %w", err)
}
var unstructuredObj unstructured.Unstructured
err = yaml.Unmarshal(deploymentYaml.Bytes(), &unstructuredObj)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml: %w", err)
}
var deployment appsv1.Deployment
err = runtime.DefaultUnstructuredConverter.FromUnstructured(unstructuredObj.UnstructuredContent(), &deployment)
if err != nil {
return fmt.Errorf("failed to convert unstructured data to typed object: %w", err)
}
err = os.MkdirAll(m.shmDir, 0755)
if err != nil {
return fmt.Errorf("error creating directory %v: %w", m.shmDir, err)
}
err = os.MkdirAll(m.pipeDir, 0755)
if err != nil {
return fmt.Errorf("error creating directory %v: %w", m.pipeDir, err)
}
err = os.MkdirAll(m.logDir, 0755)
if err != nil {
return fmt.Errorf("error creating directory %v: %w", m.logDir, err)
}
mountExecutable, err := exec.LookPath("mount")
if err != nil {
return fmt.Errorf("error finding 'mount' executable: %w", err)
}
mounter := mount.New(mountExecutable)
mountOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=65536k"}
err = mounter.Mount("shm", m.shmDir, "tmpfs", mountOptions)
if err != nil {
return fmt.Errorf("error mounting %v as tmpfs: %w", m.shmDir, err)
}
if m.devices.Type() == nascrd.GpuDeviceType {
err = m.manager.nvdevlib.setComputeMode(m.devices.UUIDs(), "EXCLUSIVE_PROCESS")
if err != nil {
return fmt.Errorf("error setting compute mode: %w", err)
}
}
_, err = m.manager.config.clientsets.Core.AppsV1().Deployments(m.namespace).Create(ctx, &deployment, metav1.CreateOptions{})
if errors.IsAlreadyExists(err) {
return nil
}
if err != nil {
return fmt.Errorf("failed to create deployment: %w", err)
}
return nil
}
func (m *MpsControlDaemon) AssertReady(ctx context.Context) error {
backoff := wait.Backoff{
Duration: time.Second,
Factor: 2,
Jitter: 1,
Steps: 4,
Cap: 10 * time.Second,
}
return retry.OnError(
backoff,
func(error) bool {
return true
},
func() error {
deployment, err := m.manager.config.clientsets.Core.AppsV1().Deployments(m.namespace).Get(
ctx,
m.name,
metav1.GetOptions{},
)
if err != nil {
return fmt.Errorf("failed to get deployment: %w", err)
}
if deployment.Status.ReadyReplicas != 1 {
return fmt.Errorf("waiting for MPS control daemon to come online")
}
selector := deployment.Spec.Selector.MatchLabels
pods, err := m.manager.config.clientsets.Core.CoreV1().Pods(m.namespace).List(
ctx,
metav1.ListOptions{
LabelSelector: labels.Set(selector).AsSelector().String(),
},
)
if err != nil {
return fmt.Errorf("error listing pods from deployment")
}
if len(pods.Items) != 1 {
return fmt.Errorf("unexpected number of pods in deployment: %v", len(pods.Items))
}
if len(pods.Items[0].Status.ContainerStatuses) != 1 {
return fmt.Errorf("unexpected number of container statuses in pod")
}
if !pods.Items[0].Status.ContainerStatuses[0].Ready {
return fmt.Errorf("control daemon not yet ready")
}
return nil
},
)
}
func (m *MpsControlDaemon) GetCDIContainerEdits() *cdiapi.ContainerEdits {
return &cdiapi.ContainerEdits{
ContainerEdits: &cdispec.ContainerEdits{
Env: []string{
fmt.Sprintf("CUDA_MPS_PIPE_DIRECTORY=%s", "/tmp/nvidia-mps"),
},
Mounts: []*cdispec.Mount{
{
ContainerPath: "/dev/shm",
HostPath: m.shmDir,
Options: []string{"rw", "nosuid", "nodev", "bind"},
},
{
ContainerPath: "/tmp/nvidia-mps",
HostPath: m.pipeDir,
Options: []string{"rw", "nosuid", "nodev", "bind"},
},
},
},
}
}
func (m *MpsControlDaemon) Stop(ctx context.Context) error {
_, err := os.Stat(m.rootDir)
if os.IsNotExist(err) {
return nil
}
klog.Infof("Stopping MPS control daemon for claim '%v'", m.claim.UID)
deletePolicy := metav1.DeletePropagationForeground
deleteOptions := metav1.DeleteOptions{
PropagationPolicy: &deletePolicy,
}
err = m.manager.config.clientsets.Core.AppsV1().Deployments(m.namespace).Delete(ctx, m.name, deleteOptions)
if err != nil && !errors.IsNotFound(err) {
return fmt.Errorf("failed to delete deployment: %w", err)
}
mountExecutable, err := exec.LookPath("mount")
if err != nil {
return fmt.Errorf("error finding 'mount' executable: %w", err)
}
mounter := mount.New(mountExecutable)
err = mount.CleanupMountPoint(m.shmDir, mounter, true)
if err != nil {
return fmt.Errorf("error unmounting %v: %w", m.shmDir, err)
}
err = os.RemoveAll(m.rootDir)
if err != nil {
return fmt.Errorf("error removing directory %v: %w", m.rootDir, err)
}
return nil
}