github.com/kobeld/docker@v1.12.0-rc1/daemon/graphdriver/aufs/aufs.go (about)

     1  // +build linux
     2  
     3  /*
     4  
     5  aufs driver directory structure
     6  
     7    .
     8    ├── layers // Metadata of layers
     9    │   ├── 1
    10    │   ├── 2
    11    │   └── 3
    12    ├── diff  // Content of the layer
    13    │   ├── 1  // Contains layers that need to be mounted for the id
    14    │   ├── 2
    15    │   └── 3
    16    └── mnt    // Mount points for the rw layers to be mounted
    17        ├── 1
    18        ├── 2
    19        └── 3
    20  
    21  */
    22  
    23  package aufs
    24  
    25  import (
    26  	"bufio"
    27  	"fmt"
    28  	"io/ioutil"
    29  	"os"
    30  	"os/exec"
    31  	"path"
    32  	"path/filepath"
    33  	"strings"
    34  	"sync"
    35  	"syscall"
    36  
    37  	"github.com/Sirupsen/logrus"
    38  	"github.com/vbatts/tar-split/tar/storage"
    39  
    40  	"github.com/docker/docker/daemon/graphdriver"
    41  	"github.com/docker/docker/pkg/archive"
    42  	"github.com/docker/docker/pkg/chrootarchive"
    43  	"github.com/docker/docker/pkg/directory"
    44  	"github.com/docker/docker/pkg/idtools"
    45  	mountpk "github.com/docker/docker/pkg/mount"
    46  	"github.com/docker/docker/pkg/stringid"
    47  
    48  	"github.com/opencontainers/runc/libcontainer/label"
    49  	rsystem "github.com/opencontainers/runc/libcontainer/system"
    50  )
    51  
    52  var (
    53  	// ErrAufsNotSupported is returned if aufs is not supported by the host.
    54  	ErrAufsNotSupported = fmt.Errorf("AUFS was not found in /proc/filesystems")
    55  	// ErrAufsNested means aufs cannot be used bc we are in a user namespace
    56  	ErrAufsNested = fmt.Errorf("AUFS cannot be used in non-init user namespace")
    57  	backingFs     = "<unknown>"
    58  
    59  	enableDirpermLock sync.Once
    60  	enableDirperm     bool
    61  )
    62  
    63  func init() {
    64  	graphdriver.Register("aufs", Init)
    65  }
    66  
    67  // Driver contains information about the filesystem mounted.
    68  type Driver struct {
    69  	sync.Mutex
    70  	root          string
    71  	uidMaps       []idtools.IDMap
    72  	gidMaps       []idtools.IDMap
    73  	ctr           *graphdriver.RefCounter
    74  	pathCacheLock sync.Mutex
    75  	pathCache     map[string]string
    76  }
    77  
    78  // Init returns a new AUFS driver.
    79  // An error is returned if AUFS is not supported.
    80  func Init(root string, options []string, uidMaps, gidMaps []idtools.IDMap) (graphdriver.Driver, error) {
    81  
    82  	// Try to load the aufs kernel module
    83  	if err := supportsAufs(); err != nil {
    84  		return nil, graphdriver.ErrNotSupported
    85  	}
    86  
    87  	fsMagic, err := graphdriver.GetFSMagic(root)
    88  	if err != nil {
    89  		return nil, err
    90  	}
    91  	if fsName, ok := graphdriver.FsNames[fsMagic]; ok {
    92  		backingFs = fsName
    93  	}
    94  
    95  	switch fsMagic {
    96  	case graphdriver.FsMagicAufs, graphdriver.FsMagicBtrfs, graphdriver.FsMagicEcryptfs:
    97  		logrus.Errorf("AUFS is not supported over %s", backingFs)
    98  		return nil, graphdriver.ErrIncompatibleFS
    99  	}
   100  
   101  	paths := []string{
   102  		"mnt",
   103  		"diff",
   104  		"layers",
   105  	}
   106  
   107  	a := &Driver{
   108  		root:      root,
   109  		uidMaps:   uidMaps,
   110  		gidMaps:   gidMaps,
   111  		pathCache: make(map[string]string),
   112  		ctr:       graphdriver.NewRefCounter(graphdriver.NewFsChecker(graphdriver.FsMagicAufs)),
   113  	}
   114  
   115  	rootUID, rootGID, err := idtools.GetRootUIDGID(uidMaps, gidMaps)
   116  	if err != nil {
   117  		return nil, err
   118  	}
   119  	// Create the root aufs driver dir and return
   120  	// if it already exists
   121  	// If not populate the dir structure
   122  	if err := idtools.MkdirAllAs(root, 0700, rootUID, rootGID); err != nil {
   123  		if os.IsExist(err) {
   124  			return a, nil
   125  		}
   126  		return nil, err
   127  	}
   128  
   129  	if err := mountpk.MakePrivate(root); err != nil {
   130  		return nil, err
   131  	}
   132  
   133  	// Populate the dir structure
   134  	for _, p := range paths {
   135  		if err := idtools.MkdirAllAs(path.Join(root, p), 0700, rootUID, rootGID); err != nil {
   136  			return nil, err
   137  		}
   138  	}
   139  	return a, nil
   140  }
   141  
   142  // Return a nil error if the kernel supports aufs
   143  // We cannot modprobe because inside dind modprobe fails
   144  // to run
   145  func supportsAufs() error {
   146  	// We can try to modprobe aufs first before looking at
   147  	// proc/filesystems for when aufs is supported
   148  	exec.Command("modprobe", "aufs").Run()
   149  
   150  	if rsystem.RunningInUserNS() {
   151  		return ErrAufsNested
   152  	}
   153  
   154  	f, err := os.Open("/proc/filesystems")
   155  	if err != nil {
   156  		return err
   157  	}
   158  	defer f.Close()
   159  
   160  	s := bufio.NewScanner(f)
   161  	for s.Scan() {
   162  		if strings.Contains(s.Text(), "aufs") {
   163  			return nil
   164  		}
   165  	}
   166  	return ErrAufsNotSupported
   167  }
   168  
   169  func (a *Driver) rootPath() string {
   170  	return a.root
   171  }
   172  
   173  func (*Driver) String() string {
   174  	return "aufs"
   175  }
   176  
   177  // Status returns current information about the filesystem such as root directory, number of directories mounted, etc.
   178  func (a *Driver) Status() [][2]string {
   179  	ids, _ := loadIds(path.Join(a.rootPath(), "layers"))
   180  	return [][2]string{
   181  		{"Root Dir", a.rootPath()},
   182  		{"Backing Filesystem", backingFs},
   183  		{"Dirs", fmt.Sprintf("%d", len(ids))},
   184  		{"Dirperm1 Supported", fmt.Sprintf("%v", useDirperm())},
   185  	}
   186  }
   187  
   188  // GetMetadata not implemented
   189  func (a *Driver) GetMetadata(id string) (map[string]string, error) {
   190  	return nil, nil
   191  }
   192  
   193  // Exists returns true if the given id is registered with
   194  // this driver
   195  func (a *Driver) Exists(id string) bool {
   196  	if _, err := os.Lstat(path.Join(a.rootPath(), "layers", id)); err != nil {
   197  		return false
   198  	}
   199  	return true
   200  }
   201  
   202  // CreateReadWrite creates a layer that is writable for use as a container
   203  // file system.
   204  func (a *Driver) CreateReadWrite(id, parent, mountLabel string, storageOpt map[string]string) error {
   205  	return a.Create(id, parent, mountLabel, storageOpt)
   206  }
   207  
   208  // Create three folders for each id
   209  // mnt, layers, and diff
   210  func (a *Driver) Create(id, parent, mountLabel string, storageOpt map[string]string) error {
   211  
   212  	if len(storageOpt) != 0 {
   213  		return fmt.Errorf("--storage-opt is not supported for aufs")
   214  	}
   215  
   216  	if err := a.createDirsFor(id); err != nil {
   217  		return err
   218  	}
   219  	// Write the layers metadata
   220  	f, err := os.Create(path.Join(a.rootPath(), "layers", id))
   221  	if err != nil {
   222  		return err
   223  	}
   224  	defer f.Close()
   225  
   226  	if parent != "" {
   227  		ids, err := getParentIds(a.rootPath(), parent)
   228  		if err != nil {
   229  			return err
   230  		}
   231  
   232  		if _, err := fmt.Fprintln(f, parent); err != nil {
   233  			return err
   234  		}
   235  		for _, i := range ids {
   236  			if _, err := fmt.Fprintln(f, i); err != nil {
   237  				return err
   238  			}
   239  		}
   240  	}
   241  
   242  	return nil
   243  }
   244  
   245  // createDirsFor creates two directories for the given id.
   246  // mnt and diff
   247  func (a *Driver) createDirsFor(id string) error {
   248  	paths := []string{
   249  		"mnt",
   250  		"diff",
   251  	}
   252  
   253  	rootUID, rootGID, err := idtools.GetRootUIDGID(a.uidMaps, a.gidMaps)
   254  	if err != nil {
   255  		return err
   256  	}
   257  	// Directory permission is 0755.
   258  	// The path of directories are <aufs_root_path>/mnt/<image_id>
   259  	// and <aufs_root_path>/diff/<image_id>
   260  	for _, p := range paths {
   261  		if err := idtools.MkdirAllAs(path.Join(a.rootPath(), p, id), 0755, rootUID, rootGID); err != nil {
   262  			return err
   263  		}
   264  	}
   265  	return nil
   266  }
   267  
   268  // Remove will unmount and remove the given id.
   269  func (a *Driver) Remove(id string) error {
   270  	a.pathCacheLock.Lock()
   271  	mountpoint, exists := a.pathCache[id]
   272  	a.pathCacheLock.Unlock()
   273  	if !exists {
   274  		mountpoint = a.getMountpoint(id)
   275  	}
   276  	if err := a.unmount(mountpoint); err != nil {
   277  		// no need to return here, we can still try to remove since the `Rename` will fail below if still mounted
   278  		logrus.Debugf("aufs: error while unmounting %s: %v", mountpoint, err)
   279  	}
   280  
   281  	// Atomically remove each directory in turn by first moving it out of the
   282  	// way (so that docker doesn't find it anymore) before doing removal of
   283  	// the whole tree.
   284  	tmpMntPath := path.Join(a.mntPath(), fmt.Sprintf("%s-removing", id))
   285  	if err := os.Rename(mountpoint, tmpMntPath); err != nil && !os.IsNotExist(err) {
   286  		return err
   287  	}
   288  	defer os.RemoveAll(tmpMntPath)
   289  
   290  	tmpDiffpath := path.Join(a.diffPath(), fmt.Sprintf("%s-removing", id))
   291  	if err := os.Rename(a.getDiffPath(id), tmpDiffpath); err != nil && !os.IsNotExist(err) {
   292  		return err
   293  	}
   294  	defer os.RemoveAll(tmpDiffpath)
   295  
   296  	// Remove the layers file for the id
   297  	if err := os.Remove(path.Join(a.rootPath(), "layers", id)); err != nil && !os.IsNotExist(err) {
   298  		return err
   299  	}
   300  
   301  	a.pathCacheLock.Lock()
   302  	delete(a.pathCache, id)
   303  	a.pathCacheLock.Unlock()
   304  	return nil
   305  }
   306  
   307  // Get returns the rootfs path for the id.
   308  // This will mount the dir at it's given path
   309  func (a *Driver) Get(id, mountLabel string) (string, error) {
   310  	parents, err := a.getParentLayerPaths(id)
   311  	if err != nil && !os.IsNotExist(err) {
   312  		return "", err
   313  	}
   314  
   315  	a.pathCacheLock.Lock()
   316  	m, exists := a.pathCache[id]
   317  	a.pathCacheLock.Unlock()
   318  
   319  	if !exists {
   320  		m = a.getDiffPath(id)
   321  		if len(parents) > 0 {
   322  			m = a.getMountpoint(id)
   323  		}
   324  	}
   325  	if count := a.ctr.Increment(m); count > 1 {
   326  		return m, nil
   327  	}
   328  
   329  	// If a dir does not have a parent ( no layers )do not try to mount
   330  	// just return the diff path to the data
   331  	if len(parents) > 0 {
   332  		if err := a.mount(id, m, mountLabel, parents); err != nil {
   333  			return "", err
   334  		}
   335  	}
   336  
   337  	a.pathCacheLock.Lock()
   338  	a.pathCache[id] = m
   339  	a.pathCacheLock.Unlock()
   340  	return m, nil
   341  }
   342  
   343  // Put unmounts and updates list of active mounts.
   344  func (a *Driver) Put(id string) error {
   345  	a.pathCacheLock.Lock()
   346  	m, exists := a.pathCache[id]
   347  	if !exists {
   348  		m = a.getMountpoint(id)
   349  		a.pathCache[id] = m
   350  	}
   351  	a.pathCacheLock.Unlock()
   352  	if count := a.ctr.Decrement(m); count > 0 {
   353  		return nil
   354  	}
   355  
   356  	err := a.unmount(m)
   357  	if err != nil {
   358  		logrus.Debugf("Failed to unmount %s aufs: %v", id, err)
   359  	}
   360  	return err
   361  }
   362  
   363  // Diff produces an archive of the changes between the specified
   364  // layer and its parent layer which may be "".
   365  func (a *Driver) Diff(id, parent string) (archive.Archive, error) {
   366  	// AUFS doesn't need the parent layer to produce a diff.
   367  	return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
   368  		Compression:     archive.Uncompressed,
   369  		ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir},
   370  		UIDMaps:         a.uidMaps,
   371  		GIDMaps:         a.gidMaps,
   372  	})
   373  }
   374  
   375  type fileGetNilCloser struct {
   376  	storage.FileGetter
   377  }
   378  
   379  func (f fileGetNilCloser) Close() error {
   380  	return nil
   381  }
   382  
   383  // DiffGetter returns a FileGetCloser that can read files from the directory that
   384  // contains files for the layer differences. Used for direct access for tar-split.
   385  func (a *Driver) DiffGetter(id string) (graphdriver.FileGetCloser, error) {
   386  	p := path.Join(a.rootPath(), "diff", id)
   387  	return fileGetNilCloser{storage.NewPathFileGetter(p)}, nil
   388  }
   389  
   390  func (a *Driver) applyDiff(id string, diff archive.Reader) error {
   391  	return chrootarchive.UntarUncompressed(diff, path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
   392  		UIDMaps: a.uidMaps,
   393  		GIDMaps: a.gidMaps,
   394  	})
   395  }
   396  
   397  // DiffSize calculates the changes between the specified id
   398  // and its parent and returns the size in bytes of the changes
   399  // relative to its base filesystem directory.
   400  func (a *Driver) DiffSize(id, parent string) (size int64, err error) {
   401  	// AUFS doesn't need the parent layer to calculate the diff size.
   402  	return directory.Size(path.Join(a.rootPath(), "diff", id))
   403  }
   404  
   405  // ApplyDiff extracts the changeset from the given diff into the
   406  // layer with the specified id and parent, returning the size of the
   407  // new layer in bytes.
   408  func (a *Driver) ApplyDiff(id, parent string, diff archive.Reader) (size int64, err error) {
   409  	// AUFS doesn't need the parent id to apply the diff.
   410  	if err = a.applyDiff(id, diff); err != nil {
   411  		return
   412  	}
   413  
   414  	return a.DiffSize(id, parent)
   415  }
   416  
   417  // Changes produces a list of changes between the specified layer
   418  // and its parent layer. If parent is "", then all changes will be ADD changes.
   419  func (a *Driver) Changes(id, parent string) ([]archive.Change, error) {
   420  	// AUFS doesn't have snapshots, so we need to get changes from all parent
   421  	// layers.
   422  	layers, err := a.getParentLayerPaths(id)
   423  	if err != nil {
   424  		return nil, err
   425  	}
   426  	return archive.Changes(layers, path.Join(a.rootPath(), "diff", id))
   427  }
   428  
   429  func (a *Driver) getParentLayerPaths(id string) ([]string, error) {
   430  	parentIds, err := getParentIds(a.rootPath(), id)
   431  	if err != nil {
   432  		return nil, err
   433  	}
   434  	layers := make([]string, len(parentIds))
   435  
   436  	// Get the diff paths for all the parent ids
   437  	for i, p := range parentIds {
   438  		layers[i] = path.Join(a.rootPath(), "diff", p)
   439  	}
   440  	return layers, nil
   441  }
   442  
   443  func (a *Driver) mount(id string, target string, mountLabel string, layers []string) error {
   444  	a.Lock()
   445  	defer a.Unlock()
   446  
   447  	// If the id is mounted or we get an error return
   448  	if mounted, err := a.mounted(target); err != nil || mounted {
   449  		return err
   450  	}
   451  
   452  	rw := a.getDiffPath(id)
   453  
   454  	if err := a.aufsMount(layers, rw, target, mountLabel); err != nil {
   455  		return fmt.Errorf("error creating aufs mount to %s: %v", target, err)
   456  	}
   457  	return nil
   458  }
   459  
   460  func (a *Driver) unmount(mountPath string) error {
   461  	a.Lock()
   462  	defer a.Unlock()
   463  
   464  	if mounted, err := a.mounted(mountPath); err != nil || !mounted {
   465  		return err
   466  	}
   467  	if err := Unmount(mountPath); err != nil {
   468  		return err
   469  	}
   470  	return nil
   471  }
   472  
   473  func (a *Driver) mounted(mountpoint string) (bool, error) {
   474  	return graphdriver.Mounted(graphdriver.FsMagicAufs, mountpoint)
   475  }
   476  
   477  // Cleanup aufs and unmount all mountpoints
   478  func (a *Driver) Cleanup() error {
   479  	var dirs []string
   480  	if err := filepath.Walk(a.mntPath(), func(path string, info os.FileInfo, err error) error {
   481  		if err != nil {
   482  			return err
   483  		}
   484  		if !info.IsDir() {
   485  			return nil
   486  		}
   487  		dirs = append(dirs, path)
   488  		return nil
   489  	}); err != nil {
   490  		return err
   491  	}
   492  
   493  	for _, m := range dirs {
   494  		if err := a.unmount(m); err != nil {
   495  			logrus.Debugf("aufs error unmounting %s: %s", stringid.TruncateID(m), err)
   496  		}
   497  	}
   498  	return mountpk.Unmount(a.root)
   499  }
   500  
   501  func (a *Driver) aufsMount(ro []string, rw, target, mountLabel string) (err error) {
   502  	defer func() {
   503  		if err != nil {
   504  			Unmount(target)
   505  		}
   506  	}()
   507  
   508  	// Mount options are clipped to page size(4096 bytes). If there are more
   509  	// layers then these are remounted individually using append.
   510  
   511  	offset := 54
   512  	if useDirperm() {
   513  		offset += len("dirperm1")
   514  	}
   515  	b := make([]byte, syscall.Getpagesize()-len(mountLabel)-offset) // room for xino & mountLabel
   516  	bp := copy(b, fmt.Sprintf("br:%s=rw", rw))
   517  
   518  	firstMount := true
   519  	i := 0
   520  
   521  	for {
   522  		for ; i < len(ro); i++ {
   523  			layer := fmt.Sprintf(":%s=ro+wh", ro[i])
   524  
   525  			if firstMount {
   526  				if bp+len(layer) > len(b) {
   527  					break
   528  				}
   529  				bp += copy(b[bp:], layer)
   530  			} else {
   531  				data := label.FormatMountLabel(fmt.Sprintf("append%s", layer), mountLabel)
   532  				if err = mount("none", target, "aufs", syscall.MS_REMOUNT, data); err != nil {
   533  					return
   534  				}
   535  			}
   536  		}
   537  
   538  		if firstMount {
   539  			opts := "dio,xino=/dev/shm/aufs.xino"
   540  			if useDirperm() {
   541  				opts += ",dirperm1"
   542  			}
   543  			data := label.FormatMountLabel(fmt.Sprintf("%s,%s", string(b[:bp]), opts), mountLabel)
   544  			if err = mount("none", target, "aufs", 0, data); err != nil {
   545  				return
   546  			}
   547  			firstMount = false
   548  		}
   549  
   550  		if i == len(ro) {
   551  			break
   552  		}
   553  	}
   554  
   555  	return
   556  }
   557  
   558  // useDirperm checks dirperm1 mount option can be used with the current
   559  // version of aufs.
   560  func useDirperm() bool {
   561  	enableDirpermLock.Do(func() {
   562  		base, err := ioutil.TempDir("", "docker-aufs-base")
   563  		if err != nil {
   564  			logrus.Errorf("error checking dirperm1: %v", err)
   565  			return
   566  		}
   567  		defer os.RemoveAll(base)
   568  
   569  		union, err := ioutil.TempDir("", "docker-aufs-union")
   570  		if err != nil {
   571  			logrus.Errorf("error checking dirperm1: %v", err)
   572  			return
   573  		}
   574  		defer os.RemoveAll(union)
   575  
   576  		opts := fmt.Sprintf("br:%s,dirperm1,xino=/dev/shm/aufs.xino", base)
   577  		if err := mount("none", union, "aufs", 0, opts); err != nil {
   578  			return
   579  		}
   580  		enableDirperm = true
   581  		if err := Unmount(union); err != nil {
   582  			logrus.Errorf("error checking dirperm1: failed to unmount %v", err)
   583  		}
   584  	})
   585  	return enableDirperm
   586  }