// ApplyManifest applies on the resources in a manifest to
// the given context.
765589
func ApplyManifest(ctx Context, manifest *Manifest) error {
	for _, resource := range manifest.Resources {
		if err := ctx.Apply(resource); err != nil {
			return err
		}
	}

	return nil
}
1005755
func (k *Kubectl) Apply(context string, data []byte) error {
	localManifestFile, err := ioutil.TempFile("", "manifest")
	if err != nil {
		return fmt.Errorf("error creating temp file: %v", err)
	}

	defer func() {
		if err := os.Remove(localManifestFile.Name()); err != nil {
			glog.Warningf("error deleting temp file %q: %v", localManifestFile.Name(), err)
		}
	}()

	if err := ioutil.WriteFile(localManifestFile.Name(), data, 0600); err != nil {
		return fmt.Errorf("error writing temp file: %v", err)
	}

	_, _, err = k.execKubectl("apply", "--context", context, "-f", localManifestFile.Name())
	return err
}
743982
func Apply(c *cli.Context) {
	if len(c.Args()) != 1 {
		MaybeError(c, "Usage should be apply [filename]")
	}
	filename := c.Args()[0]

	jsonbytes, err := ioutil.ReadFile(filename)
	if err != nil {
		MaybeError(c, fmt.Sprintf("Unable to read %s: %s", filename, err))
	}

	hostfile := AlwaysLoadHostFile(c)
	err = hostfile.Hosts.Apply(jsonbytes)
	if err != nil {
		MaybeError(c, fmt.Sprintf("Error applying changes to hosts file: %s", err))
	}

	MaybeSaveHostFile(c, hostfile)
	MaybePrintln(c, fmt.Sprintf("%s applied", filename))
}
636345
func WriteManifest(manifestWriter io.Writer, compression *pwr.CompressionSettings, container *tlc.Container, blockHashes *BlockHashMap) error {
	rawWire := wire.NewWriteContext(manifestWriter)
	err := rawWire.WriteMagic(pwr.ManifestMagic)
	if err != nil {
		return errors.WithStack(err)
	}

	err = rawWire.WriteMessage(&pwr.ManifestHeader{
		Compression: compression,
		Algorithm:   pwr.HashAlgorithm_SHAKE128_32,
	})
	if err != nil {
		return errors.WithStack(err)
	}

	wire, err := pwr.CompressWire(rawWire, compression)
	if err != nil {
		return errors.WithStack(err)
	}

	err = wire.WriteMessage(container)
	if err != nil {
		return errors.WithStack(err)
	}

	sh := &pwr.SyncHeader{}
	mbh := &pwr.ManifestBlockHash{}

	for fileIndex, f := range container.Files {
		sh.Reset()
		sh.FileIndex = int64(fileIndex)
		err = wire.WriteMessage(sh)
		if err != nil {
			return errors.WithStack(err)
		}

		numBlocks := ComputeNumBlocks(f.Size)

		for blockIndex := int64(0); blockIndex < numBlocks; blockIndex++ {
			loc := BlockLocation{FileIndex: int64(fileIndex), BlockIndex: blockIndex}
			hash := blockHashes.Get(loc)
			if hash == nil {
				err = fmt.Errorf("missing BlockHash for block %+v", loc)
				return errors.WithStack(err)
			}

			mbh.Reset()
			mbh.Hash = hash

			err = wire.WriteMessage(mbh)
			if err != nil {
				return errors.WithStack(err)
			}
		}
	}

	err = wire.Close()
	if err != nil {
		return errors.WithStack(err)
	}

	return nil
}
339908
func (c *client) PutManifest(ctx context.Context, ref reference.Named, manifest distribution.Manifest) (digest.Digest, error) {
	repoEndpoint, err := newDefaultRepositoryEndpoint(ref, c.insecureRegistry)
	if err != nil {
		return digest.Digest(""), err
	}

	repo, err := c.getRepositoryForReference(ctx, ref, repoEndpoint)
	if err != nil {
		return digest.Digest(""), err
	}

	manifestService, err := repo.Manifests(ctx)
	if err != nil {
		return digest.Digest(""), err
	}

	_, opts, err := getManifestOptionsFromReference(ref)
	if err != nil {
		return digest.Digest(""), err
	}

	dgst, err := manifestService.Put(ctx, manifest, opts...)
	return dgst, errors.Wrapf(err, "failed to put manifest %s", ref)
}
190075
func (client *Client) GetApplicationManifest(appGUID string) ([]byte, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetApplicationManifestRequest,
		URIParams:   internal.Params{"app_guid": appGUID},
	})
	if err != nil {
		return nil, nil, err
	}
	request.Header.Set("Accept", "application/x-yaml")

	var response cloudcontroller.Response
	err = client.connection.Make(request, &response)

	return response.RawResponse, response.Warnings, err
}
997727
func AllManifests(ctx context.Context, from imagereference.DockerImageReference, repo distribution.Repository) (map[digest.Digest]distribution.Manifest, *manifestlist.DeserializedManifestList, digest.Digest, error) {
	var srcDigest digest.Digest
	if len(from.Tag) > 0 {
		desc, err := repo.Tags(ctx).Get(ctx, from.Tag)
		if err != nil {
			return nil, nil, "", err
		}
		srcDigest = desc.Digest
	} else if len(from.ID) > 0 {
		srcDigest = digest.Digest(from.ID)
	} else {
		return nil, nil, "", fmt.Errorf("no tag or digest specified")
	}
	manifests, err := repo.Manifests(ctx)
	if err != nil {
		return nil, nil, "", err
	}
	srcManifest, err := manifests.Get(ctx, srcDigest, PreferManifestList)
	if err != nil {
		return nil, nil, "", err
	}

	return ManifestsFromList(ctx, srcDigest, srcManifest, manifests, from)
}
1374087
func (k KubectlCmd) ApplyResource(config *rest.Config, obj *unstructured.Unstructured, namespace string, dryRun, force bool) (string, error) {
	log.Infof("Applying resource %s/%s in cluster: %s, namespace: %s", obj.GetKind(), obj.GetName(), config.Host, namespace)
	f, err := ioutil.TempFile(util.TempDir, "")
	if err != nil {
		return "", fmt.Errorf("Failed to generate temp file for kubeconfig: %v", err)
	}
	_ = f.Close()
	err = WriteKubeConfig(config, namespace, f.Name())
	if err != nil {
		return "", fmt.Errorf("Failed to write kubeconfig: %v", err)
	}
	defer util.DeleteFile(f.Name())
	manifestBytes, err := json.Marshal(obj)
	if err != nil {
		return "", err
	}
	var out []string
	// If it is an RBAC resource, run `kubectl auth reconcile`. This is preferred over
	// `kubectl apply`, which cannot tolerate changes in roleRef, which is an immutable field.
	// See: https://github.com/kubernetes/kubernetes/issues/66353
	// `auth reconcile` will delete and recreate the resource if necessary
	if obj.GetAPIVersion() == "rbac.authorization.k8s.io/v1" {
		// `kubectl auth reconcile` has a side effect of auto-creating namespaces if it doesn't exist.
		// See: https://github.com/kubernetes/kubernetes/issues/71185. This is behavior which we do
		// not want. We need to check if the namespace exists, before know if it is safe to run this
		// command. Skip this for dryRuns.
		if !dryRun && namespace != "" {
			kubeClient, err := kubernetes.NewForConfig(config)
			if err != nil {
				return "", err
			}
			_, err = kubeClient.CoreV1().Namespaces().Get(namespace, metav1.GetOptions{})
			if err != nil {
				return "", err
			}
		}
		outReconcile, err := runKubectl(f.Name(), namespace, []string{"auth", "reconcile"}, manifestBytes, dryRun)
		if err != nil {
			return "", err
		}
		out = append(out, outReconcile)
		// We still want to fallthrough and run `kubectl apply` in order set the
		// last-applied-configuration annotation in the object.
	}

	// Run kubectl apply
	applyArgs := []string{"apply"}
	if force {
		applyArgs = append(applyArgs, "--force")
	}
	outApply, err := runKubectl(f.Name(), namespace, applyArgs, manifestBytes, dryRun)
	if err != nil {
		return "", err
	}
	out = append(out, outApply)
	return strings.Join(out, ". "), nil
}
68218
func copyAppManifest(cdir string, appName types.ACName, dest string) error {
	appInfoDir := common.AppInfoPath(cdir, appName)
	sourceFn := filepath.Join(appInfoDir, "manifest")
	destFn := filepath.Join(dest, "manifest")
	if err := fileutil.CopyRegularFile(sourceFn, destFn); err != nil {
		return errwrap.Wrap(errors.New("error copying image manifest"), err)
	}
	return nil
}
1273055
func (r Response) ApplyContext(ctx context.Context) error {
	var req, opts, err = r.applyRequest()

	if err != nil {
		return err
	}

	return r.applyUpdate(req.WithContext(ctx), opts)
}
845681
func ReadManifest(name string) (*Manifest, []error) {
	var errs []error

	hashName, err := parseAlgoName(name)
	if err != nil {
		return nil, append(errs, err)
	}

	file, err := os.Open(name)
	if err != nil {
		return nil, append(errs, err)
	}

	data, e := parseManifestData(file)
	if e != nil {
		errs = append(errs, e...)
	}

	manifestType := PayloadManifest
	if strings.HasPrefix(path.Base(name), "tagmanifest-") {
		manifestType = TagManifest
	}
	m, err := NewManifest(name, hashName, manifestType)
	if err != nil {
		return nil, append(errs, err)
	}
	m.Data = data

	return m, errs

}
280058
func (p *Pod) PodManifest() ([]byte, *schema.PodManifest, error) {
	pmb, err := p.readFile("pod")
	if err != nil {
		return nil, nil, errwrap.Wrap(errors.New("error reading pod manifest"), err)
	}
	pm := &schema.PodManifest{}
	if err = pm.UnmarshalJSON(pmb); err != nil {
		return nil, nil, errwrap.Wrap(errors.New("invalid pod manifest"), err)
	}
	return pmb, pm, nil
}
475585
func (client *Client) UpdateApplicationApplyManifest(appGUID string, rawManifest []byte) (JobURL, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PostApplicationActionApplyManifest,
		URIParams:   map[string]string{"app_guid": appGUID},
		Body:        bytes.NewReader(rawManifest),
	})

	if err != nil {
		return "", nil, err
	}

	request.Header.Set("Content-Type", "application/x-yaml")

	response := cloudcontroller.Response{}
	err = client.connection.Make(request, &response)

	return JobURL(response.ResourceLocationURL), response.Warnings, err
}
1269098
func (vs *versionSet) createManifest(dirname string) (err error) {
	var (
		filename     = dbFilename(dirname, fileTypeManifest, vs.manifestFileNumber)
		manifestFile db.File
		manifest     *record.Writer
	)
	defer func() {
		if manifest != nil {
			manifest.Close()
		}
		if manifestFile != nil {
			manifestFile.Close()
		}
		if err != nil {
			vs.fs.Remove(filename)
		}
	}()
	manifestFile, err = vs.fs.Create(filename)
	if err != nil {
		return err
	}
	manifest = record.NewWriter(manifestFile)

	snapshot := versionEdit{
		comparatorName: vs.ucmp.Name(),
	}
	// TODO: save compaction pointers.
	for level, fileMetadata := range vs.currentVersion().files {
		for _, meta := range fileMetadata {
			snapshot.newFiles = append(snapshot.newFiles, newFileEntry{
				level: level,
				meta:  meta,
			})
		}
	}

	w, err1 := manifest.Next()
	if err1 != nil {
		return err1
	}
	err1 = snapshot.encode(w)
	if err1 != nil {
		return err1
	}

	vs.manifest, manifest = manifest, nil
	vs.manifestFile, manifestFile = manifestFile, nil
	return nil
}
530080
func ImageManifestPath(root string, appName types.ACName) string {
	return filepath.Join(AppPath(root, appName), aci.ManifestFile)
}
875416
func (s *HlsGroupSettings) SetManifestCompression(v string) *HlsGroupSettings {
	s.ManifestCompression = &v
	return s
}
935955
func VerifyManifest(ctx Context, manifest *Manifest) error {
	for _, resource := range manifest.Resources {
		if err := ctx.Verify(resource); err != nil {
			return err
		}
	}

	return nil
}