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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
|
package autoupdate
import (
"context"
"fmt"
"os"
"sort"
"github.com/containers/common/libimage"
"github.com/containers/common/pkg/config"
"github.com/containers/image/v5/docker"
"github.com/containers/image/v5/docker/reference"
"github.com/containers/image/v5/transports/alltransports"
"github.com/containers/podman/v4/libpod"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/libpod/events"
"github.com/containers/podman/v4/pkg/domain/entities"
"github.com/containers/podman/v4/pkg/systemd"
systemdDefine "github.com/containers/podman/v4/pkg/systemd/define"
"github.com/coreos/go-systemd/v22/dbus"
"github.com/sirupsen/logrus"
)
// Label denotes the container/pod label key to specify auto-update policies in
// container labels.
const Label = "io.containers.autoupdate"
// Label denotes the container label key to specify authfile in
// container labels.
const AuthfileLabel = "io.containers.autoupdate.authfile"
// Policy represents an auto-update policy.
type Policy string
const (
// PolicyDefault is the default policy denoting no auto updates.
PolicyDefault Policy = "disabled"
// PolicyRegistryImage is the policy to update as soon as there's a new image found.
PolicyRegistryImage = "registry"
// PolicyLocalImage is the policy to run auto-update based on a local image
PolicyLocalImage = "local"
)
// Map for easy lookups of supported policies.
var supportedPolicies = map[string]Policy{
"": PolicyDefault,
"disabled": PolicyDefault,
"image": PolicyRegistryImage,
"registry": PolicyRegistryImage,
"local": PolicyLocalImage,
}
// policyMapper is used for tying a container to it's autoupdate policy
type policyMapper map[Policy][]*libpod.Container
// updater includes shared state for auto-updating one or more containers.
type updater struct {
conn *dbus.Conn
imageToPolicyMapper map[string]policyMapper
options *entities.AutoUpdateOptions
updatedRawImages map[string]bool
runtime *libpod.Runtime
}
// LookupPolicy looks up the corresponding Policy for the specified
// string. If none is found, an errors is returned including the list of
// supported policies.
//
// Note that an empty string resolved to PolicyDefault.
func LookupPolicy(s string) (Policy, error) {
policy, exists := supportedPolicies[s]
if exists {
return policy, nil
}
// Sort the keys first as maps are non-deterministic.
keys := []string{}
for k := range supportedPolicies {
if k != "" {
keys = append(keys, k)
}
}
sort.Strings(keys)
return "", fmt.Errorf("invalid auto-update policy %q: valid policies are %+q", s, keys)
}
// ValidateImageReference checks if the specified imageName is a fully-qualified
// image reference to the docker transport (without digest). Such a reference
// includes a domain, name and tag (e.g., quay.io/podman/stable:latest). The
// reference may also be prefixed with "docker://" explicitly indicating that
// it's a reference to the docker transport.
func ValidateImageReference(imageName string) error {
// Make sure the input image is a docker.
imageRef, err := alltransports.ParseImageName(imageName)
if err == nil && imageRef.Transport().Name() != docker.Transport.Name() {
return fmt.Errorf("auto updates require the docker image transport but image is of transport %q", imageRef.Transport().Name())
} else if err != nil {
repo, err := reference.Parse(imageName)
if err != nil {
return fmt.Errorf("enforcing fully-qualified docker transport reference for auto updates: %w", err)
}
if _, ok := repo.(reference.NamedTagged); !ok {
return fmt.Errorf("auto updates require fully-qualified image references (no tag): %q", imageName)
}
if _, ok := repo.(reference.Digested); ok {
return fmt.Errorf("auto updates require fully-qualified image references without digest: %q", imageName)
}
}
return nil
}
// AutoUpdate looks up containers with a specified auto-update policy and acts
// accordingly.
//
// If the policy is set to PolicyRegistryImage, it checks if the image
// on the remote registry is different than the local one. If the image digests
// differ, it pulls the remote image and restarts the systemd unit running the
// container.
//
// If the policy is set to PolicyLocalImage, it checks if the image
// of a running container is different than the local one. If the image digests
// differ, it restarts the systemd unit with the new image.
//
// It returns a slice of successfully restarted systemd units and a slice of
// errors encountered during auto update.
func AutoUpdate(ctx context.Context, runtime *libpod.Runtime, options entities.AutoUpdateOptions) ([]*entities.AutoUpdateReport, []error) {
auto := updater{
options: &options,
runtime: runtime,
updatedRawImages: make(map[string]bool),
}
// Create a map from `image ID -> []*Container`.
if errs := auto.imageContainersMap(); len(errs) > 0 {
return nil, errs
}
// Nothing to do.
if len(auto.imageToPolicyMapper) == 0 {
return nil, nil
}
// Create a map from `image ID -> *libimage.Image` for image lookups.
listOptions := &libimage.ListImagesOptions{
Filters: []string{"readonly=false"},
}
imagesSlice, err := runtime.LibimageRuntime().ListImages(ctx, nil, listOptions)
if err != nil {
return nil, []error{err}
}
imageMap := make(map[string]*libimage.Image)
for i := range imagesSlice {
imageMap[imagesSlice[i].ID()] = imagesSlice[i]
}
// Connect to DBUS.
conn, err := systemd.ConnectToDBUS()
if err != nil {
logrus.Errorf(err.Error())
return nil, []error{err}
}
defer conn.Close()
auto.conn = conn
runtime.NewSystemEvent(events.AutoUpdate)
// Update all images/container according to their auto-update policy.
var allReports []*entities.AutoUpdateReport
var errs []error
for imageID, policyMapper := range auto.imageToPolicyMapper {
image, exists := imageMap[imageID]
if !exists {
errs = append(errs, fmt.Errorf("container image ID %q not found in local storage", imageID))
return nil, errs
}
for _, ctr := range policyMapper[PolicyRegistryImage] {
report, err := auto.updateRegistry(ctx, image, ctr)
if err != nil {
errs = append(errs, err)
}
if report != nil {
allReports = append(allReports, report)
}
}
for _, ctr := range policyMapper[PolicyLocalImage] {
report, err := auto.updateLocally(ctx, image, ctr)
if err != nil {
errs = append(errs, err)
}
if report != nil {
allReports = append(allReports, report)
}
}
}
return allReports, errs
}
// updateRegistry updates the image/container according to the "registry" policy.
func (u *updater) updateRegistry(ctx context.Context, image *libimage.Image, ctr *libpod.Container) (*entities.AutoUpdateReport, error) {
cid := ctr.ID()
rawImageName := ctr.RawImageName()
if rawImageName == "" {
return nil, fmt.Errorf("registry auto-updating container %q: raw-image name is empty", cid)
}
labels := ctr.Labels()
unit, exists := labels[systemdDefine.EnvVariable]
if !exists {
return nil, fmt.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
}
report := &entities.AutoUpdateReport{
ContainerID: cid,
ContainerName: ctr.Name(),
ImageName: rawImageName,
Policy: PolicyRegistryImage,
SystemdUnit: unit,
Updated: "failed",
}
if _, updated := u.updatedRawImages[rawImageName]; updated {
logrus.Infof("Auto-updating container %q using registry image %q", cid, rawImageName)
if err := u.restartSystemdUnit(ctx, ctr, unit); err != nil {
return report, err
}
report.Updated = "true"
return report, nil
}
authfile := getAuthfilePath(ctr, u.options)
needsUpdate, err := newerRemoteImageAvailable(ctx, image, rawImageName, authfile)
if err != nil {
return report, fmt.Errorf("registry auto-updating container %q: image check for %q failed: %w", cid, rawImageName, err)
}
if !needsUpdate {
report.Updated = "false"
return report, nil
}
if u.options.DryRun {
report.Updated = "pending"
return report, nil
}
if _, err := updateImage(ctx, u.runtime, rawImageName, authfile); err != nil {
return report, fmt.Errorf("registry auto-updating container %q: image update for %q failed: %w", cid, rawImageName, err)
}
u.updatedRawImages[rawImageName] = true
logrus.Infof("Auto-updating container %q using registry image %q", cid, rawImageName)
updateErr := u.restartSystemdUnit(ctx, ctr, unit)
if updateErr == nil {
report.Updated = "true"
return report, nil
}
if !u.options.Rollback {
return report, updateErr
}
// To fallback, simply retag the old image and restart the service.
if err := image.Tag(rawImageName); err != nil {
return report, fmt.Errorf("falling back to previous image: %w", err)
}
if err := u.restartSystemdUnit(ctx, ctr, unit); err != nil {
return report, fmt.Errorf("restarting unit with old image during fallback: %w", err)
}
report.Updated = "rolled back"
return report, nil
}
// updateRegistry updates the image/container according to the "local" policy.
func (u *updater) updateLocally(ctx context.Context, image *libimage.Image, ctr *libpod.Container) (*entities.AutoUpdateReport, error) {
cid := ctr.ID()
rawImageName := ctr.RawImageName()
if rawImageName == "" {
return nil, fmt.Errorf("locally auto-updating container %q: raw-image name is empty", cid)
}
labels := ctr.Labels()
unit, exists := labels[systemdDefine.EnvVariable]
if !exists {
return nil, fmt.Errorf("auto-updating container %q: no %s label found", ctr.ID(), systemdDefine.EnvVariable)
}
report := &entities.AutoUpdateReport{
ContainerID: cid,
ContainerName: ctr.Name(),
ImageName: rawImageName,
Policy: PolicyLocalImage,
SystemdUnit: unit,
Updated: "failed",
}
needsUpdate, err := newerLocalImageAvailable(u.runtime, image, rawImageName)
if err != nil {
return report, fmt.Errorf("locally auto-updating container %q: image check for %q failed: %w", cid, rawImageName, err)
}
if !needsUpdate {
report.Updated = "false"
return report, nil
}
if u.options.DryRun {
report.Updated = "pending"
return report, nil
}
logrus.Infof("Auto-updating container %q using local image %q", cid, rawImageName)
updateErr := u.restartSystemdUnit(ctx, ctr, unit)
if updateErr == nil {
report.Updated = "true"
return report, nil
}
if !u.options.Rollback {
return report, updateErr
}
// To fallback, simply retag the old image and restart the service.
if err := image.Tag(rawImageName); err != nil {
return report, fmt.Errorf("falling back to previous image: %w", err)
}
if err := u.restartSystemdUnit(ctx, ctr, unit); err != nil {
return report, fmt.Errorf("restarting unit with old image during fallback: %w", err)
}
report.Updated = "rolled back"
return report, nil
}
// restartSystemdUnit restarts the systemd unit the container is running in.
func (u *updater) restartSystemdUnit(ctx context.Context, ctr *libpod.Container, unit string) error {
restartChan := make(chan string)
if _, err := u.conn.RestartUnitContext(ctx, unit, "replace", restartChan); err != nil {
return fmt.Errorf("auto-updating container %q: restarting systemd unit %q failed: %w", ctr.ID(), unit, err)
}
// Wait for the restart to finish and actually check if it was
// successful or not.
result := <-restartChan
switch result {
case "done":
logrus.Infof("Successfully restarted systemd unit %q of container %q", unit, ctr.ID())
return nil
default:
return fmt.Errorf("auto-updating container %q: restarting systemd unit %q failed: expected %q but received %q", ctr.ID(), unit, "done", result)
}
}
// imageContainersMap generates a map[image ID] -> [containers using the image]
// of all containers with a valid auto-update policy.
func (u *updater) imageContainersMap() []error {
allContainers, err := u.runtime.GetAllContainers()
if err != nil {
return []error{err}
}
u.imageToPolicyMapper = make(map[string]policyMapper)
errors := []error{}
for _, ctr := range allContainers {
state, err := ctr.State()
if err != nil {
errors = append(errors, err)
continue
}
// Only update running containers.
if state != define.ContainerStateRunning {
continue
}
// Only update containers with the specific label/policy set.
labels := ctr.Labels()
value, exists := labels[Label]
if !exists {
continue
}
policy, err := LookupPolicy(value)
if err != nil {
errors = append(errors, err)
continue
}
// Skip labels not related to autoupdate
if policy == PolicyDefault {
continue
} else {
id, _ := ctr.Image()
policyMap, exists := u.imageToPolicyMapper[id]
if !exists {
policyMap = make(map[Policy][]*libpod.Container)
}
policyMap[policy] = append(policyMap[policy], ctr)
u.imageToPolicyMapper[id] = policyMap
// Now we know that `ctr` is configured for auto updates.
}
}
return errors
}
// getAuthfilePath returns an authfile path, if set. The authfile label in the
// container, if set, as precedence over the one set in the options.
func getAuthfilePath(ctr *libpod.Container, options *entities.AutoUpdateOptions) string {
labels := ctr.Labels()
authFilePath, exists := labels[AuthfileLabel]
if exists {
return authFilePath
}
return options.Authfile
}
// newerRemoteImageAvailable returns true if there corresponding image on the remote
// registry is newer.
func newerRemoteImageAvailable(ctx context.Context, img *libimage.Image, origName string, authfile string) (bool, error) {
remoteRef, err := docker.ParseReference("//" + origName)
if err != nil {
return false, err
}
options := &libimage.HasDifferentDigestOptions{AuthFilePath: authfile}
return img.HasDifferentDigest(ctx, remoteRef, options)
}
// newerLocalImageAvailable returns true if the container and local image have different digests
func newerLocalImageAvailable(runtime *libpod.Runtime, img *libimage.Image, rawImageName string) (bool, error) {
localImg, _, err := runtime.LibimageRuntime().LookupImage(rawImageName, nil)
if err != nil {
return false, err
}
return localImg.Digest().String() != img.Digest().String(), nil
}
// updateImage pulls the specified image.
func updateImage(ctx context.Context, runtime *libpod.Runtime, name, authfile string) (*libimage.Image, error) {
pullOptions := &libimage.PullOptions{}
pullOptions.AuthFilePath = authfile
pullOptions.Writer = os.Stderr
pulledImages, err := runtime.LibimageRuntime().Pull(ctx, name, config.PullPolicyAlways, pullOptions)
if err != nil {
return nil, err
}
return pulledImages[0], nil
}
|