aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/containers/image/v5/copy/progress_channel.go
blob: d5e9e09bda90d35396b995164a5be0f0dd19a50a (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
package copy

import (
	"io"
	"time"

	"github.com/containers/image/v5/types"
)

// progressReader is a reader that reports its progress to a types.ProgressProperties channel on an interval.
type progressReader struct {
	source       io.Reader
	channel      chan<- types.ProgressProperties
	interval     time.Duration
	artifact     types.BlobInfo
	lastUpdate   time.Time
	offset       uint64
	offsetUpdate uint64
}

// newProgressReader creates a new progress reader for:
// `source`:   The source when internally reading bytes
// `channel`:  The reporter channel to which the progress will be sent
// `interval`: The update interval to indicate how often the progress should update
// `artifact`: The blob metadata which is currently being progressed
func newProgressReader(
	source io.Reader,
	channel chan<- types.ProgressProperties,
	interval time.Duration,
	artifact types.BlobInfo,
) *progressReader {
	// The progress reader constructor informs the progress channel
	// that a new artifact will be read
	channel <- types.ProgressProperties{
		Event:    types.ProgressEventNewArtifact,
		Artifact: artifact,
	}
	return &progressReader{
		source:       source,
		channel:      channel,
		interval:     interval,
		artifact:     artifact,
		lastUpdate:   time.Now(),
		offset:       0,
		offsetUpdate: 0,
	}
}

// reportDone indicates to the internal channel that the progress has been
// finished
func (r *progressReader) reportDone() {
	r.channel <- types.ProgressProperties{
		Event:        types.ProgressEventDone,
		Artifact:     r.artifact,
		Offset:       r.offset,
		OffsetUpdate: r.offsetUpdate,
	}
}

// Read continuously reads bytes into the progress reader and reports the
// status via the internal channel
func (r *progressReader) Read(p []byte) (int, error) {
	n, err := r.source.Read(p)
	r.offset += uint64(n)
	r.offsetUpdate += uint64(n)

	// Fire the progress reader in the provided interval
	if time.Since(r.lastUpdate) > r.interval {
		r.channel <- types.ProgressProperties{
			Event:        types.ProgressEventRead,
			Artifact:     r.artifact,
			Offset:       r.offset,
			OffsetUpdate: r.offsetUpdate,
		}
		r.lastUpdate = time.Now()
		r.offsetUpdate = 0
	}
	return n, err
}