Browse code

libcontainer: Create dirs/files as needed for bind mounts

If you specify a bind mount in a place that doesn't have a file yet we
create that (and parent directories). This is needed because otherwise
you can't use volumes like e.g. /dev/log, as that gets covered by the
/dev tmpfs mounts.

Docker-DCO-1.1-Signed-off-by: Alexander Larsson <alexl@redhat.com> (github: alexlarsson)

Alexander Larsson authored on 2014/05/09 02:58:33
Showing 1 changed files
... ...
@@ -91,6 +91,28 @@ func mountSystem(rootfs string, container *libcontainer.Container) error {
91 91
 	return nil
92 92
 }
93 93
 
94
+func createIfNotExists(path string, isDir bool) error {
95
+	if _, err := os.Stat(path); err != nil {
96
+		if os.IsNotExist(err) {
97
+			if isDir {
98
+				if err := os.MkdirAll(path, 0755); err != nil {
99
+					return err
100
+				}
101
+			} else {
102
+				if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
103
+					return err
104
+				}
105
+				f, err := os.OpenFile(path, os.O_CREATE, 0755)
106
+				if err != nil {
107
+					return err
108
+				}
109
+				f.Close()
110
+			}
111
+		}
112
+	}
113
+	return nil
114
+}
115
+
94 116
 func setupBindmounts(rootfs string, bindMounts libcontainer.Mounts) error {
95 117
 	for _, m := range bindMounts.OfType("bind") {
96 118
 		var (
... ...
@@ -100,6 +122,15 @@ func setupBindmounts(rootfs string, bindMounts libcontainer.Mounts) error {
100 100
 		if !m.Writable {
101 101
 			flags = flags | syscall.MS_RDONLY
102 102
 		}
103
+
104
+		stat, err := os.Stat(m.Source)
105
+		if err != nil {
106
+			return err
107
+		}
108
+		if err := createIfNotExists(dest, stat.IsDir()); err != nil {
109
+			return fmt.Errorf("Creating new bind-mount target, %s\n", err)
110
+		}
111
+
103 112
 		if err := system.Mount(m.Source, dest, "bind", uintptr(flags), ""); err != nil {
104 113
 			return fmt.Errorf("mounting %s into %s %s", m.Source, dest, err)
105 114
 		}