Skip to content
Navigation Menu
{{ message }}
-
Notifications
You must be signed in to change notification settings - Fork 898
Expand file tree
/
Copy pathlinux_namespace.go
More file actions
444 lines (389 loc) · 11.3 KB
/
Copy pathlinux_namespace.go
File metadata and controls
444 lines (389 loc) · 11.3 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//go:build !darwin && !windows
package engineutil
import (
"context"
"fmt"
"os"
"runtime"
"sync"
"time"
"github.com/opencontainers/runc/libcontainer"
"github.com/opencontainers/runtime-spec/specs-go"
"github.com/sourcegraph/conc/pool"
"golang.org/x/sys/unix"
)
const (
idleTimeout = 1 * time.Second
workerPoolSize = 5
)
// NamespaceJob represents a job to be executed in a specific namespace context
type NamespaceJob struct {
Container string // Container whose namespaces to enter
Namespaces []specs.LinuxNamespace // Namespaces to enter (e.g., network, mount, etc.)
Fn func() error // Function to execute
ResultCh chan error // Channel to send result back
}
// GlobalNamespaceWorkerPool manages a global pool of workers that can enter
// different namespace contexts based on PID and namespace type
type GlobalNamespaceWorkerPool struct {
jobs chan *NamespaceJob
ctx context.Context
cancel context.CancelFunc
pool *pool.ContextPool
mu sync.RWMutex
started bool
}
// globalNSWorkerPool is the singleton global worker pool
var (
globalNSWorkerPool *GlobalNamespaceWorkerPool
globalNSWorkerPoolOnce sync.Once
)
func runInNetNS[T any](
ctx context.Context,
state *execState,
fn func() (T, error),
) (T, error) {
var zero T
// Prepare the job result
type result struct {
value T
err error
}
resultCh := make(chan result, 1)
var nsPath string
// need this to extract the namespace file
var tmpSpec specs.Spec
if state.networkNamespace != nil {
if err := state.networkNamespace.Set(&tmpSpec); err != nil {
return zero, fmt.Errorf("failed to set network namespace: %w", err)
}
for _, ns := range tmpSpec.Linux.Namespaces {
if ns.Type == specs.NetworkNamespace {
nsPath = ns.Path
}
}
}
namespaces := []specs.LinuxNamespace{
{
Type: specs.NetworkNamespace,
Path: nsPath, // this known (and needed) ahead of time
},
}
// Wrap the function to match the expected signature and capture result
wrappedFn := func() error {
value, err := fn()
resultCh <- result{value: value, err: err}
return nil // Always return nil from wrappedFn since we handle errors via resultCh
}
// Submit job to global pool
gwp := GetGlobalNamespaceWorkerPool()
if err := gwp.RunInNamespaces(ctx, state.id, namespaces, wrappedFn); err != nil {
return zero, err
}
// Wait for result
select {
case <-ctx.Done():
return zero, context.Cause(ctx)
case <-state.done:
return zero, fmt.Errorf("container exited")
case res := <-resultCh:
return res.value, res.err
}
}
// GetGlobalNamespaceWorkerPool returns the singleton global namespace worker pool
func GetGlobalNamespaceWorkerPool() *GlobalNamespaceWorkerPool {
globalNSWorkerPoolOnce.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
globalNSWorkerPool = &GlobalNamespaceWorkerPool{
jobs: make(chan *NamespaceJob, 100), // buffered channel
ctx: ctx,
cancel: cancel,
pool: pool.New().WithContext(ctx),
}
})
return globalNSWorkerPool
}
// Start initializes and starts the global worker pool
func (gwp *GlobalNamespaceWorkerPool) Start() {
gwp.mu.Lock()
defer gwp.mu.Unlock()
if gwp.started {
return
}
for range workerPoolSize {
gwp.pool.Go(gwp.workerLoop)
}
gwp.started = true
}
// Stop gracefully shuts down the global worker pool
func (gwp *GlobalNamespaceWorkerPool) Stop() {
gwp.mu.Lock()
defer gwp.mu.Unlock()
if !gwp.started {
return
}
gwp.cancel()
gwp.pool.Wait()
close(gwp.jobs)
gwp.started = false
}
// SubmitJob submits a job to be executed in the specified namespace context
func (gwp *GlobalNamespaceWorkerPool) SubmitJob(ctx context.Context, job *NamespaceJob) error {
select {
case <-ctx.Done():
return context.Cause(ctx)
case gwp.jobs <- job:
return nil
}
}
// RunInNamespaces executes a function in the context of specific namespaces for a given PID
func (gwp *GlobalNamespaceWorkerPool) RunInNamespaces(ctx context.Context, containerID string, namespaces []specs.LinuxNamespace, fn func() error) error {
resultCh := make(chan error, 1)
job := &NamespaceJob{
Container: containerID,
Namespaces: namespaces,
Fn: fn,
ResultCh: resultCh,
}
if err := gwp.SubmitJob(ctx, job); err != nil {
return err
}
select {
case <-ctx.Done():
return context.Cause(ctx)
case err := <-resultCh:
return err
}
}
// workerLoop is the main loop for each worker goroutine
func (gwp *GlobalNamespaceWorkerPool) workerLoop(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return context.Cause(ctx)
case job := <-gwp.jobs:
if job == nil {
continue
}
gwp.executeJob(ctx, job)
}
}
}
// executeJob executes a single job in its own isolated goroutine
func (gwp *GlobalNamespaceWorkerPool) executeJob(ctx context.Context, job *NamespaceJob) {
// Create a new namespace worker for this job
nsw, err := gwp.createNamespaceWorker(job.Container, job.Namespaces)
if err != nil {
select {
case job.ResultCh <- fmt.Errorf("failed to create namespace worker: %w", err):
case <-ctx.Done():
}
return
}
defer nsw.cleanup()
// Execute the job in its own goroutine since it will lock to threads
errCh := make(chan error, 1)
go func() {
defer close(errCh)
errCh <- gwp.executeInNamespace(nsw, job.Fn)
}()
select {
case err := <-errCh:
select {
case job.ResultCh <- err:
case <-ctx.Done():
}
case <-ctx.Done():
select {
case job.ResultCh <- context.Cause(ctx):
case <-ctx.Done():
}
}
}
// createNamespaceWorker creates a namespace worker for the given PID and namespaces
func (gwp *GlobalNamespaceWorkerPool) createNamespaceWorker(containerID string, namespaces []specs.LinuxNamespace) (*dynamicNamespaceWorker, error) {
nsFiles := make([]*dynamicNamespaceFiles, 0, len(namespaces))
for _, ns := range namespaces {
var hostPath, targetPath string
var setNSArg int
// Map namespace types to their paths and setns arguments
switch ns.Type {
case specs.NetworkNamespace:
hostPath = "/proc/self/ns/net"
setNSArg = unix.CLONE_NEWNET
case specs.PIDNamespace:
hostPath = "/proc/self/ns/pid"
setNSArg = unix.CLONE_NEWPID
case specs.MountNamespace:
hostPath = "/proc/self/ns/mnt"
setNSArg = unix.CLONE_NEWNS
case specs.UserNamespace:
hostPath = "/proc/self/ns/user"
setNSArg = unix.CLONE_NEWUSER
case specs.UTSNamespace:
hostPath = "/proc/self/ns/uts"
setNSArg = unix.CLONE_NEWUTS
case specs.IPCNamespace:
hostPath = "/proc/self/ns/ipc"
setNSArg = unix.CLONE_NEWIPC
case specs.CgroupNamespace:
hostPath = "/proc/self/ns/cgroup"
setNSArg = unix.CLONE_NEWCGROUP
default:
return nil, fmt.Errorf("unsupported namespace type: %s", ns.Type)
}
// If path is specified in namespace, use it, otherwise construct from PID
if ns.Path != "" {
targetPath = ns.Path
} else {
// Get the container PID using libcontainer
pid, err := getContainerPID(containerID)
if err != nil {
return nil, fmt.Errorf("failed to get container PID: %w", err)
}
targetPath = fmt.Sprintf("/proc/%d/ns/%s", pid, namespaceTypeToString(ns.Type))
}
hostFile, err := os.OpenFile(hostPath, os.O_RDONLY, 0)
if err != nil {
// Clean up already opened files
for _, nf := range nsFiles {
nf.hostFile.Close()
nf.targetFile.Close()
}
return nil, fmt.Errorf("failed to open host namespace %s: %w", hostPath, err)
}
targetFile, err := os.OpenFile(targetPath, os.O_RDONLY, 0)
if err != nil {
hostFile.Close()
// Clean up already opened files
for _, nf := range nsFiles {
nf.hostFile.Close()
nf.targetFile.Close()
}
return nil, fmt.Errorf("failed to open target namespace %s: %w", targetPath, err)
}
nsFiles = append(nsFiles, &dynamicNamespaceFiles{
hostFile: hostFile,
targetFile: targetFile,
setNSArg: setNSArg,
})
}
return &dynamicNamespaceWorker{
namespaces: nsFiles,
}, nil
}
// namespaceTypeToString converts a namespace type to its string representation
func namespaceTypeToString(nsType specs.LinuxNamespaceType) string {
switch nsType {
case specs.NetworkNamespace:
return "net"
case specs.PIDNamespace:
return "pid"
case specs.MountNamespace:
return "mnt"
case specs.UserNamespace:
return "user"
case specs.UTSNamespace:
return "uts"
case specs.IPCNamespace:
return "ipc"
case specs.CgroupNamespace:
return "cgroup"
default:
return string(nsType)
}
}
// executeInNamespace executes a function in the namespace context
func (gwp *GlobalNamespaceWorkerPool) executeInNamespace(nsw *dynamicNamespaceWorker, fn func() error) error {
if err := nsw.enterNamespaces(); err != nil {
return err
}
defer nsw.leaveNamespaces()
return fn()
}
// dynamicNamespaceWorker handles entering/leaving multiple namespaces dynamically
type dynamicNamespaceWorker struct {
namespaces []*dynamicNamespaceFiles
inNamespace bool
}
// dynamicNamespaceFiles includes both host and target files
type dynamicNamespaceFiles struct {
hostFile *os.File
targetFile *os.File
setNSArg int
}
// cleanup closes all open files
func (nsw *dynamicNamespaceWorker) cleanup() {
for _, ns := range nsw.namespaces {
if ns.hostFile != nil {
ns.hostFile.Close()
}
if ns.targetFile != nil {
ns.targetFile.Close()
}
}
}
// enterNamespaces enters all specified namespaces
func (nsw *dynamicNamespaceWorker) enterNamespaces() error {
if nsw.inNamespace {
return nil
}
runtime.LockOSThread()
for _, ns := range nsw.namespaces {
if ns.setNSArg == unix.CLONE_NEWNS {
// Unshare FS metadata first, otherwise setns to another mount
// namespace doesn't work.
//
// Possibly relevant Kernel docs:
//
// For security reasons, a process can't join a new mount namespace if it
// is sharing filesystem-related attributes (the attributes whose sharing
// is controlled by the clone(2) CLONE_FS flag) with another process.
if err := unix.Unshare(unix.CLONE_FS); err != nil {
return fmt.Errorf("failed to unshare mount namespace: %w", err)
}
}
if err := unix.Setns(int(ns.targetFile.Fd()), ns.setNSArg); err != nil {
return fmt.Errorf("failed to enter namespace: %w", err)
}
}
nsw.inNamespace = true
return nil
}
// leaveNamespaces exits all namespaces and returns to host
func (nsw *dynamicNamespaceWorker) leaveNamespaces() error {
if !nsw.inNamespace {
return nil
}
for _, ns := range nsw.namespaces {
if err := unix.Setns(int(ns.hostFile.Fd()), ns.setNSArg); err != nil {
return fmt.Errorf("failed to leave namespace: %w", err)
}
}
runtime.UnlockOSThread()
nsw.inNamespace = false
return nil
}
// ShutdownGlobalNamespaceWorkerPool gracefully shuts down the global namespace worker pool
// This should be called during application shutdown
func ShutdownGlobalNamespaceWorkerPool() {
if globalNSWorkerPool != nil {
globalNSWorkerPool.Stop()
}
}
// getContainerPID retrieves the PID of a container using libcontainer
func getContainerPID(containerID string) (int, error) {
// Load the container using libcontainer
container, err := libcontainer.Load("/run/runc", containerID)
if err != nil {
return 0, fmt.Errorf("failed to create libcontainer factory: %w", err)
}
state, err := container.OCIState()
if err != nil {
return 0, fmt.Errorf("failed to get OCI state for container %s: %w", containerID, err)
}
if state.Pid == 0 {
return 0, fmt.Errorf("container %s has no running process", containerID)
}
return state.Pid, nil
}
You can’t perform that action at this time.
