Repository navigation
Expand file tree
/
Copy pathcoolify.go
More file actions
268 lines (246 loc) · 7.4 KB
/
Copy pathcoolify.go
File metadata and controls
268 lines (246 loc) · 7.4 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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"time"
)
type coolifyEnvelope[T any] struct {
Data []T `json:"data"`
}
// Fields nullable in practice; pointers keep parse errors away.
type coolifyApp struct {
Name string `json:"name"`
Image *string `json:"docker_registry_image_name"`
Tag *string `json:"docker_registry_image_tag"`
BaseImg *string `json:"base_image"`
Version *string `json:"version"`
}
type coolifyService struct {
UUID string `json:"uuid"`
Name string `json:"name"`
Image *string `json:"docker_registry_image_name"`
Tag *string `json:"docker_registry_image_tag"`
BaseImg *string `json:"base_image"`
Version *string `json:"version"`
}
// coolifyServiceDetail is the per-service response: compose-based services
// expose their parsed sub-services here even though the list endpoint
// omits them. Sub-applications carry a plain "image" field (with tag
// embedded); the compose file content itself stays redacted at `read`
// token level — we don't need it.
type coolifyServiceApplication struct {
Name string `json:"name"`
// Compose-style services: "image" with tag embedded.
Image *string `json:"image"`
// Service-application style: registry name + tag split.
DockerRegistryImageName *string `json:"docker_registry_image_name"`
DockerRegistryImageTag *string `json:"docker_registry_image_tag"`
}
type coolifyServiceDetail struct {
Applications []coolifyServiceApplication `json:"applications"`
Databases []coolifyDatabase `json:"databases"`
}
type coolifyDatabase struct {
Name string `json:"name"`
Image *string `json:"image"`
}
type coolifyClient struct {
baseURL string
token string
http *http.Client
log *slog.Logger
}
var errMissingToken = fmt.Errorf("missing token")
func coolifyInventory(ctx context.Context, inst *CoolifyInstance, log *slog.Logger) ([]Service, error) {
c := &coolifyClient{
baseURL: inst.URL,
token: inst.Token,
http: &http.Client{Timeout: 60 * time.Second},
log: log,
}
if inst.Token == "" {
return nil, fmt.Errorf("%w: set CVEWATCHER_COOLIFY_%s_TOKEN", errMissingToken, coolifyEnvName(inst.Name))
}
var out []Service
apps, err := fetchJSON[coolifyApp](ctx, c, "/applications")
if err != nil {
return nil, err
}
for _, a := range apps {
ref := coolifyImageRef(a.Image, a.Tag, a.BaseImg, a.Version)
out = append(out, coolifyServiceEntry(inst.Name, a.Name, ref, log)...)
}
svcs, err := fetchJSON[coolifyService](ctx, c, "/services")
if err != nil {
return nil, err
}
for _, s := range svcs {
// List-level image fields (direct docker-image services).
ref := coolifyImageRef(s.Image, s.Tag, s.BaseImg, s.Version)
if ref.repo != "" {
out = append(out, coolifyServiceEntry(inst.Name, s.Name, ref, log)...)
continue
}
// Compose-based service: pull the detail endpoint for its parsed
// sub-applications. One degraded service must not kill the rest.
detail, derr := fetchOne[coolifyServiceDetail](ctx, c, "/services/"+s.UUID)
if derr != nil {
log.Warn("coolify service detail unavailable; listing as unwatchable",
"service", s.Name, "err", derr)
out = append(out, coolifyServiceEntry(inst.Name, s.Name, imageRef{}, log)...)
continue
}
entries := 0
for _, a := range detail.Applications {
ref := composeAppImageRef(a)
if ref.repo == "" {
continue
}
out = append(out, coolifyServiceEntry(inst.Name, s.Name+"-"+a.Name, ref, log)...)
entries++
}
for _, d := range detail.Databases {
if d.Image == nil || *d.Image == "" {
continue
}
out = append(out, coolifyServiceEntry(inst.Name, s.Name+"-"+d.Name, parseRef(*d.Image), log)...)
entries++
}
if entries == 0 {
// Build-pack compose service: nothing image-based to watch.
out = append(out, coolifyServiceEntry(inst.Name, s.Name, imageRef{}, log)...)
}
}
dbs, err := fetchJSON[coolifyDatabase](ctx, c, "/databases")
if err != nil {
return nil, err
}
for _, d := range dbs {
var ref imageRef
if d.Image != nil {
ref = parseRef(*d.Image)
}
out = append(out, coolifyServiceEntry(inst.Name, d.Name, ref, log)...)
}
return out, nil
}
func coolifyServiceEntry(instance, name string, ref imageRef, log *slog.Logger) []Service {
return []Service{{
Source: "coolify:" + instance, Location: instance, Name: name,
Image: ref.repo, Tag: ref.tag, RawRef: ref.raw,
}}
}
func coolifyEnvName(name string) string {
out := []rune(name)
for i, r := range out {
if r == '-' {
out[i] = '_'
} else {
out[i] = upper(r)
}
}
return string(out)
}
func upper(r rune) rune {
if r >= 'a' && r <= 'z' {
return r - 32
}
return r
}
func fetchJSON[T any](ctx context.Context, c *coolifyClient, path string) ([]T, error) {
raw, err := fetchRaw(ctx, c, path)
if err != nil {
return nil, err
}
// Some Coolify versions wrap lists in {"data":[...]}, others return a
// bare array. Accept both.
var env coolifyEnvelope[T]
if err := json.Unmarshal(raw, &env); err == nil && env.Data != nil {
return env.Data, nil
}
var bare []T
if err := json.Unmarshal(raw, &bare); err != nil {
return nil, fmt.Errorf("%s: decode: %w", path, err)
}
return bare, nil
}
// fetchOne fetches a single-object endpoint (some Coolify versions return
// the object bare, others wrapped in {"data": {...}}).
func fetchOne[T any](ctx context.Context, c *coolifyClient, path string) (*T, error) {
// Reuse the request/retry plumbing via fetchJSON's machinery by
// treating the object as a one-element list, then unwrapping.
type box struct{ Data *T }
raw, err := fetchRaw(ctx, c, path)
if err != nil {
return nil, err
}
var direct T
if err := json.Unmarshal(raw, &direct); err == nil {
return &direct, nil
}
var wrapped box
if err := json.Unmarshal(raw, &wrapped); err == nil && wrapped.Data != nil {
return wrapped.Data, nil
}
return nil, fmt.Errorf("%s: decode: unexpected response shape", path)
}
// fetchRaw performs the GET with auth, 429 Retry-After handling, and one
// retry, returning the raw body.
func fetchRaw(ctx context.Context, c *coolifyClient, path string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet,
c.baseURL+"/api/v1"+path, nil)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.token)
req.Header.Set("Accept", "application/json")
var body io.ReadCloser
var status int
for attempt := 0; attempt < 2; attempt++ {
resp, err := c.http.Do(req)
if err != nil {
return nil, fmt.Errorf("%s: %w", path, err)
}
if resp.StatusCode == http.StatusTooManyRequests {
// Respect Retry-After; docs call for it on self-hosted too.
wait := 5 * time.Second
if ra := resp.Header.Get("Retry-After"); ra != "" {
if d, err := time.ParseDuration(ra + "s"); err == nil {
wait = d
}
}
drainClose(resp)
c.log.Warn("coolify rate limited", "path", path, "wait", wait.String())
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
}
continue
}
status = resp.StatusCode
if status != http.StatusOK {
drainClose(resp)
return nil, fmt.Errorf("%s: HTTP %d", path, status)
}
body = resp.Body
break
}
if body == nil {
return nil, fmt.Errorf("%s: HTTP %d after retry", path, status)
}
defer body.Close()
raw, err := io.ReadAll(body)
if err != nil {
return nil, fmt.Errorf("%s: read: %w", path, err)
}
return raw, nil
}
func drainClose(resp *http.Response) {
io.Copy(io.Discard, io.LimitReader(resp.Body, 4096))
resp.Body.Close()
}