summaryrefslogtreecommitdiff
path: root/pkg/bindings/images/push.go
blob: f1e059f8ce06b5a0b705412738344412610fa362 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package images

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"os"
	"strconv"

	imageTypes "github.com/containers/image/v5/types"
	"github.com/containers/podman/v4/pkg/auth"
	"github.com/containers/podman/v4/pkg/bindings"
	"github.com/containers/podman/v4/pkg/domain/entities"
)

// Push is the binding for libpod's endpoints for push images.  Note that
// `source` must be a referring to an image in the remote's container storage.
// The destination must be a reference to a registry (i.e., of docker transport
// or be normalized to one).  Other transports are rejected as they do not make
// sense in a remote context.
func Push(ctx context.Context, source string, destination string, options *PushOptions) error {
	if options == nil {
		options = new(PushOptions)
	}
	conn, err := bindings.GetClient(ctx)
	if err != nil {
		return err
	}
	header, err := auth.MakeXRegistryAuthHeader(&imageTypes.SystemContext{AuthFilePath: options.GetAuthfile()}, options.GetUsername(), options.GetPassword())
	if err != nil {
		return err
	}

	params, err := options.ToParams()
	if err != nil {
		return err
	}
	// SkipTLSVerify is special.  We need to delete the param added by
	// toparams and change the key and flip the bool
	if options.SkipTLSVerify != nil {
		params.Del("SkipTLSVerify")
		params.Set("tlsVerify", strconv.FormatBool(!options.GetSkipTLSVerify()))
	}
	params.Set("destination", destination)

	path := fmt.Sprintf("/images/%s/push", source)
	response, err := conn.DoRequest(ctx, nil, http.MethodPost, path, params, header)
	if err != nil {
		return err
	}
	defer response.Body.Close()

	if !response.IsSuccess() {
		return response.Process(err)
	}

	var writer io.Writer
	if options.GetQuiet() {
		writer = io.Discard
	} else if progressWriter := options.GetProgressWriter(); progressWriter != nil {
		writer = progressWriter
	} else {
		// Historically push writes status to stderr
		writer = os.Stderr
	}

	dec := json.NewDecoder(response.Body)
	for {
		var report entities.ImagePushReport
		if err := dec.Decode(&report); err != nil {
			if errors.Is(err, io.EOF) {
				break
			}
			return err
		}

		select {
		case <-response.Request.Context().Done():
			break
		default:
			// non-blocking select
		}

		switch {
		case report.Stream != "":
			fmt.Fprint(writer, report.Stream)
		case report.Error != "":
			// There can only be one error.
			return errors.New(report.Error)
		default:
			return fmt.Errorf("failed to parse push results stream, unexpected input: %v", report)
		}
	}

	return nil
}