// ApplyLayer parses a diff in the standard layer format from `layer`,
// and applies it to the directory `dest`. The stream `layer` can only be
// uncompressed.
// Returns the size in bytes of the contents of the layer.
432535
func ApplyLayer(dest string, layer io.Reader) (size int64, err error) {
	return applyLayerHandler(dest, layer, &archive.TarOptions{}, true)
}
674526
func (p *Proxy) Apply(dbName string, i interface{}) {
	p.ApplyLazy(gsd.Lazy(dbName), i)
}
882719
func (c *configuration) apply(t transition) {
	logf("Applying %v", t)
	w1 := int(c.stackValue(1))
	w2 := int(c.stackValue(0))

	if t.Move == Left {
		c.AddArc(w2, w1, t.DependencyType)
		c.removeSecondTopStack()
	} else if t.Move == Right {
		c.AddArc(w1, w2, t.DependencyType)
		c.removeTopStack()
	} else {
		c.shift()
	}
}
445483
func Apply(img image.Image, fn func(color.RGBA) color.RGBA) *image.RGBA {
	bounds := img.Bounds()
	dst := clone.AsRGBA(img)
	w, h := bounds.Dx(), bounds.Dy()

	parallel.Line(h, func(start, end int) {
		for y := start; y < end; y++ {
			for x := 0; x < w; x++ {
				dstPos := y*dst.Stride + x*4

				c := color.RGBA{}

				c.R = dst.Pix[dstPos+0]
				c.G = dst.Pix[dstPos+1]
				c.B = dst.Pix[dstPos+2]
				c.A = dst.Pix[dstPos+3]

				c = fn(c)

				dst.Pix[dstPos+0] = c.R
				dst.Pix[dstPos+1] = c.G
				dst.Pix[dstPos+2] = c.B
				dst.Pix[dstPos+3] = c.A
			}
		}
	})

	return dst
}
836527
func (a SizeLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
	var layerDiffs []util.SizeDiff

	maxLayer := len(image1.Layers)
	if len(image2.Layers) > maxLayer {
		maxLayer = len(image2.Layers)
	}

	for index := 0; index < maxLayer; index++ {
		var size1, size2 int64 = -1, -1
		if index < len(image1.Layers) {
			size1 = pkgutil.GetSize(image1.Layers[index].FSPath)
		}
		if index < len(image2.Layers) {
			size2 = pkgutil.GetSize(image2.Layers[index].FSPath)
		}

		if size1 != size2 {
			diff := util.SizeDiff{
				Name:  strconv.Itoa(index),
				Size1: size1,
				Size2: size2,
			}
			layerDiffs = append(layerDiffs, diff)
		}
	}

	return &util.SizeLayerDiffResult{
		Image1:   image1.Source,
		Image2:   image2.Source,
		DiffType: "SizeLayer",
		Diff:     layerDiffs,
	}, nil
}
435517
func (b *Builder) BuildLayer(l *Layer, id, name string, run []string, env map[string]string, artifact *ct.Artifact, inputs []string) (*ct.ImageLayer, error) {
	// try and get the cached layer first
	layer, err := b.GetCachedLayer(name, id)
	if err != nil {
		return nil, err
	} else if layer != nil {
		return layer, nil
	}

	// create a shared directory containing the inputs so we can ensure the
	// job only accesses declared inputs (thus enforcing the correctness of
	// the generated layer ID)
	dir, err := ioutil.TempDir("", "flynn-build-mnt")
	if err != nil {
		return nil, err
	}
	defer os.RemoveAll(dir)
	if err := os.Chmod(dir, 0755); err != nil {
		return nil, err
	}
	for _, subdir := range []string{"bin", "out", "src"} {
		if err := os.MkdirAll(filepath.Join(dir, subdir), 0755); err != nil {
			return nil, err
		}
	}
	copyFile := func(srcPath, dstPath string) error {
		src, err := os.Open(srcPath)
		if err != nil {
			return err
		}
		defer src.Close()
		stat, err := src.Stat()
		if err != nil {
			return err
		}
		path := filepath.Join(dir, dstPath)
		if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
			return err
		}
		dst, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, stat.Mode())
		if err != nil {
			return err
		}
		defer dst.Close()
		_, err = io.Copy(dst, src)
		return err
	}
	for _, input := range inputs {
		if err := copyFile(input, filepath.Join("src", input)); err != nil {
			b.log.Error("error copying input", "input", input, "err", err)
			return nil, err
		}
	}

	// copy the flynn-builder binary into the shared directory so we can
	// run it inside the job
	if err := copyFile(os.Args[0], "bin/flynn-builder"); err != nil {
		b.log.Error("error copying flynn-builder binary", "err", err)
		return nil, err
	}

	job := &host.Job{
		Config: host.ContainerConfig{
			Env:        env,
			DisableLog: true,
		},
		Resources: resource.Defaults(),
		Metadata: map[string]string{
			"flynn-controller.app_name": "builder",
			"flynn-controller.type":     name,
		},
	}
	cmd := exec.Cmd{Job: job}

	// run bash inside the job, passing the commands via stdin
	job.Config.Args = []string{"/mnt/bin/flynn-builder", "run", "bash", "-exs"}
	job.Config.Stdin = true
	cmd.Stdin = strings.NewReader(strings.Join(run, "\n"))

	// set FLYNN_VERSION which will be assigned to the pkg/version.version
	// constant using ldflags when building Go binaries.
	//
	// This is not treated as an input because we only want to build a new
	// binary with the given version if the build inputs have changed.
	job.Config.Env["FLYNN_VERSION"] = b.version

	// run the job in the host network to avoid a kernel bug which causes
	// subsequent jobs to block waiting on the lo network device to become
	// free (see https://github.com/docker/docker/issues/5618).
	//
	// NOTE: this leads to an impure build, jobs sometimes use the state of
	//   the network to change the installation procedure (e.g. PostgreSQL
	//   changes the default port to 5433 if something is already listening
	//   on port 5432 at install time)
	job.Config.HostNetwork = true

	linuxCapabilities := append(host.DefaultCapabilities, l.LinuxCapabilities...)
	job.Config.LinuxCapabilities = &linuxCapabilities

	for typ, v := range l.Limits {
		limit, err := resource.ParseLimit(resource.Type(typ), v)
		if err != nil {
			return nil, fmt.Errorf("error parsing limit %q = %q: %s", typ, v, err)
		}
		job.Resources.SetLimit(resource.Type(typ), limit)
	}

	// mount the shared directory at /mnt as a 9p filesystem
	ln, err := net.Listen("tcp", os.Getenv("EXTERNAL_IP")+":0")
	if err != nil {
		return nil, err
	}
	defer ln.Close()
	go serveFilesystem(dir, ln)
	addr := ln.Addr().(*net.TCPAddr)
	job.Config.Mounts = append(job.Config.Mounts, host.Mount{
		Device:   "9p",
		Location: "/mnt",
		Target:   addr.IP.String(),
		Data:     fmt.Sprintf("trans=tcp,port=%d", addr.Port),
	})
	job.Config.WorkingDir = "/mnt/src"

	if artifact == nil {
		// use the base layer if there is no artifact to build with
		job.Mountspecs = []*host.Mountspec{b.baseLayer}
	} else {
		utils.SetupMountspecs(job, []*ct.Artifact{artifact})
	}

	// copy output to log file + prefix stdout / stderr with the layer name
	logPath := filepath.Join("build/log", name+".log")
	if err := os.MkdirAll(filepath.Dir(logPath), 0755); err != nil {
		return nil, err
	}
	logFile, err := os.Create(logPath)
	if err != nil {
		return nil, err
	}
	logR, logW := io.Pipe()
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return nil, err
	}
	go io.Copy(logW, stdout)
	stderr, err := cmd.StderrPipe()
	if err != nil {
		return nil, err
	}
	go io.Copy(logW, stderr)
	go func() {
		defer logFile.Close()
		s := bufio.NewScanner(logR)
		for s.Scan() {
			fmt.Fprintf(os.Stderr, "%s: %s: %s\n", time.Now().Format("15:04:05.999"), name, s.Text())
			fmt.Fprintln(logFile, s.Text())
		}
	}()

	// run the job
	b.log.Info("building layer", "layer.name", name, "layer.id", id)
	if err := cmd.Run(); err != nil {
		b.log.Error("error running the build job", "name", name, "err", err)
		return nil, err
	}

	// copy the layer to the cache
	f, err := os.Open(filepath.Join(dir, "out", "layer.squashfs"))
	if err != nil {
		return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
	}
	defer f.Close()
	stat, err := f.Stat()
	if err != nil {
		return nil, fmt.Errorf("error opening SquashFS layer: %s", err)
	}
	h := sha512.New512_256()
	dst, err := os.Create(b.layerPath(id))
	if err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	defer dst.Close()
	if _, err := io.Copy(dst, io.TeeReader(f, h)); err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	layer = &ct.ImageLayer{
		ID:     id,
		Type:   ct.ImageLayerTypeSquashfs,
		Length: stat.Size(),
		Hashes: map[string]string{
			"sha512_256": hex.EncodeToString(h.Sum(nil)),
		},
	}
	data, err := json.Marshal(layer)
	if err != nil {
		return nil, fmt.Errorf("error encoding layer config: %s", err)
	}
	if err := ioutil.WriteFile(b.layerConfigPath(id), data, 0644); err != nil {
		return nil, fmt.Errorf("error writing to layer cache: %s", err)
	}
	return layer, nil
}
1196632
func ApplyConfigFile(file string) error {
	ext := filepath.Ext(file)
	switch ext {
	case ".json":
		return ApplyJsonConfigFile(file)
	case ".yml":
		fallthrough
	case ".yaml":
		return ApplyYAMLConfigFile(file)
	default:
		return errors.New(fmt.Sprintf(
			"unknown format of the specified file: %s", file))
	}
}
829536
func (a AptLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
	diff, err := singleVersionLayerDiff(image1, image2, a)
	return diff, err
}
624058
func applyLayerHandler(dest string, layer io.Reader, options *TarOptions, decompress bool) (int64, error) {
	dest = filepath.Clean(dest)

	// We need to be able to set any perms
	oldmask, err := system.Umask(0)
	if err != nil {
		return 0, err
	}
	defer system.Umask(oldmask) // ignore err, ErrNotSupportedPlatform

	if decompress {
		layer, err = DecompressStream(layer)
		if err != nil {
			return 0, err
		}
	}
	return UnpackLayer(dest, layer, options)
}
640788
func (s *FIFOStrategy) Apply(nodes []Node) Node {
	if len(nodes) == 0 {
		return Node{}
	}
	return nodes[0]
}
718607
func (o groupResourceOverrides) Apply(config *storagebackend.Config, options *StorageCodecConfig) {
	if len(o.etcdLocation) > 0 {
		config.Transport.ServerList = o.etcdLocation
	}
	if len(o.etcdPrefix) > 0 {
		config.Prefix = o.etcdPrefix
	}

	if len(o.mediaType) > 0 {
		options.StorageMediaType = o.mediaType
	}
	if o.serializer != nil {
		options.StorageSerializer = o.serializer
	}
	if o.encoderDecoratorFn != nil {
		options.EncoderDecoratorFn = o.encoderDecoratorFn
	}
	if o.decoderDecoratorFn != nil {
		options.DecoderDecoratorFn = o.decoderDecoratorFn
	}
	if o.transformer != nil {
		config.Transformer = o.transformer
	}
	if o.disablePaging {
		config.Paging = false
	}
}
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
}
286910
func (g *Git) Apply(patch string) *command.Model {
	return g.command("apply", "--index", patch)
}
1037927
func (d *Delta) Apply(latest []byte) ([]byte, error) {
	base, err := yaml.ToJSON(latest)
	if err != nil {
		return nil, err
	}
	changes, err := jsonpatch.CreateMergePatch(d.original, base)
	if err != nil {
		return nil, err
	}
	diff1 := make(map[string]interface{})
	if err := json.Unmarshal(d.edit, &diff1); err != nil {
		return nil, err
	}
	diff2 := make(map[string]interface{})
	if err := json.Unmarshal(changes, &diff2); err != nil {
		return nil, err
	}
	for _, fn := range d.preconditions {
		if !fn(diff1) || !fn(diff2) {
			return nil, ErrPreconditionFailed
		}
	}

	klog.V(6).Infof("Testing for conflict between:\n%s\n%s", string(d.edit), string(changes))
	if hasConflicts(diff1, diff2) {
		return nil, ErrConflict
	}
	return jsonpatch.MergePatch(base, d.edit)
}
1280035
func Apply(ctx context.Context, root string, r io.Reader, opts ...ApplyOpt) (int64, error) {
	root = filepath.Clean(root)

	var options ApplyOptions
	for _, opt := range opts {
		if err := opt(&options); err != nil {
			return 0, errors.Wrap(err, "failed to apply option")
		}
	}
	if options.Filter == nil {
		options.Filter = all
	}

	return apply(ctx, root, tar.NewReader(r), options)
}
843901
func (d *Driver) ApplyDiff(id string, parent string, diff io.Reader) (size int64, err error) {
	if !d.isParent(id, parent) {
		return d.naiveDiff.ApplyDiff(id, parent, diff)
	}

	applyDir := d.getDiffPath(id)

	logger.Debugf("Applying tar in %s", applyDir)
	// Overlay doesn't need the parent id to apply the diff
	if err := untar(diff, applyDir, &archive.TarOptions{
		UIDMaps:        d.uidMaps,
		GIDMaps:        d.gidMaps,
		WhiteoutFormat: archive.OverlayWhiteoutFormat,
		InUserNS:       rsystem.RunningInUserNS(),
	}); err != nil {
		return 0, err
	}

	return directory.Size(context.TODO(), applyDir)
}
893456
func (s *StaticImageDeactivateScheduleActionSettings) SetLayer(v int64) *StaticImageDeactivateScheduleActionSettings {
	s.Layer = &v
	return s
}