Browse code

Lazy init useradd and remove init()

This should not have been in init() as it causes these lookups to happen
in all reexecs of the Docker binary. The only time it needs to be
resolved is when a user is added, which is extremely rare.

Docker-DCO-1.1-Signed-off-by: Phil Estes <estesp@linux.vnet.ibm.com>

Phil Estes authored on 2016/04/07 06:24:17
Showing 1 changed files
... ...
@@ -8,6 +8,7 @@ import (
8 8
 	"sort"
9 9
 	"strconv"
10 10
 	"strings"
11
+	"sync"
11 12
 )
12 13
 
13 14
 // add a user and/or group to Linux /etc/passwd, /etc/group using standard
... ...
@@ -16,6 +17,7 @@ import (
16 16
 // useradd -r -s /bin/false <username>
17 17
 
18 18
 var (
19
+	once        sync.Once
19 20
 	userCommand string
20 21
 
21 22
 	cmdTemplates = map[string]string{
... ...
@@ -31,15 +33,6 @@ var (
31 31
 	userMod           = "usermod"
32 32
 )
33 33
 
34
-func init() {
35
-	// set up which commands are used for adding users/groups dependent on distro
36
-	if _, err := resolveBinary("adduser"); err == nil {
37
-		userCommand = "adduser"
38
-	} else if _, err := resolveBinary("useradd"); err == nil {
39
-		userCommand = "useradd"
40
-	}
41
-}
42
-
43 34
 func resolveBinary(binname string) (string, error) {
44 35
 	binaryPath, err := exec.LookPath(binname)
45 36
 	if err != nil {
... ...
@@ -94,7 +87,14 @@ func AddNamespaceRangesUser(name string) (int, int, error) {
94 94
 }
95 95
 
96 96
 func addUser(userName string) error {
97
-
97
+	once.Do(func() {
98
+		// set up which commands are used for adding users/groups dependent on distro
99
+		if _, err := resolveBinary("adduser"); err == nil {
100
+			userCommand = "adduser"
101
+		} else if _, err := resolveBinary("useradd"); err == nil {
102
+			userCommand = "useradd"
103
+		}
104
+	})
98 105
 	if userCommand == "" {
99 106
 		return fmt.Errorf("Cannot add user; no useradd/adduser binary found")
100 107
 	}