forked from apptainer/singularity
/
clean.go
87 lines (72 loc) · 2.36 KB
/
clean.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
// Copyright (c) 2018, Sylabs Inc. All rights reserved.
// This software is licensed under a 3-clause BSD license. Please consult the
// LICENSE.md file distributed with the sources of this project regarding your
// rights to use or distribute this software.
package env
import (
"os"
"strings"
"github.com/opencontainers/runtime-tools/generate"
"github.com/sylabs/singularity/internal/pkg/sylog"
)
const (
envPrefix = "SINGULARITYENV_"
)
var alwaysPassKeys = map[string]bool{
"TERM": true,
"http_proxy": true,
"HTTP_PROXY": true,
"https_proxy": true,
"HTTPS_PROXY": true,
"no_proxy": true,
"NO_PROXY": true,
"all_proxy": true,
"ALL_PROXY": true,
"ftp_proxy": true,
"FTP_PROXY": true,
}
// SetContainerEnv cleans environment variables before running the container
func SetContainerEnv(g *generate.Generator, env []string, cleanEnv bool, homeDest string) {
// first deal with special variables that allow user to control $PATH at
// runtime (meh... special cases)
if prependPath := os.Getenv("SINGULARITYENV_PREPEND_PATH"); prependPath != "" {
g.AddProcessEnv("SING_USER_DEFINED_PREPEND_PATH", prependPath)
}
if appendPath := os.Getenv("SINGULARITYENV_APPEND_PATH"); appendPath != "" {
g.AddProcessEnv("SING_USER_DEFINED_APPEND_PATH", appendPath)
}
if userPath := os.Getenv("SINGULARITYENV_PATH"); userPath != "" {
g.AddProcessEnv("SING_USER_DEFINED_PATH", userPath)
}
for _, env := range env {
e := strings.SplitN(env, "=", 2)
if len(e) != 2 {
sylog.Verbosef("Can't process environment variable %s", env)
continue
}
if e[0] == "SINGULARITYENV_PREPEND_PATH" ||
e[0] == "SINGULARITYENV_APPEND_PATH" ||
e[0] == "SINGULARITYENV_PATH" {
sylog.Verbosef("Not adding special case PATH control variable %s to container environment", e[0])
continue
}
// Transpose host env variables into config
if addKey, ok := addIfReq(e[0], cleanEnv); ok {
g.AddProcessEnv(addKey, e[1])
}
}
g.AddProcessEnv("HOME", homeDest)
g.AddProcessEnv("PATH", "/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin")
// Set LANG env
if cleanEnv {
g.AddProcessEnv("LANG", "C")
}
}
func addIfReq(key string, cleanEnv bool) (string, bool) {
if strings.HasPrefix(key, envPrefix) {
return strings.TrimPrefix(key, envPrefix), true
} else if _, ok := alwaysPassKeys[key]; cleanEnv && !ok {
return "", false
}
return key, true
}