// UploadPendingResource sends the provided resource blob up to Juju
// and makes it available.
8877
func (c Client) UploadPendingResource(applicationID string, res charmresource.Resource, filename string, reader io.ReadSeeker) (pendingID string, err error) {
	ids, err := c.AddPendingResources(AddPendingResourcesArgs{
		ApplicationID: applicationID,
		Resources:     []charmresource.Resource{res},
	})
	if err != nil {
		return "", errors.Trace(err)
	}
	pendingID = ids[0]

	if reader != nil {
		uReq, err := api.NewUploadRequest(applicationID, res.Name, filename, reader)
		if err != nil {
			return "", errors.Trace(err)
		}
		uReq.PendingID = pendingID
		req, err := uReq.HTTPRequest()
		if err != nil {
			return "", errors.Trace(err)
		}

		var response params.UploadResult // ignored
		if err := c.doer.Do(req, reader, &response); err != nil {
			return "", errors.Trace(err)
		}
	}

	return pendingID, nil
}
120323
func NewResource(init ...*Resource) *Resource {
	var o *Resource
	if len(init) == 1 {
		o = init[0]
	} else {
		o = new(Resource)
	}
	return o.Init()
}
1070758
func (maasStorageProvider) VolumeSource(providerConfig *storage.Config) (storage.VolumeSource, error) {
	// Dynamic volumes not supported.
	return nil, errors.NotSupportedf("volumes")
}
941935
func (c *cmd) uploadPayload(payload []byte) error {
	kv := c.apiclient.KV()
	pair := api.KVPair{
		Key:     path.Join(c.conf.prefix, c.sessionID, rExecFileName),
		Value:   payload,
		Session: c.sessionID,
	}
	ok, _, err := kv.Acquire(&pair, nil)
	if err != nil {
		return err
	}
	if !ok {
		return fmt.Errorf("failed to acquire key %s", pair.Key)
	}
	return nil
}
628215
func (e *Engine) VirtualizationUpdateResource(ctx context.Context, ID string, opts *enginetypes.VirtualizationResource) error {
	newResource := makeResourceSetting(opts.Quota, opts.Memory, opts.CPU, opts.SoftLimit)
	updateConfig := dockercontainer.UpdateConfig{Resources: newResource}
	_, err := e.client.ContainerUpdate(ctx, ID, updateConfig)
	return err
}
844543
func UploadResources(resources []interface{}, baseURL string) (map[string]string, error) {
	refMap := make(map[string]string)
	resources = sortResourcesByDependency(resources)
	for _, t := range resources {
		err := updateReferences(t, refMap)
		if err != nil {
			return refMap, err
		}

		// Remember the old ID so we can create a map from old ID to new location
		oldId := getId(t)

		// Upload the resource and get the new location
		_, err = UploadResource(t, baseURL)
		if err != nil {
			return refMap, err
		}

		// Add entry to map from the old ID to the new relative path
		if oldId != "" {
			refMap[oldId] = reflect.TypeOf(t).Elem().Name() + "/" + getId(t)
		}
	}

	return refMap, nil
}
294462
func (st resourceState) UpdatePendingResource(applicationID, pendingID, userID string, chRes charmresource.Resource, r io.Reader) (resource.Resource, error) {
	logger.Tracef("updating pending resource %q (%s) for application %q", chRes.Name, pendingID, applicationID)
	res, err := st.setResource(pendingID, applicationID, userID, chRes, r)
	if err != nil {
		return res, errors.Trace(err)
	}
	return res, nil
}
745597
func (u *UploadsService) UploadAsset(asset io.ReadCloser, contentType string, contentLength int64) (result *Result) {
	return u.client.upload(u.URL, asset, contentType, contentLength)
}
503128
func (iter *SyncFolderIterator) UploadObject() s3manager.BatchUploadObject {
	fi := iter.fileInfos[0]
	iter.fileInfos = iter.fileInfos[1:]
	body, err := os.Open(fi.fullpath)
	if err != nil {
		iter.err = err
	}

	extension := filepath.Ext(fi.key)
	mimeType := mime.TypeByExtension(extension)

	if mimeType == "" {
		mimeType = "binary/octet-stream"
	}

	input := s3manager.UploadInput{
		Bucket:      &iter.bucket,
		Key:         &fi.key,
		Body:        body,
		ContentType: &mimeType,
	}

	return s3manager.BatchUploadObject{
		Object: &input,
	}
}
590603
func (s *ModifyCurrentDBClusterCapacityOutput) SetPendingCapacity(v int64) *ModifyCurrentDBClusterCapacityOutput {
	s.PendingCapacity = &v
	return s
}
526674
func (h *ResourcesHandler) readResource(backend ResourcesBackend, req *http.Request) (*uploadedResource, error) {
	uReq, err := extractUploadRequest(req)
	if err != nil {
		return nil, errors.Trace(err)
	}
	var res resource.Resource
	if uReq.PendingID != "" {
		res, err = backend.GetPendingResource(uReq.Application, uReq.Name, uReq.PendingID)
	} else {
		res, err = backend.GetResource(uReq.Application, uReq.Name)
	}
	if err != nil {
		return nil, errors.Trace(err)
	}

	switch res.Type {
	case charmresource.TypeFile:
		ext := path.Ext(res.Path)
		if path.Ext(uReq.Filename) != ext {
			return nil, errors.Errorf("incorrect extension on resource upload %q, expected %q", uReq.Filename, ext)
		}
	case charmresource.TypeContainerImage:
		// At this stage the docker 'filename' could be a reference to
		// what the user has on their local filesystem that got parsed and
		// is in the process of being uploaded so it makes no sense to validate uReq.Filename
		// The uploaded finger print from the CLI will not match what comes in from the API request, do not store it.
		uReq.Fingerprint = charmresource.Fingerprint{}
	}

	chRes, err := updateResource(res.Resource, uReq.Fingerprint, uReq.Size)
	if err != nil {
		return nil, errors.Trace(err)
	}
	return &uploadedResource{
		Application: uReq.Application,
		PendingID:   uReq.PendingID,
		Resource:    chRes,
		Data:        req.Body,
	}, nil
}
828816
func UpdateResource(r rest.Updater, scope *RequestScope, admit admission.Interface) http.HandlerFunc {
	return func(w http.ResponseWriter, req *http.Request) {
		// For performance tracking purposes.
		trace := utiltrace.New("Update " + req.URL.Path)
		defer trace.LogIfLong(500 * time.Millisecond)

		if isDryRun(req.URL) && !utilfeature.DefaultFeatureGate.Enabled(features.DryRun) {
			scope.err(errors.NewBadRequest("the dryRun alpha feature is disabled"), w, req)
			return
		}

		// TODO: we either want to remove timeout or document it (if we document, move timeout out of this function and declare it in api_installer)
		timeout := parseTimeout(req.URL.Query().Get("timeout"))

		namespace, name, err := scope.Namer.Name(req)
		if err != nil {
			scope.err(err, w, req)
			return
		}
		ctx := req.Context()
		ctx = request.WithNamespace(ctx, namespace)

		outputMediaType, _, err := negotiation.NegotiateOutputMediaType(req, scope.Serializer, scope)
		if err != nil {
			scope.err(err, w, req)
			return
		}

		body, err := limitedReadBody(req, scope.MaxRequestBodyBytes)
		if err != nil {
			scope.err(err, w, req)
			return
		}

		options := &metav1.UpdateOptions{}
		if err := metainternalversion.ParameterCodec.DecodeParameters(req.URL.Query(), scope.MetaGroupVersion, options); err != nil {
			err = errors.NewBadRequest(err.Error())
			scope.err(err, w, req)
			return
		}
		if errs := validation.ValidateUpdateOptions(options); len(errs) > 0 {
			err := errors.NewInvalid(schema.GroupKind{Group: metav1.GroupName, Kind: "UpdateOptions"}, "", errs)
			scope.err(err, w, req)
			return
		}

		s, err := negotiation.NegotiateInputSerializer(req, false, scope.Serializer)
		if err != nil {
			scope.err(err, w, req)
			return
		}
		defaultGVK := scope.Kind
		original := r.New()

		trace.Step("About to convert to expected version")
		decoder := scope.Serializer.DecoderToVersion(s.Serializer, scope.HubGroupVersion)
		obj, gvk, err := decoder.Decode(body, &defaultGVK, original)
		if err != nil {
			err = transformDecodeError(scope.Typer, err, original, gvk, body)
			scope.err(err, w, req)
			return
		}
		if gvk.GroupVersion() != defaultGVK.GroupVersion() {
			err = errors.NewBadRequest(fmt.Sprintf("the API version in the data (%s) does not match the expected API version (%s)", gvk.GroupVersion(), defaultGVK.GroupVersion()))
			scope.err(err, w, req)
			return
		}
		trace.Step("Conversion done")

		ae := request.AuditEventFrom(ctx)
		audit.LogRequestObject(ae, obj, scope.Resource, scope.Subresource, scope.Serializer)
		admit = admission.WithAudit(admit, ae)

		if err := checkName(obj, name, namespace, scope.Namer); err != nil {
			scope.err(err, w, req)
			return
		}

		userInfo, _ := request.UserFrom(ctx)
		transformers := []rest.TransformFunc{}
		if scope.FieldManager != nil {
			transformers = append(transformers, func(_ context.Context, newObj, liveObj runtime.Object) (runtime.Object, error) {
				obj, err := scope.FieldManager.Update(liveObj, newObj, managerOrUserAgent(options.FieldManager, req.UserAgent()))
				if err != nil {
					return nil, fmt.Errorf("failed to update object (Update for %v) managed fields: %v", scope.Kind, err)
				}
				return obj, nil
			})
		}
		if mutatingAdmission, ok := admit.(admission.MutationInterface); ok {
			transformers = append(transformers, func(ctx context.Context, newObj, oldObj runtime.Object) (runtime.Object, error) {
				isNotZeroObject, err := hasUID(oldObj)
				if err != nil {
					return nil, fmt.Errorf("unexpected error when extracting UID from oldObj: %v", err.Error())
				} else if !isNotZeroObject {
					if mutatingAdmission.Handles(admission.Create) {
						return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, dryrun.IsDryRun(options.DryRun), userInfo), scope)
					}
				} else {
					if mutatingAdmission.Handles(admission.Update) {
						return newObj, mutatingAdmission.Admit(admission.NewAttributesRecord(newObj, oldObj, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, dryrun.IsDryRun(options.DryRun), userInfo), scope)
					}
				}
				return newObj, nil
			})

		}

		createAuthorizerAttributes := authorizer.AttributesRecord{
			User:            userInfo,
			ResourceRequest: true,
			Path:            req.URL.Path,
			Verb:            "create",
			APIGroup:        scope.Resource.Group,
			APIVersion:      scope.Resource.Version,
			Resource:        scope.Resource.Resource,
			Subresource:     scope.Subresource,
			Namespace:       namespace,
			Name:            name,
		}

		trace.Step("About to store object in database")
		wasCreated := false
		result, err := finishRequest(timeout, func() (runtime.Object, error) {
			obj, created, err := r.Update(
				ctx,
				name,
				rest.DefaultUpdatedObjectInfo(obj, transformers...),
				withAuthorization(rest.AdmissionToValidateObjectFunc(
					admit,
					admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Create, dryrun.IsDryRun(options.DryRun), userInfo), scope),
					scope.Authorizer, createAuthorizerAttributes),
				rest.AdmissionToValidateObjectUpdateFunc(
					admit,
					admission.NewAttributesRecord(nil, nil, scope.Kind, namespace, name, scope.Resource, scope.Subresource, admission.Update, dryrun.IsDryRun(options.DryRun), userInfo), scope),
				false,
				options,
			)
			wasCreated = created
			return obj, err
		})
		if err != nil {
			scope.err(err, w, req)
			return
		}
		trace.Step("Object stored in database")

		status := http.StatusOK
		if wasCreated {
			status = http.StatusCreated
		}

		transformResponseObject(ctx, scope, trace, req, w, status, outputMediaType, result)
	}
}
671902
func (st resourceState) RemovePendingAppResources(applicationID string, pendingIDs map[string]string) error {
	return errors.Trace(st.persist.RemovePendingAppResources(applicationID, pendingIDs))
}
1057866
func (p ResourcePersistence) SetResource(res resource.Resource) error {
	stored, err := p.getStored(res)
	if errors.IsNotFound(err) {
		stored = storedResource{Resource: res}
	} else if err != nil {
		return errors.Trace(err)
	}
	// TODO(ericsnow) Ensure that stored.Resource matches res? If we do
	// so then the following line is unnecessary.
	stored.Resource = res

	if err := res.Validate(); err != nil {
		return errors.Annotate(err, "bad resource")
	}

	buildTxn := func(attempt int) ([]txn.Op, error) {
		// This is an "upsert".
		var ops []txn.Op
		switch attempt {
		case 0:
			ops = newInsertResourceOps(stored)
		case 1:
			ops = newUpdateResourceOps(stored)
		default:
			// Either insert or update will work so we should not get here.
			return nil, errors.New("setting the resource failed")
		}
		if stored.PendingID == "" {
			// Only non-pending resources must have an existing application.
			ops = append(ops, p.base.ApplicationExistsOps(res.ApplicationID)...)
		}
		return ops, nil
	}
	if err := p.base.Run(buildTxn); err != nil {
		return errors.Trace(err)
	}
	return nil
}
699969
func (*AssetManager) ConfigureQorResource(res resource.Resourcer) {
	if res, ok := res.(*admin.Resource); ok {
		router := res.GetAdmin().GetRouter()
		router.Post(fmt.Sprintf("/%v/upload", res.ToParam()), func(context *admin.Context) {
			result := AssetManager{}
			result.File.Scan(context.Request.MultipartForm.File["file"])
			context.GetDB().Save(&result)
			bytes, _ := json.Marshal(map[string]string{"filelink": result.File.URL(), "filename": result.File.GetFileName()})
			context.Writer.Write(bytes)
		})

		assetURL := regexp.MustCompile(`^/system/assets/(\d+)/`)
		router.Post(fmt.Sprintf("/%v/crop", res.ToParam()), func(context *admin.Context) {
			defer context.Request.Body.Close()
			var (
				err error
				url struct{ URL string }
				buf bytes.Buffer
			)

			io.Copy(&buf, context.Request.Body)
			if err = json.Unmarshal(buf.Bytes(), &url); err == nil {
				if matches := assetURL.FindStringSubmatch(url.URL); len(matches) > 1 {
					result := &AssetManager{}
					if err = context.GetDB().Find(result, matches[1]).Error; err == nil {
						if err = result.File.Scan(buf.Bytes()); err == nil {
							if err = context.GetDB().Save(result).Error; err == nil {
								bytes, _ := json.Marshal(map[string]string{"url": result.File.URL(), "filename": result.File.GetFileName()})
								context.Writer.Write(bytes)
								return
							}
						}
					}
				}
			}

			bytes, _ := json.Marshal(map[string]string{"err": err.Error()})
			context.Writer.Write(bytes)
		})
	}
}
1306005
func (b *BigIP) UploadBytes(data []byte, filename string) (*Upload, error) {
	r := bytes.NewReader(data)
	size := int64(len(data))
	return b.Upload(r, size, uriShared, uriFileTransfer, uriUploads, filename)
}
727388
func (c *Client) UploadVolume(p *UploadVolumeParameter) (*Volume, error) {
	obj, err := c.Request("uploadVolume", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*Volume), err
}