// ApplyDiff extracts the changeset from the given diff into the
// layer with the specified id and parent, returning the size of the
// new layer in bytes.
17742
func (gdw *NaiveDiffDriver) ApplyDiff(id string, applyMappings *idtools.IDMappings, parent, mountLabel string, diff io.Reader) (size int64, err error) {
	driver := gdw.ProtoDriver

	if applyMappings == nil {
		applyMappings = &idtools.IDMappings{}
	}

	// Mount the root filesystem so we can apply the diff/layer.
	mountOpts := MountOpts{
		MountLabel: mountLabel,
	}
	layerFs, err := driver.Get(id, mountOpts)
	if err != nil {
		return
	}
	defer driver.Put(id)

	options := &archive.TarOptions{
		InUserNS: rsystem.RunningInUserNS(),
	}
	if applyMappings != nil {
		options.UIDMaps = applyMappings.UIDs()
		options.GIDMaps = applyMappings.GIDs()
	}
	start := time.Now().UTC()
	logrus.Debug("Start untar layer")
	if size, err = ApplyUncompressedLayer(layerFs, diff, options); err != nil {
		logrus.Errorf("Error while applying layer: %s", err)
		return
	}
	logrus.Debugf("Untar time: %vs", time.Now().UTC().Sub(start).Seconds())

	return
}
500152
func (d *Driver) DiffSize(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) (size int64, err error) {
	panicIfUsedByLcow()
	rPId, err := d.resolveID(parent)
	if err != nil {
		return
	}

	changes, err := d.Changes(id, idMappings, rPId, parentMappings, mountLabel)
	if err != nil {
		return
	}

	layerFs, err := d.Get(id, graphdriver.MountOpts{})
	if err != nil {
		return
	}
	defer d.Put(id)

	return archive.ChangesSize(layerFs, changes), nil
}
582015
func (r *resourceRecordChangeset) Apply() error {
	glog.V(2).Info("applying changes in record change set")
	if r.IsEmpty() {
		glog.V(2).Info("record change set is empty")
		return nil
	}

	if len(r.additions) > 0 {
		for _, rrset := range r.additions {
			err := r.applyResourceRecordSet(rrset)
			if err != nil {
				return fmt.Errorf("failed to apply resource record set: %s, err: %s", rrset.Name(), err)
			}
		}

		glog.V(2).Info("record change set additions complete")
	}

	if len(r.upserts) > 0 {
		for _, rrset := range r.upserts {
			err := r.applyResourceRecordSet(rrset)
			if err != nil {
				return fmt.Errorf("failed to apply resource record set: %s, err: %s", rrset.Name(), err)
			}
		}

		glog.V(2).Info("record change set upserts complete")
	}

	if len(r.removals) > 0 {
		records, err := getRecords(r.client, r.zone.Name())
		if err != nil {
			return err
		}

		for _, record := range r.removals {
			for _, domainRecord := range records {
				if domainRecord.Name == record.Name() {
					err := deleteRecord(r.client, r.zone.Name(), domainRecord.ID)
					if err != nil {
						return fmt.Errorf("failed to delete record: %v", err)
					}
				}
			}
		}

		glog.V(2).Info("record change set removals complete")
	}

	glog.V(2).Info("record change sets successfully applied")
	return nil
}
551607
func (gdw *NaiveDiffDriver) Changes(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) ([]archive.Change, error) {
	driver := gdw.ProtoDriver

	if idMappings == nil {
		idMappings = &idtools.IDMappings{}
	}
	if parentMappings == nil {
		parentMappings = &idtools.IDMappings{}
	}

	options := MountOpts{
		MountLabel: mountLabel,
	}
	layerFs, err := driver.Get(id, options)
	if err != nil {
		return nil, err
	}
	defer driver.Put(id)

	parentFs := ""

	if parent != "" {
		options := MountOpts{
			MountLabel: mountLabel,
		}
		parentFs, err = driver.Get(parent, options)
		if err != nil {
			return nil, err
		}
		defer driver.Put(parent)
	}

	return archive.ChangesDirs(layerFs, idMappings, parentFs, parentMappings)
}
1346520
func (s *Bitset) Diff(b *Bitset) *Bitset {
	return s.bitsetOp(
		b,

		func(s, b *Bitset, length *uint) {
			if *length > s.Length(0) {
				*length = s.Length(0)
			} else {
				b.unsetTop()
			}
		},

		func(s, b *Bitset, index uint) {
			s.set[index] &= ^b.set[index]
		},
	)
}
1025262
func (f *PropertyFilter) apply(ctx *Context, change types.ObjectUpdate) types.ObjectUpdate {
	parents := make(map[string]bool)
	set := change.ChangeSet
	change.ChangeSet = nil

	for i, p := range set {
		if f.matches(ctx, change.Obj, &p) {
			if p.Name != set[i].Name {
				// update matches a parent field from the spec.
				if parents[p.Name] {
					continue // only return 1 instance of the parent
				}
				parents[p.Name] = true
			}
			change.ChangeSet = append(change.ChangeSet, p)
		}
	}

	return change
}
729254
func (gdw *NaiveDiffDriver) Diff(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) (arch io.ReadCloser, err error) {
	startTime := time.Now()
	driver := gdw.ProtoDriver

	if idMappings == nil {
		idMappings = &idtools.IDMappings{}
	}
	if parentMappings == nil {
		parentMappings = &idtools.IDMappings{}
	}

	options := MountOpts{
		MountLabel: mountLabel,
	}
	layerFs, err := driver.Get(id, options)
	if err != nil {
		return nil, err
	}

	defer func() {
		if err != nil {
			driver.Put(id)
		}
	}()

	if parent == "" {
		archive, err := archive.TarWithOptions(layerFs, &archive.TarOptions{
			Compression: archive.Uncompressed,
			UIDMaps:     idMappings.UIDs(),
			GIDMaps:     idMappings.GIDs(),
		})
		if err != nil {
			return nil, err
		}
		return ioutils.NewReadCloserWrapper(archive, func() error {
			err := archive.Close()
			driver.Put(id)
			return err
		}), nil
	}

	parentFs, err := driver.Get(parent, options)
	if err != nil {
		return nil, err
	}
	defer driver.Put(parent)

	changes, err := archive.ChangesDirs(layerFs, idMappings, parentFs, parentMappings)
	if err != nil {
		return nil, err
	}

	archive, err := archive.ExportChanges(layerFs, changes, idMappings.UIDs(), idMappings.GIDs())
	if err != nil {
		return nil, err
	}

	return ioutils.NewReadCloserWrapper(archive, func() error {
		err := archive.Close()
		driver.Put(id)

		// NaiveDiffDriver compares file metadata with parent layers. Parent layers
		// are extracted from tar's with full second precision on modified time.
		// We need this hack here to make sure calls within same second receive
		// correct result.
		time.Sleep(startTime.Truncate(time.Second).Add(time.Second).Sub(time.Now()))
		return err
	}), nil
}
1067641
func (a *Driver) ApplyDiff(id string, idMappings *idtools.IDMappings, parent, mountLabel string, diff io.Reader) (size int64, err error) {
	if !a.isParent(id, parent) {
		return a.naiveDiff.ApplyDiff(id, idMappings, parent, mountLabel, diff)
	}

	// AUFS doesn't need the parent id to apply the diff if it is the direct parent.
	if err = a.applyDiff(id, idMappings, diff); err != nil {
		return
	}

	return directory.Size(path.Join(a.rootPath(), "diff", id))
}
1024435
func (d *Driver) DiffSize(id string, idMappings *idtools.IDMappings, parent string, parentMappings *idtools.IDMappings, mountLabel string) (size int64, err error) {
	if d.useNaiveDiff() || !d.isParent(id, parent) {
		return d.naiveDiff.DiffSize(id, idMappings, parent, parentMappings, mountLabel)
	}
	return directory.Size(d.getDiffPath(id))
}
1127249
func (rl *referencedRWLayer) ApplyDiff(diff io.Reader) (int64, error) {
	return rl.layerStore.driver.ApplyDiff(rl.mountID, rl.cacheParent(), diff)
}
481703
func (a *Driver) Diff(id, parent string) (io.ReadCloser, error) {
	if !a.isParent(id, parent) {
		return a.naiveDiff.Diff(id, parent)
	}

	// AUFS doesn't need the parent layer to produce a diff.
	return archive.TarWithOptions(path.Join(a.rootPath(), "diff", id), &archive.TarOptions{
		Compression:     archive.Uncompressed,
		ExcludePatterns: []string{archive.WhiteoutMetaPrefix + "*", "!" + archive.WhiteoutOpaqueDir},
		UIDMaps:         a.uidMaps,
		GIDMaps:         a.gidMaps,
	})
}
869813
func (serviceMap *ServiceMap) apply(changes *ServiceChangeTracker, UDPStaleClusterIP sets.String) {
	changes.lock.Lock()
	defer changes.lock.Unlock()
	for _, change := range changes.items {
		serviceMap.merge(change.current)
		// filter out the Update event of current changes from previous changes before calling unmerge() so that can
		// skip deleting the Update events.
		change.previous.filter(change.current)
		serviceMap.unmerge(change.previous, UDPStaleClusterIP)
	}
	// clear changes after applying them to ServiceMap.
	changes.items = make(map[types.NamespacedName]*serviceChange)
	return
}
1296192
func (old *Manifest_CIPDPackage) Diff(new *Manifest_CIPDPackage) ManifestDiff_Stat {
	return zeroCmpTwo(old, new, func() ManifestDiff_Stat {
		// Version and PackagePattern don't matter for diff purposes.
		return zeroCmpTwo(old.InstanceId, new.InstanceId, nil)
	})
}
866227
func (gdw *NaiveDiffDriver) Diff(id, parent string) (arch io.ReadCloser, err error) {
	startTime := time.Now()
	driver := gdw.ProtoDriver

	layerRootFs, err := driver.Get(id, "")
	if err != nil {
		return nil, err
	}
	layerFs := layerRootFs.Path()

	defer func() {
		if err != nil {
			driver.Put(id)
		}
	}()

	if parent == "" {
		archive, err := archive.Tar(layerFs, archive.Uncompressed)
		if err != nil {
			return nil, err
		}
		return ioutils.NewReadCloserWrapper(archive, func() error {
			err := archive.Close()
			driver.Put(id)
			return err
		}), nil
	}

	parentRootFs, err := driver.Get(parent, "")
	if err != nil {
		return nil, err
	}
	defer driver.Put(parent)

	parentFs := parentRootFs.Path()

	changes, err := archive.ChangesDirs(layerFs, parentFs)
	if err != nil {
		return nil, err
	}

	archive, err := archive.ExportChanges(layerFs, changes, gdw.uidMaps, gdw.gidMaps)
	if err != nil {
		return nil, err
	}

	return ioutils.NewReadCloserWrapper(archive, func() error {
		err := archive.Close()
		driver.Put(id)

		// NaiveDiffDriver compares file metadata with parent layers. Parent layers
		// are extracted from tar's with full second precision on modified time.
		// We need this hack here to make sure calls within same second receive
		// correct result.
		time.Sleep(time.Until(startTime.Truncate(time.Second).Add(time.Second)))
		return err
	}), nil
}
1077596
func (s windowsDiff) Apply(ctx context.Context, desc ocispec.Descriptor, mounts []mount.Mount) (d ocispec.Descriptor, err error) {
	t1 := time.Now()
	defer func() {
		if err == nil {
			log.G(ctx).WithFields(logrus.Fields{
				"d":     time.Since(t1),
				"dgst":  desc.Digest,
				"size":  desc.Size,
				"media": desc.MediaType,
			}).Debugf("diff applied")
		}
	}()

	isCompressed, err := images.IsCompressedDiff(ctx, desc.MediaType)
	if err != nil {
		return emptyDesc, errors.Wrapf(errdefs.ErrNotImplemented, "unsupported diff media type: %v", desc.MediaType)
	}

	ra, err := s.store.ReaderAt(ctx, desc)
	if err != nil {
		return emptyDesc, errors.Wrap(err, "failed to get reader from content store")
	}
	defer ra.Close()

	r := content.NewReader(ra)
	if isCompressed {
		ds, err := compression.DecompressStream(r)
		if err != nil {
			return emptyDesc, err
		}
		defer ds.Close()
		r = ds
	}

	digester := digest.Canonical.Digester()
	rc := &readCounter{
		r: io.TeeReader(r, digester.Hash()),
	}

	layer, parentLayerPaths, err := mountsToLayerAndParents(mounts)
	if err != nil {
		return emptyDesc, err
	}

	// TODO darrenstahlmsft: When this is done isolated, we should disable these.
	// it currently cannot be disabled, unless we add ref counting. Since this is
	// temporary, leaving it enabled is OK for now.
	if err := winio.EnableProcessPrivileges([]string{winio.SeBackupPrivilege, winio.SeRestorePrivilege}); err != nil {
		return emptyDesc, err
	}

	if _, err := archive.Apply(ctx, layer, rc, archive.WithParentLayers(parentLayerPaths), archive.AsWindowsContainerLayer()); err != nil {
		return emptyDesc, err
	}

	// Read any trailing data
	if _, err := io.Copy(ioutil.Discard, rc); err != nil {
		return emptyDesc, err
	}

	return ocispec.Descriptor{
		MediaType: ocispec.MediaTypeImageLayer,
		Size:      rc.c,
		Digest:    digester.Digest(),
	}, nil
}
432614
func (b *bulkVersionEdit) apply(base *version, icmp db.Comparer) (*version, error) {
	v := new(version)
	for level := range v.files {
		combined := [2][]fileMetadata{
			nil,
			b.added[level],
		}
		if base != nil {
			combined[0] = base.files[level]
		}
		n := len(combined[0]) + len(combined[1])
		if n == 0 {
			continue
		}
		v.files[level] = make([]fileMetadata, 0, n)
		dmap := b.deleted[level]

		for _, ff := range combined {
			for _, f := range ff {
				if dmap != nil && dmap[f.fileNum] {
					continue
				}
				v.files[level] = append(v.files[level], f)
			}
		}

		// TODO: base.files[level] is already sorted. Instead of appending
		// b.addFiles[level] to the end and sorting afterwards, it might be more
		// efficient to sort b.addFiles[level] and then merge the two sorted slices.
		if level == 0 {
			sort.Sort(byFileNum(v.files[level]))
		} else {
			sort.Sort(bySmallest{v.files[level], icmp})
		}
	}
	if err := v.checkOrdering(icmp); err != nil {
		return nil, fmt.Errorf("leveldb: internal error: %v", err)
	}
	v.updateCompactionScore()
	return v, nil
}
370061
func Diff(a, b interface{}) (desc []string) {
	Pdiff((*sbuf)(&desc), a, b)
	return desc
}