github.com/michael-k/docker@v1.7.0-rc2/pkg/archive/changes.go (about)

     1  package archive
     2  
     3  import (
     4  	"archive/tar"
     5  	"bytes"
     6  	"fmt"
     7  	"io"
     8  	"os"
     9  	"path/filepath"
    10  	"sort"
    11  	"strings"
    12  	"syscall"
    13  	"time"
    14  
    15  	"github.com/Sirupsen/logrus"
    16  	"github.com/docker/docker/pkg/pools"
    17  	"github.com/docker/docker/pkg/system"
    18  )
    19  
    20  type ChangeType int
    21  
    22  const (
    23  	ChangeModify = iota
    24  	ChangeAdd
    25  	ChangeDelete
    26  )
    27  
    28  type Change struct {
    29  	Path string
    30  	Kind ChangeType
    31  }
    32  
    33  func (change *Change) String() string {
    34  	var kind string
    35  	switch change.Kind {
    36  	case ChangeModify:
    37  		kind = "C"
    38  	case ChangeAdd:
    39  		kind = "A"
    40  	case ChangeDelete:
    41  		kind = "D"
    42  	}
    43  	return fmt.Sprintf("%s %s", kind, change.Path)
    44  }
    45  
    46  // for sort.Sort
    47  type changesByPath []Change
    48  
    49  func (c changesByPath) Less(i, j int) bool { return c[i].Path < c[j].Path }
    50  func (c changesByPath) Len() int           { return len(c) }
    51  func (c changesByPath) Swap(i, j int)      { c[j], c[i] = c[i], c[j] }
    52  
    53  // Gnu tar and the go tar writer don't have sub-second mtime
    54  // precision, which is problematic when we apply changes via tar
    55  // files, we handle this by comparing for exact times, *or* same
    56  // second count and either a or b having exactly 0 nanoseconds
    57  func sameFsTime(a, b time.Time) bool {
    58  	return a == b ||
    59  		(a.Unix() == b.Unix() &&
    60  			(a.Nanosecond() == 0 || b.Nanosecond() == 0))
    61  }
    62  
    63  func sameFsTimeSpec(a, b syscall.Timespec) bool {
    64  	return a.Sec == b.Sec &&
    65  		(a.Nsec == b.Nsec || a.Nsec == 0 || b.Nsec == 0)
    66  }
    67  
    68  // Changes walks the path rw and determines changes for the files in the path,
    69  // with respect to the parent layers
    70  func Changes(layers []string, rw string) ([]Change, error) {
    71  	var changes []Change
    72  	err := filepath.Walk(rw, func(path string, f os.FileInfo, err error) error {
    73  		if err != nil {
    74  			return err
    75  		}
    76  
    77  		// Rebase path
    78  		path, err = filepath.Rel(rw, path)
    79  		if err != nil {
    80  			return err
    81  		}
    82  		path = filepath.Join("/", path)
    83  
    84  		// Skip root
    85  		if path == "/" {
    86  			return nil
    87  		}
    88  
    89  		// Skip AUFS metadata
    90  		if matched, err := filepath.Match("/.wh..wh.*", path); err != nil || matched {
    91  			return err
    92  		}
    93  
    94  		change := Change{
    95  			Path: path,
    96  		}
    97  
    98  		// Find out what kind of modification happened
    99  		file := filepath.Base(path)
   100  		// If there is a whiteout, then the file was removed
   101  		if strings.HasPrefix(file, ".wh.") {
   102  			originalFile := file[len(".wh."):]
   103  			change.Path = filepath.Join(filepath.Dir(path), originalFile)
   104  			change.Kind = ChangeDelete
   105  		} else {
   106  			// Otherwise, the file was added
   107  			change.Kind = ChangeAdd
   108  
   109  			// ...Unless it already existed in a top layer, in which case, it's a modification
   110  			for _, layer := range layers {
   111  				stat, err := os.Stat(filepath.Join(layer, path))
   112  				if err != nil && !os.IsNotExist(err) {
   113  					return err
   114  				}
   115  				if err == nil {
   116  					// The file existed in the top layer, so that's a modification
   117  
   118  					// However, if it's a directory, maybe it wasn't actually modified.
   119  					// If you modify /foo/bar/baz, then /foo will be part of the changed files only because it's the parent of bar
   120  					if stat.IsDir() && f.IsDir() {
   121  						if f.Size() == stat.Size() && f.Mode() == stat.Mode() && sameFsTime(f.ModTime(), stat.ModTime()) {
   122  							// Both directories are the same, don't record the change
   123  							return nil
   124  						}
   125  					}
   126  					change.Kind = ChangeModify
   127  					break
   128  				}
   129  			}
   130  		}
   131  
   132  		// Record change
   133  		changes = append(changes, change)
   134  		return nil
   135  	})
   136  	if err != nil && !os.IsNotExist(err) {
   137  		return nil, err
   138  	}
   139  	return changes, nil
   140  }
   141  
   142  type FileInfo struct {
   143  	parent     *FileInfo
   144  	name       string
   145  	stat       *system.Stat_t
   146  	children   map[string]*FileInfo
   147  	capability []byte
   148  	added      bool
   149  }
   150  
   151  func (root *FileInfo) LookUp(path string) *FileInfo {
   152  	parent := root
   153  	if path == "/" {
   154  		return root
   155  	}
   156  
   157  	pathElements := strings.Split(path, "/")
   158  	for _, elem := range pathElements {
   159  		if elem != "" {
   160  			child := parent.children[elem]
   161  			if child == nil {
   162  				return nil
   163  			}
   164  			parent = child
   165  		}
   166  	}
   167  	return parent
   168  }
   169  
   170  func (info *FileInfo) path() string {
   171  	if info.parent == nil {
   172  		return "/"
   173  	}
   174  	return filepath.Join(info.parent.path(), info.name)
   175  }
   176  
   177  func (info *FileInfo) addChanges(oldInfo *FileInfo, changes *[]Change) {
   178  
   179  	sizeAtEntry := len(*changes)
   180  
   181  	if oldInfo == nil {
   182  		// add
   183  		change := Change{
   184  			Path: info.path(),
   185  			Kind: ChangeAdd,
   186  		}
   187  		*changes = append(*changes, change)
   188  		info.added = true
   189  	}
   190  
   191  	// We make a copy so we can modify it to detect additions
   192  	// also, we only recurse on the old dir if the new info is a directory
   193  	// otherwise any previous delete/change is considered recursive
   194  	oldChildren := make(map[string]*FileInfo)
   195  	if oldInfo != nil && info.isDir() {
   196  		for k, v := range oldInfo.children {
   197  			oldChildren[k] = v
   198  		}
   199  	}
   200  
   201  	for name, newChild := range info.children {
   202  		oldChild, _ := oldChildren[name]
   203  		if oldChild != nil {
   204  			// change?
   205  			oldStat := oldChild.stat
   206  			newStat := newChild.stat
   207  			// Note: We can't compare inode or ctime or blocksize here, because these change
   208  			// when copying a file into a container. However, that is not generally a problem
   209  			// because any content change will change mtime, and any status change should
   210  			// be visible when actually comparing the stat fields. The only time this
   211  			// breaks down is if some code intentionally hides a change by setting
   212  			// back mtime
   213  			if statDifferent(oldStat, newStat) ||
   214  				bytes.Compare(oldChild.capability, newChild.capability) != 0 {
   215  				change := Change{
   216  					Path: newChild.path(),
   217  					Kind: ChangeModify,
   218  				}
   219  				*changes = append(*changes, change)
   220  				newChild.added = true
   221  			}
   222  
   223  			// Remove from copy so we can detect deletions
   224  			delete(oldChildren, name)
   225  		}
   226  
   227  		newChild.addChanges(oldChild, changes)
   228  	}
   229  	for _, oldChild := range oldChildren {
   230  		// delete
   231  		change := Change{
   232  			Path: oldChild.path(),
   233  			Kind: ChangeDelete,
   234  		}
   235  		*changes = append(*changes, change)
   236  	}
   237  
   238  	// If there were changes inside this directory, we need to add it, even if the directory
   239  	// itself wasn't changed. This is needed to properly save and restore filesystem permissions.
   240  	if len(*changes) > sizeAtEntry && info.isDir() && !info.added && info.path() != "/" {
   241  		change := Change{
   242  			Path: info.path(),
   243  			Kind: ChangeModify,
   244  		}
   245  		// Let's insert the directory entry before the recently added entries located inside this dir
   246  		*changes = append(*changes, change) // just to resize the slice, will be overwritten
   247  		copy((*changes)[sizeAtEntry+1:], (*changes)[sizeAtEntry:])
   248  		(*changes)[sizeAtEntry] = change
   249  	}
   250  
   251  }
   252  
   253  func (info *FileInfo) Changes(oldInfo *FileInfo) []Change {
   254  	var changes []Change
   255  
   256  	info.addChanges(oldInfo, &changes)
   257  
   258  	return changes
   259  }
   260  
   261  func newRootFileInfo() *FileInfo {
   262  	root := &FileInfo{
   263  		name:     "/",
   264  		children: make(map[string]*FileInfo),
   265  	}
   266  	return root
   267  }
   268  
   269  func collectFileInfo(sourceDir string) (*FileInfo, error) {
   270  	root := newRootFileInfo()
   271  
   272  	err := filepath.Walk(sourceDir, func(path string, f os.FileInfo, err error) error {
   273  		if err != nil {
   274  			return err
   275  		}
   276  
   277  		// Rebase path
   278  		relPath, err := filepath.Rel(sourceDir, path)
   279  		if err != nil {
   280  			return err
   281  		}
   282  		relPath = filepath.Join("/", relPath)
   283  
   284  		if relPath == "/" {
   285  			return nil
   286  		}
   287  
   288  		parent := root.LookUp(filepath.Dir(relPath))
   289  		if parent == nil {
   290  			return fmt.Errorf("collectFileInfo: Unexpectedly no parent for %s", relPath)
   291  		}
   292  
   293  		info := &FileInfo{
   294  			name:     filepath.Base(relPath),
   295  			children: make(map[string]*FileInfo),
   296  			parent:   parent,
   297  		}
   298  
   299  		s, err := system.Lstat(path)
   300  		if err != nil {
   301  			return err
   302  		}
   303  		info.stat = s
   304  
   305  		info.capability, _ = system.Lgetxattr(path, "security.capability")
   306  
   307  		parent.children[info.name] = info
   308  
   309  		return nil
   310  	})
   311  	if err != nil {
   312  		return nil, err
   313  	}
   314  	return root, nil
   315  }
   316  
   317  // ChangesDirs compares two directories and generates an array of Change objects describing the changes.
   318  // If oldDir is "", then all files in newDir will be Add-Changes.
   319  func ChangesDirs(newDir, oldDir string) ([]Change, error) {
   320  	var (
   321  		oldRoot, newRoot *FileInfo
   322  		err1, err2       error
   323  		errs             = make(chan error, 2)
   324  	)
   325  	go func() {
   326  		if oldDir != "" {
   327  			oldRoot, err1 = collectFileInfo(oldDir)
   328  		}
   329  		errs <- err1
   330  	}()
   331  	go func() {
   332  		newRoot, err2 = collectFileInfo(newDir)
   333  		errs <- err2
   334  	}()
   335  
   336  	// block until both routines have returned
   337  	for i := 0; i < 2; i++ {
   338  		if err := <-errs; err != nil {
   339  			return nil, err
   340  		}
   341  	}
   342  
   343  	return newRoot.Changes(oldRoot), nil
   344  }
   345  
   346  // ChangesSize calculates the size in bytes of the provided changes, based on newDir.
   347  func ChangesSize(newDir string, changes []Change) int64 {
   348  	var size int64
   349  	for _, change := range changes {
   350  		if change.Kind == ChangeModify || change.Kind == ChangeAdd {
   351  			file := filepath.Join(newDir, change.Path)
   352  			fileInfo, _ := os.Lstat(file)
   353  			if fileInfo != nil && !fileInfo.IsDir() {
   354  				size += fileInfo.Size()
   355  			}
   356  		}
   357  	}
   358  	return size
   359  }
   360  
   361  // ExportChanges produces an Archive from the provided changes, relative to dir.
   362  func ExportChanges(dir string, changes []Change) (Archive, error) {
   363  	reader, writer := io.Pipe()
   364  	go func() {
   365  		ta := &tarAppender{
   366  			TarWriter: tar.NewWriter(writer),
   367  			Buffer:    pools.BufioWriter32KPool.Get(nil),
   368  			SeenFiles: make(map[uint64]string),
   369  		}
   370  		// this buffer is needed for the duration of this piped stream
   371  		defer pools.BufioWriter32KPool.Put(ta.Buffer)
   372  
   373  		sort.Sort(changesByPath(changes))
   374  
   375  		// In general we log errors here but ignore them because
   376  		// during e.g. a diff operation the container can continue
   377  		// mutating the filesystem and we can see transient errors
   378  		// from this
   379  		for _, change := range changes {
   380  			if change.Kind == ChangeDelete {
   381  				whiteOutDir := filepath.Dir(change.Path)
   382  				whiteOutBase := filepath.Base(change.Path)
   383  				whiteOut := filepath.Join(whiteOutDir, ".wh."+whiteOutBase)
   384  				timestamp := time.Now()
   385  				hdr := &tar.Header{
   386  					Name:       whiteOut[1:],
   387  					Size:       0,
   388  					ModTime:    timestamp,
   389  					AccessTime: timestamp,
   390  					ChangeTime: timestamp,
   391  				}
   392  				if err := ta.TarWriter.WriteHeader(hdr); err != nil {
   393  					logrus.Debugf("Can't write whiteout header: %s", err)
   394  				}
   395  			} else {
   396  				path := filepath.Join(dir, change.Path)
   397  				if err := ta.addTarFile(path, change.Path[1:]); err != nil {
   398  					logrus.Debugf("Can't add file %s to tar: %s", path, err)
   399  				}
   400  			}
   401  		}
   402  
   403  		// Make sure to check the error on Close.
   404  		if err := ta.TarWriter.Close(); err != nil {
   405  			logrus.Debugf("Can't close layer: %s", err)
   406  		}
   407  		if err := writer.Close(); err != nil {
   408  			logrus.Debugf("failed close Changes writer: %s", err)
   409  		}
   410  	}()
   411  	return reader, nil
   412  }