| 1 |
/* |
| 2 |
Copyright The containerd Authors. |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
*/ |
| 16 |
|
| 17 |
package snapshot |
| 18 |
|
| 19 |
import ( |
| 20 |
"context" |
| 21 |
"fmt" |
| 22 |
"os" |
| 23 |
"path/filepath" |
| 24 |
"strings" |
| 25 |
"syscall" |
| 26 |
|
| 27 |
"github.com/containerd/containerd/errdefs" |
| 28 |
"github.com/containerd/containerd/log" |
| 29 |
"github.com/containerd/containerd/mount" |
| 30 |
"github.com/containerd/containerd/snapshots" |
| 31 |
"github.com/containerd/containerd/snapshots/overlay/overlayutils" |
| 32 |
"github.com/containerd/containerd/snapshots/storage" |
| 33 |
"github.com/containerd/continuity/fs" |
| 34 |
"github.com/moby/sys/mountinfo" |
| 35 |
"github.com/sirupsen/logrus" |
| 36 |
"golang.org/x/sync/errgroup" |
| 37 |
) |
| 38 |
|
| 39 |
const ( |
| 40 |
targetSnapshotLabel = "containerd.io/snapshot.ref" |
| 41 |
remoteLabel = "containerd.io/snapshot/remote" |
| 42 |
remoteLabelVal = "remote snapshot" |
| 43 |
|
| 44 |
// remoteSnapshotLogKey is a key for log line, which indicates whether |
| 45 |
// `Prepare` method successfully prepared targeting remote snapshot or not, as |
| 46 |
// defined in the following: |
| 47 |
// - "true" : indicates the snapshot has been successfully prepared as a |
| 48 |
// remote snapshot |
| 49 |
// - "false" : indicates the snapshot failed to be prepared as a remote |
| 50 |
// snapshot |
| 51 |
// - null : undetermined |
| 52 |
remoteSnapshotLogKey = "remote-snapshot-prepared" |
| 53 |
prepareSucceeded = "true" |
| 54 |
prepareFailed = "false" |
| 55 |
) |
| 56 |
|
| 57 |
// FileSystem is a backing filesystem abstraction. |
| 58 |
// |
| 59 |
// Mount() tries to mount a remote snapshot to the specified mount point |
| 60 |
// directory. If succeed, the mountpoint directory will be treated as a layer |
| 61 |
// snapshot. If Mount() fails, the mountpoint directory MUST be cleaned up. |
| 62 |
// Check() is called to check the connectibity of the existing layer snapshot |
| 63 |
// every time the layer is used by containerd. |
| 64 |
// Unmount() is called to unmount a remote snapshot from the specified mount point |
| 65 |
// directory. |
| 66 |
type FileSystem interface { |
| 67 |
Mount(ctx context.Context, mountpoint string, labels map[string]string) error |
| 68 |
Check(ctx context.Context, mountpoint string, labels map[string]string) error |
| 69 |
Unmount(ctx context.Context, mountpoint string) error |
| 70 |
} |
| 71 |
|
| 72 |
// SnapshotterConfig is used to configure the remote snapshotter instance |
| 73 |
type SnapshotterConfig struct { |
| 74 |
asyncRemove bool |
| 75 |
noRestore bool |
| 76 |
allowInvalidMountsOnRestart bool |
| 77 |
} |
| 78 |
|
| 79 |
// Opt is an option to configure the remote snapshotter |
| 80 |
type Opt func(config *SnapshotterConfig) error |
| 81 |
|
| 82 |
// AsynchronousRemove defers removal of filesystem content until |
| 83 |
// the Cleanup method is called. Removals will make the snapshot |
| 84 |
// referred to by the key unavailable and make the key immediately |
| 85 |
// available for re-use. |
| 86 |
func AsynchronousRemove(config *SnapshotterConfig) error { |
| 87 |
config.asyncRemove = true |
| 88 |
return nil |
| 89 |
} |
| 90 |
|
| 91 |
func NoRestore(config *SnapshotterConfig) error { |
| 92 |
config.noRestore = true |
| 93 |
return nil |
| 94 |
} |
| 95 |
|
| 96 |
func AllowInvalidMountsOnRestart(config *SnapshotterConfig) error { |
| 97 |
config.allowInvalidMountsOnRestart = true |
| 98 |
return nil |
| 99 |
} |
| 100 |
|
| 101 |
type snapshotter struct { |
| 102 |
root string |
| 103 |
ms *storage.MetaStore |
| 104 |
asyncRemove bool |
| 105 |
|
| 106 |
// fs is a filesystem that this snapshotter recognizes. |
| 107 |
fs FileSystem |
| 108 |
userxattr bool // whether to enable "userxattr" mount option |
| 109 |
noRestore bool |
| 110 |
allowInvalidMountsOnRestart bool |
| 111 |
} |
| 112 |
|
| 113 |
// NewSnapshotter returns a Snapshotter which can use unpacked remote layers |
| 114 |
// as snapshots. This is implemented based on the overlayfs snapshotter, so |
| 115 |
// diffs are stored under the provided root and a metadata file is stored under |
| 116 |
// the root as same as overlayfs snapshotter. |
| 117 |
func NewSnapshotter(ctx context.Context, root string, targetFs FileSystem, opts ...Opt) (snapshots.Snapshotter, error) { |
| 118 |
if targetFs == nil { |
| 119 |
return nil, fmt.Errorf("Specify filesystem to use") |
| 120 |
} |
| 121 |
|
| 122 |
var config SnapshotterConfig |
| 123 |
for _, opt := range opts { |
| 124 |
if err := opt(&config); err != nil { |
| 125 |
return nil, err |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
if err := os.MkdirAll(root, 0700); err != nil { |
| 130 |
return nil, err |
| 131 |
} |
| 132 |
supportsDType, err := fs.SupportsDType(root) |
| 133 |
if err != nil { |
| 134 |
return nil, err |
| 135 |
} |
| 136 |
if !supportsDType { |
| 137 |
return nil, fmt.Errorf("%s does not support d_type. If the backing filesystem is xfs, please reformat with ftype=1 to enable d_type support", root) |
| 138 |
} |
| 139 |
ms, err := storage.NewMetaStore(filepath.Join(root, "metadata.db")) |
| 140 |
if err != nil { |
| 141 |
return nil, err |
| 142 |
} |
| 143 |
|
| 144 |
if err := os.Mkdir(filepath.Join(root, "snapshots"), 0700); err != nil && !os.IsExist(err) { |
| 145 |
return nil, err |
| 146 |
} |
| 147 |
|
| 148 |
userxattr, err := overlayutils.NeedsUserXAttr(root) |
| 149 |
if err != nil { |
| 150 |
logrus.WithError(err).Warnf("cannot detect whether \"userxattr\" option needs to be used, assuming to be %v", userxattr) |
| 151 |
} |
| 152 |
|
| 153 |
o := &snapshotter{ |
| 154 |
root: root, |
| 155 |
ms: ms, |
| 156 |
asyncRemove: config.asyncRemove, |
| 157 |
fs: targetFs, |
| 158 |
userxattr: userxattr, |
| 159 |
noRestore: config.noRestore, |
| 160 |
allowInvalidMountsOnRestart: config.allowInvalidMountsOnRestart, |
| 161 |
} |
| 162 |
|
| 163 |
if err := o.restoreRemoteSnapshot(ctx); err != nil { |
| 164 |
return nil, fmt.Errorf("failed to restore remote snapshot: %w", err) |
| 165 |
} |
| 166 |
|
| 167 |
return o, nil |
| 168 |
} |
| 169 |
|
| 170 |
// Stat returns the info for an active or committed snapshot by name or |
| 171 |
// key. |
| 172 |
// |
| 173 |
// Should be used for parent resolution, existence checks and to discern |
| 174 |
// the kind of snapshot. |
| 175 |
func (o *snapshotter) Stat(ctx context.Context, key string) (snapshots.Info, error) { |
| 176 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 177 |
if err != nil { |
| 178 |
return snapshots.Info{}, err |
| 179 |
} |
| 180 |
defer t.Rollback() |
| 181 |
_, info, _, err := storage.GetInfo(ctx, key) |
| 182 |
if err != nil { |
| 183 |
return snapshots.Info{}, err |
| 184 |
} |
| 185 |
|
| 186 |
return info, nil |
| 187 |
} |
| 188 |
|
| 189 |
func (o *snapshotter) Update(ctx context.Context, info snapshots.Info, fieldpaths ...string) (snapshots.Info, error) { |
| 190 |
ctx, t, err := o.ms.TransactionContext(ctx, true) |
| 191 |
if err != nil { |
| 192 |
return snapshots.Info{}, err |
| 193 |
} |
| 194 |
|
| 195 |
info, err = storage.UpdateInfo(ctx, info, fieldpaths...) |
| 196 |
if err != nil { |
| 197 |
t.Rollback() |
| 198 |
return snapshots.Info{}, err |
| 199 |
} |
| 200 |
|
| 201 |
if err := t.Commit(); err != nil { |
| 202 |
return snapshots.Info{}, err |
| 203 |
} |
| 204 |
|
| 205 |
return info, nil |
| 206 |
} |
| 207 |
|
| 208 |
// Usage returns the resources taken by the snapshot identified by key. |
| 209 |
// |
| 210 |
// For active snapshots, this will scan the usage of the overlay "diff" (aka |
| 211 |
// "upper") directory and may take some time. |
| 212 |
// for remote snapshots, no scan will be held and recognise the number of inodes |
| 213 |
// and these sizes as "zero". |
| 214 |
// |
| 215 |
// For committed snapshots, the value is returned from the metadata database. |
| 216 |
func (o *snapshotter) Usage(ctx context.Context, key string) (snapshots.Usage, error) { |
| 217 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 218 |
if err != nil { |
| 219 |
return snapshots.Usage{}, err |
| 220 |
} |
| 221 |
id, info, usage, err := storage.GetInfo(ctx, key) |
| 222 |
t.Rollback() // transaction no longer needed at this point. |
| 223 |
|
| 224 |
if err != nil { |
| 225 |
return snapshots.Usage{}, err |
| 226 |
} |
| 227 |
|
| 228 |
upperPath := o.upperPath(id) |
| 229 |
|
| 230 |
if info.Kind == snapshots.KindActive { |
| 231 |
du, err := fs.DiskUsage(ctx, upperPath) |
| 232 |
if err != nil { |
| 233 |
// TODO(stevvooe): Consider not reporting an error in this case. |
| 234 |
return snapshots.Usage{}, err |
| 235 |
} |
| 236 |
|
| 237 |
usage = snapshots.Usage(du) |
| 238 |
} |
| 239 |
|
| 240 |
return usage, nil |
| 241 |
} |
| 242 |
|
| 243 |
func (o *snapshotter) Prepare(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) { |
| 244 |
s, err := o.createSnapshot(ctx, snapshots.KindActive, key, parent, opts) |
| 245 |
if err != nil { |
| 246 |
return nil, err |
| 247 |
} |
| 248 |
|
| 249 |
// Try to prepare the remote snapshot. If succeeded, we commit the snapshot now |
| 250 |
// and return ErrAlreadyExists. |
| 251 |
var base snapshots.Info |
| 252 |
for _, opt := range opts { |
| 253 |
if err := opt(&base); err != nil { |
| 254 |
return nil, err |
| 255 |
} |
| 256 |
} |
| 257 |
if target, ok := base.Labels[targetSnapshotLabel]; ok { |
| 258 |
// NOTE: If passed labels include a target of the remote snapshot, `Prepare` |
| 259 |
// must log whether this method succeeded to prepare that remote snapshot |
| 260 |
// or not, using the key `remoteSnapshotLogKey` defined in the above. This |
| 261 |
// log is used by tests in this project. |
| 262 |
lCtx := log.WithLogger(ctx, log.G(ctx).WithField("key", key).WithField("parent", parent)) |
| 263 |
if err := o.prepareRemoteSnapshot(lCtx, key, base.Labels); err != nil { |
| 264 |
log.G(lCtx).WithField(remoteSnapshotLogKey, prepareFailed). |
| 265 |
WithError(err).Warn("failed to prepare remote snapshot") |
| 266 |
} else { |
| 267 |
base.Labels[remoteLabel] = remoteLabelVal // Mark this snapshot as remote |
| 268 |
err := o.commit(ctx, true, target, key, append(opts, snapshots.WithLabels(base.Labels))...) |
| 269 |
if err == nil || errdefs.IsAlreadyExists(err) { |
| 270 |
// count also AlreadyExists as "success" |
| 271 |
log.G(lCtx).WithField(remoteSnapshotLogKey, prepareSucceeded).Debug("prepared remote snapshot") |
| 272 |
return nil, fmt.Errorf("target snapshot %q: %w", target, errdefs.ErrAlreadyExists) |
| 273 |
} |
| 274 |
log.G(lCtx).WithField(remoteSnapshotLogKey, prepareFailed). |
| 275 |
WithError(err).Warn("failed to internally commit remote snapshot") |
| 276 |
// Don't fallback here (= prohibit to use this key again) because the FileSystem |
| 277 |
// possible has done some work on this "upper" directory. |
| 278 |
return nil, err |
| 279 |
} |
| 280 |
} |
| 281 |
return o.mounts(ctx, s, parent) |
| 282 |
} |
| 283 |
|
| 284 |
func (o *snapshotter) View(ctx context.Context, key, parent string, opts ...snapshots.Opt) ([]mount.Mount, error) { |
| 285 |
s, err := o.createSnapshot(ctx, snapshots.KindView, key, parent, opts) |
| 286 |
if err != nil { |
| 287 |
return nil, err |
| 288 |
} |
| 289 |
return o.mounts(ctx, s, parent) |
| 290 |
} |
| 291 |
|
| 292 |
// Mounts returns the mounts for the transaction identified by key. Can be |
| 293 |
// called on an read-write or readonly transaction. |
| 294 |
// |
| 295 |
// This can be used to recover mounts after calling View or Prepare. |
| 296 |
func (o *snapshotter) Mounts(ctx context.Context, key string) ([]mount.Mount, error) { |
| 297 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 298 |
if err != nil { |
| 299 |
return nil, err |
| 300 |
} |
| 301 |
s, err := storage.GetSnapshot(ctx, key) |
| 302 |
t.Rollback() |
| 303 |
if err != nil { |
| 304 |
return nil, fmt.Errorf("failed to get active mount: %w", err) |
| 305 |
} |
| 306 |
return o.mounts(ctx, s, key) |
| 307 |
} |
| 308 |
|
| 309 |
func (o *snapshotter) Commit(ctx context.Context, name, key string, opts ...snapshots.Opt) error { |
| 310 |
return o.commit(ctx, false, name, key, opts...) |
| 311 |
} |
| 312 |
|
| 313 |
func (o *snapshotter) commit(ctx context.Context, isRemote bool, name, key string, opts ...snapshots.Opt) error { |
| 314 |
ctx, t, err := o.ms.TransactionContext(ctx, true) |
| 315 |
if err != nil { |
| 316 |
return err |
| 317 |
} |
| 318 |
|
| 319 |
defer func() { |
| 320 |
if err != nil { |
| 321 |
if rerr := t.Rollback(); rerr != nil { |
| 322 |
log.G(ctx).WithError(rerr).Warn("failed to rollback transaction") |
| 323 |
} |
| 324 |
} |
| 325 |
}() |
| 326 |
|
| 327 |
// grab the existing id |
| 328 |
id, _, usage, err := storage.GetInfo(ctx, key) |
| 329 |
if err != nil { |
| 330 |
return err |
| 331 |
} |
| 332 |
|
| 333 |
if !isRemote { // skip diskusage for remote snapshots for allowing lazy preparation of nodes |
| 334 |
du, err := fs.DiskUsage(ctx, o.upperPath(id)) |
| 335 |
if err != nil { |
| 336 |
return err |
| 337 |
} |
| 338 |
usage = snapshots.Usage(du) |
| 339 |
} |
| 340 |
|
| 341 |
if _, err = storage.CommitActive(ctx, key, name, usage, opts...); err != nil { |
| 342 |
return fmt.Errorf("failed to commit snapshot: %w", err) |
| 343 |
} |
| 344 |
|
| 345 |
return t.Commit() |
| 346 |
} |
| 347 |
|
| 348 |
// Remove abandons the snapshot identified by key. The snapshot will |
| 349 |
// immediately become unavailable and unrecoverable. Disk space will |
| 350 |
// be freed up on the next call to `Cleanup`. |
| 351 |
func (o *snapshotter) Remove(ctx context.Context, key string) (err error) { |
| 352 |
ctx, t, err := o.ms.TransactionContext(ctx, true) |
| 353 |
if err != nil { |
| 354 |
return err |
| 355 |
} |
| 356 |
defer func() { |
| 357 |
if err != nil { |
| 358 |
if rerr := t.Rollback(); rerr != nil { |
| 359 |
log.G(ctx).WithError(rerr).Warn("failed to rollback transaction") |
| 360 |
} |
| 361 |
} |
| 362 |
}() |
| 363 |
|
| 364 |
_, _, err = storage.Remove(ctx, key) |
| 365 |
if err != nil { |
| 366 |
return fmt.Errorf("failed to remove: %w", err) |
| 367 |
} |
| 368 |
|
| 369 |
if !o.asyncRemove { |
| 370 |
var removals []string |
| 371 |
const cleanupCommitted = false |
| 372 |
removals, err = o.getCleanupDirectories(ctx, t, cleanupCommitted) |
| 373 |
if err != nil { |
| 374 |
return fmt.Errorf("unable to get directories for removal: %w", err) |
| 375 |
} |
| 376 |
|
| 377 |
// Remove directories after the transaction is closed, failures must not |
| 378 |
// return error since the transaction is committed with the removal |
| 379 |
// key no longer available. |
| 380 |
defer func() { |
| 381 |
if err == nil { |
| 382 |
for _, dir := range removals { |
| 383 |
if err := o.cleanupSnapshotDirectory(ctx, dir); err != nil { |
| 384 |
log.G(ctx).WithError(err).WithField("path", dir).Warn("failed to remove directory") |
| 385 |
} |
| 386 |
} |
| 387 |
} |
| 388 |
}() |
| 389 |
|
| 390 |
} |
| 391 |
|
| 392 |
return t.Commit() |
| 393 |
} |
| 394 |
|
| 395 |
// Walk the snapshots. |
| 396 |
func (o *snapshotter) Walk(ctx context.Context, fn snapshots.WalkFunc, fs ...string) error { |
| 397 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 398 |
if err != nil { |
| 399 |
return err |
| 400 |
} |
| 401 |
defer t.Rollback() |
| 402 |
return storage.WalkInfo(ctx, fn, fs...) |
| 403 |
} |
| 404 |
|
| 405 |
// Cleanup cleans up disk resources from removed or abandoned snapshots |
| 406 |
func (o *snapshotter) Cleanup(ctx context.Context) error { |
| 407 |
const cleanupCommitted = false |
| 408 |
return o.cleanup(ctx, cleanupCommitted) |
| 409 |
} |
| 410 |
|
| 411 |
func (o *snapshotter) cleanup(ctx context.Context, cleanupCommitted bool) error { |
| 412 |
cleanup, err := o.cleanupDirectories(ctx, cleanupCommitted) |
| 413 |
if err != nil { |
| 414 |
return err |
| 415 |
} |
| 416 |
|
| 417 |
log.G(ctx).Debugf("cleanup: dirs=%v", cleanup) |
| 418 |
for _, dir := range cleanup { |
| 419 |
if err := o.cleanupSnapshotDirectory(ctx, dir); err != nil { |
| 420 |
log.G(ctx).WithError(err).WithField("path", dir).Warn("failed to remove directory") |
| 421 |
} |
| 422 |
} |
| 423 |
|
| 424 |
return nil |
| 425 |
} |
| 426 |
|
| 427 |
func (o *snapshotter) cleanupDirectories(ctx context.Context, cleanupCommitted bool) ([]string, error) { |
| 428 |
// Get a write transaction to ensure no other write transaction can be entered |
| 429 |
// while the cleanup is scanning. |
| 430 |
ctx, t, err := o.ms.TransactionContext(ctx, true) |
| 431 |
if err != nil { |
| 432 |
return nil, err |
| 433 |
} |
| 434 |
|
| 435 |
defer t.Rollback() |
| 436 |
return o.getCleanupDirectories(ctx, t, cleanupCommitted) |
| 437 |
} |
| 438 |
|
| 439 |
func (o *snapshotter) getCleanupDirectories(ctx context.Context, t storage.Transactor, cleanupCommitted bool) ([]string, error) { |
| 440 |
ids, err := storage.IDMap(ctx) |
| 441 |
if err != nil { |
| 442 |
return nil, err |
| 443 |
} |
| 444 |
|
| 445 |
snapshotDir := filepath.Join(o.root, "snapshots") |
| 446 |
fd, err := os.Open(snapshotDir) |
| 447 |
if err != nil { |
| 448 |
return nil, err |
| 449 |
} |
| 450 |
defer fd.Close() |
| 451 |
|
| 452 |
dirs, err := fd.Readdirnames(0) |
| 453 |
if err != nil { |
| 454 |
return nil, err |
| 455 |
} |
| 456 |
|
| 457 |
cleanup := []string{} |
| 458 |
for _, d := range dirs { |
| 459 |
if !cleanupCommitted { |
| 460 |
if _, ok := ids[d]; ok { |
| 461 |
continue |
| 462 |
} |
| 463 |
} |
| 464 |
|
| 465 |
cleanup = append(cleanup, filepath.Join(snapshotDir, d)) |
| 466 |
} |
| 467 |
|
| 468 |
return cleanup, nil |
| 469 |
} |
| 470 |
|
| 471 |
func (o *snapshotter) cleanupSnapshotDirectory(ctx context.Context, dir string) error { |
| 472 |
|
| 473 |
// On a remote snapshot, the layer is mounted on the "fs" directory. |
| 474 |
// We use Filesystem's Unmount API so that it can do necessary finalization |
| 475 |
// before/after the unmount. |
| 476 |
mp := filepath.Join(dir, "fs") |
| 477 |
if err := o.fs.Unmount(ctx, mp); err != nil { |
| 478 |
log.G(ctx).WithError(err).WithField("dir", mp).Debug("failed to unmount") |
| 479 |
} |
| 480 |
if err := os.RemoveAll(dir); err != nil { |
| 481 |
return fmt.Errorf("failed to remove directory %q: %w", dir, err) |
| 482 |
} |
| 483 |
return nil |
| 484 |
} |
| 485 |
|
| 486 |
func (o *snapshotter) createSnapshot(ctx context.Context, kind snapshots.Kind, key, parent string, opts []snapshots.Opt) (_ storage.Snapshot, err error) { |
| 487 |
ctx, t, err := o.ms.TransactionContext(ctx, true) |
| 488 |
if err != nil { |
| 489 |
return storage.Snapshot{}, err |
| 490 |
} |
| 491 |
|
| 492 |
var td, path string |
| 493 |
defer func() { |
| 494 |
if err != nil { |
| 495 |
if td != "" { |
| 496 |
if err1 := o.cleanupSnapshotDirectory(ctx, td); err1 != nil { |
| 497 |
log.G(ctx).WithError(err1).Warn("failed to cleanup temp snapshot directory") |
| 498 |
} |
| 499 |
} |
| 500 |
if path != "" { |
| 501 |
if err1 := o.cleanupSnapshotDirectory(ctx, path); err1 != nil { |
| 502 |
log.G(ctx).WithError(err1).WithField("path", path).Error("failed to reclaim snapshot directory, directory may need removal") |
| 503 |
err = fmt.Errorf("failed to remove path: %v: %w", err1, err) |
| 504 |
} |
| 505 |
} |
| 506 |
} |
| 507 |
}() |
| 508 |
|
| 509 |
snapshotDir := filepath.Join(o.root, "snapshots") |
| 510 |
td, err = o.prepareDirectory(ctx, snapshotDir, kind) |
| 511 |
if err != nil { |
| 512 |
if rerr := t.Rollback(); rerr != nil { |
| 513 |
log.G(ctx).WithError(rerr).Warn("failed to rollback transaction") |
| 514 |
} |
| 515 |
return storage.Snapshot{}, fmt.Errorf("failed to create prepare snapshot dir: %w", err) |
| 516 |
} |
| 517 |
rollback := true |
| 518 |
defer func() { |
| 519 |
if rollback { |
| 520 |
if rerr := t.Rollback(); rerr != nil { |
| 521 |
log.G(ctx).WithError(rerr).Warn("failed to rollback transaction") |
| 522 |
} |
| 523 |
} |
| 524 |
}() |
| 525 |
|
| 526 |
s, err := storage.CreateSnapshot(ctx, kind, key, parent, opts...) |
| 527 |
if err != nil { |
| 528 |
return storage.Snapshot{}, fmt.Errorf("failed to create snapshot: %w", err) |
| 529 |
} |
| 530 |
|
| 531 |
if len(s.ParentIDs) > 0 { |
| 532 |
st, err := os.Stat(o.upperPath(s.ParentIDs[0])) |
| 533 |
if err != nil { |
| 534 |
return storage.Snapshot{}, fmt.Errorf("failed to stat parent: %w", err) |
| 535 |
} |
| 536 |
|
| 537 |
stat := st.Sys().(*syscall.Stat_t) |
| 538 |
|
| 539 |
if err := os.Lchown(filepath.Join(td, "fs"), int(stat.Uid), int(stat.Gid)); err != nil { |
| 540 |
if rerr := t.Rollback(); rerr != nil { |
| 541 |
log.G(ctx).WithError(rerr).Warn("failed to rollback transaction") |
| 542 |
} |
| 543 |
return storage.Snapshot{}, fmt.Errorf("failed to chown: %w", err) |
| 544 |
} |
| 545 |
} |
| 546 |
|
| 547 |
path = filepath.Join(snapshotDir, s.ID) |
| 548 |
if err = os.Rename(td, path); err != nil { |
| 549 |
return storage.Snapshot{}, fmt.Errorf("failed to rename: %w", err) |
| 550 |
} |
| 551 |
td = "" |
| 552 |
|
| 553 |
rollback = false |
| 554 |
if err = t.Commit(); err != nil { |
| 555 |
return storage.Snapshot{}, fmt.Errorf("commit failed: %w", err) |
| 556 |
} |
| 557 |
|
| 558 |
return s, nil |
| 559 |
} |
| 560 |
|
| 561 |
func (o *snapshotter) prepareDirectory(ctx context.Context, snapshotDir string, kind snapshots.Kind) (string, error) { |
| 562 |
td, err := os.MkdirTemp(snapshotDir, "new-") |
| 563 |
if err != nil { |
| 564 |
return "", fmt.Errorf("failed to create temp dir: %w", err) |
| 565 |
} |
| 566 |
|
| 567 |
if err := os.Mkdir(filepath.Join(td, "fs"), 0755); err != nil { |
| 568 |
return td, err |
| 569 |
} |
| 570 |
|
| 571 |
if kind == snapshots.KindActive { |
| 572 |
if err := os.Mkdir(filepath.Join(td, "work"), 0711); err != nil { |
| 573 |
return td, err |
| 574 |
} |
| 575 |
} |
| 576 |
|
| 577 |
return td, nil |
| 578 |
} |
| 579 |
|
| 580 |
func (o *snapshotter) mounts(ctx context.Context, s storage.Snapshot, checkKey string) ([]mount.Mount, error) { |
| 581 |
// Make sure that all layers lower than the target layer are available |
| 582 |
if checkKey != "" && !o.checkAvailability(ctx, checkKey) { |
| 583 |
return nil, fmt.Errorf("layer %q unavailable: %w", s.ID, errdefs.ErrUnavailable) |
| 584 |
} |
| 585 |
|
| 586 |
if len(s.ParentIDs) == 0 { |
| 587 |
// if we only have one layer/no parents then just return a bind mount as overlay |
| 588 |
// will not work |
| 589 |
roFlag := "rw" |
| 590 |
if s.Kind == snapshots.KindView { |
| 591 |
roFlag = "ro" |
| 592 |
} |
| 593 |
|
| 594 |
return []mount.Mount{ |
| 595 |
{ |
| 596 |
Source: o.upperPath(s.ID), |
| 597 |
Type: "bind", |
| 598 |
Options: []string{ |
| 599 |
roFlag, |
| 600 |
"rbind", |
| 601 |
}, |
| 602 |
}, |
| 603 |
}, nil |
| 604 |
} |
| 605 |
var options []string |
| 606 |
|
| 607 |
if s.Kind == snapshots.KindActive { |
| 608 |
options = append(options, |
| 609 |
fmt.Sprintf("workdir=%s", o.workPath(s.ID)), |
| 610 |
fmt.Sprintf("upperdir=%s", o.upperPath(s.ID)), |
| 611 |
) |
| 612 |
} else if len(s.ParentIDs) == 1 { |
| 613 |
return []mount.Mount{ |
| 614 |
{ |
| 615 |
Source: o.upperPath(s.ParentIDs[0]), |
| 616 |
Type: "bind", |
| 617 |
Options: []string{ |
| 618 |
"ro", |
| 619 |
"rbind", |
| 620 |
}, |
| 621 |
}, |
| 622 |
}, nil |
| 623 |
} |
| 624 |
|
| 625 |
parentPaths := make([]string, len(s.ParentIDs)) |
| 626 |
for i := range s.ParentIDs { |
| 627 |
parentPaths[i] = o.upperPath(s.ParentIDs[i]) |
| 628 |
} |
| 629 |
|
| 630 |
options = append(options, fmt.Sprintf("lowerdir=%s", strings.Join(parentPaths, ":"))) |
| 631 |
if o.userxattr { |
| 632 |
options = append(options, "userxattr") |
| 633 |
} |
| 634 |
return []mount.Mount{ |
| 635 |
{ |
| 636 |
Type: "overlay", |
| 637 |
Source: "overlay", |
| 638 |
Options: options, |
| 639 |
}, |
| 640 |
}, nil |
| 641 |
|
| 642 |
} |
| 643 |
|
| 644 |
func (o *snapshotter) upperPath(id string) string { |
| 645 |
return filepath.Join(o.root, "snapshots", id, "fs") |
| 646 |
} |
| 647 |
|
| 648 |
func (o *snapshotter) workPath(id string) string { |
| 649 |
return filepath.Join(o.root, "snapshots", id, "work") |
| 650 |
} |
| 651 |
|
| 652 |
// Close closes the snapshotter |
| 653 |
func (o *snapshotter) Close() error { |
| 654 |
// unmount all mounts including Committed |
| 655 |
const cleanupCommitted = true |
| 656 |
ctx := context.Background() |
| 657 |
if err := o.cleanup(ctx, cleanupCommitted); err != nil { |
| 658 |
log.G(ctx).WithError(err).Warn("failed to cleanup") |
| 659 |
} |
| 660 |
return o.ms.Close() |
| 661 |
} |
| 662 |
|
| 663 |
// prepareRemoteSnapshot tries to prepare the snapshot as a remote snapshot |
| 664 |
// using filesystems registered in this snapshotter. |
| 665 |
func (o *snapshotter) prepareRemoteSnapshot(ctx context.Context, key string, labels map[string]string) error { |
| 666 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 667 |
if err != nil { |
| 668 |
return err |
| 669 |
} |
| 670 |
defer t.Rollback() |
| 671 |
id, _, _, err := storage.GetInfo(ctx, key) |
| 672 |
if err != nil { |
| 673 |
return err |
| 674 |
} |
| 675 |
|
| 676 |
mountpoint := o.upperPath(id) |
| 677 |
log.G(ctx).Infof("preparing filesystem mount at mountpoint=%v", mountpoint) |
| 678 |
|
| 679 |
return o.fs.Mount(ctx, mountpoint, labels) |
| 680 |
} |
| 681 |
|
| 682 |
// checkAvailability checks avaiability of the specified layer and all lower |
| 683 |
// layers using filesystem's checking functionality. |
| 684 |
func (o *snapshotter) checkAvailability(ctx context.Context, key string) bool { |
| 685 |
ctx = log.WithLogger(ctx, log.G(ctx).WithField("key", key)) |
| 686 |
log.G(ctx).Debug("checking layer availability") |
| 687 |
|
| 688 |
ctx, t, err := o.ms.TransactionContext(ctx, false) |
| 689 |
if err != nil { |
| 690 |
log.G(ctx).WithError(err).Warn("failed to get transaction") |
| 691 |
return false |
| 692 |
} |
| 693 |
defer t.Rollback() |
| 694 |
|
| 695 |
eg, egCtx := errgroup.WithContext(ctx) |
| 696 |
for cKey := key; cKey != ""; { |
| 697 |
id, info, _, err := storage.GetInfo(ctx, cKey) |
| 698 |
if err != nil { |
| 699 |
log.G(ctx).WithError(err).Warnf("failed to get info of %q", cKey) |
| 700 |
return false |
| 701 |
} |
| 702 |
mp := o.upperPath(id) |
| 703 |
lCtx := log.WithLogger(ctx, log.G(ctx).WithField("mount-point", mp)) |
| 704 |
if _, ok := info.Labels[remoteLabel]; ok { |
| 705 |
eg.Go(func() error { |
| 706 |
log.G(lCtx).Debug("checking mount point") |
| 707 |
if err := o.fs.Check(egCtx, mp, info.Labels); err != nil { |
| 708 |
log.G(lCtx).WithError(err).Warn("layer is unavailable") |
| 709 |
return err |
| 710 |
} |
| 711 |
return nil |
| 712 |
}) |
| 713 |
} else { |
| 714 |
log.G(lCtx).Debug("layer is normal snapshot(overlayfs)") |
| 715 |
} |
| 716 |
cKey = info.Parent |
| 717 |
} |
| 718 |
if err := eg.Wait(); err != nil { |
| 719 |
return false |
| 720 |
} |
| 721 |
return true |
| 722 |
} |
| 723 |
|
| 724 |
func (o *snapshotter) restoreRemoteSnapshot(ctx context.Context) error { |
| 725 |
mounts, err := mountinfo.GetMounts(nil) |
| 726 |
if err != nil { |
| 727 |
return err |
| 728 |
} |
| 729 |
for _, m := range mounts { |
| 730 |
if strings.HasPrefix(m.Mountpoint, filepath.Join(o.root, "snapshots")) { |
| 731 |
if err := syscall.Unmount(m.Mountpoint, syscall.MNT_FORCE); err != nil { |
| 732 |
return fmt.Errorf("failed to unmount %s: %w", m.Mountpoint, err) |
| 733 |
} |
| 734 |
} |
| 735 |
} |
| 736 |
|
| 737 |
if o.noRestore { |
| 738 |
return nil |
| 739 |
} |
| 740 |
|
| 741 |
var task []snapshots.Info |
| 742 |
if err := o.Walk(ctx, func(ctx context.Context, info snapshots.Info) error { |
| 743 |
if _, ok := info.Labels[remoteLabel]; ok { |
| 744 |
task = append(task, info) |
| 745 |
} |
| 746 |
return nil |
| 747 |
}); err != nil && !errdefs.IsNotFound(err) { |
| 748 |
return err |
| 749 |
} |
| 750 |
for _, info := range task { |
| 751 |
if err := o.prepareRemoteSnapshot(ctx, info.Name, info.Labels); err != nil { |
| 752 |
if o.allowInvalidMountsOnRestart { |
| 753 |
logrus.WithError(err).Warnf("failed to restore remote snapshot %s; remove this snapshot manually", info.Name) |
| 754 |
// This snapshot mount is invalid but allow this. |
| 755 |
// NOTE: snapshotter.Mount() will fail to return the mountpoint of these invalid snapshots so |
| 756 |
// containerd cannot use them anymore. User needs to manually remove the snapshots from |
| 757 |
// containerd's metadata store using ctr (e.g. `ctr snapshot rm`). |
| 758 |
continue |
| 759 |
} |
| 760 |
return fmt.Errorf("failed to prepare remote snapshot: %s: %w", info.Name, err) |
| 761 |
} |
| 762 |
} |
| 763 |
|
| 764 |
return nil |
| 765 |
} |