// manifestDeployError annotates or replaces the supplied error according
// to whether or not an upgrade operation is in play. It was extracted from
// Deploy to aid that method's readability.
775845
func manifestDeployError(err *error, upgrading bool) {
	if *err != nil {
		if upgrading {
			// We now treat any failure to overwrite the charm -- or otherwise
			// manipulate the charm directory -- as a conflict, because it's
			// actually plausible for a user (or at least a charm author, who
			// is the real audience for this case) to get in there and fix it.
			logger.Errorf("cannot upgrade charm: %v", *err)
			*err = ErrConflict
		} else {
			// ...but if we can't install at all, we just fail out as the old
			// gitDeployer did, because I'm not willing to mess around with
			// the uniter to enable ErrConflict handling on install. We've
			// never heard of it actually happening, so this is probably not
			// a big deal.
			*err = fmt.Errorf("cannot install charm: %v", *err)
		}
	}
}
260242
func formatError(format string, err error) error {
	if s, ok := err.(errors.APIStatus); ok {
		se := &errors.StatusError{ErrStatus: s.Status()}
		se.ErrStatus.Message = fmt.Sprintf(format, se.ErrStatus.Message)
		return se
	}
	return fmt.Errorf(format, err)
}
1194032
func (o *TaskTrackerAPI) ServeErrorFor(operationID string) func(http.ResponseWriter, *http.Request, error) {
	return o.ServeError
}
682761
func StackDeploy(name, content string, authes map[string]string) error {
	ctx, cli, err := mgr.Client()
	if err != nil {
		return err
	}

	cfg, err := compose.Parse(name, content)
	if err != nil {
		return err
	}

	namespace := compose.NewNamespace(name)

	serviceNetworks := compose.GetServicesDeclaredNetworks(cfg.Services)
	networks, externalNetworks := compose.Networks(namespace, cfg.Networks, serviceNetworks)
	if err = validateExternalNetworks(ctx, cli, externalNetworks); err != nil {
		return err
	}
	if err = createNetworks(ctx, cli, namespace, networks); err != nil {
		return err
	}

	secrets, err := compose.Secrets(namespace, cfg.Secrets)
	if err != nil {
		return err
	}
	if err = createSecrets(ctx, cli, secrets); err != nil {
		return err
	}

	configs, err := compose.Configs(namespace, cfg.Configs)
	if err != nil {
		return err
	}
	if err = createConfigs(ctx, cli, configs); err != nil {
		return err
	}

	services, err := compose.Services(namespace, cfg, cli)
	if err != nil {
		return err
	}
	return deployServices(ctx, cli, services, namespace, authes)
}
181829
func (cli *DockerCli) ManifestStore() manifeststore.Store {
	// TODO: support override default location from config file
	return manifeststore.NewStore(filepath.Join(config.Dir(), "manifests"))
}
496082
func formatError(err error) string {
	if err, ok := err.(kerrs.Aggregate); ok {
		var errorStrings []string
		for _, err := range err.Errors() {
			errorStrings = append(errorStrings, err.Error())
		}
		return strings.Join(errorStrings, "\n")
	}

	return err.Error()
}
742194
func (c *retryRepository) Manifests(ctx context.Context, options ...distribution.ManifestServiceOption) (distribution.ManifestService, error) {
	s, err := c.Repository.Manifests(ctx, options...)
	if err != nil {
		return nil, err
	}
	return retryManifest{ManifestService: s, repo: c}, nil
}
1323043
func SetDeploymentAnnotationsTo(deployment *apps.Deployment, rollbackToRS *apps.ReplicaSet) {
	deployment.Annotations = getSkippedAnnotations(deployment.Annotations)
	for k, v := range rollbackToRS.Annotations {
		if !skipCopyAnnotation(k) {
			deployment.Annotations[k] = v
		}
	}
}
327783
func InterpretUpdateError(err error, qualifiedResource schema.GroupResource, name string) error {
	switch {
	case storage.IsConflict(err), storage.IsNodeExist(err), storage.IsInvalidObj(err):
		return errors.NewConflict(qualifiedResource, name, err)
	case storage.IsUnreachable(err):
		return errors.NewServerTimeout(qualifiedResource, "update", 2) // TODO: make configurable or handled at a higher level
	case storage.IsNotFound(err):
		return errors.NewNotFound(qualifiedResource, name)
	case storage.IsInternalError(err):
		return errors.NewInternalError(err)
	default:
		return err
	}
}
580503
func (s *DeploymentStyle) SetDeploymentType(v string) *DeploymentStyle {
	s.DeploymentType = &v
	return s
}
230888
func (up *tenantURLProvider) CanDeploy(envType string) bool {
	_, pres := internalNamespaceTypes[envType]
	return !pres
}
754524
func RunDeploy(dockerCli command.Cli, flags *pflag.FlagSet, config *composetypes.Config, commonOrchestrator command.Orchestrator, opts options.Deploy) error {
	return runOrchestratedCommand(dockerCli, flags, commonOrchestrator,
		func() error { return swarm.RunDeploy(dockerCli, opts, config) },
		func(kli *kubernetes.KubeCli) error { return kubernetes.RunDeploy(kli, opts, config) })
}
1357321
func (a *Remote) Manifest(ctx context.Context, ref string) (ImageEntry, error) {
	repository, err := client.NewRepository(named{a.repo}, a.base, a.transport)
	if err != nil {
		return ImageEntry{}, err
	}
	manifests, err := repository.Manifests(ctx)
	if err != nil {
		return ImageEntry{}, err
	}
	var manifestDigest digest.Digest
	digestOpt := client.ReturnContentDigest(&manifestDigest)
	manifest, fetchErr := manifests.Get(ctx, digest.Digest(ref), digestOpt, distribution.WithTagOption{ref})

interpret:
	if fetchErr != nil {
		return ImageEntry{}, fetchErr
	}

	info := image.Info{ID: a.repo.ToRef(ref), Digest: manifestDigest.String()}

	// TODO(michael): can we type switch? Not sure how dependable the
	// underlying types are.
	switch deserialised := manifest.(type) {
	case *schema1.SignedManifest:
		var man schema1.Manifest = deserialised.Manifest
		// for decoding the v1-compatibility entry in schema1 manifests
		var v1 struct {
			ID      string    `json:"id"`
			Created time.Time `json:"created"`
			OS      string    `json:"os"`
			Arch    string    `json:"architecture"`
		}

		if err = json.Unmarshal([]byte(man.History[0].V1Compatibility), &v1); err != nil {
			return ImageEntry{}, err
		}
		// This is not the ImageID that Docker uses, but assumed to
		// identify the image as it's the topmost layer.
		info.ImageID = v1.ID
		info.CreatedAt = v1.Created
	case *schema2.DeserializedManifest:
		var man schema2.Manifest = deserialised.Manifest
		configBytes, err := repository.Blobs(ctx).Get(ctx, man.Config.Digest)
		if err != nil {
			return ImageEntry{}, err
		}

		var config struct {
			Arch    string    `json:"architecture"`
			Created time.Time `json:"created"`
			OS      string    `json:"os"`
		}
		if err = json.Unmarshal(configBytes, &config); err != nil {
			return ImageEntry{}, err
		}
		// This _is_ what Docker uses as its Image ID.
		info.ImageID = man.Config.Digest.String()
		info.CreatedAt = config.Created
	case *manifestlist.DeserializedManifestList:
		var list manifestlist.ManifestList = deserialised.ManifestList
		// TODO(michael): is it valid to just pick the first one that matches?
		for _, m := range list.Manifests {
			if m.Platform.OS == "linux" && m.Platform.Architecture == "amd64" {
				manifest, fetchErr = manifests.Get(ctx, m.Digest, digestOpt)
				goto interpret
			}
		}
		entry := ImageEntry{}
		entry.ExcludedReason = "no suitable manifest (linux amd64) in manifestlist"
		return entry, nil
	default:
		t := reflect.TypeOf(manifest)
		return ImageEntry{}, errors.New("unknown manifest type: " + t.String())
	}
	return ImageEntry{Info: info}, nil
}
496455
func (w *deploymentWatcher) getDeployment() *structs.Deployment {
	w.l.RLock()
	defer w.l.RUnlock()
	return w.d
}
486325
func managerError(c ErrorCode, desc string, err error) ManagerError {
	return ManagerError{ErrorCode: c, Description: desc, Err: err}
}
547922
func (h *charmsHandler) manifestSender(w http.ResponseWriter, r *http.Request, bundle *charm.CharmArchive) error {
	manifest, err := bundle.Manifest()
	if err != nil {
		return errors.Annotatef(err, "unable to read manifest in %q", bundle.Path)
	}
	return errors.Trace(sendStatusAndJSON(w, http.StatusOK, &params.CharmsResponse{
		Files: manifest.SortedValues(),
	}))
}
412457
func (api *APIBase) Deploy(args params.ApplicationsDeploy) (params.ErrorResults, error) {
	if err := api.checkCanWrite(); err != nil {
		return params.ErrorResults{}, errors.Trace(err)
	}
	result := params.ErrorResults{
		Results: make([]params.ErrorResult, len(args.Applications)),
	}
	if err := api.check.ChangeAllowed(); err != nil {
		return result, errors.Trace(err)
	}

	for i, arg := range args.Applications {
		err := deployApplication(api.backend, api.model, api.stateCharm, arg, api.deployApplicationFunc, api.storagePoolManager, api.registry, api.storageValidator)
		result.Results[i].Error = common.ServerError(err)

		if err != nil && len(arg.Resources) != 0 {
			// Remove any pending resources - these would have been
			// converted into real resources if the application had
			// been created successfully, but will otherwise be
			// leaked. lp:1705730
			// TODO(babbageclunk): rework the deploy API so the
			// resources are created transactionally to avoid needing
			// to do this.
			resources, err := api.backend.Resources()
			if err != nil {
				logger.Errorf("couldn't get backend.Resources")
				continue
			}
			err = resources.RemovePendingAppResources(arg.ApplicationName, arg.Resources)
			if err != nil {
				logger.Errorf("couldn't remove pending resources for %q", arg.ApplicationName)
			}
		}
	}
	return result, nil
}