forked from kubevirt/containerized-data-importer
/
prlimit.go
177 lines (150 loc) · 5.26 KB
/
prlimit.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
/*
Copyright 2018 The CDI Authors.
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 system
import (
"bufio"
"bytes"
"context"
"os/exec"
"syscall"
"time"
"unsafe"
"github.com/pkg/errors"
"golang.org/x/sys/unix"
"k8s.io/klog"
)
// ProcessLimiter defines the methods limiting resources of a Process
type ProcessLimiter interface {
SetAddressSpaceLimit(pid int, value uint64) error
SetCPUTimeLimit(pid int, value uint64) error
}
// ProcessLimitValues specifies the resource limits available to a process
type ProcessLimitValues struct {
AddressSpaceLimit uint64
CPUTimeLimit uint64
}
type processLimiter struct{}
var execCommand = exec.Command
var execCommandContext = exec.CommandContext
var limiter = NewProcessLimiter()
// NewProcessLimiter returns a new ProcessLimiter
func NewProcessLimiter() ProcessLimiter {
return &processLimiter{}
}
func (p *processLimiter) SetAddressSpaceLimit(pid int, value uint64) error {
return prlimit(pid, unix.RLIMIT_AS, &syscall.Rlimit{Cur: value, Max: value})
}
func (p *processLimiter) SetCPUTimeLimit(pid int, value uint64) error {
return prlimit(pid, unix.RLIMIT_CPU, &syscall.Rlimit{Cur: value, Max: value})
}
// SetAddressSpaceLimit sets a limit on total address space of a process
func SetAddressSpaceLimit(pid int, value uint64) error {
return limiter.SetAddressSpaceLimit(pid, value)
}
// SetCPUTimeLimit sets a limit on the total cpu time a process may have
func SetCPUTimeLimit(pid int, value uint64) error {
return limiter.SetCPUTimeLimit(pid, value)
}
// scanLinesWithCR is an alternate split function that works with carriage returns as well
// as new lines.
func scanLinesWithCR(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := bytes.IndexByte(data, '\r'); i >= 0 {
// We have a full carriage return-terminated line.
return i + 1, data[0:i], nil
}
if i := bytes.IndexByte(data, '\n'); i >= 0 {
// We have a full newline-terminated line.
return i + 1, data[0:i], nil
}
// If we're at EOF, we have a final, non-terminated line. Return it.
if atEOF {
return len(data), data, nil
}
// Request more data.
return 0, nil, nil
}
func processScanner(scanner *bufio.Scanner, buf *bytes.Buffer, done chan bool, callback func(string)) {
for scanner.Scan() {
line := scanner.Text()
buf.WriteString(line)
buf.WriteString("\n")
if callback != nil {
callback(line)
}
}
done <- true
}
// ExecWithLimits executes a command with process limits
func ExecWithLimits(limits *ProcessLimitValues, callback func(string), command string, args ...string) ([]byte, error) {
// Args can potentially contain sensitive information, make sure NOT to write args to the logs.
var buf bytes.Buffer
var cmd *exec.Cmd
stdoutDone := make(chan bool)
stderrDone := make(chan bool)
if limits != nil && limits.CPUTimeLimit > 0 {
klog.V(3).Infof("Setting CPU limit to %d\n", limits.CPUTimeLimit)
ctx, cancel := context.WithTimeout(context.Background(), time.Duration(limits.CPUTimeLimit)*time.Second)
defer cancel()
cmd = execCommandContext(ctx, command, args...)
} else {
cmd = execCommand(command, args...)
}
stdoutIn, err := cmd.StdoutPipe()
if err != nil {
return nil, errors.Wrapf(err, "Couldn't get stdout for %s", command)
}
stderrIn, err := cmd.StderrPipe()
if err != nil {
return nil, errors.Wrapf(err, "Couldn't get stderr for %s", command)
}
scanner := bufio.NewScanner(stdoutIn)
scanner.Split(scanLinesWithCR)
errScanner := bufio.NewScanner(stderrIn)
errScanner.Split(scanLinesWithCR)
err = cmd.Start()
if err != nil {
return nil, errors.Wrapf(err, "Couldn't start %s", command)
}
defer cmd.Process.Kill()
go processScanner(scanner, &buf, stdoutDone, callback)
go processScanner(errScanner, &buf, stderrDone, callback)
if limits != nil && limits.AddressSpaceLimit > 0 {
klog.V(3).Infof("Setting Address space limit to %d\n", limits.AddressSpaceLimit)
err = SetAddressSpaceLimit(cmd.Process.Pid, limits.AddressSpaceLimit)
if err != nil {
return nil, errors.Wrap(err, "Couldn't set address space limit")
}
}
<-stdoutDone
<-stderrDone
// The wait has to be after the reading channels are finished otherwise there is a race where the wait completes and closes stdout/err before anything
// is read from it.
err = cmd.Wait()
output := buf.Bytes()
if err != nil {
klog.Errorf("%s failed output is:\n", command)
klog.Errorf("%s\n", string(output))
return output, errors.Wrapf(err, "%s execution failed", command)
}
return output, nil
}
func prlimit(pid int, limit int, value *syscall.Rlimit) error {
_, _, e1 := syscall.RawSyscall6(syscall.SYS_PRLIMIT64, uintptr(pid), uintptr(limit), uintptr(unsafe.Pointer(value)), 0, 0, 0)
if e1 != 0 {
return errors.Wrapf(e1, "error setting prlimit on %d with value %d on pid %d", limit, value, pid)
}
return nil
}