-
Notifications
You must be signed in to change notification settings - Fork 1.9k
/
cpuset_manager_v2.go
368 lines (307 loc) · 9.93 KB
/
cpuset_manager_v2.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
//go:build linux
package cgutil
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-set"
"github.com/hashicorp/nomad/helper"
"github.com/hashicorp/nomad/lib/cpuset"
"github.com/hashicorp/nomad/nomad/structs"
"github.com/opencontainers/runc/libcontainer/cgroups"
"github.com/opencontainers/runc/libcontainer/cgroups/fs2"
"github.com/opencontainers/runc/libcontainer/configs"
)
const (
// CreationPID is a special PID in libcontainer used to denote a cgroup
// should be created, but with no process added.
//
// https://github.com/opencontainers/runc/blob/v1.0.3/libcontainer/cgroups/utils.go#L372
CreationPID = -1
// DefaultCgroupParentV2 is the name of Nomad's default parent cgroup, under which
// all other cgroups are managed. This can be changed with client configuration
// in case for e.g. Nomad tasks should be further constrained by an externally
// configured systemd cgroup.
DefaultCgroupParentV2 = "nomad.slice"
)
// nothing is used for treating a map like a set with no values
type nothing struct{}
// present indicates something exists
var present = nothing{}
type cpusetManagerV2 struct {
logger hclog.Logger
parent string // relative to cgroup root (e.g. "nomad.slice")
parentAbs string // absolute path (e.g. "/sys/fs/cgroup/nomad.slice")
initial cpuset.CPUSet // set of initial cores (never changes)
lock sync.Mutex // hold this when managing pool / sharing / isolating
pool cpuset.CPUSet // pool of cores being shared among all tasks
sharing map[identity]nothing // sharing tasks using cores only from the pool
isolating map[identity]cpuset.CPUSet // isolating tasks using cores from the pool + reserved cores
}
func NewCpusetManagerV2(parent string, reservable []uint16, logger hclog.Logger) CpusetManager {
if err := minimumRootControllers(); err != nil {
logger.Error("failed to enabled minimum set of cgroup controllers; disabling cpuset management", "error", err)
return new(NoopCpusetManager)
}
parentAbs := filepath.Join(CgroupRoot, parent)
if err := os.MkdirAll(parentAbs, 0o755); err != nil {
logger.Error("failed to ensure nomad parent cgroup exists; disabling cpuset management", "error", err)
return new(NoopCpusetManager)
}
if len(reservable) == 0 {
// read from group
if cpus, err := GetCPUsFromCgroup(parent); err != nil {
logger.Error("failed to lookup cpus from parent cgroup; disabling cpuset management", "error", err)
return new(NoopCpusetManager)
} else {
reservable = cpus
}
}
return &cpusetManagerV2{
initial: cpuset.New(reservable...),
parent: parent,
parentAbs: parentAbs,
logger: logger,
sharing: make(map[identity]nothing),
isolating: make(map[identity]cpuset.CPUSet),
}
}
// minimumControllers sets the minimum set of required controllers on the
// /sys/fs/cgroup/cgroup.subtree_control file - ensuring [cpuset, cpu, io, memory, pids]
// are enabled.
func minimumRootControllers() error {
e := new(editor)
s, err := e.read("cgroup.subtree_control")
if err != nil {
return err
}
required := set.From[string]([]string{"cpuset", "cpu", "io", "memory", "pids"})
enabled := set.From[string](strings.Fields(s))
needed := required.Difference(enabled)
if needed.Size() == 0 {
return nil // already sufficient
}
sb := new(strings.Builder)
for _, controller := range needed.List() {
sb.WriteString("+" + controller + " ")
}
activation := strings.TrimSpace(sb.String())
return e.write("cgroup.subtree_control", activation)
}
func (c *cpusetManagerV2) Init() {
c.logger.Debug("initializing with", "cores", c.initial)
}
func (c *cpusetManagerV2) AddAlloc(alloc *structs.Allocation) {
if alloc == nil || alloc.AllocatedResources == nil {
return
}
c.logger.Trace("add allocation", "name", alloc.Name, "id", alloc.ID)
// grab write lock while we recompute and apply changes
c.lock.Lock()
defer c.lock.Unlock()
// first update our tracking of isolating and sharing tasks
for task, resources := range alloc.AllocatedResources.Tasks {
id := makeID(alloc.ID, task)
if len(resources.Cpu.ReservedCores) > 0 {
c.isolating[id] = cpuset.New(resources.Cpu.ReservedCores...)
} else {
c.sharing[id] = present
}
}
// recompute the available sharable cpu cores
c.recalculate()
// now write out the entire cgroups space
c.reconcile()
// no need to cleanup on adds, we did not remove a task
}
func (c *cpusetManagerV2) RemoveAlloc(allocID string) {
c.logger.Trace("remove allocation", "id", allocID)
// grab write lock while we recompute and apply changes.
c.lock.Lock()
defer c.lock.Unlock()
// remove tasks of allocID from the sharing set
for id := range c.sharing {
if strings.HasPrefix(string(id), allocID) {
delete(c.sharing, id)
}
}
// remove tasks of allocID from the isolating set
for id := range c.isolating {
if strings.HasPrefix(string(id), allocID) {
delete(c.isolating, id)
}
}
// recompute available sharable cpu cores
c.recalculate()
// now write out the entire cgroups space
c.reconcile()
// now remove any tasks no longer running
c.cleanup()
}
func (c *cpusetManagerV2) CgroupPathFor(allocID, task string) CgroupPathGetter {
// The CgroupPathFor implementation must block until cgroup for allocID.task
// exists [and can accept a PID].
return func(ctx context.Context) (string, error) {
ticks, cancel := helper.NewSafeTimer(100 * time.Millisecond)
defer cancel()
for {
path := c.pathOf(makeID(allocID, task))
mgr, err := fs2.NewManager(nil, path)
if err != nil {
return "", err
}
if mgr.Exists() {
return path, nil
}
select {
case <-ctx.Done():
return "", ctx.Err()
case <-ticks.C:
continue
}
}
}
}
// recalculate the number of cores sharable by non-isolating tasks (and isolating tasks)
//
// must be called while holding c.lock
func (c *cpusetManagerV2) recalculate() {
remaining := c.initial.Copy()
for _, set := range c.isolating {
remaining = remaining.Difference(set)
}
c.pool = remaining
}
// reconcile will actually write the cpuset values for all tracked tasks.
//
// must be called while holding c.lock
func (c *cpusetManagerV2) reconcile() {
for id := range c.sharing {
c.write(id, c.pool)
}
for id, set := range c.isolating {
c.write(id, c.pool.Union(set))
}
}
// cleanup will remove any cgroups for allocations no longer being tracked
//
// must be called while holding c.lock
func (c *cpusetManagerV2) cleanup() {
// create a map to lookup ids we know about
size := len(c.sharing) + len(c.isolating)
ids := make(map[identity]nothing, size)
for id := range c.sharing {
ids[id] = present
}
for id := range c.isolating {
ids[id] = present
}
if err := filepath.WalkDir(c.parentAbs, func(path string, entry os.DirEntry, err error) error {
// skip anything we cannot read
if err != nil {
return nil
}
// a cgroup is a directory
if !entry.IsDir() {
return nil
}
dir := filepath.Dir(path)
base := filepath.Base(path)
// only manage scopes directly under nomad.slice
if dir != c.parentAbs || !strings.HasSuffix(base, ".scope") {
return nil
}
// only remove the scope if we do not track it
id := identity(strings.TrimSuffix(base, ".scope"))
_, exists := ids[id]
if !exists {
c.remove(path)
}
return nil
}); err != nil {
c.logger.Error("failed to cleanup cgroup", "error", err)
}
}
// pathOf returns the absolute path to a task with identity id.
func (c *cpusetManagerV2) pathOf(id identity) string {
return filepath.Join(c.parentAbs, makeScope(id))
}
// remove does the actual fs delete of the cgroup
//
// We avoid removing a cgroup if it still contains a PID, as the cpuset manager
// may be initially empty on a Nomad client restart.
func (c *cpusetManagerV2) remove(path string) {
mgr, err := fs2.NewManager(nil, path)
if err != nil {
c.logger.Warn("failed to create manager", "path", path, "error", err)
return
}
// get the list of pids managed by this scope (should be 0 or 1)
pids, _ := mgr.GetPids()
// do not destroy the scope if a PID is still present
// this is a normal condition when an agent restarts with running tasks
// and the v2 manager is still rebuilding its tracked tasks
if len(pids) > 0 {
return
}
// remove the cgroup
if err3 := mgr.Destroy(); err3 != nil {
c.logger.Warn("failed to cleanup cgroup", "path", path, "error", err)
return
}
}
// write does the actual write of cpuset set for cgroup id
func (c *cpusetManagerV2) write(id identity, set cpuset.CPUSet) {
path := c.pathOf(id)
// make a manager for the cgroup
m, err := fs2.NewManager(new(configs.Cgroup), path)
if err != nil {
c.logger.Error("failed to manage cgroup", "path", path, "error", err)
return
}
// create the cgroup
if err = m.Apply(CreationPID); err != nil {
c.logger.Error("failed to apply cgroup", "path", path, "error", err)
return
}
// set the cpuset value for the cgroup
if err = m.Set(&configs.Resources{
CpusetCpus: set.String(),
SkipDevices: true,
}); err != nil {
c.logger.Error("failed to set cgroup", "path", path, "error", err)
return
}
}
// fromRoot returns the joined filepath of group on the CgroupRoot
func fromRoot(group string) string {
return filepath.Join(CgroupRoot, group)
}
// getCPUsFromCgroupV2 retrieves the effective cpuset for the group, which must
// be directly under the cgroup root (i.e. the parent, like nomad.slice).
func getCPUsFromCgroupV2(group string) ([]uint16, error) {
path := fromRoot(group)
effective, err := cgroups.ReadFile(path, "cpuset.cpus.effective")
if err != nil {
return nil, err
}
set, err := cpuset.Parse(effective)
if err != nil {
return nil, err
}
return set.ToSlice(), nil
}
// identity is the "<allocID>.<taskName>" string that uniquely identifies an
// individual instance of a task within the flat cgroup namespace
type identity string
func makeID(allocID, task string) identity {
return identity(fmt.Sprintf("%s.%s", allocID, task))
}
func makeScope(id identity) string {
return string(id) + ".scope"
}