// AdoptResources asks the cloud provider to update the controller
// tags for a model's resources. This prevents the resources from
// being destroyed if the source controller is destroyed after the
// model is migrated away.
773807
func (api *API) AdoptResources(args params.AdoptResourcesArgs) error {
	tag, err := names.ParseModelTag(args.ModelTag)
	if err != nil {
		return errors.Trace(err)
	}
	st, err := api.pool.Get(tag.Id())
	if err != nil {
		return errors.Trace(err)
	}
	defer st.Release()

	m, err := st.Model()
	if err != nil {
		return errors.Trace(err)
	}

	var ra environs.ResourceAdopter
	if m.Type() == state.ModelTypeCAAS {
		ra, err = api.getCAASBroker(st.State)
	} else {
		ra, err = api.getEnviron(st.State)
	}
	if err != nil {
		return errors.Trace(err)
	}

	return errors.Trace(ra.AdoptResources(api.callContext, st.ControllerUUID(), args.SourceControllerVersion))
}
888361
func (client *Client) SetupResources(bootstrapURL string) error {
	request, err := client.newRequest(requestOptions{
		Method: http.MethodGet,
		URL:    fmt.Sprintf("%s/login", bootstrapURL),
	})

	if err != nil {
		return err
	}

	info := NewInfo(bootstrapURL)
	response := Response{
		Result: &info,
	}

	err = client.connection.Make(request, &response)
	if err != nil {
		return err
	}

	resources := map[string]string{
		"uaa":                    info.UAALink(),
		"authorization_endpoint": bootstrapURL,
	}

	client.router = internal.NewRouter(internal.APIRoutes, resources)
	client.Info = info

	client.config.SetUAAEndpoint(info.UAALink())

	return nil
}
825182
func WithResources(resources interface{}) UpdateTaskOpts {
	return func(ctx context.Context, client *Client, r *UpdateTaskInfo) error {
		switch resources.(type) {
		case *specs.LinuxResources:
		case *specs.WindowsResources:
		default:
			return errors.New("WithResources requires a *specs.LinuxResources or *specs.WindowsResources")
		}

		r.Resources = resources
		return nil
	}
}
697112
func (c *TriggerController) syncResource(key string) error {
	if klog.V(4) {
		startTime := time.Now()
		klog.Infof("Started syncing resource %q", key)
		defer func() {
			klog.Infof("Finished syncing resource %q (%v)", key, time.Since(startTime))
		}()
	}

	parts := strings.SplitN(key, "/", 2)
	source := c.triggerSources[parts[0]]
	obj, exists, err := source.Store.GetByKey(parts[1])
	if err != nil {
		return fmt.Errorf("unable to retrieve %s %s from store: %v", parts[0], parts[1], err)
	}
	if !exists {
		return nil
	}

	return source.Reactor.ImageChanged(obj.(runtime.Object), c.tagRetriever)
}
865843
func (e *Environ) AdoptResources(ctx envcontext.ProviderCallContext, controllerUUID string, fromVersion version.Number) error {
	return errors.NotImplementedf("AdoptResources")
}
653392
func (e *Environ) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error {
	var failed []string
	controllerTag := map[string]string{tags.JujuController: controllerUUID}

	instances, err := e.AllInstances(ctx)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return errors.Trace(err)
	}
	for _, instance := range instances {
		err := e.TagInstance(ctx, instance.Id(), controllerTag)
		if err != nil {
			logger.Errorf("error updating controller tag for instance %s: %v", instance.Id(), err)
			failed = append(failed, string(instance.Id()))
			if denied := common.MaybeHandleCredentialError(IsAuthorisationFailure, err, ctx); denied {
				// If we have an invvalid credential, there is no need to proceed: we'll fail 100%.
				break
			}
		}
	}

	failedVolumes, err := e.adoptVolumes(controllerTag, ctx)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return errors.Trace(err)
	}
	failed = append(failed, failedVolumes...)

	err = e.firewaller.UpdateGroupController(ctx, controllerUUID)
	if err != nil {
		common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
		return errors.Trace(err)
	}
	if len(failed) != 0 {
		return errors.Errorf("error updating controller tag for some resources: %v", failed)
	}
	return nil
}
1293321
func (o *RollbackOptions) findResource(targetName string) (runtime.Object, *meta.RESTMapping, error) {
	candidates := []string{}
	if strings.Index(targetName, "/") == -1 {
		candidates = append(candidates, "rc/"+targetName)
		candidates = append(candidates, "dc/"+targetName)
	} else {
		candidates = append(candidates, targetName)
	}
	var obj runtime.Object
	var m *meta.RESTMapping
	for _, name := range candidates {
		r := o.builder().
			WithScheme(scheme.Scheme, scheme.Scheme.PrioritizedVersionsAllGroups()...).
			NamespaceParam(o.Namespace).
			ResourceTypeOrNameArgs(false, name).
			SingleResourceType().
			Do()
		if r.Err() != nil {
			return nil, nil, r.Err()
		}

		resultObj, err := r.Object()
		if err != nil {
			// If the resource wasn't found, try another candidate.
			if kerrors.IsNotFound(err) {
				continue
			}
			return nil, nil, err
		}
		obj = resultObj
		mapping, err := r.ResourceMapping()
		if err != nil {
			return nil, nil, err
		}

		m = mapping
		break
	}
	if obj == nil {
		return nil, nil, fmt.Errorf("%s is not a valid deployment or deployment config", targetName)
	}
	return obj, m, nil
}
974317
func (r *RemoteRuntimeService) UpdateContainerResources(containerID string, resources *runtimeapi.LinuxContainerResources) error {
	ctx, cancel := getContextWithTimeout(r.timeout)
	defer cancel()

	_, err := r.runtimeClient.UpdateContainerResources(ctx, &runtimeapi.UpdateContainerResourcesRequest{
		ContainerId: containerID,
		Linux:       resources,
	})
	if err != nil {
		klog.Errorf("UpdateContainerResources %q from runtime service failed: %v", containerID, err)
		return err
	}

	return nil
}
196889
func (s *ResourceDefinitionVersion) SetResources(v []*Resource) *ResourceDefinitionVersion {
	s.Resources = v
	return s
}
29657
func (m *MockZonedEnviron) AdoptResources(arg0 context.ProviderCallContext, arg1 string, arg2 version.Number) error {
	ret := m.ctrl.Call(m, "AdoptResources", arg0, arg1, arg2)
	ret0, _ := ret[0].(error)
	return ret0
}
1156620
func (p *Provider) ValidateResource(
	t string, c *terraform.ResourceConfig) ([]string, []error) {
	r, ok := p.ResourcesMap[t]
	if !ok {
		return nil, []error{fmt.Errorf(
			"Provider doesn't support resource: %s", t)}
	}

	return r.Validate(c)
}
381897
func DeployResources(args DeployResourcesArgs) (ids map[string]string, err error) {
	d := deployUploader{
		applicationID: args.ApplicationID,
		chID:          args.CharmID,
		csMac:         args.CharmStoreMacaroon,
		client:        args.Client,
		resources:     args.ResourcesMeta,
		osOpen:        func(s string) (ReadSeekCloser, error) { return os.Open(s) },
		osStat:        func(s string) error { _, err := os.Stat(s); return err },
	}

	ids, err = d.upload(args.ResourceValues, args.Revisions)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return ids, nil
}
312605
func (r *Resource) inheritResourceType(resourceTypes map[string]ResourceType, apiDef *APIDefinition) error {
	// get resource type object to inherit
	rt, err := r.getResourceType(resourceTypes)
	if rt == nil || err != nil {
		return err
	}

	// initialize dicts
	dicts := initResourceTypeDicts(r, r.Type.Parameters)

	r.Description = substituteParams(r.Description, rt.Description, dicts)

	// uri parameters
	if len(r.URIParameters) == 0 {
		r.URIParameters = map[string]NamedParameter{}
	}
	for name, up := range rt.URIParameters {
		p, ok := r.URIParameters[name]
		if !ok {
			p = NamedParameter{}
		}
		p.inherit(up, dicts)
		r.URIParameters[name] = p
	}

	// methods
	r.inheritMethods(rt, apiDef)

	return nil
}
437143
func (m *Method) inheritFromResourceType(r *Resource, rtm *Method, rt *ResourceType, apiDef *APIDefinition) {
	if rtm == nil {
		return
	}
	dicts := initResourceTypeDicts(r, r.Type.Parameters)

	// inherit description
	m.Description = substituteParams(m.Description, rtm.Description, dicts)

	// inherit display name
	m.DisplayName = substituteParams(m.DisplayName, rtm.DisplayName, dicts)

	// inherit bodies
	m.Bodies.inherit(rtm.Bodies, dicts, m.resourceTypeName, apiDef)

	// inherit headers
	m.inheritHeaders(rtm.Headers, dicts)

	// inherit query params
	m.inheritQueryParams(rtm.QueryParameters, dicts)

	// inherit response
	m.inheritResponses(rtm.Responses, dicts, apiDef)

	// inherit protocols
	m.inheritProtocols(rtm.Protocols)
}
393937
func (st *resourceSyncTask) updateResource(resClient dynamic.ResourceInterface, spec *unstructured.Unstructured, actual runtime.Object) (actualRet *unstructured.Unstructured, retriableError bool, e error) {
	st.logger.Debug("Object found, checking spec", ctrlLogz.ObjectGk(spec.GroupVersionKind().GroupKind()), ctrlLogz.Object(spec))
	// Compare spec and existing resource
	updated, match, difference, err := st.specChecker.CompareActualVsSpec(st.logger, spec, actual)
	if err != nil {
		return nil, false, errors.Wrap(err, "specification check failed")
	}

	// Delete the DeletionTimestamp annotation if it is present
	annotations := updated.GetAnnotations()
	if _, ok := annotations[smith.DeletionTimestampAnnotation]; ok {
		delete(annotations, smith.DeletionTimestampAnnotation)
		updated.SetAnnotations(annotations)
		match = false
	}

	if match {
		st.logger.Debug("Object has correct spec", ctrlLogz.Object(spec))
		return updated, false, nil
	}
	st.logger.Sugar().Infof("Objects are different (`a` is specification and `b` is the actual object): %s", difference)

	// Update if different
	updated, err = resClient.Update(updated, meta_v1.UpdateOptions{})
	if err != nil {
		if api_errors.IsConflict(err) {
			// We let the next processKey() iteration, triggered by someone else updating the resource, finish the work.
			return nil, false, errors.Wrap(err, "object update resulted in conflict (will re-process)")
		}
		// Unexpected error, will retry
		apiStatusErr, ok := err.(api_errors.APIStatus)
		if ok {
			apiStatus := apiStatusErr.Status()
			return nil, true, errors.Wrapf(err, "unexpected APIStatus (code %v, reason %q) while creating resource", apiStatus.Code, apiStatus.Reason)
		}
		return nil, true, errors.WithStack(err)
	}
	st.logger.Info("Object updated", ctrlLogz.Object(spec))
	return updated, false, nil
}
156730
func (_m *API) VirtualizationUpdateResource(ctx context.Context, ID string, opts *types.VirtualizationResource) error {
	ret := _m.Called(ctx, ID, opts)

	var r0 error
	if rf, ok := ret.Get(0).(func(context.Context, string, *types.VirtualizationResource) error); ok {
		r0 = rf(ctx, ID, opts)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
703828
func (e *environ) AdoptResources(ctx context.ProviderCallContext, controllerUUID string, fromVersion version.Number) error {
	// Gather resource ids for instances, volumes and security groups tagged with this model.
	instances, err := e.AllInstances(ctx)
	if err != nil {
		return errors.Trace(err)
	}
	// We want to update the controller tags on root disks even though
	// they are destroyed automatically with the instance they're
	// attached to.
	volumeIds, err := e.allModelVolumes(ctx, true)
	if err != nil {
		return errors.Trace(err)
	}
	groupIds, err := e.modelSecurityGroupIDs(ctx)
	if err != nil {
		return errors.Trace(err)
	}

	resourceIds := make([]string, len(instances))
	for i, instance := range instances {
		resourceIds[i] = string(instance.Id())
	}
	resourceIds = append(resourceIds, volumeIds...)
	resourceIds = append(resourceIds, groupIds...)

	tags := map[string]string{tags.JujuController: controllerUUID}
	return errors.Annotate(tagResources(e.ec2, ctx, tags, resourceIds...), "updating tags")
}