// Uploads the image to an reserved image location at the imageEndpoint using the reserved image ID and imageMetadata.
// Returns nil error if the upload is successful, otherwise returns an error.
// Requires client's token to upload the image.
179869
func uploadImage(tokenID string, imageEndpoint string, imageID string, imagePath string, imageApiVersion int) error {
	// Read the image file
	file, err := os.Open(imagePath)
	if err != nil {
		return fmt.Errorf("unable to open image file")
	}
	defer file.Close()

	stat, err := file.Stat()
	if err != nil {
		return fmt.Errorf("unable to get the stats of the image file: %s", err)
	}
	imageFileSize := stat.Size()

	// Prepare the request to upload the image file
	imageLocation := ""
	if imageVersionEncoded(imageEndpoint) {
		imageLocation = fmt.Sprintf("%simages/%s", imageEndpoint, imageID)
	} else {
		imageLocation = fmt.Sprintf("%sv%d/images/%s", imageEndpoint, imageApiVersion, imageID)
	}
	if imageApiVersion == 2 {
		imageLocation += "/file"
	}

	uploadReq, err := http.NewRequest("PUT", imageLocation, file)
	if err != nil {
		return fmt.Errorf("unable to upload image to the openstack")
	}

	uploadReq.Header.Add("Content-Type", "application/octet-stream")
	uploadReq.Header.Add("X-Auth-Token", tokenID)
	uploadReq.Header.Add("Content-Length", fmt.Sprintf("%d", imageFileSize))

	uploadClient := &http.Client{}

	// Send the request to upload the image
	resp, err := uploadClient.Do(uploadReq)
	if err != nil {
		return fmt.Errorf("failed to send a upload image request")
	}
	defer resp.Body.Close()

	body, _ := ioutil.ReadAll(resp.Body)
	if (imageApiVersion == 1 && resp.StatusCode != http.StatusOK) ||
		(imageApiVersion == 2 && resp.StatusCode != http.StatusNoContent) {
		return fmt.Errorf("upload image request returned bad response, %s", string(body))
	}

	return nil
}
494223
func (client *Client) UploadServerCertificate(args *UploadServerCertificateArgs) (response *UploadServerCertificateResponse, err error) {
	response = &UploadServerCertificateResponse{}
	err = client.Invoke("UploadServerCertificate", args, response)
	if err != nil {
		return nil, err
	}
	return response, err
}
797670
func (c *Cluster) PushImage(opts docker.PushImageOptions, auth docker.AuthConfiguration) error {
	key := imageKey(opts.Name, opts.Tag)
	img, err := c.storage().RetrieveImage(key)
	if err != nil {
		return err
	}
	node, err := c.getNodeByAddr(img.LastNode)
	if err != nil {
		return err
	}
	node.setPersistentClient()
	return wrapError(node, node.PushImage(opts, auth))
}
1075792
func uploadAsset(ctx *context.Context, put *config.Put, artifact artifact.Artifact, kind string, check ResponseChecker) error {
	envBase := fmt.Sprintf("%s_%s_", strings.ToUpper(kind), strings.ToUpper(put.Name))
	username := put.Username
	if username == "" {
		// username not configured: using env
		username = ctx.Env[envBase+"USERNAME"]
	}
	secret := ctx.Env[envBase+"SECRET"]

	// Generate the target url
	targetURL, err := resolveTargetTemplate(ctx, put, artifact)
	if err != nil {
		msg := fmt.Sprintf("%s: error while building the target url", kind)
		log.WithField("instance", put.Name).WithError(err).Error(msg)
		return errors.Wrap(err, msg)
	}

	// Handle the artifact
	asset, err := assetOpen(kind, &artifact)
	if err != nil {
		return err
	}
	defer asset.ReadCloser.Close() // nolint: errcheck

	// The target url needs to contain the artifact name
	if !strings.HasSuffix(targetURL, "/") {
		targetURL += "/"
	}
	targetURL += artifact.Name

	var headers = map[string]string{}
	if put.ChecksumHeader != "" {
		sum, err := artifact.Checksum("sha256")
		if err != nil {
			return err
		}
		headers[put.ChecksumHeader] = sum
	}

	_, err = uploadAssetToServer(ctx, put, targetURL, username, secret, headers, asset, check)
	if err != nil {
		msg := fmt.Sprintf("%s: upload failed", kind)
		log.WithError(err).WithFields(log.Fields{
			"instance": put.Name,
			"username": username,
		}).Error(msg)
		return errors.Wrap(err, msg)
	}

	log.WithFields(log.Fields{
		"instance": put.Name,
		"mode":     put.Mode,
	}).Info("uploaded successful")

	return nil
}
417310
func PushImage(repotag string) error {
	iid, err := commons.ParseImageID(repotag)
	if err != nil {
		return err
	}

	return pushImage(iid.BaseName(), iid.Registry(), iid.Tag)
}
701274
func ImageMetadataURL(source, stream string) (string, error) {
	if source == "" {
		return "", nil
	}
	// If the image metadata is coming from the official cloud images site,
	// set up the correct path according to the images stream requested.
	if source == UbuntuCloudImagesURL || source == JujuStreamsImagesURL {
		cloudImagesPath := ReleasedImagesPath
		if stream != "" && stream != ReleasedStream {
			cloudImagesPath = stream
		}
		source = fmt.Sprintf("%s/%s", source, cloudImagesPath)
	}

	return utils.GetURL(source, storage.BaseImagesPath)
}
599203
func (d Datastore) Upload(ctx context.Context, f io.Reader, path string, param *soap.Upload) error {
	u, p, err := d.uploadTicket(ctx, path, param)
	if err != nil {
		return err
	}
	return d.Client().Upload(ctx, f, u, p)
}
955059
func (i *ImageService) PushImage(ctx context.Context, image, tag string, metaHeaders map[string][]string, authConfig *types.AuthConfig, outStream io.Writer) error {
	start := time.Now()
	ref, err := reference.ParseNormalizedNamed(image)
	if err != nil {
		return err
	}
	if tag != "" {
		// Push by digest is not supported, so only tags are supported.
		ref, err = reference.WithTag(ref, tag)
		if err != nil {
			return err
		}
	}

	// Include a buffer so that slow client connections don't affect
	// transfer performance.
	progressChan := make(chan progress.Progress, 100)

	writesDone := make(chan struct{})

	ctx, cancelFunc := context.WithCancel(ctx)

	go func() {
		progressutils.WriteDistributionProgress(cancelFunc, outStream, progressChan)
		close(writesDone)
	}()

	imagePushConfig := &distribution.ImagePushConfig{
		Config: distribution.Config{
			MetaHeaders:      metaHeaders,
			AuthConfig:       authConfig,
			ProgressOutput:   progress.ChanOutput(progressChan),
			RegistryService:  i.registryService,
			ImageEventLogger: i.LogImageEvent,
			MetadataStore:    i.distributionMetadataStore,
			ImageStore:       distribution.NewImageConfigStoreFromStore(i.imageStore),
			ReferenceStore:   i.referenceStore,
		},
		ConfigMediaType: schema2.MediaTypeImageConfig,
		LayerStores:     distribution.NewLayerProvidersFromStores(i.layerStores),
		UploadManager:   i.uploadManager,
	}

	err = distribution.Push(ctx, ref, imagePushConfig)
	close(progressChan)
	<-writesDone
	imageActions.WithValues("push").UpdateSince(start)
	return err
}
1085108
func (c *Client) AddSecondaryStorage(p *AddSecondaryStorageParameter) (*ImageStore, error) {
	obj, err := c.Request("addSecondaryStorage", convertParamToMap(p))
	if err != nil {
		return nil, err
	}
	return obj.(*ImageStore), err
}
261950
func (c *GitHubClient) UploadAsset(ctx context.Context, releaseID int64, filename string) (*github.ReleaseAsset, error) {

	filename, err := filepath.Abs(filename)
	if err != nil {
		return nil, errors.Wrap(err, "failed to get abs path")
	}

	opts := &github.UploadOptions{
		// Use base name by default
		Name: filepath.Base(filename),
	}

	var asset *github.ReleaseAsset
	err = retry.Retry(3, 3*time.Second, func() error {
		var (
			res *github.Response
			err error
		)

		f, err := os.Open(filename)
		if err != nil {
			return errors.Wrap(err, "failed to open file")
		}
		defer f.Close()

		asset, res, err = c.Repositories.UploadReleaseAsset(context.TODO(), c.Owner, c.Repo, releaseID, opts, f)
		if err != nil {
			return errors.Wrapf(err, "failed to upload release asset: %s", filename)
		}

		switch res.StatusCode {
		case http.StatusCreated:
			return nil
		case 422:
			return errors.Errorf(
				"upload release asset: invalid status code: %s",
				"422 (this is probably because the asset already uploaded)")
		default:
			return errors.Errorf(
				"upload release asset: invalid status code: %s", res.Status)
		}
	})
	return asset, err
}
704880
func (bot *BotAPI) uploadAndSend(method string, config Fileable) (Message, error) {
	params, err := config.params()
	if err != nil {
		return Message{}, err
	}

	file := config.getFile()

	resp, err := bot.UploadFile(method, params, config.name(), file)
	if err != nil {
		return Message{}, err
	}

	var message Message
	json.Unmarshal(resp.Result, &message)

	bot.debugLog(method, nil, message)

	return message, nil
}
329509
func (m *MockImageAPIClient) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
	ret := m.ctrl.Call(m, "ImageLoad", ctx, input, quiet)
	ret0, _ := ret[0].(types.ImageLoadResponse)
	ret1, _ := ret[1].(error)
	return ret0, ret1
}
293767
func (cli *Client) ImageLoad(ctx context.Context, input io.Reader, quiet bool) (types.ImageLoadResponse, error) {
	v := url.Values{}
	v.Set("quiet", "0")
	if quiet {
		v.Set("quiet", "1")
	}
	headers := map[string][]string{"Content-Type": {"application/x-tar"}}
	resp, err := cli.postRaw(ctx, "/images/load", v, input, headers)
	if err != nil {
		return types.ImageLoadResponse{}, err
	}
	return types.ImageLoadResponse{
		Body: resp.body,
		JSON: resp.header.Get("Content-Type") == "application/json",
	}, nil
}
454308
func uploadFile(serverURL, key, filename string) error {
	var r io.ReadCloser
	var size int64
	if len(filename) > 0 {
		f, err := os.Open(filename)
		if err != nil {
			return fmt.Errorf("failed to open upload file %s, %v", filename, err)
		}

		// Get the size of the file so that the constraint of Content-Length
		// can be included with the presigned URL. This can be used by the
		// server or client to ensure the content uploaded is of a certain size.
		//
		// These constraints can further be expanded to include things like
		// Content-Type. Additionally constraints such as X-Amz-Content-Sha256
		// header set restricting the content of the file to only the content
		// the client initially made the request with. This prevents the object
		// from being overwritten or used to upload other unintended content.
		stat, err := f.Stat()
		if err != nil {
			return fmt.Errorf("failed to stat file, %s, %v", filename, err)
		}

		size = stat.Size()
		r = f
	} else {
		buf := &bytes.Buffer{}
		io.Copy(buf, os.Stdin)
		size = int64(buf.Len())

		r = ioutil.NopCloser(buf)
	}
	defer r.Close()

	// Get the Presigned URL from the remote service. Pass in the file's
	// size if it is known so that the presigned URL returned will be required
	// to be used with the size of content requested.
	req, err := getPresignedRequest(serverURL, "PUT", key, size)
	if err != nil {
		return fmt.Errorf("failed to get get presigned request, %v", err)
	}
	req.Body = r

	// Upload the file contents to S3.
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		return fmt.Errorf("failed to do GET request, %v", err)
	}

	defer resp.Body.Close()

	if resp.StatusCode != http.StatusOK {
		return fmt.Errorf("failed to put S3 object, %d:%s",
			resp.StatusCode, resp.Status)
	}

	return nil
}
775663
func Push(ctx context.Context, ref reference.Named, imagePushConfig *ImagePushConfig) error {
	// FIXME: Allow to interrupt current push when new push of same image is done.

	// Resolve the Repository name from fqn to RepositoryInfo
	repoInfo, err := imagePushConfig.RegistryService.ResolveRepository(ref)
	if err != nil {
		return err
	}

	endpoints, err := imagePushConfig.RegistryService.LookupPushEndpoints(reference.Domain(repoInfo.Name))
	if err != nil {
		return err
	}

	progress.Messagef(imagePushConfig.ProgressOutput, "", "The push refers to repository [%s]", repoInfo.Name.Name())

	associations := imagePushConfig.ReferenceStore.ReferencesByName(repoInfo.Name)
	if len(associations) == 0 {
		return fmt.Errorf("An image does not exist locally with the tag: %s", reference.FamiliarName(repoInfo.Name))
	}

	var (
		lastErr error

		// confirmedV2 is set to true if a push attempt managed to
		// confirm that it was talking to a v2 registry. This will
		// prevent fallback to the v1 protocol.
		confirmedV2 bool

		// confirmedTLSRegistries is a map indicating which registries
		// are known to be using TLS. There should never be a plaintext
		// retry for any of these.
		confirmedTLSRegistries = make(map[string]struct{})
	)

	for _, endpoint := range endpoints {
		if imagePushConfig.RequireSchema2 && endpoint.Version == registry.APIVersion1 {
			continue
		}
		if confirmedV2 && endpoint.Version == registry.APIVersion1 {
			logrus.Debugf("Skipping v1 endpoint %s because v2 registry was detected", endpoint.URL)
			continue
		}

		if endpoint.URL.Scheme != "https" {
			if _, confirmedTLS := confirmedTLSRegistries[endpoint.URL.Host]; confirmedTLS {
				logrus.Debugf("Skipping non-TLS endpoint %s for host/port that appears to use TLS", endpoint.URL)
				continue
			}
		}

		logrus.Debugf("Trying to push %s to %s %s", repoInfo.Name.Name(), endpoint.URL, endpoint.Version)

		pusher, err := NewPusher(ref, endpoint, repoInfo, imagePushConfig)
		if err != nil {
			lastErr = err
			continue
		}
		if err := pusher.Push(ctx); err != nil {
			// Was this push cancelled? If so, don't try to fall
			// back.
			select {
			case <-ctx.Done():
			default:
				if fallbackErr, ok := err.(fallbackError); ok {
					confirmedV2 = confirmedV2 || fallbackErr.confirmedV2
					if fallbackErr.transportOK && endpoint.URL.Scheme == "https" {
						confirmedTLSRegistries[endpoint.URL.Host] = struct{}{}
					}
					err = fallbackErr.err
					lastErr = err
					logrus.Infof("Attempting next endpoint for push after error: %v", err)
					continue
				}
			}

			logrus.Errorf("Not continuing with push after error: %v", err)
			return err
		}

		imagePushConfig.ImageEventLogger(reference.FamiliarString(ref), reference.FamiliarName(repoInfo.Name), "push")
		return nil
	}

	if lastErr == nil {
		lastErr = fmt.Errorf("no endpoints found for %s", repoInfo.Name.Name())
	}
	return lastErr
}
1046426
func (mr *MockImageAPIClientMockRecorder) ImageLoad(ctx, input, quiet interface{}) *gomock.Call {
	return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ImageLoad", reflect.TypeOf((*MockImageAPIClient)(nil).ImageLoad), ctx, input, quiet)
}
1361997
func UploadResource(resource interface{}, baseURL string) (string, error) {
	// FYI: We can post resource w/ bogus id because it doesn't get serialized
	json, _ := json.Marshal(resource)
	body := bytes.NewReader(json)
	url := baseURL + "/" + reflect.TypeOf(resource).Elem().Name()
	response, err := http.Post(url, "application/json+fhir", body)
	if err != nil {
		return "", err
	}
	defer response.Body.Close()
	loc := response.Header.Get("Location")

	regs := []string{".*/([^/]+)/_history/.*", ".*/([^/]+)"}
	for _, reg := range regs {
		creg := regexp.MustCompile(reg)
		if matches := creg.FindStringSubmatch(loc); matches != nil {
			setId(resource, matches[1])
			break
		}
	}

	return loc, nil
}