// ApplyUncompressedLayer 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.
191725
func ApplyUncompressedLayer(dest string, layer io.Reader, options *archive.TarOptions) (int64, error) {
	return applyLayerHandler(dest, layer, options, false)
}
88043
func (b *Builder) ApplyDiff(m *meta.Meta, diff *model.SchemaDiff) ([]int64, error) {
	b.is.schemaMetaVersion = diff.Version
	if diff.Type == model.ActionCreateSchema {
		return nil, b.applyCreateSchema(m, diff)
	} else if diff.Type == model.ActionDropSchema {
		tblIDs := b.applyDropSchema(diff.SchemaID)
		return tblIDs, nil
	}

	roDBInfo, ok := b.is.SchemaByID(diff.SchemaID)
	if !ok {
		return nil, ErrDatabaseNotExists.GenWithStackByArgs(
			fmt.Sprintf("(Schema ID %d)", diff.SchemaID),
		)
	}
	var oldTableID, newTableID int64
	tblIDs := make([]int64, 0, 2)
	switch diff.Type {
	case model.ActionCreateTable, model.ActionRecoverTable:
		newTableID = diff.TableID
		tblIDs = append(tblIDs, newTableID)
	case model.ActionDropTable, model.ActionDropView:
		oldTableID = diff.TableID
		tblIDs = append(tblIDs, oldTableID)
	case model.ActionTruncateTable:
		oldTableID = diff.OldTableID
		newTableID = diff.TableID
		tblIDs = append(tblIDs, oldTableID, newTableID)
	default:
		oldTableID = diff.TableID
		newTableID = diff.TableID
		tblIDs = append(tblIDs, oldTableID)
	}
	dbInfo := b.copySchemaTables(roDBInfo.Name.L)
	b.copySortedTables(oldTableID, newTableID)

	// We try to reuse the old allocator, so the cached auto ID can be reused.
	var alloc autoid.Allocator
	if tableIDIsValid(oldTableID) {
		if oldTableID == newTableID && diff.Type != model.ActionRenameTable && diff.Type != model.ActionRebaseAutoID {
			alloc, _ = b.is.AllocByID(oldTableID)
		}
		if diff.Type == model.ActionRenameTable && diff.OldSchemaID != diff.SchemaID {
			oldRoDBInfo, ok := b.is.SchemaByID(diff.OldSchemaID)
			if !ok {
				return nil, ErrDatabaseNotExists.GenWithStackByArgs(
					fmt.Sprintf("(Schema ID %d)", diff.OldSchemaID),
				)
			}
			oldDBInfo := b.copySchemaTables(oldRoDBInfo.Name.L)
			b.applyDropTable(oldDBInfo, oldTableID)
		} else {
			b.applyDropTable(dbInfo, oldTableID)
		}
	}
	if tableIDIsValid(newTableID) {
		// All types except DropTableOrView.
		err := b.applyCreateTable(m, dbInfo, newTableID, alloc)
		if err != nil {
			return nil, errors.Trace(err)
		}
	}
	return tblIDs, 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))
	}
}
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()
	}
}
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
}
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))
}
1237881
func (ns *Namespace) Apply(seq interface{}, fname string, args ...interface{}) (interface{}, error) {
	if seq == nil {
		return make([]interface{}, 0), nil
	}

	if fname == "apply" {
		return nil, errors.New("can't apply myself (no turtles allowed)")
	}

	seqv := reflect.ValueOf(seq)
	seqv, isNil := indirect(seqv)
	if isNil {
		return nil, errors.New("can't iterate over a nil value")
	}

	fnv, found := ns.lookupFunc(fname)
	if !found {
		return nil, errors.New("can't find function " + fname)
	}

	// fnv := reflect.ValueOf(fn)

	switch seqv.Kind() {
	case reflect.Array, reflect.Slice:
		r := make([]interface{}, seqv.Len())
		for i := 0; i < seqv.Len(); i++ {
			vv := seqv.Index(i)

			vvv, err := applyFnToThis(fnv, vv, args...)

			if err != nil {
				return nil, err
			}

			r[i] = vvv.Interface()
		}

		return r, nil
	default:
		return nil, fmt.Errorf("can't apply over %v", seq)
	}
}
469188
func (d *Driver) ApplyDiff(id string, parent string, diff archive.Reader) (size int64, err error) {
	dir := path.Join(virtPath, id)
	// dir := path.Join("/tmp/chainfs/", id)

	logrus.Infof("Applying diff at path %s\n", dir)

	if err := chrootarchive.UntarUncompressed(diff, dir, nil); err != nil {
		logrus.Warnf("Error while applying diff to %s: %v", id, err)
		return 0, err
	}

	// show invalid whiteouts warning.
	files, err := ioutil.ReadDir(path.Join(dir, archive.WhiteoutLinkDir))
	if err == nil && len(files) > 0 {
		logrus.Warnf("Archive contains aufs hardlink references that are not supported.")
	}

	return d.DiffSize(id, parent)
}
65019
func (t *TriggerDefinition) Apply(obj runtime.Object) error {
	switch c := obj.(type) {
	case *appsv1.DeploymentConfig:
		if len(t.GitHubWebHooks) > 0 {
			return fmt.Errorf("deployment configs do not support GitHub web hooks")
		}
		if len(t.GenericWebHooks) > 0 {
			return fmt.Errorf("deployment configs do not support web hooks")
		}
		if len(t.GitLabWebHooks) > 0 {
			return fmt.Errorf("deployment configs do not support GitLab web hooks")
		}
		if len(t.BitbucketWebHooks) > 0 {
			return fmt.Errorf("deployment configs do not support Bitbucket web hooks")
		}

		existingTriggers := filterDeploymentTriggers(c.Spec.Triggers, appsv1.DeploymentTriggerOnConfigChange)
		var triggers []appsv1.DeploymentTriggerPolicy
		if t.ConfigChange {
			triggers = append(triggers, appsv1.DeploymentTriggerPolicy{Type: appsv1.DeploymentTriggerOnConfigChange})
		}
		allNames := sets.NewString()
		for _, container := range c.Spec.Template.Spec.Containers {
			allNames.Insert(container.Name)
		}
		for _, container := range c.Spec.Template.Spec.InitContainers {
			allNames.Insert(container.Name)
		}
		for _, trigger := range t.ImageChange {
			if len(trigger.Names) == 0 {
				return fmt.Errorf("you must specify --containers when setting --from-image")
			}
			if !allNames.HasAll(trigger.Names...) {
				return fmt.Errorf(
					"not all container names exist: %s (accepts: %s)",
					strings.Join(sets.NewString(trigger.Names...).Difference(allNames).List(), ", "),
					strings.Join(allNames.List(), ", "),
				)
			}
			triggers = append(triggers, appsv1.DeploymentTriggerPolicy{
				Type: appsv1.DeploymentTriggerOnImageChange,
				ImageChangeParams: &appsv1.DeploymentTriggerImageChangeParams{
					Automatic: trigger.Auto,
					From: corev1.ObjectReference{
						Kind:      "ImageStreamTag",
						Name:      trigger.From,
						Namespace: trigger.Namespace,
					},
					ContainerNames: trigger.Names,
				},
			})
		}
		c.Spec.Triggers = mergeDeployTriggers(existingTriggers, triggers)
		return nil

	case *buildv1.BuildConfig:
		var triggers []buildv1.BuildTriggerPolicy
		if t.ConfigChange {
			triggers = append(triggers, buildv1.BuildTriggerPolicy{Type: buildv1.ConfigChangeBuildTriggerType})
		}
		for i := range t.GenericWebHooks {
			triggers = append(triggers, buildv1.BuildTriggerPolicy{
				Type:           buildv1.GenericWebHookBuildTriggerType,
				GenericWebHook: &t.GenericWebHooks[i],
			})
		}
		for i := range t.GitHubWebHooks {
			triggers = append(triggers, buildv1.BuildTriggerPolicy{
				Type:          buildv1.GitHubWebHookBuildTriggerType,
				GitHubWebHook: &t.GitHubWebHooks[i],
			})
		}
		for i := range t.GitLabWebHooks {
			triggers = append(triggers, buildv1.BuildTriggerPolicy{
				Type:          buildv1.GitLabWebHookBuildTriggerType,
				GitLabWebHook: &t.GitLabWebHooks[i],
			})
		}
		for i := range t.BitbucketWebHooks {
			triggers = append(triggers, buildv1.BuildTriggerPolicy{
				Type:             buildv1.BitbucketWebHookBuildTriggerType,
				BitbucketWebHook: &t.BitbucketWebHooks[i],
			})
		}

		// add new triggers, filter out any old triggers that match (if moving from automatic to manual),
		// and then merge the old triggers and the new triggers to preserve fields like lastTriggeredImageID
		existingTriggers := c.Spec.Triggers
		strategyTrigger := strategyTrigger(c)
		for _, trigger := range t.ImageChange {
			change := &buildv1.ImageChangeTrigger{
				From: &corev1.ObjectReference{
					Kind:      "ImageStreamTag",
					Name:      trigger.From,
					Namespace: trigger.Namespace,
				},
			}

			// use the canonical ImageChangeTrigger with nil From
			if strategyTrigger != nil {
				strategyTrigger.Auto = trigger.Auto
			}
			if reflect.DeepEqual(strategyTrigger, &trigger) {
				change.From = nil
			}

			// if this trigger is not automatic, then we need to remove it from the list of triggers
			if !trigger.Auto {
				existingTriggers = filterBuildImageTriggers(existingTriggers, trigger, strategyTrigger)
				continue
			}

			triggers = append(triggers, buildv1.BuildTriggerPolicy{
				Type:        buildv1.ImageChangeBuildTriggerType,
				ImageChange: change,
			})
		}
		c.Spec.Triggers = mergeBuildTriggers(existingTriggers, triggers)
		return nil

	case *extensionsv1beta1.DaemonSet, *kappsv1beta2.DaemonSet, *kappsv1.DaemonSet,
		*extensionsv1beta1.Deployment, *kappsv1beta1.Deployment, *kappsv1beta2.Deployment, *kappsv1.Deployment,
		*kappsv1beta1.StatefulSet, *kappsv1beta2.StatefulSet, *kappsv1.StatefulSet,
		*batchv1beta1.CronJob, *batchv2alpha1.CronJob:

		if len(t.GitHubWebHooks) > 0 {
			return fmt.Errorf("does not support GitHub web hooks")
		}
		if len(t.GenericWebHooks) > 0 {
			return fmt.Errorf("does not support web hooks")
		}
		if len(t.GitLabWebHooks) > 0 {
			return fmt.Errorf("does not support GitLab web hooks")
		}
		if len(t.BitbucketWebHooks) > 0 {
			return fmt.Errorf("does not support Bitbucket web hooks")
		}
		m, err := meta.Accessor(obj)
		if err != nil {
			return err
		}
		spec, path, err := ometa.GetPodSpecV1(obj)
		if err != nil {
			return err
		}
		allNames := sets.NewString()
		for _, container := range spec.Containers {
			allNames.Insert(container.Name)
		}
		for _, container := range spec.InitContainers {
			allNames.Insert(container.Name)
		}
		alreadyTriggered := sets.NewString()
		var triggers []triggerapi.ObjectFieldTrigger
		klog.V(4).Infof("calculated triggers: %#v", t.ImageChange)
		for _, trigger := range t.ImageChange {
			if len(trigger.Names) == 0 {
				return fmt.Errorf("you must specify --containers when setting --from-image")
			}
			if !allNames.HasAll(trigger.Names...) {
				return fmt.Errorf(
					"not all container names exist: %s (accepts: %s)",
					strings.Join(sets.NewString(trigger.Names...).Difference(allNames).List(), ", "),
					strings.Join(allNames.List(), ", "),
				)
			}
			if alreadyTriggered.HasAny(trigger.Names...) {
				return fmt.Errorf("only one trigger may reference each container: %s", strings.Join(alreadyTriggered.Intersection(sets.NewString(trigger.Names...)).List(), ", "))
			}
			alreadyTriggered.Insert(trigger.Names...)

			ns := trigger.Namespace
			if ns == m.GetNamespace() {
				ns = ""
			}
			for _, name := range trigger.Names {
				triggers = append(triggers, triggerapi.ObjectFieldTrigger{
					From: triggerapi.ObjectReference{
						Kind:      "ImageStreamTag",
						Name:      trigger.From,
						Namespace: ns,
					},
					FieldPath: fmt.Sprintf(path.Child("containers").String()+"[?(@.name==\"%s\")].image", name),
					Paused:    !trigger.Auto,
				})
			}
		}
		out, err := json.Marshal(triggers)
		if err != nil {
			return err
		}
		a := m.GetAnnotations()
		if a == nil {
			a = make(map[string]string)
		}
		a[triggerapi.TriggerAnnotationKey] = string(out)
		m.SetAnnotations(a)

		switch typed := obj.(type) {
		case *extensionsv1beta1.Deployment:
			typed.Spec.Paused = !t.ConfigChange
		case *kappsv1beta1.Deployment:
			typed.Spec.Paused = !t.ConfigChange
		case *kappsv1beta2.Deployment:
			typed.Spec.Paused = !t.ConfigChange
		case *kappsv1.Deployment:
			typed.Spec.Paused = !t.ConfigChange
		}
		klog.V(4).Infof("Updated annotated object: %#v", obj)
		return nil

	default:
		return fmt.Errorf("the object is not a deployment config or build config")
	}
}
841197
func (d *Driver) ApplyDiff(id string, idMappings *idtools.IDMappings, parent string, mountLabel string, diff io.Reader) (size int64, err error) {
	if !d.isParent(id, parent) {
		return d.naiveDiff.ApplyDiff(id, idMappings, parent, mountLabel, diff)
	}

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

	applyDir := d.getDiffPath(id)

	logrus.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:        idMappings.UIDs(),
		GIDMaps:        idMappings.GIDs(),
		WhiteoutFormat: d.getWhiteoutFormat(),
		InUserNS:       rsystem.RunningInUserNS(),
	}); err != nil {
		return 0, err
	}

	_, convert := d.convert[id]
	if convert {
		if err := ostree.ConvertToOSTree(d.options.ostreeRepo, applyDir, id); err != nil {
			return 0, err
		}
	}

	return directory.Size(applyDir)
}
303020
func (mf *MigrationFiles) Applied(versions Versions) (Files, error) {
	sort.Sort(sort.Reverse(mf))
	files := make(Files, 0)
	for _, migrationFile := range *mf {
		if versions.Contains(migrationFile.Version) && migrationFile.DownFile != nil {
			files = append(files, *migrationFile.DownFile)
		}
	}
	return files, nil
}
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)
}
907579
func (a FileLayerAnalyzer) Diff(image1, image2 pkgutil.Image) (util.Result, error) {
	var dirDiffs []util.DirDiff

	// Go through each layer of the first image...
	for index, layer := range image1.Layers {
		if index >= len(image2.Layers) {
			continue
		}
		// ...else, diff as usual
		layer2 := image2.Layers[index]
		diff, err := diffImageFiles(layer.FSPath, layer2.FSPath)
		if err != nil {
			return &util.MultipleDirDiffResult{}, err
		}
		dirDiffs = append(dirDiffs, diff)
	}

	// check if there are any additional layers in either image
	if len(image1.Layers) != len(image2.Layers) {
		if len(image1.Layers) > len(image2.Layers) {
			logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image1.Source)
		} else {
			logrus.Infof("%s has additional layers, please use container-diff analyze to view the files in these layers", image2.Source)
		}
	}
	return &util.MultipleDirDiffResult{
		Image1:   image1.Source,
		Image2:   image2.Source,
		DiffType: "FileLayer",
		Diff: util.MultipleDirDiff{
			DirDiffs: dirDiffs,
		},
	}, nil
}
995163
func ApplyStreamInbound(h transport.StreamHandler, i StreamInbound) transport.StreamHandler {
	if i == nil {
		return h
	}
	return streamHandlerWithMiddleware{h: h, i: i}
}
967216
func ApplyJsonConfigFile(file string) error {
	bin, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}
	decoder := json.NewDecoder(bytes.NewBuffer(bin))
	decoder.UseNumber()
	var conf Conf
	if err = decoder.Decode(&conf); err != nil {
		return err
	}
	return DictConfig(&conf)
}
1262494
func (op *op) apply(b *Bitmap) (changed bool) {
	switch op.typ {
	case opTypeAdd:
		return b.DirectAdd(op.value)
	case opTypeRemove:
		return b.remove(op.value)
	case opTypeAddBatch:
		changed = b.DirectAddN(op.values...) > 0
	case opTypeRemoveBatch:
		changed = b.DirectRemoveN(op.values...) > 0
	default:
		panic(fmt.Sprintf("invalid op type: %d", op.typ))
	}
	return changed
}
1073562
func (s *Store) Apply(l *raft.Log) interface{} {
	s.restoreMu.RLock()
	defer s.restoreMu.RUnlock()

	var c command
	if err := json.Unmarshal(l.Data, &c); err != nil {
		panic(fmt.Sprintf("failed to unmarshal cluster command: %s", err.Error()))
	}

	switch c.Typ {
	case execute, query:
		var d databaseSub
		if err := json.Unmarshal(c.Sub, &d); err != nil {
			return &fsmGenericResponse{error: err}
		}

		s.connsMu.RLock()
		conn, ok := s.conns[d.ConnID]
		s.connsMu.RUnlock()
		if !ok {
			return &fsmGenericResponse{error: ErrConnectionDoesNotExist}
		}

		if c.Typ == execute {
			txChange := NewTxStateChange(conn)
			r, err := conn.db.Execute(d.Queries, d.Atomic, d.Timings)
			txChange.CheckAndSet()
			return &fsmExecuteResponse{results: r, error: err}
		}
		r, err := conn.db.Query(d.Queries, d.Atomic, d.Timings)
		return &fsmQueryResponse{rows: r, error: err}
	case metadataSet:
		var d metadataSetSub
		if err := json.Unmarshal(c.Sub, &d); err != nil {
			return &fsmGenericResponse{error: err}
		}
		func() {
			s.metaMu.Lock()
			defer s.metaMu.Unlock()
			if _, ok := s.meta[d.RaftID]; !ok {
				s.meta[d.RaftID] = make(map[string]string)
			}
			for k, v := range d.Data {
				s.meta[d.RaftID][k] = v
			}
		}()
		return &fsmGenericResponse{}
	case metadataDelete:
		var d string
		if err := json.Unmarshal(c.Sub, &d); err != nil {
			return &fsmGenericResponse{error: err}
		}
		func() {
			s.metaMu.Lock()
			defer s.metaMu.Unlock()
			delete(s.meta, d)
		}()
		return &fsmGenericResponse{}
	case connect:
		var d connectionSub
		if err := json.Unmarshal(c.Sub, &d); err != nil {
			return &fsmGenericResponse{error: err}
		}

		conn, err := s.db.Connect()
		if err != nil {
			return &fsmGenericResponse{error: err}
		}
		s.connsMu.Lock()
		s.conns[d.ConnID] = NewConnection(conn, s, d.ConnID, d.IdleTimeout, d.TxTimeout)
		s.connsMu.Unlock()
		return d.ConnID
	case disconnect:
		var d connectionSub
		if err := json.Unmarshal(c.Sub, &d); err != nil {
			return &fsmGenericResponse{error: err}
		}

		if d.ConnID == defaultConnID {
			return &fsmGenericResponse{error: ErrDefaultConnection}
		}

		return func() interface{} {
			s.connsMu.Lock()
			defer s.connsMu.Unlock()
			delete(s.conns, d.ConnID)
			return &fsmGenericResponse{}
		}()

	default:
		return &fsmGenericResponse{error: fmt.Errorf("unknown command: %v", c.Typ)}
	}
}