Browse code

Improve logging for nsinit Docker-DCO-1.1-Signed-off-by: Michael Crosby <michael@crosbymichael.com> (github: crosbymichael)

Michael Crosby authored on 2014/02/25 11:38:24
Showing 7 changed files
... ...
@@ -11,6 +11,7 @@ import (
11 11
 	"github.com/dotcloud/docker/pkg/libcontainer/nsinit"
12 12
 	"io"
13 13
 	"io/ioutil"
14
+	"log"
14 15
 	"os"
15 16
 	"os/exec"
16 17
 	"path/filepath"
... ...
@@ -26,6 +27,7 @@ const (
26 26
 
27 27
 var (
28 28
 	ErrNotSupported = errors.New("not supported")
29
+	noOpLog         = log.New(ioutil.Discard, "[nsinit] ", log.LstdFlags)
29 30
 )
30 31
 
31 32
 func init() {
... ...
@@ -49,7 +51,8 @@ func init() {
49 49
 		if err != nil {
50 50
 			return err
51 51
 		}
52
-		if err := nsinit.Init(container, cwd, args.Console, syncPipe, args.Args); err != nil {
52
+		ns := nsinit.NewNsInit(noOpLog, "", &nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{})
53
+		if err := ns.Init(container, cwd, args.Console, syncPipe, args.Args); err != nil {
53 54
 			return err
54 55
 		}
55 56
 		return nil
... ...
@@ -90,6 +93,7 @@ func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
90 90
 			dsw:      &nsinit.DefaultStateWriter{c.Rootfs},
91 91
 		}
92 92
 	)
93
+	ns := nsinit.NewNsInit(noOpLog, "", factory, stateWriter)
93 94
 	if c.Tty {
94 95
 		term = &dockerTtyTerm{
95 96
 			pipes: pipes,
... ...
@@ -104,7 +108,7 @@ func (d *driver) Run(c *execdriver.Command, pipes *execdriver.Pipes, startCallba
104 104
 		return -1, err
105 105
 	}
106 106
 	args := append([]string{c.Entrypoint}, c.Arguments...)
107
-	return nsinit.Exec(container, factory, stateWriter, term, "", args)
107
+	return ns.Exec(container, term, args)
108 108
 }
109 109
 
110 110
 func (d *driver) Kill(p *execdriver.Command, sig int) error {
... ...
@@ -4,14 +4,12 @@ import (
4 4
 	"fmt"
5 5
 	"github.com/dotcloud/docker/pkg/libcontainer"
6 6
 	"github.com/dotcloud/docker/pkg/libcontainer/utils"
7
-	"log"
8 7
 )
9 8
 
10 9
 type Veth struct {
11 10
 }
12 11
 
13 12
 func (v *Veth) Create(n *libcontainer.Network, nspid int) (libcontainer.Context, error) {
14
-	log.Printf("creating veth network")
15 13
 	var (
16 14
 		bridge string
17 15
 		prefix string
... ...
@@ -31,7 +29,6 @@ func (v *Veth) Create(n *libcontainer.Network, nspid int) (libcontainer.Context,
31 31
 		"vethHost":  name1,
32 32
 		"vethChild": name2,
33 33
 	}
34
-	log.Printf("veth pair created %s <> %s", name1, name2)
35 34
 	if err := SetInterfaceMaster(name1, bridge); err != nil {
36 35
 		return context, err
37 36
 	}
... ...
@@ -41,7 +38,6 @@ func (v *Veth) Create(n *libcontainer.Network, nspid int) (libcontainer.Context,
41 41
 	if err := InterfaceUp(name1); err != nil {
42 42
 		return context, err
43 43
 	}
44
-	log.Printf("setting %s inside %d namespace", name2, nspid)
45 44
 	if err := SetInterfaceInNamespacePid(name2, nspid); err != nil {
46 45
 		return context, err
47 46
 	}
... ...
@@ -6,7 +6,6 @@ import (
6 6
 	"github.com/dotcloud/docker/pkg/libcontainer"
7 7
 	"github.com/dotcloud/docker/pkg/libcontainer/network"
8 8
 	"github.com/dotcloud/docker/pkg/system"
9
-	"log"
10 9
 	"os"
11 10
 	"os/exec"
12 11
 	"syscall"
... ...
@@ -14,9 +13,7 @@ import (
14 14
 
15 15
 // Exec performes setup outside of a namespace so that a container can be
16 16
 // executed.  Exec is a high level function for working with container namespaces.
17
-func Exec(container *libcontainer.Container,
18
-	factory CommandFactory, state StateWriter, term Terminal,
19
-	logFile string, args []string) (int, error) {
17
+func (ns *linuxNs) Exec(container *libcontainer.Container, term Terminal, args []string) (int, error) {
20 18
 	var (
21 19
 		master  *os.File
22 20
 		console string
... ...
@@ -31,7 +28,7 @@ func Exec(container *libcontainer.Container,
31 31
 	}
32 32
 
33 33
 	if container.Tty {
34
-		log.Printf("setting up master and console")
34
+		ns.logger.Printf("setting up master and console")
35 35
 		master, console, err = CreateMasterAndConsole()
36 36
 		if err != nil {
37 37
 			return -1, err
... ...
@@ -39,54 +36,56 @@ func Exec(container *libcontainer.Container,
39 39
 		term.SetMaster(master)
40 40
 	}
41 41
 
42
-	command := factory.Create(container, console, logFile, syncPipe.child.Fd(), args)
42
+	command := ns.commandFactory.Create(container, console, ns.logFile, syncPipe.child.Fd(), args)
43 43
 	if err := term.Attach(command); err != nil {
44 44
 		return -1, err
45 45
 	}
46 46
 	defer term.Close()
47 47
 
48
-	log.Printf("staring init")
48
+	ns.logger.Printf("staring init")
49 49
 	if err := command.Start(); err != nil {
50 50
 		return -1, err
51 51
 	}
52
-	log.Printf("writing state file")
53
-	if err := state.WritePid(command.Process.Pid); err != nil {
52
+	ns.logger.Printf("writing state file")
53
+	if err := ns.stateWriter.WritePid(command.Process.Pid); err != nil {
54 54
 		command.Process.Kill()
55 55
 		return -1, err
56 56
 	}
57 57
 	defer func() {
58
-		log.Printf("removing state file")
59
-		state.DeletePid()
58
+		ns.logger.Printf("removing state file")
59
+		ns.stateWriter.DeletePid()
60 60
 	}()
61 61
 
62 62
 	// Do this before syncing with child so that no children
63 63
 	// can escape the cgroup
64
-	if err := SetupCgroups(container, command.Process.Pid); err != nil {
64
+	if err := ns.SetupCgroups(container, command.Process.Pid); err != nil {
65 65
 		command.Process.Kill()
66 66
 		return -1, err
67 67
 	}
68
-	if err := InitializeNetworking(container, command.Process.Pid, syncPipe); err != nil {
68
+	if err := ns.InitializeNetworking(container, command.Process.Pid, syncPipe); err != nil {
69 69
 		command.Process.Kill()
70 70
 		return -1, err
71 71
 	}
72 72
 
73 73
 	// Sync with child
74
-	log.Printf("closing sync pipes")
74
+	ns.logger.Printf("closing sync pipes")
75 75
 	syncPipe.Close()
76 76
 
77
-	log.Printf("waiting on process")
77
+	ns.logger.Printf("waiting on process")
78 78
 	if err := command.Wait(); err != nil {
79 79
 		if _, ok := err.(*exec.ExitError); !ok {
80 80
 			return -1, err
81 81
 		}
82 82
 	}
83
-	log.Printf("process ended")
84
-	return command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus(), nil
83
+
84
+	exitCode := command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus()
85
+	ns.logger.Printf("process ended with exit code %d", exitCode)
86
+	return exitCode, nil
85 87
 }
86 88
 
87
-func SetupCgroups(container *libcontainer.Container, nspid int) error {
89
+func (ns *linuxNs) SetupCgroups(container *libcontainer.Container, nspid int) error {
88 90
 	if container.Cgroups != nil {
89
-		log.Printf("setting up cgroups")
91
+		ns.logger.Printf("setting up cgroups")
90 92
 		if err := container.Cgroups.Apply(nspid); err != nil {
91 93
 			return err
92 94
 		}
... ...
@@ -94,9 +93,9 @@ func SetupCgroups(container *libcontainer.Container, nspid int) error {
94 94
 	return nil
95 95
 }
96 96
 
97
-func InitializeNetworking(container *libcontainer.Container, nspid int, pipe *SyncPipe) error {
97
+func (ns *linuxNs) InitializeNetworking(container *libcontainer.Container, nspid int, pipe *SyncPipe) error {
98 98
 	if container.Network != nil {
99
-		log.Printf("creating host network configuration type %s", container.Network.Type)
99
+		ns.logger.Printf("creating host network configuration type %s", container.Network.Type)
100 100
 		strategy, err := network.GetStrategy(container.Network.Type)
101 101
 		if err != nil {
102 102
 			return err
... ...
@@ -105,7 +104,7 @@ func InitializeNetworking(container *libcontainer.Container, nspid int, pipe *Sy
105 105
 		if err != nil {
106 106
 			return err
107 107
 		}
108
-		log.Printf("sending %v as network context", networkContext)
108
+		ns.logger.Printf("sending %v as network context", networkContext)
109 109
 		if err := pipe.SendToChild(networkContext); err != nil {
110 110
 			return err
111 111
 		}
... ...
@@ -12,7 +12,7 @@ import (
12 12
 )
13 13
 
14 14
 // ExecIn uses an existing pid and joins the pid's namespaces with the new command.
15
-func ExecIn(container *libcontainer.Container, nspid int, args []string) (int, error) {
15
+func (ns *linuxNs) ExecIn(container *libcontainer.Container, nspid int, args []string) (int, error) {
16 16
 	for _, ns := range container.Namespaces {
17 17
 		if err := system.Unshare(namespaceMap[ns]); err != nil {
18 18
 			return -1, err
... ...
@@ -17,7 +17,7 @@ import (
17 17
 
18 18
 // Init is the init process that first runs inside a new namespace to setup mounts, users, networking,
19 19
 // and other options required for the new container.
20
-func Init(container *libcontainer.Container, uncleanRootfs, console string, syncPipe *SyncPipe, args []string) error {
20
+func (ns *linuxNs) Init(container *libcontainer.Container, uncleanRootfs, console string, syncPipe *SyncPipe, args []string) error {
21 21
 	rootfs, err := resolveRootfs(uncleanRootfs)
22 22
 	if err != nil {
23 23
 		return err
24 24
new file mode 100644
... ...
@@ -0,0 +1,29 @@
0
+package nsinit
1
+
2
+import (
3
+	"github.com/dotcloud/docker/pkg/libcontainer"
4
+	"log"
5
+)
6
+
7
+type NsInit interface {
8
+	Exec(container *libcontainer.Container, term Terminal, args []string) (int, error)
9
+	ExecIn(container *libcontainer.Container, nspid int, args []string) (int, error)
10
+	Init(container *libcontainer.Container, uncleanRootfs, console string, syncPipe *SyncPipe, args []string) error
11
+}
12
+
13
+type linuxNs struct {
14
+	root           string
15
+	logFile        string
16
+	logger         *log.Logger
17
+	commandFactory CommandFactory
18
+	stateWriter    StateWriter
19
+}
20
+
21
+func NewNsInit(logger *log.Logger, logFile string, command CommandFactory, state StateWriter) NsInit {
22
+	return &linuxNs{
23
+		logger:         logger,
24
+		commandFactory: command,
25
+		stateWriter:    state,
26
+		logFile:        logFile,
27
+	}
28
+}
... ...
@@ -42,13 +42,13 @@ func main() {
42 42
 	if err != nil {
43 43
 		log.Fatal(err)
44 44
 	}
45
-	if err := setupLogging(); err != nil {
45
+	ns, err := newNsInit()
46
+	if err != nil {
46 47
 		log.Fatal(err)
47 48
 	}
49
+
48 50
 	switch flag.Arg(0) {
49 51
 	case "exec": // this is executed outside of the namespace in the cwd
50
-		log.SetPrefix("[nsinit exec] ")
51
-
52 52
 		var exitCode int
53 53
 		nspid, err := readPid()
54 54
 		if err != nil {
... ...
@@ -57,20 +57,16 @@ func main() {
57 57
 			}
58 58
 		}
59 59
 		if nspid > 0 {
60
-			exitCode, err = nsinit.ExecIn(container, nspid, flag.Args()[1:])
60
+			exitCode, err = ns.ExecIn(container, nspid, flag.Args()[1:])
61 61
 		} else {
62 62
 			term := nsinit.NewTerminal(os.Stdin, os.Stdout, os.Stderr, container.Tty)
63
-			exitCode, err = nsinit.Exec(container,
64
-				&nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{},
65
-				term,
66
-				logFile, flag.Args()[1:])
63
+			exitCode, err = ns.Exec(container, term, flag.Args()[1:])
67 64
 		}
68 65
 		if err != nil {
69 66
 			log.Fatal(err)
70 67
 		}
71 68
 		os.Exit(exitCode)
72 69
 	case "init": // this is executed inside of the namespace to setup the container
73
-		log.SetPrefix("[nsinit init] ")
74 70
 		cwd, err := os.Getwd()
75 71
 		if err != nil {
76 72
 			log.Fatal(err)
... ...
@@ -82,7 +78,7 @@ func main() {
82 82
 		if err != nil {
83 83
 			log.Fatal(err)
84 84
 		}
85
-		if err := nsinit.Init(container, cwd, console, syncPipe, flag.Args()[1:]); err != nil {
85
+		if err := ns.Init(container, cwd, console, syncPipe, flag.Args()[1:]); err != nil {
86 86
 			log.Fatal(err)
87 87
 		}
88 88
 	default:
... ...
@@ -116,19 +112,27 @@ func readPid() (int, error) {
116 116
 	return pid, nil
117 117
 }
118 118
 
119
-func setupLogging() (err error) {
119
+func newNsInit() (nsinit.NsInit, error) {
120
+	logger, err := setupLogging()
121
+	if err != nil {
122
+		return nil, err
123
+	}
124
+	return nsinit.NewNsInit(logger, logFile, &nsinit.DefaultCommandFactory{}, &nsinit.DefaultStateWriter{}), nil
125
+}
126
+
127
+func setupLogging() (logger *log.Logger, err error) {
120 128
 	var writer io.Writer
129
+
121 130
 	switch logFile {
122 131
 	case "stderr":
123 132
 		writer = os.Stderr
124 133
 	case "none", "":
125 134
 		writer = ioutil.Discard
126 135
 	default:
127
-		writer, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755)
128
-		if err != nil {
129
-			return err
136
+		if writer, err = os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0755); err != nil {
137
+			return
130 138
 		}
131 139
 	}
132
-	log.SetOutput(writer)
133
-	return nil
140
+	logger = log.New(writer, "", log.LstdFlags)
141
+	return
134 142
 }