Skip to content

Commit e45e776

Browse files
authored
Merge pull request redenfire#31 from NeoMod/pr/feat-docker-pull-rate-limit-warning
feat: support multi-registry auth and pull errors
2 parents d39339a + 448b20a commit e45e776

4 files changed

Lines changed: 126 additions & 44 deletions

File tree

‎README.md‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Open [http://localhost:8099](http://localhost:8099).
1818
Or use Docker Compose:
1919

2020
```yaml
21+
2122
services:
2223
image-watch:
2324
image: ghcr.io/redenfire/docker-image-watcher:latest
@@ -32,7 +33,10 @@ services:
3233
- PORT=8080
3334
- DOCKER_SOCK=/var/run/docker.sock
3435
- AUTO_FILE=/data/auto-update.json
35-
# - AUTH_USER=admin # uncomment to enable auth
36+
# - CHECK_INTERVAL=10m # default: 10m
37+
# - CHECK_CONCURRENCY=5 # default: 5
38+
# - AUTO_COOLDOWN=5m # default: 5m
39+
# - AUTH_USER=admin # uncomment to enable auth
3640
# - AUTH_PASS=changeme
3741

3842
volumes:
@@ -48,8 +52,10 @@ volumes:
4852
- Background check every 10 minutes with 5-minute auto-update cooldown
4953
- i18n with EN/IT language toggle
5054
- Optional auth via AUTH_USER/AUTH_PASS with login page and HMAC-signed session cookies
55+
- Supports authenticated Docker pulls via `DOCKER_REGISTRY_AUTH`, using either `username:password` for Docker Hub or a JSON registry map for multiple registries
56+
- Persists last container pull error in UI until a later successful pull clears it
5157
- Excludes own container from listing and blocks self-update
52-
- Multi-arch container build support for `linux/amd64`, `linux/arm64`, `linux/arm/v7`
58+
- Single-arch CI build; multi-arch builds supported locally with Docker Buildx
5359

5460
## How It Works
5561

@@ -113,7 +119,7 @@ Full reference: [`docs/project/API.md`](docs/project/API.md)
113119
| `CHECK_INTERVAL` | `10m` | Background check interval |
114120
| `CHECK_CONCURRENCY` | `5` | Max concurrent registry requests during check |
115121
| `AUTO_COOLDOWN` | `5m` | Cooldown between auto-updates for same container |
116-
| `DOCKER_REGISTRY_AUTH` | — | Docker registry credentials in `username:password` format. When set, sends authenticated pull requests to Docker Engine API via `X-Registry-Auth` header, avoiding unauthenticated Docker Hub pull rate limits. |
122+
| `DOCKER_REGISTRY_AUTH` | — | Docker registry auth. Supports `username:password` for Docker Hub only, or a JSON map like `{"ghcr.io":"user:token","https://index.docker.io/v1/":"user:token"}` for multi-registry pulls. |
117123

118124
Details: [`docs/project/CONFIGURATION.md`](docs/project/CONFIGURATION.md)
119125

@@ -158,7 +164,7 @@ The application exposes a `GET /health` endpoint that returns HTTP 200. Since th
158164
## Troubleshooting
159165

160166
- Images showing `unknown` status: check Docker socket access and registry connectivity
161-
- Pull failures or UI rate-limit banner: check Docker Hub rate limits, configure `DOCKER_REGISTRY_AUTH` for authenticated pulls, or wait for rate-limit window to reset
167+
- Pull failures, persistent container error text, or UI rate-limit banner: check Docker Hub rate limits, configure `DOCKER_REGISTRY_AUTH` with Docker Hub shorthand or JSON multi-registry credentials, or wait for rate-limit window to reset
162168
- Auto-update not triggering: confirm container is `outdated` and not inside cooldown window
163169

164170
More: [`docs/project/TROUBLESHOOTING.md`](docs/project/TROUBLESHOOTING.md)

‎docker.go‎

Lines changed: 72 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,18 @@ func dockerClient() *http.Client {
4242
}
4343
}
4444

45+
func pullStreamDockerClient() *http.Client {
46+
return &http.Client{
47+
Transport: &http.Transport{
48+
DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) {
49+
dialer := &net.Dialer{Timeout: 30 * time.Second}
50+
return dialer.DialContext(ctx, "unix", dockerSocket)
51+
},
52+
ResponseHeaderTimeout: 30 * time.Second,
53+
},
54+
}
55+
}
56+
4557
func dockerAPI(method, path string, body io.Reader) (*http.Response, error) {
4658
client := dockerClient()
4759
url := "http://localhost" + path
@@ -98,41 +110,80 @@ func IsRateLimitError(err error) bool {
98110
strings.Contains(msg, "too many requests")
99111
}
100112

113+
func registryAliases(hostname string) []string {
114+
switch hostname {
115+
case "registry-1.docker.io", "docker.io", "index.docker.io", "https://index.docker.io/v1/":
116+
return []string{"https://index.docker.io/v1/", "registry-1.docker.io", "docker.io", "index.docker.io"}
117+
default:
118+
return []string{hostname}
119+
}
120+
}
121+
122+
func buildRegistryAuthHeader(serverAddress, auth string) (string, error) {
123+
username, password, ok := strings.Cut(auth, ":")
124+
if !ok || username == "" || password == "" {
125+
return "", fmt.Errorf("invalid registry auth, expected username:password")
126+
}
127+
payload, err := json.Marshal(struct {
128+
Username string `json:"username"`
129+
Password string `json:"password"`
130+
ServerAddress string `json:"serveraddress,omitempty"`
131+
}{
132+
Username: username,
133+
Password: password,
134+
ServerAddress: serverAddress,
135+
})
136+
if err != nil {
137+
return "", err
138+
}
139+
return base64.StdEncoding.EncodeToString(payload), nil
140+
}
141+
101142
func pullImageStream(image string, progressFn func(PullProgress)) error {
102143
v := url.Values{}
103144
v.Set("fromImage", image)
104-
client := dockerClient()
145+
client := pullStreamDockerClient()
105146
req, err := http.NewRequest("POST", "http://localhost/images/create?"+v.Encode(), nil)
106147
if err != nil {
107148
return fmt.Errorf("pull request: %w", err)
108149
}
109150
req.Header.Set("Content-Type", "application/json")
110151
auth := strings.TrimSpace(os.Getenv("DOCKER_REGISTRY_AUTH"))
111152
if auth != "" {
112-
username, password, ok := strings.Cut(auth, ":")
113-
if !ok || username == "" || password == "" {
114-
return fmt.Errorf("registry auth: invalid DOCKER_REGISTRY_AUTH, expected username:password")
153+
registry := ""
154+
if host, _, _, ok := parseImage(image); ok {
155+
registry = host
115156
}
116-
serverAddress := ""
117-
if registry, _, _, ok := parseImage(image); ok {
118-
serverAddress = registry
119-
if serverAddress == "registry-1.docker.io" {
120-
serverAddress = "https://index.docker.io/v1/"
157+
aliases := registryAliases(registry)
158+
header := ""
159+
var authByRegistry map[string]string
160+
if strings.HasPrefix(auth, "{") {
161+
if err := json.Unmarshal([]byte(auth), &authByRegistry); err != nil {
162+
return fmt.Errorf("registry auth: invalid JSON auth map: %w", err)
163+
}
164+
for _, alias := range aliases {
165+
if creds, ok := authByRegistry[alias]; ok && strings.TrimSpace(creds) != "" {
166+
header, err = buildRegistryAuthHeader(alias, creds)
167+
if err != nil {
168+
return fmt.Errorf("registry auth: %w", err)
169+
}
170+
break
171+
}
172+
}
173+
} else {
174+
for _, alias := range aliases {
175+
if alias == "https://index.docker.io/v1/" {
176+
header, err = buildRegistryAuthHeader(alias, auth)
177+
if err != nil {
178+
return fmt.Errorf("registry auth: %w", err)
179+
}
180+
break
181+
}
121182
}
122183
}
123-
payload, err := json.Marshal(struct {
124-
Username string `json:"username"`
125-
Password string `json:"password"`
126-
ServerAddress string `json:"serveraddress,omitempty"`
127-
}{
128-
Username: username,
129-
Password: password,
130-
ServerAddress: serverAddress,
131-
})
132-
if err != nil {
133-
return fmt.Errorf("registry auth: %w", err)
184+
if header != "" {
185+
req.Header.Set("X-Registry-Auth", header)
134186
}
135-
req.Header.Set("X-Registry-Auth", base64.StdEncoding.EncodeToString(payload))
136187
}
137188
resp, err := client.Do(req)
138189
if err != nil {

‎main.go‎

Lines changed: 40 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"embed"
1010
"encoding/base64"
1111
"encoding/json"
12+
"errors"
1213
"io/fs"
1314
"log"
1415
"net/http"
@@ -196,6 +197,7 @@ type ContainerItem struct {
196197
LocalDigest string `json:"local_digest"`
197198
Status string `json:"status"`
198199
AutoUpdate bool `json:"auto_update"`
200+
Error string `json:"error,omitempty"`
199201
}
200202

201203
type ImageGroup struct {
@@ -206,15 +208,16 @@ type ImageGroup struct {
206208
}
207209

208210
type App struct {
209-
mu sync.RWMutex
210-
images []ImageGroup
211-
autoFile string
212-
autoSaved map[string]bool
213-
cooldowns map[string]time.Time
214-
rateLimited bool
215-
progress sync.Map
216-
updating sync.Map
217-
selfCID string
211+
mu sync.RWMutex
212+
images []ImageGroup
213+
autoFile string
214+
autoSaved map[string]bool
215+
cooldowns map[string]time.Time
216+
containerErrors map[string]string
217+
rateLimited bool
218+
progress sync.Map
219+
updating sync.Map
220+
selfCID string
218221
}
219222

220223
func main() {
@@ -228,9 +231,10 @@ func main() {
228231
}
229232

230233
app := &App{
231-
autoFile: autoFile,
232-
autoSaved: make(map[string]bool),
233-
cooldowns: make(map[string]time.Time),
234+
autoFile: autoFile,
235+
autoSaved: make(map[string]bool),
236+
cooldowns: make(map[string]time.Time),
237+
containerErrors: make(map[string]string),
234238
}
235239
app.loadAuto()
236240
if host, err := os.Hostname(); err == nil && len(host) >= 12 {
@@ -562,6 +566,9 @@ func (app *App) checkAll() {
562566
if auto, ok := autoMap[e.cid]; ok {
563567
item.AutoUpdate = auto
564568
}
569+
app.mu.RLock()
570+
item.Error = app.containerErrors[e.cid]
571+
app.mu.RUnlock()
565572
containers = append(containers, item)
566573
}
567574

@@ -596,9 +603,19 @@ func (app *App) checkAll() {
596603
return results[i].Image < results[j].Image
597604
})
598605

606+
rateLimited := sawRateLimit
607+
app.mu.RLock()
608+
for _, err := range app.containerErrors {
609+
if IsRateLimitError(errors.New(err)) {
610+
rateLimited = true
611+
break
612+
}
613+
}
614+
app.mu.RUnlock()
615+
599616
app.mu.Lock()
600617
app.images = results
601-
app.rateLimited = sawRateLimit
618+
app.rateLimited = rateLimited
602619
app.mu.Unlock()
603620

604621
autoCooldown := getEnvDuration("AUTO_COOLDOWN", 5*time.Minute)
@@ -644,21 +661,29 @@ func (app *App) updateContainer(cid string) {
644661
if err := pullImageStream(image, func(p PullProgress) {
645662
app.progress.Store(cid, p)
646663
}); err != nil {
664+
app.mu.Lock()
665+
app.containerErrors[cid] = err.Error()
647666
if IsRateLimitError(err) {
648-
app.mu.Lock()
649667
app.rateLimited = true
650-
app.mu.Unlock()
651668
}
669+
app.mu.Unlock()
652670
app.progress.Store(cid, PullProgress{Status: "error: " + err.Error()})
653671
log.Printf("pull %s: %v", image, err)
672+
app.checkAll()
654673
return
655674
}
675+
app.mu.Lock()
676+
delete(app.containerErrors, cid)
677+
app.mu.Unlock()
656678
app.progress.Store(cid, PullProgress{Status: "recreating", Percent: 100})
657679
if err := recreateContainer(cid, image); err != nil {
658680
app.progress.Store(cid, PullProgress{Status: "error: " + err.Error()})
659681
log.Printf("recreate %s: %v", cid, err)
660682
return
661683
}
684+
app.mu.Lock()
685+
delete(app.containerErrors, cid)
686+
app.mu.Unlock()
662687
app.progress.Delete(cid)
663688
log.Printf("updated %s -> %s", containerName, image)
664689
app.checkAll()

‎web/index.html‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ <h1>🐳 <span id="appTitle">Docker Image Watcher</span> <small id="status"></sm
119119
logout: 'Logout',
120120
dismiss: 'Dismiss',
121121
rateLimitTitle: 'Docker pull rate limit detected',
122-
rateLimitBody: 'Anonymous registry pulls are being throttled. Set DOCKER_REGISTRY_AUTH=username:password, then wait for next successful check or pull.',
122+
rateLimitBody: 'Anonymous registry pulls are being throttled. Configure DOCKER_REGISTRY_AUTH with Docker Hub shorthand or JSON per-registry credentials, then wait for next successful check or pull.',
123123
},
124124
it: {
125125
title: 'Docker Image Watcher',
@@ -152,7 +152,7 @@ <h1>🐳 <span id="appTitle">Docker Image Watcher</span> <small id="status"></sm
152152
logout: 'Esci',
153153
dismiss: 'Chiudi',
154154
rateLimitTitle: 'Limite di pull Docker rilevato',
155-
rateLimitBody: 'I pull anonimi dal registry sono limitati. Imposta DOCKER_REGISTRY_AUTH=username:password, poi attendi il prossimo controllo o pull riuscito.',
155+
rateLimitBody: 'I pull anonimi dal registry sono limitati. Configura DOCKER_REGISTRY_AUTH con formato Docker Hub o JSON per-registry, poi attendi il prossimo controllo o pull riuscito.',
156156
}
157157
};
158158

@@ -244,7 +244,7 @@ <h1>🐳 <span id="appTitle">Docker Image Watcher</span> <small id="status"></sm
244244
<td class="digest">${esc(c.local_digest)}</td>
245245
<td></td>
246246
<td><div class="toggle ${c.auto_update ? 'on' : ''}" data-cid="${esc(c.container_id)}" onclick="toggle(this)"></div></td>
247-
<td><div class="progress-cell" id="progress-${esc(c.container_id)}">${isUpdating ? '<div class="progress-bar"><div class="bar"><div class="fill" style="width:0%"></div></div><span class="pct">0%</span></div>' : `<button class="btn btn-update" data-cid="${esc(c.container_id)}" onclick="doUpdate(this)" ${c.status !== 'outdated' ? 'disabled' : ''}>${esc(t.update)}</button>`}</div></td>
247+
<td><div class="progress-cell" id="progress-${esc(c.container_id)}">${isUpdating ? '<div class="progress-bar"><div class="bar"><div class="fill" style="width:0%"></div></div><span class="pct">0%</span></div>' : `<button class="btn btn-update" data-cid="${esc(c.container_id)}" onclick="doUpdate(this)" ${c.status !== 'outdated' ? 'disabled' : ''}>${esc(t.update)}</button>`}</div>${c.error ? `<div style="color:#ef4444;font-size:.7rem;margin-top:4px;word-break:break-all">${esc(c.error)}</div>` : ''}</td>
248248
</tr>`;
249249
}
250250
}
@@ -314,7 +314,7 @@ <h1>🐳 <span id="appTitle">Docker Image Watcher</span> <small id="status"></sm
314314
const res = await fetch(`/api/images/${cid}/progress`);
315315
if (!res.ok) { updating.delete(cid); load(); return; }
316316
const p = await res.json();
317-
if (p.status === 'error' || p.status === 'recreating') {
317+
if (p.status === 'recreating' || p.status.startsWith('error')) {
318318
const statusLabel = p.status === 'recreating' ? t.recreating : (p.status.startsWith('error') ? p.status.replace('error: ', t.errorLabel + ': ') : p.status);
319319
cell.innerHTML = `<div class="progress-bar"><div class="bar"><div class="fill" style="width:${p.percent}%"></div></div><span class="pct">${p.percent}%</span> <span style="color:#94a3b8;font-size:.7rem">${esc(statusLabel)}</span></div>`;
320320
if (p.status === 'recreating') {

0 commit comments

Comments
 (0)