-
Notifications
You must be signed in to change notification settings - Fork 446
Expand file tree
/
Copy pathimage_pull_progress.go
More file actions
284 lines (242 loc) · 7.55 KB
/
Copy pathimage_pull_progress.go
File metadata and controls
284 lines (242 loc) · 7.55 KB
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
package docker
import (
"bufio"
"encoding/json"
"fmt"
"io"
"os"
"strings"
"time"
"github.com/charmbracelet/bubbles/progress"
tea "github.com/charmbracelet/bubbletea"
"github.com/charmbracelet/lipgloss"
)
// imagePullProgress represents the JSON structure from Docker's ImagePull API
type imagePullProgress struct {
Status string `json:"status"`
ID string `json:"id"`
Progress string `json:"progress"`
ProgressDetail *imagePullProgressDetail `json:"progressDetail"`
}
type imagePullProgressDetail struct {
Current int64 `json:"current"`
Total int64 `json:"total"`
}
// progressMsg is sent when progress updates
type progressMsg struct {
percent float64
status string
}
// doneMsg is sent when pulling is complete
type doneMsg struct{}
// model holds the bubbletea model for the progress bar
type model struct {
progress progress.Model
imageName string
currentState string
done bool
}
func (m model) Init() tea.Cmd {
return nil
}
func (m model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
switch msg := msg.(type) {
case tea.WindowSizeMsg:
m.progress.Width = min(msg.Width-4, 80)
return m, nil
case progressMsg:
if msg.percent >= 1.0 {
m.done = true
return m, tea.Quit
}
m.currentState = msg.status
return m, m.progress.SetPercent(msg.percent)
case doneMsg:
m.done = true
return m, tea.Quit
case progress.FrameMsg:
progressModel, cmd := m.progress.Update(msg)
m.progress = progressModel.(progress.Model)
return m, cmd
default:
return m, nil
}
}
func (m model) View() string {
if m.done {
// Use Hatchet blue for success
successStyle := lipgloss.NewStyle().Foreground(lipgloss.Color("#3392FF")).Bold(true)
return successStyle.Render(fmt.Sprintf("✓ Pulled image %s\n", m.imageName))
}
pad := strings.Repeat(" ", 2)
// Use Hatchet muted cyan for status text
status := lipgloss.NewStyle().Foreground(lipgloss.Color("#A5C5E9")).Render(m.currentState)
return "\n" + pad + m.progress.View() + "\n" + pad + status + "\n"
}
// displayImagePullProgress displays progress information while pulling a Docker image.
// It is panic-safe and will not crash if there are any errors parsing the progress stream.
//
// Note: Docker's image pull API doesn't provide total layer count or size upfront.
// Layers are discovered progressively during the pull, so we track the maximum progress
// seen to ensure the progress bar only moves forward, even as new layers are discovered.
func displayImagePullProgress(reader io.Reader, imageName string) {
// Ensure we recover from any panics to avoid crashing the application
defer func() {
if r := recover(); r != nil {
// Silently recover - progress display is not critical
_ = r
}
}()
prog := progress.New(
progress.WithScaledGradient("#3392FF", "#B8D9FF"), // Blue to Cyan
progress.WithWidth(80),
progress.WithoutPercentage(),
)
m := model{
progress: prog,
imageName: imageName,
currentState: fmt.Sprintf("Pulling %s...", imageName),
}
p := tea.NewProgram(m)
// Channel to signal when the goroutine has finished consuming the reader
done := make(chan struct{})
// Start parsing in background
go func() {
defer func() {
if r := recover(); r != nil {
// Silently recover from parsing errors
_ = r
}
p.Send(doneMsg{})
close(done) // Signal that we're done consuming the reader
}()
scanner := bufio.NewScanner(reader)
layerProgress := make(map[string]*imagePullProgressDetail)
layerStates := make(map[string]string)
maxPercent := 0.0 // Track the maximum progress seen to ensure we only move forward
for scanner.Scan() {
line := scanner.Bytes()
var progress imagePullProgress
if err := json.Unmarshal(line, &progress); err != nil {
continue
}
// Track layer states
if progress.ID != "" {
layerStates[progress.ID] = progress.Status
if progress.ProgressDetail != nil && progress.ProgressDetail.Total > 0 {
layerProgress[progress.ID] = progress.ProgressDetail
}
}
// Calculate overall progress
percent, status := calculateProgress(layerProgress, layerStates)
// Only move forward - never backwards
if percent > maxPercent {
maxPercent = percent
p.Send(progressMsg{
percent: percent,
status: status,
})
} else {
// Still update status even if percentage hasn't increased
p.Send(progressMsg{
percent: maxPercent,
status: status,
})
}
// Small delay to avoid overwhelming the UI
time.Sleep(50 * time.Millisecond)
}
}()
// Run the program (this blocks until done)
if _, err := p.Run(); err != nil {
// Fallback for non-TTY environments: wait for the goroutine to finish
// consuming the reader before returning to ensure the image pull completes
<-done
fmt.Fprintf(os.Stderr, "Pulled image %s\n", imageName)
} else {
// Even on success, wait for the goroutine to clean up
<-done
}
}
// calculateProgress computes the overall progress percentage and status message
func calculateProgress(layerProgress map[string]*imagePullProgressDetail, layerStates map[string]string) (float64, string) {
if len(layerStates) == 0 {
return 0, "Starting..."
}
// Count states and track cached layers
statusCounts := make(map[string]int)
cachedLayers := 0
for _, status := range layerStates {
normalized := normalizeStatus(status)
statusCounts[normalized]++
// Track layers that are cached (no download needed)
if strings.Contains(strings.ToLower(status), "already exists") {
cachedLayers++
}
}
// Build status message
var parts []string
if count := statusCounts["downloading"]; count > 0 {
parts = append(parts, fmt.Sprintf("%d downloading", count))
}
if count := statusCounts["extracting"]; count > 0 {
parts = append(parts, fmt.Sprintf("%d extracting", count))
}
if count := statusCounts["complete"]; count > 0 {
parts = append(parts, fmt.Sprintf("%d complete", count))
}
statusMsg := strings.Join(parts, ", ")
if statusMsg == "" {
statusMsg = "Processing layers..."
}
// Calculate weighted progress
// Strategy: Only count layers that need downloading (have byte data or are actively downloading)
// Ignore cached layers in the denominator since they don't contribute to download time
var totalBytes int64
var currentBytes int64
activeLayerCount := 0
for _, detail := range layerProgress {
if detail.Total > 0 {
totalBytes += detail.Total
currentBytes += detail.Current
activeLayerCount++
}
}
var percent float64
switch {
case totalBytes > 0:
// Use byte-based progress for layers being downloaded
percent = float64(currentBytes) / float64(totalBytes)
case activeLayerCount == 0 && cachedLayers > 0:
// All layers are cached - show near complete
percent = 0.95
default:
// Fallback: base on completed non-cached layers
totalActiveLayers := len(layerStates) - cachedLayers
completedLayers := statusCounts["complete"] - cachedLayers
if totalActiveLayers > 0 {
percent = float64(completedLayers) / float64(totalActiveLayers)
}
}
// Cap at 0.99 until we receive the done message
if percent >= 1.0 {
percent = 0.99
}
return percent, statusMsg
}
// normalizeStatus converts various Docker status messages to simplified categories
func normalizeStatus(status string) string {
status = strings.ToLower(status)
switch {
case strings.Contains(status, "download"):
return "downloading"
case strings.Contains(status, "extract"):
return "extracting"
case strings.Contains(status, "pull complete"):
return "complete"
case strings.Contains(status, "already exists"):
return "complete"
default:
return "processing"
}
}