Skip to content

Commit ad32b35

Browse files
committed
libct: change Process.Env handling
Current implementation sets all the environment variables passed in Process.Env in the current process, then uses os.Environ to read those back. As pointed out in [1], this is slow, as runc calls os.Setenv for every variable, and there may be a few thousands of those. Looking into why it was implemented, I found commit 9744d72 and traced it to [2], which discusses the actual reasons. At the time were: - HOME is not passed into container as it is set in setupUser by os.Setenv and has no effect on config.Env; - there is no deduplication of environment variables. Yet it was decided to not go ahead with this patch, but later [3] was merged with the carry of this patch. Now, from what I see: 1. Passing environment to exec is way faster than using os.Setenv and os.Environment() (tests show ~20x faster in simple Go test, and 2x faster in real-world test, see below). 2. Setting environment variables in the runc context can result is ugly side effects (think GODEBUG). 3. Nothing in runtime spec says that the environment needs to be deduplicated, or the order of preference (whether the first or the last value of a variable with the same name is to be used). In C (Linux/glibc), the first value is used. In Go, it's the last one. We should probably stick to what we have in order to maintain backward compatibility. This patch: - switches to passing env directly to exec; - adds deduplication mechanism to retain backward compatibility; - sets PATH from process.Env in the current process; - adds HOME to process.Env if not set; - removes os.Clearenv call as it's no longer needed. The benchmark added by the previous commit shows 2x improvement: name old time/op new time/op delta ExecInBigEnv-20 60.2ms ± 2% 27.4ms ±20% -54.42% (p=0.000 n=8+9) The remaining questions are: - are there any potential regressions (for example, from not setting values from process.Env to the current process); - should deduplication show warnings (maybe promoted to errors later); - whether a default for PATH (e.g "/bin:/usr/bin" should be added, when PATH is not set. [1] opencontainers#1983 [2] docker-archive/libcontainer#418 [3] docker-archive/libcontainer#432 Signed-off-by: Kir Kolyshkin <[email protected]>
1 parent fd05661 commit ad32b35

File tree

4 files changed

+101
-38
lines changed

4 files changed

+101
-38
lines changed

libcontainer/init_linux.go

Lines changed: 53 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import (
1010
"path/filepath"
1111
"runtime"
1212
"runtime/debug"
13+
"slices"
1314
"strconv"
1415
"strings"
1516
"syscall"
@@ -196,10 +197,6 @@ func startInitialization() (retErr error) {
196197
dmzExe = os.NewFile(uintptr(dmzFd), "runc-dmz")
197198
}
198199

199-
// clear the current process's environment to clean any libcontainer
200-
// specific env vars.
201-
os.Clearenv()
202-
203200
defer func() {
204201
if err := recover(); err != nil {
205202
if err2, ok := err.(error); ok {
@@ -220,9 +217,11 @@ func startInitialization() (retErr error) {
220217
}
221218

222219
func containerInit(t initType, config *initConfig, pipe *syncSocket, consoleSocket, pidfdSocket, fifoFile, logPipe, dmzExe *os.File) error {
223-
if err := populateProcessEnvironment(config.Env); err != nil {
220+
env, homeSet, err := prepareEnv(config.Env)
221+
if err != nil {
224222
return err
225223
}
224+
config.Env = env
226225

227226
// Clean the RLIMIT_NOFILE cache in go runtime.
228227
// Issue: https://github.com/opencontainers/runc/issues/4195
@@ -237,6 +236,7 @@ func containerInit(t initType, config *initConfig, pipe *syncSocket, consoleSock
237236
config: config,
238237
logPipe: logPipe,
239238
dmzExe: dmzExe,
239+
addHome: !homeSet,
240240
}
241241
return i.Init()
242242
case initStandard:
@@ -249,35 +249,57 @@ func containerInit(t initType, config *initConfig, pipe *syncSocket, consoleSock
249249
fifoFile: fifoFile,
250250
logPipe: logPipe,
251251
dmzExe: dmzExe,
252+
addHome: !homeSet,
252253
}
253254
return i.Init()
254255
}
255256
return fmt.Errorf("unknown init type %q", t)
256257
}
257258

258-
// populateProcessEnvironment loads the provided environment variables into the
259-
// current processes's environment.
260-
func populateProcessEnvironment(env []string) error {
261-
for _, pair := range env {
262-
p := strings.SplitN(pair, "=", 2)
263-
if len(p) < 2 {
264-
return errors.New("invalid environment variable: missing '='")
259+
// prepareEnv checks supplied environment variables for validity, removes
260+
// duplicates in place (leaving the last value only), and sets PATH from env,
261+
// if found. Returns a flag telling if HOME is found in env.
262+
func prepareEnv(env []string) (newEnv []string, homeSet bool, _ error) {
263+
if env == nil {
264+
return nil, false, nil
265+
}
266+
envs := make(map[string]int)
267+
var dups []int
268+
269+
for i, pair := range env {
270+
j := strings.IndexByte(pair, '=')
271+
if j == -1 {
272+
return nil, false, errors.New("invalid environment variable: missing '='")
265273
}
266-
name, val := p[0], p[1]
267-
if name == "" {
268-
return errors.New("invalid environment variable: name cannot be empty")
274+
if j == 0 {
275+
return nil, false, errors.New("invalid environment variable: name cannot be empty")
269276
}
270-
if strings.IndexByte(name, 0) >= 0 {
271-
return fmt.Errorf("invalid environment variable %q: name contains nul byte (\\x00)", name)
277+
key := pair[:j]
278+
if strings.IndexByte(pair, 0) >= 0 {
279+
return nil, false, fmt.Errorf("invalid environment variable %q: contains nul byte (\\x00)", key)
272280
}
273-
if strings.IndexByte(val, 0) >= 0 {
274-
return fmt.Errorf("invalid environment variable %q: value contains nul byte (\\x00)", name)
281+
if last, ok := envs[key]; ok {
282+
dups = append(dups, last)
275283
}
276-
if err := os.Setenv(name, val); err != nil {
277-
return err
284+
envs[key] = i
285+
}
286+
287+
// Check if HOME is set.
288+
_, homeSet = envs["HOME"]
289+
// Set PATH from env, unless empty.
290+
if i, ok := envs["PATH"]; ok {
291+
if err := os.Setenv("PATH", env[i][5:]); err != nil {
292+
return nil, false, err
278293
}
279294
}
280-
return nil
295+
296+
// Remove duplicates, starting from the rightmost one.
297+
slices.SortFunc(dups, func(a, b int) int { return b - a })
298+
for _, rm := range dups {
299+
env = append(env[:rm], env[rm+1:]...)
300+
}
301+
302+
return env, homeSet, nil
281303
}
282304

283305
// verifyCwd ensures that the current directory is actually inside the mount
@@ -308,8 +330,8 @@ func verifyCwd() error {
308330

309331
// finalizeNamespace drops the caps, sets the correct user
310332
// and working dir, and closes any leaked file descriptors
311-
// before executing the command inside the namespace
312-
func finalizeNamespace(config *initConfig) error {
333+
// before executing the command inside the namespace.
334+
func finalizeNamespace(config *initConfig, addHome bool) error {
313335
// Ensure that all unwanted fds we may have accidentally
314336
// inherited are marked close-on-exec so they stay out of the
315337
// container
@@ -355,7 +377,7 @@ func finalizeNamespace(config *initConfig) error {
355377
if err := system.SetKeepCaps(); err != nil {
356378
return fmt.Errorf("unable to set keep caps: %w", err)
357379
}
358-
if err := setupUser(config); err != nil {
380+
if err := setupUser(config, addHome); err != nil {
359381
return fmt.Errorf("unable to setup user: %w", err)
360382
}
361383
// Change working directory AFTER the user has been set up, if we haven't done it yet.
@@ -473,8 +495,9 @@ func syncParentSeccomp(pipe *syncSocket, seccompFd *os.File) error {
473495
return readSync(pipe, procSeccompDone)
474496
}
475497

476-
// setupUser changes the groups, gid, and uid for the user inside the container
477-
func setupUser(config *initConfig) error {
498+
// setupUser changes the groups, gid, and uid for the user inside the container,
499+
// and appends user's HOME to config.Env if addHome is true.
500+
func setupUser(config *initConfig, addHome bool) error {
478501
// Set up defaults.
479502
defaultExecUser := user.ExecUser{
480503
Uid: 0,
@@ -555,11 +578,9 @@ func setupUser(config *initConfig) error {
555578
return err
556579
}
557580

558-
// if we didn't get HOME already, set it based on the user's HOME
559-
if envHome := os.Getenv("HOME"); envHome == "" {
560-
if err := os.Setenv("HOME", execUser.Home); err != nil {
561-
return err
562-
}
581+
// If we didn't get HOME already, set it based on the user's HOME.
582+
if addHome {
583+
config.Env = append(config.Env, "HOME="+execUser.Home)
563584
}
564585
return nil
565586
}

libcontainer/init_linux_test.go

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
package libcontainer
2+
3+
import (
4+
"slices"
5+
"testing"
6+
)
7+
8+
func TestPrepareEnvDedup(t *testing.T) {
9+
tests := []struct {
10+
env, wantEnv []string
11+
}{
12+
{
13+
env: []string{},
14+
wantEnv: []string{},
15+
},
16+
{
17+
env: []string{"HOME=/root", "FOO=bar"},
18+
wantEnv: []string{"HOME=/root", "FOO=bar"},
19+
},
20+
{
21+
env: []string{"A=a", "A=b", "A=c"},
22+
wantEnv: []string{"A=c"},
23+
},
24+
{
25+
env: []string{"TERM=vt100", "HOME=/home/one", "HOME=/home/two", "TERM=xterm", "HOME=/home/three", "FOO=bar"},
26+
wantEnv: []string{"TERM=xterm", "HOME=/home/three", "FOO=bar"},
27+
},
28+
}
29+
30+
for _, tc := range tests {
31+
env, _, err := prepareEnv(tc.env)
32+
if err != nil {
33+
t.Error(err)
34+
continue
35+
}
36+
if !slices.Equal(env, tc.wantEnv) {
37+
t.Errorf("want %v, got %v", tc.wantEnv, env)
38+
}
39+
}
40+
}

libcontainer/setns_init_linux.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ type linuxSetnsInit struct {
2626
config *initConfig
2727
logPipe *os.File
2828
dmzExe *os.File
29+
addHome bool
2930
}
3031

3132
func (l *linuxSetnsInit) getSessionRingName() string {
@@ -101,7 +102,7 @@ func (l *linuxSetnsInit) Init() error {
101102
return err
102103
}
103104
}
104-
if err := finalizeNamespace(l.config); err != nil {
105+
if err := finalizeNamespace(l.config, l.addHome); err != nil {
105106
return err
106107
}
107108
if err := apparmor.ApplyProfile(l.config.AppArmorProfile); err != nil {
@@ -143,7 +144,7 @@ func (l *linuxSetnsInit) Init() error {
143144

144145
if l.dmzExe != nil {
145146
l.config.Args[0] = name
146-
return system.Fexecve(l.dmzExe.Fd(), l.config.Args, os.Environ())
147+
return system.Fexecve(l.dmzExe.Fd(), l.config.Args, l.config.Env)
147148
}
148149
// Close all file descriptors we are not passing to the container. This is
149150
// necessary because the execve target could use internal runc fds as the
@@ -163,5 +164,5 @@ func (l *linuxSetnsInit) Init() error {
163164
if err := utils.UnsafeCloseFrom(l.config.PassedFilesCount + 3); err != nil {
164165
return err
165166
}
166-
return system.Exec(name, l.config.Args, os.Environ())
167+
return system.Exec(name, l.config.Args, l.config.Env)
167168
}

libcontainer/standard_init_linux.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ type linuxStandardInit struct {
2828
logPipe *os.File
2929
dmzExe *os.File
3030
config *initConfig
31+
addHome bool
3132
}
3233

3334
func (l *linuxStandardInit) getSessionRingParams() (string, uint32, uint32) {
@@ -190,7 +191,7 @@ func (l *linuxStandardInit) Init() error {
190191
return err
191192
}
192193
}
193-
if err := finalizeNamespace(l.config); err != nil {
194+
if err := finalizeNamespace(l.config, l.addHome); err != nil {
194195
return err
195196
}
196197
// finalizeNamespace can change user/group which clears the parent death
@@ -277,7 +278,7 @@ func (l *linuxStandardInit) Init() error {
277278

278279
if l.dmzExe != nil {
279280
l.config.Args[0] = name
280-
return system.Fexecve(l.dmzExe.Fd(), l.config.Args, os.Environ())
281+
return system.Fexecve(l.dmzExe.Fd(), l.config.Args, l.config.Env)
281282
}
282283
// Close all file descriptors we are not passing to the container. This is
283284
// necessary because the execve target could use internal runc fds as the
@@ -297,5 +298,5 @@ func (l *linuxStandardInit) Init() error {
297298
if err := utils.UnsafeCloseFrom(l.config.PassedFilesCount + 3); err != nil {
298299
return err
299300
}
300-
return system.Exec(name, l.config.Args, os.Environ())
301+
return system.Exec(name, l.config.Args, l.config.Env)
301302
}

0 commit comments

Comments
 (0)