-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathservice_impl.go
More file actions
423 lines (386 loc) · 11.4 KB
/
Copy pathservice_impl.go
File metadata and controls
423 lines (386 loc) · 11.4 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
411
412
413
414
415
416
417
418
419
420
421
422
423
// Package service implements service of getting pids
package service
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"syscall"
"time"
"google.golang.org/grpc"
"huawei.com/vxpu-device-plugin/pkg/log"
"huawei.com/vxpu-device-plugin/pkg/plugin/config"
"huawei.com/vxpu-device-plugin/pkg/plugin/types"
"huawei.com/vxpu-device-plugin/pkg/plugin/util"
"huawei.com/vxpu-device-plugin/pkg/plugin/xpu"
"k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/fields"
"k8s.io/klog/v2"
)
const (
cgroupBaseDir = "/sys/fs/cgroup/memory"
cgroupProcs = "cgroup.procs"
pidsSockPath = "/var/lib/xpu/pids.sock"
hostProcDir = "/hostproc"
procStatus = "status"
nsPid = "NSpid:"
nsPidFieldCount = 3
containerdPodIdPrefix = "-pod"
dockerPodIdPrefix = "/pod"
containerdPodIdSuffix = ".slice"
dockerPodIdSuffix = "/"
containerIdPrefix = "cri-containerd-"
containerIdSuffix = ".scope"
containerIdPrefixInContainerd = "containerd://"
containerIdPrefixInDocker = "docker://"
vxpuConfigBaseDir = "/etc/xpu"
pidsConfigFileName = "pids.config"
configFilePerm = 0644
pidsSockPerm = 0666
podDirCleanInterval = 60
minPeriod = 1
maxPeriod = 86400
defaultPeriod = 60
percentage = 100
float64BitsSize = 64
)
// PidsServiceServerImpl implementation of pids service
type PidsServiceServerImpl struct {
*UnimplementedPidsServiceServer
}
func readProcsFile(file string) ([]int, error) {
f, err := os.Open(file)
if err != nil {
return nil, err
}
defer f.Close()
scanner := bufio.NewScanner(f)
pids := make([]int, 0)
for scanner.Scan() {
line := scanner.Text()
if pid, err := strconv.Atoi(line); err == nil {
pids = append(pids, pid)
}
}
return pids, nil
}
func readStatusFile(file string) (string, error) {
f, err := os.Open(file)
if err != nil {
return "", err
}
defer f.Close()
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, nsPid) {
eles := strings.Fields(line)
if len(eles) != nsPidFieldCount {
return "", errors.New("NpPid field count error")
}
pids := fmt.Sprintf("%-11s %-11s", eles[1], eles[2])
return pids, nil
}
}
return "", errors.New("NpPid not found")
}
func getPidMaps(hostPids []int) string {
pidMaps := make([]string, 0)
for _, hp := range hostPids {
procStatusPath := filepath.Clean(filepath.Join(hostProcDir, strconv.Itoa(hp), procStatus))
pids, err := readStatusFile(procStatusPath)
if err != nil {
klog.Warning("read proc status error: %v, path: %s", err, procStatusPath)
} else {
pidMaps = append(pidMaps, pids)
}
}
return strings.Join(pidMaps, ",")
}
func parseCgroupPath(cgroupPath string) (string, string, error) {
// 定义正则表达式模式
podPattern := `([a-f0-9]{8}_[a-f0-9]{4}_[a-f0-9]{4}_[a-f0-9]{4}_[a-f0-9]{12})`
containerPattern := `([a-f0-9]{64})`
// 编译正则表达式
podRegex := regexp.MustCompile(podPattern)
containerRegex := regexp.MustCompile(containerPattern)
// 查找podId
podMatches := podRegex.FindStringSubmatch(cgroupPath)
if len(podMatches) < 2 {
return "", "", errors.New("pod id not found")
}
podId := podMatches[1]
podId = strings.Replace(podId, "_", "-", -1)
// 查找containerId
containerMatches := containerRegex.FindStringSubmatch(cgroupPath)
if len(containerMatches) < 2 {
return "", "", errors.New("container id not found")
}
containerId := containerMatches[1]
return podId, containerId, nil
}
func getContainerName(cgroupPath string) (string, string, error) {
podId, containerId, err := parseCgroupPath(cgroupPath)
log.Infof("podID: %s, containerId: %s", podId, containerId)
if err != nil {
klog.Error("parse cgroup path error: %v", err)
return "", "", err
}
selector := fields.SelectorFromSet(fields.Set{"spec.nodeName": config.NodeName, "status.phase": string(v1.PodRunning)})
podList, err := util.ListPods(
metav1.ListOptions{
FieldSelector: selector.String(),
})
if err != nil {
return podId, "", err
}
for _, pod := range podList.Items {
if string(pod.UID) != podId {
continue
}
if pod.Status.Phase != v1.PodRunning || len(pod.Status.ContainerStatuses) == 0 {
errMsg := fmt.Sprintf("pod status error: %v, container status len: %d",
pod.Status.Phase, len(pod.Status.ContainerStatuses))
return podId, "", errors.New(errMsg)
}
for _, cs := range pod.Status.ContainerStatuses {
if cs.ContainerID[len(containerIdPrefixInContainerd):] != containerId &&
cs.ContainerID[len(containerIdPrefixInDocker):] != containerId {
continue
}
return podId, cs.Name, nil
}
}
return podId, "", errors.New("container not found")
}
func readPidsConfig(pidsConfigPath string) ([]uint32, error) {
f, err := os.OpenFile(pidsConfigPath, os.O_RDONLY, configFilePerm)
if err != nil {
return nil, err
}
defer f.Close()
var pids []uint32
scanner := bufio.NewScanner(f)
for scanner.Scan() {
line := scanner.Text()
tmp := strings.Fields(line)
if len(tmp) == 0 {
continue
}
pid, err := strconv.Atoi(tmp[0])
if err != nil {
continue
}
pids = append(pids, uint32(pid))
}
return pids, nil
}
func writePidsConfig(pidsConfigPath, pidMaps string) error {
f, err := os.OpenFile(pidsConfigPath, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, configFilePerm)
if err != nil {
return err
}
defer f.Close()
w := bufio.NewWriter(f)
pids := strings.Split(pidMaps, ",")
for _, pid := range pids {
_, err = w.WriteString(pid + "\n")
if err != nil {
return err
}
}
return w.Flush()
}
func getPodDirNames() ([]string, error) {
dirNames := make([]string, 0)
err := filepath.Walk(vxpuConfigBaseDir, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info == nil || !info.IsDir() || path == vxpuConfigBaseDir {
return nil
}
dirNames = append(dirNames, info.Name())
return filepath.SkipDir
})
if err != nil {
return []string{}, err
}
return dirNames, nil
}
type void struct{}
var val void
func cleanDestroyedPodDir() error {
podDirNames, err := getPodDirNames()
if err != nil {
return err
}
selector := fields.SelectorFromSet(fields.Set{"spec.nodeName": config.NodeName})
podList, err := util.ListPods(
metav1.ListOptions{
FieldSelector: selector.String(),
})
if err != nil {
return err
}
podIdSet := make(map[string]void)
for _, pod := range podList.Items {
podIdSet[string(pod.UID)] = val
}
for _, podDirName := range podDirNames {
if _, ok := podIdSet[podDirName]; ok {
continue
}
podAbsoluteDir := filepath.Clean(filepath.Join(vxpuConfigBaseDir, podDirName))
err = os.RemoveAll(podAbsoluteDir)
}
return nil
}
// GetPids pids service external interface, get all pids map relationship in container
func (PidsServiceServerImpl) GetPids(ctx context.Context, req *GetPidsRequest) (*GetPidsResponse, error) {
cgroupAbsolutePath := filepath.Clean(filepath.Join(cgroupBaseDir, req.CgroupPath, cgroupProcs))
hostPids, err := readProcsFile(cgroupAbsolutePath)
if err != nil {
return nil, err
}
pidMaps := getPidMaps(hostPids)
podId, containerName, err := getContainerName(req.CgroupPath)
if err != nil {
return nil, err
}
pidsConfigPath := filepath.Clean(filepath.Join(vxpuConfigBaseDir, podId, containerName, pidsConfigFileName))
err = writePidsConfig(pidsConfigPath, pidMaps)
if err != nil {
return nil, err
}
return &GetPidsResponse{EncodedPids: pidMaps}, nil
}
func getPodSet(pSet map[string][]uint32) map[string][]uint32 {
if pSet == nil {
return nil
}
for k := range pSet {
pidsConfigPath := filepath.Clean(filepath.Join(vxpuConfigBaseDir, k, pidsConfigFileName))
pids, err := readPidsConfig(pidsConfigPath)
if err != nil {
continue
}
pSet[k] = pids
}
return pSet
}
func setVxpuDevices(vxpuDevices types.VxpuDevices,
xpuDevices map[string]*types.XPUDevice,
uidToProcessMap map[string]map[uint32]*types.ProcessUsage,
pSet map[string][]uint32) map[string]*types.XPUDevice {
for _, v := range vxpuDevices {
if _, ok := xpuDevices[v.GpuId]; !ok {
continue
}
processUsage, ok := uidToProcessMap[v.GpuId]
if !ok {
xpuDevices[v.GpuId].VxpuDeviceList = append(xpuDevices[v.GpuId].VxpuDeviceList, v)
continue
}
pidkey := fmt.Sprintf("%s/%s", v.PodUID, v.ContainerName)
for _, pid := range pSet[pidkey] {
if pUsage, ok := processUsage[pid]; ok {
v.VxpuCoreUtilization += float64(pUsage.ProcessCoreUtilization)
v.VxpuMemoryUsed += pUsage.ProcessMem
}
}
v.VxpuMemoryUsed = v.VxpuMemoryUsed / 1024 / 1024
if xpuDevices[v.GpuId].MemoryTotal != 0 {
vxpuMemoryUtil := float64(v.VxpuMemoryUsed*percentage) / float64(xpuDevices[v.GpuId].MemoryTotal)
vxpuMemoryUtil, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", vxpuMemoryUtil), float64BitsSize)
v.VxpuMemoryUtilization = vxpuMemoryUtil
}
xpuDevices[v.GpuId].VxpuDeviceList = append(xpuDevices[v.GpuId].VxpuDeviceList, v)
}
for _, device := range xpuDevices {
for _, vxpuDevices := range device.VxpuDeviceList {
device.MemoryUsed += vxpuDevices.VxpuMemoryUsed
}
memoryUtil := float64(device.MemoryUsed*percentage) / float64(device.MemoryTotal)
memoryUtil, _ = strconv.ParseFloat(fmt.Sprintf("%.2f", memoryUtil), float64BitsSize)
device.MemoryUtilization = memoryUtil
}
return xpuDevices
}
// GetAllVgpuInfo get all vgpu info of the node
func (PidsServiceServerImpl) GetAllVxpuInfo(ctx context.Context, req *GetAllVxpuInfoRequest) (*GetAllVxpuInfoResponse, error) {
period, err := strconv.Atoi(req.Period)
if err != nil || period < minPeriod || period > maxPeriod {
period = defaultPeriod
}
// xpuDevices: map[uuid]xpuDevice
xpuDevices, err := util.GetXPUs()
if err != nil {
return nil, err
}
// vgpuDevices: types.VgpuDevices[]
vxpuDevices, pSet, err := util.GetVxpus()
if err != nil {
return nil, err
}
// pSet: map["podId/containerName"]pids
pSet = getPodSet(pSet)
// uidToProcessMap: map[uuid]map[processId]processUsage
uidToProcessMap := make(map[string]map[uint32]*types.ProcessUsage)
for _, v := range xpuDevices {
deviceUsageInfo, processMap, err := xpu.GetXPUUsage(v.Index, int32(period))
if err != nil {
return nil, err
}
// XpuUtilization = deviceUsageInfo.CoreUtil
v.XpuUtilization = float64(deviceUsageInfo.CoreUtil)
v.PowerUsage = deviceUsageInfo.PowerUsage
v.Temperature = deviceUsageInfo.Temperature
uidToProcessMap[v.Id] = processMap
}
xpuDevices = setVxpuDevices(vxpuDevices, xpuDevices, uidToProcessMap, pSet)
jsonVgpuInfos, err := json.Marshal(xpuDevices)
if err != nil {
return nil, err
}
return &GetAllVxpuInfoResponse{VxpuInfos: string(jsonVgpuInfos)}, nil
}
// Start run pids service
func Start() {
srv := grpc.NewServer()
RegisterPidsServiceServer(srv, PidsServiceServerImpl{})
err := syscall.Unlink(pidsSockPath)
if err != nil && !os.IsNotExist(err) {
return
}
listener, err := net.Listen("unix", pidsSockPath)
if err != nil {
return
}
err = os.Chmod(pidsSockPath, pidsSockPerm)
if err != nil {
return
}
go func() {
err := srv.Serve(listener)
if err != nil {
}
}()
go func() {
for {
time.Sleep(time.Second * podDirCleanInterval)
err := cleanDestroyedPodDir()
if err != nil {
break
}
}
}()
}