Compare commits

...

1093 Commits

Author SHA1 Message Date
imeoer d7924384ac
Merge pull request #644 from DataDog/fricounet/referrer-detect-shared-layer
[mountRemote] include intermediate snapshots in mount slice during referrer detection
2025-06-13 16:45:27 +08:00
Baptiste Girard-Carrabin d9a8e57451
[mountRemote] include intermediate snapshots in mount slice in referrer detection
This fixes #640.
When the nydus-snapshotter returns the final mount slice for an image that is not nydus but shares layers with an images that is nydus, it currently doesn't include all the layers between the topmost and the nydus layer which causes missing files in the final running container. This commit attempts to fix the issue by adding all the missing layers to the final mount slice.
2025-06-13 10:37:51 +02:00
imeoer 00c3cbe005
Merge pull request #639 from DataDog/fricounet/converter-push-ecr
Fix converter to be able to push manifests to ECR
2025-05-26 10:03:32 +08:00
Baptiste Girard-Carrabin 6542a8949d
[converter] Remove useless logic from convertIndex
This code is useless now since we return the first manifest in the index directly without updating the index itself
2025-05-23 09:44:56 +02:00
Baptiste Girard-Carrabin 5f82310ee5
[converter] Remove `nydus.remoteimage.v1` OS feature from index manifest
This field is causing issues when attempting to push multi-arch images to ECR because the feature field is not supported in index manifests. According to https://github.com/dragonflyoss/nydus/issues/1692, the goal of this feature is to help the container runtime pick the nydus image in an index manifest if there are multiple entries for the same architecture. However, as this is a feature that is not supported in any container runtime yet and the only way to get a manifest with both architecture is to use `nydusify convert --merge-platform`, which uses harbor acceleration-service to add the feature in the manifest, this means that we can remove it from the converter.
2025-05-21 18:25:34 +02:00
Baptiste Girard-Carrabin 2e932b5b9c
[converter] Remove platform in subject when using WithReferrer
This field is not supported by certain registries like ECR and is not really needed according to https://github.com/dragonflyoss/nydus/issues/1691.
2025-05-21 18:11:27 +02:00
imeoer 88a72d945c
Merge pull request #636 from Apokleos/fix-bug-01
nydus sn: fix issues with "not found" in CoCo cases.
2025-04-09 18:22:34 +08:00
alex.lyn 314951f620 nydus sn: fix issues with "not found" in CoCo cases.
To make nydus-snapshotter work well in CoCo:

(1) Just go pass when do AddRafsInstance failed.
(2) When sn can't get label.CRIImageRef, just assign it with
overlayfs.

Signed-off-by: alex.lyn <alex.lyn@antgroup.com>
2025-04-09 10:18:22 +08:00
imeoer 9089ad11ad
Merge pull request #630 from gane5hvarma/bug.fixVrNameInCleanup
echo image instead of images
2025-01-26 10:00:09 +08:00
imeoer 9983eb470c
Merge pull request #627 from gane5hvarma/chore.AddVendorInGitignore
chore: Add vendor directory in .gitignore file
2025-01-26 09:59:42 +08:00
Ganesh varma Raghava raju e3fe566b3e echo image instead of images 2025-01-24 12:08:08 +05:30
imeoer 456c3fcad9
Merge pull request #629 from thaJeztah/vendor_containerd_2.0.2
go.mod: update github.com/containerd/containerd v2.0.2
2025-01-16 20:52:06 +08:00
Sebastiaan van Stijn 7ca785d176
go.mod: update github.com/containerd/containerd v2.0.2
Also downgrade github.com/davecgh/go-spew and
github.com/pmezard/go-difflib back to tagged releases.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2025-01-14 20:12:14 +01:00
Ganesh varma Raghava raju b4e07f5558 add vendor directory in .gitignore file 2025-01-03 12:21:42 +05:30
imeoer fbf6bb5573
Merge pull request #626 from gaius-qi/feature/rename-dragonfly
docs: rename repo Dragonfly2 to dragonfly
2024-12-20 17:23:06 +08:00
Gaius 5aee43c99d
docs: rename repo Dragonfly2 to dragonfly
Signed-off-by: Gaius <gaius.qi@gmail.com>
2024-12-20 17:12:32 +08:00
imeoer aec799e1b5
Merge pull request #625 from imeoer/revert-config
Revert "feat: Remove DumpFile operations"
2024-12-11 10:14:18 +08:00
Yan Song 9ec5a73739 misc: bump nydusd v2.3.0
Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-12-10 01:59:09 +00:00
Yan Song 38dc1f5f5b misc: stablize the kubectl version
Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-12-10 01:55:54 +00:00
Yan Song 1bdecad6f4 Revert "feat: Remove DumpFile operations"
This reverts commit 29243e35cc.

For the design of non-persistent configuration, we need to consider more factors
and cannot simply place the configuration files in the local metadata database.
2024-12-10 01:52:54 +00:00
imeoer 021c50521a
Merge pull request #622 from coder-y04/deal_zombie_processes
Dealing with optimizer-server zombie processes
2024-12-04 11:36:08 +08:00
imeoer 5f948e4498
Merge pull request #623 from dmcgowan/containerd-2.0.0
Update containerd to v2.0.0
2024-11-15 14:49:24 +08:00
Derek McGowan fcfc371bba Update containerd to v2.0.0
Signed-off-by: Derek McGowan <derek@mcg.dev>
2024-11-14 16:05:41 -08:00
coder-y04 917375e9b7 Change the print content 2024-11-14 15:55:11 +08:00
coder-y04 ebbf5d122e Dealing with optimizer-server zombie processes 2024-11-14 15:27:40 +08:00
imeoer e55ae70fd4
Merge pull request #616 from fappy1234567/no-disk-write
Remove DumpFile operations
2024-10-16 09:29:21 +08:00
fappy1234567 29243e35cc feat: Remove DumpFile operations 2024-10-15 21:40:23 +08:00
imeoer 306d2dd3bf
Merge pull request #614 from SToPire/unpack-test
tests/converter: modify unpack testcase
2024-10-15 10:55:48 +08:00
Yifan Zhao 6964102e8c tests/converter: fix invalid use of user.Username
The Go package `user` has a `Current` method that returns the current
user. We should use `user.Current().Username` instead of
`user.Current().Name` to get the current username. This patch fixes it.

Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
2024-10-15 10:18:13 +08:00
Yifan Zhao c5b8011f1a tests/converter: modify unpack testcase
This patch modifies the unpack testcase to keep consistent with the
new `nydus-image unpack` interface in nydus-image.

Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
2024-10-15 10:18:05 +08:00
imeoer 8ec7897d02
Merge pull request #620 from imeoer/test-bump-nydus-v2.3.0
upgrade nydus version to v2.3.0 in test
2024-10-15 09:42:30 +08:00
Yan Song d507ca6eba upgrade nydus version to v2.3.0 in test
Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-10-15 01:32:38 +00:00
imeoer e69bf9b9c3
Merge pull request #621 from Desiki-high/chunkmap-suffix
test: update chunkmap suffix
2024-10-14 20:56:03 +08:00
Yadong Ding aa65327218 test: update chunkmap suffix
Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-10-14 20:16:13 +08:00
imeoer d6ca59c83a
Merge pull request #619 from Desiki-high/chunkmap-suffix
fix: update chunkmap suffix
2024-10-11 11:54:22 +08:00
Yadong Ding 067f6b2e6d chore: update kubectl download source
ref: https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/
replace `https://storage.googleapis.com/kubernetes-release/release/` by `https://dl.k8s.io/release`.

Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-10-10 15:55:05 +08:00
Yadong Ding 36975a374e fix: update chunkmap suffix
Add blobChunkMapSuffixedPath to clear latest nydus chunmap: {blob_id}.blob.data.chunk_map

Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-10-10 15:54:45 +08:00
imeoer d42d55a33a
Merge pull request #615 from katexochen/nydus-overlayfs-path
snapshotter: add flag to specify nydus-overlayfs path
2024-09-09 09:32:22 +08:00
Paul Meyer 50a833f545 snapshotter: add flag to specify nydus-overlayfs path
This allows installation of multiple nydus-overlayfs versions on the same machine.

Signed-off-by: Paul Meyer <49727155+katexochen@users.noreply.github.com>
2024-09-05 08:01:13 +02:00
Changwei Ge 30f3d65e5a
Merge pull request #613 from imeoer/fix-supervisor
supervisor: fix large opaque data handle
2024-09-02 16:05:42 +08:00
Yan Song 4f4dbcd7ab supervisor: fix large opaque data handle
When the supervisor needs to process a large amount of opaque data (for example,
a nydusd instance has a large number of sub mounts, and the opaque is usually
larger than 32kb), a recvmsg / sendmsg system call cannot process all data.

The commit fixes the problem with multiple recvmsg/sendmsg calls and updates
the test cases.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-08-19 07:26:40 +00:00
imeoer 8fa319bfe9
Merge pull request #604 from apostasie/main
Update to containerd v2
2024-08-06 14:31:46 +08:00
apostasie e22e77df4b
Containerd v2
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-08-03 15:55:18 -07:00
imeoer 8e72f94dca
Merge pull request #611 from thaJeztah/remove_cri_alpha
pkg/auth: remove CRI Alpha API
2024-08-02 11:59:11 +08:00
Sebastiaan van Stijn f46b6316b2
pkg/auth: remove CRI Alpha API
CRI v1alpha2 is deprecated since containerd 1.7:
https://github.com/containerd/containerd/blob/v1.7.0/RELEASES.md#deprecated-features

Co-authored-by: apostasie <spam_blackhole@farcloser.world>
Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-01 10:12:38 +02:00
imeoer 15fe07131b
Merge pull request #610 from thaJeztah/containerd_1.7.20
go.mod: github.com/containerd/containerd v1.7.20, switch to github.com/containerd/platforms, github.com/distribution/reference module
2024-08-01 15:26:06 +08:00
Sebastiaan van Stijn 261dd69e5a
switch to github.com/distribution/reference module
containerd 1.7.19 and up alias the reference/docker package to the new module,
and deprecate the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-01 09:05:21 +02:00
Sebastiaan van Stijn 5447c5d615
switch to github.com/containerd/platforms module
containerd 1.7.19 and up alias the platforms package to the new module,
and deprecate the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-01 09:05:14 +02:00
Sebastiaan van Stijn b823d335e7
go.mod: github.com/containerd/containerd v1.7.20
- switches to separate github.com/containerd/containerd/api module
- switches to separate github.com/containerd/platforms module

full diff: https://github.com/containerd/containerd/compare/v1.7.18...v1.7.20

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-08-01 09:04:07 +02:00
imeoer 483b1af423
Merge pull request #608 from thaJeztah/migrate_mergo
go.mod: dario.cat/mergo v1.0.0
2024-08-01 14:42:34 +08:00
imeoer 08b8d7e836
Merge pull request #599 from thaJeztah/c8d_errdefs
go.mod: github.com/containerd/containerd v1.7.18, switch to github.com/containerd/errdefs module
2024-08-01 14:41:47 +08:00
Sebastiaan van Stijn d5701f06fa
go.mod: dario.cat/mergo v1.0.0
The module was renamed to dario.cat/mergo. The old dependency isn't fully
gone yet, because kubernetes still uses the old location, but that may go
away eventually; https://github.com/kubernetes/client-go/blob/v0.26.2/go.mod#L18

full diff: https://github.com/darccio/mergo/compare/v0.3.13...v1.0.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-31 14:07:28 +02:00
Sebastiaan van Stijn cd5233c84c
switch to github.com/containerd/errdefs module
containerd 1.7.18 and up alias the errdefs package to the new module,
and deprecate the package.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-31 10:35:24 +02:00
Sebastiaan van Stijn 60c19b35f3
go.mod: github.com/containerd/containerd v1.7.18
full diff: https://github.com/containerd/containerd/compare/v1.7.7...v1.7.18

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-07-31 10:35:21 +02:00
imeoer 331a09a727
Merge pull request #609 from ChengyuZhu6/snapshotter-clean
misc: remove related images/contents/snapshots in cleanup progress
2024-07-31 10:42:37 +08:00
ChengyuZhu6 27d320f56c misc: remove related images/contents/snapshots in cleanup progress
remove related images/contents/snapshots in cleanup progress.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-07-31 10:26:08 +08:00
imeoer 39737d9f4c
Merge pull request #607 from apostasie/dev-fix-kube
CI fix, part II: kube
2024-07-31 10:18:12 +08:00
imeoer 2735f536b7
Merge pull request #605 from ryansavino/cleanup-rm-bug
cleanup: regex not being evaluated in quoted expression
2024-07-31 10:09:40 +08:00
apostasie 1535ce67d6
Fix kube test bustage
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-30 18:34:31 -07:00
imeoer 1fc2063ed6
Merge pull request #606 from apostasie/dev-ci
CI fix, part I: update and cleanup
2024-07-31 09:27:37 +08:00
Ryan Savino 7faa12cd63 formatting: replaced lingering tabs with spaces
Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2024-07-27 02:18:09 -05:00
Ryan Savino 7708a79218 cleanup: return true on the ps so script doesn't exit on failure
When no containerd-nydus-grpc pid is found, script will exit on this line.

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2024-07-27 02:14:58 -05:00
Ryan Savino f71498da3c cleanup: regex not being evaluated in quoted expression
Cleanup never happening for these directories.
Regex needed to be passed outside of quotes.
Quoted variable references only.

Signed-Off-By: Ryan Savino <ryan.savino@amd.com>
2024-07-27 02:14:57 -05:00
apostasie 8d8079cc60
Pin ubuntu versions, move to 22.04 and bookworm
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-25 14:16:13 -07:00
apostasie 473eff8926
Increase timeout after kill to fix racy metrics port conflict
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:38:45 -07:00
apostasie 2e55d2614e
Remove no longer useful DOCKER_BUILDKIT and GO11MODULE variables
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:35:47 -07:00
apostasie 3942dfdebb
git mark /nydus-snapshotter as trusted to avoid ownership error in container
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:34:06 -07:00
apostasie 4154d2cae9
Update golang to 1.21
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:29:25 -07:00
apostasie 305fd3f2c0
Update github actions
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:26:14 -07:00
apostasie c6f631cbf4
Quiet apk
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:09:55 -07:00
apostasie 962eecc7ea
Use fsSL for curl consistently
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:09:00 -07:00
apostasie 8a872ae58e
Quiet apt-get
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:05:04 -07:00
apostasie 15c12ace6f
Quiet wget
Signed-off-by: apostasie <spam_blackhole@farcloser.world>
2024-07-23 16:03:58 -07:00
imeoer 239009aa48
Merge pull request #603 from fappy1234567/rootDir
fix: error in Kubelet when using default root directory
2024-07-17 15:20:26 +08:00
fappy123 462ba12a20 update tests/e2e/k8s 2024-07-15 12:28:50 +08:00
fappy123 aa95d0eca6 update Readme.md 2024-07-15 09:54:15 +08:00
fappy123 b769ec7336 Update path /var/lib/containerd-nydus across some files 2024-07-12 10:56:59 +08:00
fappy123 367d4f22f8 Update path /var/lib/containerd-nydus across all files 2024-07-12 10:38:31 +08:00
imeoer f24f0d9b03
Merge pull request #600 from SToPire/remove-chmod
misc: merge chmod into copy in Dockerfile
2024-07-11 14:28:08 +08:00
fappy123 ca3a808d0e modify DefaultRootDir 2024-07-10 21:43:42 +08:00
Yifan Zhao f646a17568 misc: merge chmod into copy in Dockerfile
Let's use Docker's `COPY --chmod` feature instead of using a separate
chmod command. This will reduce the generated image size by ~12KB.

Fixes: #402

Signed-off-by: Yifan Zhao <zhaoyifan@sjtu.edu.cn>
2024-07-10 01:20:18 +08:00
imeoer 831f849aa8
Merge pull request #601 from daiyongxuan/main
docs: fix incorrect file path for nginx result file
2024-07-05 11:20:21 +08:00
daiyongxuan 1182518a45 docs: fix incorrect file path for nginx image
The documentation incorrectly stated that the result file for the nginx image is located at `/opt/nri/optimizer/results/nginx:latest`. However, the correct file path is `/opt/nri/optimizer/results/library/nginx:latest`.
2024-07-04 12:43:02 +00:00
imeoer 71ab64ad42
Merge pull request #598 from thaJeztah/switch_to_containerd_log
go.mod: github.com/containerd/containerd v1.7.7, containerd/nri v0.4.0, switch to github.com/containerd/log module
2024-06-26 14:32:08 +08:00
Sebastiaan van Stijn 1eee7eb462
switch to github.com/containerd/log module
containerd 1.7.7 and up alias the log package to the new module,
and deprecate the package.

This patch:

- replaces existing uses of the log package to use the module
- replaces some direct uses of logrus to use the log module
- enables the depguard linter to prevent accidental use of
  the deprecated packages.

There is one change in behavior in the nri-plugins, which now
use the default format as used by the containerd log module.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-22 00:33:30 +02:00
Sebastiaan van Stijn 04cf1d746a
go.mod: github.com/containerd/containerd v1.7.7, containerd/nri v0.4.0
Update to the first release of containerd to alias the log package to
the new containerd/log module.

This update of the containerd module also comes with an updated version
of github.com/containerd/nr, which has some breaking changes in the
interface definitions.

the optimizer-nri-plugin and prefetchfilees-nri-pugin pacakges had to be
updated due to [containerd/nri@9d86150] changing the interface to require
a context to be passed.

[containerd/nri@9d86150]: 9d86150fce

Full diffs:

- https://github.com/containerd/containerd/v1.7.0...v1.7.7
- https://github.com/containerd/nri/compare/v0.3.0...v0.4.0

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2024-06-22 00:25:09 +02:00
imeoer e9d1bb738f
Merge pull request #593 from ChengyuZhu6/fix-error
snapshot: fix error on proxy driver when switching different snapshotter
2024-05-15 10:27:10 +08:00
ChengyuZhu6 8b98d6a46e snapshot: fix error on proxy driver when switching different snapshotter
During image pull, the containerd client calls Prepare API with the label containerd.io/snapshot.ref.
When an image is pulled by other snapshotter, containerd doesn't send the label "containerd.io/snapshot.ref" to
nydus snapshotter to let snapshotter prepare ro layers.
Consequently, the code logic in nydus snapshotter cannot find label "containerd.io/snapshot/nydus-proxy-mode"
and the logic of guest pull (proxy) is skipped.
This occurs while reading the label data of parent snapshots(ro layers) during the preparation of the active snapshot(rw layer).
Thus, when the snapshotter driver is configured to proxy mode, nydus snapshotter is compelled to implement the proxy logic.

Fixes: #592

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-05-15 10:11:12 +08:00
imeoer ce4848e443
Merge pull request #591 from imeoer/converter-bootstrap-append
converter: support appending files to bootstrap layer
2024-04-26 12:11:52 +08:00
Yan Song b8ffddf416 optimizer-server: fix clippy errors
Fix the clippy check errors like:

```
warning: field `0` is never read
  --> src/main.rs:79:8
   |
79 |     IO(io::Error),
   |     -- ^^^^^^^^^
   |     |
   |     field in this variant
   |
   = note: `#[warn(dead_code)]` on by default
help: consider changing the field to be of unit type to suppress this warning while preserving the field numbering, or remove the field
   |
79 |     IO(()),
   |        ~~
```

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-04-25 08:23:46 +00:00
Yan Song 52145e6a01 converter: support appending files to bootstrap layer
Support `AppendFiles` option on `converter.Merge` method,
`AppendFiles` specifies the files that need to be appended
to the bootstrap layer.

This option allows the user to place some files in the nydus
bootstrap layer, for example, the user can place metadata
info generated at build time, e.g. named `image/metadata.json`.

And this usage does not affect the `image/image.boot` bootstrap
file that is accessed by the nydus runtime.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-04-25 07:21:01 +00:00
imeoer 7835988d38
Merge pull request #586 from fidencio/topic/misc-fix-snapshotter-cleanup-on-k3s-and-rke2
misc: Fix cleanup with k3s / rke2
2024-03-22 09:23:08 +08:00
Fabiano Fidêncio 1b21030182
misc: Simplify check for k3s / rke2
Let's make it simpler, following the same pattern introduced in the
cleanup function.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-03-21 00:07:37 +01:00
Fabiano Fidêncio 5a8dc3116f
misc: Fix cleanup with k3s / rke2
When performing the cleanup with k3s / rke2, we must specify the
containerd socket address that's been created by them, instead of using
the default one.

For both k3s and rke2 the containerd address socket is the same:
`/run/k3s/containerd/containerd.sock`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-03-21 00:07:05 +01:00
imeoer c7841c765b
Merge pull request #585 from BbolroC/fix-multiple-tags
action: publish manifest for multiple tags
2024-03-19 09:30:29 +08:00
Hyounggyu Choi e707fd1806 action: publish manifest for multiple tags
The PR #584 overlooked a scenario involving more than two elements
in `steps.meta.outputs.tags`. This commit addresses that by iterating
over the tags and creating/pushing a manifest for them, respectively.

Fixes: #583

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2024-03-18 19:21:38 +01:00
imeoer 81119b89f8
Merge pull request #584 from BbolroC/enable-multi-arch-image
action: enable nydus-snapshotter image to support multi-arch
2024-03-18 19:04:26 +08:00
Hyounggyu Choi 108e5fed87 action: enable nydus-snapshotter image to support multi-arch
This commit is to build and release `ghcr.io/containerd/nydus-snapshotter`
for multiple platforms (below) by leveraging GHA's QEMU/buildx funtionalities.

- amd64
- arm64
- s390x
- ppc64le

Fixes: #583

Signed-off-by: Hyounggyu Choi <Hyounggyu.Choi@ibm.com>
2024-03-18 11:54:51 +01:00
imeoer e15c985fab
Merge pull request #582 from imeoer/fix-nydus-overlayfs
misc: fix incorrect nydus-overlayfs version
2024-02-22 14:37:17 +08:00
Yan Song 02b37763e3 misc: fix incorrect nydus-overlayfs version
1. The nydus-overlayfs component has been moved into the cmd/nydus-overlayfs
directory in snapshotter repository, we should also use the nydus-overlayfs
binary in docker image.

2. Bump the nydus binary version v2.2.4, it's the latest stable release.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-02-22 03:31:16 +00:00
imeoer 3e5ad7fdea
Merge pull request #581 from Desiki-high/chore-golangci-lint-action-v4
chore: bump golangci-lint-action v4
2024-02-20 18:15:33 +08:00
Yadong Ding 730b88b38e lint: fix error with golanglint-ci v1.56.1
Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-02-13 13:04:36 +08:00
Yadong Ding 18ba01d44d chore: bump golangci-lint-action v4
Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-02-13 12:56:50 +08:00
imeoer 8dbd486cfd
Merge pull request #578 from Desiki-high/action-update-nodejs20
action: update nodejs20
2024-02-05 11:27:58 +08:00
Yadong Ding 9dd0af7483 lint: fix errors
Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-02-04 13:22:10 +08:00
Yadong Ding 95b3c5485c action: update nodejs20 and golangci-lint version
- use nodejs 20 version action: https://github.blog/changelog/2023-09-22-github-actions-transitioning-from-node-16-to-node-20/ .
- update golangci-lint v1.55.2 and use official GitHub action.
- use setup-go @v5 native cache ability.

Signed-off-by: Yadong Ding <ding_yadong@foxmail.com>
2024-02-04 13:21:43 +08:00
imeoer 3fcac86ccf
Merge pull request #577 from fidencio/topic/misc-snapshotter-ds-add-overlays-for-other-k8s-flavours
misc: snapshotter: Add `k3s` and `rke2` overlays to the snapshotter daemonset
2024-02-02 11:52:49 +08:00
ChengyuZhu6 3c70256fc8
tests: e2e: Adapt to using the nydus-snapshotter
Let's make sure the ClusterRole, ClusterRoleBinding, and the correct
environment variables (such as NODE_NAME) are properly set as part of
the E2E tests.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-02-01 14:48:56 +01:00
Fabiano Fidêncio de199669b7
misc: Detect k0s and error out if used
Differently than `k3s` or `rke2`, getting `k0s` to work as expected is
quite tricky, as it relies on a drop-in configuration file, and I'm not
so confident we can easily drop-in a file with all the needed bits.

With this in mind, at least for now, let's just error out in case k0s is
used, as at least this will make sure that the users will at least have
a clue on what's been gone wrong.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-02-01 08:02:24 +01:00
Fabiano Fidêncio 451a427c19
misc: Add rke2 kustomization
With these changes we're now able to also run the nydus-snapshotter
daemonset on `rke2` clusters.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-02-01 08:02:24 +01:00
Fabiano Fidêncio 9e6a0f1747
misc: Add k3s kustomization
With these changes we're now able to also run the nydus-snapshotter
daemonset on `k3s` clusters.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-02-01 08:02:24 +01:00
Fabiano Fidêncio 725016c371
misc: Add basic function to detect the container runtime
Right now this is very basic and simply will let us know whether we're
running on a node that's using containerd or not.

This ended up with the move of parts of the logic on detecting
containerd and containerd configuration files being removed from a few
specific functions and being put directly into the main one.

In the coming patches of this series we'll expand it to also detect
other kubernetes flavours, such as `k3s` or `rke2`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-02-01 08:02:19 +01:00
Fabiano Fidêncio 2f432eca29
misc: Add `kubectl` to the nydus-snapshotter daemonset image
We're doing this in order to, later on this series, use kubectl to
determine which kubernetes flavour we're running on the node.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-01-31 16:48:12 +01:00
Fabiano Fidêncio 2b35b9738f
misc: Adjust containerd-conf mount
In order to be able to override this accordingly to the kubernetes
flavour being used, we want to make it slightly more flexible on our end
and pass the directory instead of the file itself.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-01-31 16:48:12 +01:00
Fabiano Fidêncio dbca4274bb
misc: Move the nydus-snapshotter.yaml location
Let's have it under `base`, as we want to add a few overlays in order to
make sure this will work as expected with kubernetes flavours such as
`k3s`, or `rke2`.

Signed-off-by: Fabiano Fidêncio <fabiano.fidencio@intel.com>
2024-01-31 16:48:12 +01:00
imeoer 9ad5ad488c
Merge pull request #576 from imeoer/action-fix-image
action: fix failed image build
2024-01-30 18:20:06 +08:00
Yan Song a02a6c1ab9 action: fix failed image build
The nydus latest reelase version should be got from dragonfly/nydus repo.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-01-30 09:35:32 +00:00
imeoer bc761805a4
Merge pull request #575 from imeoer/action-fix-asset-link
action: fix incorrect release asset link
2024-01-30 15:53:10 +08:00
Yan Song 2a29116140 action: fix incorrect release asset link
Fixed the asset link in github release page from
nydus-snapshotter-x.x.x-linux-amd64.tar.gz to nydus-snapshotter-vx.x.x-linux-amd64.tar.gz

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2024-01-30 06:51:09 +00:00
imeoer 918ca3b144
Merge pull request #570 from ChengyuZhu6/payload
A more easy way to setup nydus snapshotter by DaemonSet
2024-01-26 14:12:29 +08:00
ChengyuZhu6 e0ba512a42 tests: update the e2e tests
update the e2e tests.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-26 13:27:34 +08:00
ChengyuZhu6 ad4299ee5e misc: check the status after restarting the systemd service
Check the status of the systemd service after restarting it.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-26 13:22:14 +08:00
ChengyuZhu6 492e57808b misc: remove entrypoint
We no longer need the entrypoint because snapshotter.sh handles
both the deployment and the cleanup of the snapshotter.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-26 13:22:14 +08:00
ChengyuZhu6 ce51815641 docs: Add document to setup snapshotter by daemonset
Add document to setup snapshotter by daemonset.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-26 13:22:14 +08:00
ChengyuZhu6 d5643215d8 misc: support to run snapshotter as systemd service
Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-26 13:22:14 +08:00
ChengyuZhu6 0380827405 misc: support to configmap to env and volume
Use configmap to decouple configuration artifacts from image content
to keep containerized applications portable and inject configuration
files and variables to the daemonset.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-25 21:38:22 +08:00
ChengyuZhu6 6b6c9239c0 misc: introduce main function to handle
introduce main function to handle different commandline.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-25 21:37:41 +08:00
ChengyuZhu6 c1220632cf misc: cleanup nydus snapshotter
This can be seamlessly handled for users, eliminating the requirement for them
to restore Containerd to its state prior to running the snapshotter.
This approach reduces errors caused by misconfiguration or misbehavior.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-25 21:37:41 +08:00
ChengyuZhu6 8baf2e6d3b misc: support to configure snapshotter in containerd config
This can be made transparent to users, eliminating the need for them to understand
how to configure snapshotter in Containerd and reducing errors caused by
misconfiguration.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-25 21:37:40 +08:00
ChengyuZhu6 84e341eab4 misc: introduce a script to deploy nydus snapshotter
Fixes #565

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-24 17:06:16 +08:00
ChengyuZhu6 4e7f9eb385 misc: Copy all configs to snapshotter image
Copy all configs to nydus snapshotter image.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-24 17:06:15 +08:00
imeoer cc66508a3f
Merge pull request #573 from ChengyuZhu6/config
docs: Supplementary for containerd configuration required by snapshotter
2024-01-15 14:16:52 +08:00
ChengyuZhu6 0041455546 docs: Supplementary for containerd configuration required by nydus snapshotter
Supplementary for containerd configuration required by nydus
snapshotter: `disable_snapshot_annotations` and
`discard_unpacked_layers`.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2024-01-12 14:23:19 +08:00
imeoer 47d4311951
Merge pull request #560 from ChengyuZhu6/layer_block
Support sharing image on the host for layer block mode
2023-12-25 11:35:10 +08:00
ChengyuZhu6 bfa2d368c0 misc: add comments for fs_driver on snapshotter config
Add comments for fs_driver on snapshotter config.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-18 21:39:50 +08:00
imeoer 0397a1f5c0
Merge pull request #569 from ChengyuZhu6/guest-pull
misc: add daemon_mode option to guest pull config
2023-12-15 14:18:35 +08:00
ChengyuZhu6 af40ded62b misc: add comments for daemon_mode on snapshotter config
Add comments for daemon_mode on snapshotter config.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-15 12:44:22 +08:00
ChengyuZhu6 5ec75bc671 misc: Delete blank lines in snapshotter config
Delete blank lines in snapshotter config.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-15 12:21:16 +08:00
ChengyuZhu6 1a85191939 misc: add daemon_mode option to guest pull config
`daemon_mode` should be specified in guest pull config, even if it is none.
This ensures that guest pull config is consistent with other configs and avoids confusion.

Fixes #568

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-15 12:21:07 +08:00
imeoer b42e3f5526
Merge pull request #566 from thaJeztah/replace_docker_distribution
replace docker/distribution for github.com/distribution/reference v0.5.0
2023-12-12 09:21:32 +08:00
Sebastiaan van Stijn 0907ace254
replace docker/distribution for github.com/distribution/reference v0.5.0
The "reference' package has now moved to a separate repository, which means
we can replace the local fork, and use the upstream implementation again.

The new module was extracted from the distribution repository at commit:
b9b19409cf

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
2023-12-11 16:57:17 +01:00
ChengyuZhu6 44733280e5 snapshot: get image reference from cri annotations for guest pull
The sandbox image (pause image) name cannot be stored in annotations by containerd,
so snapshotter is unable to retrieve it. This means that the source field of `KataVirtualVolume`
has to be set to "" to support guest pull in proxy mode now. However, once containerd fixes this bug
(https://github.com/containerd/containerd/pull/9419), I think the nydus snapshotter could be able to get the sandbox image name
from annotations directly. I recommend that we can support to obtain the image name through
"containerd.io/snapshot/cri.image-ref" in snapshotter. If this value is empty, the source should be set to "",
otherwise it should be set to the image name.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-07 16:31:12 +08:00
ChengyuZhu6 671c4140e2 snapshot: support to handle kata volume for layer block
Support to handle kata volume for layer block and reconstruct functions
about handling kata virtual volumes.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-07 16:31:11 +08:00
ChengyuZhu6 7ead21fa5b snapshot: Introduce a function to prepare KataVirtualVolume
Introduce a function to prepare KataVirtualVolume for both guest pull image
and host sharing image modes to eliminate redundant code.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-07 14:14:58 +08:00
ChengyuZhu6 685b70863b tarfs: fix error when export block data for layer block
When the layer_block mode is enabled, the remote snapshot does not contain the
`containerd.io/snapshot/nydus-layer-block` label, which prevents the creation of
a kata volume. Therefore, we need to add the `containerd.io/snapshot/nydus-layer-block`
label to the remote snapshot.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-07 14:14:57 +08:00
imeoer 094fb40a3b
Merge pull request #553 from sctb512/release-different-arch-packages
Release nydus-snapshotter packages with different architectures
2023-12-07 11:27:36 +08:00
imeoer 7b9f4ca6bd
Merge pull request #563 from adamqqqplay/enable-stable-ci
action: enable CI on stable branch
2023-12-06 08:49:10 +08:00
Qinqi Qu 33d6c7361c action: enable CI on stable branch
Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-12-05 14:44:02 +08:00
imeoer d44bfb7930
Merge pull request #561 from adamqqqplay/update-release-yaml
release: get latest nydusd version from Github API
2023-12-05 11:36:21 +08:00
Qinqi Qu 5de264b094 release: get latest nydusd version from Github API
In our released nydus-snapshotter images, the nydusd version is always
v2.1.5, and this patch fixes that.

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-12-05 11:07:45 +08:00
ChengyuZhu6 49f347e68f tarfs: Introduce a function to get the path of layer disk file
Introduce a function to get the path of layer disk file.

Fixes: #559

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-12-05 09:22:46 +08:00
imeoer 5009c522df
Merge pull request #556 from ChengyuZhu6/fix_typos
snapshot: Fix typo
2023-11-10 09:33:01 +08:00
ChengyuZhu6 1cdbcfbc86 snapshot: Fix typo
Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-11-09 22:05:56 +08:00
imeoer 5afc3f2f4b
Merge pull request #554 from hangvane/amplify_io_snap
daemon: change `amplify_io` into nullable int
2023-11-06 09:13:59 +08:00
Bin Tang c75cb971d1 workflow: release packages with different architecture
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-11-03 19:12:26 +08:00
Bin Tang d8ddcc1291 Makefile: add package subcommand to build nydus-snapshotter package
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-11-03 19:12:25 +08:00
Wenhao Ren b0a0d9ddb4
daemon: change `amplify_io` into nullable int
`amplify_io` should be nullable in config file.
The absence of `amplify_io` in the config file means
it follows the default value in nydusd, i.e., 1M.
`amplify_io=0` means it is set to zero.
So let's change this field into nullable to pass the value
as what it is read from template config file.

Signed-off-by: Wenhao Ren <wenhaoren@mail.dlut.edu.cn>
2023-11-03 13:40:11 +08:00
imeoer bd47e03986
Merge pull request #549 from hangvane/amplify_io_snap
daemon: add `amplify_io` support in nydusd configuration file
2023-11-03 08:36:23 +08:00
Bin Tang e12a3eb546 misc: add default value of nydusd rotation size
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-11-02 13:03:49 +08:00
Wenhao Ren 7cd7f0b1ed
daemon: add `amplify_io` support in nydusd configuration file
Add `amplify_io` support, by reading and forwarding this arg.

Signed-off-by: Wenhao Ren <wenhaoren@mail.dlut.edu.cn>
2023-11-01 13:26:36 +08:00
imeoer 985c185e66
Merge pull request #551 from adamqqqplay/update-deps
deps: bump google.golang.org/grpc to 1.59.0
2023-11-01 11:58:27 +08:00
Qinqi Qu bcc92951ab deps: bump google.golang.org/grpc to 1.59.0
1. Fix gRPC-Go HTTP/2 Rapid Reset vulnerability

Please refer to:
https://github.com/advisories/GHSA-m425-mq94-257g

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-11-01 09:55:19 +08:00
Changwei Ge f894d55cbb
Merge pull request #504 from DarkMountain-wyz/main
Adding an interface to the system socket to help nydusd obtain config
2023-10-31 19:29:33 +08:00
Guijie Wang 402b9e4a3f Fixed CI errors
Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-31 18:24:06 +08:00
Guijie Wang 1561c9572b Fixed CI error
Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-31 17:20:54 +08:00
Guijie Wang 2954505815 Fixed CI error
Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-31 16:51:36 +08:00
Guijie Wang a078fd3264 Fixed CI error
Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-31 16:35:34 +08:00
Guijie Wang c64c21942b Fixed CI errors
Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-31 16:15:09 +08:00
imeoer 3ffbe8f590
Merge pull request #550 from billie60/fix-CItest
modify the nydus releases address to fix CI test
2023-10-30 12:09:59 +08:00
billie60 2402ede7bd modify the nydus releases address to fix CI test
modify all image-service to nydus
2023-10-26 12:18:50 +08:00
imeoer 2f20ea7448
Merge pull request #545 from hangvane/batch-bugfix
converter: fix missed BatchSize arg for dir-rafs packing
2023-10-18 21:40:05 -05:00
Wenhao Ren 478903ffee
converter: fix missed BatchSize arg for dir-rafs packing
dir-rafs lacks the `batch-size` build parameter,
making the converting failed when tar-rafs is disabled and fallbacked to dir-rafs

Signed-off-by: Wenhao Ren <wenhaoren@mail.dlut.edu.cn>
2023-10-19 10:19:53 +08:00
Changwei Ge 1e090da3b5
Merge pull request #543 from imeoer/converter-fix-cache
converter: fix invalid layer desc when cache hits
2023-10-11 11:17:35 +08:00
Yan Song 30c558e2a3 converter: fix invalid layer desc when cache hits
We should also add the labels.LabelUncompressed label and the
label.NydusRefLayer, LayerAnnotationNydusEncryptedBlob annotations
for the layer in content store cache, otherwise the generated
layer descriptor is invalid for acceld/nydusify.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2023-10-10 06:07:12 +00:00
Guijie Wang b166c69c50 system: add interface for nydusd to obtain backend config
This commit introduces a new interface that allows nydusd to request backend configurations from the snapshotter via a Unix domain socket. Transferring all backend configs is to cope with the addition of different backend in the future.

Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-01 11:44:18 +08:00
Guijie Wang 17efbb47f0 deamonconfig: add serializeWithSecretFilter function to filter fields with secret tag
This commit introduces a new function, serializeWithSecretFilter, which filters fields with the 'secret' tag and prevents them from being persisted to local storage when the value is true.

Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-01 11:31:46 +08:00
Guijie Wang b37efb1fdd config: add enable_backend_source startup option to control persistence of auth information
This change introduces a new startup option, enable_backend_source, which controls whether the authentication information is persisted or not. By default, enable_backend_source is set to false, which means that the authentication information will be persisted.

Signed-off-by: Guijie Wang <wgj1128@mail.dlut.edu.cn>
2023-10-01 11:30:36 +08:00
imeoer dde21094df
Merge pull request #542 from imeoer/move-out-encryption
converter: move out encryption package
2023-10-01 07:41:04 +08:00
Yan Song 30e904101f converter: move out encryption package
Due to the introduction of the github.com/containers/ocicrypt package
in converter, which brings in many other dependencies, but encryption
should currently be an experimental optional feature, we need to move
this part of the codes out to reduce the burden on other projects that
reference the package.

Signed-off-by: Yan Song <yansong.ys@antgroup.com>
2023-09-28 15:31:28 +00:00
Changwei Ge 2cc7d81b30
Merge pull request #536 from jiangliu/cachemgr
cache: fix null pointer access when cachemanager.Disable is true
2023-09-25 14:52:33 +08:00
Changwei Ge 14bcfedf6d
Merge pull request #541 from sctb512/fix-optimize-workflow-failed
workflow: fix containerd not ready error for optimizer test
2023-09-25 09:38:58 +08:00
Changwei Ge c0c30c7bac
Merge pull request #540 from changweige/fix-e2e-error
e2e: always disable erofs ondemand-read test and failover test
2023-09-22 15:02:20 +08:00
Changwei Ge 3d3439b21b
Merge pull request #537 from jedevc/fix-windows-conversion-funcs
fix: update windows public functions to match linux
2023-09-22 15:02:08 +08:00
Bin Tang f86a6a9e22 workflow: fix containerd not ready error for optimizer test
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-09-21 22:41:58 +08:00
Changwei Ge 62f53c7ed4 e2e: always disable erofs ondemand-read test and failover test
Github action has upgraded its worker kernel to 6.2 with
CONFIG_EROFS_FS_ONDEMAND enabled. The e2e tests of failover depends
on private kernel patches rather upstream kernel. So we have to totally
disable the failover tests for now

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-09-21 18:01:27 +08:00
Jiang Liu 02a5c14b9a cache: fix null pointer access when cachemanager.Disable is true
Filesystem.cacheMgr is null when cacheManager.Disable is configured
to be true, thus cause null pointer access. Fix it by always create
the cacheMgr object no matter cacheManager.Disable is true or false.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-19 09:10:33 +08:00
Justin Chadwell 96413bf99c fix: update windows public functions to match linux
Previously, the function signatures differed after being updated in
b16a068584. This patch updates the
corresponding windows functions to match the linux signatures.

Signed-off-by: Justin Chadwell <me@jedevc.com>
2023-09-18 09:57:36 +01:00
Changwei Ge 106a9a178b
Merge pull request #530 from jiangliu/coco
Support host sharing and guest pulling for Confidential Container image management
2023-09-12 17:52:54 +08:00
Jiang Liu 0da2966cc0 snapshot: fix a bug in generating mount for view snapshot
When generating a view snapshot with only one parent, it will generate
bind mount instead of overlayfs mount, and missing extra options,
such as `KataVirtualVolume` or `extraoptions`.

Fix it by using overlayfs for view snapshot with only one parent.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:35 +08:00
Jiang Liu fedb996240 tarfs: fix several bugs related to tarfs
1. chooseProcessor() forgot to update tarfs annotations for parent
   snapshot during preparing rw snapshot.
2. initialize `Labels` map in function createSnapshot() to avoid
   accessing nil pointer.
3. enhance error hanlding of tarfs::Manager::PrepareLayer().

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:34 +08:00
Jiang Liu 794ff09335 snapshot: add proxy mode to support guest pulling for CoCo
Add proxy mode to support guest pulling for Confidential Containers,
which doesn't download any image layer content on host but relay the
image pulling request to Kata runtime/agent. It generates a fake rootfs
with an extra mount option for Kata virtual volume.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:33 +08:00
Jiang Liu 57f088de29 filesystem: use hashmap to manage registered managers
Simplify code by using hashmap to manage registered managers.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:33 +08:00
Jiang Liu 6683fb0baf tarfs: add a sample configuration file for tarfs
Create a minimal configuration file for tarfs
- treat tarfs as DaemonMode == "none"
- create rafs instance for DaemonMode == "none"

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:32 +08:00
Jiang Liu 7d24dee6d2 tarfs: append Kata volume information to mount option
Append Kata volume information to mount option
- change value of annotation `containerd.io/snapshot/nydus-tarfs`
  from bool to tarfs export mode.
- save tarfs meta information in Rafs.Annotation.
- add "io.katacontainers.volume=xxx" to Mount.Options

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:32 +08:00
Jiang Liu 7a5725041b filesystem: enhance error handling for Mount()
Enhance error handling for Mount() by rollback operations on errors.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:31 +08:00
Jiang Liu 3b89f95a24 snapshot: introduce data structures to support Kata virtual volumes
Introduce data structures to support Kata virtual volumes, which is a
superset of Nydus `ExtraOption`.

Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-12 17:02:30 +08:00
imeoer 2f1bfad15b
Merge pull request #529 from jiangliu/overlayfs
cmd: move nydus-overlayfs from image service to snapshotter
2023-09-11 16:56:31 +08:00
Jiang Liu a48b65223b cmd: move nydus-overlayfs from image service to snapshotter
Nydus-overlayfs is a mount helper for nydus-snapshotter, and is only
used by nydus-snapshotter. So move it from Image Service into
nydus-snapshotter.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-11 11:49:06 +08:00
Changwei Ge a2d744bc8c
Merge pull request #528 from jiangliu/rafs
Make RAFS independent of daemon
2023-09-08 15:44:13 +08:00
Jiang Liu d646992956 fs: refine implementation of filesystem related code
Refine implementation of filesystem related code:
- enhance error handling.
- replace instance with rafs.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-06 11:45:37 +08:00
Jiang Liu c3cdfd70d2 daemon: refine implementation of daemon
Refine implementation of daemon.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-04 11:28:40 +08:00
Jiang Liu 061007f1c1 manager: rename DaemonStates as DaemonCache
Rename DaemonStates as DaemonCache to clearly state it's a cache for
daemons stored in DB.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-04 11:28:39 +08:00
Jiang Liu f0369bf2df rafs: make RAFS instances independent of daemons,
Originally all RAFS instances are associated with daemons, so it's
abstracted daemons owns RAFS instance. With addition of tarfs, RAFS
instances may be independent of nydusd daemons.

So make them independent by:
- rename xxxInstance to xxxRafsInstance to clear state the target is
  RAFS instance
- rename DaemonStore to DaemonRafsStore

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-04 11:28:38 +08:00
Jiang Liu cf4f1bdc9c rafs: make RAFS related code as a dedicated package
Move RAFS related code out of package daemon, and make it as a
dedicated `rafs` package.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-04 11:28:23 +08:00
Jiang Liu a9b6e0193b manager: split code of manager into several submodules
Split code of manager into several submodules to improve readability.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-09-02 22:46:30 +08:00
Changwei Ge 9a2575b617
Merge pull request #499 from jiangliu/tarfs
Refine tarfs overall design and implementation details
2023-08-31 10:58:08 +08:00
Jiang Liu f3c1541909 snapshot: extend the ExtraOption struct
Move ExtraOption to dedicated file and extend it for more usage cases.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:19 +08:00
Jiang Liu 14d2417b37 tarfs: add documentation for tarfs
Add documentation for tarfs.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:16 +08:00
Jiang Liu d9c0b38f25 tarfs: simplify tarfs implementation
Simplify tarfs implementation by:
1) simplify the way to detech images without data blob
2) do not regenerate tarfs data when it already exists

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:15 +08:00
Jiang Liu 472624d93c tarfs: export nydus tarfs image as block with verity
Enhance tarfs implementation to support following operations:
- export an tarfs image as a block device
- export an tarfs image as a block device with verity
- export an tarfs layer as a block device
- export an tarfs layer as a block device with verity

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:14 +08:00
Jiang Liu 2543daa761 snapshot: change if else to switch
Change if else to switch according to golint suggestions.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:13 +08:00
Jiang Liu d90b73db02 snapshot: support overlay volatile option for nydus
The overlay volatile option is only supported for OCIv1 images,
so enhance nydus remote images to support it too.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:12 +08:00
Jiang Liu ea6f182249 snapshot: remove function prepareRemoteSnapshot()
Remove function prepareRemoteSnapshot() to simplify the code and
improve readability.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:11 +08:00
Jiang Liu 35b48e5472 tarfs: refine tarfs overall design and implementation details
1) move loopdev setup from Prepare()/Merge() into Mount(), preparing
   for support of nodev mode in addition to blockdev.
2) store tar file in the global cache directory, mount tarfs at "mnt"
   instead of "tarfs", to keep consistence with fusedev/fscache drivers.
3) use tempfile/rename mechanism to easy error recover
4) use lock to avoid some possible race conditions
5) use mode 0750 instead of 0755 for new directories
6) associate a Manager with filesystems managed by blockdev

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 10:37:10 +08:00
Jiang Liu 1eb7bf23d5 tarfs: only caches needed information
Only caches needed information according to manager configuration.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 09:51:32 +08:00
Jiang Liu 47372c14de tarfs: limit maximum size of image manifest and config
Limit maximum size of image manifest and config, to avoid DoS attack.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 09:51:31 +08:00
Jiang Liu 91fb535080 tarfs: syntax only changes
Syntax only changes:
- fix some typos
- rename manifest to manifestDigest

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-08-31 09:51:31 +08:00
Xin Yin ace7d56c81 pkg: support VIEW for tarfs
Support VIEW for tarfs snapshot.

Signed-off-by: Xin Yin <yinxin.x@bytedance.com>
2023-08-31 09:51:30 +08:00
Xin Yin fba1c892d5 pkg: add concurrent control for tarfs blob process
Add 'tarfs_max_concurrent_proc' option to set number of concurrent
goroutines for tarfs blob processing.

Signed-off-by: Xin Yin <yinxin.x@bytedance.com>
2023-08-31 09:51:29 +08:00
Xin Yin 1fd9ac4e62 pkg: support run oci image with erofs tarfs
Add 'enable_tarfs' option in config.toml, to enable run oci image with
erofs tarfs.

Snapshotter will download all image layers, uncompress to tar files and
generate tarfs boostraps. Finally mount erofs based on loop device as
the image read only rootfs.

Signed-off-by: Xin Yin <yinxin.x@bytedance.com>
2023-08-31 09:51:26 +08:00
imeoer 33bca864ca
Merge pull request #523 from changweige/upgrade-pkg
upgrade package github.com/KarpelesLab/reflink
2023-08-31 09:34:55 +08:00
Changwei Ge aa64c04ce4 upgrade package github.com/KarpelesLab/reflink
Current dependent package github.com/KarpelesLab/reflink is of version
0.0.2 which has no associated lisense. It may have legal problem. So
upgrade the package

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-08-28 19:25:53 +08:00
Changwei Ge 490cc94878
Merge pull request #493 from billie60/prefetchfiles-nri
Transmit the prefetch list to snapshotter during runp pod.yaml
2023-08-28 18:51:28 +08:00
Guang Xu 983f342342 nri-plugin: file prefetching
1. modify config file's default dir in /etc/nydus/
2. modify GetPrefetchMap in prefetch package to GetPrefetchInfo
2023-08-28 17:44:59 +08:00
Changwei Ge 81e630df36
Merge pull request #522 from ChengyuZhu6/fix_typo
docs: Fix typo
2023-08-22 10:20:02 +08:00
ChengyuZhu6 b6a722ad51 docs: Fix typo
Signed-off-by: ChengyuZhu6 <chengyu.zhu@intel.com>
2023-08-21 22:06:47 +08:00
imeoer f9cfcf057a
Merge pull request #517 from PerseidMeteor/feat-remote-cache
feat: prevent unnecessary conversions
2023-08-18 17:44:40 +08:00
Changwei Ge 732d9a62a8
Merge pull request #518 from loheagn/parallelize-nydusd-setup
optimize: resume nydusd processes parallelizilly
2023-08-16 15:07:17 +08:00
breezeTuT bf7032c14d feat: prevent unnecessary conversions
If content store provides remote cache,  we can use remote cache to avoid unnecessary conversions.
The layer converted using cache is the same as the layer converted normally, both containing two annotations: LayerAnnotationUncompressed, LayerAnnotationNydusBlob.
Also add two constant LayerAnnotations labels.

Signed-off-by: breezeTuT <y_q_email@163.com>
2023-08-15 11:32:22 +08:00
Nan Li d37a00ef20 optimize: resume nydusd processes parallelizilly
This patch allows the snapshotter resumes the recovering nydusd daemons parallelizilly in the starting stage.

Signed-off-by: Nan Li <loheagn@icloud.com>
2023-08-09 11:36:41 +00:00
Changwei Ge a6f4457b31
Merge pull request #515 from imeoer/remove-auth-through
config: remove useless auth_through option
2023-08-02 18:57:06 +08:00
Yan Song 77dd2aa3a7 config: remove useless auth_through option
We have removed the `auth_through` option in https://github.com/dragonflyoss/image-service/pull/1375

Let's remove it in snapshotter, since its default value is
false, there is no compatibility impact.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-08-01 02:03:46 +00:00
Changwei Ge 0e3857eb34
Merge pull request #514 from sctb512/remove-codecov-patch-check
workflow: disable codecov/patch check
2023-07-28 15:37:20 +08:00
Bin Tang 100f055587 workflow: disable codecov/patch check
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-27 15:49:23 +08:00
Changwei Ge 8ca9591ac8
Merge pull request #511 from imeoer/fix-release-action
action: remove the broken step of installing hub
2023-07-18 20:03:01 +08:00
Yan Song ce9b7b0468 action: remove the broken step of installing hub
https://github.com/containerd/nydus-snapshotter/actions/runs/5584824903

The hub has been integrated to github action worker, so let's
remove it to fix the failure.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-07-18 11:22:55 +00:00
Changwei Ge ae06355efe
Merge pull request #509 from imeoer/subject-option
converter: allow controlling referrer with option
2023-07-17 11:40:59 +08:00
Yan Song f8107339e1 converter: allow controlling referrer with option
Some registry implementations like Docker Hub don't support the
OCI reference type (aka referrer) yet, we shouldn't enable it by
default, instead, provide a `WithReferrer` option to control it.

With this option, we can track all nydus images associated with
an OCI image. For example, in Harbor we can cascade to show nydus
images linked to an OCI image, deleting the OCI image can also delete
the corresponding nydus images. At runtime, nydus snapshotter can also
automatically upgrade an OCI image run to nydus image.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-07-17 03:31:58 +00:00
Changwei Ge 72c3f63130
Merge pull request #507 from sctb512/fix-log-rotate
transmit log rotation max size to nydus daemon
2023-07-14 18:03:18 +08:00
Changwei Ge 7f7c9984d5
Merge pull request #508 from sctb512/remove-unused-code
Remove some unused code and updated docs for metrics
2023-07-14 10:49:40 +08:00
Bin Tang e35a80081e docs: add more information about enabling metrics
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-14 10:38:18 +08:00
Bin Tang 0266ac10dc metrics: remove root directory in metrics server
The root directory is not used by metrics server forever because
we have remove the function to dump metrics to a file in root directory.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-13 19:52:05 +08:00
Bin Tang ea9360239b config: change test to adapt the updated configuration file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-13 16:18:00 +08:00
Bin Tang 35f06e5356 misc: add log rotation entry for nydus daemon
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-13 16:18:00 +08:00
Bin Tang 117a170953 config: transmit log rotation size to nydusd arguments
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-13 16:17:57 +08:00
Changwei Ge e02116ca6a
Merge pull request #498 from taoohong/nydus-image-encrypt
feats: support encrypting nydus data blobs
2023-07-13 14:58:57 +08:00
taohong 3915fce9db feats: support encrypting nydus data blobs
Support encrypting nydus data blobs.

Signed-off-by: taohong <taoohong@linux.alibaba.com>
2023-07-13 14:43:19 +08:00
Changwei Ge e26c8081bf
Merge pull request #503 from changweige/dont-let-codecov-comment
don't let codecov tool comment everywhere in PR
2023-07-13 14:15:02 +08:00
Changwei Ge 4a7ac0911c reduce comments from codecov
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-07-13 10:32:35 +08:00
Bin Tang b732b9c9ee command: convert different types of value to nydusd paramter
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-07-12 17:48:35 +08:00
Changwei Ge 3338db6702
Merge pull request #501 from changweige/dump-action-logs
dump logs of containerd if optimizer test fails
2023-06-29 09:42:06 +08:00
Eryu Guan 88728c1bc8
Merge pull request #500 from jiangliu/remote
remote: enhance FetchByDigest() to handle more mediatypes
2023-06-27 16:50:14 +08:00
Jiang Liu 86cbcb7350 remote: enhance FetchByDigest() to handle more mediatypes
Enhance FetchByDigest() to handle manifest with mediatype
"application/vnd.oci.image.manifest.v1+json"

The affected file is copied from containerd upstream and we will try
to upstream this change to containerd.

Fixes: https://github.com/containerd/nydus-snapshotter/issues/474

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-27 14:07:24 +08:00
Changwei Ge 4652ef59a2 dump logs of containerd if optimzer test fails
The optimzer test occasionally fails, let's see what bad happens.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-06-27 10:07:49 +08:00
imeoer 9e555b8a59
Merge pull request #472 from jiangliu/multi-modes
Prepare to support multiple running modes and tarfs
2023-06-19 11:58:04 +08:00
imeoer baa637ba24
Merge pull request #495 from changweige/add-reviewer
add Bin Tang as a reviewer
2023-06-19 11:57:53 +08:00
Changwei Ge b26812ce64 add Bin Tang as a reviewer
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-06-17 10:53:33 +08:00
Jiang Liu 03a9481e92 filesystem: prepare to support multiple daemon modes
Prepare to support multiple daemon modes, so we can create filesystem
instances with blockdev, fscache, fusedev concurrently.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-16 14:49:17 +08:00
Jiang Liu df98c75f58 manager: fix a typo
Fix a typo, it should be "s.path == path" instead of "s.id == path"

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-16 13:00:23 +08:00
Changwei Ge 2c811d7b2e
Merge pull request #494 from sctb512/remove-goproxy-for-integration
integration: remove GOPROXY environment
2023-06-16 12:57:35 +08:00
Bin Tang c4c2478945 integration: remove GOPROXY environment
We don't need this proxy, so remove it.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-16 10:54:53 +08:00
Changwei Ge 9ce8cceb5c
Merge pull request #491 from sctb512/fix-optimizer-workflow
workflow: fix incorrect files number for optimizer test
2023-06-16 10:05:36 +08:00
Changwei Ge 0a9b4adef5
Merge pull request #415 from sctb512/limit-daemon-memory-via-cgroup
Limit memory resource usage for nydus daemon via cgroup
2023-06-16 10:01:15 +08:00
Jiang Liu da4c40b0cf daemon: record FsDriver in Rafs object
Record FsDriver in Rafs instance, it will be used later.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-16 09:59:24 +08:00
Jiang Liu a63a4e20c3 config: always probe and setup DaemonConfig.NydusdPath
config: always probe and setup DaemonConfig.NydusdPath, no matter
what the daemon mode is.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-16 09:59:17 +08:00
Jiang Liu 7dced5a46c config: introduce two new fsdriver
Introduce two new fsdriver,
- blockdev: will be used to support tarfs
- nulldev: acts as `DaemonMode = none`

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-16 09:59:03 +08:00
Bin Tang 5d9bdba059 misc: add enable entry for nydusd cgroup
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:32 +08:00
Bin Tang a5c6821b17 config: add enable entry for nydusd cgroup
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:32 +08:00
Bin Tang a85f4fd52f integration: enable nesting for cgroup v2
refer to https://github.com/moby/moby/issues/43093

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:32 +08:00
Bin Tang 51615c4c25 makefile(integration): enable cgroup capability for container
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:32 +08:00
Bin Tang 59641087fe workflow: add iontegration test for cgroup v2 environment
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang c6e22ec916 misc: add cgroup configuration for daemon
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang 18542aae2c update go.mod to adapt pkg/cgroup package
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang d8d6dbe0e7 daemon: add cgroup manager to daemon manager
The cgroup manager aims to manager the lifetime of daemon's cgroup
and add nydusd to this cgroup for memory resource limitation and reclaim.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang 8d70c00db9 config: add test for ParseCgroupConfig
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang 7b055ff550 config: parse cgroup configuration to expected units
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:31 +08:00
Bin Tang 6030cab456 pkg: introduce pkg/parser package
The parser package aims to parse configuration data to expected units

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 20:37:30 +08:00
Bin Tang 54fc5bc5cd config: add cgroup config entry for daemon
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 19:36:01 +08:00
Bin Tang 57509f4d4a cgroup: add cgroup v2 implementation
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 19:35:59 +08:00
Bin Tang 97a3493529 workflow: fix incorrect files number for optimizer test
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 16:21:56 +08:00
Bin Tang 756fc94f6a misc: add entrypoint script for optimizer test
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-15 16:20:23 +08:00
Bin Tang 9b373c0f08 cgroup: add cgroup v1 implementation
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-14 18:08:27 +08:00
Bin Tang eda54d52ef pkg: introduce pkg/cgroup package
This PR introduce a cgroup interface for nydusd daemon

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-06-14 18:08:27 +08:00
imeoer 88ccb5207f
Merge pull request #467 from jiangliu/metrics
metrics: prepare to support multiple instances of Manager
2023-06-07 20:37:55 +08:00
Jiang Liu 66dba0d927 system: enhance controller to support multiple instnace of Manager
Enhance controller to support multiple instnace of Manager.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-07 16:53:07 +08:00
Jiang Liu 73409c4883 metrics: prepare to support multiple instances of Manager
Enhance metrics server to support multiple instances of Manager.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-07 14:04:48 +08:00
imeoer 3224e84c62
Merge pull request #475 from jiangliu/syntax
pkg: minor code style improvements
2023-06-07 10:06:06 +08:00
imeoer 8fe6bbafc3
Merge pull request #476 from jiangliu/snapshot
Minor enhancements and bugfixes to snapshot
2023-06-07 10:01:37 +08:00
imeoer 0c19b54b9f
Merge pull request #489 from hangvane/feature-detection
converter: add feature detection for `--batch-size`
2023-06-07 10:00:27 +08:00
Jiang Liu e6be9a6e72 snapshot: ensure parent snapshot exists in Mount()
Ensure parent snapshot exists in Mount(), otherwise return error code.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-06 22:12:41 +08:00
Jiang Liu 81a517dae3 snasphot: use helper functions to avoid duplicated code
Use helper functions to avoid  duplicated code.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-06 22:12:41 +08:00
Jiang Liu 5b5f7bc876 snapshot: remove field hasDaemon from snapshotter
Remove field hasDaemon from struct snapshotter.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-06 22:12:41 +08:00
Jiang Liu abf19f54aa snapshot: refine chooseProcessor() for readability
Refine chooseProcessor() for readability.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-06 22:12:41 +08:00
Jiang Liu 007a63f28d snapshot: normalize trace messages
Normalize trace messages for prepare/view/mount/remove etc.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-06 22:12:41 +08:00
Wenhao Ren 536b5c811f
converter: detect features by checking help message, close #482
1. detect features by checking `nydus-image create -h`.
2. Add feature detection for `--batch-size`.

Signed-off-by: Wenhao Ren <wenhaoren@mail.dlut.edu.cn>
2023-06-06 20:03:59 +08:00
imeoer 8fc731a090
Merge pull request #479 from taoohong/nydus-encryption
Support Nydus boostrap layer encryption and decryption
2023-06-06 12:12:20 +08:00
Bin Tang 1c0b46ef50 Revert "workflow: fix incorrect files number for optimizer test"
This reverts commit b3e676d20f.
2023-06-05 19:51:12 +08:00
taohong 5a1814790e tests: add test for Nydus bootstrap encryption
Add testImageConvertWithCrypt to test Nydus bootstrap
encryption and decryption.

Signed-off-by: taohong <taoohong@linux.alibaba.com>
2023-06-05 15:22:59 +08:00
Jiang Liu 3881a3197a pkg: minor code style improvements
Minor code style improvements, should be no functional changes.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-06-05 00:08:05 +08:00
Changwei Ge 2c1de89684
Merge pull request #487 from changweige/impr-optimizer
Minor improvements for image optimizer
2023-05-27 09:23:22 +08:00
Changwei Ge 63914fe64d optimizer: just use standard integer types
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-05-26 14:20:26 +08:00
Changwei Ge 533603efa7 invoke building of image optimizer by its own Makefile
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-05-26 14:20:26 +08:00
Changwei Ge 31b74000ed optimizer: add simple Makefile
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-05-26 14:20:26 +08:00
imeoer 4b133ee7fb
Merge pull request #485 from adamqqqplay/fix-test-coverage
action: remove patch coverage check in workflow
2023-05-22 18:23:24 +08:00
Qinqi Qu 03ae8fc3db action: remove patch coverage check in workflow
In the recent PR, the patch coverage requirement seems to be too strict.
So we temporarily remove this check and focus on project coverage.

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-05-22 17:35:04 +08:00
imeoer 10b4835d4d
Merge pull request #483 from imeoer/ignore-blob-for-unpack
converter: ignore nonexistent blob data for unpack
2023-05-22 16:35:05 +08:00
Yan Song c532b57234 converter: ignore nonexistent blob data for unpack
When we convert nydus with empty blob data to gzip
(or other compression types) layer, will encounter the error:

```
unpack nydus blob: unpack nydus tar: unpack blob from nydus:
can't find target image.blob by seeking tar: data not found
```

The nydus layer may contain only bootstrap and no blob
data, which should be ignored.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-05-22 07:48:24 +00:00
Changwei Ge 38d93012f3
Merge pull request #459 from imeoer/fix_referrer
referrer: fix panic on enable_referrer_detect enabled
2023-05-16 09:55:41 +08:00
taohong ae4a443cad encryption: support multiple encryption recipients when conversion
Update encryptRecipients from string to []string,
support multiple encryption recipients when conversion.

Signed-off-by: taohong <taoohong@linux.alibaba.com>
2023-05-15 17:54:12 +08:00
Yan Song c2502ebf7f integration: add referrer detect test case
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-05-15 08:59:52 +00:00
Yan Song 321fc7f951 referrer: fix panic on enable_referrer_detect enabled
The panic occurs when `enable_referrer_detect = true` is enabled in config.toml:

```
panic: interface conversion: docker.dockerFetcher is not remotes.ReferrersFetcher:
missing method FetchReferrers runtime/debug.Stack()
```

Fixed it by replacing all `github.com/containerd/containerd/remotes` package to
`github.com/containerd/nydus-snapshotter/pkg/remote/remotes` in `remote` package.

Fix #458

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-05-15 08:18:53 +00:00
taohong 6542781350 feat: support convertion to encrypted nydus image
When converting to nydus image, encrypt the bootstrap layer.

Signed-off-by: taohong <ht1135@foxmail.com>
2023-05-15 10:33:24 +08:00
Changwei Ge 70599d979b
Merge pull request #477 from containerd/dependabot/go_modules/github.com/docker/distribution-2.8.2incompatible
build(deps): bump github.com/docker/distribution from 2.8.1+incompatible to 2.8.2+incompatible
2023-05-12 11:02:13 +08:00
dependabot[bot] d5ad80c44d
build(deps): bump github.com/docker/distribution
Bumps [github.com/docker/distribution](https://github.com/docker/distribution) from 2.8.1+incompatible to 2.8.2+incompatible.
- [Release notes](https://github.com/docker/distribution/releases)
- [Commits](https://github.com/docker/distribution/compare/v2.8.1...v2.8.2)

---
updated-dependencies:
- dependency-name: github.com/docker/distribution
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-12 01:49:26 +00:00
Changwei Ge 895f77a612
Merge pull request #466 from jiangliu/daemon-mode
Maintain daemon mode information for each daemon instance
2023-05-10 19:17:27 +08:00
Jiang Liu 6109cdcb87 daemon: migrate boltdb from old version
Migrate boltdb from old version to add `DaemonMode` field to daemon
object.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-10 11:39:48 +08:00
Changwei Ge 1ba2505d20
Merge pull request #446 from sctb512/fix-optimizer-workflow
workflow: fix incorrect files number for optimizer test
2023-05-09 17:07:44 +08:00
Changwei Ge 21815f7fc3
Merge pull request #473 from AkihiroSuda/image-spec-v1.1.0-rc3
go.mod: github.com/opencontainers/image-spec v1.1.0-rc3
2023-05-09 16:08:14 +08:00
Akihiro Suda ce2216aa8d
go.mod: github.com/opencontainers/image-spec v1.1.0-rc3
Signed-off-by: Akihiro Suda <akihiro.suda.cz@hco.ntt.co.jp>
2023-05-09 16:11:23 +09:00
Bin Tang b3e676d20f workflow: fix incorrect files number for optimizer test
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-05-08 20:39:28 +08:00
Jiang Liu 5b9c751e16 daemon: record daemon mode on each instance
Currently the daemon mode is global and is recorded in manager, which
limits extensibility. So record daemon mode in every daemon instance,
so we can extend it later.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-08 19:21:33 +08:00
Jiang Liu 0167b96f15 cmd: introduce daemon mode `dedicated` as an alias for `multiple`
Introduce daemon mode `dedicated` as an alias for `multiple`.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-08 19:21:23 +08:00
imeoer 7f8a71976c
Merge pull request #469 from jiangliu/referrer
referrer: tune implementation details of referrer
2023-05-08 19:03:11 +08:00
Changwei Ge 3a30a15320
Merge pull request #468 from jiangliu/cache
cache: simplify cache manager by removing FsDriver
2023-05-08 17:37:37 +08:00
Jiang Liu 194ff48079 referrer: tune implementation details of referrer
Refine implementation of referrer by:
- avoid retry if error is not network related
- limit maximum size of manifest index blob
- remove partially downloaded meta blob

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-08 17:07:10 +08:00
Changwei Ge f9d21e3bdc
Merge pull request #470 from jiangliu/convert-permission
converter: restrict file permission to 0640
2023-05-08 16:41:20 +08:00
Jiang Liu c69ddddebc converter: restrict file permission to 0640
Restrict permission of files generated by converter from 0644 to 0640.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-07 23:00:25 +08:00
Jiang Liu 77dc73c8a6 cache: simplify cache manager by removing FsDriver
The FsDriver field is never used, so remove it.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-06 16:09:36 +08:00
imeoer 81765b5d11
Merge pull request #464 from jiangliu/config
config: enforce stricter validation rules and tune default config
2023-05-06 14:47:18 +08:00
Changwei Ge e732202729
Merge pull request #456 from adamqqqplay/improve-help-message
cmd: improve user interface for help message by add default text
2023-05-06 14:31:21 +08:00
Qinqi Qu e83562332d cmd: improve user interface for help message by add default text
1. Fix missing default values in the --help after v0.6.1.
2. Sort out some usage information.

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-05-06 14:16:11 +08:00
Qinqi Qu e80f79c715 pkg: introduce internal/constant package
Move some string constants in CLI config to a new package
for easier future refactoring.

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-05-06 14:14:42 +08:00
Jiang Liu a6edb14f08 config: enforce stricter validation rules and tune default config
Enforce stricter validation rules and tune default configuration in
misc/snapshotter/config.toml

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-06 13:52:30 +08:00
Changwei Ge 2455464868
Merge pull request #460 from adamqqqplay/update-test-coverage
action: update workflow to block low unit test coverage code
2023-05-06 09:27:08 +08:00
Changwei Ge 9144aa3e13
Merge pull request #463 from jiangliu/cmd-help
cmd: refine command line help messages and error messages
2023-05-05 13:06:45 +08:00
Changwei Ge c7e1bdf2b9
Merge pull request #462 from jiangliu/daemon-states
manager: simplify implementation of DaemonStates
2023-05-05 13:06:13 +08:00
Jiang Liu f435d5c033 manager: simplify implementation of DaemonStates
Simplify implementation of DaemonStates by removing field `daemons`.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-05 11:58:37 +08:00
Jiang Liu 10867a8906 cmd: refine command line help messages and error messages
Refine command line help messages and error messages.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-05 11:08:04 +08:00
Changwei Ge 02c6e93531
Merge pull request #461 from jiangliu/toc-size
Limit the maximum size of "Table of Content" in nydus data blobs
2023-05-05 10:47:49 +08:00
Jiang Liu 039145e34f converter: limit max size of ToC table to 1MB
Limit max size of ToC to 1MB, to avoid consuming too much memory
by malformed images.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-04 13:53:52 +08:00
Jiang Liu 05db24ce3a converter: improve the way to handle compression flags for ToC
Improve the way to handle compression flags for ToC, also add definition
for CompressorLz4Block.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-05-04 12:20:49 +08:00
Qinqi Qu 689c25ce3c action: update workflow to block low unit test coverage code
1. The project's unit test coverage cannot be reduced by more than 0.5%.
2. The unit test coverage of each patch must be higher than 75%.

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-04-28 11:23:12 +08:00
imeoer f89d069747
Merge pull request #453 from changweige/mounts-empty-parent
Support using nydus-snapshotter as Builkdit's oci-woker-snapshotter to gain lazyload when building images
2023-04-24 15:53:59 +08:00
Changwei Ge 7b32383d61 also try to get image ref by stargz specific labels
Buildkit does not pass labels in containerd's fashion.
So we have to use stargz specific lables until the labels
are generalized.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-24 12:04:52 +08:00
Changwei Ge 8635b16683 don't return remote mounts if clients is unpacking to the snapshot
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-24 12:04:52 +08:00
Changwei Ge dc477edd47 only try to travers referrers when it is enabled
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-24 12:04:35 +08:00
Changwei Ge cd2803cf30 allow empty parent when invoking Mounts
Nydus-snapshotter's may invoke Mounts without parent specified

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-24 12:04:35 +08:00
Changwei Ge f848ed11a8
Merge pull request #455 from containerd/dependabot/go_modules/github.com/docker/docker-23.0.3incompatible
build(deps): bump github.com/docker/docker from 23.0.1+incompatible to 23.0.3+incompatible
2023-04-24 10:28:28 +08:00
dependabot[bot] 379c8768db
build(deps): bump github.com/docker/docker
Bumps [github.com/docker/docker](https://github.com/docker/docker) from 23.0.1+incompatible to 23.0.3+incompatible.
- [Release notes](https://github.com/docker/docker/releases)
- [Commits](https://github.com/docker/docker/compare/v23.0.1...v23.0.3)

---
updated-dependencies:
- dependency-name: github.com/docker/docker
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-04-24 02:18:13 +00:00
Changwei Ge 208c4017cf
Merge pull request #450 from sctb512/fix-optimizer-server-error
Avoid optimizer to use too much memory and improve error handling processes
2023-04-24 09:56:08 +08:00
Bin Tang 6e3992db3c workflow: fix incorrect result file name for optimizer
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:08:33 +08:00
Bin Tang e510907b93 optimizer: improve error handling processes for server
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:08:33 +08:00
Bin Tang 75bf0abc2d docs: add document about making result readable
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:08:33 +08:00
Bin Tang 8da4ff6337 misc: add readable item to optimizer config file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:08:33 +08:00
Bin Tang 702106cdfd optimizer: add option to make result readable
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:08:32 +08:00
Bin Tang 93623c47f7 fanotify: decode event one by one and write to csv format file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-23 21:06:34 +08:00
Changwei Ge ccd366f636
Merge pull request #445 from Desiki-high/batchsize
feat: support the arg batch-size for small chunks mergence
2023-04-23 16:04:09 +08:00
Desiki-high 56242259d4 feat: add the arg batch-size
to support the feature of small chunks mergence  in nydus, we need to add the arg batch-size

Signed-off-by: Desiki-high <ding_yadong@foxmail.com>
2023-04-20 09:33:03 +08:00
Bin Tang 4201b28f25 tools: send event information one by one
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-18 15:12:34 +08:00
Bin Tang 83ceb6f0d7 tools: avoid to create new thread for signal hook
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-04-18 15:12:34 +08:00
imeoer d4ccae07e7
Merge pull request #447 from changweige/view-support-2
support nydus image topmost layer view
2023-04-18 10:02:25 +08:00
Changwei Ge 1db810a602 wait daemon ready when invoking Prepare
clients like ctr is using Prepare to generate a
active snapshot when mounting an image to host.
But containerd is only only writing contents to
the active snapshot.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-17 10:26:58 +08:00
Changwei Ge 66cfa188c1 support nydus image topmost layer view
Without inline layer fs meta blob, we can still support the
topmost View for nydus image. It is useful for Buildkit to use
nydus image as the base image.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-17 10:26:58 +08:00
Changwei Ge ab8c6fef8d
Merge pull request #426 from imeoer/support-referrers
experimental referrers support
2023-04-17 10:18:59 +08:00
Yan Song 1ec20892a5 vendor: port pkg/remote/remotes codes
To use containerd remote referrers API in advance.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-04-14 07:22:32 +00:00
Yan Song 751acbf306 support reference type for nydus image
Add the new `enable_referrers` option in config.toml, to enables trying
to fetch the nydus image associated with the OCI image and run it.

This feature relies on the support of OCI reference type. Currently, only
Harbor (>=v2.8) registry and ORAS registry support this. Additionally, we
need to rely on containerd's referrer fetcher interface, related links:

https://github.com/containerd/containerd/pull/7644
https://oras.land/cli/6_reference_types/

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-04-14 07:22:30 +00:00
imeoer 7a345f2464
Merge pull request #448 from jiangliu/null-features
converter: return null feature set when failed to detect version
2023-04-14 10:58:04 +08:00
imeoer 0e78aecfa9
Merge pull request #449 from jiangliu/nfile-position.patch
converter: fix a possible bug in type seekReader::Read()
2023-04-14 10:50:39 +08:00
Jiang Liu 496204be40 converter: fix a possible bug in type seekReader::Read()
Reader.ReadAt() may return bytes read less than len(buf), so fix it.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-04-14 00:05:01 +08:00
Jiang Liu 91d329a81f converter: return null feature set when failed to detect version
Return null feature set for safety when failed to detect nydus-image
version.

Signed-off-by: Jiang Liu <gerry@linux.alibaba.com>
2023-04-12 18:15:57 +08:00
imeoer cf6a8f723c
Merge pull request #434 from changweige/misc-impr
Misc improvements about enhancing nydus-snapshotter's stability and add more debug message
2023-04-12 14:49:43 +08:00
Changwei Ge fbfada655e wrap the logic that returns nydusd working status
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 14:10:18 +08:00
Changwei Ge ccd6f512fb refine doc for nydus image optimizer
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:51:51 +08:00
Changwei Ge 2eae17f761 enable golangci linter prealloc
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:51:51 +08:00
Changwei Ge c5b3956c2b readme: slightly refine readme description
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:51:51 +08:00
Changwei Ge b2e253aacf stop waiting for nydusd if it is already a zombie
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:51:51 +08:00
Changwei Ge 0ee689656c add helper to detect if process is a zombie one
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:50:51 +08:00
Changwei Ge 91a3cac9ec add capability to abort retrying for utility retry
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:50:51 +08:00
Changwei Ge 325b1ce802 print more information about nydus-snapshotter's work status
Most on what socket address it is relying on

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:50:51 +08:00
Changwei Ge 37e3c0b274 rename function SetupEnvironment to SetUpEnvironment
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-12 09:50:51 +08:00
Changwei Ge 397914dec8
Merge pull request #444 from adamqqqplay/add-helm-docs
docs: add helm quickstart link to deploy Dragonfly+Nydus
2023-04-11 11:31:39 +08:00
Qinqi Qu c27792f1f1 docs: add helm quickstart link to deploy Dragonfly+Nydus
1. add link in docs/run_nydus_in_kubernetes.md and README.md
2. adjusted the article structure of README.md

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-04-10 16:35:52 +08:00
Changwei Ge 887a3ed125 makefile: add target to build debug version of nydus-snapshotter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-07 14:17:15 +08:00
Changwei Ge c3f4ad57a4 only collect metrics for Ready daemons
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-04-07 14:17:15 +08:00
Changwei Ge 2f1d2fa661
Merge pull request #443 from adamqqqplay/upgrade-runc-and-protobuf
deps: upgrade runc and protobuf to resolve vulnerabilities
2023-04-04 18:43:18 +08:00
Qinqi Qu 6535bbf2b7 deps: upgrade runc and protobuf to resolve vulnerabilities
1. upgrade runc to v1.1.5
2. upgrade protobuf to v1.30.0

Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-04-04 16:34:37 +08:00
Changwei Ge 01d045f673
Merge pull request #440 from adamqqqplay/refine-readme
docs: add FAQ, Website and Quickstart link in README.md
2023-03-30 17:24:03 +08:00
Qinqi Qu 5bb861e54d docs: add FAQ, Website and Quickstart link in README.md
Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-03-30 11:32:52 +08:00
Changwei Ge bbf8cf7886
Merge pull request #436 from sctb512/not-add-null-server-to-mirror
Do not add server to mirror list
2023-03-29 20:28:45 +08:00
Bin Tang 2cebe490b3 daemonconfig: adjust test for mirror list without server
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-29 18:14:47 +08:00
Bin Tang 2c6be6694f daemonconfig: avoid to append server to mirror list
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-29 18:14:44 +08:00
Changwei Ge 71180668af
Merge pull request #432 from sctb512/remove-daemon-log-level
misc: remove log level item in daemon config
2023-03-22 13:47:31 +08:00
Bin Tang 6bca714c7a misc: remove log level item in daemon config
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-22 12:01:30 +08:00
imeoer 2ee4efdbef
Merge pull request #430 from changweige/add-link
add a link to introduction of zran
2023-03-21 10:53:52 +08:00
Changwei Ge e61b93d88f add a link to introduction of zran
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-21 09:42:40 +08:00
Changwei Ge dabb486dae
Merge pull request #425 from changweige/fill-default-address
fill default snapshotter's address
2023-03-21 09:17:43 +08:00
Changwei Ge 7ee5ff21a8
Merge pull request #427 from imeoer/converter-fix-history
[v1.7.2] converter: fix image history handle
2023-03-21 09:17:26 +08:00
imeoer 00757049e9
Merge pull request #423 from changweige/impr-cleanup
Simplify the logics preparing snapshots for containerd
2023-03-20 19:33:58 +08:00
Yan Song e9e2ad18c2 converter: fix image history handle
1. If the original image is already an OCI type, we should forcibly set the
   bootstrap layer to the OCI type.
2. We need to append history item for bootstrap layer, to ensure the history
   consistency, see:
   e5d5810851/manifest/schema1/config_builder.go (L136)

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-03-20 10:56:45 +00:00
imeoer 50f730e7f7
Merge pull request #418 from sctb512/release-static-package
Package optimizer binary when releasing new version
2023-03-20 16:42:20 +08:00
Changwei Ge fe47057ddd fill default snapshotter's address
Otherwise, snapshotter will listen on a random unix socket

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-20 16:09:05 +08:00
Bin Tang 674b6d8f48 workflow: add optimizer binary to release package
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-20 15:06:07 +08:00
Bin Tang 363a84d9ed Makefile: build optimizer for static release
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-20 15:04:53 +08:00
Bin Tang 96e21a45d1 misc: remove the index of optimizer nri plugin binary
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-20 15:03:46 +08:00
Changwei Ge b5be142542 refactor how snapshots are prepared
Simplify the logics preparing snapshots

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-20 14:37:07 +08:00
Changwei Ge 4cf68e0650 no need to check if timer is nil
Metrics timer can't be nil

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-20 14:30:08 +08:00
Changwei Ge 7127315fc6 no need to create root dir twice
As working environment is set up after processing parameters,
we don't have to create it twice

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-20 14:14:15 +08:00
imeoer 889ef1fdcd
Merge pull request #421 from changweige/set-fsdriver-default
set default value for fsdriver
2023-03-17 11:47:04 +08:00
Changwei Ge e8be81d724 set default value for fsdriver
So we can start nydus-snapshotter witout its toml config file
with minimal parameters

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-17 10:40:13 +08:00
Changwei Ge 97b1f0dd55
Merge pull request #413 from changweige/impr-optimizer
fix bugs in image optimizer and improve the code a bit
2023-03-16 18:54:42 +08:00
Changwei Ge 0173d4b52a
Merge pull request #419 from adamqqqplay/update-nydus-version
misc: update stable nydusd version v2.1.5 in Dockerfile and docs
2023-03-16 18:54:20 +08:00
Changwei Ge 808ae94a90
Merge pull request #416 from imeoer/converter-support-reference-type
remove useless blob manager
2023-03-16 18:53:35 +08:00
Yan Song 22421c4a4e remove useless blob manager
This feature is used to preheat the download of nydus blob data.
It is no longer used by any users and should be removed to
reduce the dead code.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-03-16 09:24:37 +00:00
Bin Tang b80a8948c9 Makefile: change clear to clean
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-16 17:12:38 +08:00
Qinqi Qu ebf8bb5855 misc: update stable nydusd version v2.1.5 in Dockerfile and docs
Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-03-16 17:05:11 +08:00
Changwei Ge d0d9f04c68
Merge pull request #414 from imeoer/converter-support-reference-type
converter: support OCI reference type
2023-03-16 11:02:41 +08:00
Changwei Ge dd17db413d optimizer: rename fanotify_event to FanotifyEvent
The renamed one is conforming rust naming style.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-16 10:57:53 +08:00
Changwei Ge 97a26d9fa7 optimizer: get rid of crate chrono
chrono is not necessary. We can just depend on
std::time to avoid unnecssary deps. Moreover, it is easier and clear
to show ecplased time than epouch time.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-16 10:57:53 +08:00
Changwei Ge 3a1e66c7aa optimizer: exit from epoll loop if it fails and alwasy close event.fd
We should always close event.fd even witn an error and handle
epoll error.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-16 10:34:57 +08:00
Changwei Ge bca74c9f6e optimizer: fix some typos
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-16 10:34:57 +08:00
Yan Song a8d0cecc44 converter: support OCI reference type
Associate a reference to the original OCI manifest, see the
`subject` field description in the doc:
https://github.com/opencontainers/image-spec/blob/main/manifest.md#image-manifest-property-descriptions

And if the converted manifest list contains only one manifest,
then convert it directly to manifest.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-03-15 08:40:11 +00:00
imeoer 557c5ab78b
Merge pull request #412 from sctb512/e2e-for-optimizer
add e2e test for optimizer in github workflow
2023-03-15 11:26:21 +08:00
Bin Tang a24ac731b0 workflow: add e2e test for optimizer
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-15 10:47:44 +08:00
imeoer e4f762ca16
Merge pull request #410 from changweige/update-deps
Update dependencies
2023-03-15 09:52:07 +08:00
Bin Tang 8c2d6ef8ca workflow: add ci test for building optimizer
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-15 09:42:29 +08:00
Bin Tang 9370b19fe9 misc: add test configuration file for optimizer
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-15 09:42:02 +08:00
Changwei Ge 77124cac59
Merge pull request #409 from sctb512/decode-json-from-reader
fanotify: decode json from reader to avoid specifying token
2023-03-13 16:39:27 +08:00
Bin Tang 8686d81159 fanotify: decode json from reader to avoid specifying token
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-13 16:26:49 +08:00
Changwei Ge 663b568080 update golang deps
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-13 15:06:38 +08:00
Changwei Ge 4fc1a44cac
Merge pull request #408 from imeoer/converter-fix
converter: fix handle of manifest index
2023-03-13 15:04:17 +08:00
Changwei Ge faa66ac989
Merge pull request #400 from sctb512/optimizer-output-to-json
add size and timestamp for monitored files and dump to json file
2023-03-13 14:52:10 +08:00
Bin Tang 6e0690a29b fanotify: unmarshal eventInfo and dump to json file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-13 14:07:28 +08:00
Bin Tang e81b3403cb tools: add timestamp and size for monitored file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-13 14:06:54 +08:00
Yan Song 80a70ea676 converter: fix handle of manifest index
- Skip to convert the nydus image manifest/index again;
- Handle the situation when the conversion did not occur;

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-03-13 02:56:46 +00:00
Changwei Ge 50c4b60f20
Merge pull request #407 from wllenyj/fix-root-path
fix containerd mount failed when root is a relative path
2023-03-13 10:55:29 +08:00
wanglei01 8096d25fa2 fix containerd mount failed when root is a relative path
When the Root path is set as a relative path, Prepare return a relative
path, the containerd will fail to mount.

Signed-off-by: wanglei01 <wllenyj@linux.alibaba.com>
2023-03-10 16:21:14 +08:00
Changwei Ge f77f8d1a97
Merge pull request #405 from wllenyj/fix-doc-link
docs: fix bad link
2023-03-09 18:32:50 +08:00
wanglei01 9b4c8b9043 docs: fix bad link
Signed-off-by: wanglei01 <wllenyj@linux.alibaba.com>
2023-03-09 18:16:42 +08:00
Changwei Ge 24b888fb0e
Merge pull request #403 from imeoer/converter-parent-bootstrap
converter: support parent bootstrap for merge
2023-03-08 16:57:27 +08:00
Changwei Ge a2c67a5096
Merge pull request #401 from sctb512/load-mirrror-config-for-target-host
daemonconfig: only load mirrorsConfig for target host
2023-03-08 16:56:29 +08:00
Yan Song 9d5bd28918 converter: support parent bootstrap for merge
Add `ParentBootstrapPath` option for `converter.Merge` method, the
option holds the bootstrap path of a parent image.

This option allow to merge multiple bootstraps of upper layer with
the bootstrap of a parent image, so that we can implement container
commit operation for nydus image.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-03-08 03:18:34 +00:00
Bin Tang 899465112a daemonconfig: update TestLoadMirrorConfig for new logic
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-07 20:45:01 +08:00
Bin Tang 987fdc81b1 daemonconfig: only load mirrorsConfig for target host
Now, we load all the mirrorsConfig from directory. And the mirrorsConfig
is available to all hosts. This is not compatible with containerd's
mirror configuration. This PR tries to solve this issue.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-07 19:59:25 +08:00
imeoer 1e7a12e61c
Merge pull request #343 from changweige/enhance-linters
enable more golang linters
2023-03-06 16:25:24 +08:00
Changwei Ge 43a0b7a1ee silent warnings from converter package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 15:58:53 +08:00
Changwei Ge 4ed68e774a silent warnings from fanotify package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 15:58:53 +08:00
Changwei Ge 900338f55d silent warnings from config package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 15:58:53 +08:00
Changwei Ge 4f368b906a enable more golang linters
In addition, fix linter warnings reported by new linter.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 15:58:53 +08:00
Changwei Ge a7897816fd
Merge pull request #399 from changweige/nydus-bin-can-not-exist
allow nydusd and nydus-image absence in PATH
2023-03-06 15:56:18 +08:00
Changwei Ge c6dd694525 allow nydusd and nydus-image absence in PATH
Nydusd and nydus-image's path be customized.
It should throw error if they can't be found.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 15:36:18 +08:00
Changwei Ge b0c8c5d1ac
Merge pull request #364 from changweige/fscache-e2e
Fscache e2e
2023-03-06 15:27:45 +08:00
imeoer 5e4b493eb4
Merge pull request #387 from changweige/support-cri-v1
auth: use new stargz crialpha package
2023-03-06 14:17:39 +08:00
Changwei Ge b397935dcb upgrade all the dependences
By perform go get -u ./...

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:24:45 +08:00
Changwei Ge 01083a1be2 auth/cri: adopt stable cri api v1
K8s 1.26 has dropped alpha CRI api. Snapshotter now should
adopt it.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:16:06 +08:00
Changwei Ge 9e9ecf9688 add optimizer's cargo target dir to .gitignore
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:16:06 +08:00
Changwei Ge a830cf857c fix golangci-lint warning in registry package
pkg/utils/registry/registry.go:77:14: SA1019: transport.New is deprecated: Use NewWithContext. (staticcheck)
		rTr, err = transport.New(
		           ^
make: *** [Makefile:108: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:16:06 +08:00
Changwei Ge 16bc577c0e auth: use new stargz crialpha package
Stargz-snapshotter has adopted the CRI api v1 and
keeps back-compatibility with api v1alpha2. In order to upgrade
containerd and stargz dependency. Let's adopt the new
crialpha packge and upgrade all the dependecies.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:16:06 +08:00
Changwei Ge 837af009b7
Merge pull request #396 from changweige/cleanup-layout
clean up project folder layout
2023-03-06 13:13:09 +08:00
Changwei Ge 5993cf1a17 clean up project folder layout
Move some package to internal folder

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 13:03:41 +08:00
Changwei Ge 1e429ea62b
Merge pull request #395 from changweige/refine-optimizer-doc
refine containerd nri plugin optimizer docs
2023-03-06 11:54:19 +08:00
Changwei Ge cbb02e3c2b
Merge pull request #393 from sctb512/fix-incorrect-configuration
config: avoid to use default dir if root is valid
2023-03-06 11:53:08 +08:00
Changwei Ge 83b6745f99 refine containerd nri plugin optimizer docs
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 11:45:14 +08:00
Bin Tang fbb7a33212 config: add test for ProcessConfigurations
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-06 10:32:29 +08:00
Bin Tang e215ba03fb config: add test for MergeConfig
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-06 10:32:11 +08:00
Bin Tang 318f8b04c4 config: avoid to use default dir if root is valid
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-06 10:30:04 +08:00
Changwei Ge 5e6474ef1c
Merge pull request #394 from sctb512/fix-incorrect-nydusd-number
daemon: increase retry times to avoid premature returns
2023-03-06 10:08:55 +08:00
Bin Tang 3052215372 daemon: increase retry times to avoid premature returns
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-06 09:57:21 +08:00
Changwei Ge cd6a0a2925 add failover e2e test for fscache driver
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-03-06 09:54:16 +08:00
Changwei Ge 0a85891473
Merge pull request #397 from sctb512/add-log-to-stdout-to-toml
misc: add log_to_stdout to snapshotter's sample toml file
2023-03-06 09:27:36 +08:00
Bin Tang 13da9a8f11 misc: add log_to_stdout to snapshotter's sample toml file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-03-05 11:54:27 +08:00
Changwei Ge d925eb5394
Merge pull request #391 from PKizzle/fix-cmdline-toml-override
Fix override for log-to-stdout cmdline option
2023-03-05 11:38:05 +08:00
Philipp Kolberg be666b790f
Undo log_to_stdout removal from toml config 2023-03-03 19:43:06 +01:00
Philipp Kolberg 989869f3c3
Fix TestLoadSnapshotterTOMLConfig test 2023-03-02 17:05:13 +01:00
Philipp Kolberg 674836e7b8
Fix dependencies 2023-03-02 16:56:59 +01:00
Philipp Kolberg 8856ff2b49
Fix cmdline log-to-stdout override 2023-03-02 16:48:20 +01:00
Changwei Ge 2fc62a6795
Merge pull request #385 from mofishzz/hjn/live-upgrade
Fix some small problems in the live upgrade procedure
2023-02-27 16:18:55 +08:00
imeoer 5338178927
Merge pull request #294 from loheagn/cs-proxy
converter: add stream mode to `Unpack`
2023-02-27 12:08:40 +08:00
Huang Jianan c1971c39fb daemon: send states when umount
So we can get the correct state after umount.

Signed-off-by: Huang Jianan <jnhuang@linux.alibaba.com>
2023-02-27 11:14:23 +08:00
Huang Jianan c3bacbed9b system: send states before takeover
Send states to the new daemon to restore.

Signed-off-by: Huang Jianan <jnhuang@linux.alibaba.com>
2023-02-27 11:14:23 +08:00
Huang Jianan 038023a0f2 system: retain shared daemon when live upgrade
By this we can use the new daemon to handle the upcomming mounts.

Signed-off-by: Huang Jianan <jnhuang@linux.alibaba.com>
2023-02-27 11:14:23 +08:00
Huang Jianan 93b0e9ecc6 system: fix deadlock when live upgrade
We observe the following deadlock when live upgrade:

- sc.upgradeDaemons
  - sc.manager.Lock()
    - manager.upgradeNydusDaemon
      - m.mu.Lock()

Let's fix it.

Signed-off-by: Huang Jianan <jnhuang@linux.alibaba.com>
2023-02-27 11:14:19 +08:00
Nan Li a9c38d037a converter: add stream mode to `Unpack`
This patch adds stream mode to `Unpack`, which avoids to unpack the blob data to the local disk but sets up a local http server to proxy the blob data reading.

Signed-off-by: Nan Li <loheagn@icloud.com>
2023-02-26 21:27:31 +08:00
imeoer 63c4a145db
Merge pull request #378 from sctb512/validate-mirrors-config-directory
config: validate mirrors directory when starting snapshotter
2023-02-24 19:56:17 +08:00
Changwei Ge b85715e1d1
Merge pull request #380 from sctb512/fix-toml-file-not-work
Fix the problem of snapshotter's toml configuration file not working
2023-02-24 18:48:59 +08:00
Changwei Ge 0f833e8b6e
Merge pull request #383 from containerd/dependabot/go_modules/github.com/containerd/containerd-1.6.18
build(deps): bump github.com/containerd/containerd from 1.6.17 to 1.6.18
2023-02-24 18:48:07 +08:00
Changwei Ge f4b7756474
Merge pull request #384 from containerd/dependabot/go_modules/golang.org/x/net-0.7.0
build(deps): bump golang.org/x/net from 0.5.0 to 0.7.0
2023-02-24 18:47:06 +08:00
Bin Tang d67faf9d27 config: validate mirrors directory when starting snapshotter
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 18:42:48 +08:00
dependabot[bot] 89ec1e8cf2
build(deps): bump golang.org/x/net from 0.5.0 to 0.7.0
Bumps [golang.org/x/net](https://github.com/golang/net) from 0.5.0 to 0.7.0.
- [Release notes](https://github.com/golang/net/releases)
- [Commits](https://github.com/golang/net/compare/v0.5.0...v0.7.0)

---
updated-dependencies:
- dependency-name: golang.org/x/net
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-24 10:26:18 +00:00
dependabot[bot] f6d13eab92
build(deps): bump github.com/containerd/containerd from 1.6.17 to 1.6.18
Bumps [github.com/containerd/containerd](https://github.com/containerd/containerd) from 1.6.17 to 1.6.18.
- [Release notes](https://github.com/containerd/containerd/releases)
- [Changelog](https://github.com/containerd/containerd/blob/main/RELEASES.md)
- [Commits](https://github.com/containerd/containerd/compare/v1.6.17...v1.6.18)

---
updated-dependencies:
- dependency-name: github.com/containerd/containerd
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-24 10:24:03 +00:00
Changwei Ge c1b1104b92
Merge pull request #382 from containerd/dependabot/cargo/tools/optimizer-server/nix-0.20.2
build(deps): bump nix from 0.19.1 to 0.20.2 in /tools/optimizer-server
2023-02-24 18:21:04 +08:00
dependabot[bot] 0392d2bf13
build(deps): bump nix from 0.19.1 to 0.20.2 in /tools/optimizer-server
Bumps [nix](https://github.com/nix-rust/nix) from 0.19.1 to 0.20.2.
- [Release notes](https://github.com/nix-rust/nix/releases)
- [Changelog](https://github.com/nix-rust/nix/blob/master/CHANGELOG.md)
- [Commits](https://github.com/nix-rust/nix/compare/v0.19.1...v0.20.2)

---
updated-dependencies:
- dependency-name: nix
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-02-24 10:11:49 +00:00
Changwei Ge 6876c4f5cf
Merge pull request #349 from sctb512/generate-accessed-files-list
generate accessed files list for container with NRI plugin
2023-02-24 18:07:20 +08:00
Bin Tang 5abe19811a optimizer: redirect logs to stdout as well
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:54:26 +08:00
Bin Tang 5f5ea66abd docs: add document about optimizer
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:54:26 +08:00
Bin Tang c3efe9c67a optimizer: kill server of subprocess completely
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:54:26 +08:00
Bin Tang 093bf93f86 Makefile: add install-optimizer subcommand for make
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:54:26 +08:00
Bin Tang e378decded update go.mod to adapt optimizer client
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:54:26 +08:00
Bin Tang 541132d328 Makefile: support to build optimizer-nri-plugin
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Bin Tang 0b00e5147d misc: add configuration example for optimizer NRI plugin
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Bin Tang 1f6010c57c cmd: add optimizer client as a NRI plugin
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Bin Tang 2eeec3d1f8 pkg: add fanotify package
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Bin Tang 3ec6a695f8 Makefile: support to build optimizer server
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Bin Tang ad4d0919e2 tools: optimizer server running in target mount namespace
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:43:09 +08:00
Changwei Ge 470f4a61ef
Merge pull request #381 from sctb512/fix-no-such-directory-error
system: fix no such file or directory error
2023-02-24 17:34:40 +08:00
Bin Tang 04e48e6f89 tests: modify TestNewFlags for flags without default value
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:32:44 +08:00
Bin Tang 0f47bf8827 tests: remove log_to_stdout from toml file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:32:23 +08:00
Bin Tang 65be82cd64 system: fix no such file or directory error
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 17:19:06 +08:00
Bin Tang c07eaa4813 config: avoid to load log_to_stdout from toml file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 16:48:24 +08:00
Bin Tang 76a3a8b854 config: add test for loaded configuration with parsed arguments
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 16:45:40 +08:00
Bin Tang d6a58fc71f config: remove default value of cmd arguments
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-24 16:44:21 +08:00
imeoer 468c222322
Merge pull request #377 from changweige/only-count-nydus-layers
only count nydusd local cache if it a nydus layer
2023-02-24 15:16:07 +08:00
Changwei Ge e410251a2c only count nydusd local cache if it a nydus layer
Sandbox container image may not be downloaded through CRI flow.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-24 12:13:01 +08:00
imeoer 222d2b12cc
Merge pull request #363 from changweige/fail-start-metrics-address
fail the snapshotter immediately if metrics server can't be bound
2023-02-24 11:46:46 +08:00
Changwei Ge 7354a06bb8 fail the snapshotter immedidately if metrics server can't be bound
We'd better to exit from snapshotter's startup if the metrics server
address can't be bound.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-24 11:34:14 +08:00
Changwei Ge e0e8b0485f
Merge pull request #375 from sctb512/add-nydusd-memory-usage-metric
metrics: export nydus daemon memory usage (RSS)
2023-02-24 11:27:50 +08:00
Changwei Ge d1f5b25763
Merge pull request #352 from imeoer/converter-speedup
converter: speed up conversion
2023-02-24 09:40:56 +08:00
Yan Song fe4c07c256 remove useless constant oldDefaultRootDir
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 10:02:14 +00:00
Yan Song 7850fe7eae converter: make feature detection strong
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 10:00:09 +00:00
Yan Song e57bebe1d8 converter: fix prefetch patterns option
The `PrefetchPatterns` option should be paased to the builder (nydus-image)
merge subcommand, otherwise the prefetch feature table will not work in
the final bootstrap (used in nydus image).

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 10:00:09 +00:00
Yan Song eb2bc66ef6 converter: support feature fallback by detecting builder version
We should fallback some cli flags automatically for older versions of builder.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 10:00:09 +00:00
Yan Song 7346f66f84 converter: make rafs fs version v6 as default
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 09:59:22 +00:00
Yan Song b3667ff8fe converter: support features option for builder
The `Features` option enables feature collection for nydus-image builder.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 09:59:22 +00:00
Yan Song f54893c775 converter: fix hang when fail to invoke builder
The Pack conversion workflow will hang on `io.Copy` once the
builder execution failed, this patch fixes it.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 09:59:22 +00:00
Yan Song 556be15cf4 converter: speed up conversion
Support the new option `--type tar-rafs` of builder for Pack method in converter
package, enables converting OCI tar blob stream into nydus blob directly,
eliminating the need to decompress it to a local directory first, thus
greatly accelerating the pack process.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-23 09:59:22 +00:00
Bin Tang 688bab99b9 metrics: export nydus daemon memory usage (RSS)
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-23 17:28:57 +08:00
Changwei Ge 411dff6d1f
Merge pull request #374 from sctb512/fix-incorrect-rss-value
metrics: fix incorrect rss value
2023-02-23 16:59:09 +08:00
Bin Tang 99c22a5a32 metrics: fix incorrect rss value
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-23 16:15:05 +08:00
imeoer 9350a9735d
Merge pull request #372 from sctb512/add-pprof-for-snapshotter
Add pprof HTTP server for snapshotter
2023-02-23 14:57:07 +08:00
imeoer 439926d310
Merge pull request #371 from changweige/upgrade-golang
upgrade project's golang version to 1.19.6
2023-02-23 14:10:48 +08:00
Changwei Ge 7b32b0c6db upgrade project's golang version to 1.19.6
Thus to catch up with containerd

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-23 10:53:55 +08:00
imeoer b26eedd735
Merge pull request #366 from changweige/system-diagnose-print-image-id
print instance image id from system diagnose API
2023-02-23 10:50:31 +08:00
imeoer cb7a98594c
Merge pull request #373 from changweige/e2e-upgrade-nydusd
upgrade nydusd version used by e2e test to 2.1.4
2023-02-23 10:44:34 +08:00
Changwei Ge ed8f638791 upgrade nydusd version used by e2e test to 2.1.4
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-23 10:32:38 +08:00
Bin Tang 335b16922f modify new http listener function to be distincted with pprof
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:26:16 +08:00
Bin Tang fdc9ffcd5e config: modify test function to adapt pprof address
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:56 +08:00
Bin Tang 2c63a329a4 misc: add pprof_address in sample toml file
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:52 +08:00
Bin Tang f8356407a8 snapshot: start pprof HTTP server when enable it
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:49 +08:00
Bin Tang 021dfb70df pkg: add pprof package for pprof server
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:44 +08:00
Bin Tang 0324f8f167 config: add a function to get pprof address
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:39 +08:00
Bin Tang 8c15eadeb3 config: add pprof_address item
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-22 17:21:24 +08:00
Changwei Ge 9fb0d50392
Merge pull request #368 from changweige/print-error-digest
print the invalid blob digest to log
2023-02-22 15:01:37 +08:00
Changwei Ge 87c8299b94 print the invalid blob digest to log
For debug purpose.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-22 14:48:11 +08:00
imeoer 16ca123667
Merge pull request #367 from changweige/fix-system-default-socket
fix system controller default socket address
2023-02-22 14:11:24 +08:00
Changwei Ge cd29966cfd fix system controller default socket address
The default address should locate at
/var/run/containerd-nydus/system.sock

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-22 13:23:28 +08:00
Changwei Ge 366f3e88eb print instance image id from system diagnose API
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-22 13:15:11 +08:00
Changwei Ge aaed554215
Merge pull request #355 from changweige/chge/install-not-overwrite-config
don't overwrite existed user's configuration file
2023-02-21 10:00:29 +08:00
Changwei Ge 869ac963e0 don't overwrite existed user's configuration file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-20 19:42:00 +08:00
imeoer d137adb0cd
Merge pull request #362 from changweige/no-umount-fscache
only do umount against nydusd that has host mounted
2023-02-20 17:33:24 +08:00
Changwei Ge df2f748db3 only do umount against nydusd that has host mounted
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-17 17:32:44 +08:00
Changwei Ge 302c0c3529
Merge pull request #356 from changweige/fix-broken-doc-link
fix a broken doc link to the example configuration file
2023-02-17 14:22:31 +08:00
Changwei Ge bb28284375
Merge pull request #358 from aniruddha2000/ani/k8s-gcr-io-to-registry-k8s-io
Migrate from k8s.gcr.io to registry.k8s.io
2023-02-17 12:55:52 +08:00
Aniruddha Basak 5180464e30
Migrate from k8s.gcr.io to registry.k8s.io
Signed-off-by: Aniruddha Basak <codewithaniruddha@gmail.com>
2023-02-17 09:47:24 +05:30
Changwei Ge 16699aee28 fix a broken doc link to the example configuration file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-16 16:33:45 +08:00
imeoer b010060140
Merge pull request #353 from sctb512/fix-unused-variable
daemonconfig: remove unused variable
2023-02-14 11:33:47 +08:00
imeoer 7b230cb3aa
Merge pull request #354 from sctb512/disable-display-about-mkdir
Makefile: disable display about mkdir
2023-02-14 11:33:31 +08:00
Bin Tang 50e43009ab Makefile: disable display about mkdir
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-14 11:23:29 +08:00
Bin Tang 457cf3713c daemonconfig: remove unused variable
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-14 11:18:54 +08:00
Changwei Ge d78c617954
Merge pull request #351 from imeoer/label-handler
export label and handler defined in containerd
2023-02-13 10:25:37 +08:00
Yan Song d959c58643 export label and handler defined in containerd
See https://github.com/containerd/containerd/pull/8054

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-12 13:05:08 +00:00
Yan Song c437387fb8 mod: bump containerd v1.6.17
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2023-02-12 13:05:06 +00:00
imeoer 0b379b040b
Merge pull request #344 from changweige/add-docs
add brief introduction on metrics and diagnose methods
2023-02-08 10:04:31 +08:00
imeoer 2d9c187c99
Merge pull request #346 from changweige/mark-stargz-as-experimental
mark stargz configuration as experimental
2023-02-08 10:00:23 +08:00
Changwei Ge 48e9c7cb4d add brief introduction on metrics and diagnose methods
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-08 09:43:38 +08:00
Changwei Ge 8b3f9dbd09 mark stargz configuration as experimental
As the stargz compatiblity feature is not production ready
 and reliable enought.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-07 19:29:59 +08:00
imeoer 36e00c2c77
Merge pull request #345 from changweige/enhance-system-controller
enable system controller config
2023-02-07 14:35:00 +08:00
Changwei Ge 75493b1c3f
Merge pull request #348 from sctb512/fix-daemon-null-version
update daemon version when getting state
2023-02-07 10:06:43 +08:00
Changwei Ge 356cc07b38 enable system controller config
1. move system controller config to a dedicated struct
2. capable of configuring daemon cpu profile duration.
3. capable of configuring system controller address path

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-07 09:53:07 +08:00
Bin Tang 7e5aa930c4 metrics: fix negative numbers for nydusd counts
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 21:06:31 +08:00
Bin Tang a6f5bcf92f update daemon version when getting state
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 21:05:14 +08:00
Changwei Ge fcca6f9344
Merge pull request #347 from sctb512/add-doc-for-hot-update-mirror-conf
doc: add document about hot update mirror configurations
2023-02-06 18:47:03 +08:00
Bin Tang 1e9b674b96 doc: add document about hot update mirror configurations
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 17:40:28 +08:00
Changwei Ge 4a92a52e67
Merge pull request #342 from sctb512/modify-mirror-without-reload-service
config: support configuring mirror registry without reloading snapshotter
2023-02-06 14:48:23 +08:00
Bin Tang 752f75d0ec test: modify test for loading toml to adjust mirror configuration
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 14:26:14 +08:00
Bin Tang 63293a782d misc: add mirror configuration directory for config.toml
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 14:26:14 +08:00
Bin Tang 234d30529e config: add test for loading mirror configuration
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 14:26:14 +08:00
Bin Tang 4f394c8b9a Makefile: create default directory for mirrors configuration
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 14:26:14 +08:00
Bin Tang c0ad31e7ba config: support configuring mirror registry without reloading snapshotter
Now, the mirror registry is configured with nydusd config file.
Reloading service is needed if we modify it after the nydus-snapshotter running.

This commit solves this problem.
Snapshotter will overwrite the daemon's mirror configuration
if the values loaded from this directory are not null before starting a daemon.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-02-06 14:26:09 +08:00
imeoer 13a9e0565d
Merge pull request #337 from changweige/arrange-docs
arrange docs after some cli parameters are deleted
2023-02-03 15:29:21 +08:00
Changwei Ge a802abd0d0 arrange docs after some cli parameters are deleted
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-03 14:47:44 +08:00
imeoer 135d9d9566
Merge pull request #339 from changweige/refine-cli-help
refine CLI help messages
2023-02-03 11:48:41 +08:00
imeoer 089c6f54d9
Merge pull request #340 from changweige/impr-systemd
let systemd service adapt the new toml configuration
2023-02-03 11:47:26 +08:00
Changwei Ge 557de39ffe refine CLI help messages
Make them more suggestive

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-02-02 16:34:44 +08:00
Changwei Ge dfb3621bdb let systemd service apdat the new toml configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-31 11:45:29 +08:00
Changwei Ge 3d37ee2f68
Merge pull request #338 from changweige/fscache-enforce-shared
let fscache driver enforce shared daemon mode forcefully
2023-01-31 11:05:43 +08:00
Changwei Ge f0c2bde324 let fscache driver enforce shared daemon mode forcefully
It will be more friendly to users by hiding some inner details

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-31 10:18:14 +08:00
imeoer 89aa69ee36
Merge pull request #336 from changweige/remove-other-cli-parameters
Remove the other cli parameters
2023-01-31 09:46:54 +08:00
Changwei Ge eba5538d27 move recover poliy parser to config package
It is a more sutible package to accommodate the logics

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 19:10:51 +08:00
Changwei Ge 1eadfda7e3 set daemon recover policy default value to restart
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 15:22:44 +08:00
Changwei Ge 22ed95f2db let e2e test adapt new toml snapshotter's config file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 15:22:44 +08:00
Changwei Ge bc59fe5a30 misc arrangement for cli parameters
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge 813c9752b6 remove deprecated cli parameters alias
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge 4d9c7897e2 remove cli parameter `metrics-address`
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge 5ee075d19d remove deprecated cli parameter `shared-daemon`
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge 3aff363011 remove cli parameter `recover-policy`
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge 5155ec64d8 remove cli parameter `enable-system-controller`
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
Changwei Ge dd8d945358 remove parameter `enable-nydus-overlayfs`
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 11:04:05 +08:00
imeoer 962358f774
Merge pull request #335 from changweige/metrics-config
move metrics config to a separated section
2023-01-30 10:57:25 +08:00
Changwei Ge 04309e3c3d move metrics config to a separated section
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-30 10:27:19 +08:00
imeoer 69c9c6bb85
Merge pull request #330 from changweige/remove-more-cli-parameters-2
Remove CLI K8s auth passing related parameters
2023-01-30 10:24:37 +08:00
Changwei Ge 02475bd9d7 validate cacheManager configurations
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge 847bbeac04 add method to merge default config and input config file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge ae558bd16c Use snapshotter's config only after it's successfully loaded
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge 8c0ea41cea let k8s e2e test apdapt toml configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge fc9ad3c06d fix k8s e2e test containerd template configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge 236ea3619f remove cli parameters about k8s auth passing
They should configured in new TOML based configuration file now.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge 72005b97d3 validate if cri and kubeconfig auth methods are set at the same time
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 10:12:22 +08:00
Changwei Ge fb65c223c0
Merge pull request #327 from changweige/update-more-e2e-deps
Update more e2e dependencies
2023-01-23 10:11:39 +08:00
Changwei Ge a5ec097bd0
Merge pull request #333 from adamqqqplay/update-readme
docs: add badges and update community description
2023-01-23 09:54:43 +08:00
Changwei Ge 94e4b13100 fix that e2e test mirror downloads sources build-arg is wrongly passed
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 09:52:44 +08:00
Changwei Ge 059b918973 update more e2e test deps
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-23 09:52:29 +08:00
Qinqi Qu 93e48c69eb docs: add badges and update community description
Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-01-20 23:16:56 +08:00
Changwei Ge e50f8e540d
Merge pull request #331 from sctb512/atomic-for-nydusd-count
metrics: make it atomic for nydusd count
2023-01-19 13:13:15 +08:00
Bin Tang 4105a1c638 metrics: make it atomic for nydusd count
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-19 11:59:15 +08:00
Changwei Ge 2ed90fe587
Merge pull request #324 from changweige/fix-daemon-event-metrics
fix that nydusd lifecycle event might be duplicated
2023-01-19 09:24:42 +08:00
Changwei Ge 3e7f76029b
Merge pull request #325 from changweige/add-committer
Invite Yan Song as nydus-snapshotter committer
2023-01-19 09:21:44 +08:00
Changwei Ge 872b31666c
Merge pull request #328 from changweige/root-dir-first
assign root dir in the first place when filling up defaults
2023-01-18 20:25:03 +08:00
Changwei Ge b462fea5df assign root dir in the first place when filling up defaults
As other default value may depend on root dir.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-18 16:50:12 +08:00
Changwei Ge bd3893c54f
Merge pull request #326 from changweige/fix-daemon-version-gorace
fix a gorace when retrieving Version from daemon object
2023-01-18 16:30:30 +08:00
Changwei Ge ae053f67a5 fix a gorace when retrieving Version from daemon object
go race detected
==================
WARNING: DATA RACE
Read at 0x00c0000bed48 by goroutine 34:
  github.com/containerd/nydus-snapshotter/pkg/metrics/collector.(*DaemonInfoCollector).Collect()
      /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/metrics/collector/daemon.go:33 +0x78
  github.com/containerd/nydus-snapshotter/pkg/manager.(*Manager).handleDaemonDeathEvent()
      /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/manager/manager.go:314 +0x212
  github.com/containerd/nydus-snapshotter/pkg/manager.NewManager.func1()
      /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/manager/manager.go:364 +0x39

Previous write at 0x00c0000bed48 by goroutine 88:
  github.com/containerd/nydus-snapshotter/pkg/manager.(*Manager).StartDaemon.func2()
      /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/manager/daemon_adaptor.go:97 +0x5d3

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-18 12:41:03 +08:00
Changwei Ge 69910d9821 maintainers: add a committer
Add Yan Song as a committer

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-18 11:02:23 +08:00
Changwei Ge 3c2b1f3f56 fix that nydusd lifecycle event might be duplicated
There is a race that multiple goroutines can all WaitUntilState()
at the same time and waiting for the same expected state. So they
can both escape from the very beginning state check ending up with
an extra event record.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-18 10:15:04 +08:00
Changwei Ge 677523e533
Merge pull request #321 from changweige/fix-docker-file
fix k8s e2e test docker file
2023-01-18 09:56:47 +08:00
Changwei Ge 3c56792180
Merge pull request #320 from changweige/remove-more-cli-parameters
Remove some cli parameters
2023-01-18 09:56:29 +08:00
Changwei Ge 187e180191 change the daemon mode to multiple for e2e test
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-18 09:36:00 +08:00
Changwei Ge f9fe9d4904 remove unused shell variable and env variable
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-17 10:51:24 +08:00
Changwei Ge 37caced77c
Merge pull request #322 from changweige/clean-up-diagram
rename fscache based architecture diagram
2023-01-17 10:49:38 +08:00
Changwei Ge 1e45f900b8 remove not frequently used CLI parameters from k8s e2e test
Parpare for making full use of toml based config file.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-17 10:45:07 +08:00
Changwei Ge ba540ec39a
Merge pull request #323 from changweige/cron-e2e-test
trigger e2e github action everyday
2023-01-17 10:33:45 +08:00
Changwei Ge 05a02d0f3a
Merge pull request #319 from changweige/update-test-infra
update e2e test nydusd deps
2023-01-17 10:30:25 +08:00
Changwei Ge 643757b7c2 trigger e2e github action everyday
Add a cron trigger to github action

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:47:37 +08:00
Changwei Ge 4a7c5f5915 rename fscache based architecture diagram
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:19:23 +08:00
Changwei Ge 7fd29b7047 remove not frequently used CLI parameters
Parpare for making full use of toml based config file.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:16:19 +08:00
Changwei Ge 6af02cc35d validate snapshotter's configuration after parsing
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:16:19 +08:00
Changwei Ge fbba504ec4 remove some CLI arguements which are not frequently used
This is the second stage for build nydus-snapshotter's own
configuration file

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:16:19 +08:00
Changwei Ge 92487ff731 no need to pass snapshotter's rootdir to logging setup
The default logDir is already decided when filling up
snapshotter's defaults config

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 19:16:19 +08:00
Changwei Ge b97e96b33e add method to validate snapshotter configuration file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 17:01:08 +08:00
Changwei Ge a4342655df update e2e test nydusd deps
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-16 16:09:02 +08:00
Changwei Ge c84085c52d
Merge pull request #314 from sctb512/use-fixed-nydus-version-to-avoid-github-limitation
misc: use fixed nydus version for E2E test
2023-01-16 16:01:11 +08:00
Changwei Ge 74a87b3b59
Merge pull request #317 from sctb512/avoid-collect-inflight-metrics
metrics: avoid to collect inflight metrics for fscache driver
2023-01-16 15:49:51 +08:00
Changwei Ge 636bb6c9e1
Merge pull request #318 from adamqqqplay/add-readme-badge
docs: add some badges in README.md
2023-01-16 15:43:25 +08:00
Qinqi Qu d10f0168ac docs: add some badges in README.md
Signed-off-by: Qinqi Qu <quqinqi@linux.alibaba.com>
2023-01-16 12:50:06 +08:00
Bin Tang 915190c9eb metrics: avoid to collect inflight metrics for fscache driver
Similar to FS metrics. The metrics for /api/v1/metrics/inflight
are in the RAFS of nydus daemon.
When the driver is fscache, there are no metrics in RAFS.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-16 03:15:27 +00:00
Bin Tang 8c1287a71b misc: use fixed nydus version for E2E test
The value of NYDUS_VERDION is null frequently if we request it from github API.
We cannot solve this issue by sleeping 1 second, because the next available time
is in the response headers and longer than 1 second.
The NYDUS_VERSION is not changed often, so we can fix it.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-13 19:56:38 +08:00
Changwei Ge 7e6afdb8e8
Merge pull request #313 from sctb512/avoid-collect-fs-metrics
metrics: avoid collect FS metrics for fscache driver
2023-01-13 16:24:52 +08:00
Bin Tang 8c748010ed metrics: avoid collect FS metrics for fscache driver
The metrics for /api/v1/metrics are in the RAFS of nydus daemon.
When the driver is fscache, there are no metrics in RAFS.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-13 08:11:57 +00:00
Changwei Ge 38ec2ed694
Merge pull request #308 from sctb512/add-nydusd-hang-IO-metric
metrics: add metrics for FS hang IOs
2023-01-13 15:47:08 +08:00
Changwei Ge 7ad68e58c4
Merge pull request #306 from changweige/config-file
nydus-snapshotter own configuration file
2023-01-13 15:31:23 +08:00
Changwei Ge 2e095fe4d8
Merge pull request #312 from sctb512/fix-github-workflow
misc: fix 404 for snapshotter dockerfile
2023-01-13 13:51:44 +08:00
Bin Tang af5d85da13 misc: fix 404 for snapshotter dockerfile
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-13 11:53:40 +08:00
Bin Tang e270c1e00d metrics: add metrics for FS hang IOs
Add the metric TotalHangIO to record the total hang IO counts of FS.
The inflight IOs data are from nydus daemon API /api/v1/metrics/inflight.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-12 16:59:06 +08:00
Changwei Ge 0a5e30d0a4 add test for toml based configuration file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-12 10:49:22 +08:00
Changwei Ge b41aa4148c remove useless log print
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-12 10:49:22 +08:00
Changwei Ge c26b887a97 add an example toml configuration file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-12 10:49:22 +08:00
Changwei Ge 0fbd52582a make directory for blob manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-12 10:49:22 +08:00
Changwei Ge 7af9bb0025 introduce toml based nydus-snapshotter configuration file
At present, nydus-snapshotter can only be configured by
command parameters which has reached a large number.
Using configuartion file would make deployment easier

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-12 10:49:22 +08:00
Changwei Ge 744cf77d94
Merge pull request #311 from sctb512/fix-unused-flag-metrics-file
command: remove unused flag metrics-file
2023-01-11 13:16:39 +08:00
Bin Tang cd64d1cad1 command: remove unused flag metrics-file
There is enough to export metrics via HTTP port. Therefore,
The flag to set metrics file path, metrics-file, is unused.
We could remove it.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-11 11:11:50 +08:00
Changwei Ge 66a0b6db7d
Merge pull request #309 from fengshunli/bump
update dependencies
2023-01-11 09:46:44 +08:00
Changwei Ge 54fe1f034c
Merge pull request #307 from sctb512/rename-percentage-metric
metrics: fix incorrect descriptions
2023-01-11 09:34:34 +08:00
fsl 475bcaf761 update dependencies
Signed-off-by: fsl <1171313930@qq.com>
2023-01-10 22:54:57 +08:00
Bin Tang 705fca62eb metrics: fix incorrect descriptions
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-10 15:57:00 +08:00
Changwei Ge 29a9e9080d
Merge pull request #305 from changweige/impr-e2e-test
e2e: provide a makefile parameters thus to replace test target images
2023-01-06 14:10:59 +08:00
Changwei Ge 541bf40443
Merge pull request #303 from changweige/fscache-failover
Support fscache nydusd failover
2023-01-05 20:19:37 +08:00
Changwei Ge c133ed71c4 e2e: disable stargz test until it works
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 18:56:25 +08:00
Changwei Ge 6447adad22 refine rafs instance GetMountpoint method usage comments
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 17:50:53 +08:00
Changwei Ge ec76199ad4 command fscache nydusd to send states for failover
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 17:50:53 +08:00
Changwei Ge 356eee9c83 e2e: provide a makefile paramter thus to replace test target images
So developers can replace the images' sources to boost test
procedure

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 17:47:06 +08:00
Changwei Ge 32ed88c4cf also provide supervisor to fscache nydusd
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 16:33:46 +08:00
Changwei Ge 866a6e46cc fix the order of debug message parameters
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 16:33:46 +08:00
Changwei Ge 521bb58620 print domain id and fscache id for debug purpose
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 16:33:46 +08:00
Changwei Ge 070e44849b fix typo for fscacheID
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2023-01-05 15:12:32 +08:00
Changwei Ge 634a0fa91b
Merge pull request #304 from sctb512/improve-fs-metrics
metrics: improve FS metrics and remove unused metrics
2023-01-05 10:31:36 +08:00
Bin Tang 6800021fea metrics: improve FS metrics and remove unused metrics
Improve FS metrics to collect histograms with labels.
Moreover, remove unused metric OpenFdCount.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-05 10:08:36 +08:00
Changwei Ge 8ab3fcf24f
Merge pull request #302 from sctb512/add-nydusd-version-metric
metrics: add nydus daemon version
2023-01-03 19:46:40 +08:00
Bin Tang 338b8fbce7 metrics: add nydus daemon version
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2023-01-03 19:05:13 +08:00
Bin Tang 2db28deaa6 metrics: improve daemon metrics
Remove some metrics that have been deleted in nydus.
Improve descriptions for daemon FS metrics.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-12-30 17:36:51 +08:00
Changwei Ge ef09f76791
Merge pull request #300 from liubin/docs/update-registry-auth
docs: add more details about how to use kubeconfig keychain
2022-12-30 15:51:49 +08:00
Changwei Ge e3ffe387cf
Merge pull request #301 from sctb512/support-warmup-config
config: add warmup option for nydus daemon
2022-12-30 15:35:54 +08:00
Bin Tang 8bc7891a14 config: add warmup option for nydus daemon
This is an experimental feature. With the warmup option,
the nydus daemon could cache more data on the local disk
to increase hit ratio.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-12-30 15:17:19 +08:00
Changwei Ge 2f2922d0bc
Merge pull request #298 from sctb512/support-http-metrics-server
metrics: support HTTP metrics server
2022-12-30 15:08:19 +08:00
bin liu 21f77f31df docs: add more details about how to use kubeconfig keychain
Add RBAC/ServiceAccount configs for kubeconfig keychain, and also add an
example of creating secret of dockerconfig.

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-30 14:59:03 +08:00
bin liu 9a43e012e2 docs: fix a typo
Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-30 14:59:03 +08:00
Bin Tang b2c5b61f27 metrics: support HTTP metrics server
Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-12-30 14:23:18 +08:00
Changwei Ge 908a5961fb
Merge pull request #297 from liubin/docs/run-in-k8s
docs: add docs for running nydus snapshotter in Kubernetes
2022-12-30 10:01:51 +08:00
bin liu 2ced0f8c4e docs: add docs for running nydus snapshotter in Kubernetes
This new document will describe how to create a local Kubernetes cluster
using kind and then deploy nydus snapshotter in the Kubernetes cluster.

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-29 17:55:07 +08:00
Changwei Ge d7eeb13a58
Merge pull request #296 from darfux/fix-extra-option-config
snapshot:remoteMounts: Load snapshot config under shared mode
2022-12-29 17:16:02 +08:00
Li Yuxuan d60e68db80 snapshot:remoteMounts: Load snapshot config under shared mode
When shared daemon is enabled, snapshot config uses `<daemon
id>/<snapshot id>/config.json` now.

Signed-off-by: Li Yuxuan <liyuxuan.darfux@bytedance.com>
2022-12-29 16:08:10 +08:00
Changwei Ge 053440cb6f
Merge pull request #295 from imeoer/refactor-converter-backend
converter: support more options
2022-12-28 17:47:37 +08:00
Yan Song f0e2a9df84 converter: support more options for pack
- Add `alignedChunk` option;
- Add `chunkSize` option;

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-28 03:46:03 +00:00
Yan Song 53dd21ddc1 converter: suport force push for backend
Allow forcing to push blobs even if they already exist in storage backend.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-28 03:46:03 +00:00
Yan Song 1180306618 converter: refactor backend interface
Always enable multipart upload for oss/s3, it make code cleaner.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-28 03:46:02 +00:00
Changwei Ge dadd2762f2
Merge pull request #293 from imeoer/converter-errdefs
converter: remove pkg/errdefs dependence
2022-12-22 16:37:55 +08:00
Yan Song b572e245d5 converter: fix possible panic when labels is nil
Prevent panic when use nil map (labels) returned by `readJSON` func.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-22 06:15:22 +00:00
Yan Song 4ebc81c801 converter: remove pkg/errdefs dependence
To reduce a external package for the users.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-22 03:40:55 +00:00
Changwei Ge b98a90caf1
Merge pull request #287 from changweige/fix-redirect-config
redirect nydusd and rafs instance configuration to new location
2022-12-22 10:33:31 +08:00
Changwei Ge 07d6352c80
Merge pull request #262 from kevinXYin/fscache_gc
Fscache gc
2022-12-22 10:30:54 +08:00
Xin Yin a9145a2215 call blob API to delete fscache blob files when remove image
delete fscache cache files for blobs and bootstrap when remove image.

Signed-off-by:Xin Yin <yinxin.x@bytedance.com>
2022-12-16 11:58:18 +08:00
Xin Yin 5647d3aabe fix paramters for DEL blob API in fscache shared domain mode
In fscache shared domain mode, before umount erofs we should call DELETE
blob API with domainId + fscacheId.

Signed-off-by Xin Yin <yinxin.x@bytedance.com>
2022-12-16 11:58:18 +08:00
Changwei Ge 84c74391ee
Merge pull request #285 from changweige/cleanup-fs-pkg
cleanup file system package
2022-12-15 16:29:37 +08:00
Changwei Ge 6c0b103f97
Merge pull request #290 from darfux/add-cri-auth-e2e
test:e2e: Add cri auth test
2022-12-15 15:57:58 +08:00
Li Yuxuan 23364c0dac test:e2e: Add cri auth test
Make the original k8s-e2e workflow to be a reusable workflow template,
which is used by cri case and kubeconf case with different `auth-type`
input.

Differences between cri case and kubeconf case:
- CRI snapshotter spec needs extra containerd socket mount
- CRI snapshotter spec has no cluster role for secrets
- CRI snapshotter spec uses `--enable-cri-keychain` instead of
`--enable-kubeconfig-keychain`
- In the `Run E2E test` step, cri case needs to change the image service
endpoint of kubelet to nydus-snapshotter

Other changes:
- Add `imagePullSecrets` to test pod spec and change it's namespace to
`nydus-system`. So that kubelet can get the image secret under both
cri&kubeconf cases. The auth info in the containerd config file is no
longer needed and has been removed.
- Add a `ps -ef` info log in the `Dump logs` step

Signed-off-by: Li Yuxuan <liyuxuan.darfux@bytedance.com>
2022-12-15 15:01:51 +08:00
Changwei Ge c27f80978d
Merge pull request #277 from loheagn/s3-backend
backend: support s3 backend
2022-12-15 14:18:02 +08:00
Nan Li 9038ab8d02 backend: support s3 backend
Signed-off-by: Nan Li <loheagn@icloud.com>
2022-12-15 11:59:13 +08:00
Changwei Ge d3af18bb0c
Merge pull request #291 from changweige/ignore-existing-target
ignore existing symlink target existence
2022-12-15 10:36:50 +08:00
Changwei Ge 0e8b417243 ignore existing symlink target existence
ln: failed to create symbolic link '/etc/nydus/nydusd-config.json': File exists

It's more convenient and not disturb users

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-15 10:23:27 +08:00
Changwei Ge cbaaea1f00
Merge pull request #289 from liubin/debug
Don't return error if test pod is not created or has been deleted
2022-12-15 09:59:35 +08:00
bin liu 48d5e6e8b5 Don't return error if test pod is not created or has been deleted
Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-14 19:38:30 +08:00
Changwei Ge 9b01f43014 clean up file system package
Filesystem no longger keeps configurations of daemon.
It should just be  thin layer to abstract file system
operations especially for Mount and Umount.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 15:00:27 +08:00
Changwei Ge 3d0e02d244
Merge pull request #279 from changweige/nydusd-cpu-resouces
Collect nydusd startup cpu utilization and report its mem usage
2022-12-14 14:26:13 +08:00
Changwei Ge 83c114b4ef
Merge pull request #282 from darfux/support-cri-auth
Support cri image service proxy mode for getting registry auth
2022-12-14 14:18:25 +08:00
Li Yuxuan 9ddfe16399 Support cri image service proxy mode for getting registry auth
Support cri based authentication like stargz-snapshotter
(https://github.com/containerd/stargz-snapshotter/blob/main/docs/overview.md#cri-based-authentication).
The proxy service uses the implementation by stargz directly.

Fixes: #47

Signed-off-by: Li Yuxuan <liyuxuan.darfux@bytedance.com>
2022-12-14 14:08:40 +08:00
Changwei Ge 85b4aa8f79
Merge pull request #245 from imeoer/converter-support-ref
converter: support ref image build
2022-12-14 13:57:07 +08:00
Changwei Ge a02f61446e export read data amount when start container
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge 92c8c35f32 export daemon startup CPU utilizatioin
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge fce6580d44 record nydusd startup CPU utilization
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge c8464e8db6 rename GetCurrentStat to GetProcessStat
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge 4235ee89da extract out helper functions to calculate cpu utilization
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge 86500ff5e4 add more buckets to snapshotter's metrcis
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 13:32:56 +08:00
Changwei Ge 0fb6d6ab0d redirect nydusd and rafs instance configuration to new location
For shared daemon mode, it has diffent location to store those
configurations

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-14 12:16:45 +08:00
Yan Song a3fccd09a9 converter: support ref image build
It allows nydus lazily load OCI targz layer with the nydus
zran ref image.

https://github.com/containerd/nydus-snapshotter/issues/244

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-14 02:26:58 +00:00
Changwei Ge 7dee1819f1
Merge pull request #284 from liubin/check-kebesecret-startup-error
Check KubeSecretListener start error
2022-12-14 10:25:21 +08:00
Changwei Ge e5e2ae024c
Merge pull request #286 from hsiangkao/path_cleanup
treewide: tidy up --config-path
2022-12-14 10:19:03 +08:00
Gao Xiang 254c0cde76 treewide: tidy up --config-path
1. --config-path "/etc/nydus/nydusd-config.fusedev.json" or
                 "/etc/nydus/nydusd-config.fscache.json"

2. Add a symlink /etc/nysud/nydusd-config.json to match the
   default configuration.

In order to match
https://github.com/dragonflyoss/image-service/pull/955

Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
2022-12-13 13:58:25 +00:00
bin liu 31733f257a Check KubeSecretListener start error
Check if KubeSecretListener has start error, then return the error
to prevent snapshotter to start.

Also this commit reduce a goroutine that is not required.

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-13 18:41:59 +08:00
Changwei Ge d349d561ab
Merge pull request #283 from liubin/feat/k8s-e2e
add e2e test for running nydus snapshotter in Kubernetes
2022-12-13 16:07:22 +08:00
bin liu 9771f7adc4 add e2e test for running nydus snapshotter in Kubernetes
This e2e test will
- deploy nydus snapshotter with RBAC in Kubernetes
- setup a Docker retistry needs auth
- create a dockerconfig secret and let snapshotter get the auth from it

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-13 15:43:25 +08:00
Changwei Ge f1f0cffd56
Merge pull request #280 from changweige/fix-default-api-socket
maintenance api server's default socket should be under root dir
2022-12-13 14:13:19 +08:00
Changwei Ge c9c834a977 maintenance api server's default socket should be under root dir
We should put all snapshotter's stuff under root dir which can
be customized.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-13 13:51:36 +08:00
bin liu 8c87cb3983 Optimize image size
Change base image from ubuntu to alpine to reduce image size.

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-12-12 21:37:34 +08:00
Changwei Ge da9408aaf1
Merge pull request #281 from changweige/move-readme-ribbon
move FOSSA license ribbon to the top position
2022-12-12 10:40:59 +08:00
Changwei Ge 26b2ffc695 move FOSSA license ribbon to the top position
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-12-12 09:39:45 +08:00
Changwei Ge 0374a5bf0b
Merge pull request #261 from sctb512/metrics
metrics: collect the metrics about snapshotter
2022-12-09 20:01:52 +08:00
Changwei Ge dccb970e73
Merge pull request #278 from AkihiroSuda/retract-v0.3.0
go.mod: retract v0.3.0
2022-12-09 12:11:38 +08:00
Akihiro Suda dcb0f109cb
go.mod: retract v0.3.0
v0.3.0 was retagged:
cd604c1b59...85653575c7

Signed-off-by: Akihiro Suda <akihiro.suda.cz@hco.ntt.co.jp>
2022-12-09 12:49:13 +09:00
Bin Tang 56f9ceb7be metrics: collect the metrics about snapshotter
Collect the metrics of preparing snapshots, mounting snapshots, and removing snapshots.
In addition, collect the metrics about snapshotter, including cache usage,
cleanup time, cpu usage, memory usage, file descriptor counts, run time and thread counts.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-12-09 11:35:17 +08:00
Changwei Ge 6e5f1fa17b
Merge pull request #268 from imeoer/improve-doc
remove scheme field in nydusd config
2022-12-08 20:35:46 +08:00
Yan Song 13d5375934 remove scheme field in nydusd config
We have implemented automatically scheme detect for nydusd in this PR:

https://github.com/dragonflyoss/image-service/pull/893#merged-event

So we can remove the default scheme field in nydusd config file.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-12-08 10:02:11 +00:00
Changwei Ge 30980d96ba
Merge pull request #273 from hsiangkao/nydus_zran
README.md: add ZRAN support description
2022-12-07 10:11:19 +08:00
Gao Xiang a80f874216 README.md: add ZRAN support description
Nydus can now support lazy pulling with original OCI artifacts and
new Nydus zran indices.

Signed-off-by: Gao Xiang <hsiangkao@linux.alibaba.com>
2022-12-06 10:55:01 +08:00
Changwei Ge c9110678a7
Merge pull request #272 from Desiki-high/feature/add-nydusdconfig
feat: add some nydusd-config for metrics work
2022-12-05 14:40:33 +08:00
Desiki-high 58979cb9ea feat: add nydusdconfig.fix 2022-12-05 11:44:47 +00:00
Changwei Ge 600c0c9d33
Merge pull request #270 from austinvazquez/resolve-release-workflow-warnings
Resolve warnings in GitHub actions release workflow
2022-12-01 16:48:25 +08:00
Austin Vazquez 3bb6013629 Resolve warnings in GitHub actions release workflow
Updates actions/checkout and actions/download-artifact packages from v2
to v3 to resolve NodeJS 12 warnings.

Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2022-11-30 15:38:07 +00:00
Changwei Ge 1e18acbf9d
Merge pull request #269 from changweige/release-0.4
get rid of getting daemon state in single flight
2022-11-30 14:07:50 +08:00
Changwei Ge 222d577887 get rid of getting daemon state in single flight
It is possible that snapshotter waits for RUNNING
state before waits for INIT stat which is a deadlock

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-30 13:29:38 +08:00
Changwei Ge dba3aaff1c
Merge pull request #265 from imeoer/converter-fix
converter: enhance nydus tar unpack
2022-11-30 10:19:11 +08:00
Yan Song 15b62b3da9 converter: enhance nydus tar unpack
Unpacking file from nydus blob should seek until encountering the head
of blob stream, this patch ensures this to improve unpack compatibility
and refine the test codes.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-11-29 10:44:53 +00:00
Changwei Ge 1a6f980714
Merge pull request #224 from fossabot/add-license-scan-badge
Add license scan report and status
2022-11-29 15:19:39 +08:00
Changwei Ge b0e8560e5c
Merge pull request #263 from sctb512/nydusd-event-metric
metrics: collect the metrics of nydusd events
2022-11-29 14:15:15 +08:00
Bin Tang fe511b89ba metrics: collect the metrics of nydusd events
Collect the metrics of nydus daemon events, including INIT, RUNNING and DIED.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-11-29 11:46:46 +08:00
Changwei Ge 7052dd643f
Merge pull request #264 from changweige/dont-api-mount
don't invoke API to mount rafs if it is not shareDaemon
2022-11-28 15:38:42 +08:00
Changwei Ge e920fcad47 don't invoke API to mount rafs if it is not shareDaemon
Rafs is already mounted during starting nydusd.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-28 15:07:30 +08:00
Changwei Ge a6fc3af81d
Merge pull request #260 from changweige/exit-daemon-after-ref0
Shutdown nydusd if it serves no filesystem or snapshot
2022-11-25 17:50:04 +08:00
Changwei Ge cbe79da219 just return if no daemon serves the snapshot
No need to use has_daemon to check.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge 3ba2f595e2 clean up what messages are printed to log file
Make the log lines more suggestive and clear.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge e8bf568768 print more infmormation about nydusd and its instances
So we can know more about nydusd and snapshots via
management API.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge 33cf2f480c fix missing cache usage reported with nydusd>2.1
Beyond nydusd 2.1, data blob cache has a suffix .blob.data

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge 2324feabae stop shared daemon if no snapshots is exsited
Stop the shared daemon when closing snapshotter if
no snapshots is referenced to the shared daemon.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge d8f06c208c retain shared daemon when snapshotter is restarting
We can reliably judege the recoverd daemon is shared one
when its host mount point equals to the root mount point.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:41:33 +08:00
Changwei Ge d55cfe8aaa umount fs by the snapshot ID rather than a dir
As the snapshot and rafs intance is well managed now,
we can easily umount a snapshot by its ID.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:33:11 +08:00
Changwei Ge 69192003c1 add method GetRef to reflect daemon's reference number
So the modules can rely on this to decide if stop nydusd
daemon.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-25 17:33:11 +08:00
Changwei Ge 84d9ba34fa
Merge pull request #249 from changweige/upgrade
Add nydusd live-upgrade control flow
2022-11-25 17:16:18 +08:00
Changwei Ge 44bf88f377
Merge pull request #238 from liubin/release-docker-image
release: build and push Docker image
2022-11-23 15:59:06 +08:00
bin liu 32cf26e554 release: build and push Docker image
When new release is created, build and push Docker image
to GitHub Packages.

Signed-off-by: bin liu <liubin0329@gmail.com>
2022-11-23 10:46:52 +08:00
Changwei Ge 2edfc80227 Public methods lock and unlock from daemonss manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:45 +08:00
Changwei Ge 8df9819afb repalce the old nydusd binary with the new one
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:41 +08:00
Changwei Ge b8c667fe2f support nydusd live-upgrade
We can do live-upgrade to take over old nydusd fs
service by handling http requests

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:38 +08:00
Changwei Ge f698ba67eb Public methods to subscribe and unsubscribe daemon events
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:34 +08:00
Changwei Ge 4ab49c05d0 Public the method to build nydusd command line
Also make it support replace the nydusd binary path
pointing to the newer version and receive --upgrade flag

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:27 +08:00
Changwei Ge 60a321112a add capablity to clone daemon instances
We can use it when start upgraded daemon with
the awareness of those instances ralated to old one.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:23 +08:00
Changwei Ge 7fc0854b89 open a daemon API method to stop daemon fs service
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 15:05:20 +08:00
Changwei Ge b2962d5f20
Merge pull request #254 from changweige/enable-errcheck
Optimize how nydus meta snapshot is prepared and enable errcheck linter
2022-11-22 14:39:26 +08:00
Changwei Ge 57c2a02c06
Merge pull request #258 from changweige/clear-daemon-state
clear daemon state after nydusd dies
2022-11-22 14:11:08 +08:00
Changwei Ge 228648848c fix blob manager ut test after checkerr is enforced
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 14:10:21 +08:00
Changwei Ge e516e19d77 enable error check linter and silent all warnings
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 14:10:21 +08:00
Changwei Ge 6f221f6282 only calculate disk usage for OCI snapshots
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 12:13:21 +08:00
Changwei Ge 66ab412640 blobManger chmod a file that should exists
The chmod target file has been rename previously.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 12:13:21 +08:00
Changwei Ge 08479ebe08 reduce queries to db to boost container startup
We can rely on snapshots relationship to decide whether
to wait for nydusd until it's ready.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-22 12:10:51 +08:00
Changwei Ge afb8ecb003
Merge pull request #259 from austinvazquez/resolve-workflow-warnings
Resolve GitHub actions workflow warnings
2022-11-22 09:03:08 +08:00
Austin Vazquez 4294f79fef Resolve GitHub actions workflow warnings
Resolves GitHub actions CI/Integration test workflow warnings for NodeJS
12 actions, `set-output` and `save-state` command usage.

Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2022-11-22 00:00:57 +00:00
Changwei Ge 03c82d30a1
Merge pull request #256 from changweige/pass-fscache-prefetch-config
pass prefetch config to fscache config
2022-11-21 09:50:08 +08:00
Changwei Ge 93496ad987
Merge pull request #257 from changweige/fix-version-typo
fix a typo in version message
2022-11-21 09:49:30 +08:00
Changwei Ge 098129181b clear daemon state after nydusd dies
A new nydusd has to be brought up, so we have
to query the daemon state again.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 22:23:42 +08:00
Changwei Ge 79abb9659b pass prefetch config to fscache config
The prefetch config part is lacked in fscache configuration

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 22:15:26 +08:00
Changwei Ge 5ff7a3681a fix a typo in version message
The correct one shoud be revision

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 18:58:13 +08:00
Changwei Ge 81ef88a255
Merge pull request #253 from changweige/enforce-fsdriver
fails snapshotter startup if its fsdriver mismatches daemon's
2022-11-18 18:53:35 +08:00
Changwei Ge bbfaced8db
Merge pull request #250 from changweige/more-linters
don't write config file with permissions greater than 0600
2022-11-18 18:53:18 +08:00
Changwei Ge b36d5310ed
Merge pull request #248 from changweige/running-state-cache
Running state cache
2022-11-18 18:52:50 +08:00
Changwei Ge ba7f5519db avoid frequent daemon state query
At present, nydus-snapshotter queries daemon's state each
time when it gets daemon object's state. The query comes
from several positions which cause duplicated query.
We can use single-flight mechanism to query daemon'state
to reduce unnecessary comunications between processes.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 17:49:29 +08:00
Changwei Ge 5d29359e3d caches daemon's RUNNING state
Only query remote nydusd process when daemon is not in RUNNING state

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 17:48:38 +08:00
Changwei Ge 54a8b75f63 rename Daemon method State to GetState
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 17:47:33 +08:00
Changwei Ge c6bf0d50bf fails snapshotter startup if its fsdriver mismatches daemon's
Otherwise, even snapshotter can restore and recover daemons
during this startup, it can't provide correct rootfs.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 17:40:58 +08:00
Changwei Ge d71c1f06df
Merge pull request #251 from changweige/simplify-nydusd-client
simplify nydusd http client initialization
2022-11-18 17:37:51 +08:00
Changwei Ge 60f4d42e21 don't write config file with permissions greater than 0600
Don't show config content to other users.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-18 17:35:24 +08:00
Changwei Ge aaffbb444e
Merge pull request #252 from gaius-qi/feature/version
refactor: move version from cmd/containerd-nydus-grpc/version.go to version package
2022-11-16 20:25:08 +08:00
Gaius c73b584991
refactor: move version from cmd/containerd-nydus-grpc/version.go to version package
Signed-off-by: Gaius <gaius.qi@gmail.com>
2022-11-16 20:11:12 +08:00
Changwei Ge f88a15a7cf
Merge pull request #239 from power-more/zhaoshang/upper
[Bugfix] Use the correct label to distinguish the lower layer from th…
2022-11-16 14:21:16 +08:00
Changwei Ge 558b036130 simplify nydusd http client initialization
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 22:55:03 +08:00
Changwei Ge 0b0782c9ec
Merge pull request #247 from changweige/remove-mirros-urls
remove registry mirror urls
2022-11-15 17:34:27 +08:00
Changwei Ge 5d8318e5af remove registry mirror urls
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 17:09:09 +08:00
Changwei Ge e96ee64bd2
Merge pull request #236 from changweige/decouple-daemon-rafs
decouple Rafs instance from daemon
2022-11-15 15:03:26 +08:00
Changwei Ge 20f3a5cf05 remove useless Filesystem struct method
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 11:31:46 +08:00
Changwei Ge 2e541d502b store the whole api socket path in daemon
As in the upgrade procedure, the api socket path differs

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 11:31:46 +08:00
Changwei Ge a777f2b0f5 add UT for start from legacy DB records
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 11:31:46 +08:00
Changwei Ge 70a0b30dcd convert legacy db records to new bucket
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 11:31:46 +08:00
Changwei Ge bf6faaa5e3 refactor basic data structures by decoupling daemon and fs instances
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-15 11:31:46 +08:00
Austin Vazquez 7a55d4ff0d Update golangci-lint to v1.50.1
Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2022-11-15 10:08:10 +08:00
Changwei Ge 7a65342205
Merge pull request #242 from austinvazquez/update-golangci-lint
Update golangci-lint to v1.50.1
2022-11-10 09:51:07 +08:00
Changwei Ge 6e0c326604
Merge pull request #241 from austinvazquez/update-github-actions-packages
Update GitHub actions packages in workflows
2022-11-10 09:37:11 +08:00
Austin Vazquez 77242dfc91 Update golangci-lint to v1.50.1
Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2022-11-09 23:43:47 +00:00
Austin Vazquez 184b7f3a92 Update GitHub actions packages in workflows
Update actions/checkout, actions/cache, and actions/upload-artifact to
v3.

Signed-off-by: Austin Vazquez <macedonv@amazon.com>
2022-11-09 23:27:08 +00:00
zhaoshang 27a8e26170 [Bugfix] Use the correct label to distinguish the lower layer from the upper layer
Previously, the unreliable (may not exist, such as when disable_snapshot_annotations = true)
label added by cri was used as the basis for judging the upper layer, then when the OCI image
without the label was started, it would mistakenly enter prepare for upper layer logic.

We noticed that "containerd.io/snapshot.ref" is a label added by containerd before calling
sn.Prepare(), and only exists in the lower layer snapshot, not in the upper layer, so we can
simply put the negative situation of lower layer as the upper layer.

Signed-off-by: zhaoshang <zhaoshangsjtu@linux.alibaba.com>
2022-11-08 20:19:56 +08:00
Changwei Ge 43ca9b2e3b
Merge pull request #229 from changweige/generic-daemon-config
Generalize daemon configuration provisioning
2022-11-08 10:14:54 +08:00
Changwei Ge 9a053a04a8 validate if configuration files are legal
Remind uers that they are providing wrong configurations

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 9e222ffbf3 better to return errors when dumping configration fails
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge aa11ecc502 remove prefetch daemon mode
It is no longer used.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 1c7d52b8d5 remove daemonMode field from daemon oject
We can still rely on the state on Manger thus to
simplify code.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge ad4b779795 move stargz code to a separate package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 81b0873c6f rename BlobManager to Manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 172ddf19b4 create blob manager for snapshotter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 38447c1260 remove dead function OldMountPoint
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 8b14d5b123 get rid of blob manager from Filesystem object
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge b901a163a2 remove blobs manager code to a blob package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 3dd26bd101 move image resolving logics to a new package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 5b12d12c65 only print error when discard Body fails
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 787f793b96 add e2e test for blobs prehead for blobs manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge a7a8b3c39f change default localfs backend nydusd backend.device.config.dir to new
one

Keep it the same with dafalt nydus configuration

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 3d1d4f0a54 move some methods to a new file mode.go
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge a1a075f4ff no need to pass labels to remoteMounts anymore
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge c5e1c57766 remove unnecessary items in example nydusd configuration
work_dir item will be overrided by cache manager's working
directory

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge e297d21e4d pass cache manager's directory to nydusd config
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 9620b8f069 only enable domain_id when it is not equal to fscacheID
Otherwise. we cant tell if it is configured by users.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge caac954929 persist configuration file after suplementing info from labels
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 82d31dacce reload daemon config when recovering daemons
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 260bfa2d4b dump daemon config file before starting daemon process
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 112f145822 generate daemon config from daemon.Config when make remote mounts
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge bd8f2e147f keep DaemonConfig interace to Daemon object
So config can be dumped to string or file when needed
insteat of unmarshaling from json file

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge e5450b2e63 suplement daemon config by parsing snapshot labels
In addition, don't parse daemon config file again and again

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 0059779592 Associate a daemon config template to manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge dba3024c43 don't load daemon config when parsing snapshotter's configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 8e4e1b2ea3 nydusd client doesn't read daemon config file anymore
Only meaningful info is paased to daemon client

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 0b2548d857 fix a function name typo
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge b345b6f010 public Manager field of filesystem
So other packages can reference the Manger to retrieve daemons

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 3df98a55d7 use basic log infra to log rather than directly using logrus
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 02afb0b2f6 implement DaemonConfig for fscache daemon configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge 46b90c34bc implement DaemonConfig interface for FUSE daemon configuration
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-08 10:00:49 +08:00
Changwei Ge bcc8b5ed3d define daemon common configurations types
Also create a new daemonconfig package to accomodate them

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-07 16:25:55 +08:00
Changwei Ge b9a215a06d
Merge pull request #233 from changweige/new-blob-gc
remove complex blob cache GC code
2022-11-07 16:25:32 +08:00
Changwei Ge 3258ca07c7 remove layer label containerd.io/snapshot/nydus-blob-ids
The label is too large when pulling image by containerd.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-07 16:15:57 +08:00
Changwei Ge 33be2734a9 remove complex blob cache GC code
Containers can contorl if a committed snapshot should
be removed. We don't have to consider if snapshot belongs
to multiple images.

Just respond to containerd a committed snapshot shoud be remove.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-11-07 16:15:57 +08:00
Changwei Ge 60604ea6e8
Merge pull request #217 from sctb512/mirror-health-check
support configure nydusd mirror health checking
2022-11-04 11:31:10 +08:00
Bin Tang 044b758c80 add mirror health checking
Currently, the mirror is set to unavailable if the failed times reach failure_limit.
We added mirror health checking, which will recover unavailable mirror.
The failure_limit indicates the failed time at which the mirror is set to unavailable.
The health_check_interval indicates the time interval to recover the unavailable mirror.
The ping_url is the endpoint to check mirror server health.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-10-31 21:01:36 +08:00
Changwei Ge af3b14adfa
Merge pull request #204 from changweige/supervisor
Introduce supervisor to manage nydusd runtime states and hold resources
2022-10-28 15:47:30 +08:00
Changwei Ge 5543b5eea2 rename WaitForStatesTimeout to WaitStatesTimeout
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 49e0f0a13c wait until it is unmounted when juding nydusd is exited.
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge cb7088f43a add a helper to wait until it is unmounted
This is helpful when nydus-snapshotter is restared
while nydusd is still running. Then snapshotter can
judge if nydusd is exited.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 6d3de09806 add error ErrDeviceBusy to convenience
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 078d04f85f lock daemon client when requesting API
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge d12dff675a rename some functions to clearly distinguish between virtual daemon or
not

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 10f35b3567 sleep for 500 miliseconds if nydusd is not child process
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 0da2119503 move daemon mode judge helper to a new source file
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 96c16a712a add some comments to tell core snapshot deletion logic
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge ce270cf40a add more tools to e2e test container
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge e3ba2dc446 build binary for e2e with debug info
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 3f93bae192 treat it succeeded when kill containers failed
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge ef7c2509b5 bump golang version to 1.18.7 for e2e test
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge 03019030ba try to stop container before deleting it.
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge cdb9f88a40 add e2e test for nydusds failover
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:37:23 +08:00
Changwei Ge cd2b305ba1 do failover after nydusd dies
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:29:10 +08:00
Changwei Ge ee4aac1c13 create supervisor for each daemon
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:29:10 +08:00
Changwei Ge 1989890659 create supvervisorSet when creating manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:29:10 +08:00
Changwei Ge f28c36cea5 introduce nydusds' supervisor
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-28 15:29:10 +08:00
Changwei Ge 870ccffbc4
Merge pull request #225 from changweige/retract-versions
retract some published module versions
2022-10-25 15:25:02 +08:00
Changwei Ge 396f8d5556
Merge pull request #223 from changweige/snapshots-usage
Report nydus real blob cache disk usage
2022-10-25 15:23:52 +08:00
Changwei Ge 289739f7a5 retract some published module versions
The were published by accident.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-25 15:10:47 +08:00
Changwei Ge 989c8ca683 add e2e test case for snapshotts/Usage interface
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-25 14:56:43 +08:00
Changwei Ge 42ca339d47 Open a API for daemon to fetch nydusd cache metrics
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-25 14:56:43 +08:00
Changwei Ge 77e7fdb910 implement containerd/snapshots Usage interface
report nydusd blob cache real disk usage. We can find
blob layer digest from labels thus to locate the blob
cache file rather than use the fake usage in DB. This
can benefit Kubelet imagefs based Pod eviction.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-25 14:56:43 +08:00
fossabot 0fcf080853 Add license scan report and status
Signed off by: fossabot <badges@fossa.com>
2022-10-24 23:27:38 -04:00
Changwei Ge dfd63b7e63
Merge pull request #211 from userzj/zhujia/shared-domain
support shared domain
2022-10-21 14:46:07 +08:00
Jia Zhu 0cd92d09c6 support shared domain
User could configure the 'domain_id' field in config
file to use this feature.

Be cautious! If you use this feature, make sure your kernel
version >= 6.1.

Signed-off-by: Jia Zhu <zhujia.zj@bytedance.com>
Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-10-20 11:46:34 +08:00
Changwei Ge 4f8d7dfc23
Merge pull request #218 from loheagn/fix-image-convert-fs-version
Fix the annotation error of the converted bootstrap layer
2022-10-20 11:26:53 +08:00
Changwei Ge 8abf82f809
Merge pull request #219 from changweige/fix-release-action
fix broken release github action
2022-10-20 10:29:55 +08:00
Changwei Ge cb876b3f6c fix broken release github action
The release action can't upload artifacts when it told the error:

🤔 Pattern 'nydus-snapshotter-v0.11.2-x86_64.tgz nydus-snapshotter-v0.11.2-x86_64.tgz.sha256sum' does not match any files.
👩‍🏭 Creating new GitHub release for tag v0.11.2...
🤔 nydus-snapshotter-v0.11.2-x86_64.tgz nydus-snapshotter-v0.11.2-x86_64.tgz.sha256sum not include valid file.
🎉 Release ready at https://github.com/containerd/nydus-snapshotter/releases/tag/v0.11.2

So we shoud use literal style yaml block to keep the newline untouched

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-20 10:03:35 +08:00
Nan Li 3207516e55 Fix the fs-version annotation error of the converted Nydus bootstrap layer.
By now, the "containerd.io/snapshot/nydus-fs-version" annotation of the converted bootstrap layer is always `5` which is the default value. The reason for this error is that the value of `MergeOption.FsVersion` is not assigned correctly in the `convertManifest` function of `convert_unix.go` when call the `MergeLayers` function and the `MergeLayers` always uses the empty string as the value of `MergeOption.FsVersion`.

Signed-off-by: Nan Li <loheagn@icloud.com>
2022-10-19 22:55:15 +08:00
Changwei Ge 7d0d5db51e
Merge pull request #213 from changweige/add-arch-pictures
add architecture diagrams to README
2022-10-17 10:42:49 +08:00
Changwei Ge e826301f44 add a section telling integration with dragonfly
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-17 10:33:04 +08:00
Changwei Ge 575d60b3e4 add architecture diagrams to README
Also revise README

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-17 10:33:04 +08:00
Changwei Ge fe95b89e6c
Merge pull request #216 from changweige/change-nydusd-fusedev
change dependent nydusd-fusedev to nydusd
2022-10-17 10:32:31 +08:00
Changwei Ge 9ccf82a326 bump e2e nydusd version to 2.1-rc.4
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-17 10:26:02 +08:00
Changwei Ge 0ed08ff803 change dependant nydusd-fusedev to nydusd
Nydusd has unified fusedev and virtofs

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-17 10:25:31 +08:00
Changwei Ge 9269132b36
Merge pull request #212 from changweige/close-race
lock daemon client when requesting to daemon
2022-10-14 16:28:48 +08:00
Changwei Ge 298c918769
Merge pull request #210 from sctb512/auth-through
support configure authorization through mirror
2022-10-13 14:39:55 +08:00
Changwei Ge e8a06b8c43 lock daemon client when requesting to daemon
There is a race between reseting client during recovering
daemons and requesting to daemon.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-13 13:27:53 +08:00
Changwei Ge 977c2e9b03
Merge pull request #208 from changweige/enhance-cmd-builder
command builder recognize id parameter
2022-10-13 11:31:37 +08:00
Changwei Ge 823c82eb94
Merge pull request #207 from changweige/public-apis
public three nydusd API through daemon methods
2022-10-13 11:05:32 +08:00
Changwei Ge 76b34049e3 command builder recognize id parameter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-13 10:34:32 +08:00
Changwei Ge 7e5ce1a22b public three nydusd API through daemon methods
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-13 10:32:16 +08:00
Bin Tang d506e21763 support configure authorization through mirror
Nydusd needs a parameters to determine if it is authorized through mirror.
So snapshotter should also load auth_through item and provide it to nydusd.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-10-12 21:27:36 +08:00
Changwei Ge 8d038feca1
Merge pull request #209 from userzj/zhujia/revert
Revert "support global shared domain"
2022-10-12 18:00:36 +08:00
Jia Zhu 6e364305a6 Revert "support global shared domain"
This reverts commit f2f36e99fe.
2022-10-12 17:46:36 +08:00
Changwei Ge fbe53a47ec
Merge pull request #206 from changweige/rename-fs-metrics
rename FsMetric to FsMetrics across the project
2022-10-12 15:54:45 +08:00
Changwei Ge c638f4f272 rename FsMetric to FsMetrics across the project
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-12 15:46:14 +08:00
Changwei Ge d5efe1ab56
Merge pull request #205 from changweige/cross-build-converter
Only cross build for converter packge
2022-10-12 15:44:24 +08:00
Changwei Ge 366a0ebf2f add main package for building converter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 17:09:57 +08:00
Changwei Ge 36c3b22c83 remove stub _other.go files
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 17:09:57 +08:00
Changwei Ge 40531ab599 only do cross build for converter package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 17:09:57 +08:00
Changwei Ge d33bd1dad9 add makefile target for build converter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 17:09:57 +08:00
Changwei Ge ddd78c3b63
Merge pull request #201 from changweige/system-http-server
System http server
2022-10-11 14:51:07 +08:00
Changwei Ge 42f7822756 add helper jsonResponse to return error to client
The helper wraps error code and particular messages.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 14:43:20 +08:00
Changwei Ge 3a4b074a9c Add a helper to compose controller error message
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 14:43:20 +08:00
Changwei Ge 58caac35d6 rename package metric to metrics
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:52:34 +08:00
Changwei Ge ef2e7b9da3 merge system controller and prometheus http servers
Only one http server is needed for different service
endpoints

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:52:34 +08:00
Changwei Ge 99eb8df485 add initial unmature http service to fetch daemon records
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:52:32 +08:00
Changwei Ge 18d11bfff6 create system controller when starting
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:51:49 +08:00
Changwei Ge 611d9213cd add option --api-socket to specify the socket path
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:51:49 +08:00
Changwei Ge 1911139a8a add system controller
Nydus-snapshotter might manage dozens of running nydus daemons, each daemon may have multiple
file system instances attached. For easy maintenance, the system controller can interact with
all the daemons in a consistent and automatic way.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-11 11:51:47 +08:00
Changwei Ge ddd543e927
Merge pull request #162 from userzj/zhujia/domain-upstream
Support shared domain
2022-10-11 10:28:56 +08:00
Jia Zhu f2f36e99fe support global shared domain
Use a global domain for all mountpoints.
If kernel doesn't support shared domain, will fallback to
the mount without 'domain_id' option.

Signed-off-by: Jia Zhu <zhujia.zj@bytedance.com>
2022-10-10 19:56:40 +08:00
Changwei Ge 686042e141
Merge pull request #203 from changweige/validate-daemon-mode
Validate daemon mode
2022-10-10 15:21:52 +08:00
Changwei Ge 2acc59142c refine loading configuration file code a bit
Refine some error message sentences and
rename a function name

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-10 12:17:49 +08:00
Changwei Ge 10ddc26611 fix typos in e2e test cases
It should be multiple

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-10 12:17:49 +08:00
Changwei Ge 610d8f48d3 validate daemon modes and return explicit errors
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-10 12:17:49 +08:00
Changwei Ge df4391b10d define daemon mode and adapt it everywhere
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-10 12:14:14 +08:00
Changwei Ge d65d531508 add more errors definitions
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 17:17:50 +08:00
Changwei Ge 09ba87a331
Merge pull request #202 from changweige/move-client-code
Move nydusd http client code to daemon package
2022-10-09 14:05:12 +08:00
Changwei Ge 2b06f2e798 rename package process to manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 12:50:36 +08:00
Changwei Ge db3e82baa2 move nydusd client code to daemon package
This is prepared for removing nydussdk package and
make daemon package as a universal exported packge
for other projects.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:49:48 +08:00
Changwei Ge 431e96cc77
Merge pull request #200 from changweige/cmd-builder
Add nydusd daemon command line builder
2022-10-09 11:43:02 +08:00
Changwei Ge 5de01152ec
Merge pull request #196 from changweige/refactor-nydusd-client
refactor nydusd http client package
2022-10-09 11:42:45 +08:00
Changwei Ge cda881e4f6 move forking daemons logics to a new file
The file is named daemon_adapter.go. manager.go only
contains logics managing running daemons and persiting
their states.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:26:01 +08:00
Changwei Ge f64d500597 introduce daemon command line builder
Provide a flexible way to generate command line
to start nydusd as a libary API.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:26:01 +08:00
Changwei Ge e4d199542d change to underlying type of DaemonState to string
So to avoid integer and string conversions

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:04:11 +08:00
Changwei Ge 7820134377 move nydusd relate type definition to daemon package
We are going to delete package nydussdk. Before that,
let' move the type defined there to daemon.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:04:10 +08:00
Changwei Ge 92917b1ead simplify some methods nameing
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-09 11:03:27 +08:00
Changwei Ge 167d201f95 rename nydud http client interface to NydudClient
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 19:11:17 +08:00
Changwei Ge 0c034a4496 add some comments to describe functions behaviors
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 14:08:23 +08:00
Changwei Ge a9fc19eb07 let simpleRequest receive body and directly process reponse
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 14:08:23 +08:00
Changwei Ge 94d8b26f91 make daemon state waiter generic for any daemon state
Nydus-snapshotter would also wait daemon to reach
 Init and Ready state.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 13:03:02 +08:00
Changwei Ge 2c8944acbf rename client method CheckStatus to GetDaemonInfo
The new name is more suggestive and expressive

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 13:03:02 +08:00
Changwei Ge 5dca85613c silent linter's complaints
pkg/nydussdk/client.go:127:54: buildTransport - result 1 (error) is always nil (unparam)
func buildTransport(sock string) (http.RoundTripper, error) {
                                                     ^
make: *** [Makefile:56: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 13:03:02 +08:00
Changwei Ge 7dc3ce9775 add nydusd client method takeover, sendfd and start
To implement more methods to control nydusd work flow.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 13:03:02 +08:00
Changwei Ge e3ecd74d1e refactor nydusd http clients package
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-08 13:03:02 +08:00
Changwei Ge 7abbca296e rename NydusClient to NydusdClient
It's more suggestive.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:29:40 +08:00
Changwei Ge d1605e985a rename several API endpoints constant names
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:29:40 +08:00
Changwei Ge 8bb1a4d28f define nydus daemon state
So client doesn't have to care about the specific state string

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:29:40 +08:00
Changwei Ge ca8e67e767
Merge pull request #192 from changweige/upgrade-golang
upgrade golang version to 1.18.6
2022-10-02 10:27:53 +08:00
Changwei Ge 404a573224 fix warnings reported by linter exhaustive
golangci-lint run
pkg/process/manager.go:37:2: missing cases in switch of type DaemonRecoverPolicy: RecoverPolicyInvalid (exhaustive)
        switch p {
        ^
make: *** [Makefile:56: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:05:37 +08:00
Changwei Ge 91f4e7627e fix warnings report by nilerr linter
golangci-lint run
config/daemonconfig.go:135:3: error is not nil (line 133) but it returns nil (nilerr)
                return nil
                ^
pkg/auth/keychain.go:38:3: error is not nil (line 36) but it returns nil (nilerr)
                return emptyPassKeyChain, nil
                ^
pkg/filesystem/fs/stargz/resolver.go:174:4: error is not nil (line 172) but it returns nil (nilerr)
                        return 0, nil
                        ^
pkg/filesystem/fs/stargz/resolver.go:201:3: error is not nil (line 199) but it returns nil (nilerr)
                return 0, nil

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:05:37 +08:00
Changwei Ge 2b757d1024 silent linter gocritic complaints
com/containerd/nydus-snapshotter/pkg/utils/transport github.com/containerd/nydus-snapshotter/snapshot ./tests
golangci-lint run
pkg/converter/tool/builder.go:101:69: unslice: could simplify args[:] to args (gocritic)
        logrus.Debugf("\tCommand: %s %s", option.BuilderPath, strings.Join(args[:], " "))
                                                                           ^
pkg/converter/tool/builder.go:146:69: unslice: could simplify args[:] to args (gocritic)
        logrus.Debugf("\tCommand: %s %s", option.BuilderPath, strings.Join(args[:], " "))
                                                                           ^
pkg/converter/tool/builder.go:201:69: unslice: could simplify args[:] to args (gocritic)
        logrus.Debugf("\tCommand: %s %s", option.BuilderPath, strings.Join(args[:], " "))
                                                                           ^
snapshot/snapshot.go:690:13: appendAssign: append result not assigned to the same slice (gocritic)
        options := append(overlayOptions, opt)
                   ^
pkg/process/manager.go:469:3: ifElseChain: rewrite if-else to switch statement (gocritic)
                if d.IsMultipleDaemon() {
                ^
pkg/metric/exporter/types.go:73:3: assignOp: replace `sum = sum + h.Buckets[i]*c` with `sum += h.Buckets[i]*c` (gocritic)
                sum = sum + h.Buckets[i]*c
                ^
pkg/converter/convert_unix.go:636:22: appendAssign: append result not assigned to the same slice (gocritic)
                        manifest.Layers = append(blobDescs, *bootstrapDesc)
                                          ^
pkg/converter/utils.go:67:2: ifElseChain: rewrite if-else to switch statement (gocritic)
        if whence == io.SeekCurrent {
        ^
pkg/converter/utils.go:129:4: ifElseChain: rewrite if-else to switch statement (gocritic)
                        if err != nil {
                        ^
pkg/filesystem/fs/stargz/resolver_test.go:99:46: unslice: could simplify footer[:] to footer (gocritic)
                                Body:       io.NopCloser(bytes.NewReader(footer[:])),
                                                                         ^
pkg/filesystem/fs/stargz/resolver_test.go:106:46: unslice: could simplify toc[:] to toc (gocritic)
                                Body:       io.NopCloser(bytes.NewReader(toc[:])),
                                                                         ^
make: *** [Makefile:56: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 10:05:37 +08:00
Changwei Ge 628b52f8d4 resolve linters' complaints
pkg/metric/serve.go:101:59: (*Server).collectDaemonMetric - result 0 (error) is always nil (unparam)
func (s *Server) collectDaemonMetric(ctx context.Context) error {
                                                          ^
pkg/backend/oss.go:99:27: `(*OSSBackend).push` - `ctx` is unused (unparam)
func (b *OSSBackend) push(ctx context.Context, ra content.ReaderAt, blobDigest digest.Digest) error {
                          ^
pkg/converter/convert_unix.go:146:34: `unpackBootstrapFromNydusTar` - `ctx` is unused (unparam)
func unpackBootstrapFromNydusTar(ctx context.Context, ra content.ReaderAt, target io.Writer) error {
                                 ^
pkg/converter/convert_unix.go:205:29: `unpackBlobFromNydusTar` - `ctx` is unused (unparam)
func unpackBlobFromNydusTar(ctx context.Context, ra content.ReaderAt, target io.Writer) error {
                            ^
tests/nydusd.go:97:65: checkReady - result 1 (error) is always nil (unparam)
func checkReady(ctx context.Context, sock string) (<-chan bool, error) {
                                                                ^
snapshot/snapshot.go:758:40: `(*snapshotter).prepareDirectory` - `ctx` is unused (unparam)
func (o *snapshotter) prepareDirectory(ctx context.Context, snapshotDir string, kind snapshots.Kind) (string, error) {
                                       ^
pkg/filesystem/fs/fs.go:718:43: (*Filesystem).initSharedDaemon - result 0 (*github.com/containerd/nydus-snapshotter/pkg/daemon.Daemon) is never used (unparam)
func (fs *Filesystem) initSharedDaemon() (_ *daemon.Daemon, retErr error) {
                                          ^
make: *** [Makefile:56: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge 4e908e4cd4 add more lint rules to golangci-lint
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge debaca8b36 trim deprecated linters for golangci-lint
WARN [runner] The linter 'structcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter.  Replaced by unused.
WARN [runner] The linter 'varcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter.  Replaced by unused.
WARN [linters context] structcheck is disabled because of generics. You can track the evolution of the generics support by following the https://github.com/golangci/golangci-lint/issues/2649.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge 219d8edff8 silent linter static complaints
pkg/converter/tool/builder.go:13:2: SA1019: "io/ioutil" has been deprecated since Go 1.16: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)
	"io/ioutil"
	^

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge 53fb487e27 lint job uses golang v1.19.1
Thus to gain more advanced and strict check from
golangci-lint/staticlint

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge 05142ddbb2 upgrade golangci-lint to v1.49.0
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge e762d57242 upgrade golang version to 1.18.6
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-10-02 09:49:53 +08:00
Changwei Ge cf24f24e29
Merge pull request #198 from raoxiang1996/start-nydus-by-toml-config
start nydus by toml config
2022-10-02 09:22:25 +08:00
Changwei Ge cd604c1b59
Merge pull request #195 from changweige/print-deleting-dirs
print which directories are being deleted
2022-09-30 14:58:18 +08:00
Changwei Ge 68bcd4d5aa print which directories are being deleted
This is very helpful when debug and trace how
nydus-snapshotter is releasing resources.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-30 13:46:45 +08:00
Changwei Ge 95b8bc9118 reset virtual daemon's nydusd client
Otherwise, it skips checking nydusd's socket's existence.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-30 13:46:45 +08:00
Changwei Ge a13044b3f6
Merge pull request #197 from changweige/reset-virtual-daemon-client
reset virtual daemon's nydusd client
2022-09-29 18:29:13 +08:00
Changwei Ge 80f0f803d9 reset virtual daemon's nydusd client
Otherwise, it skips checking nydusd's socket's existence.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-29 09:40:23 +08:00
Raoxiang d0df881fa3 start nydus by toml config
Use the toml file to configure the startup parameters of nydus-snapshotter
2022-09-29 02:55:13 +08:00
Changwei Ge b11c9c9f14
Merge pull request #193 from loheagn/fix-image-convert-index
Fix some bugs in image conversion
2022-09-28 17:10:57 +08:00
Nan Li 528734c022 Fix some bugs in image conversion using `LayerConvertFunc` and `ConvertHookFunc`.
1. append `nydus.remoteimage.v1` to `os.features` of the manifest descriptor in the index
2. add `"containerd.io/snapshot/nydus-blob": "true"` to the annotations of the blob layer descriptor in the manifest
3. avoid appending duplicate bootstrap layer digest to the diffID list of the config

This commit also adds a smoke test `TestContainerdImageConvert` to make sure `LayerConvertFunc` and `ConvertHookFunc` work well with the containerd image conversion library.

Signed-off-by: Nan Li <loheagn@icloud.com>
2022-09-28 16:27:56 +08:00
Changwei Ge c294c1bb3c
Merge pull request #194 from changweige/fix-client-go-race
fix go race when resetting http client
2022-09-28 14:21:14 +08:00
Changwei Ge 7dc5b12156 fix go race when resetting http client
otherwise, go race happens:

 go race detected
2022-09-28T03:58:01.2478136Z ==================
2022-09-28T03:58:01.2478813Z WARNING: DATA RACE
2022-09-28T03:58:01.2479296Z Write at 0x00c00017a8d0 by goroutine 40:
2022-09-28T03:58:01.2480254Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).ResetClient()
2022-09-28T03:58:01.2618661Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:286 +0x4b9
2022-09-28T03:58:01.2619768Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).ClearVestige()
2022-09-28T03:58:01.2620682Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:367 +0x4a5
2022-09-28T03:58:01.2621606Z   github.com/containerd/nydus-snapshotter/pkg/process.(*Manager).handleDaemonDeathEvent.func1()
2022-09-28T03:58:01.2622497Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/process/manager.go:267 +0x2b3
2022-09-28T03:58:01.2623343Z   github.com/containerd/nydus-snapshotter/pkg/process.(*Manager).handleDaemonDeathEvent·dwrap·7()
2022-09-28T03:58:01.2624258Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/process/manager.go:284 +0x74
2022-09-28T03:58:01.2624545Z
2022-09-28T03:58:01.2624739Z Previous read at 0x00c00017a8d0 by goroutine 41:
2022-09-28T03:58:01.2625338Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).ensureClient()
2022-09-28T03:58:01.2626171Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:302 +0xee
2022-09-28T03:58:01.2626837Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).CheckStatus()
2022-09-28T03:58:01.2627664Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:145 +0x3c
2022-09-28T03:58:01.2628365Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).WaitUntilReady.func1()
2022-09-28T03:58:01.2629360Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:154 +0x34
2022-09-28T03:58:01.2629926Z   github.com/containerd/nydus-snapshotter/pkg/utils/retry.Do()
2022-09-28T03:58:01.2630675Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/utils/retry/retry.go:158 +0x455
2022-09-28T03:58:01.2631296Z   github.com/containerd/nydus-snapshotter/pkg/daemon.(*Daemon).WaitUntilReady()
2022-09-28T03:58:01.2632055Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/daemon/daemon.go:153 +0xf8
2022-09-28T03:58:01.2633167Z   github.com/containerd/nydus-snapshotter/pkg/filesystem/fs.(*Filesystem).WaitUntilReady()
2022-09-28T03:58:01.2633857Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/pkg/filesystem/fs/fs.go:585 +0xce
2022-09-28T03:58:01.2634536Z   github.com/containerd/nydus-snapshotter/snapshot.(*snapshotter).Mounts()
2022-09-28T03:58:01.2635214Z       /home/runner/work/nydus-snapshotter/nydus-snapshotter/snapshot/snapshot.go:233 +0x4b1
2022-09-28T03:58:01.2635668Z   github.com/containerd/containerd/contrib/snapshotservice.service.Mounts()
2022-09-28T03:58:01.2636316Z       /home/runner/go/pkg/mod/github.com/containerd/containerd@v1.6.6/contrib/snapshotservice/service.go:71 +0x97
2022-09-28T03:58:01.2636796Z   github.com/containerd/containerd/contrib/snapshotservice.(*service).Mounts()
2022-09-28T03:58:01.2637400Z       <autogenerated>:1 +0x7a
2022-09-28T03:58:01.2637803Z   github.com/containerd/containerd/api/services/snapshots/v1._Snapshots_Mounts_Handler()
2022-09-28T03:58:01.2638479Z       /home/runner/go/pkg/mod/github.com/containerd/containerd@v1.6.6/api/services/snapshots/v1/snapshots.pb.go:1162 +0x257
2022-09-28T03:58:01.2639004Z   google.golang.org/grpc.(*Server).processUnaryRPC()
2022-09-28T03:58:01.2639562Z       /home/runner/go/pkg/mod/google.golang.org/grpc@v1.43.0/server.go:1282 +0x1514
2022-09-28T03:58:01.2639941Z   google.golang.org/grpc.(*Server).handleStream()
2022-09-28T03:58:01.2640445Z       /home/runner/go/pkg/mod/google.golang.org/grpc@v1.43.0/server.go:1616 +0xfd3
2022-09-28T03:58:01.2640835Z   google.golang.org/grpc.(*Server).serveStreams.func1.2()
2022-09-28T03:58:01.2641352Z       /home/runner/go/pkg/mod/google.golang.org/grpc@v1.43.0/server.go:921 +0xfd

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-28 13:07:04 +08:00
Changwei Ge 2a8ffd69cf
Merge pull request #191 from changweige/support-use-http
support configure nydusd with use_http
2022-09-28 10:40:09 +08:00
Changwei Ge cac3b5af3e support configure nydusd with use_http
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-27 13:39:03 +08:00
Changwei Ge d2e533852e
Merge pull request #190 from changweige/fix-daemon-race
Fix daemon race
2022-09-27 11:59:35 +08:00
Changwei Ge a142ac5380 start snapshotter in multiple mode when test stargz
snapshotter is killed after starting in sharedmode,
the recovered snapshotter start in multiple mode.
Keep them the same.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-26 19:56:56 +08:00
Changwei Ge c03d3de5a2 reset daemon http client when clear vestige
So the client will be recreated to build http transport.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-26 19:46:41 +08:00
Changwei Ge a0af396f68 also start shared daemon if it can't be found
This is workaround for wrongly deleting daemon record
from DB. We still need a more reliable method to fix it.
It needs extra time

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-26 19:46:41 +08:00
Changwei Ge d7c5d7366e
Merge pull request #189 from changweige/fulfill-version
print version and build information
2022-09-26 19:42:46 +08:00
Changwei Ge 13b05da76d print version and build information
For debug and maintainece fake.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-26 18:40:54 +08:00
Changwei Ge 7e30f298ee
Merge pull request #180 from changweige/delete-daemon-in-the-first-place
delete daemon from DB in the first place when removing snapshot
2022-09-26 16:34:00 +08:00
Changwei Ge 03f7a0c808
Merge pull request #188 from changweige/remove-mirror-scheme
remove scheme from mirro configuration
2022-09-23 16:28:19 +08:00
Changwei Ge a0ea726903 no need to umount in snapshotter
Graceful termination of nydusd will umount automatically.
So we don't have to umount in snapshotter.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 15:42:08 +08:00
Changwei Ge 66dad9971d delete daemon from DB in the first place when removing snapshot
If any step fails after deleting daemon from DB, it won't
cause daemon record residual.

Residual daemon records will cause snapshotter restart the
nydusd continuously.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 15:22:11 +08:00
Changwei Ge 15c87ea9fd remove scheme from mirro configuration
Mirror host should be filled with URL rather than URI

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 15:20:07 +08:00
Changwei Ge 21af48d3d9
Merge pull request #187 from changweige/turn-to-fixed-delay
turn delay policy from Backoff to Fixed
2022-09-23 15:11:13 +08:00
Changwei Ge c5dff32b00 turn delay policy from Backoff to Fixed
Backendoff delay policy brings longer and longer
delay when retrying. So it brings long latency to
set up images snapshots when creating containers.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 12:22:15 +08:00
Changwei Ge 6714de89cf
Merge pull request #185 from changweige/print-pid-version
print process PID and program version to log
2022-09-23 12:00:50 +08:00
Changwei Ge 8cf4b48e85
Merge pull request #186 from changweige/remove-ctx
remove ctx from snapshotter object
2022-09-23 11:54:54 +08:00
Changwei Ge 6c904eebde remove ctx from snapshotter object
The ctx is only used to print log.
Let's use log.L instead

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 11:48:19 +08:00
Changwei Ge b75961b4b8
Merge pull request #173 from changweige/add-e2e-oci-compatibility
add e2e test for nydus-snapshotter OCI/overlayfs compatibility
2022-09-23 11:44:05 +08:00
Changwei Ge 8bd76edbb9 add e2e test for nydus-snapshotter OCI/overlayfs compatibility
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 11:32:40 +08:00
Changwei Ge b063aa3499 print process PID and program version to log
For debug and trace sake.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 10:56:58 +08:00
Changwei Ge b4baa6c31c
Merge pull request #181 from changweige/tiny-fix
fix wrong description in help message
2022-09-23 10:51:17 +08:00
Changwei Ge 1812c6d053 fix wrong description in help message
In addition remove --recover-plicy from systemd service file
since restart is default one now.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 10:41:31 +08:00
Changwei Ge cea98b8a56
Merge pull request #184 from changweige/fscache-recover
Fscache recover
2022-09-23 10:35:50 +08:00
Changwei Ge 5bf4778512 extract method ResetClient
It resets http client in order to initialize a new one.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-23 10:24:42 +08:00
Changwei Ge ccb8aea230 close race that event is overwritten when handling events
6c9533b6a733793b0aa6c83c72f9ae458e87dd41505d2077c9d874b3b91e8b74
go race detected
==================
WARNING: DATA RACE
Read at 0x00c00039c020 by goroutine 189:
  github.com/containerd/nydus-snapshotter/pkg/process.(*Manager).handleDaemonDeathEvent.func1()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:254 +0x5a

Previous write at 0x00c00039c020 by goroutine 31:
  github.com/containerd/nydus-snapshotter/pkg/process.(*Manager).handleDaemonDeathEvent()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:249 +0xf5
  github.com/containerd/nydus-snapshotter/pkg/process.NewManager.func1()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:319 +0x39

Goroutine 189 (running) created at:
  github.com/containerd/nydus-snapshotter/pkg/process.(*Manager).handleDaemonDeathEvent()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:253 +0x30e
  github.com/containerd/nydus-snapshotter/pkg/process.NewManager.func1()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:319 +0x39

Goroutine 31 (running) created at:
  github.com/containerd/nydus-snapshotter/pkg/process.NewManager()
      /home/gechangwei/git_repo/nydus-snapshotter/pkg/process/manager.go:319 +0x584
  github.com/containerd/nydus-snapshotter/snapshot.NewSnapshotter()
      /home/gechangwei/git_repo/nydus-snapshotter/snapshot/snapshot.go:80 +0x824
  github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/app/snapshotter.Start()
      /home/gechangwei/git_repo/nydus-snapshotter/cmd/containerd-nydus-grpc/app/snapshotter/main.go:23 +0xa9
  main.main.func1()
      /home/gechangwei/git_repo/nydus-snapshotter/cmd/containerd-nydus-grpc/main.go:48 +0x304
  github.com/urfave/cli/v2.(*App).RunContext()
      /home/gechangwei/go/pkg/mod/github.com/urfave/cli/v2@v2.3.0/app.go:322 +0x100c
  github.com/urfave/cli/v2.(*App).Run()
      /home/gechangwei/go/pkg/mod/github.com/urfave/cli/v2@v2.3.0/app.go:224 +0x4b5
  main.main()
      /home/gechangwei/git_repo/nydus-snapshotter/cmd/containerd-nydus-grpc/main.go:51 +0x44a
==================
make: *** [Makefile:71: integration] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-22 18:46:46 +08:00
Changwei Ge 18f30d5d6c add nydusd startup recover case for fscache driver
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-22 18:46:46 +08:00
Changwei Ge f2cf10b2e4 bump nydusd version to 2.1.0-rc.3.1
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-22 18:46:46 +08:00
Changwei Ge 7d8f445f8f clear vestiage for daemons started in fscache driver
They have different mount points.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-22 18:46:46 +08:00
Changwei Ge 4967a13650 install fscache configuration file
In order to perferm fscache driver snapshotter e2e test

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-22 15:45:53 +08:00
Changwei Ge 6d3b17639b
Merge pull request #178 from changweige/support-mirrors
support configure nydusd mirror registry
2022-09-21 16:52:33 +08:00
Changwei Ge a82fcf475b support configure nydusd mirror registry
Nydusd is going to support adding multiple registry
mirrors as a pull-through cache.
So snapshotter should also load mirror-related
configuration items and provide them to nydusd.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 16:22:40 +08:00
Changwei Ge 263201a3b6
Merge pull request #171 from changweige/daemons-monitor
Introduce daemons liveness monitor
2022-09-21 16:11:37 +08:00
Changwei Ge b0aee3c139
Merge pull request #151 from imeoer/converter-merge-fix
converter: fix incorrect blob list from merge
2022-09-21 16:01:49 +08:00
Changwei Ge 98c89f3775 rename clearDamonVestige to ClearVestige and relocate it
Make it more suggestive and encapsulated

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 15:22:49 +08:00
Changwei Ge 7212a95edb asynchronously recover nydusd in case it is blocked
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 13:04:19 +08:00
Changwei Ge 3b968aed19 add recover policy parser and use recover policy type
Instead of comparing to string, using specific type is
safer and clear.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 17c9319a8b rename waitDaemon to Wait and terminateDaemon to Terminate and relocate
them

Relocate them to daemon package as Daemon's methods

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 25896bb3b5 also subscribe death event when reconnecting to alive daemon
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 8e242f72d4 add comments to tell Add method behavior
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 3a965f8cde add method UpdateDaemon to update daemon cache and DB
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge f270b4e87f retry for extra 2400ms when connecting to nydusd
We have observed that nydusd starts very slowly.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge b890309bd1 wait for a while when stopping nydus-snapshotter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge c89704c28b recover each rafs instance for shared mode daemon
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 83c8a16ece add ut test for manager daemon states cache
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge ede8b493a1 add daemon states cache test
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge c0de7ec26c retry to connect api sock when subscribing
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 1ffa1d95bd lock daemen when reading or writing PID to close race
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 51eb3b859d also install nydusctl to e2e test container
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge e784799d3d add e2e test case for liveness monitor
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge ee64effe1b add flag --recover-policy to control how to recover nydusd
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:07:30 +08:00
Changwei Ge 4ab6ee4beb restart nydusd on its death
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge b1d1318496 extract functions to terminate and wait nydusd
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge 885177a255 extract a helper function to clear dead nydusd vestige
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge 8540a323e1 add a helper function to identify host mountpoint
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge d6eca94150 also update states cache after nydusd started
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge 773558cfbd start liveness monitor when creating daemons manager
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge 9000ec3f22 public a function to ensure socket file existence
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Changwei Ge f335748f00 introduce daemons monitor
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-21 12:02:41 +08:00
Yan Song b16a068584 converter: fix incorrect blob list from merge
Affected by chunk dict, the blob list referenced by final bootstrap
are from different layers, part of them are from original layers,
part from chunk dict bootstrap.

So we need to rewrite manifest's layers using the real blob list
referenced by final bootstrap.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-09-20 03:04:19 +00:00
Changwei Ge 4894e28122
Merge pull request #175 from bergwolf/github/nydusd-cli
manager: update nydusd commandline options
2022-09-19 19:21:55 +08:00
Changwei Ge 913c6b769d
Merge pull request #177 from changweige/close-file
close file after opened and written
2022-09-18 13:24:00 +08:00
Changwei Ge d1fc731db6 close file after opened and written
Otherwise, it is leaked.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-16 15:12:25 +08:00
Peng Tao 3126c7593c manager: update nydusd commandline options
We've renamed `daemon` subcommand to `singleton`.

Signed-off-by: Peng Tao <bergwolf@hyper.sh>
2022-09-16 11:25:18 +08:00
Changwei Ge 0f88fb6a4f
Merge pull request #170 from power-more/zhaoshang/remove-label
[Bugfix] Modify the logic of obtaining image ref when deleting snapshots
2022-09-15 21:33:13 +08:00
zhaoshang 3c88f4a651 [Bugfix] Modify the logic of obtaining image ref when deleting snapshots
In some cases, such as a user-defined label in the upper layer, the
snapshot label is not empty, but does not contain
"containerd.io/snapshot/cri.image-ref", the function should continue to
execute normally instead of returning an error.

Signed-off-by: zhaoshang <zhaoshangsjtu@linux.alibaba.com>
2022-09-15 16:40:56 +08:00
Changwei Ge 29fcf03a72
Merge pull request #172 from changweige/e2e-detect-race
detect go race condition when perform e2e test
2022-09-15 08:29:43 +08:00
Changwei Ge b272b0d580 detect go race condition when perform e2d test
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-14 18:03:58 +08:00
Changwei Ge 8af7157257
Merge pull request #169 from changweige/fix-lint
replace deprecated ioutil package
2022-09-13 15:58:24 +08:00
Changwei Ge 4b95461b9f
Merge pull request #150 from sctb512/main
converter: add buffer for io.Writer
2022-09-13 15:58:07 +08:00
Changwei Ge f8cfe3885d
Merge pull request #152 from changweige/recover-after-restart
Enhance daemon states management to improve usability and stability
2022-09-13 15:57:39 +08:00
Changwei Ge f86c9051eb e2e test re-run containiers after pruning all containers
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge f3030665ef manager daemon state getter can't fail
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge b09247e4be add ErrNotFound effor defintion
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 5f1b9dd6b9 enable integration tests for only restarting snapshotter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 085bdc1542 no need to for new nydusd if they are already running
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 57c0f77e96 add integration test for recovering nydusds
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 8e58c11a97 also recover each nydusd for mupltiple daemon mode
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 378f308cf7 recover ever persisted daemon when restarting snapshotter
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge ca181d0ec3 don't clean up DB when reconnecting all nydusd daemons
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 9b7920e1f1 daemons manager use new states cache
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 224b816ce7 DB Store implementation does not operate states in-memory cache
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 6e71b1d1ee Store interface does not operate in-memory cache
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 0284cd5002 add in-memory daemon states cache for daemons manager
Decouple daemon states cache from persistence storage in DB.
So it is easier to do nydusd daemon recover.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 15:22:14 +08:00
Changwei Ge 5fe38f6012 replace deprecated ioutil package
golangci-lint run
WARN [runner] The linter 'varcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter.  Replaced by unused.
WARN [runner] The linter 'structcheck' is deprecated (since v1.49.0) due to: The owner seems to have abandoned the linter.  Replaced by unused.
pkg/signature/signature.go:12:2: SA1019: "io/ioutil" has been deprecated since Go 1.16: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)
	"io/ioutil"
	^
pkg/filesystem/fs/fs.go:15:2: SA1019: "io/ioutil" has been deprecated since Go 1.16: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)
	"io/ioutil"
	^
pkg/converter/convert_unix.go:19:2: SA1019: "io/ioutil" has been deprecated since Go 1.16: As of Go 1.16, the same functionality is now provided by package io or package os, and those implementations should be preferred in new code. See the specific function documentation for details. (staticcheck)
	"io/ioutil"
	^
make: *** [Makefile:52: check] Error 1

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 13:54:54 +08:00
Bin Tang 0d1f51be16 converter: add buffer for io.Writer
add buffer for io.Writer to improve
nydus image conversion performation.

Signed-off-by: Bin Tang <tangbin.bin@bytedance.com>
2022-09-13 11:46:05 +08:00
Changwei Ge d2f4610380
Merge pull request #168 from changweige/fix-log-test-residual
clean up test purpose log directory
2022-09-13 10:22:49 +08:00
Changwei Ge 5b875cf6ce clean up test purpose log directory
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-13 10:19:12 +08:00
Changwei Ge 8a8d51a49f
Merge pull request #163 from zyfjeff/remove-timeout-limit
Remove default http timeout limit
2022-09-09 10:49:06 +08:00
zyfjeff 455c472e39 Remove default http timeout limit
When the single-layer image is too large or the network bandwidth is poor,
it is easy to reach this timeout period. The default resolver of docker has no timeout limit,
so this timeout limit is removed here, and the timeout is controlled by upper-layer tools such as nerdctl/ct.

Signed-off-by: zyfjeff <zyfjeff@linux.alibaba-inc.com>
2022-09-08 05:42:10 +00:00
Changwei Ge 8cc0c230b4
Merge pull request #160 from changweige/fix-none-mode-lowerdir
give NoneMode mount option with lowerdir=/dummy
2022-09-06 15:33:56 +08:00
Changwei Ge 80efb1604c give NoneMode mount option with lowerdir=/dummy
NoneMode nydus-snapshotter does not start nydusd and
no container image mounted contents are provided. Only
info in mount options are meaningful. So give a dummy
mount dir there.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-09-06 15:21:26 +08:00
Changwei Ge f17066c55a
Merge pull request #159 from imeoer/converter-export-methods
converter: export IsNydusBlob and MergeLayers methods
2022-09-06 11:37:35 +08:00
Yan Song 72644df4f9 converter: export IsNydusBlob and MergeLayers methods
Make them easier for buildkit/nerdctl/acceld components to use.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-09-06 03:22:03 +00:00
Changwei Ge cc9c5bed4b
Merge pull request #155 from imeoer/converter-api-improvement
converter: improve method options
2022-09-01 15:00:31 +08:00
Changwei Ge b9c1f927a2
Merge pull request #154 from imeoer/converter-diff-calculation
converter: improve performance by calculating diffid ahead of time
2022-09-01 11:49:33 +08:00
Changwei Ge 31cd41171c
Merge pull request #153 from changweige/add-erofs-test
add e2e test for fscache driver
2022-09-01 11:09:00 +08:00
Changwei Ge e2f20997ca
Merge pull request #157 from changweige/fscache-prefetch-conf
configure prefetch in example fscache nydusd config file
2022-09-01 11:08:41 +08:00
Changwei Ge 3d900f2d88 configure prefetch in example fscache nydusd config file
So nydusd in fscache mode can have a better porformance.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-31 21:20:43 +08:00
Changwei Ge 1ba65a45e7 add e2e test for fscache driver
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-31 13:31:47 +08:00
Yan Song 8af4106c51 converter: improve method options
Update some comments for exported methods in the same time.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-08-31 02:43:56 +00:00
Yan Song 84767d44c6 converter: improve performance by calculating diffid ahead of time
Write a diff id label of layer in content store for simplifying
diff id calculation to speed up the conversion.
See: e4fefea554/images/diffid.go (L49)

Related performance test: https://github.com/goharbor/acceleration-service/pull/50

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-08-31 02:29:10 +00:00
Changwei Ge 63b1bcb6a2
Merge pull request #146 from power-more/zhaoshang/cmdkill
fix: kill nydus-image process with timeout
2022-08-26 17:42:12 +08:00
zhaoshang 7a643a9db8 add Timeout field for converter options
Signed-off-by: zhaoshang <zhaoshangsjtu@linux.alibaba.com>
2022-08-26 16:47:24 +08:00
zhaoshang 942a20e612 fix: kill nydus-image process with timeout
In general, nydus-image does not run timeout, but in order to be
prepared, after all, there is such a risk in theory.
In addition, we found in some business scenarios that in extreme cases
(such as insufficient CPU resources and too large OCI layers), the
conversion time of nydus-image process may be calculated in hours.

Signed-off-by: zhaoshang <zhaoshangsjtu@linux.alibaba.com>
2022-08-26 16:47:24 +08:00
Changwei Ge d6b5c65f58
Merge pull request #149 from changweige/fix-default-dir
e2e test use new default root dir
2022-08-26 16:42:17 +08:00
Changwei Ge f630cd15e6 e2e test use new default root dir
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 16:24:00 +08:00
Changwei Ge 4d57893631
Merge pull request #147 from imeoer/fix-converter-workdir
converter: create work directory if not exists
2022-08-26 15:14:42 +08:00
Changwei Ge d7a0200a57
Merge pull request #143 from changweige/change-default-root
change default work root dir to /var/lib/containerd-nydus
2022-08-26 15:14:00 +08:00
Changwei Ge c141269768
Merge pull request #140 from changweige/e2e-test.2
Add containerized e2e test
2022-08-26 15:13:44 +08:00
Yan Song 0013df1683 converter: create work directory if not exists
In case users forget to create the work directory before using converter.

Signed-off-by: Yan Song <imeoer@linux.alibaba.com>
2022-08-26 06:59:23 +00:00
Changwei Ge 7db468d12c change default work root dir to /var/lib/containerd-nydus
Thus to keep consistent with /run/containerd-nydus

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:36:25 +08:00
Changwei Ge 258dc4791b
Merge pull request #148 from changweige/auto-start-nydusd
clean up nydus vestige when starting
2022-08-26 13:32:27 +08:00
Changwei Ge 1a8c238c97 remove image.yml github action
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge 4a741e4a63 enable stargz e2e test
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge 6dc8733c55 fix example toml format
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge 4bcf4e0adb add integration test makefile target
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge b6e500936d add snapshotter e2e test scripts with nerdctl
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge 8f12cadc1b add github e2e test action
Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:23:36 +08:00
Changwei Ge 5381d65a18 change snapshootter address in ontainerd config
Thus to meet the default address of nydus-snapshotter.
Then it will be easier to experience nydus

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 13:22:55 +08:00
Changwei Ge c61b91e6bc clean up nydus vestige when starting
Nydusd judges if it should enter failover phrase by
checking residual disconnected unix socket file and mounted
mountpoint. But if snapshotter is restarting, nydusd can't fetch
back its states. So just start a fresh nydusd

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-26 12:40:46 +08:00
Changwei Ge a0f3d22d72
Merge pull request #141 from changweige/fix-goarch
Make current machine's arch as defaulted GOARCH
2022-08-25 14:21:49 +08:00
Changwei Ge c1a8520343 Make current machine's arch as defaulted GOARCH
When building on arm64 machine, don't build amd64 as default GOARCH.

Signed-off-by: Changwei Ge <gechangwei@bytedance.com>
2022-08-23 17:01:56 +08:00
Changwei Ge d6588e8bc0
Merge pull request #139 from zyfjeff/fix-permission
Change upperPath permission from 0750 to 0755
2022-08-22 14:18:57 +08:00
zyfjeff 6ed31543e8 Change upperPath permission from 0750 to 0755
The user of ctr/nerdctl may be different from the user of nydus snapshotter.
In order to allow users of ctr and nerdctl to access rootfs, other group permissions need to be given here,
and the default permission of overlayfs is also 0755

Signed-off-by: zyfjeff <zyfjeff@linux.alibaba-inc.com>
2022-08-22 06:13:10 +00:00
276 changed files with 31346 additions and 7182 deletions

23
.github/codecov.yml vendored Normal file
View File

@ -0,0 +1,23 @@
coverage:
status:
patch: off
project:
default:
enabled: yes
target: auto # auto compares coverage to the previous base commit
# adjust accordingly based on how flaky your tests are
# this allows a 0.3% drop from the previous base commit coverage
threshold: 0.3%
comment:
layout: "reach, diff, flags, files"
behavior: default
require_changes: true # if true: only post the comment if coverage changes
codecov:
require_ci_to_pass: false
notify:
wait_for_ci: true
# When modifying this file, please validate using
# curl -X POST --data-binary @codecov.yml https://codecov.io/validate

View File

@ -2,116 +2,113 @@ name: CI
on:
push:
branches: ["*"]
branches: ["**", "stable/**"]
pull_request:
branches: [main]
branches: ["**", "stable/**"]
env:
CARGO_TERM_COLOR: always
jobs:
build:
name: Build
name: Build and Lint
timeout-minutes: 10
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '1.17'
- name: Check out code
uses: actions/checkout@v1
- name: cache go mod
uses: actions/cache@v2
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: golangci-lint
uses: golangci/golangci-lint-action@v6
with:
version: v1.59
skip-cache: true
- name: Build
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.43.0
export PATH=$PATH:$(go env GOPATH)/bin
make
make test
make check
build-optimizer:
name: Build optimizer
timeout-minutes: 10
runs-on: ubuntu-22.04
steps:
- name: Check out code
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Build
run: |
rustup component add rustfmt clippy
make build-optimizer
smoke:
name: Smoke
timeout-minutes: 10
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '1.17'
- name: Check out code
uses: actions/checkout@v1
- name: cache go mod
uses: actions/cache@v2
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Set up containerd
uses: crazy-max/ghaction-setup-containerd@v3
- name: Build
run: |
# Download nydus components
NYDUS_VER=v$(curl -s "https://api.github.com/repos/dragonflyoss/image-service/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget https://github.com/dragonflyoss/image-service/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz
NYDUS_VER=v$(curl -fsSL --header 'authorization: Bearer ${{ secrets.GITHUB_TOKEN }}' "https://api.github.com/repos/dragonflyoss/nydus/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget -q https://github.com/dragonflyoss/nydus/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz
tar xzvf nydus-static-$NYDUS_VER-linux-amd64.tgz
mkdir -p /usr/bin
sudo mv nydus-static/nydus-image nydus-static/nydusd-fusedev nydus-static/nydusify /usr/bin/
sudo mv nydus-static/nydus-image nydus-static/nydusd nydus-static/nydusify /usr/bin/
export PATH=$PATH:$(go env GOPATH)/bin
make smoke
cross-build-test:
name: Cross Build Test
timeout-minutes: 10
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
strategy:
matrix:
GOOS: ['linux', 'windows', 'darwin']
GOARCH: ['amd64', 'arm64']
GOOS: ["linux", "windows", "darwin"]
GOARCH: ["amd64", "arm64"]
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: '1.17'
- name: Check out code
uses: actions/checkout@v1
- name: cache go mod
uses: actions/cache@v2
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Build
run: |
make -e GOOS=${{ matrix.GOOS }} GOARCH=${{ matrix.GOARCH }}
make -e GOOS=${{ matrix.GOOS }} GOARCH=${{ matrix.GOARCH }} converter
coverage:
name: Code coverage
timeout-minutes: 10
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
needs: [build]
steps:
- name: Install Go
uses: actions/setup-go@v3
with:
go-version: '1.17'
- name: Checkout code
uses: actions/checkout@v2
- name: cache go mod
uses: actions/cache@v2
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Run unit tests.
run: make cover
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v1
uses: codecov/codecov-action@v4
with:
token: ${{ secrets.CODECOV_TOKEN }} # not required for public repos
files: ./coverage.txt

66
.github/workflows/e2e.yml vendored Normal file
View File

@ -0,0 +1,66 @@
name: integration test
on:
push:
branches:
- "main"
tags:
- v[0-9]+.[0-9]+.[0-9]+
pull_request:
branches:
- "main"
schedule:
# Trigger test every day at 00:03 clock UTC
- cron: "3 0 * * *"
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
REGISTRY: ghcr.io
jobs:
run-e2e-for-cgroups-v1:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Log in to container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Run e2e test
run: |
TAG=$GITHUB_REF_NAME
[ "$TAG" == "main" ] && TAG="latest"
[ "$GITHUB_EVENT_NAME" == "pull_request" ] && TAG="local"
make integration
run-e2e-for-cgroups-v2:
runs-on: ubuntu-24.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Log in to container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Run e2e test
run: |
TAG=$GITHUB_REF_NAME
[ "$TAG" == "main" ] && TAG="latest"
[ "$GITHUB_EVENT_NAME" == "pull_request" ] && TAG="local"
make integration

View File

@ -1,203 +0,0 @@
name: nydus-snapshotter image
on:
push:
branches:
- "main"
tags:
- v[0-9]+.[0-9]+.[0-9]+
pull_request:
branches:
- "main"
env:
CARGO_TERM_COLOR: always
REGISTRY: ghcr.io
ORGANIZATION: ${{ github.repository }}
CNI_VERSION: v1.1.0
CRICTL_VERSION: v1.23.0
jobs:
build-image:
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v3
with:
go-version: "1.17"
- name: Checkout repository
uses: actions/checkout@v2
- name: cache go mod
uses: actions/cache@v2
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
- name: Build nydus-snapshotter
run: |
make static-release
cp bin/containerd-nydus-grpc misc/snapshotter
- name: Log in to container registry
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Build and push nydus-snapshotter image
run: |
TAG=$GITHUB_REF_NAME
[ "$TAG" == "main" ] && TAG="latest"
[ "$GITHUB_EVENT_NAME" == "pull_request" ] && TAG="local"
cd misc/snapshotter
docker build -t ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:$TAG .
# Only push for non pull_request
if [ "$GITHUB_EVENT_NAME" != "pull_request" ]; then
docker push ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:$TAG
fi
- name: Prepare nydus-snapshotter image test
if: ${{ github.event_name == 'pull_request' }}
run: |
sudo mkdir -p /var/lib/containerd-test/ /etc/containerd/ /opt/cni/bin/ /etc/cni/net.d/
sudo cp misc/example/containerd-test-config.toml /etc/containerd/
sudo cp misc/example/crictl.yaml /etc/
sudo cp misc/example/10-containerd-net.conflist /etc/cni/net.d/
# install cni plugin
wget https://github.com/containernetworking/plugins/releases/download/${{ env.CNI_VERSION }}/cni-plugins-linux-amd64-${{ env.CNI_VERSION }}.tgz
sudo tar xzf cni-plugins-linux-amd64-${{ env.CNI_VERSION }}.tgz -C /opt/cni/bin/
# install crictl
wget https://github.com/kubernetes-sigs/cri-tools/releases/download/${{ env.CRICTL_VERSION }}/crictl-${{ env.CRICTL_VERSION }}-linux-amd64.tar.gz
tar xzf crictl-${{ env.CRICTL_VERSION }}-linux-amd64.tar.gz -C /usr/local/bin/
# install nydus-overlayfs
NYDUS_VER=v$(curl -s "https://api.github.com/repos/dragonflyoss/image-service/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget https://github.com/dragonflyoss/image-service/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz
tar xzf nydus-static-$NYDUS_VER-linux-amd64.tgz
sudo cp nydus-static/nydus-overlayfs /usr/local/sbin/
sudo cp nydus-static/ctr-remote /usr/local/sbin/
# install containerd
#CONTAINERD_VER=$(curl -s "https://api.github.com/repos/containerd/containerd/releases/latest" | jq -r .tag_name | sed 's/^v//')
# Let's use fixed containerd version for now.
CONTAINERD_VER=1.6.1
wget https://github.com/containerd/containerd/releases/download/v$CONTAINERD_VER/containerd-$CONTAINERD_VER-linux-amd64.tar.gz
tar xzf containerd-$CONTAINERD_VER-linux-amd64.tar.gz
sudo cp bin/* /usr/local/bin/
- name: Test nydus-snapshotter image
if: ${{ github.event_name == 'pull_request' }}
run: |
# start nydus-snapshotter
docker run -d --name snapshotter --device /dev/fuse --cap-add SYS_ADMIN --security-opt apparmor:unconfined -e CONTAINERD_ROOT=/var/lib/containerd-test -v /var/lib/containerd-test:/var/lib/containerd-test:shared -v ~/.docker/config.json:/root/.docker/config.json:shared ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:local
# start containerd
sudo /usr/local/bin/containerd --config /etc/containerd/containerd-test-config.toml -l debug &
# wait for containerd to start up
sleep 10
echo "Pull nydus-latest image"
sudo crictl pull ghcr.io/dragonflyoss/image-service/ubuntu:nydus-latest
docker logs `docker ps |grep "nydus-snapshotter"|cut -d ' ' -f1`
echo "create new pod with nydus snapshotter"
sudo crictl run misc/example/container.yaml misc/example/pod.yaml
container=$(sudo crictl ps -q)
echo "check container liveness"
sudo crictl exec $container ls
echo "delete pod"
sudo crictl rmp -fa
- name: Cleanup containerd and snapshotter
if: ${{ github.event_name == 'pull_request' }}
run: |
echo "stop snapshotter"
docker stop snapshotter
docker rm snapshotter
echo "stop containerd"
sudo pkill -f /usr/local/bin/containerd
echo "delete containerd dir"
# After the snapshotter container is stopped, it seems that Nydusd doesn't umount it
# so we need to umount it here, otherwise you cannot delete this directory.
# Frankly, I don't know why Nydusd didn't clean up these resources.
sudo umount -f /var/lib/containerd-test/io.containerd.snapshotter.v1.nydus/mnt
sudo rm -rf /var/lib/containerd-test/*
- name: Test nydus-snapshotter with multiple daemon mode
if: ${{ github.event_name == 'pull_request' }}
run: |
# start nydus-snapshotter
docker run -d --name snapshotter --device /dev/fuse --cap-add SYS_ADMIN --security-opt apparmor:unconfined -e CONTAINERD_ROOT=/var/lib/containerd-test -e NYDUSD_DAEMON_MODE=multiple -v /var/lib/containerd-test:/var/lib/containerd-test:shared -v ~/.docker/config.json:/root/.docker/config.json:shared ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:local
# start containerd
sudo /usr/local/bin/containerd --config /etc/containerd/containerd-test-config.toml -l debug &
# wait for containerd to start up
sleep 10
echo "Pull nydus-latest image"
sudo crictl pull ghcr.io/dragonflyoss/image-service/ubuntu:nydus-latest
docker logs `docker ps |grep "nydus-snapshotter"|cut -d ' ' -f1`
echo "create new pod with nydus snapshotter"
sudo crictl run misc/example/container.yaml misc/example/pod.yaml
container=$(sudo crictl ps -q)
echo "check container liveness"
sudo crictl exec $container ls
echo "delete pod"
sudo crictl rmp -fa
sudo crictl rmi --all --prune
- name: Cleanup containerd and snapshotter
if: ${{ github.event_name == 'pull_request' }}
run: |
echo "stop snapshotter"
docker stop snapshotter
docker rm snapshotter
echo "stop containerd"
sudo pkill -f /usr/local/bin/containerd
echo "delete containerd dir"
sudo rm -rf /var/lib/containerd-test/*
- name: Test nydus-snapshotter image in localfs mode
if: ${{ github.event_name == 'pull_request' }}
run: |
# start nydus-snapshotter
docker run -d --name snapshotter --device /dev/fuse --cap-add SYS_ADMIN --security-opt apparmor:unconfined -e BACKEND_TYPE=localfs -e CONTAINERD_ROOT=/var/lib/containerd-test -v /var/lib/containerd-test:/var/lib/containerd-test:shared -v ~/.docker/config.json:/root/.docker/config.json:shared ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:local
docker_snapshotter=$(docker ps -q)
# start containerd
sudo /usr/local/bin/containerd --config /etc/containerd/containerd-test-config.toml -l debug &
# wait for containerd to start up
sleep 10
echo "Pull nydus-latest image"
sudo crictl pull ghcr.io/dragonflyoss/image-service/ubuntu:nydus-latest
docker logs `docker ps |grep "nydus-snapshotter"|cut -d ' ' -f1`
echo "create new pod with nydus snapshotter"
sudo crictl run misc/example/container.yaml misc/example/pod.yaml
container=$(sudo crictl ps -q)
echo "check container liveness"
sudo crictl exec $container ls
echo "delete pod"
sudo crictl rmp -fa
echo "delete nydus-latest image"
sudo crictl rmi ghcr.io/dragonflyoss/image-service/ubuntu:nydus-latest
echo "check whether the blobs of nydus-latest image has been deleted"
docker exec -i $docker_snapshotter sh -c 'if [ "`ls -A /tmp/blobs/`" != "" ]; then exit 1; fi'
- name: Cleanup containerd and snapshotter
if: ${{ github.event_name == 'pull_request' }}
run: |
echo "stop snapshotter"
docker stop snapshotter
docker rm snapshotter
echo "stop containerd"
sudo pkill -f /usr/local/bin/containerd
echo "delete containerd dir"
# After the snapshotter container is stopped, it seems that Nydusd doesn't umount it
# so we need to umount it here, otherwise you cannot delete this directory.
# Frankly, I don't know why Nydusd didn't clean up these resources.
sudo umount -f /var/lib/containerd-test/io.containerd.snapshotter.v1.nydus/mnt
sudo rm -rf /var/lib/containerd-test/*
- name: Test nydus-snapshotter with estargz image
if: ${{ github.event_name == 'pull_request' }}
run: |
# start nydus-snapshotter
docker run -d --name snapshotter --device /dev/fuse --cap-add SYS_ADMIN --security-opt apparmor:unconfined -e CONTAINERD_ROOT=/var/lib/containerd-test -v /var/lib/containerd-test:/var/lib/containerd-test:shared -v ~/.docker/config.json:/root/.docker/config.json:shared ${{ env.REGISTRY }}/${{ env.ORGANIZATION }}/nydus-snapshotter:local
# start containerd
sudo /usr/local/bin/containerd --config /etc/containerd/containerd-test-config.toml -l debug &
# wait for containerd to start up
sleep 10
echo "pull estargz image"
sudo crictl pull ghcr.io/stargz-containers/wordpress:5.9.2-esgz
docker logs `docker ps |grep "nydus-snapshotter"|cut -d ' ' -f1`
echo "create new pod with nydus snapshotter"
sudo crictl run misc/example/container.yaml misc/example/pod.yaml
container=$(sudo crictl ps -q)
echo "check container liveness"
sudo crictl exec $container ls
echo "delete pod"
sudo crictl rmp -fa

21
.github/workflows/k8s-e2e-run.yml vendored Normal file
View File

@ -0,0 +1,21 @@
name: E2E Test With Kubernetes
on:
push:
branches:
- "main"
tags:
- v[0-9]+.[0-9]+.[0-9]+
pull_request:
branches: [main]
jobs:
cri_auth:
uses: ./.github/workflows/k8s-e2e.yml
with:
auth-type: cri
kubeconf_auth:
uses: ./.github/workflows/k8s-e2e.yml
with:
auth-type: kubeconf

63
.github/workflows/k8s-e2e.yml vendored Normal file
View File

@ -0,0 +1,63 @@
name: E2E Test With Kubernetes Template
on:
workflow_call:
inputs:
auth-type:
required: true
type: string
env:
DOCKER_USER: testuser
DOCKER_PASSWORD: testpassword
NAMESPACE: nydus-system
jobs:
e2e_tests_k8s:
runs-on: ubuntu-22.04
timeout-minutes: 30
steps:
- name: Checkout code
uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup Golang
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: Test
run: |
AUTH_TYPE='${{ inputs.auth-type }}'
./tests/helpers/kind.sh
- name: Dump logs
if: failure()
continue-on-error: true
run: |
log_dir="/tmp/nydus-log"
mkdir -p $log_dir
for p in `kubectl --namespace "$NAMESPACE" get pods --no-headers -o custom-columns=NAME:metadata.name`; do
kubectl --namespace "$NAMESPACE" get pod $p -o yaml >> $log_dir/nydus-pods.conf
kubectl --namespace "$NAMESPACE" describe pod $p >> $log_dir/nydus-pods.conf
kubectl --namespace "$NAMESPACE" logs $p -c nydus-snapshotter >> $log_dir/nydus-snapshotter.log || echo "failed to get snapshotter log"
done
kubectl --namespace "$NAMESPACE" get secrets -o yaml >> $log_dir/nydus-secrets.log
docker exec kind-control-plane cat /etc/containerd/config.toml >> $log_dir/containerd-config.toml
docker exec kind-control-plane containerd config dump >> $log_dir/containerd-config-dump.toml
docker exec kind-control-plane journalctl --no-pager -u containerd >> $log_dir/containerd.log
docker exec kind-control-plane journalctl --no-pager -u kubelet >> $log_dir/kubelet.log
docker exec kind-control-plane ps -ef >> $log_dir/psef.log
kubectl get pod test-pod -o yaml >> $log_dir/test-pod.log || echo "test-pod may be deleted or not created"
cat ~/.docker/config.json > $log_dir/docker.config.json || echo "~/.docker/config.json not found"
- name: Upload Logs
uses: actions/upload-artifact@v4
if: failure()
with:
name: k8s-e2e-tests-logs
path: |
/tmp/nydus-log
overwrite: true

109
.github/workflows/optimizer.yml vendored Normal file
View File

@ -0,0 +1,109 @@
name: optimizer test
on:
push:
branches:
- "main"
tags:
- v[0-9]+.[0-9]+.[0-9]+
pull_request:
branches:
- "main"
schedule:
# Trigger test every day at 00:03 clock UTC
- cron: "3 0 * * *"
workflow_dispatch:
env:
CARGO_TERM_COLOR: always
jobs:
run_optimizer:
runs-on: ubuntu-22.04
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Golang
uses: actions/setup-go@v5
with:
go-version-file: 'go.mod'
cache-dependency-path: "go.sum"
- name: cache cargo
uses: actions/cache@v4
with:
path: |
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
tools/optimizer-server/target/
key: ${{ runner.os }}-cargo-${{ hashFiles('tools/optimizer-server/Cargo.lock') }}
restore-keys: |
${{ runner.os }}-cargo
- name: containerd runc and crictl
run: |
sudo wget -q https://github.com/kubernetes-sigs/cri-tools/releases/download/v1.26.0/crictl-v1.26.0-linux-amd64.tar.gz
sudo tar zxvf ./crictl-v1.26.0-linux-amd64.tar.gz -C /usr/local/bin
sudo install -D -m 755 misc/optimizer/crictl.yaml /etc/crictl.yaml
sudo wget -q https://github.com/containerd/containerd/releases/download/v1.7.0/containerd-static-1.7.0-linux-amd64.tar.gz
sudo systemctl stop containerd
sudo tar -zxf ./containerd-static-1.7.0-linux-amd64.tar.gz -C /usr/
sudo install -D -m 755 misc/optimizer/containerd-config.toml /etc/containerd/config.toml
sudo systemctl restart containerd
sudo wget -q https://github.com/opencontainers/runc/releases/download/v1.1.5/runc.amd64 -O /usr/bin/runc
sudo chmod +x /usr/bin/runc
- name: Setup CNI
run: |
wget -q https://github.com/containernetworking/plugins/releases/download/v1.2.0/cni-plugins-linux-amd64-v1.2.0.tgz
sudo mkdir -p /opt/cni/bin
sudo tar xzf cni-plugins-linux-amd64-v1.2.0.tgz -C /opt/cni/bin/
sudo install -D -m 755 misc/example/10-containerd-net.conflist /etc/cni/net.d/10-containerd-net.conflist
- name: Build and install optimizer
run: |
rustup component add rustfmt clippy
make optimizer
sudo chown -R $(id -un):$(id -gn) . ~/.cargo/
pwd
ls -lh bin/*optimizer*
sudo make install-optimizer
sudo install -D -m 755 misc/example/optimizer-nri-plugin.conf /etc/nri/conf.d/02-optimizer-nri-plugin.conf
sudo systemctl restart containerd
systemctl status containerd --no-pager -l
- name: Wait containerd ready
run: |
unset READY
for i in $(seq 30); do
if eval "timeout 180 ls /run/containerd/containerd.sock"; then
READY=true
break
fi
echo "Fail(${i}). Retrying..."
sleep 1
done
if [ "$READY" != "true" ];then
echo "containerd is not ready"
exit 1
fi
- name: Generate accessed files list
run: |
sed -i "s|host_path: script|host_path: $(pwd)/misc/optimizer/script|g" misc/optimizer/nginx.yaml
sudo crictl run misc/optimizer/nginx.yaml misc/optimizer/sandbox.yaml
sleep 20
sudo crictl rmp -f --all
tree /opt/nri/optimizer/results/
count=$(cat /opt/nri/optimizer/results/library/nginx:1.23.3 | wc -l)
expected=$(cat misc/optimizer/script/file_list.txt | wc -l)
echo "count: $count expected minimum value: $expected"
if [ $count -lt $expected ]; then
echo "failed to generate accessed files list for nginx:1.23.3"
cat misc/optimizer/script/file_list.txt
exit 1
fi
cat /opt/nri/optimizer/results/library/nginx:1.23.3.csv
- name: Dump logs
if: failure()
continue-on-error: true
run: |
systemctl status containerd --no-pager -l
journalctl -xeu containerd --no-pager

View File

@ -7,66 +7,180 @@ on:
env:
CARGO_TERM_COLOR: always
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
build:
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
strategy:
matrix:
include:
- build-os: linux
build-arch: amd64
build-linker: x86-64
- build-os: linux
build-arch: arm64
build-linker: aarch64
- build-os: linux
build-arch: s390x
build-linker: s390x
- build-os: linux
build-arch: ppc64le
build-linker: powerpc64le
- build-os: linux
build-arch: riscv64
build-linker: riscv64
- build-os: linux
build-arch: static
build-linker: static
steps:
- uses: actions/checkout@v2
- uses: actions/setup-go@v3
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version: '1.17'
go-version: "1.22.5"
- name: cache go mod
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: ~/go/pkg/mod
key: ${{ runner.os }}-go-${{ hashFiles('go.sum') }}
key: ${{ matrix.build-os }}-go-${{ hashFiles('go.sum') }}
restore-keys: |
${{ runner.os }}-go
- name: build nydus-snapshotter
run: |
curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.43.0
export PATH=$PATH:$(go env GOPATH)/bin
make
- name: upload artifacts
uses: actions/upload-artifact@v2
${{ matrix.build-os }}-go
- name: cache cargo
uses: actions/cache@v4
with:
name: nydus-snapshotter_artifacts
path: |
bin/containerd-nydus-grpc
~/.cargo/bin/
~/.cargo/registry/index/
~/.cargo/registry/cache/
~/.cargo/git/db/
tools/optimizer-server/target/
key: ${{ matrix.build-os }}-cargo-${{ hashFiles('tools/optimizer-server/Cargo.lock') }}
restore-keys: |
${{ matrix.build-os }}-cargo
- name: install gnu gcc linker
run: |
if [ "${{ matrix.build-linker }}" != "static" ]; then
sudo apt-get install -qq gcc-${{ matrix.build-linker }}-linux-gnu
fi
- name: build nydus-snapshotter and optimizer
run: |
go install github.com/golangci/golangci-lint/cmd/golangci-lint@v1.51.2
export PATH=$PATH:$(go env GOPATH)/bin
if [ "${{ matrix.build-arch }}" == "static" ]; then
make static-package
else
make package GOOS=${{ matrix.build-os }} GOARCH=${{ matrix.build-arch }}
fi
- name: upload artifacts
uses: actions/upload-artifact@v4
with:
name: release-tars-${{ matrix.build-os }}-${{ matrix.build-arch }}
path: |
package/*.tar.gz*
overwrite: true
upload:
runs-on: ubuntu-latest
runs-on: ubuntu-22.04
needs: [build]
steps:
- uses: actions/checkout@v2
- name: install hub
run: |
HUB_VER=$(curl -s "https://api.github.com/repos/github/hub/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget -q -O- https://github.com/github/hub/releases/download/v$HUB_VER/hub-linux-amd64-$HUB_VER.tgz | \
tar xz --strip-components=2 --wildcards '*/bin/hub'
sudo mv hub /usr/local/bin/hub
- name: download artifacts
uses: actions/download-artifact@v2
- uses: actions/checkout@v4
- name: Download Artifacts
uses: actions/download-artifact@v4
with:
name: nydus-snapshotter_artifacts
path: nydus-snapshotter
- name: upload artifacts
run: |
tag=$(echo $GITHUB_REF | cut -d/ -f3-)
tarball="nydus-snapshotter-$tag-x86_64.tgz"
chmod +x nydus-snapshotter/*
tar cf - nydus-snapshotter | gzip > ${tarball}
echo "tag=$tag" >> $GITHUB_ENV
echo "tarball=$tarball" >> $GITHUB_ENV
tarball_shasum="$tarball.sha256sum"
sha256sum $tarball > $tarball_shasum
echo "tarball_shasum=$tarball_shasum" >> $GITHUB_ENV
path: builds
- name: Release
uses: softprops/action-gh-release@v1
with:
name: "Nydus Snapshotter ${{ env.tag }} Release"
name: "Nydus Snapshotter ${{ github.ref_name }} Release"
generate_release_notes: true
files:
${{ env.tarball }}
${{ env.tarball_shasum }}
files: |
builds/release-tars-**/*
publish-image:
runs-on: ubuntu-22.04
needs: [build]
strategy:
matrix:
include:
- build-os: linux
build-arch: amd64
- build-os: linux
build-arch: arm64
- build-os: linux
build-arch: s390x
- build-os: linux
build-arch: ppc64le
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: download artifacts
uses: actions/download-artifact@v4
with:
name: release-tars-${{ matrix.build-os }}-${{ matrix.build-arch }}
path: misc/snapshotter
- name: unpack static release
run: |
cd misc/snapshotter && tar -zxf *.tar.gz && mv bin/* . && rm -rf bin
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Get the nydusd version
run: |
export NYDUS_STABLE_VER=$(curl -fsSL https://api.github.com/repos/dragonflyoss/nydus/releases/latest | jq -r .tag_name)
echo "NYDUS_STABLE_VER=$NYDUS_STABLE_VER" >> "$GITHUB_ENV"
printf 'nydus version is: %s\n' "$NYDUS_STABLE_VER"
- name: build and push nydus-snapshotter image
uses: docker/build-push-action@v5
with:
context: misc/snapshotter
file: misc/snapshotter/Dockerfile
push: true
platforms: ${{ matrix.build-os }}/${{ matrix.build-arch }}
provenance: false
tags: |
${{ fromJSON(steps.meta.outputs.json).tags[0] }}-${{ matrix.build-arch }}
${{ fromJSON(steps.meta.outputs.json).tags[1] }}-${{ matrix.build-arch }}
labels: ${{ steps.meta.outputs.labels }}
build-args: NYDUS_VER=${{ env.NYDUS_STABLE_VER }}
publish-manifest:
runs-on: ubuntu-22.04
needs: [publish-image]
steps:
- name: Log in to the container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@v4
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
- name: Publish manifest for multi-arch image
run: |
IFS=',' read -ra tags <<< "$(echo "${{ steps.meta.outputs.tags }}" | tr '\n' ',')"
for tag in "${tags[@]}"; do
docker manifest create "${tag}" \
--amend "${tag}-amd64" \
--amend "${tag}-arm64" \
--amend "${tag}-s390x" \
--amend "${tag}-ppc64le"
docker manifest push "${tag}"
done

4
.gitignore vendored
View File

@ -2,3 +2,7 @@ bin/
pkg/filesystem/stargz/testdata/db/
coverage.txt
.vscode/
tests/output/
smoke.tests
tools/optimizer-server/target
vendor/

View File

@ -1,23 +1,77 @@
# https://golangci-lint.run/usage/configuration#config-file
run:
concurrency: 4
timeout: 5m
issues-exit-code: 1
tests: true
issues:
exclude-dirs:
- misc
# The package is ported from containerd project, let's skip it.
- pkg/remote/remotes
linters-settings:
depguard:
rules:
main:
deny:
- pkg: "github.com/containerd/containerd/errdefs"
desc: The containerd errdefs package was migrated to a separate module. Use github.com/containerd/errdefs instead.
- pkg: "github.com/containerd/containerd/log"
desc: The containerd log package was migrated to a separate module. Use github.com/containerd/log instead.
- pkg: "github.com/containerd/containerd/platforms"
desc: The containerd platforms package was migrated to a separate module. Use github.com/containerd/platforms instead.
- pkg: "github.com/containerd/containerd/reference/docker"
desc: The containerd platforms package was migrated to a separate module. Use github.com/distribution/reference instead.
# govet:
# check-shadowing: true
# enable:
# - fieldalignment
funlen:
# Checks the number of lines in a function.
# If lower than 0, disable the check.
# Default: 60
lines: 100
# Checks the number of statements in a function.
# If lower than 0, disable the check.
# Default: 40
statements: 80
nilnil:
checked-types:
- ptr
- func
- iface
- map
- chan
linters:
enable:
- structcheck
- varcheck
- depguard # Checks for imports that shouldn't be used.
- staticcheck
- unconvert
- gofmt
- goimports
- revive
- ineffassign
- vet
- govet
- unused
- misspell
disable:
- bodyclose
# - cyclop
- dogsled
- nilnil
- unparam
- nilerr
# - goerr113
- exportloopref
# - gosec
- gocritic
- prealloc
- tenv
# - funlen
- exhaustive
- errcheck
run:
deadline: 4m
skip-dirs:
- misc
disable:
- gosec

View File

@ -7,7 +7,10 @@
# GitHub ID, Name, Email address
changweige, Changwei Ge, changweige@gmail.com
eryugey, Eryu Guan, eguan@linux.alibaba.com
imeoer, Yan Song, yansong.ys@antgroup.com
#
# REVIEWERS
# GitHub ID, Name, Email address
imeoer, Yan Song, imeoer@linux.alibaba.com
sctb512, Bin Tang, tangbin.bin@bytedance.com

139
Makefile
View File

@ -1,15 +1,33 @@
all: clear build
all: clean build
optimizer: clean-optimizer build-optimizer
VERSION=$(shell git rev-parse --verify HEAD --short=7)
BRANCH=$(shell git rev-parse --abbrev-ref HEAD)
PKG = github.com/containerd/nydus-snapshotter
PACKAGES ?= $(shell go list ./... | grep -v /tests)
SUDO = $(shell which sudo)
GO_EXECUTABLE_PATH ?= $(shell which go)
NYDUS_BUILDER ?= /usr/bin/nydus-image
NYDUS_NYDUSD ?= /usr/bin/nydusd-fusedev
NYDUS_NYDUSD ?= /usr/bin/nydusd
GOOS ?= linux
GOARCH ?= amd64
#GOPROXY ?= https://goproxy.io
GOARCH ?= $(shell go env GOARCH)
KERNEL_VER = $(shell uname -r)
# Used to populate variables in version package.
BUILD_TIMESTAMP=$(shell date '+%Y-%m-%dT%H:%M:%S')
VERSION=$(shell git describe --match 'v[0-9]*' --dirty='.m' --always --tags)
REVISION=$(shell git rev-parse HEAD)$(shell if ! git diff --no-ext-diff --quiet --exit-code; then echo .m; fi)
RELEASE=nydus-snapshotter-v$(VERSION:v%=%)-${GOOS}-${GOARCH}
STATIC_RELEASE=nydus-snapshotter-v$(VERSION:v%=%)-${GOOS}-static
# Relpace test target images for e2e tests.
ifdef E2E_TEST_TARGET_IMAGES_FILE
ENV_TARGET_IMAGES_FILE = --env-file ${E2E_TEST_TARGET_IMAGES_FILE}
endif
ifdef E2E_DOWNLOADS_MIRROR
BUILD_ARG_E2E_DOWNLOADS_MIRROR = --build-arg DOWNLOADS_MIRROR=${E2E_DOWNLOADS_MIRROR}
endif
ifdef GOPROXY
PROXY := GOPROXY="${GOPROXY}"
@ -21,25 +39,100 @@ else
FS_DRIVER = fusedev
endif
SNAPSHOTTER_CONFIG=/etc/nydus/config.toml
SOURCE_SNAPSHOTTER_CONFIG=misc/snapshotter/config.toml
NYDUSD_CONFIG=/etc/nydus/nydusd-config.${FS_DRIVER}.json
SOURCE_NYDUSD_CONFIG=misc/snapshotter/nydusd-config.${FS_DRIVER}.json
SNAPSHOTTER_SYSTEMD_UNIT_SERVICE=misc/snapshotter/nydus-snapshotter.${FS_DRIVER}.service
LDFLAGS = -s -w -X ${PKG}/version.Version=${VERSION} -X ${PKG}/version.Revision=$(REVISION) -X ${PKG}/version.BuildTimestamp=$(BUILD_TIMESTAMP)
DEBUG_LDFLAGS = -X ${PKG}/version.Version=${VERSION} -X ${PKG}/version.Revision=$(REVISION) -X ${PKG}/version.BuildTimestamp=$(BUILD_TIMESTAMP)
CARGO ?= $(shell which cargo)
OPTIMIZER_SERVER = tools/optimizer-server
OPTIMIZER_SERVER_TOML = ${OPTIMIZER_SERVER}/Cargo.toml
OPTIMIZER_SERVER_BIN = ${OPTIMIZER_SERVER}/bin/optimizer-server
.PHONY: build
build:
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags="-s -w -X 'main.Version=${VERSION}'" -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS)" -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS)" -v -o bin/nydus-overlayfs ./cmd/nydus-overlayfs
.PHONY: static
static:
CGO_ENABLED=0 GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS) -extldflags -static" -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
CGO_ENABLED=0 GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS) -extldflags -static" -v -o bin/nydus-overlayfs ./cmd/nydus-overlayfs
debug:
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(DEBUG_LDFLAGS)" -gcflags "-N -l" -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(DEBUG_LDFLAGS)" -gcflags "-N -l" -v -o bin/nydus-overlayfs ./cmd/nydus-overlayfs
.PHONY: build-optimizer
build-optimizer:
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS)" -v -o bin/optimizer-nri-plugin ./cmd/optimizer-nri-plugin
make -C tools/optimizer-server release OS=$(GOOS) ARCH=$(GOARCH) && cp ${OPTIMIZER_SERVER_BIN} ./bin
static-release:
CGO_ENABLED=0 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags '-s -w -X "main.Version=${VERSION}" -extldflags "-static"' -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
CGO_ENABLED=0 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags "$(LDFLAGS) -extldflags -static" -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
CGO_ENABLED=0 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags "$(LDFLAGS) -extldflags -static" -v -o bin/nydus-overlayfs ./cmd/nydus-overlayfs
CGO_ENABLED=0 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags "$(LDFLAGS) -extldflags -static" -v -o bin/optimizer-nri-plugin ./cmd/optimizer-nri-plugin
make -C tools/optimizer-server static-release && cp ${OPTIMIZER_SERVER_BIN} ./bin
.PHONY: clear
clear:
package/$(RELEASE).tar.gz: build build-optimizer
mkdir -p package
rm -rf package/$(RELEASE) package/$(RELEASE).tar.gz
tar -czf package/$(RELEASE).tar.gz bin
rm -rf package/$(RELEASE)
package/$(STATIC_RELEASE).tar.gz: static-release
@mkdir -p package
@rm -rf package/$(STATIC_RELEASE) package/$(STATIC_RELEASE).tar.gz
@tar -czf package/$(STATIC_RELEASE).tar.gz bin
@rm -rf package/$(STATIC_RELEASE)
package: package/$(RELEASE).tar.gz
cd package && sha256sum $(RELEASE).tar.gz >$(RELEASE).tar.gz.sha256sum
static-package: package/$(STATIC_RELEASE).tar.gz
@cd package && sha256sum $(STATIC_RELEASE).tar.gz >$(STATIC_RELEASE).tar.gz.sha256sum
# Majorly for cross build for converter package since it is imported by other projects
converter:
GOOS=${GOOS} GOARCH=${GOARCH} ${PROXY} go build -ldflags "$(LDFLAGS)" -v -o bin/converter ./cmd/converter
.PHONY: clean
clean:
rm -f bin/*
rm -rf _out
.PHONY: clean-optimizer
clean-optimizer:
rm -rf bin/optimizer-nri-plugin bin/optimizer-server
make -C tools/optimizer-server clean
.PHONY: install
install: static-release
sudo install -D -m 755 bin/containerd-nydus-grpc /usr/local/bin/containerd-nydus-grpc
sudo install -D -m 755 misc/snapshotter/nydusd-config.${FS_DRIVER}.json /etc/nydus/config.json
sudo install -D -m 644 misc/snapshotter/nydus-snapshotter.${FS_DRIVER}.service /etc/systemd/system/nydus-snapshotter.service
sudo systemctl enable /etc/systemd/system/nydus-snapshotter.service
install:
@echo "+ $@ bin/containerd-nydus-grpc"
@sudo install -D -m 755 bin/containerd-nydus-grpc /usr/local/bin/containerd-nydus-grpc
@echo "+ $@ bin/nydus-overlayfs"
@sudo install -D -m 755 bin/nydus-overlayfs /usr/local/bin/nydus-overlayfs
@if [ ! -e ${NYDUSD_CONFIG} ]; then echo "+ $@ SOURCE_NYDUSD_CONFIG"; sudo install -D -m 664 ${SOURCE_NYDUSD_CONFIG} ${NYDUSD_CONFIG}; fi
@if [ ! -e ${SNAPSHOTTER_CONFIG} ]; then echo "+ $@ ${SOURCE_SNAPSHOTTER_CONFIG}"; sudo install -D -m 664 ${SOURCE_SNAPSHOTTER_CONFIG} ${SNAPSHOTTER_CONFIG}; fi
@sudo ln -f -s /etc/nydus/nydusd-config.${FS_DRIVER}.json /etc/nydus/nydusd-config.json
@echo "+ $@ ${SNAPSHOTTER_SYSTEMD_UNIT_SERVICE}"
@sudo install -D -m 644 ${SNAPSHOTTER_SYSTEMD_UNIT_SERVICE} /etc/systemd/system/nydus-snapshotter.service
@sudo mkdir -p /etc/nydus/certs.d
@if which systemctl >/dev/null; then sudo systemctl enable /etc/systemd/system/nydus-snapshotter.service; sudo systemctl restart nydus-snapshotter; fi
install-optimizer:
sudo install -D -m 755 bin/optimizer-nri-plugin /opt/nri/plugins/02-optimizer-nri-plugin
sudo install -D -m 755 bin/optimizer-server /usr/local/bin/optimizer-server
sudo install -D -m 755 misc/example/optimizer-nri-plugin.conf /etc/nri/conf.d/02-optimizer-nri-plugin.conf
@sudo mkdir -p /opt/nri/optimizer/results
.PHONY: vet
vet:
@ -58,6 +151,18 @@ cover:
go test -v -covermode=atomic -coverprofile=coverage.txt $(PACKAGES)
go tool cover -func=coverage.txt
# make smoke TESTS=TestPack
smoke:
$(SUDO) NYDUS_BUILDER=${NYDUS_BUILDER} NYDUS_NYDUSD=${NYDUS_NYDUSD} ${GO_EXECUTABLE_PATH} test -race -v ./tests
$(SUDO) NYDUS_BUILDER=${NYDUS_BUILDER} NYDUS_NYDUSD=${NYDUS_NYDUSD} ${GO_EXECUTABLE_PATH} test -race -v ./tests -args -fs-version=6
${GO_EXECUTABLE_PATH} test -o smoke.tests -c -race -v -cover ./tests
$(SUDO) -E NYDUS_BUILDER=${NYDUS_BUILDER} NYDUS_NYDUSD=${NYDUS_NYDUSD} ./smoke.tests -test.v -test.timeout 10m -test.parallel=8 -test.run=$(TESTS)
.PHONY: integration
integration:
CGO_ENABLED=1 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags '-X "${PKG}/version.Version=${VERSION}" -extldflags "-static"' -race -v -o bin/containerd-nydus-grpc ./cmd/containerd-nydus-grpc
CGO_ENABLED=1 ${PROXY} GOOS=${GOOS} GOARCH=${GOARCH} go build -ldflags '-X "${PKG}/version.Version=${VERSION}" -extldflags "-static"' -race -v -o bin/nydus-overlayfs ./cmd/nydus-overlayfs
$(SUDO) docker build ${BUILD_ARG_E2E_DOWNLOADS_MIRROR} -t nydus-snapshotter-e2e:0.1 -f integration/Dockerfile .
$(SUDO) docker run --cap-add SYS_ADMIN --security-opt seccomp=unconfined --cgroup-parent=system.slice --cgroupns private --name nydus-snapshotter_e2e --rm --privileged -v /root/.docker:/root/.docker -v `go env GOMODCACHE`:/go/pkg/mod \
-v `go env GOCACHE`:/root/.cache/go-build -v `pwd`:/nydus-snapshotter \
-v /usr/src/linux-headers-${KERNEL_VER}:/usr/src/linux-headers-${KERNEL_VER} \
${ENV_TARGET_IMAGES_FILE} \
nydus-snapshotter-e2e:0.1

170
README.md
View File

@ -1,14 +1,37 @@
[**[⬇️ Download]**](https://github.com/containerd/nydus-snapshotter/releases)
[**[📖 Website]**](https://nydus.dev/)
[**[☸ Quick Start (Kubernetes)**]](https://github.com/containerd/nydus-snapshotter/blob/main/docs/run_nydus_in_kubernetes.md)
[**[🤓 Quick Start (nerdctl)**]](https://github.com/containerd/nerdctl/blob/master/docs/nydus.md)
[**[❓ FAQs & Troubleshooting]**](https://github.com/dragonflyoss/nydus/wiki/FAQ)
# Nydus Snapshotter
<p><img src="https://github.com/dragonflyoss/image-service/blob/master/misc/logo.svg" width="170"></p>
<p><img src="https://github.com/dragonflyoss/nydus/blob/master/misc/logo.svg" width="170"></p>
[![Release Version](https://img.shields.io/github/v/release/containerd/nydus-snapshotter?style=flat)](https://github.com/containerd/nydus-snapshotter/releases)
[![LICENSE](https://img.shields.io/github/license/containerd/nydus-snapshotter.svg?style=flat)](https://github.com/containerd/nydus-snapshotter/blob/main/LICENSE)
![CI](https://github.com/containerd/nydus-snapshotter/actions/workflows/ci.yml/badge.svg?event=push)
[![Go Report Card](https://goreportcard.com/badge/github.com/containerd/nydus-snapshotter?style=flat)](https://goreportcard.com/report/github.com/containerd/nydus-snapshotter)
[![Twitter](https://img.shields.io/twitter/url?style=social&url=https%3A%2F%2Ftwitter.com%2Fdragonfly_oss)](https://twitter.com/dragonfly_oss)
[![Nydus Stars](https://img.shields.io/github/stars/dragonflyoss/nydus?label=Nydus%20Stars&style=social)](https://github.com/dragonflyoss/nydus)
Nydus-snapshotter is a **non-core** sub-project of containerd.
Nydus snapshotter is an external plugin of containerd for [Nydus image service](https://nydus.dev) which implements a chunk-based content-addressable filesystem on top of a called `RAFS (Registry Acceleration File System)` format that improves the current OCI image specification, in terms of container launching speed, image space, and network bandwidth efficiency, as well as data integrity with several runtime backends: FUSE, virtiofs and in-kernel [EROFS](https://www.kernel.org/doc/html/latest/filesystems/erofs.html).
Nydus supports lazy pulling feature since pulling image is one of the time-consuming steps in the container lifecycle. Lazy pulling here means a container can run even the image is partially available and necessary chunks of the image are fetched on-demand. Apart from that, Nydus also supports [(e)Stargz](https://github.com/containerd/stargz-snapshotter) lazy pulling directly **WITHOUT** any explicit conversion.
Nydus supports lazy pulling feature since pulling image is one of the time-consuming steps in the container lifecycle. Lazy pulling here means a container can run even the image is partially available and necessary chunks of the image are fetched on-demand. Apart from that, Nydus also supports [(e)Stargz](https://github.com/containerd/stargz-snapshotter) and OCI (by using [zran](https://github.com/dragonflyoss/nydus/blob/master/docs/nydus-zran.md)) lazy pulling directly **WITHOUT** any explicit conversion.
For more details about how to build Nydus container image, please refer to [nydusify](https://github.com/dragonflyoss/image-service/blob/master/docs/nydusify.md) conversion tool and [acceld](https://github.com/goharbor/acceleration-service).
For more details about how to build Nydus container image, please refer to [nydusify](https://github.com/dragonflyoss/nydus/blob/master/docs/nydusify.md) conversion tool and [acceld](https://github.com/goharbor/acceleration-service).
## Architecture
### Architecture Based on FUSE
![fuse arch](./docs/diagram/nydus_fuse_arch.svg)
### Architecture Based on Fscache/Erofs
![fscache arch](./docs/diagram/nydus_fscache_erofs_arch.svg)
## Building
@ -20,6 +43,8 @@ make
## Integrate Nydus-snapshotter into Containerd
The following document will describe how to manually configure containerd + Nydus snapshotter. If you want to run Nydus snapshotter in Kubernetes cluster, you can try to use helm or run nydus snapshotter as a container. You can refer to [this documentation](./docs/run_nydus_in_kubernetes.md).
Containerd provides a general mechanism to exploit different types of snapshotters. Please ensure your containerd's version is 1.4.0 or above.
Add Nydus as a proxy plugin into containerd's configuration file which may be located at `/etc/containerd/config.toml`.
@ -37,48 +62,39 @@ Restart your containerd service making the change take effect. Assume that your
systemctl restart containerd
```
## Get Nydusd Binary
### Get Nydus Binaries
Find a suitable `nydusd` release for you from [nydus releases page](https://github.com/dragonflyoss/image-service/releases).
Get `nydusd` `nydus-image` and `nydusctl` binaries from [nydus releases page](https://github.com/dragonflyoss/nydus/releases).
It's suggested to install the binaries to your system path. `nydusd` is FUSE userspace daemon and a vhost-user-fs backend. Nydus-snapshotter
will fork a nydusd process when necessary.
`nydusd-fusedev` is FUSE userspace daemon handling linux kernel FUSE requests from `/dev/fuse` frontend.
`nydusd-virtiofs` is a virtiofs daemon handling guest kernel FUSE requests.
### Configure Nydus
## Configure Nydus
Please follow instructions to [configure nydus](./docs/configure_nydus.md) in order to make it work properly in your environment.
Nydus is configured by a json file which is required now. Since Nydus container images are likely stored in a registry, where auth has to be provided.
Please follow instructions to [configure nydus](./docs/configure_nydus.md) configure Nydus in order to make it work properly in your environment.
## Start Nydus Snapshotter
### Start Nydus Snapshotter
Nydus-snapshotter is implemented as a [proxy plugin](https://github.com/containerd/containerd/blob/04985039cede6aafbb7dfb3206c9c4d04e2f924d/PLUGINS.md#proxy-plugins) (`containerd-nydus-grpc`) for containerd.
Assume your server systemd based, install nydus-snapshotter:
Assume your server is systemd based, install nydus-snapshotter:
Note: `nydusd` and `nydus-image` should be found from $PATH.
```bash
make install
systemctl restart containerd
```
Or you can start nydus-snapshotter manually.
```bash
# `nydusd-path` is the path to nydusd binary
# `address` is the domain socket that you configured in containerd configuration file
# `root` is the path to Nydus snapshotter
# `config-path` is the path to Nydus configuration file
$ ./containerd-nydus-grpc \
--config-path /etc/nydusd-config.json \
--shared-daemon \
--log-level info \
--root /var/lib/containerd/io.containerd.snapshotter.v1.nydus \
--cache-dir /var/lib/nydus/cache \
--address /run/containerd-nydus/containerd-nydus-grpc.sock \
--nydusd-path /usr/local/bin/nydusd \
--nydusimg-path /usr/local/bin/nydus-image \
--log-to-stdout
```
You could append `--enable-stargz` to the command line above in order to enable (e)Stargz support.
```bash
# `--nydusd` specifies the path to nydusd binary. If `nydusd` and `nydus-image` are installed, `--nydusd` and `--nydus-image`can be omitted.
# Otherwise, provide them in below command line.
# `address` is the domain socket that you configured in containerd configuration file
# `--nydusd-config` is the path to `nydusd` configuration file
# The default nydus-snapshotter work directory is located at `/var/lib/containerd/io.containerd.snapshotter.v1.nydus`
$ sudo ./containerd-nydus-grpc --config /etc/nydus/config.toml --nydusd-config /etc/nydus/nydusd-config.json --log-to-stdout
```
### Validate Nydus-snapshotter Setup
@ -90,37 +106,25 @@ TYPE ID PLATFORMS STATUS
io.containerd.snapshotter.v1 nydus - ok
```
## Quickly Start Container with Lazy Pulling
### Optimize Nydus Image as per Workload
### Start Container on Node
Nydus usually prefetch image data to local filesystem before a real user on-demand read. It helps to improve the performance and availability. A containerd NRI plugin [container image optimizer](docs/optimize_nydus_image.md) can be used to generate nydus image building suggestions to optimize your nydus image making the nydusd runtime match your workload IO pattern. The optimized nydus image has
a better performance.
Containerd can start container with specified snapshotter, so `nerdctl` or `ctr` needs to specify the Nydus snapshotter when start container.
## Quickstart Container with Lazy Pulling
A CLI tool [ctr-remote](https://github.com/dragonflyoss/image-service/tree/master/contrib/ctr-remote) is alongside. Use Nydus `ctr-remote` to pull Nydus image or start container based on nydus image.
### Start Container on single Node
Start container using `nerdctl` (>=v0.22) which has native nydus support with `nydus-snapshotter`.
```bash
$ sudo ctr-remote image rpull ghcr.io/dragonflyoss/image-service/nginx:nydus-latest
fetching sha256:75002dfe... application/vnd.oci.image.manifest.v1+json
fetching sha256:5a42e21c... application/vnd.oci.image.config.v1+json
fetching sha256:eb1af2e1... application/vnd.oci.image.layer.v1.tar+gzip
# Start container by `ctr-remote`
$ sudo ctr-remote run --snapshotter nydus ghcr.io/dragonflyoss/image-service/nginx:nydus-latest awesome-nydus
# Start container by `nerdctl`
nerdctl --snapshotter nydus run ghcr.io/dragonflyoss/image-service/nginx:nydus-latest
```
In addition that, `nerdctl` can now directly pull Nydus or (e)Stargz images with Nydus snapshotter without `ctr-remote` involved:
### Start Container in Kubernetes Cluster
```bash
# Start an eStargz container with Nydus snapshotter by `nerdctl`
nerdctl --snapshotter nydus run -it --rm ghcr.io/stargz-containers/fedora:35-esgz
```
### Start Container in Kubernetes
**NOTE:** A potential drawback using CRI is that we can hardly specify snapshotter to `nydus-snapshotter`. So we have to change containerd's default snapshotter in its configuration file and enable snapshot annotations like below:
Change containerd's CRI configuration:
```toml
[plugins."io.containerd.grpc.v1.cri".containerd]
@ -131,11 +135,71 @@ nerdctl --snapshotter nydus run -it --rm ghcr.io/stargz-containers/fedora:35-esg
Use `crictl` to debug starting container via Kubernetes CRI. Dry run [steps](./docs/crictl_dry_run.md) of using `crictl` can be found in [documents](./docs).
### Setup with nydus-snapshotter image
We can also use the `nydus-snapshotter` container image when we want to put Nydus stuffs inside a container. See the [nydus-snapshotter exmple](./misc/example/README.md) for how to setup and use it.
We can also use the `nydus-snapshotter` container image when we want to put Nydus stuffs inside a container. See the [nydus-snapshotter example](./misc/example/README.md) for how to setup and use it.
## Integrate with Dragonfly to Distribute Images by P2P
Nydus is a sub-project of [Dragonfly](https://github.com/dragonflyoss/dragonfly). So it closely works with Dragonfly to distribute container images in a fast and efficient P2P fashion to reduce network latency and lower the pressure on a single-point of the registry.
### Quickstart Dragonfly & Nydus in Kubernetes
We recommend using the Dragonfly P2P data distribution system to further improve the runtime performance of Nydus images.
If you want to deploy Dragonfly and Nydus at the same time, please refer to this **[Quick Start](https://github.com/dragonflyoss/helm-charts/blob/main/INSTALL.md)**.
### Config Dragonfly mode
Dragonfly supports both **mirror** mode and HTTP **proxy** mode to boost the containers startup. It is suggested to use Dragonfly mirror mode. To integrate with Dragonfly in the mirror mode, please provide registry mirror in nydusd's json configuration file in section `device.backend.mirrors`
```json
{
"mirrors": [
{
"host": "http://127.0.0.1:65001",
"headers": "https://index.docker.io/v1/"
}
]
}
```
### Hot updating mirror configurations
In addition to setting the registry mirror in nydusd's json configuration file, `nydus-snapshotter` also supports hot updating mirror configurations. You can set the configuration directory in nudus-snapshotter's toml configuration file with `remote.mirrors_config.dir`. The empty `remote.mirrors_config.dir` means disabling it.
```toml
[remote.mirrors_config]
dir = "/etc/nydus/certs.d"
```
Configuration file is compatible with containerd's configuration file in toml format.
```toml
[host]
[host."http://127.0.0.1:65001"]
[host."http://127.0.0.1:65001".header]
# NOTE: For Dragonfly, the HTTP scheme must be explicitly specified.
X-Dragonfly-Registry = ["https://p2p-nydus.com"]
```
Mirror configurations loaded from nydusd's json file will be overwritten before pulling image if the valid mirror configuration items loaded from `remote.mirrors_config.dir` are greater than 0.
## Community
Nydus aims to form a **vendor-neutral opensource** image distribution solution to all communities.
Questions, bug reports, technical discussion, feature requests and contribution are always welcomed!
Join our Slack [workspace](https://join.slack.com/t/nydusimageservice/shared_invite/zt-pz4qvl4y-WIh4itPNILGhPS8JqdFm_w)
We're very pleased to hear your use cases any time.
Feel free to reach/join us via Slack and/or Dingtalk.
- **Slack:** [Nydus Workspace](https://join.slack.com/t/nydusimageservice/shared_invite/zt-pz4qvl4y-WIh4itPNILGhPS8JqdFm_w)
- **Twitter:** [@dragonfly_oss](https://twitter.com/dragonfly_oss)
- **Dingtalk:** [34971767](https://qr.dingtalk.com/action/joingroup?code=v1,k1,ioWGzuDZEIO10Bf+/ohz4RcQqAkW0MtOwoG1nbbMxQg=&_dt_no_comment=1&origin=11)
<img src="https://github.com/dragonflyoss/nydus/blob/master/misc/dingtalk.jpg" width="250" height="300"/>
- **Technical Meeting:** Every Wednesday at 06:00 UTC (Beijing, Shanghai 14:00), please see our [HackMD](https://hackmd.io/@Nydus/Bk8u2X0p9) page for more information.
## License
[![FOSSA Status](https://app.fossa.com/api/projects/git%2Bgithub.com%2Fcontainerd%2Fnydus-snapshotter.svg?type=large)](https://app.fossa.com/projects/git%2Bgithub.com%2Fcontainerd%2Fnydus-snapshotter?ref=badge_large)

View File

@ -1,38 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package snapshotter
import (
"context"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/pkg/auth"
"github.com/containerd/nydus-snapshotter/pkg/utils/signals"
"github.com/containerd/nydus-snapshotter/snapshot"
)
func Start(ctx context.Context, cfg config.Config) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
rs, err := snapshot.NewSnapshotter(ctx, &cfg)
if err != nil {
return errors.Wrap(err, "failed to initialize snapshotter")
}
stopSignal := signals.SetupSignalHandler()
opt := ServeOptions{
ListeningSocketPath: cfg.Address,
}
if cfg.EnableKubeconfigKeychain {
auth.InitKubeSecretListener(ctx, cfg.KubeconfigPath)
}
return Serve(ctx, rs, opt, stopSignal)
}

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package snapshotter
import (
"context"
"net"
"os"
"path/filepath"
snapshotsapi "github.com/containerd/containerd/api/services/snapshots/v1"
"github.com/containerd/containerd/contrib/snapshotservice"
"github.com/containerd/containerd/log"
"github.com/containerd/containerd/snapshots"
"github.com/pkg/errors"
"google.golang.org/grpc"
)
type ServeOptions struct {
ListeningSocketPath string
}
func Serve(ctx context.Context, rs snapshots.Snapshotter, options ServeOptions, stop <-chan struct{}) error {
err := ensureSocketNotExists(options.ListeningSocketPath)
if err != nil {
return err
}
rpc := grpc.NewServer()
snapshotsapi.RegisterSnapshotsServer(rpc, snapshotservice.FromSnapshotter(rs))
l, err := net.Listen("unix", options.ListeningSocketPath)
if err != nil {
return errors.Wrapf(err, "error on listen socket %q", options.ListeningSocketPath)
}
go func() {
sig := <-stop
log.G(ctx).Infof("caught signal %s: shutting down", sig)
err := l.Close()
if err != nil {
log.G(ctx).Errorf("failed to close listener %s, err: %v", options.ListeningSocketPath, err)
}
}()
return rpc.Serve(l)
}
func ensureSocketNotExists(listeningSocketPath string) error {
if err := os.MkdirAll(filepath.Dir(listeningSocketPath), 0700); err != nil {
return errors.Wrapf(err, "failed to create directory %q", filepath.Dir(listeningSocketPath))
}
finfo, err := os.Stat(listeningSocketPath)
// err is nil means listening socket path exists, remove before serve
if err == nil {
if finfo.Mode()&os.ModeSocket == 0 {
return errors.Errorf("file %s is not a socket", listeningSocketPath)
}
err := os.Remove(listeningSocketPath)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,29 +0,0 @@
{
"device": {
"backend": {
"type": "registry",
"config": {
"scheme": "https",
"auth": "",
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 0
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/tmp/nydus-rs/cache"
}
}
},
"mode": "direct",
"digest_validate": true,
"iostats_files": true,
"enable_xattr": true,
"fs_prefetch": {
"enable": true,
"threads_count": 10,
"merging_size": 131072
}
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
@ -7,52 +8,103 @@
package main
import (
"fmt"
"os"
"github.com/containerd/containerd/log"
"github.com/containerd/log"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/app/snapshotter"
"github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/pkg/command"
"github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/pkg/logging"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/internal/flags"
"github.com/containerd/nydus-snapshotter/internal/logging"
"github.com/containerd/nydus-snapshotter/pkg/errdefs"
"github.com/containerd/nydus-snapshotter/version"
)
func main() {
flags := command.NewFlags()
flags := flags.NewFlags()
app := &cli.App{
Name: "containerd-nydus-grpc",
Usage: "Nydus remote snapshotter for containerd",
Version: Version,
Flags: flags.F,
Action: func(c *cli.Context) error {
var cfg config.Config
if err := command.Validate(flags.Args, &cfg); err != nil {
return errors.Wrap(err, "invalid argument")
Name: "containerd-nydus-grpc",
Usage: "Nydus remote snapshotter for containerd",
Version: version.Version,
Flags: flags.F,
HideVersion: true,
Action: func(_ *cli.Context) error {
if flags.Args.PrintVersion {
fmt.Println("Version: ", version.Version)
fmt.Println("Revision: ", version.Revision)
fmt.Println("Go version: ", version.GoVersion)
fmt.Println("Build time: ", version.BuildTimestamp)
return nil
}
snapshotterConfigPath := flags.Args.SnapshotterConfigPath
var defaultSnapshotterConfig config.SnapshotterConfig
var snapshotterConfig config.SnapshotterConfig
if err := defaultSnapshotterConfig.FillUpWithDefaults(); err != nil {
return errors.New("failed to generate nydus default configuration")
}
// Once snapshotter's configuration file is provided, parse it and let command line parameters override it.
if snapshotterConfigPath != "" {
if c, err := config.LoadSnapshotterConfig(snapshotterConfigPath); err == nil {
// Command line parameters override the snapshotter's configurations for backwards compatibility
if err := config.ParseParameters(flags.Args, c); err != nil {
return errors.Wrap(err, "failed to parse commandline options")
}
snapshotterConfig = *c
} else {
return errors.Wrapf(err, "failed to load snapshotter configuration from %q", snapshotterConfigPath)
}
} else {
if err := config.ParseParameters(flags.Args, &snapshotterConfig); err != nil {
return errors.Wrap(err, "failed to parse commandline options")
}
}
if err := config.MergeConfig(&snapshotterConfig, &defaultSnapshotterConfig); err != nil {
return errors.Wrap(err, "failed to merge configurations")
}
if err := config.ValidateConfig(&snapshotterConfig); err != nil {
return errors.Wrapf(err, "failed to validate configurations")
}
if err := config.ProcessConfigurations(&snapshotterConfig); err != nil {
return errors.Wrap(err, "failed to process configurations")
}
if err := config.SetUpEnvironment(&snapshotterConfig); err != nil {
return errors.Wrap(err, "failed to setup environment")
}
ctx := logging.WithContext()
logConfig := &snapshotterConfig.LoggingConfig
logRotateArgs := &logging.RotateLogArgs{
RotateLogMaxSize: cfg.RotateLogMaxSize,
RotateLogMaxBackups: cfg.RotateLogMaxBackups,
RotateLogMaxAge: cfg.RotateLogMaxAge,
RotateLogLocalTime: cfg.RotateLogLocalTime,
RotateLogCompress: cfg.RotateLogCompress,
}
if err := logging.SetUp(flags.Args.LogLevel, flags.Args.LogToStdout, flags.Args.LogDir, flags.Args.RootDir, logRotateArgs); err != nil {
return errors.Wrap(err, "failed to prepare logger")
RotateLogMaxSize: logConfig.RotateLogMaxSize,
RotateLogMaxBackups: logConfig.RotateLogMaxBackups,
RotateLogMaxAge: logConfig.RotateLogMaxAge,
RotateLogLocalTime: logConfig.RotateLogLocalTime,
RotateLogCompress: logConfig.RotateLogCompress,
}
return snapshotter.Start(ctx, cfg)
if err := logging.SetUp(logConfig.LogLevel, logConfig.LogToStdout, logConfig.LogDir, logRotateArgs); err != nil {
return errors.Wrap(err, "failed to setup logger")
}
log.L.Infof("Start nydus-snapshotter. Version: %s, PID: %d, FsDriver: %s, DaemonMode: %s",
version.Version, os.Getpid(), config.GetFsDriver(), snapshotterConfig.DaemonMode)
return Start(ctx, &snapshotterConfig)
},
}
if err := app.Run(os.Args); err != nil {
if errdefs.IsConnectionClosed(err) {
log.L.Info("nydus snapshotter exited")
log.L.Info("nydus-snapshotter exited")
} else {
log.L.WithError(err).Fatal("failed to start nydus snapshotter:\n\r")
log.L.WithError(err).Fatal("failed to start nydus-snapshotter")
}
}
}

View File

@ -1,307 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package command
import (
"os"
"path/filepath"
"time"
"github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/pkg/logging"
"github.com/containerd/nydus-snapshotter/config"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/urfave/cli/v2"
)
const (
defaultAddress = "/run/containerd-nydus/containerd-nydus-grpc.sock"
defaultLogLevel = logrus.InfoLevel
defaultRootDir = "/var/lib/containerd-nydus-grpc"
defaultGCPeriod = "24h"
defaultPublicKey = "/signing/nydus-image-signing-public.key"
defaultRotateLogMaxSize = 200 // 200 megabytes
defaultRotateLogMaxBackups = 10
defaultRotateLogMaxAge = 0 // days
defaultRotateLogLocalTime = true
defaultRotateLogCompress = true
)
type Args struct {
Address string
LogLevel string
LogDir string
ConfigPath string
RootDir string
CacheDir string
GCPeriod string
ValidateSignature bool
PublicKeyFile string
ConvertVpcRegistry bool
NydusdBinaryPath string
NydusImageBinaryPath string
SharedDaemon bool
DaemonMode string
FsDriver string
SyncRemove bool
EnableMetrics bool
MetricsFile string
EnableStargz bool
DisableCacheManager bool
LogToStdout bool
EnableNydusOverlayFS bool
NydusdThreadNum int
CleanupOnClose bool
KubeconfigPath string
EnableKubeconfigKeychain bool
}
type Flags struct {
Args *Args
F []cli.Flag
}
func buildFlags(args *Args) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "address",
Value: defaultAddress,
Usage: "set `PATH` for gRPC socket",
Destination: &args.Address,
},
&cli.StringFlag{
Name: "cache-dir",
Value: "",
Aliases: []string{"C"},
Usage: "set `DIRECTORY` to store/cache downloaded image data",
Destination: &args.CacheDir,
},
&cli.BoolFlag{
Name: "cleanup-on-close",
Value: false,
Usage: "whether to clean up on exit",
Destination: &args.CleanupOnClose,
},
&cli.StringFlag{
Name: "config-path",
Required: true,
Aliases: []string{"c", "config"},
Usage: "path to the configuration `FILE`",
Destination: &args.ConfigPath,
},
&cli.BoolFlag{
Name: "convert-vpc-registry",
Usage: "whether to automatically convert the image to vpc registry to accelerate image pulling",
Destination: &args.ConvertVpcRegistry,
},
&cli.StringFlag{
Name: "daemon-mode",
Value: config.DefaultDaemonMode,
Aliases: []string{"M"},
Usage: "set daemon working `MODE`, one of \"multiple\", \"shared\" or \"none\"",
Destination: &args.DaemonMode,
},
&cli.BoolFlag{
Name: "disable-cache-manager",
Usage: "whether to disable blob cache manager",
Destination: &args.DisableCacheManager,
},
&cli.BoolFlag{
Name: "enable-metrics",
Usage: "whether to collect metrics",
Destination: &args.EnableMetrics,
},
&cli.BoolFlag{
Name: "enable-nydus-overlayfs",
Usage: "whether to enable nydus-overlayfs",
Destination: &args.EnableNydusOverlayFS,
},
&cli.BoolFlag{
Name: "enable-stargz",
Usage: "whether to enable support of estargz image (experimental)",
Destination: &args.EnableStargz,
},
&cli.StringFlag{
Name: "fs-driver",
Value: config.FsDriverFusedev,
Aliases: []string{"daemon-backend"},
Usage: "backend `DRIVER` to serve the filesystem, one of \"fusedev\", \"fscache\"",
Destination: &args.FsDriver,
},
&cli.StringFlag{
Name: "gc-period",
Value: defaultGCPeriod,
Usage: "blob cache garbage collection `INTERVAL`, duration string(for example, 1m, 2h)",
Destination: &args.GCPeriod,
},
&cli.StringFlag{
Name: "log-dir",
Value: "",
Aliases: []string{"L"},
Usage: "set `DIRECTORY` to store log files",
Destination: &args.LogDir,
},
&cli.StringFlag{
Name: "log-level",
Value: defaultLogLevel.String(),
Aliases: []string{"l"},
Usage: "set the logging `LEVEL` [trace, debug, info, warn, error, fatal, panic]",
Destination: &args.LogLevel,
},
&cli.BoolFlag{
Name: "log-to-stdout",
Usage: "log messages to standard out rather than files.",
Destination: &args.LogToStdout,
},
&cli.StringFlag{
Name: "metrics-file",
Usage: "path to the metrics output `FILE`",
Destination: &args.MetricsFile,
},
&cli.StringFlag{
Name: "nydus-image",
Value: "",
Aliases: []string{"nydusimg-path"},
Usage: "set `PATH` to the nydus-image binary, default to lookup nydus-image in $PATH",
Destination: &args.NydusImageBinaryPath,
},
&cli.StringFlag{
Name: "nydusd",
Value: "",
Aliases: []string{"nydusd-path"},
Usage: "set `PATH` to the nydusd binary, default to lookup nydusd in $PATH",
Destination: &args.NydusdBinaryPath,
},
&cli.IntFlag{
Name: "nydusd-thread-num",
Usage: "set worker thread number for nydusd, default to the number of CPUs",
Destination: &args.NydusdThreadNum,
},
&cli.StringFlag{
Name: "publickey-file",
Value: defaultPublicKey,
Usage: "path to the publickey `FILE` for signature validation",
Destination: &args.PublicKeyFile,
},
&cli.StringFlag{
Name: "root",
Value: defaultRootDir,
Aliases: []string{"R"},
Usage: "set `DIRECTORY` to store snapshotter working state",
Destination: &args.RootDir,
},
&cli.BoolFlag{
Name: "shared-daemon",
Usage: "Deprecated, equivalent to \"--daemon-mode shared\"",
Destination: &args.SharedDaemon,
},
&cli.BoolFlag{
Name: "sync-remove",
Usage: "whether to clean up snapshots in synchronous mode, default to asynchronous mode",
Destination: &args.SyncRemove,
},
&cli.BoolFlag{
Name: "validate-signature",
Usage: "whether to validate integrity of image bootstrap",
Destination: &args.ValidateSignature,
},
&cli.StringFlag{
Name: "kubeconfig-path",
Value: "",
Usage: "path to the kubeconfig file",
Destination: &args.KubeconfigPath,
},
&cli.BoolFlag{
Name: "enable-kubeconfig-keychain",
Value: false,
Usage: "synchronize `kubernetes.io/dockerconfigjson` secret from kubernetes API server with provided `--kubeconfig-path` (default `$KUBECONFIG` or `~/.kube/config`)",
Destination: &args.EnableKubeconfigKeychain,
},
}
}
func NewFlags() *Flags {
var args Args
return &Flags{
Args: &args,
F: buildFlags(&args),
}
}
func Validate(args *Args, cfg *config.Config) error {
var daemonCfg config.DaemonConfig
if err := config.LoadConfig(args.ConfigPath, &daemonCfg); err != nil {
return errors.Wrapf(err, "failed to load config file %q", args.ConfigPath)
}
cfg.DaemonCfg = daemonCfg
if args.ValidateSignature {
if args.PublicKeyFile == "" {
return errors.New("need to specify publicKey file for signature validation")
} else if _, err := os.Stat(args.PublicKeyFile); err != nil {
return errors.Wrapf(err, "failed to find publicKey file %q", args.PublicKeyFile)
}
}
cfg.PublicKeyFile = args.PublicKeyFile
cfg.ValidateSignature = args.ValidateSignature
// Give --shared-daemon higher priority
cfg.DaemonMode = args.DaemonMode
if args.SharedDaemon {
cfg.DaemonMode = config.DaemonModeShared
}
if args.FsDriver == config.FsDriverFscache && args.DaemonMode != config.DaemonModeShared {
return errors.New("`fscache` backend driver only supports `shared` daemon mode")
}
cfg.RootDir = args.RootDir
if len(cfg.RootDir) == 0 {
return errors.New("invalid empty root directory")
}
cfg.CacheDir = args.CacheDir
if len(cfg.CacheDir) == 0 {
cfg.CacheDir = filepath.Join(cfg.RootDir, "cache")
}
cfg.LogLevel = args.LogLevel
// Always let options from CLI override those from configuration file.
cfg.LogToStdout = args.LogToStdout
cfg.LogDir = args.LogDir
if len(cfg.LogDir) == 0 {
cfg.LogDir = filepath.Join(cfg.RootDir, logging.DefaultLogDirName)
}
cfg.RotateLogMaxSize = defaultRotateLogMaxSize
cfg.RotateLogMaxBackups = defaultRotateLogMaxBackups
cfg.RotateLogMaxAge = defaultRotateLogMaxAge
cfg.RotateLogLocalTime = defaultRotateLogLocalTime
cfg.RotateLogCompress = defaultRotateLogCompress
d, err := time.ParseDuration(args.GCPeriod)
if err != nil {
return errors.Wrapf(err, "parse gc period %v failed", args.GCPeriod)
}
cfg.GCPeriod = d
cfg.Address = args.Address
cfg.CleanupOnClose = args.CleanupOnClose
cfg.ConvertVpcRegistry = args.ConvertVpcRegistry
cfg.DisableCacheManager = args.DisableCacheManager
cfg.EnableMetrics = args.EnableMetrics
cfg.EnableStargz = args.EnableStargz
cfg.EnableNydusOverlayFS = args.EnableNydusOverlayFS
cfg.FsDriver = args.FsDriver
cfg.MetricsFile = args.MetricsFile
cfg.NydusdBinaryPath = args.NydusdBinaryPath
cfg.NydusImageBinaryPath = args.NydusImageBinaryPath
cfg.NydusdThreadNum = args.NydusdThreadNum
cfg.SyncRemove = args.SyncRemove
cfg.KubeconfigPath = args.KubeconfigPath
cfg.EnableKubeconfigKeychain = args.EnableKubeconfigKeychain
return cfg.SetupNydusBinaryPaths()
}

View File

@ -0,0 +1,112 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"net"
"os"
"path/filepath"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/pkg/auth"
"github.com/containerd/nydus-snapshotter/pkg/utils/signals"
"github.com/containerd/nydus-snapshotter/snapshot"
api "github.com/containerd/containerd/api/services/snapshots/v1"
"github.com/containerd/containerd/v2/contrib/snapshotservice"
"github.com/containerd/containerd/v2/core/snapshots"
"github.com/containerd/log"
"google.golang.org/grpc"
)
func Start(ctx context.Context, cfg *config.SnapshotterConfig) error {
ctx, cancel := context.WithCancel(ctx)
defer cancel()
rs, err := snapshot.NewSnapshotter(ctx, cfg)
if err != nil {
return errors.Wrap(err, "failed to initialize snapshotter")
}
stopSignal := signals.SetupSignalHandler()
opt := ServeOptions{
ListeningSocketPath: cfg.Address,
EnableCRIKeychain: cfg.RemoteConfig.AuthConfig.EnableCRIKeychain,
ImageServiceAddress: cfg.RemoteConfig.AuthConfig.ImageServiceAddress,
}
if cfg.RemoteConfig.AuthConfig.EnableKubeconfigKeychain {
if err := auth.InitKubeSecretListener(ctx, cfg.RemoteConfig.AuthConfig.KubeconfigPath); err != nil {
return err
}
}
return Serve(ctx, rs, opt, stopSignal)
}
type ServeOptions struct {
ListeningSocketPath string
EnableCRIKeychain bool
ImageServiceAddress string
}
func Serve(ctx context.Context, sn snapshots.Snapshotter, options ServeOptions, stop <-chan struct{}) error {
err := ensureSocketNotExists(options.ListeningSocketPath)
if err != nil {
return err
}
rpc := grpc.NewServer()
if rpc == nil {
return errors.New("start gRPC server")
}
api.RegisterSnapshotsServer(rpc, snapshotservice.FromSnapshotter(sn))
listener, err := net.Listen("unix", options.ListeningSocketPath)
if err != nil {
return errors.Wrapf(err, "listen socket %q", options.ListeningSocketPath)
}
if options.EnableCRIKeychain {
auth.AddImageProxy(ctx, rpc, options.ImageServiceAddress)
}
go func() {
<-stop
log.L.Infof("Shutting down nydus-snapshotter!")
if err := sn.Close(); err != nil {
log.L.WithError(err).Errorf("Closing snapshotter error")
}
if err := listener.Close(); err != nil {
log.L.Errorf("Failed to close listener %s, err: %v", options.ListeningSocketPath, err)
}
}()
return rpc.Serve(listener)
}
func ensureSocketNotExists(listeningSocketPath string) error {
if err := os.MkdirAll(filepath.Dir(listeningSocketPath), 0700); err != nil {
return errors.Wrapf(err, "failed to create directory %q", filepath.Dir(listeningSocketPath))
}
finfo, err := os.Stat(listeningSocketPath)
// err is nil means listening socket path exists, remove before serve
if err == nil {
if finfo.Mode()&os.ModeSocket == 0 {
return errors.Errorf("file %s is not a socket", listeningSocketPath)
}
err := os.Remove(listeningSocketPath)
if err != nil {
return err
}
}
return nil
}

View File

@ -1,11 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package main
var (
Version = "development"
)

10
cmd/converter/main.go Normal file
View File

@ -0,0 +1,10 @@
package main
// Import the converter package so that it can be compiled during
// `go build` to ensure cross-compilation compatibility.
import (
_ "github.com/containerd/nydus-snapshotter/pkg/converter"
)
func main() {
}

146
cmd/nydus-overlayfs/main.go Normal file
View File

@ -0,0 +1,146 @@
package main
import (
"fmt"
"log"
"os"
"strings"
"syscall"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"golang.org/x/sys/unix"
)
const (
// Extra mount option to pass Nydus specific information from snapshotter to runtime through containerd.
extraOptionKey = "extraoption="
// Kata virtual volume infmation passed from snapshotter to runtime through containerd, superset of `extraOptionKey`.
// Please refer to `KataVirtualVolume` in https://github.com/kata-containers/kata-containers/blob/main/src/libs/kata-types/src/mount.rs
kataVolumeOptionKey = "io.katacontainers.volume="
)
var (
Version = "v0.1"
BuildTime = "unknown"
)
/*
containerd run fuse.mount format: nydus-overlayfs overlay /tmp/ctd-volume107067851
-o lowerdir=/foo/lower2:/foo/lower1,upperdir=/foo/upper,workdir=/foo/work,extraoption={...},dev,suid]
*/
type mountArgs struct {
fsType string
target string
options []string
}
func parseArgs(args []string) (*mountArgs, error) {
margs := &mountArgs{
fsType: args[0],
target: args[1],
}
if margs.fsType != "overlay" {
return nil, errors.Errorf("invalid filesystem type %s for overlayfs", margs.fsType)
}
if len(margs.target) == 0 {
return nil, errors.New("empty overlayfs mount target")
}
if args[2] == "-o" && len(args[3]) != 0 {
for _, opt := range strings.Split(args[3], ",") {
// filter Nydus specific options
if strings.HasPrefix(opt, extraOptionKey) || strings.HasPrefix(opt, kataVolumeOptionKey) {
continue
}
margs.options = append(margs.options, opt)
}
}
if len(margs.options) == 0 {
return nil, errors.New("empty overlayfs mount options")
}
return margs, nil
}
func parseOptions(options []string) (int, string) {
flagsTable := map[string]int{
"async": unix.MS_SYNCHRONOUS,
"atime": unix.MS_NOATIME,
"bind": unix.MS_BIND,
"defaults": 0,
"dev": unix.MS_NODEV,
"diratime": unix.MS_NODIRATIME,
"dirsync": unix.MS_DIRSYNC,
"exec": unix.MS_NOEXEC,
"mand": unix.MS_MANDLOCK,
"noatime": unix.MS_NOATIME,
"nodev": unix.MS_NODEV,
"nodiratime": unix.MS_NODIRATIME,
"noexec": unix.MS_NOEXEC,
"nomand": unix.MS_MANDLOCK,
"norelatime": unix.MS_RELATIME,
"nostrictatime": unix.MS_STRICTATIME,
"nosuid": unix.MS_NOSUID,
"rbind": unix.MS_BIND | unix.MS_REC,
"relatime": unix.MS_RELATIME,
"remount": unix.MS_REMOUNT,
"ro": unix.MS_RDONLY,
"rw": unix.MS_RDONLY,
"strictatime": unix.MS_STRICTATIME,
"suid": unix.MS_NOSUID,
"sync": unix.MS_SYNCHRONOUS,
}
var (
flags int
data []string
)
for _, o := range options {
if f, exist := flagsTable[o]; exist {
flags |= f
} else {
data = append(data, o)
}
}
return flags, strings.Join(data, ",")
}
func run(args cli.Args) error {
margs, err := parseArgs(args.Slice())
if err != nil {
return errors.Wrap(err, "parse mount options")
}
flags, data := parseOptions(margs.options)
err = syscall.Mount(margs.fsType, margs.target, margs.fsType, uintptr(flags), data)
if err != nil {
return errors.Wrapf(err, "mount overlayfs by syscall")
}
return nil
}
func main() {
app := &cli.App{
Name: "NydusOverlayfs",
Usage: "FUSE mount helper for containerd to filter out Nydus specific options",
Version: fmt.Sprintf("%s.%s", Version, BuildTime),
UsageText: "[Usage]: nydus-overlayfs overlay <target> -o <options>",
Action: func(c *cli.Context) error {
return run(c.Args())
},
Before: func(c *cli.Context) error {
if c.NArg() != 4 {
cli.ShowAppHelpAndExit(c, 1)
}
return nil
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
os.Exit(0)
}

View File

@ -0,0 +1,285 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"fmt"
"io"
"log/syslog"
"os"
"path/filepath"
"strings"
"time"
"github.com/containerd/log"
distribution "github.com/distribution/reference"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/containerd/nri/pkg/api"
"github.com/containerd/nri/pkg/stub"
"github.com/containerd/nydus-snapshotter/pkg/errdefs"
"github.com/containerd/nydus-snapshotter/pkg/fanotify"
"github.com/containerd/nydus-snapshotter/version"
"github.com/pelletier/go-toml"
)
const (
defaultEvents = "StartContainer,StopContainer"
defaultServerPath = "/usr/local/bin/optimizer-server"
defaultPersistDir = "/opt/nri/optimizer/results"
)
type PluginConfig struct {
Events []string `toml:"events"`
ServerPath string `toml:"server_path"`
PersistDir string `toml:"persist_dir"`
Readable bool `toml:"readable"`
Timeout int `toml:"timeout"`
Overwrite bool `toml:"overwrite"`
}
type PluginArgs struct {
PluginName string
PluginIdx string
PluginEvents string
Config PluginConfig
}
type Flags struct {
Args *PluginArgs
F []cli.Flag
}
func buildFlags(args *PluginArgs) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "plugin name to register to NRI",
Destination: &args.PluginName,
},
&cli.StringFlag{
Name: "idx",
Usage: "plugin index to register to NRI",
Destination: &args.PluginIdx,
},
&cli.StringFlag{
Name: "events",
Value: defaultEvents,
Usage: "the events that containerd subscribes to. DO NOT CHANGE THIS.",
Destination: &args.PluginEvents,
},
&cli.StringFlag{
Name: "server-path",
Value: defaultServerPath,
Usage: "the path of optimizer server binary",
Destination: &args.Config.ServerPath,
},
&cli.StringFlag{
Name: "persist-dir",
Value: defaultPersistDir,
Usage: "the directory to persist accessed files list for container",
Destination: &args.Config.PersistDir,
},
&cli.BoolFlag{
Name: "readable",
Value: false,
Usage: "whether to make the csv file human readable",
Destination: &args.Config.Readable,
},
&cli.IntFlag{
Name: "timeout",
Value: 0,
Usage: "the timeout to kill optimizer server, 0 to disable it",
Destination: &args.Config.Timeout,
},
&cli.BoolFlag{
Name: "overwrite",
Usage: "whether to overwrite the existed persistent files",
Destination: &args.Config.Overwrite,
},
}
}
func NewPluginFlags() *Flags {
var args PluginArgs
return &Flags{
Args: &args,
F: buildFlags(&args),
}
}
type plugin struct {
stub stub.Stub
mask stub.EventMask
}
var (
cfg PluginConfig
logWriter *syslog.Writer
globalFanotifyServer = make(map[string]*fanotify.Server)
_ = stub.ConfigureInterface(&plugin{})
_ = stub.StartContainerInterface(&plugin{})
_ = stub.StopContainerInterface(&plugin{})
)
const (
imageNameLabel = "io.kubernetes.cri.image-name"
)
func (p *plugin) Configure(ctx context.Context, config, runtime, version string) (stub.EventMask, error) {
log.G(ctx).Infof("got configuration data: %q from runtime %s %s", config, runtime, version)
if config == "" {
return p.mask, nil
}
tree, err := toml.Load(config)
if err != nil {
return 0, errors.Wrap(err, "parse TOML")
}
if err := tree.Unmarshal(&cfg); err != nil {
return 0, err
}
p.mask, err = api.ParseEventMask(cfg.Events...)
if err != nil {
return 0, errors.Wrap(err, "parse events in configuration")
}
log.G(ctx).Infof("configuration: %#v", cfg)
return p.mask, nil
}
func (p *plugin) StartContainer(_ context.Context, _ *api.PodSandbox, container *api.Container) error {
dir, imageName, err := GetImageName(container.Annotations)
if err != nil {
return err
}
persistDir := filepath.Join(cfg.PersistDir, dir)
if err := os.MkdirAll(persistDir, os.ModePerm); err != nil {
return err
}
persistFile := filepath.Join(persistDir, imageName)
if cfg.Timeout > 0 {
persistFile = fmt.Sprintf("%s.timeout%ds", persistFile, cfg.Timeout)
}
fanotifyServer := fanotify.NewServer(cfg.ServerPath, container.Pid, imageName, persistFile, cfg.Readable, cfg.Overwrite, time.Duration(cfg.Timeout)*time.Second, logWriter)
if err := fanotifyServer.RunServer(); err != nil {
return err
}
globalFanotifyServer[imageName] = fanotifyServer
return nil
}
func (p *plugin) StopContainer(_ context.Context, _ *api.PodSandbox, container *api.Container) ([]*api.ContainerUpdate, error) {
var update = []*api.ContainerUpdate{}
_, imageName, err := GetImageName(container.Annotations)
if err != nil {
return update, err
}
if fanotifyServer, ok := globalFanotifyServer[imageName]; ok {
fanotifyServer.StopServer()
} else {
return nil, errors.New("can not find fanotify server for container image " + imageName)
}
return update, nil
}
func GetImageName(annotations map[string]string) (string, string, error) {
named, err := distribution.ParseDockerRef(annotations[imageNameLabel])
if err != nil {
return "", "", err
}
nameTagged := named.(distribution.NamedTagged)
repo := distribution.Path(nameTagged)
dir := filepath.Dir(repo)
image := filepath.Base(repo)
imageName := image + ":" + nameTagged.Tag()
return dir, imageName, nil
}
func (p *plugin) onClose() {
for _, fanotifyServer := range globalFanotifyServer {
fanotifyServer.StopServer()
}
os.Exit(0)
}
func main() {
flags := NewPluginFlags()
app := &cli.App{
Name: "optimizer-nri-plugin",
Usage: "Optimizer client for NRI plugin to manage optimizer server",
Version: version.Version,
Flags: flags.F,
HideVersion: true,
Action: func(_ *cli.Context) error {
var (
opts []stub.Option
err error
)
cfg = flags.Args.Config
// FIXME(thaJeztah): ucontainerd's log does not set "PadLevelText: true"
_ = log.SetFormat(log.TextFormat)
ctx := log.WithLogger(context.Background(), log.L)
logWriter, err = syslog.New(syslog.LOG_INFO, "optimizer-nri-plugin")
if err == nil {
log.G(ctx).Logger.SetOutput(io.MultiWriter(os.Stdout, logWriter))
}
if flags.Args.PluginName != "" {
opts = append(opts, stub.WithPluginName(flags.Args.PluginName))
}
if flags.Args.PluginIdx != "" {
opts = append(opts, stub.WithPluginIdx(flags.Args.PluginIdx))
}
p := &plugin{}
if p.mask, err = api.ParseEventMask(flags.Args.PluginEvents); err != nil {
log.G(ctx).Fatalf("failed to parse events: %v", err)
}
cfg.Events = strings.Split(flags.Args.PluginEvents, ",")
if p.stub, err = stub.New(p, append(opts, stub.WithOnClose(p.onClose))...); err != nil {
log.G(ctx).Fatalf("failed to create plugin stub: %v", err)
}
err = p.stub.Run(context.Background())
if err != nil {
log.G(ctx).Errorf("plugin exited with error %v", err)
os.Exit(1)
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
if errdefs.IsConnectionClosed(err) {
log.L.Info("optimizer NRI plugin exited")
} else {
log.L.WithError(err).Fatal("failed to start optimizer NRI plugin")
}
}
}

View File

@ -0,0 +1,209 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package main
import (
"context"
"fmt"
"io"
"log/syslog"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"github.com/containerd/log"
"github.com/containerd/nri/pkg/api"
"github.com/containerd/nri/pkg/stub"
"github.com/pelletier/go-toml"
"github.com/pkg/errors"
"github.com/urfave/cli/v2"
"github.com/containerd/nydus-snapshotter/pkg/errdefs"
"github.com/containerd/nydus-snapshotter/version"
)
const (
endpointPrefetch = "/api/v1/prefetch"
defaultEvents = "RunPodSandbox"
defaultSystemControllerAddress = "/run/containerd-nydus/system.sock"
defaultPrefetchConfigDir = "/etc/nydus"
nydusPrefetchAnnotation = "containerd.io/nydus-prefetch"
)
type PluginArgs struct {
PluginName string
PluginIdx string
SocketAddress string
}
type Flags struct {
Args *PluginArgs
Flag []cli.Flag
}
func buildFlags(args *PluginArgs) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "name",
Usage: "plugin name to register to NRI",
Destination: &args.PluginName,
},
&cli.StringFlag{
Name: "idx",
Usage: "plugin index to register to NRI",
Destination: &args.PluginIdx,
},
&cli.StringFlag{
Name: "socket-addr",
Value: defaultSystemControllerAddress,
Usage: "unix domain socket address. If defined in the configuration file, there is no need to add ",
Destination: &args.SocketAddress,
},
}
}
func NewPluginFlags() *Flags {
var args PluginArgs
return &Flags{
Args: &args,
Flag: buildFlags(&args),
}
}
type plugin struct {
stub stub.Stub
mask stub.EventMask
}
var (
globalSocket string
logWriter *syslog.Writer
_ = stub.RunPodInterface(&plugin{})
)
// sendDataOverHTTP sends the prefetch data to the specified endpoint over HTTP using a Unix socket.
func sendDataOverHTTP(data string, endpoint, sock string) error {
url := fmt.Sprintf("http://unix%s", endpoint)
req, err := http.NewRequest(http.MethodPut, url, strings.NewReader(data))
if err != nil {
return err
}
client := &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
return net.Dial("unix", sock)
},
},
}
resp, err := client.Do(req)
if err != nil {
return err
}
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to send data, status code: %d", resp.StatusCode)
}
resp.Body.Close()
return nil
}
func (p *plugin) RunPodSandbox(ctx context.Context, pod *api.PodSandbox) error {
prefetchList, ok := pod.Annotations[nydusPrefetchAnnotation]
if !ok {
return nil
}
err := sendDataOverHTTP(prefetchList, endpointPrefetch, globalSocket)
if err != nil {
log.G(ctx).Errorf("failed to send data: %v", err)
return err
}
return nil
}
func main() {
flags := NewPluginFlags()
app := &cli.App{
Name: "prefetch-nri-plugin",
Usage: "NRI plugin for obtaining and transmitting prefetch files path",
Version: version.Version,
Flags: flags.Flag,
HideVersion: true,
Action: func(_ *cli.Context) error {
var (
opts []stub.Option
err error
)
// FIXME(thaJeztah): ucontainerd's log does not set "PadLevelText: true"
_ = log.SetFormat(log.TextFormat)
ctx := log.WithLogger(context.Background(), log.L)
configFileName := "prefetchConfig.toml"
configDir := defaultPrefetchConfigDir
configFilePath := filepath.Join(configDir, configFileName)
config, err := toml.LoadFile(configFilePath)
if err != nil {
log.G(ctx).Warnf("failed to read config file: %v", err)
}
configSocketAddrRaw := config.Get("file_prefetch.socket_address")
if configSocketAddrRaw != nil {
if configSocketAddr, ok := configSocketAddrRaw.(string); ok {
globalSocket = configSocketAddr
} else {
log.G(ctx).Warnf("failed to read config: 'file_prefetch.socket_address' is not a string")
}
} else {
globalSocket = flags.Args.SocketAddress
}
logWriter, err = syslog.New(syslog.LOG_INFO, "prefetch-nri-plugin")
if err == nil {
log.G(ctx).Logger.SetOutput(io.MultiWriter(os.Stdout, logWriter))
}
if flags.Args.PluginName != "" {
opts = append(opts, stub.WithPluginName(flags.Args.PluginName))
}
if flags.Args.PluginIdx != "" {
opts = append(opts, stub.WithPluginIdx(flags.Args.PluginIdx))
}
p := &plugin{}
if p.mask, err = api.ParseEventMask(defaultEvents); err != nil {
log.G(ctx).Fatalf("failed to parse events: %v", err)
}
if p.stub, err = stub.New(p, opts...); err != nil {
log.G(ctx).Fatalf("failed to create plugin stub: %v", err)
}
err = p.stub.Run(context.Background())
if err != nil {
return errors.Wrap(err, "plugin exited")
}
return nil
},
}
if err := app.Run(os.Args); err != nil {
if errdefs.IsConnectionClosed(err) {
log.L.Info("prefetch NRI plugin exited")
} else {
log.L.WithError(err).Fatal("failed to start prefetch NRI plugin")
}
}
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
@ -7,121 +8,378 @@
package config
import (
"path/filepath"
"time"
"os"
"github.com/containerd/nydus-snapshotter/cmd/containerd-nydus-grpc/pkg/logging"
"dario.cat/mergo"
"github.com/pelletier/go-toml"
"github.com/pkg/errors"
exec "golang.org/x/sys/execabs"
"github.com/containerd/nydus-snapshotter/internal/constant"
"github.com/containerd/nydus-snapshotter/internal/flags"
"github.com/containerd/nydus-snapshotter/pkg/cgroup"
"github.com/containerd/nydus-snapshotter/pkg/errdefs"
"github.com/containerd/nydus-snapshotter/pkg/utils/file"
"github.com/containerd/nydus-snapshotter/pkg/utils/parser"
"github.com/containerd/nydus-snapshotter/pkg/utils/sysinfo"
)
const (
DefaultDaemonMode string = "multiple"
DaemonModeMultiple string = "multiple"
DaemonModeShared string = "shared"
DaemonModeNone string = "none"
DaemonModePrefetch string = "prefetch"
DefaultLogLevel string = "info"
defaultGCPeriod = 24 * time.Hour
defaultNydusDaemonConfigPath string = "/etc/nydus/config.json"
nydusdBinaryName string = "nydusd"
nydusImageBinaryName string = "nydus-image"
)
const (
FsDriverFusedev string = "fusedev"
FsDriverFscache string = "fscache"
)
type Config struct {
Address string `toml:"-"`
ConvertVpcRegistry bool `toml:"-"`
DaemonCfgPath string `toml:"daemon_cfg_path"`
DaemonCfg DaemonConfig `toml:"-"`
PublicKeyFile string `toml:"-"`
RootDir string `toml:"-"`
CacheDir string `toml:"cache_dir"`
GCPeriod time.Duration `toml:"gc_period"`
ValidateSignature bool `toml:"validate_signature"`
NydusdBinaryPath string `toml:"nydusd_binary_path"`
NydusImageBinaryPath string `toml:"nydus_image_binary"`
DaemonMode string `toml:"daemon_mode"`
FsDriver string `toml:"daemon_backend"`
SyncRemove bool `toml:"sync_remove"`
EnableMetrics bool `toml:"enable_metrics"`
MetricsFile string `toml:"metrics_file"`
EnableStargz bool `toml:"enable_stargz"`
LogLevel string `toml:"-"`
LogDir string `toml:"log_dir"`
LogToStdout bool `toml:"log_to_stdout"`
DisableCacheManager bool `toml:"disable_cache_manager"`
EnableNydusOverlayFS bool `toml:"enable_nydus_overlayfs"`
NydusdThreadNum int `toml:"nydusd_thread_num"`
CleanupOnClose bool `toml:"cleanup_on_close"`
KubeconfigPath string `toml:"kubeconfig_path"`
EnableKubeconfigKeychain bool `toml:"enable_kubeconfig_keychain"`
RotateLogMaxSize int `toml:"log_rotate_max_size"`
RotateLogMaxBackups int `toml:"log_rotate_max_backups"`
RotateLogMaxAge int `toml:"log_rotate_max_age"`
RotateLogLocalTime bool `toml:"log_rotate_local_time"`
RotateLogCompress bool `toml:"log_rotate_compress"`
func init() {
recoverPolicyParser = map[string]DaemonRecoverPolicy{
RecoverPolicyNone.String(): RecoverPolicyNone,
RecoverPolicyRestart.String(): RecoverPolicyRestart,
RecoverPolicyFailover.String(): RecoverPolicyFailover}
}
func (c *Config) FillupWithDefaults() error {
if c.LogLevel == "" {
c.LogLevel = DefaultLogLevel
}
if c.DaemonCfgPath == "" {
c.DaemonCfgPath = defaultNydusDaemonConfigPath
}
// Define a policy how to fork nydusd daemon and attach file system instances to serve.
type DaemonMode string
if c.DaemonMode == "" {
c.DaemonMode = DefaultDaemonMode
}
const (
// Spawn a dedicated nydusd for each RAFS instance.
DaemonModeMultiple DaemonMode = DaemonMode(constant.DaemonModeMultiple)
// Spawn a dedicated nydusd for each RAFS instance.
DaemonModeDedicated DaemonMode = DaemonMode(constant.DaemonModeDedicated)
// Share a global nydusd to serve all RAFS instances.
DaemonModeShared DaemonMode = DaemonMode(constant.DaemonModeShared)
// Do not spawn nydusd for RAFS instances.
//
// For tarfs and rund, there's no need to create nydusd to serve RAFS instances,
// the snapshotter just returns mount slices with additional information for runC/runD
// to manage those snapshots.
DaemonModeNone DaemonMode = DaemonMode(constant.DaemonModeNone)
DaemonModeInvalid DaemonMode = DaemonMode(constant.DaemonModeInvalid)
)
if c.GCPeriod == 0 {
c.GCPeriod = defaultGCPeriod
func parseDaemonMode(m string) (DaemonMode, error) {
switch m {
case string(DaemonModeMultiple):
return DaemonModeDedicated, nil
case string(DaemonModeDedicated):
return DaemonModeDedicated, nil
case string(DaemonModeShared):
return DaemonModeShared, nil
case string(DaemonModeNone):
return DaemonModeNone, nil
default:
return DaemonModeInvalid, errors.Errorf("invalid daemon mode %q", m)
}
if len(c.CacheDir) == 0 {
c.CacheDir = filepath.Join(c.RootDir, "cache")
}
if len(c.LogDir) == 0 {
c.LogDir = filepath.Join(c.RootDir, logging.DefaultLogDirName)
}
var daemonCfg DaemonConfig
if err := LoadConfig(c.DaemonCfgPath, &daemonCfg); err != nil {
return errors.Wrapf(err, "failed to load config file %q", c.DaemonCfgPath)
}
c.DaemonCfg = daemonCfg
return c.SetupNydusBinaryPaths()
}
func (c *Config) SetupNydusBinaryPaths() error {
// when using DaemonMode = none, nydusd and nydus-image binaries are not required
if c.DaemonMode == DaemonModeNone {
return nil
type DaemonRecoverPolicy int
const (
RecoverPolicyInvalid DaemonRecoverPolicy = iota
RecoverPolicyNone
RecoverPolicyRestart
RecoverPolicyFailover
)
func (p DaemonRecoverPolicy) String() string {
switch p {
case RecoverPolicyNone:
return "none"
case RecoverPolicyRestart:
return "restart"
case RecoverPolicyFailover:
return "failover"
case RecoverPolicyInvalid:
fallthrough
default:
return ""
}
}
var recoverPolicyParser map[string]DaemonRecoverPolicy
func ParseRecoverPolicy(p string) (DaemonRecoverPolicy, error) {
policy, ok := recoverPolicyParser[p]
if !ok {
return RecoverPolicyInvalid, errors.Errorf("invalid recover policy %q", p)
}
// resolve nydusd path
if c.NydusdBinaryPath == "" {
path, err := exec.LookPath(nydusdBinaryName)
if err != nil {
return err
}
c.NydusdBinaryPath = path
return policy, nil
}
const (
FsDriverBlockdev string = constant.FsDriverBlockdev
FsDriverFusedev string = constant.FsDriverFusedev
FsDriverFscache string = constant.FsDriverFscache
FsDriverNodev string = constant.FsDriverNodev
FsDriverProxy string = constant.FsDriverProxy
)
type Experimental struct {
EnableStargz bool `toml:"enable_stargz"`
EnableReferrerDetect bool `toml:"enable_referrer_detect"`
TarfsConfig TarfsConfig `toml:"tarfs"`
EnableBackendSource bool `toml:"enable_backend_source"`
}
type TarfsConfig struct {
EnableTarfs bool `toml:"enable_tarfs"`
MountTarfsOnHost bool `toml:"mount_tarfs_on_host"`
TarfsHint bool `toml:"tarfs_hint"`
MaxConcurrentProc int `toml:"max_concurrent_proc"`
ExportMode string `toml:"export_mode"`
}
type CgroupConfig struct {
Enable bool `toml:"enable"`
MemoryLimit string `toml:"memory_limit"`
}
// Configure how to start and recover nydusd daemons
type DaemonConfig struct {
NydusdPath string `toml:"nydusd_path"`
NydusdConfigPath string `toml:"nydusd_config"`
NydusImagePath string `toml:"nydusimage_path"`
RecoverPolicy string `toml:"recover_policy"`
FsDriver string `toml:"fs_driver"`
ThreadsNumber int `toml:"threads_number"`
LogRotationSize int `toml:"log_rotation_size"`
}
type LoggingConfig struct {
LogToStdout bool `toml:"log_to_stdout"`
LogLevel string `toml:"level"`
LogDir string `toml:"dir"`
RotateLogMaxSize int `toml:"log_rotation_max_size"`
RotateLogMaxBackups int `toml:"log_rotation_max_backups"`
RotateLogMaxAge int `toml:"log_rotation_max_age"`
RotateLogLocalTime bool `toml:"log_rotation_local_time"`
RotateLogCompress bool `toml:"log_rotation_compress"`
}
// Nydus image layers additional process
type ImageConfig struct {
PublicKeyFile string `toml:"public_key_file"`
ValidateSignature bool `toml:"validate_signature"`
}
// Configure containerd snapshots interfaces and how to process the snapshots
// requests from containerd
type SnapshotConfig struct {
EnableNydusOverlayFS bool `toml:"enable_nydus_overlayfs"`
NydusOverlayFSPath string `toml:"nydus_overlayfs_path"`
EnableKataVolume bool `toml:"enable_kata_volume"`
SyncRemove bool `toml:"sync_remove"`
}
// Configure cache manager that manages the cache files lifecycle
type CacheManagerConfig struct {
Disable bool `toml:"disable"`
// Trigger GC gc_period after the specified period.
// Example format: 24h, 120min
GCPeriod string `toml:"gc_period"`
CacheDir string `toml:"cache_dir"`
}
// Configure how nydus-snapshotter receive auth information
type AuthConfig struct {
// based on kubeconfig or ServiceAccount
EnableKubeconfigKeychain bool `toml:"enable_kubeconfig_keychain"`
KubeconfigPath string `toml:"kubeconfig_path"`
// CRI proxy mode
EnableCRIKeychain bool `toml:"enable_cri_keychain"`
ImageServiceAddress string `toml:"image_service_address"`
}
// Configure remote storage like container registry
type RemoteConfig struct {
AuthConfig AuthConfig `toml:"auth"`
ConvertVpcRegistry bool `toml:"convert_vpc_registry"`
SkipSSLVerify bool `toml:"skip_ssl_verify"`
MirrorsConfig MirrorsConfig `toml:"mirrors_config"`
}
type MirrorsConfig struct {
Dir string `toml:"dir"`
}
type MetricsConfig struct {
Address string `toml:"address"`
}
type DebugConfig struct {
ProfileDuration int64 `toml:"daemon_cpu_profile_duration_secs"`
PprofAddress string `toml:"pprof_address"`
}
type SystemControllerConfig struct {
Enable bool `toml:"enable"`
Address string `toml:"address"`
DebugConfig DebugConfig `toml:"debug"`
}
type SnapshotterConfig struct {
// Configuration format version
Version int `toml:"version"`
// Snapshotter's root work directory
Root string `toml:"root"`
Address string `toml:"address"`
DaemonMode string `toml:"daemon_mode"`
// Clean up all the resources when snapshotter is closed
CleanupOnClose bool `toml:"cleanup_on_close"`
SystemControllerConfig SystemControllerConfig `toml:"system"`
MetricsConfig MetricsConfig `toml:"metrics"`
DaemonConfig DaemonConfig `toml:"daemon"`
SnapshotsConfig SnapshotConfig `toml:"snapshot"`
RemoteConfig RemoteConfig `toml:"remote"`
ImageConfig ImageConfig `toml:"image"`
CacheManagerConfig CacheManagerConfig `toml:"cache_manager"`
LoggingConfig LoggingConfig `toml:"log"`
CgroupConfig CgroupConfig `toml:"cgroup"`
Experimental Experimental `toml:"experimental"`
}
func LoadSnapshotterConfig(path string) (*SnapshotterConfig, error) {
var config SnapshotterConfig
// get nydus-snapshotter configuration from specified path of toml file
if path == "" {
return nil, errors.New("snapshotter configuration path cannot be empty")
}
tree, err := toml.LoadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "load toml configuration from file %q", path)
}
// resolve nydus-image path
if c.NydusImageBinaryPath == "" {
path, err := exec.LookPath(nydusImageBinaryName)
if err != nil {
return err
}
c.NydusImageBinaryPath = path
if err = tree.Unmarshal(&config); err != nil {
return nil, errors.Wrap(err, "unmarshal snapshotter configuration")
}
if config.Version != 1 {
return nil, errors.Errorf("unsupported configuration version %d", config.Version)
}
return &config, nil
}
func MergeConfig(to, from *SnapshotterConfig) error {
err := mergo.Merge(to, from)
if err != nil {
return err
}
return nil
}
func ValidateConfig(c *SnapshotterConfig) error {
if c == nil {
return errors.Wrapf(errdefs.ErrInvalidArgument, "configuration is none")
}
if c.ImageConfig.ValidateSignature {
if c.ImageConfig.PublicKeyFile == "" {
return errors.New("public key file for signature validation is not provided")
} else if _, err := os.Stat(c.ImageConfig.PublicKeyFile); err != nil {
return errors.Wrapf(err, "check publicKey file %q", c.ImageConfig.PublicKeyFile)
}
}
if len(c.Root) == 0 {
return errors.New("empty root directory")
}
if c.DaemonConfig.FsDriver != FsDriverFscache && c.DaemonConfig.FsDriver != FsDriverFusedev &&
c.DaemonConfig.FsDriver != FsDriverBlockdev && c.DaemonConfig.FsDriver != FsDriverNodev &&
c.DaemonConfig.FsDriver != FsDriverProxy {
return errors.Errorf("invalid filesystem driver %q", c.DaemonConfig.FsDriver)
}
if _, err := ParseRecoverPolicy(c.DaemonConfig.RecoverPolicy); err != nil {
return err
}
if c.DaemonConfig.ThreadsNumber > 1024 {
return errors.Errorf("nydusd worker thread number %d is too big, max 1024", c.DaemonConfig.ThreadsNumber)
}
if c.RemoteConfig.AuthConfig.EnableCRIKeychain && c.RemoteConfig.AuthConfig.EnableKubeconfigKeychain {
return errors.Wrapf(errdefs.ErrInvalidArgument,
"\"enable_cri_keychain\" and \"enable_kubeconfig_keychain\" can't be set at the same time")
}
if c.RemoteConfig.MirrorsConfig.Dir != "" {
dirExisted, err := file.IsDirExisted(c.RemoteConfig.MirrorsConfig.Dir)
if err != nil {
return err
}
if !dirExisted {
return errors.Errorf("mirrors config directory %s does not exist", c.RemoteConfig.MirrorsConfig.Dir)
}
}
return nil
}
// Parse command line arguments and fill the nydus-snapshotter configuration
// Always let options from CLI override those from configuration file.
func ParseParameters(args *flags.Args, cfg *SnapshotterConfig) error {
// --- essential configuration
if args.Address != "" {
cfg.Address = args.Address
}
if args.RootDir != "" {
cfg.Root = args.RootDir
}
// Give --shared-daemon higher priority
if args.DaemonMode != "" {
cfg.DaemonMode = args.DaemonMode
}
// --- image processor configuration
// empty
// --- daemon configuration
daemonConfig := &cfg.DaemonConfig
if args.NydusdConfigPath != "" {
daemonConfig.NydusdConfigPath = args.NydusdConfigPath
}
if args.NydusdPath != "" {
daemonConfig.NydusdPath = args.NydusdPath
}
if args.NydusImagePath != "" {
daemonConfig.NydusImagePath = args.NydusImagePath
}
if args.FsDriver != "" {
daemonConfig.FsDriver = args.FsDriver
}
// --- cache manager configuration
// empty
// --- logging configuration
logConfig := &cfg.LoggingConfig
if args.LogLevel != "" {
logConfig.LogLevel = args.LogLevel
}
if args.LogToStdoutCount > 0 {
logConfig.LogToStdout = args.LogToStdout
}
// --- remote storage configuration
// empty
// --- snapshot configuration
if args.NydusOverlayFSPath != "" {
cfg.SnapshotsConfig.NydusOverlayFSPath = args.NydusOverlayFSPath
}
// --- metrics configuration
// empty
return nil
}
func ParseCgroupConfig(config CgroupConfig) (cgroup.Config, error) {
totalMemory, err := sysinfo.GetTotalMemoryBytes()
if err != nil {
return cgroup.Config{}, errors.Wrap(err, "Failed to get total memory bytes")
}
memoryLimitInBytes, err := parser.MemoryConfigToBytes(config.MemoryLimit, totalMemory)
if err != nil {
return cgroup.Config{}, err
}
return cgroup.Config{
MemoryLimitInBytes: memoryLimitInBytes,
}, nil
}

256
config/config_test.go Normal file
View File

@ -0,0 +1,256 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"path/filepath"
"testing"
"time"
"github.com/containerd/nydus-snapshotter/internal/constant"
"github.com/containerd/nydus-snapshotter/internal/flags"
"github.com/stretchr/testify/assert"
)
func TestLoadSnapshotterTOMLConfig(t *testing.T) {
A := assert.New(t)
cfg, err := LoadSnapshotterConfig("../misc/snapshotter/config.toml")
A.NoError(err)
exampleConfig := SnapshotterConfig{
Version: 1,
Root: "/var/lib/containerd/io.containerd.snapshotter.v1.nydus",
Address: "/run/containerd-nydus/containerd-nydus-grpc.sock",
DaemonMode: "dedicated",
Experimental: Experimental{
EnableStargz: false,
EnableReferrerDetect: false,
},
CleanupOnClose: false,
SystemControllerConfig: SystemControllerConfig{
Enable: true,
Address: "/run/containerd-nydus/system.sock",
DebugConfig: DebugConfig{
ProfileDuration: 5,
PprofAddress: "",
},
},
DaemonConfig: DaemonConfig{
NydusdPath: "/usr/local/bin/nydusd",
NydusImagePath: "/usr/local/bin/nydus-image",
FsDriver: "fusedev",
RecoverPolicy: "restart",
NydusdConfigPath: "/etc/nydus/nydusd-config.fusedev.json",
ThreadsNumber: 4,
LogRotationSize: 100,
},
SnapshotsConfig: SnapshotConfig{
EnableNydusOverlayFS: false,
NydusOverlayFSPath: "nydus-overlayfs",
SyncRemove: false,
},
RemoteConfig: RemoteConfig{
ConvertVpcRegistry: false,
AuthConfig: AuthConfig{
EnableKubeconfigKeychain: false,
KubeconfigPath: "",
},
MirrorsConfig: MirrorsConfig{
Dir: "",
},
},
ImageConfig: ImageConfig{
PublicKeyFile: "",
ValidateSignature: false,
},
CacheManagerConfig: CacheManagerConfig{
Disable: false,
GCPeriod: "24h",
CacheDir: "",
},
LoggingConfig: LoggingConfig{
LogLevel: "info",
RotateLogCompress: true,
RotateLogLocalTime: true,
RotateLogMaxAge: 7,
RotateLogMaxBackups: 5,
RotateLogMaxSize: 100,
LogToStdout: false,
},
MetricsConfig: MetricsConfig{
Address: ":9110",
},
CgroupConfig: CgroupConfig{
Enable: true,
MemoryLimit: "",
},
}
A.EqualValues(cfg, &exampleConfig)
args := flags.Args{}
args.RootDir = "/var/lib/containerd/nydus"
exampleConfig.Root = "/var/lib/containerd/nydus"
err = ParseParameters(&args, cfg)
A.NoError(err)
A.EqualValues(cfg, &exampleConfig)
A.EqualValues(cfg.LoggingConfig.LogToStdout, false)
args.LogToStdout = true
args.LogToStdoutCount = 1
err = ParseParameters(&args, cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, true)
err = ProcessConfigurations(cfg)
A.NoError(err)
A.Equal(GetCacheGCPeriod(), time.Hour*24)
}
func TestSnapshotterConfig(t *testing.T) {
A := assert.New(t)
var cfg SnapshotterConfig
var args flags.Args
// The log_to_stdout is false in toml file without --log-to-stdout flag.
// Expected false.
cfg.LoggingConfig.LogToStdout = false
args.LogToStdoutCount = 0
err := ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, false)
// The log_to_stdout is true in toml file without --log-to-stdout flag.
// Expected true.
// This case is failed.
cfg.LoggingConfig.LogToStdout = true
args.LogToStdoutCount = 0
err = ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, true)
// The log_to_stdout is false in toml file with --log-to-stdout=true.
// Expected true (command flag has higher priority).
args.LogToStdout = true
args.LogToStdoutCount = 1
cfg.LoggingConfig.LogToStdout = false
err = ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, true)
// The log_to_stdout is true in toml file with --log-to-stdout=true.
// Expected true (command flag has higher priority).
args.LogToStdout = true
args.LogToStdoutCount = 1
cfg.LoggingConfig.LogToStdout = true
err = ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, true)
// The log_to_stdout is false in toml file with --log-to-stdout=false.
// Expected false (command flag has higher priority).
args.LogToStdout = false
args.LogToStdoutCount = 1
cfg.LoggingConfig.LogToStdout = false
err = ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, false)
// The log_to_stdout is true in toml file with --log-to-stdout=false.
// Expected false (command flag has higher priority).
args.LogToStdout = false
args.LogToStdoutCount = 1
cfg.LoggingConfig.LogToStdout = true
err = ParseParameters(&args, &cfg)
A.NoError(err)
A.EqualValues(cfg.LoggingConfig.LogToStdout, false)
}
func TestMergeConfig(t *testing.T) {
A := assert.New(t)
var defaultSnapshotterConfig SnapshotterConfig
var snapshotterConfig1 SnapshotterConfig
err := defaultSnapshotterConfig.FillUpWithDefaults()
A.NoError(err)
err = MergeConfig(&snapshotterConfig1, &defaultSnapshotterConfig)
A.NoError(err)
A.Equal(snapshotterConfig1.Root, constant.DefaultRootDir)
A.Equal(snapshotterConfig1.LoggingConfig.LogDir, "")
A.Equal(snapshotterConfig1.CacheManagerConfig.CacheDir, "")
A.Equal(snapshotterConfig1.DaemonMode, constant.DefaultDaemonMode)
A.Equal(snapshotterConfig1.SystemControllerConfig.Address, constant.DefaultSystemControllerAddress)
A.Equal(snapshotterConfig1.LoggingConfig.LogLevel, constant.DefaultLogLevel)
A.Equal(snapshotterConfig1.LoggingConfig.RotateLogMaxSize, constant.DefaultRotateLogMaxSize)
A.Equal(snapshotterConfig1.LoggingConfig.RotateLogMaxBackups, constant.DefaultRotateLogMaxBackups)
A.Equal(snapshotterConfig1.LoggingConfig.RotateLogMaxAge, constant.DefaultRotateLogMaxAge)
A.Equal(snapshotterConfig1.LoggingConfig.RotateLogCompress, constant.DefaultRotateLogCompress)
A.Equal(snapshotterConfig1.DaemonConfig.NydusdConfigPath, constant.DefaultNydusDaemonConfigPath)
A.Equal(snapshotterConfig1.DaemonConfig.RecoverPolicy, RecoverPolicyRestart.String())
A.Equal(snapshotterConfig1.CacheManagerConfig.GCPeriod, constant.DefaultGCPeriod)
var snapshotterConfig2 SnapshotterConfig
snapshotterConfig2.Root = "/snapshotter/root"
err = MergeConfig(&snapshotterConfig2, &defaultSnapshotterConfig)
A.NoError(err)
A.Equal(snapshotterConfig2.Root, "/snapshotter/root")
A.Equal(snapshotterConfig2.LoggingConfig.LogDir, "")
A.Equal(snapshotterConfig2.CacheManagerConfig.CacheDir, "")
}
func TestProcessConfigurations(t *testing.T) {
A := assert.New(t)
var defaultSnapshotterConfig SnapshotterConfig
var snapshotterConfig1 SnapshotterConfig
err := defaultSnapshotterConfig.FillUpWithDefaults()
A.NoError(err)
err = MergeConfig(&snapshotterConfig1, &defaultSnapshotterConfig)
A.NoError(err)
err = ValidateConfig(&snapshotterConfig1)
A.NoError(err)
err = ProcessConfigurations(&snapshotterConfig1)
A.NoError(err)
A.Equal(snapshotterConfig1.LoggingConfig.LogDir, filepath.Join(snapshotterConfig1.Root, "logs"))
A.Equal(snapshotterConfig1.CacheManagerConfig.CacheDir, filepath.Join(snapshotterConfig1.Root, "cache"))
var snapshotterConfig2 SnapshotterConfig
snapshotterConfig2.Root = "/snapshotter/root"
err = MergeConfig(&snapshotterConfig2, &defaultSnapshotterConfig)
A.NoError(err)
err = ValidateConfig(&snapshotterConfig2)
A.NoError(err)
err = ProcessConfigurations(&snapshotterConfig2)
A.NoError(err)
A.Equal(snapshotterConfig2.LoggingConfig.LogDir, filepath.Join(snapshotterConfig2.Root, "logs"))
A.Equal(snapshotterConfig2.CacheManagerConfig.CacheDir, filepath.Join(snapshotterConfig2.Root, "cache"))
var snapshotterConfig3 SnapshotterConfig
snapshotterConfig3.Root = "./snapshotter/root"
err = MergeConfig(&snapshotterConfig3, &defaultSnapshotterConfig)
A.NoError(err)
err = ValidateConfig(&snapshotterConfig3)
A.NoError(err)
err = ProcessConfigurations(&snapshotterConfig3)
A.NoError(err)
}

View File

@ -1,184 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"encoding/json"
"io/ioutil"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/pkg/auth"
"github.com/containerd/nydus-snapshotter/pkg/utils/erofs"
"github.com/containerd/nydus-snapshotter/pkg/utils/registry"
)
const (
backendTypeLocalfs = "localfs"
backendTypeOss = "oss"
backendTypeRegistry = "registry"
)
type FSPrefetch struct {
Enable bool `json:"enable"`
PrefetchAll bool `json:"prefetch_all"`
ThreadsCount int `json:"threads_count"`
MergingSize int `json:"merging_size"`
BandwidthRate int `json:"bandwidth_rate"`
}
type FscacheDaemonConfig struct {
// These fields is only for fscache daemon.
Type string `json:"type"`
ID string `json:"id"`
DomainID string `json:"domain_id"`
Config struct {
ID string `json:"id"`
BackendType string `json:"backend_type"`
BackendConfig BackendConfig `json:"backend_config"`
CacheType string `json:"cache_type"`
CacheConfig struct {
WorkDir string `json:"work_dir"`
} `json:"cache_config"`
MetadataPath string `json:"metadata_path"`
} `json:"config"`
FSPrefetch `json:"fs_prefetch,omitempty"`
}
type DaemonConfig struct {
Device DeviceConfig `json:"device"`
Mode string `json:"mode"`
DigestValidate bool `json:"digest_validate"`
IOStatsFiles bool `json:"iostats_files,omitempty"`
EnableXattr bool `json:"enable_xattr,omitempty"`
FSPrefetch `json:"fs_prefetch,omitempty"`
FscacheDaemonConfig
}
type BackendConfig struct {
// Localfs backend configs
BlobFile string `json:"blob_file,omitempty"`
Dir string `json:"dir,omitempty"`
ReadAhead bool `json:"readahead"`
ReadAheadSec int `json:"readahead_sec,omitempty"`
// Registry backend configs
Host string `json:"host,omitempty"`
Repo string `json:"repo,omitempty"`
Auth string `json:"auth,omitempty"`
RegistryToken string `json:"registry_token,omitempty"`
BlobURLScheme string `json:"blob_url_scheme,omitempty"`
BlobRedirectedHost string `json:"blob_redirected_host,omitempty"`
// OSS backend configs
EndPoint string `json:"endpoint,omitempty"`
AccessKeyID string `json:"access_key_id,omitempty"`
AccessKeySecret string `json:"access_key_secret,omitempty"`
BucketName string `json:"bucket_name,omitempty"`
ObjectPrefix string `json:"object_prefix,omitempty"`
// Shared by registry and oss backend
Scheme string `json:"scheme,omitempty"`
SkipVerify bool `json:"skip_verify,omitempty"`
// Below configs are common configs shared by all backends
Proxy struct {
URL string `json:"url,omitempty"`
Fallback bool `json:"fallback"`
PingURL string `json:"ping_url,omitempty"`
CheckInterval int `json:"check_interval,omitempty"`
} `json:"proxy,omitempty"`
Timeout int `json:"timeout,omitempty"`
ConnectTimeout int `json:"connect_timeout,omitempty"`
RetryLimit int `json:"retry_limit,omitempty"`
}
type DeviceConfig struct {
Backend struct {
BackendType string `json:"type"`
Config BackendConfig `json:"config"`
} `json:"backend"`
Cache struct {
CacheType string `json:"type"`
Compressed bool `json:"compressed,omitempty"`
Config struct {
WorkDir string `json:"work_dir"`
DisableIndexedMap bool `json:"disable_indexed_map"`
} `json:"config"`
} `json:"cache"`
}
func LoadConfig(configFile string, cfg *DaemonConfig) error {
b, err := ioutil.ReadFile(configFile)
if err != nil {
return err
}
if err := json.Unmarshal(b, cfg); err != nil {
return err
}
return nil
}
func SaveConfig(c interface{}, configFile string) error {
b, err := json.Marshal(c)
if err != nil {
return nil
}
return ioutil.WriteFile(configFile, b, 0755)
}
func NewDaemonConfig(fsDriver string, cfg DaemonConfig, imageID, snapshotID string, vpcRegistry bool, labels map[string]string) (DaemonConfig, error) {
image, err := registry.ParseImage(imageID)
if err != nil {
return DaemonConfig{}, errors.Wrapf(err, "failed to parse image %s", imageID)
}
backend := cfg.Device.Backend.BackendType
if fsDriver == FsDriverFscache {
backend = cfg.Config.BackendType
}
switch backend {
case backendTypeRegistry:
registryHost := image.Host
if vpcRegistry {
registryHost = registry.ConvertToVPCHost(registryHost)
} else if registryHost == "docker.io" {
// For docker.io images, we should use index.docker.io
registryHost = "index.docker.io"
}
keyChain := auth.GetRegistryKeyChain(registryHost, labels)
// If no auth is provided, don't touch auth from provided nydusd configuration file.
// We don't validate the original nydusd auth from configuration file since it can be empty
// when repository is public.
backendConfig := &cfg.Device.Backend.Config
if fsDriver == FsDriverFscache {
backendConfig = &cfg.Config.BackendConfig
fscacheID := erofs.FscacheID(snapshotID)
cfg.ID = fscacheID
cfg.DomainID = fscacheID
cfg.Config.ID = fscacheID
}
if keyChain != nil {
if keyChain.TokenBase() {
backendConfig.RegistryToken = keyChain.Password
} else {
backendConfig.Auth = keyChain.ToBase64()
}
}
backendConfig.Host = registryHost
backendConfig.Repo = image.Repo
// Localfs and OSS backends don't need any update, just use the provided config in template
case backendTypeLocalfs:
case backendTypeOss:
default:
return DaemonConfig{}, errors.Errorf("unknown backend type %s", backend)
}
return cfg, nil
}

View File

@ -0,0 +1,236 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"encoding/json"
"os"
"reflect"
"strings"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/pkg/auth"
"github.com/containerd/nydus-snapshotter/pkg/utils/registry"
)
type StorageBackendType = string
const (
backendTypeLocalfs StorageBackendType = "localfs"
backendTypeOss StorageBackendType = "oss"
backendTypeRegistry StorageBackendType = "registry"
)
type DaemonConfig interface {
// Provide stuffs relevant to accessing registry apart from auth
Supplement(host, repo, snapshotID string, params map[string]string)
// Provide auth
FillAuth(kc *auth.PassKeyChain)
StorageBackend() (StorageBackendType, *BackendConfig)
UpdateMirrors(mirrorsConfigDir, registryHost string) error
DumpString() (string, error)
DumpFile(path string) error
}
// Daemon configurations factory
func NewDaemonConfig(fsDriver, path string) (DaemonConfig, error) {
switch fsDriver {
case config.FsDriverFscache:
cfg, err := LoadFscacheConfig(path)
if err != nil {
return nil, err
}
return cfg, nil
case config.FsDriverFusedev:
cfg, err := LoadFuseConfig(path)
if err != nil {
return nil, err
}
return cfg, nil
default:
return nil, errors.Errorf("unsupported, fs driver %q", fsDriver)
}
}
type MirrorConfig struct {
Host string `json:"host,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
HealthCheckInterval int `json:"health_check_interval,omitempty"`
FailureLimit uint8 `json:"failure_limit,omitempty"`
PingURL string `json:"ping_url,omitempty"`
}
type BackendConfig struct {
// Localfs backend configs
BlobFile string `json:"blob_file,omitempty"`
Dir string `json:"dir,omitempty"`
ReadAhead bool `json:"readahead"`
ReadAheadSec int `json:"readahead_sec,omitempty"`
// Registry backend configs
Host string `json:"host,omitempty"`
Repo string `json:"repo,omitempty"`
Auth string `json:"auth,omitempty" secret:"true"`
RegistryToken string `json:"registry_token,omitempty" secret:"true"`
BlobURLScheme string `json:"blob_url_scheme,omitempty"`
BlobRedirectedHost string `json:"blob_redirected_host,omitempty"`
Mirrors []MirrorConfig `json:"mirrors,omitempty"`
// OSS backend configs
EndPoint string `json:"endpoint,omitempty"`
AccessKeyID string `json:"access_key_id,omitempty" secret:"true"`
AccessKeySecret string `json:"access_key_secret,omitempty" secret:"true"`
BucketName string `json:"bucket_name,omitempty"`
ObjectPrefix string `json:"object_prefix,omitempty"`
// Shared by registry and oss backend
Scheme string `json:"scheme,omitempty"`
SkipVerify bool `json:"skip_verify,omitempty"`
// Below configs are common configs shared by all backends
Proxy struct {
URL string `json:"url,omitempty"`
Fallback bool `json:"fallback"`
PingURL string `json:"ping_url,omitempty"`
CheckInterval int `json:"check_interval,omitempty"`
UseHTTP bool `json:"use_http,omitempty"`
} `json:"proxy,omitempty"`
Timeout int `json:"timeout,omitempty"`
ConnectTimeout int `json:"connect_timeout,omitempty"`
RetryLimit int `json:"retry_limit,omitempty"`
}
type DeviceConfig struct {
Backend struct {
BackendType string `json:"type"`
Config BackendConfig `json:"config"`
} `json:"backend"`
Cache struct {
CacheType string `json:"type"`
Compressed bool `json:"compressed,omitempty"`
Config struct {
WorkDir string `json:"work_dir"`
DisableIndexedMap bool `json:"disable_indexed_map"`
} `json:"config"`
} `json:"cache"`
}
// For nydusd as FUSE daemon. Serialize Daemon info and persist to a json file
// We don't have to persist configuration file for fscache since its configuration
// is passed through HTTP API.
func DumpConfigFile(c interface{}, path string) error {
if config.IsBackendSourceEnabled() {
c = serializeWithSecretFilter(c)
}
b, err := json.Marshal(c)
if err != nil {
return errors.Wrapf(err, "marshal config")
}
return os.WriteFile(path, b, 0600)
}
func DumpConfigString(c interface{}) (string, error) {
b, err := json.Marshal(c)
return string(b), err
}
// Achieve a daemon configuration from template or snapshotter's configuration
func SupplementDaemonConfig(c DaemonConfig, imageID, snapshotID string,
vpcRegistry bool, labels map[string]string, params map[string]string) error {
image, err := registry.ParseImage(imageID)
if err != nil {
return errors.Wrapf(err, "parse image %s", imageID)
}
backendType, _ := c.StorageBackend()
switch backendType {
case backendTypeRegistry:
registryHost := image.Host
if vpcRegistry {
registryHost = registry.ConvertToVPCHost(registryHost)
} else if registryHost == "docker.io" {
// For docker.io images, we should use index.docker.io
registryHost = "index.docker.io"
}
if err := c.UpdateMirrors(config.GetMirrorsConfigDir(), registryHost); err != nil {
return errors.Wrap(err, "update mirrors config")
}
// If no auth is provided, don't touch auth from provided nydusd configuration file.
// We don't validate the original nydusd auth from configuration file since it can be empty
// when repository is public.
keyChain := auth.GetRegistryKeyChain(registryHost, imageID, labels)
c.Supplement(registryHost, image.Repo, snapshotID, params)
c.FillAuth(keyChain)
// Localfs and OSS backends don't need any update,
// just use the provided config in template
case backendTypeLocalfs:
case backendTypeOss:
default:
return errors.Errorf("unknown backend type %s", backendType)
}
return nil
}
func serializeWithSecretFilter(obj interface{}) map[string]interface{} {
result := make(map[string]interface{})
value := reflect.ValueOf(obj)
typeOfObj := reflect.TypeOf(obj)
if value.Kind() == reflect.Ptr {
value = value.Elem()
typeOfObj = typeOfObj.Elem()
}
for i := 0; i < value.NumField(); i++ {
field := value.Field(i)
fieldType := typeOfObj.Field(i)
secretTag := fieldType.Tag.Get("secret")
jsonTags := strings.Split(fieldType.Tag.Get("json"), ",")
omitemptyTag := false
for _, tag := range jsonTags {
if tag == "omitempty" {
omitemptyTag = true
break
}
}
if secretTag == "true" {
continue
}
if field.Kind() == reflect.Ptr && field.IsNil() {
continue
}
if omitemptyTag && reflect.DeepEqual(reflect.Zero(field.Type()).Interface(), field.Interface()) {
continue
}
//nolint:exhaustive
switch fieldType.Type.Kind() {
case reflect.Struct:
result[jsonTags[0]] = serializeWithSecretFilter(field.Interface())
case reflect.Ptr:
result[jsonTags[0]] = serializeWithSecretFilter(field.Elem().Interface())
default:
result[jsonTags[0]] = field.Interface()
}
}
return result
}

View File

@ -0,0 +1,155 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoadConfig(t *testing.T) {
buf := []byte(`{
"device": {
"backend": {
"type": "registry",
"config": {
"skip_verify": true,
"host": "acr-nydus-registry-vpc.cn-hangzhou.cr.aliyuncs.com",
"repo": "test/myserver",
"auth": "",
"blob_url_scheme": "http",
"proxy": {
"url": "http://p2p-proxy:65001",
"fallback": true,
"ping_url": "http://p2p-proxy:40901/server/ping",
"check_interval": 5
},
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 0
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/cache"
}
}
},
"mode": "direct",
"digest_validate": true,
"iostats_files": true,
"enable_xattr": true,
"amplify_io": 1048576,
"fs_prefetch": {
"enable": true,
"threads_count": 10,
"merging_size": 131072
}
}`)
var cfg FuseDaemonConfig
err := json.Unmarshal(buf, &cfg)
require.Nil(t, err)
require.Equal(t, cfg.FSPrefetch.Enable, true)
require.Equal(t, cfg.FSPrefetch.MergingSize, 131072)
require.Equal(t, cfg.FSPrefetch.ThreadsCount, 10)
require.Equal(t, cfg.Device.Backend.Config.BlobURLScheme, "http")
require.Equal(t, cfg.Device.Backend.Config.SkipVerify, true)
require.Equal(t, cfg.Device.Backend.Config.Proxy.CheckInterval, 5)
}
func TestAmplifyIo(t *testing.T) {
// Test non-zero value
input1 := []byte(`{"amplify_io": 1048576}`)
var cfg1 FuseDaemonConfig
err1 := json.Unmarshal(input1, &cfg1)
require.Nil(t, err1)
require.Equal(t, *cfg1.AmplifyIo, 1048576)
output1, _ := json.Marshal(cfg1)
require.Contains(t, string(output1), `"amplify_io":1048576`)
// Test zero value
input2 := []byte(`{"amplify_io": 0}`)
var cfg2 FuseDaemonConfig
err2 := json.Unmarshal(input2, &cfg2)
require.Nil(t, err2)
require.Equal(t, *cfg2.AmplifyIo, 0)
output2, _ := json.Marshal(cfg2)
require.Contains(t, string(output2), `"amplify_io":0`)
// Test nil value
input3 := []byte(`{}`)
var cfg3 FuseDaemonConfig
err3 := json.Unmarshal(input3, &cfg3)
require.Nil(t, err3)
require.Nil(t, cfg3.AmplifyIo)
output3, _ := json.Marshal(cfg3)
require.NotContains(t, string(output3), `amplify_io`)
}
func TestSerializeWithSecretFilter(t *testing.T) {
buf := []byte(`{
"device": {
"backend": {
"type": "registry",
"config": {
"skip_verify": true,
"host": "acr-nydus-registry-vpc.cn-hangzhou.cr.aliyuncs.com",
"repo": "test/myserver",
"auth": "token_token",
"blob_url_scheme": "http",
"proxy": {
"url": "http://p2p-proxy:65001",
"fallback": true,
"ping_url": "http://p2p-proxy:40901/server/ping",
"check_interval": 5
},
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 0
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/cache"
}
}
},
"mode": "direct",
"digest_validate": true,
"iostats_files": true,
"enable_xattr": true,
"fs_prefetch": {
"enable": true,
"threads_count": 10,
"merging_size": 131072
}
}`)
var cfg FuseDaemonConfig
_ = json.Unmarshal(buf, &cfg)
filter := serializeWithSecretFilter(&cfg)
jsonData, err := json.Marshal(filter)
require.Nil(t, err)
var newCfg FuseDaemonConfig
err = json.Unmarshal(jsonData, &newCfg)
require.Nil(t, err)
require.Equal(t, newCfg.FSPrefetch, cfg.FSPrefetch)
require.Equal(t, newCfg.Device.Cache.CacheType, cfg.Device.Cache.CacheType)
require.Equal(t, newCfg.Device.Cache.Config, cfg.Device.Cache.Config)
require.Equal(t, newCfg.Mode, cfg.Mode)
require.Equal(t, newCfg.DigestValidate, cfg.DigestValidate)
require.Equal(t, newCfg.IOStatsFiles, cfg.IOStatsFiles)
require.Equal(t, newCfg.Device.Backend.Config.Host, cfg.Device.Backend.Config.Host)
require.Equal(t, newCfg.Device.Backend.Config.Repo, cfg.Device.Backend.Config.Repo)
require.Equal(t, newCfg.Device.Backend.Config.Proxy, cfg.Device.Backend.Config.Proxy)
require.Equal(t, newCfg.Device.Backend.Config.BlobURLScheme, cfg.Device.Backend.Config.BlobURLScheme)
require.Equal(t, newCfg.Device.Backend.Config.Auth, "")
require.NotEqual(t, newCfg.Device.Backend.Config.Auth, cfg.Device.Backend.Config.Auth)
}

View File

@ -0,0 +1,131 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"encoding/json"
"os"
"path"
"github.com/containerd/log"
"github.com/containerd/nydus-snapshotter/pkg/auth"
"github.com/containerd/nydus-snapshotter/pkg/utils/erofs"
"github.com/pkg/errors"
)
const (
WorkDir string = "workdir"
Bootstrap string = "bootstrap"
)
type BlobPrefetchConfig struct {
Enable bool `json:"enable"`
ThreadsCount int `json:"threads_count"`
MergingSize int `json:"merging_size"`
BandwidthRate int `json:"bandwidth_rate"`
}
type FscacheDaemonConfig struct {
// These fields is only for fscache daemon.
Type string `json:"type"`
// Snapshotter fills
ID string `json:"id"`
DomainID string `json:"domain_id"`
Config *struct {
ID string `json:"id"`
BackendType string `json:"backend_type"`
BackendConfig BackendConfig `json:"backend_config"`
CacheType string `json:"cache_type"`
// Snapshotter fills
CacheConfig struct {
WorkDir string `json:"work_dir"`
} `json:"cache_config"`
BlobPrefetchConfig BlobPrefetchConfig `json:"prefetch_config"`
MetadataPath string `json:"metadata_path"`
} `json:"config"`
}
// Load Fscache configuration template file
func LoadFscacheConfig(p string) (*FscacheDaemonConfig, error) {
var cfg FscacheDaemonConfig
b, err := os.ReadFile(p)
if err != nil {
return nil, errors.Wrapf(err, "read fscache configuration file %s", p)
}
if err = json.Unmarshal(b, &cfg); err != nil {
return nil, errors.Wrapf(err, "unmarshal")
}
if cfg.Config == nil {
return nil, errors.New("invalid fscache configuration")
}
return &cfg, nil
}
func (c *FscacheDaemonConfig) UpdateMirrors(mirrorsConfigDir, registryHost string) error {
mirrors, err := LoadMirrorsConfig(mirrorsConfigDir, registryHost)
if err != nil {
return err
}
if len(mirrors) > 0 {
c.Config.BackendConfig.Mirrors = mirrors
}
return nil
}
func (c *FscacheDaemonConfig) StorageBackend() (string, *BackendConfig) {
return c.Config.BackendType, &c.Config.BackendConfig
}
// Each fscache/erofs has a configuration with different fscache ID built from snapshot ID.
func (c *FscacheDaemonConfig) Supplement(host, repo, snapshotID string, params map[string]string) {
c.Config.BackendConfig.Host = host
c.Config.BackendConfig.Repo = repo
fscacheID := erofs.FscacheID(snapshotID)
c.ID = fscacheID
if c.DomainID != "" {
log.L.Warnf("Linux Kernel Shared Domain feature in use. make sure your kernel version >= 6.1")
} else {
c.DomainID = fscacheID
}
c.Config.ID = fscacheID
if WorkDir, ok := params[WorkDir]; ok {
c.Config.CacheConfig.WorkDir = WorkDir
}
if bootstrap, ok := params[Bootstrap]; ok {
c.Config.MetadataPath = bootstrap
}
}
func (c *FscacheDaemonConfig) FillAuth(kc *auth.PassKeyChain) {
if kc != nil {
if kc.TokenBase() {
c.Config.BackendConfig.RegistryToken = kc.Password
} else {
c.Config.BackendConfig.Auth = kc.ToBase64()
}
}
}
func (c *FscacheDaemonConfig) DumpString() (string, error) {
return DumpConfigString(c)
}
func (c *FscacheDaemonConfig) DumpFile(f string) error {
if err := os.MkdirAll(path.Dir(f), 0755); err != nil {
return err
}
return DumpConfigFile(c, f)
}

103
config/daemonconfig/fuse.go Normal file
View File

@ -0,0 +1,103 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"encoding/json"
"os"
"path"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/pkg/auth"
)
const CacheDir string = "cachedir"
// Used when nydusd works as a FUSE daemon or vhost-user-fs backend
type FuseDaemonConfig struct {
Device *DeviceConfig `json:"device"`
Mode string `json:"mode"`
DigestValidate bool `json:"digest_validate"`
IOStatsFiles bool `json:"iostats_files,omitempty"`
EnableXattr bool `json:"enable_xattr,omitempty"`
AccessPattern bool `json:"access_pattern,omitempty"`
LatestReadFiles bool `json:"latest_read_files,omitempty"`
AmplifyIo *int `json:"amplify_io,omitempty"`
FSPrefetch `json:"fs_prefetch,omitempty"`
// (experimental) The nydus daemon could cache more data to increase hit ratio when enabled the warmup feature.
Warmup uint64 `json:"warmup,omitempty"`
}
// Control how to perform prefetch from file system layer
type FSPrefetch struct {
Enable bool `json:"enable"`
PrefetchAll bool `json:"prefetch_all"`
ThreadsCount int `json:"threads_count"`
MergingSize int `json:"merging_size"`
BandwidthRate int `json:"bandwidth_rate"`
}
// Load fuse daemon configuration from template file
func LoadFuseConfig(p string) (*FuseDaemonConfig, error) {
b, err := os.ReadFile(p)
if err != nil {
return nil, errors.Wrapf(err, "read FUSE configuration file %s", p)
}
var cfg FuseDaemonConfig
if err := json.Unmarshal(b, &cfg); err != nil {
return nil, errors.Wrapf(err, "unmarshal %s", p)
}
if cfg.Device == nil {
return nil, errors.New("invalid fuse daemon configuration")
}
return &cfg, nil
}
func (c *FuseDaemonConfig) Supplement(host, repo, _ string, params map[string]string) {
c.Device.Backend.Config.Host = host
c.Device.Backend.Config.Repo = repo
c.Device.Cache.Config.WorkDir = params[CacheDir]
}
func (c *FuseDaemonConfig) FillAuth(kc *auth.PassKeyChain) {
if kc != nil {
if kc.TokenBase() {
c.Device.Backend.Config.RegistryToken = kc.Password
} else {
c.Device.Backend.Config.Auth = kc.ToBase64()
}
}
}
func (c *FuseDaemonConfig) UpdateMirrors(mirrorsConfigDir, registryHost string) error {
mirrors, err := LoadMirrorsConfig(mirrorsConfigDir, registryHost)
if err != nil {
return err
}
if len(mirrors) > 0 {
c.Device.Backend.Config.Mirrors = mirrors
}
return nil
}
func (c *FuseDaemonConfig) StorageBackend() (string, *BackendConfig) {
return c.Device.Backend.BackendType, &c.Device.Backend.Config
}
func (c *FuseDaemonConfig) DumpString() (string, error) {
return DumpConfigString(c)
}
func (c *FuseDaemonConfig) DumpFile(f string) error {
if err := os.MkdirAll(path.Dir(f), 0755); err != nil {
return err
}
return DumpConfigFile(c, f)
}

View File

@ -0,0 +1,259 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"sort"
"strings"
"github.com/containerd/log"
"github.com/pelletier/go-toml"
"github.com/pkg/errors"
)
// Copied from containerd, for compatibility with containerd's toml configuration file.
type HostFileConfig struct {
Capabilities []string `toml:"capabilities"`
CACert interface{} `toml:"ca"`
Client interface{} `toml:"client"`
SkipVerify *bool `toml:"skip_verify"`
Header map[string]interface{} `toml:"header"`
OverridePath bool `toml:"override_path"`
// The following configuration items are specific to nydus.
HealthCheckInterval int `toml:"health_check_interval,omitempty"`
FailureLimit uint8 `toml:"failure_limit,omitempty"`
PingURL string `toml:"ping_url,omitempty"`
}
type hostConfig struct {
Scheme string
Host string
Header http.Header
HealthCheckInterval int
FailureLimit uint8
PingURL string
}
func makeStringSlice(slice []interface{}, cb func(string) string) ([]string, error) {
out := make([]string, len(slice))
for i, value := range slice {
str, ok := value.(string)
if !ok {
return nil, fmt.Errorf("unable to cast %v to string", value)
}
if cb != nil {
out[i] = cb(str)
} else {
out[i] = str
}
}
return out, nil
}
func parseMirrorsConfig(hosts []hostConfig) []MirrorConfig {
var parsedMirrors = make([]MirrorConfig, len(hosts))
for i, host := range hosts {
parsedMirrors[i].Host = fmt.Sprintf("%s://%s", host.Scheme, host.Host)
parsedMirrors[i].HealthCheckInterval = host.HealthCheckInterval
parsedMirrors[i].FailureLimit = host.FailureLimit
parsedMirrors[i].PingURL = host.PingURL
if len(host.Header) > 0 {
mirrorHeader := make(map[string]string, len(host.Header))
for key, value := range host.Header {
if len(value) > 1 {
log.L.Warnf("some values of the header[%q] are omitted: %#v", key, value[1:])
}
mirrorHeader[key] = host.Header.Get(key)
}
parsedMirrors[i].Headers = mirrorHeader
}
}
return parsedMirrors
}
// hostDirectory converts ":port" to "_port_" in directory names
func hostDirectory(host string) string {
idx := strings.LastIndex(host, ":")
if idx > 0 {
return host[:idx] + "_" + host[idx+1:] + "_"
}
return host
}
func hostPaths(root, host string) []string {
var hosts []string
ch := hostDirectory(host)
if ch != host {
hosts = append(hosts, filepath.Join(root, ch))
}
return append(hosts,
filepath.Join(root, host),
filepath.Join(root, "_default"),
)
}
func hostDirFromRoot(root, host string) (string, error) {
for _, p := range hostPaths(root, host) {
if _, err := os.Stat(p); err == nil {
return p, nil
} else if !os.IsNotExist(err) {
return "", err
}
}
return "", nil
}
// getSortedHosts returns the list of hosts as they defined in the file.
func getSortedHosts(root *toml.Tree) ([]string, error) {
iter, ok := root.Get("host").(*toml.Tree)
if !ok {
return nil, errors.New("invalid `host` tree")
}
list := append([]string{}, iter.Keys()...)
// go-toml stores TOML sections in the map object, so no order guaranteed.
// We retrieve line number for each key and sort the keys by position.
sort.Slice(list, func(i, j int) bool {
h1 := iter.GetPath([]string{list[i]}).(*toml.Tree)
h2 := iter.GetPath([]string{list[j]}).(*toml.Tree)
return h1.Position().Line < h2.Position().Line
})
return list, nil
}
// parseHostConfig returns the parsed host configuration, make sure the server is not null.
func parseHostConfig(server string, config HostFileConfig) (hostConfig, error) {
var (
result = hostConfig{}
err error
)
if !strings.HasPrefix(server, "http") {
server = "https://" + server
}
u, err := url.Parse(server)
if err != nil {
return hostConfig{}, fmt.Errorf("unable to parse server %v: %w", server, err)
}
result.Scheme = u.Scheme
result.Host = u.Host
if config.Header != nil {
header := http.Header{}
for key, ty := range config.Header {
switch value := ty.(type) {
case string:
header[key] = []string{value}
case []interface{}:
header[key], err = makeStringSlice(value, nil)
if err != nil {
return hostConfig{}, err
}
default:
return hostConfig{}, fmt.Errorf("invalid type %v for header %q", ty, key)
}
}
result.Header = header
}
result.HealthCheckInterval = config.HealthCheckInterval
result.FailureLimit = config.FailureLimit
result.PingURL = config.PingURL
return result, nil
}
func parseHostsFile(b []byte) ([]hostConfig, error) {
tree, err := toml.LoadBytes(b)
if err != nil {
return nil, fmt.Errorf("failed to parse TOML: %w", err)
}
c := struct {
// HostConfigs store the per-host configuration
HostConfigs map[string]HostFileConfig `toml:"host"`
}{}
orderedHosts, err := getSortedHosts(tree)
if err != nil {
return nil, err
}
var (
hosts []hostConfig
)
if err := tree.Unmarshal(&c); err != nil {
return nil, err
}
// Parse hosts array
for _, host := range orderedHosts {
if host != "" {
config := c.HostConfigs[host]
parsed, err := parseHostConfig(host, config)
if err != nil {
return nil, err
}
hosts = append(hosts, parsed)
}
}
return hosts, nil
}
func loadHostDir(hostsDir string) ([]hostConfig, error) {
b, err := os.ReadFile(filepath.Join(hostsDir, "hosts.toml"))
if err != nil {
if !os.IsNotExist(err) {
return nil, err
}
return []hostConfig{}, nil
}
hosts, err := parseHostsFile(b)
if err != nil {
return nil, err
}
return hosts, nil
}
func LoadMirrorsConfig(mirrorsConfigDir, registryHost string) ([]MirrorConfig, error) {
var mirrors []MirrorConfig
if mirrorsConfigDir == "" {
return mirrors, nil
}
hostDir, err := hostDirFromRoot(mirrorsConfigDir, registryHost)
if err != nil {
return nil, err
}
if hostDir == "" {
return mirrors, nil
}
hostConfig, err := loadHostDir(hostDir)
if err != nil {
return nil, err
}
mirrors = append(mirrors, parseMirrorsConfig(hostConfig)...)
return mirrors, nil
}

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package daemonconfig
import (
"os"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoadMirrorConfig(t *testing.T) {
tmpDir := t.TempDir()
defer os.RemoveAll(tmpDir)
registryHost := "registry.docker.io"
mirrorsConfigDir := filepath.Join(tmpDir, "certs.d")
registryHostConfigDir := filepath.Join(mirrorsConfigDir, registryHost)
defaultHostConfigDir := filepath.Join(mirrorsConfigDir, "_default")
mirrors, err := LoadMirrorsConfig("", registryHost)
require.NoError(t, err)
require.Nil(t, mirrors)
mirrors, err = LoadMirrorsConfig(mirrorsConfigDir, registryHost)
require.NoError(t, err)
require.Nil(t, mirrors)
err = os.MkdirAll(defaultHostConfigDir, os.ModePerm)
assert.NoError(t, err)
mirrors, err = LoadMirrorsConfig(mirrorsConfigDir, registryHost)
require.NoError(t, err)
require.Nil(t, mirrors)
buf1 := []byte(`server = "https://default-docker.hub.com"
[host]
[host."http://default-p2p-mirror1:65001"]
[host."http://default-p2p-mirror1:65001".header]
X-Dragonfly-Registry = ["https://default-docker.hub.com"]
`)
err = os.WriteFile(filepath.Join(defaultHostConfigDir, "hosts.toml"), buf1, 0600)
assert.NoError(t, err)
mirrors, err = LoadMirrorsConfig(mirrorsConfigDir, registryHost)
require.NoError(t, err)
require.Equal(t, len(mirrors), 1)
require.Equal(t, mirrors[0].Host, "http://default-p2p-mirror1:65001")
require.Equal(t, mirrors[0].Headers["X-Dragonfly-Registry"], "https://default-docker.hub.com")
err = os.MkdirAll(registryHostConfigDir, os.ModePerm)
assert.NoError(t, err)
buf2 := []byte(`server = "https://docker.hub.com"
[host]
[host."http://p2p-mirror1:65001"]
[host."http://p2p-mirror1:65001".header]
X-Dragonfly-Registry = ["https://docker.hub.com"]
`)
err = os.WriteFile(filepath.Join(registryHostConfigDir, "hosts.toml"), buf2, 0600)
assert.NoError(t, err)
mirrors, err = LoadMirrorsConfig(mirrorsConfigDir, registryHost)
require.NoError(t, err)
require.Equal(t, len(mirrors), 1)
require.Equal(t, mirrors[0].Host, "http://p2p-mirror1:65001")
require.Equal(t, mirrors[0].Headers["X-Dragonfly-Registry"], "https://docker.hub.com")
buf3 := []byte(`
[host."http://p2p-mirror2:65001"]
[host."http://p2p-mirror2:65001".header]
X-Dragonfly-Registry = ["https://docker.hub.com"]
`)
err = os.WriteFile(filepath.Join(registryHostConfigDir, "hosts.toml"), buf3, 0600)
assert.NoError(t, err)
mirrors, err = LoadMirrorsConfig(mirrorsConfigDir, registryHost)
require.NoError(t, err)
require.Equal(t, len(mirrors), 1)
require.Equal(t, mirrors[0].Host, "http://p2p-mirror2:65001")
require.Equal(t, mirrors[0].Headers["X-Dragonfly-Registry"], "https://docker.hub.com")
}

View File

@ -1,65 +0,0 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"encoding/json"
"testing"
"github.com/stretchr/testify/require"
)
func TestLoadConfig(t *testing.T) {
buf := []byte(`{
"device": {
"backend": {
"type": "registry",
"config": {
"scheme": "https",
"skip_verify": true,
"host": "acr-nydus-registry-vpc.cn-hangzhou.cr.aliyuncs.com",
"repo": "test/myserver",
"auth": "",
"blob_url_scheme": "http",
"proxy": {
"url": "http://p2p-proxy:65001",
"fallback": true,
"ping_url": "http://p2p-proxy:40901/server/ping",
"check_interval": 5
},
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 0
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/cache"
}
}
},
"mode": "direct",
"digest_validate": true,
"iostats_files": true,
"enable_xattr": true,
"fs_prefetch": {
"enable": true,
"threads_count": 10,
"merging_size": 131072
}
}`)
var cfg DaemonConfig
err := json.Unmarshal(buf, &cfg)
require.Nil(t, err)
require.Equal(t, cfg.FSPrefetch.Enable, true)
require.Equal(t, cfg.FSPrefetch.MergingSize, 131072)
require.Equal(t, cfg.FSPrefetch.ThreadsCount, 10)
require.Equal(t, cfg.Device.Backend.Config.BlobURLScheme, "http")
require.Equal(t, cfg.Device.Backend.Config.SkipVerify, true)
require.Equal(t, cfg.Device.Backend.Config.Proxy.CheckInterval, 5)
}

69
config/default.go Normal file
View File

@ -0,0 +1,69 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package config
import (
"os/exec"
"github.com/containerd/nydus-snapshotter/internal/constant"
)
func (c *SnapshotterConfig) FillUpWithDefaults() error {
c.Version = 1
c.Root = constant.DefaultRootDir
c.Address = constant.DefaultAddress
// essential configuration
if c.DaemonMode == "" {
c.DaemonMode = constant.DefaultDaemonMode
}
// system controller configuration
c.SystemControllerConfig.Address = constant.DefaultSystemControllerAddress
// logging configuration
logConfig := &c.LoggingConfig
if logConfig.LogLevel == "" {
logConfig.LogLevel = constant.DefaultLogLevel
}
logConfig.RotateLogMaxSize = constant.DefaultRotateLogMaxSize
logConfig.RotateLogMaxBackups = constant.DefaultRotateLogMaxBackups
logConfig.RotateLogMaxAge = constant.DefaultRotateLogMaxAge
logConfig.RotateLogLocalTime = constant.DefaultRotateLogLocalTime
logConfig.RotateLogCompress = constant.DefaultRotateLogCompress
// daemon configuration
daemonConfig := &c.DaemonConfig
if daemonConfig.NydusdConfigPath == "" {
daemonConfig.NydusdConfigPath = constant.DefaultNydusDaemonConfigPath
}
daemonConfig.RecoverPolicy = RecoverPolicyRestart.String()
daemonConfig.FsDriver = constant.DefaultFsDriver
daemonConfig.LogRotationSize = constant.DefaultDaemonRotateLogMaxSize
// cache configuration
cacheConfig := &c.CacheManagerConfig
if cacheConfig.GCPeriod == "" {
cacheConfig.GCPeriod = constant.DefaultGCPeriod
}
return c.SetupNydusBinaryPaths()
}
func (c *SnapshotterConfig) SetupNydusBinaryPaths() error {
// resolve nydusd path
if path, err := exec.LookPath(constant.NydusdBinaryName); err == nil {
c.DaemonConfig.NydusdPath = path
}
// resolve nydus-image path
if path, err := exec.LookPath(constant.NydusImageBinaryName); err == nil {
c.DaemonConfig.NydusImagePath = path
}
return nil
}

221
config/global.go Normal file
View File

@ -0,0 +1,221 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
// Expose configurations across nydus-snapshotter, the configurations is parsed
// and extracted from nydus-snapshotter toml based configuration file or command line
package config
import (
"os"
"path/filepath"
"time"
"github.com/containerd/log"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/internal/logging"
"github.com/containerd/nydus-snapshotter/pkg/utils/mount"
)
var (
globalConfig GlobalConfig
)
// Global cached configuration information to help:
// - access configuration information without passing a configuration object
// - avoid frequent generation of information from configuration information
type GlobalConfig struct {
origin *SnapshotterConfig
SnapshotsDir string
DaemonMode DaemonMode
SocketRoot string
ConfigRoot string
RootMountpoint string
DaemonThreadsNum int
CacheGCPeriod time.Duration
MirrorsConfig MirrorsConfig
}
func IsFusedevSharedModeEnabled() bool {
return globalConfig.DaemonMode == DaemonModeShared
}
func GetDaemonMode() DaemonMode {
return globalConfig.DaemonMode
}
func GetSnapshotsRootDir() string {
return globalConfig.SnapshotsDir
}
func GetRootMountpoint() string {
return globalConfig.RootMountpoint
}
func GetSocketRoot() string {
return globalConfig.SocketRoot
}
func GetConfigRoot() string {
return globalConfig.ConfigRoot
}
func GetMirrorsConfigDir() string {
return globalConfig.MirrorsConfig.Dir
}
func GetFsDriver() string {
return globalConfig.origin.DaemonConfig.FsDriver
}
func GetCacheGCPeriod() time.Duration {
return globalConfig.CacheGCPeriod
}
func GetLogDir() string {
return globalConfig.origin.LoggingConfig.LogDir
}
func GetLogLevel() string {
return globalConfig.origin.LoggingConfig.LogLevel
}
func GetDaemonLogRotationSize() int {
return globalConfig.origin.DaemonConfig.LogRotationSize
}
func GetDaemonThreadsNumber() int {
return globalConfig.origin.DaemonConfig.ThreadsNumber
}
func GetLogToStdout() bool {
return globalConfig.origin.LoggingConfig.LogToStdout
}
func IsBackendSourceEnabled() bool {
return globalConfig.origin.Experimental.EnableBackendSource && globalConfig.origin.SystemControllerConfig.Enable
}
func IsSystemControllerEnabled() bool {
return globalConfig.origin.SystemControllerConfig.Enable
}
func SystemControllerAddress() string {
return globalConfig.origin.SystemControllerConfig.Address
}
func SystemControllerPprofAddress() string {
return globalConfig.origin.SystemControllerConfig.DebugConfig.PprofAddress
}
func GetDaemonProfileCPUDuration() int64 {
return globalConfig.origin.SystemControllerConfig.DebugConfig.ProfileDuration
}
func GetSkipSSLVerify() bool {
return globalConfig.origin.RemoteConfig.SkipSSLVerify
}
const (
TarfsLayerVerityOnly string = "layer_verity_only"
TarfsImageVerityOnly string = "image_verity_only"
TarfsLayerBlockDevice string = "layer_block"
TarfsImageBlockDevice string = "image_block"
TarfsLayerBlockWithVerity string = "layer_block_with_verity"
TarfsImageBlockWithVerity string = "image_block_with_verity"
)
func GetTarfsMountOnHost() bool {
return globalConfig.origin.Experimental.TarfsConfig.MountTarfsOnHost
}
func GetTarfsExportEnabled() bool {
switch globalConfig.origin.Experimental.TarfsConfig.ExportMode {
case TarfsLayerVerityOnly, TarfsLayerBlockDevice, TarfsLayerBlockWithVerity:
return true
case TarfsImageVerityOnly, TarfsImageBlockDevice, TarfsImageBlockWithVerity:
return true
default:
return false
}
}
// Returns (wholeImage, generateBlockImage, withVerityInfo)
// wholeImage: generate tarfs for the whole image instead of of a specific layer.
// generateBlockImage: generate a block image file.
// withVerityInfo: generate disk verity information.
func GetTarfsExportFlags() (bool, bool, bool) {
switch globalConfig.origin.Experimental.TarfsConfig.ExportMode {
case "layer_verity_only":
return false, false, true
case "image_verity_only":
return true, false, true
case "layer_block":
return false, true, false
case "image_block":
return true, true, false
case "layer_block_with_verity":
return false, true, true
case "image_block_with_verity":
return true, true, true
default:
return false, false, false
}
}
func ProcessConfigurations(c *SnapshotterConfig) error {
if c.LoggingConfig.LogDir == "" {
c.LoggingConfig.LogDir = filepath.Join(c.Root, logging.DefaultLogDirName)
}
if c.CacheManagerConfig.CacheDir == "" {
c.CacheManagerConfig.CacheDir = filepath.Join(c.Root, "cache")
}
globalConfig.origin = c
globalConfig.SnapshotsDir = filepath.Join(c.Root, "snapshots")
globalConfig.ConfigRoot = filepath.Join(c.Root, "config")
globalConfig.SocketRoot = filepath.Join(c.Root, "socket")
globalConfig.RootMountpoint = filepath.Join(c.Root, "mnt")
globalConfig.MirrorsConfig = c.RemoteConfig.MirrorsConfig
if c.CacheManagerConfig.GCPeriod != "" {
d, err := time.ParseDuration(c.CacheManagerConfig.GCPeriod)
if err != nil {
return errors.Errorf("invalid GC period '%s'", c.CacheManagerConfig.GCPeriod)
}
globalConfig.CacheGCPeriod = d
}
m, err := parseDaemonMode(c.DaemonMode)
if err != nil {
return err
}
if c.DaemonConfig.FsDriver == FsDriverFscache && m != DaemonModeShared {
log.L.Infof("fscache driver only supports 'shared' mode, override daemon mode from '%s' to 'shared'", m)
m = DaemonModeShared
}
globalConfig.DaemonMode = m
return nil
}
func SetUpEnvironment(c *SnapshotterConfig) error {
if err := os.MkdirAll(c.Root, 0700); err != nil {
return errors.Wrapf(err, "create root dir %s", c.Root)
}
realPath, err := mount.NormalizePath(c.Root)
if err != nil {
return errors.Wrapf(err, "invalid root path")
}
c.Root = realPath
return nil
}

View File

@ -1,37 +1,139 @@
# How to Configure Nydus
# Configure Nydus-snapshotter
Nydus-snapshotter receives a json file as nydusd configuration through CLI option `--config-path`.
An example configuration looks like below.
You can find registry auth from local docker configuration.
Nydus-snapshotter can receive a toml file as its configurations to start providing image service through CLI parameter `--config`. An example configuration file can be found [here](../misc/snapshotter/config.toml). Besides nydus-snapshotter's configuration, `nydusd`'s configuration has to be provided to nydus-snapshotter too. Nydusd is started by nydus-snapshotter and it is configured by the provided json configuration file. A minimal configuration file can be found [here](../misc/snapshotter/nydusd-config.fusedev.json)
```json
{
"device": {
"backend": {
"type": "registry",
"config": {
"scheme": "https",
"auth": "<registry auth token>",
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 0
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/tmp/cache"
}
}
},
"mode": "direct",
"digest_validate": false,
"iostats_files": false,
"enable_xattr": true,
"fs_prefetch": {
"enable": true,
"threads_count": 6,
"merging_size": 131072
}
}
## Authentication
As [containerd#3731](https://github.com/containerd/containerd/issues/3731) discussed, containerd doesn't share credentials with third snapshotters now. Like [stargz snapshotter](https://github.com/containerd/stargz-snapshotter/blob/main/docs/overview.md#authentication), nydus-snapshotter supports 3 main ways to access registries with custom configurations. You can use configuration file to enable them.
The snapshotter will try to get image pull keychain in the following order if such way is enabled:
1. intercept CRI request and extract private registry auth
2. docker config (default enabled)
3. k8s docker config secret
### dockerconfig-based authentication
By default, the snapshotter tries to get credentials from `$DOCKER_CONFIG` or `~/.docker/config.json`.
Following example enables nydus-snapshotter to access to private registries using `docker login` command.
```console
# docker login
(Enter username and password)
# crictl pull --creds USERNAME[:PASSWORD] docker.io/<your-repository>/ubuntu:22.04
(Here the credential is only used by containerd)
```
### CRI-based authentication
Following configuration enables nydus-snapshotter to pull private images via CRI requests.
```toml
[remote.auth]
# Fetch the private registry auth as CRI image service proxy
enable_cri_keychain = true
image_service_address = "/run/containerd/containerd.sock"
```
The snapshotter works as a proxy of CRI Image Service and exposes CRI Image Service API on the snapshotter's unix socket (i.e. `/run/containerd/containerd-nydus-grpc.sock`). The snapshotter acquires registry creds by scanning requests.
The `image_service_address` is the original image service socket. It can be omitted and the default value will be the containerd's default socket path `/run/containerd/containerd.sock`.
You **must** specify `--image-service-endpoint=unix:///run/containerd-nydus/containerd-nydus-grpc.sock` option to kubelet when using Kubernetes. Or specify `image-endpoint: "unix:////run/containerd-nydus/containerd-nydus-grpc.sock"` in `crictl.yaml` when using `crictl`.
### kubeconfig-based authentication
This is another way to enable lazy pulling of private images on Kubernetes, Nydus snapshotter will start a goroutine to listen on secrets (type = `kubernetes.io/dockerconfigjson`) for private registries.
#### use kubeconfig file
Following configuration enables nydus-snapshotter to access to private registries using kubernetes secrets in the cluster using kubeconfig files.
```toml
[remote.auth]
enable_kubeconfig_keychain = true
kubeconfig_path = "/path/to/.kubeconfig"
```
If no `kubeconfig_path` is specified, snapshotter searches kubeconfig files from `$KUBECONFIG` or `~/.kube/config`.
Please note that kubeconfig-based authentication requires additional privilege (i.e. kubeconfig to list/watch secrets) to the node.
And this doesn't work if `kubelet` retrieve credentials from somewhere not API server (e.g. [credential provider](https://kubernetes.io/docs/tasks/kubelet-credential-provider/kubelet-credential-provider/)).
#### use ServiceAccount
If your Nydus snapshotter runs in a Kubernetes cluster and you don't want to use kubeconfig, you can also choose to use ServiceAccount to configure the corresponding permissions for Nydus snapshotter.
```yaml
apiVersion: v1
kind: ServiceAccount
metadata:
name: nydus-snapshotter-sa
namespace: nydus-system
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: nydus-snapshotter-role
rules:
- apiGroups:
- ""
resources:
- secrets
verbs:
- get
- list
- watch
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: nydus-snapshotter-role-binding
roleRef:
kind: ClusterRole
name: nydus-snapshotter-role
apiGroup: rbac.authorization.k8s.io
subjects:
- kind: ServiceAccount
name: nydus-snapshotter-sa
namespace: nydus-system
```
Then you can set the desired ServiceAccount with the required permissions fro your Nydus snapshotter Pod:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: nydus-snapshotter
namespace: nydus-system
spec:
containers:
name: nydus-snapshotter
serviceAccountName: nydus-snapshotter-sa
...
```
#### create secrets
If you have logged into a private registry, you can create a secret from the config file:
```bash
$ kubectl create --namespace nydus-system secret generic regcred \
--from-file=.dockerconfigjson=$HOME/.docker/config.json \
--type=kubernetes.io/dockerconfigjson
```
The Nydus snapshotter will get the new secret and parse the authorization. If your new Pod uses a private registry, then this authentication information will be used to pull the image from the private registry.
## Metrics
Nydusd records metrics in its own format. The metrics are exported via a HTTP server on top of unix domain socket. Nydus-snapshotter fetches the metrics and convert them in to Prometheus format which is exported via a network address. Nydus-snapshotter by default does not fetch metrics from nydusd. You can enable the nydusd metrics download by assigning a network address to `metrics.address` in nydus-snapshotter's toml [configuration file](../misc/snapshotter/config.toml).
Once this entry is enabled, not only nydusd metrics, but also some information about the nydus-snapshotter
runtime and snapshot related events are exported in Prometheus format as well.
## Diagnose
A system controller can be ran insides nydus-snapshotter.
By setting `system.enable` to `true`, nydus-snapshotter will start a simple HTTP server on unix domain socket `system.address` path and exports some internal working status to users. The address defaults to `/var/run/containerd-nydus/system.sock`

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 23 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 22 KiB

File diff suppressed because one or more lines are too long

After

Width:  |  Height:  |  Size: 14 KiB

View File

@ -0,0 +1,135 @@
# Optimize a nydus image
To improve the prefetch hit rate, we can specify a prefetch table when converting an OCI image to a nydus image. The prefetch table is workload related and we should generate the list of accessed files in order when the workload is running. Nydus-snapshotter has implemented an optimizer with Containerd NRI plugin to optimize the nydus image. The optimizer is image format independent and requires NRI 2.0, which is available in containerd (>=v1.7.0). The optimizer subscribes container events to watch what files are opened and read, etc. during container application is starting up. This enables nydus image build tools to optimize the nydus image making it put the necessary and prioritized files into a special region of nydus image with extra image metadata. So nydus runtime can pull this files into local disk in top priority, thus to boost the performance further.
## Requirements
- [NRI 2.0](https://github.com/containerd/nri): Which has been integrated into containerd since [v1.7.0](https://github.com/containerd/containerd/tree/v1.7.0-beta.1).
## Workflow
![optimizer workload](./diagram/optmizer_workflow.svg)
1. Run the optimizer as a NRI plugin to run optimizer server when the StartContainer event occurs.
2. Optimizer server joins container mount namespace and starts fanotify server.
3. Optimizer server detects fanotify event and sends the accessed file descriptor to client.
4. Optimizer client converts file descriptor to path.
5. Generate list of accessed files on local disk.
6. Convert OCI images with accessed files list to nydus image.
## Generate an accessed files list
To install the optimizer and optimizer-server, invoke below command:
```console
make optimizer && make install-optimizer
```
This command installs the optimizer's default toml configuration file in `/etc/nri/conf.d/02-optimizer-nri-plugin.conf`. Here is an example:
```toml
# The directory to persist accessed files list for container.
persist_dir = "/opt/nri/optimizer/results"
# Whether to make the csv file human readable.
readable = false
# The path of optimizer server binary.
server_path = "/usr/local/bin/optimizer-server"
# The timeout to kill optimizer server, 0 to disable it.
timeout = 0
# Whether to overwrite the existed persistent files.
overwrite = false
# The events that containerd subscribes to.
# Do not change this element.
events = [ "StartContainer", "StopContainer" ]
```
Modify containerd's toml configuration file to enable NRI.
```console
sudo tee -a /etc/containerd/config.toml <<- EOF
[plugins."io.containerd.nri.v1.nri"]
config_file = "/etc/nri/nri.conf"
disable = false
plugin_path = "/opt/nri/plugins"
socket_path = "/var/run/nri.sock"
EOF
```
Containerd will load all NRI plugins in the `plugin_path` directory on startup. If you want to start a NRI plugin manually, please add the following configuration to allow other NRI plugins to connect via `socket_path`.
```console
sudo tee /etc/nri/nri.conf <<- EOF
disableConnections: false
EOF
```
Restart the containerd service.
```console
sudo systemctl restart containerd
```
Now, just run a container workload in sandbox and you will get the list of accessed files in `persist_dir`.
Note that NRI plugin can only be called from containerd/CRI. So start a container using `crictl` as below.
```console
sudo tee nginx.yaml <<- EOF
metadata:
name: nginx
image:
image: nginx:latest
log_path: nginx.0.log
linux: {}
EOF
sudo tee pod.yaml <<- EOF
metadata:
name: nginx-sandbox
namespace: default
attempt: 1
uid: hdishd83djaidwnduwk28bcsb
log_directory: /tmp
linux: {}
EOF
crictl run nginx.yaml pod.yaml
```
The result file for the nginx image is `/opt/nri/optimizer/results/library/nginx:latest`.
## Build Nydus Image with Optimizer's Suggestions
Nydus provides a [nydusify](https://github.com/dragonflyoss/nydus/blob/master/docs/nydusify.md) CLI tool to convert OCI images from the source registry or local file system to nydus format and push them to the target registry.
We can install the `nydusify` cli tool from the nydus package.
```console
VERSION=v2.3.0
wget https://github.com/dragonflyoss/nydus/releases/download/$VERSION/nydus-static-$VERSION-linux-amd64.tgz
tar -zxvf nydus-static-$VERSION-linux-amd64.tgz
sudo install -D -m 755 nydus-static/nydusify /usr/local/bin/nydusify
sudo install -D -m 755 nydus-static/nydus-image /usr/local/bin/nydus-image
```
A simple example converts the OCI image nginx to nydus format in RAFS V6.
```console
sudo nydusify convert --source nginx --target sctb512/nginx:nydusv6 --fs-version 6
```
With the `--prefetch-patterns` argument, we can specify the list of files to be written in the front of the nydus image and be prefetched in order when starting a container.
```console
sudo nydusify convert --source nginx --target sctb512/nginx:optimized-nydusv6 --fs-version 6 --prefetch-patterns < /opt/nri/optimizer/results/library/nginx:latest
```
On a host with nydus-snapshotter installed and configured properly, start a container with an optimized nydus image.
```console
sudo nerdctl --snapshotter nydus run --rm --net host -it sctb512/nginx:optimized-nydusv6
```

View File

@ -0,0 +1,137 @@
# Run Dragonfly & Nydus in Kubernetes
We recommend using the Dragonfly P2P data distribution system to further improve the runtime performance of Nydus images.
If you want to deploy Dragonfly and Nydus at the same time through Helm, please refer to the **[Quick Start](https://github.com/dragonflyoss/helm-charts/blob/main/INSTALL.md)**.
# Run Nydus snapshotter in Kubernetes
This document will introduce how to run Nydus snapshotter in Kubernetes cluster, you can use helm to deploy Nydus snapshotter container.
**NOTE:** This document is mainly to allow everyone to quickly deploy and experience Nydus snapshotter in the Kubernetes cluster. You cannot use it as a deployment and configuration solution for the production environment.
## Setup Kubernetes using kind
[kind](https://kind.sigs.k8s.io/) is a tool for running local Kubernetes clusters using Docker container “nodes”.
kind was primarily designed for testing Kubernetes itself, but may be used for local development or CI.
First, we need to prepare a configuration file(`kind-config.yaml`) for kind to specify the devices and files we need to mount to the kind node.
```yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
ipFamily: dual
nodes:
- role: control-plane
image: kindest/node:v1.30.2
extraMounts:
- hostPath: ./containerd-config.toml
containerPath: /etc/containerd/config.toml
- hostPath: /dev/fuse
containerPath: /dev/fuse
```
Next, we also need a config for containerd(`containerd-config.toml`).
**NOTE:** It may be necessary to explain here why `disable_snapshot_annotations` and `discard_unpacked_layers` need to be configured in containerd.
- `disable_snapshot_annotations`: This variable disables to pass additional annotations (image related information) to snapshotters in containerd (default value is `true`). In nydus snapshotter, we need these annotations to pull images. Therefore, we need to set it to `false`.
- `discard_unpacked_layers`: This variable allows GC to remove layers from the content store after successfully unpacking these layers to the snapshotter in containerd (default value is `true`). In nydus snapshotter, we need to preserve layers for demand pulling and sharing even after they are unpacked. Therefore, we need to set it to `false`.
```toml
version = 2
[debug]
level = "debug"
[plugins."io.containerd.grpc.v1.cri".containerd]
discard_unpacked_layers = false
disable_snapshot_annotations = false
snapshotter = "overlayfs"
default_runtime_name = "runc"
[plugins."io.containerd.grpc.v1.cri".containerd.runtimes.runc]
runtime_type = "io.containerd.runc.v2"
[plugins."io.containerd.grpc.v1.cri"]
sandbox_image = "registry.k8s.io/pause:3.6"
```
With these two configuration files, we can create a kind cluster.
```bash
$ kind create cluster --config=kind-config.yaml
```
If everything is fine, kind should have prepared the configuration for us, and we can run the `kubectl` command directly on the host machine, such as:
```bash
$ kubectl get nodes
NAME STATUS ROLES AGE VERSION
kind-control-plane Ready control-plane,master 19m v1.23.4
```
## Use helm to install Nydus snapshotter
Before proceeding, you need to make sure [`helm` is installed](https://helm.sh/docs/intro/quickstart/#install-helm).
First, you need to create a `config-nydus.yaml` for helm to install Nydus-snapshotter.
```yaml
name: nydus-snapshotter
pullPolicy: Always
hostNetwork: true
dragonfly:
enable: false
containerRuntime:
containerd:
enable: true
```
Then clone the Nydus snapshotter helm chart.
```bash
$ git clone https://github.com/dragonflyoss/helm-charts.git
```
Last run helm to create Nydus snapshotter.
```bash
$ cd helm-charts
$ helm install --wait --timeout 10m --dependency-update \
--create-namespace --namespace nydus-system \
-f config-nydus.yaml \
nydus-snapshotter charts/nydus-snapshotter
```
## Run Nydus containers
We can then create a Pod(`nydus-pod.yaml`) config file that runs Nydus image.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: nydus-pod
spec:
containers:
- name: nginx
image: ghcr.io/dragonflyoss/image-service/nginx:nydus-latest
imagePullPolicy: Always
command: ["sh", "-c"]
args:
- tail -f /dev/null
```
Use `kubectl` to create the Pod.
```bash
$ kubectl create -f nydus-pod.yaml
$ kubectl get pods -w
```
The `-w` options will block the console and wait for the changes of the status of the pod. If everything is normal, you can see that the pod will become `Running` after a while.
```bash
NAME READY STATUS RESTARTS AGE
nydus-pod 1/1 Running 0 51s
```

View File

@ -0,0 +1,165 @@
# Setup Nydus Snapshotter by DaemonSet
This document will guide you through the simple steps of setting up and cleaning up the nydus snapshotter in a kubernetes cluster that runs on the host.
## Steps for Setting up Nydus Snapshotter
To begin, let's clone the Nydus Snapshotter repository.
```bash
git clone https://github.com/containerd/nydus-snapshotter
cd nydus-snapshotter
```
We can build the docker image locally. (optional)
```bash
$ export NYDUS_VER=$(curl -s "https://api.github.com/repos/dragonflyoss/nydus/releases/latest" | jq -r .tag_name)
$ make # build snapshotter binaries
$ cp bin/* misc/snapshotter/
$ pushd misc/snapshotter/
$ docker build --build-arg NYDUS_VER="${NYDUS_VER}" -t ghcr.io/containerd/nydus-snapshotter:latest .
$ popd
```
**NOTE:** By default, the nydus snapshotter would use the latest release nydus version. If you want to use a specific version, you can set `NYDUS_VER` on your side.
Next, we can configure access control for nydus snapshotter.
```bash
kubectl apply -f misc/snapshotter/nydus-snapshotter-rbac.yaml
```
Afterward, we can deploy a DaemonSet for nydus snapshotter, according to the kubernetes flavour you're using.
```bash
# Vanilla kubernetes
kubectl apply -f misc/snapshotter/base/nydus-snapshotter.yaml
```
```bash
# k3s
kubectl apply -k misc/snapshotter/overlays/k3s/
```
```bash
# rke2
kubectl apply -k misc/snapshotter/overlays/rke2/
```
Then, we can confirm that nydus snapshotter is running through the DaemonSet.
```bash
$ kubectl get pods -n nydus-system
NAME READY STATUS RESTARTS AGE
nydus-snapshotter-26rf7 1/1 Running 0 18s
```
Finally, we can view the logs in the pod.
```bash
$ kubectl logs nydus-snapshotter-26rf7 -n nydus-system
install nydus snapshotter artifacts
there is no proxy plugin!
Created symlink /etc/systemd/system/multi-user.target.wants/nydus-snapshotter.service → /etc/systemd/system/nydus-snapshotter.service.
```
And we can see the nydus snapshotter service on the host.
```bash
$ systemctl status nydus-snapshotter
● nydus-snapshotter.service - nydus snapshotter
Loaded: loaded (/etc/systemd/system/nydus-snapshotter.service; enabled; vendor preset: enabled)
Drop-In: /etc/systemd/system/nydus-snapshotter.service.d
└─proxy.conf
Active: active (running) since Wed 2024-01-17 16:14:22 UTC; 56s ago
Main PID: 1100169 (containerd-nydu)
Tasks: 11 (limit: 96376)
Memory: 8.6M
CPU: 35ms
CGroup: /system.slice/nydus-snapshotter.service
└─1100169 /opt/nydus/bin/containerd-nydus-grpc --config /etc/nydus/config.toml
Jan 17 16:14:22 worker systemd[1]: Started nydus snapshotter.
Jan 17 16:14:22 worker containerd-nydus-grpc[1100169]: time="2024-01-17T16:14:22.998798369Z" level=info msg="Start nydus-snapshotter. Version: v0.7.0-308-g106a6cb, PID: 1100169, FsDriver: fusedev, DaemonMode: dedicated"
Jan 17 16:14:23 worker containerd-nydus-grpc[1100169]: time="2024-01-17T16:14:23.000186538Z" level=info msg="Run daemons monitor..."
```
**NOTE:** By default, the nydus snapshotter operates as a systemd service. If you prefer to run nydus snapshotter as a standalone process, you can set `ENABLE_SYSTEMD_SERVICE` to `false` in `nydus-snapshotter.yaml`.
## Steps for Cleaning up Nydus Snapshotter
We use `preStop`` hook in the DaemonSet to uninstall nydus snapshotter and roll back the containerd configuration.
```bash
# Vanilla kubernetes
$ kubectl delete -f misc/snapshotter/base/nydus-snapshotter.yaml
```
```bash
# k3s
$ kubectl delete -k misc/snapshotter/overlays/k3s/
```
```bash
# rke2
$ kubectl delete -k misc/snapshotter/overlays/rke2/
```
```bash
$ kubectl delete -f misc/snapshotter/nydus-snapshotter-rbac.yaml
$ systemd restart containerd.service
```
## Customized Setup
As we know, nydus snapshotter supports four filesystem drivers (fs_driver): `fusedev`, `fscache`, `blockdev`, `proxy`. Within the container image, we have included configurations for these snapshotter drivers, as well as the corresponding nydusd configurations. By default, the fusedev driver is enabled in the nydus snapshotter, using the snapshotter configuration [`config-fusedev.toml`](../misc/snapshotter/config-fusedev.toml) and the nydusd configuration [`nydusd-config.fusedev.json`](../misc/snapshotter/nydusd-config.fusedev.json).
### Other filesystem driver with related default configuration
If we want to setup the nydus snapshotter with the default configuration for different fs_driver (such as `proxy`), we can modify the values in the `Configmap` in `nydus-snapshotter.yaml`:
```yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nydus-snapshotter-configs
labels:
app: nydus-snapshotter
namespace: nydus-snapshotter
data:
FS_DRIVER: "proxy"
NYDUSD_DAEMON_MODE: "none"
```
Then we can run the nydus snapshotter enabling `proxy` `fs_driver` with the snapshotter configuration [`config-proxy.toml`](../misc/snapshotter/config-proxy.toml).
**NOTE:** The fs_driver (`blockdev` and `proxy`) do not need nydusd, so they do not need nydusd config.
### Same filesystem with different snapshotter configuration and different nydusd configuration
If we want to setup the nydus snapshotter for the same fs_driver (such as `fusedev`) with different snapshotter configuration and different nydusd configuration, we can enable `ENABLE_CONFIG_FROM_VOLUME` and add the snapshotter configuration [`config.toml`](../misc/snapshotter/config.toml) and nydusd configuration [`nydusd-config.json`](../misc/snapshotter/nydusd-config.fusedev.json) in the `Configmap` in `nydus-snapshotter.yaml`:
```yaml
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nydus-snapshotter-configs
labels:
app: nydus-snapshotter
namespace: nydus-snapshotter
data:
ENABLE_CONFIG_FROM_VOLUME: "true"
config.toml: |-
# The snapshotter config content copied here
nydusd-config.json: |-
# The nydusd config content copied here
```
**NOTE:** We need to set `nydusd_config` to `/etc/nydus/nydusd-config.json` in the `config.toml`, so that snapshotter can find the nydusd configuration from configmap.
### Customized Options
| Options | Type | Default | Comment |
| ----------------------------------- | ------ | ------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| FS_DRIVER | string | "fusedev" | the filesystem driver of snapshotter |
| ENABLE_CONFIG_FROM_VOLUME | bool | false | enabling to use the configurations from volume |
| ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER | bool | false | enabling to skip to set `plugins."io.containerd.grpc.v1.cri".containerd` to `nydus` for runtime specific snapshotter feature in containerd 1.7+ |
| ENABLE_SYSTEMD_SERVICE | bool | true | enabling to run nydus snapshotter as a systemd service |

175
docs/tarfs.md Normal file
View File

@ -0,0 +1,175 @@
# Nydus Tarfs Mode
`Nydus Tarfs Mode` or `Tarfs` is a working mode for Nydus Image, which uses tar files as Nydus data blobs instead of generating native Nydus data blobs.
### Enable Tarfs
`Nydus Tarfs Mode` is still an experiment feature, please edit the snapshotter configuration file to enable the feature:
```
[experimental.tarfs]
enable_tarfs = true
```
### Generate Raw Disk Image for Each Layer of a Container Image
`Tarfs` supports generating a raw disk image for each layer of a container image, which can be directly mounted as EROFS filesystem through loopdev. Please edit the snapshotter configuration file to enable this submode:
```
[experimental.tarfs]
enable_tarfs = true
export_mode = "layer_block"
```
This is an example to generate and verify raw disk image for each layer of a container image:
```
$ containerd-nydus-grpc --config /etc/nydus/config.toml &
$ nerdctl run --snapshotter nydus --rm nginx
# Show mounted rootfs a container
$ mount
/dev/loop17 on /var/lib/containerd/io.containerd.snapshotter.v1.nydus/snapshots/7/mnt type erofs (ro,relatime,user_xattr,acl,cache_strategy=readaround)
# Show loop devices used to mount layers and bootstrap for a container image
$ losetup
NAME SIZELIMIT OFFSET AUTOCLEAR RO BACK-FILE DIO LOG-SEC
/dev/loop11 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/fd9f026c631046113bd492f69761c3ba6042c791c35a60e7c7f3b8f254592daa 0 512
/dev/loop12 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3 0 512
/dev/loop13 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/96576293dd2954ff84251aa0455687c8643358ba1b190ea1818f56b41884bdbd 0 512
/dev/loop14 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/a7c4092be9044bd4eef78f27c95785ef3a9f345d01fd4512bc94ddaaefc359f4 0 512
/dev/loop15 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/e3b6889c89547ec9ba653ab44ed32a99370940d51df956968c0d578dd61ab665 0 512
/dev/loop16 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75 0 512
/dev/loop17 0 0 0 0 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/snapshots/7/fs/image/image.boot 0 512
# Files without suffix are tar files, files with suffix `layer.disk` are raw disk image for container image layers
$ ls -l /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/
total 376800
-rw-r--r-- 1 root root 3584 Aug 30 23:18 055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3
-rw-r--r-- 1 root root 527872 Aug 30 23:18 055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3.layer.disk
-rw-r--r-- 1 root root 77814784 Aug 30 23:18 52d2b7f179e32b4cbd579ee3c4958027988f9a8274850ab0c7c24661e3adaac5
-rw-r--r-- 1 root root 78863360 Aug 30 23:18 52d2b7f179e32b4cbd579ee3c4958027988f9a8274850ab0c7c24661e3adaac5.layer.disk
-rw-r--r-- 1 root root 4608 Aug 30 23:18 96576293dd2954ff84251aa0455687c8643358ba1b190ea1818f56b41884bdbd
-rw-r--r-- 1 root root 528896 Aug 30 23:18 96576293dd2954ff84251aa0455687c8643358ba1b190ea1818f56b41884bdbd.layer.disk
-rw-r--r-- 1 root root 2560 Aug 30 23:18 a7c4092be9044bd4eef78f27c95785ef3a9f345d01fd4512bc94ddaaefc359f4
-rw-r--r-- 1 root root 526848 Aug 30 23:18 a7c4092be9044bd4eef78f27c95785ef3a9f345d01fd4512bc94ddaaefc359f4.layer.disk
-rw-r--r-- 1 root root 7168 Aug 30 23:18 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75
-rw-r--r-- 1 root root 531456 Aug 30 23:18 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.layer.disk
-rw-r--r-- 1 root root 5120 Aug 30 23:18 e3b6889c89547ec9ba653ab44ed32a99370940d51df956968c0d578dd61ab665
-rw-r--r-- 1 root root 529408 Aug 30 23:18 e3b6889c89547ec9ba653ab44ed32a99370940d51df956968c0d578dd61ab665.layer.disk
-rw-r--r-- 1 root root 112968704 Aug 30 23:18 fd9f026c631046113bd492f69761c3ba6042c791c35a60e7c7f3b8f254592daa
-rw-r--r-- 1 root root 113492992 Aug 30 23:18 fd9f026c631046113bd492f69761c3ba6042c791c35a60e7c7f3b8f254592daa.layer.disk
$ file /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3
/var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3: POSIX tar archive
# Mount the raw disk image for a container image layer
$ losetup /dev/loop100 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3.layer.disk
$ mount -t erofs /dev/loop100 ./mnt/
$ mount
tmpfs on /run/user/0 type tmpfs (rw,nosuid,nodev,relatime,size=1544836k,nr_inodes=386209,mode=700,inode64)
/dev/loop17 on /var/lib/containerd/io.containerd.snapshotter.v1.nydus/snapshots/7/mnt type erofs (ro,relatime,user_xattr,acl,cache_strategy=readaround)
/dev/loop100 on /root/ws/nydus-snapshotter.git/mnt type erofs (ro,relatime,user_xattr,acl,cache_strategy=readaround)
```
### Generate Raw Disk Image for a Container Image
`Tarfs` supports generating a raw disk image a container image, which can be directly mounted as EROFS filesystem through loopdev. Please edit the snapshotter configuration file to enable this submode:
```
[experimental.tarfs]
enable_tarfs = true
export_mode = "image_block"
```
This is an example to generate and verify raw disk image for a container image:
```
$ containerd-nydus-grpc --config /etc/nydus/config.toml &
$ nerdctl run --snapshotter nydus --rm nginx
# Files without suffix are tar files, files with suffix `image.disk` are raw disk image for a container image
$ ls -l /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/
total 376320
-rw-r--r-- 1 root root 3584 Aug 30 23:35 055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3
-rw-r--r-- 1 root root 77814784 Aug 30 23:35 52d2b7f179e32b4cbd579ee3c4958027988f9a8274850ab0c7c24661e3adaac5
-rw-r--r-- 1 root root 4608 Aug 30 23:35 96576293dd2954ff84251aa0455687c8643358ba1b190ea1818f56b41884bdbd
-rw-r--r-- 1 root root 2560 Aug 30 23:35 a7c4092be9044bd4eef78f27c95785ef3a9f345d01fd4512bc94ddaaefc359f4
-rw-r--r-- 1 root root 7168 Aug 30 23:35 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75
-rw-r--r-- 1 root root 194518016 Aug 30 23:36 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.image.disk
-rw-r--r-- 1 root root 5120 Aug 30 23:35 e3b6889c89547ec9ba653ab44ed32a99370940d51df956968c0d578dd61ab665
-rw-r--r-- 1 root root 112968704 Aug 30 23:36 fd9f026c631046113bd492f69761c3ba6042c791c35a60e7c7f3b8f254592daa
```
### Generate Raw Disk Image with dm-verity Information
`Tarfs` supports generating raw disk images with dm-verity information, to enable runtime data integrity validation. Please change `export_mode` in snapshotter configuration file to `layer_block_with_verity` or `image_block_with_verity`.
```
[experimental.tarfs]
enable_tarfs = true
export_mode = "image_block_with_verity"
```
This is an example to generate and verify raw disk image for a container image with dm-verity information:
```
$ containerd-nydus-grpc --config /etc/nydus/config.toml &
$ nerdctl run --snapshotter nydus --rm nginx
# Files without suffix are tar files, files with suffix `image.disk` are raw disk image for a container image
$ ls -l /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/
total 388296
-rw-r--r-- 1 root root 3584 Aug 30 23:45 055fa98b43638b67d10c58d41094d99c8696cc34b7a960c7a0cc5d9d152d12b3
-rw-r--r-- 1 root root 77814784 Aug 30 23:46 52d2b7f179e32b4cbd579ee3c4958027988f9a8274850ab0c7c24661e3adaac5
-rw-r--r-- 1 root root 4608 Aug 30 23:45 96576293dd2954ff84251aa0455687c8643358ba1b190ea1818f56b41884bdbd
-rw-r--r-- 1 root root 2560 Aug 30 23:45 a7c4092be9044bd4eef78f27c95785ef3a9f345d01fd4512bc94ddaaefc359f4
-rw-r--r-- 1 root root 7168 Aug 30 23:45 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75
-rw-r--r-- 1 root root 206782464 Aug 30 23:46 da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.image.disk
-rw-r--r-- 1 root root 5120 Aug 30 23:45 e3b6889c89547ec9ba653ab44ed32a99370940d51df956968c0d578dd61ab665
-rw-r--r-- 1 root root 112968704 Aug 30 23:46 fd9f026c631046113bd492f69761c3ba6042c791c35a60e7c7f3b8f254592daa
$ losetup /dev/loop100 /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.image.disk
$ veritysetup open --no-superblock --format=1 -s "" --hash=sha256 --data-block-size=512 --hash-block-size=4096 --data-blocks 379918 --hash-offset 194519040 /dev/loop100 image1 /dev/loop100 8113799aaf9a5d14feca1eadc3b7e6ea98bdaf61e3a2e4a8ef8c24e26a551efd
$ lsblk
loop100 7:100 0 197.2M 0 loop
└─dm-0 252:0 0 185.5M 1 crypt
$ veritysetup status dm-0
/dev/mapper/dm-0 is active and is in use.
type: VERITY
status: verified
hash type: 1
data block: 512
hash block: 4096
hash name: sha256
salt: -
data device: /dev/loop100
data loop: /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.image.disk
size: 379918 sectors
mode: readonly
hash device: /dev/loop100
hash loop: /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/da761d9a302b21dc50767b67d46f737f5072fb4490c525b4a7ae6f18e1dbbf75.image.disk
hash offset: 379920 sectors
root hash: 8113799aaf9a5d14feca1eadc3b7e6ea98bdaf61e3a2e4a8ef8c24e26a551efd
$ mount -t erofs /dev/dm-0 ./mnt/
mount: /root/ws/nydus-snapshotter.git/mnt: WARNING: source write-protected, mounted read-only.
$ ls -l mnt/
total 14
lrwxrwxrwx 1 root root 7 Aug 14 08:00 bin -> usr/bin
drwxr-xr-x 2 root root 27 Jul 15 00:00 boot
drwxr-xr-x 2 root root 27 Aug 14 08:00 dev
drwxr-xr-x 2 root root 184 Aug 16 17:50 docker-entrypoint.d
-rwxrwxr-x 1 root root 1620 Aug 16 17:50 docker-entrypoint.sh
drwxr-xr-x 34 root root 1524 Aug 16 17:50 etc
drwxr-xr-x 2 root root 27 Jul 15 00:00 home
lrwxrwxrwx 1 root root 7 Aug 14 08:00 lib -> usr/lib
lrwxrwxrwx 1 root root 9 Aug 14 08:00 lib32 -> usr/lib32
lrwxrwxrwx 1 root root 9 Aug 14 08:00 lib64 -> usr/lib64
lrwxrwxrwx 1 root root 10 Aug 14 08:00 libx32 -> usr/libx32
drwxr-xr-x 2 root root 27 Aug 14 08:00 media
drwxr-xr-x 2 root root 27 Aug 14 08:00 mnt
drwxr-xr-x 2 root root 27 Aug 14 08:00 opt
drwxr-xr-x 2 root root 27 Jul 15 00:00 proc
drwx------ 2 root root 66 Aug 14 08:00 root
drwxr-xr-x 3 root root 43 Aug 14 08:00 run
lrwxrwxrwx 1 root root 8 Aug 14 08:00 sbin -> usr/sbin
drwxr-xr-x 2 root root 27 Aug 14 08:00 srv
drwxr-xr-x 2 root root 27 Jul 15 00:00 sys
drwxrwxrwt 2 root root 27 Aug 16 17:50 tmp
drwxr-xr-x 14 root root 229 Aug 14 08:00 usr
drwxr-xr-x 11 root root 204 Aug 14 08:00 var
```

View File

@ -1,8 +1,10 @@
package snapshotter
import (
"github.com/containerd/containerd/platforms"
"github.com/containerd/containerd/plugin"
"github.com/containerd/containerd/v2/plugins"
"github.com/containerd/platforms"
"github.com/containerd/plugin"
"github.com/containerd/plugin/registry"
"github.com/pkg/errors"
"github.com/containerd/nydus-snapshotter/config"
@ -10,23 +12,25 @@ import (
)
func init() {
plugin.Register(&plugin.Registration{
Type: plugin.SnapshotPlugin,
registry.Register(&plugin.Registration{
Type: plugins.SnapshotPlugin,
ID: "nydus",
Config: &config.Config{},
Config: &config.SnapshotterConfig{},
InitFn: func(ic *plugin.InitContext) (interface{}, error) {
ic.Meta.Platforms = append(ic.Meta.Platforms, platforms.DefaultSpec())
cfg, ok := ic.Config.(*config.Config)
cfg, ok := ic.Config.(*config.SnapshotterConfig)
if !ok {
return nil, errors.New("invalid nydus snapshotter configuration")
}
if cfg.RootDir == "" {
cfg.RootDir = ic.Root
root := ic.Properties[plugins.PropertyRootDir]
if root == "" {
cfg.Root = root
}
if err := cfg.FillupWithDefaults(); err != nil {
return nil, errors.New("failed to fillup nydus configuration with defaults")
if err := cfg.FillUpWithDefaults(); err != nil {
return nil, errors.New("failed to fill up nydus configuration with defaults")
}
rs, err := snapshot.NewSnapshotter(ic.Context, cfg)

230
go.mod
View File

@ -1,94 +1,186 @@
module github.com/containerd/nydus-snapshotter
go 1.17
go 1.22.0
require (
github.com/KarpelesLab/reflink v0.0.2
github.com/aliyun/aliyun-oss-go-sdk v0.0.0-20190307165228-86c17b95fcd5
github.com/containerd/containerd v1.6.6
github.com/containerd/continuity v0.2.2
github.com/containerd/fifo v1.0.0
github.com/containerd/stargz-snapshotter/estargz v0.11.4
github.com/docker/cli v20.10.0-beta1.0.20201029214301-1d20b15adc38+incompatible
dario.cat/mergo v1.0.1
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6
github.com/KarpelesLab/reflink v1.0.1
github.com/aliyun/aliyun-oss-go-sdk v3.0.2+incompatible
github.com/aws/aws-sdk-go-v2 v1.30.3
github.com/aws/aws-sdk-go-v2/config v1.27.27
github.com/aws/aws-sdk-go-v2/credentials v1.17.27
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.17.8
github.com/aws/aws-sdk-go-v2/service/s3 v1.58.2
github.com/containerd/cgroups/v3 v3.0.3
github.com/containerd/containerd/api v1.8.0
github.com/containerd/containerd/v2 v2.0.2
github.com/containerd/continuity v0.4.4
github.com/containerd/errdefs v1.0.0
github.com/containerd/fifo v1.1.0
github.com/containerd/log v0.1.0
github.com/containerd/nri v0.8.0
github.com/containerd/platforms v1.0.0-rc.1
github.com/containerd/plugin v1.0.0
github.com/containerd/stargz-snapshotter v0.15.2-0.20240709063920-1dac5ef89319
github.com/containerd/stargz-snapshotter/estargz v0.15.2-0.20240709063920-1dac5ef89319
github.com/containers/ocicrypt v1.2.0
github.com/distribution/reference v0.6.0
github.com/docker/cli v27.1.0+incompatible
github.com/freddierice/go-losetup v0.0.0-20220711213114-2a14873012db
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da
github.com/google/go-containerregistry v0.5.1
github.com/hashicorp/go-retryablehttp v0.7.1
github.com/google/go-containerregistry v0.20.1
github.com/gorilla/mux v1.8.1
github.com/hashicorp/go-retryablehttp v0.7.7
github.com/klauspost/compress v1.17.11
github.com/moby/locker v1.0.1
github.com/mohae/deepcopy v0.0.0-20170929034955-c48cc78d4826
github.com/opencontainers/go-digest v1.0.0
github.com/opencontainers/image-spec v1.0.3-0.20211202183452-c5a74bcca799
github.com/opencontainers/image-spec v1.1.0
github.com/opencontainers/runtime-spec v1.2.0
github.com/pelletier/go-toml v1.9.5
github.com/pkg/errors v0.9.1
github.com/prometheus/client_golang v1.11.1
github.com/prometheus/client_model v0.2.0
github.com/prometheus/common v0.30.0
github.com/rs/xid v1.4.0
github.com/sirupsen/logrus v1.8.1
github.com/stretchr/testify v1.7.0
github.com/urfave/cli/v2 v2.3.0
go.etcd.io/bbolt v1.3.6
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c
golang.org/x/sys v0.0.0-20220412211240-33da011f77ad
google.golang.org/grpc v1.43.0
gopkg.in/natefinch/lumberjack.v2 v2.0.0
github.com/prometheus/client_golang v1.20.5
github.com/prometheus/client_model v0.6.1
github.com/rs/xid v1.5.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.10.0
github.com/urfave/cli/v2 v2.27.5
go.etcd.io/bbolt v1.3.11
golang.org/x/exp v0.0.0-20240719175910-8a7402abbf56
golang.org/x/net v0.30.0
golang.org/x/sync v0.8.0
golang.org/x/sys v0.26.0
google.golang.org/grpc v1.67.1
gopkg.in/natefinch/lumberjack.v2 v2.2.1
gotest.tools v2.2.0+incompatible
k8s.io/api v0.22.5
k8s.io/apimachinery v0.22.5
k8s.io/client-go v0.22.5
k8s.io/api v0.31.2
k8s.io/apimachinery v0.31.2
k8s.io/client-go v0.31.2
k8s.io/cri-api v0.31.2
k8s.io/utils v0.0.0-20240711033017-18e509b52bc8
)
require (
github.com/Microsoft/go-winio v0.5.1 // indirect
github.com/Microsoft/hcsshim v0.9.3 // indirect
github.com/baiyubin/aliyun-sts-go-sdk v0.0.0-20180326062324-cfa1a18b161f // indirect
github.com/AdamKorcz/go-118-fuzz-build v0.0.0-20231105174938-2b5cbb29f3e2 // indirect
github.com/Microsoft/go-winio v0.6.2 // indirect
github.com/Microsoft/hcsshim v0.12.9 // indirect
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.6.3 // indirect
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.16.11 // indirect
github.com/aws/aws-sdk-go-v2/internal/configsources v1.3.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.6.15 // indirect
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.0 // indirect
github.com/aws/aws-sdk-go-v2/internal/v4a v1.3.15 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/accept-encoding v1.11.3 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/checksum v1.3.17 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/presigned-url v1.11.17 // indirect
github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.17.15 // indirect
github.com/aws/aws-sdk-go-v2/service/sso v1.22.4 // indirect
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.26.4 // indirect
github.com/aws/aws-sdk-go-v2/service/sts v1.30.3 // indirect
github.com/aws/smithy-go v1.20.3 // indirect
github.com/beorn7/perks v1.0.1 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/containerd/cgroups v1.0.3 // indirect
github.com/containerd/ttrpc v1.1.0 // indirect
github.com/containerd/typeurl v1.0.2 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.0 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/cilium/ebpf v0.11.0 // indirect
github.com/containerd/errdefs/pkg v0.3.0 // indirect
github.com/containerd/ttrpc v1.2.7 // indirect
github.com/containerd/typeurl/v2 v2.2.3 // indirect
github.com/coreos/go-systemd/v22 v22.5.0 // indirect
github.com/cpuguy83/go-md2man/v2 v2.0.5 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/docker/distribution v2.8.1+incompatible // indirect
github.com/docker/docker v20.10.17+incompatible // indirect
github.com/docker/docker-credential-helpers v0.6.3 // indirect
github.com/docker/go-events v0.0.0-20190806004212-e31b211e4f1c // indirect
github.com/go-logr/logr v1.2.2 // indirect
github.com/docker/distribution v2.8.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.7.0 // indirect
github.com/docker/go-units v0.5.0 // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/felixge/httpsnoop v1.0.4 // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
github.com/fxamacker/cbor/v2 v2.7.0 // indirect
github.com/go-jose/go-jose/v4 v4.0.4 // indirect
github.com/go-logr/logr v1.4.2 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.4 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.2 // indirect
github.com/google/go-cmp v0.5.6 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/go-cmp v0.6.0 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/googleapis/gnostic v0.5.5 // indirect
github.com/hashicorp/go-cleanhttp v0.5.1 // indirect
github.com/imdario/mergo v0.3.12 // indirect
github.com/google/uuid v1.6.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/imdario/mergo v0.3.13 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.15.1 // indirect
github.com/matttproud/golang_protobuf_extensions v1.0.2-0.20181231171920-c182affec369 // indirect
github.com/moby/sys/mountinfo v0.5.0 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/miekg/pkcs11 v1.1.1 // indirect
github.com/mitchellh/go-homedir v1.1.0 // indirect
github.com/moby/sys/mountinfo v0.7.2 // indirect
github.com/moby/sys/sequential v0.6.0 // indirect
github.com/moby/sys/signal v0.7.1 // indirect
github.com/moby/sys/user v0.3.0 // indirect
github.com/moby/sys/userns v0.1.0 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
github.com/opencontainers/runtime-tools v0.9.1-0.20221107090550-2e043c6bd626 // indirect
github.com/opencontainers/selinux v1.11.1 // indirect
github.com/pelletier/go-toml/v2 v2.2.3 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/prometheus/procfs v0.7.3 // indirect
github.com/russross/blackfriday/v2 v2.0.1 // indirect
github.com/shurcooL/sanitized_anchor_name v1.0.0 // indirect
github.com/prometheus/common v0.55.0 // indirect
github.com/prometheus/procfs v0.15.1 // indirect
github.com/russross/blackfriday/v2 v2.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/vbatts/tar-split v0.11.2 // indirect
go.opencensus.io v0.23.0 // indirect
golang.org/x/net v0.0.0-20211216030914-fe4d6282115f // indirect
golang.org/x/oauth2 v0.0.0-20210819190943-2bc19b11175f // indirect
golang.org/x/term v0.0.0-20210615171337-6886f2dfbf5b // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/time v0.0.0-20210723032227-1f47c861a9ac // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/genproto v0.0.0-20211208223120-3a66f561d7aa // indirect
google.golang.org/protobuf v1.27.1 // indirect
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect
github.com/stefanberger/go-pkcs11uri v0.0.0-20230803200340-78284954bff6 // indirect
github.com/syndtr/gocapability v0.0.0-20200815063812-42c35b437635 // indirect
github.com/vbatts/tar-split v0.11.5 // indirect
github.com/x448/float16 v0.8.4 // indirect
github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
go.mozilla.org/pkcs7 v0.9.0 // indirect
go.opencensus.io v0.24.0 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.56.0 // indirect
go.opentelemetry.io/otel v1.31.0 // indirect
go.opentelemetry.io/otel/metric v1.31.0 // indirect
go.opentelemetry.io/otel/trace v1.31.0 // indirect
golang.org/x/crypto v0.28.0 // indirect
golang.org/x/mod v0.21.0 // indirect
golang.org/x/oauth2 v0.22.0 // indirect
golang.org/x/term v0.25.0 // indirect
golang.org/x/text v0.19.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20241021214115-324edc3d5d38 // indirect
google.golang.org/protobuf v1.35.1 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
k8s.io/klog/v2 v2.30.0 // indirect
k8s.io/utils v0.0.0-20210930125809-cb0fa318a74b // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.1.2 // indirect
sigs.k8s.io/yaml v1.2.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.130.1 // indirect
k8s.io/kube-openapi v0.0.0-20240228011516-70dd3763d340 // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
sigs.k8s.io/yaml v1.4.0 // indirect
tags.cncf.io/container-device-interface v0.8.0 // indirect
tags.cncf.io/container-device-interface/specs-go v0.8.0 // indirect
)
replace (
cloud.google.com/go => cloud.google.com/go v0.81.0
github.com/opencontainers/image-spec => github.com/opencontainers/image-spec v1.0.2
retract (
v0.11.3
v0.11.2
v0.11.1
v0.11.0
v0.3.0 // retagged: cd604c1b597558ea045a79c4f80a8c780909801b -> 85653575c7dafb6b06548478ee1dc61ac5905d00
)
exclude (
// These dependencies were updated to "master" in some modules we depend on,
// but have no code-changes since their last release. Unfortunately, this also
// causes a ripple effect, forcing all users of the containerd module to also
// update these dependencies to an unrelease / un-tagged version.
//
// Both these dependencies will unlikely do a new release in the near future,
// so exclude these versions so that we can downgrade to the current release.
//
// For additional details, see this PR and links mentioned in that PR:
// https://github.com/kubernetes-sigs/kustomize/pull/5830#issuecomment-2569960859
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2
)

1515
go.sum

File diff suppressed because it is too large Load Diff

70
integration/Dockerfile Normal file
View File

@ -0,0 +1,70 @@
ARG CONTAINERD_VER=2.0.0-rc.3
ARG CONTAINERD_PROJECT=/containerd
ARG RUNC_VER=1.1.4
ARG NYDUS_SNAPSHOTTER_PROJECT=/nydus-snapshotter
ARG DOWNLOADS_MIRROR="https://github.com"
ARG NYDUS_VER=2.3.0
ARG NERDCTL_VER=1.7.6
ARG DELVE_VER=1.23.0
ARG GO_VER=1.22.5-bookworm
FROM golang:$GO_VER AS golang-base
ARG TARGETARCH
ARG CONTAINERD_VER
ARG CONTAINERD_PROJECT
ARG RUNC_VER
ARG NYDUS_SNAPSHOTTER_PROJECT
ARG DOWNLOADS_MIRROR
ARG NYDUS_VER
ARG NERDCTL_VER
ARG DELVE_VER
# RUN echo '\
# deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye main contrib non-free\n\
# deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-updates main contrib non-free\n\
# deb https://mirrors.tuna.tsinghua.edu.cn/debian/ bullseye-backports main contrib non-free\n\
# deb https://mirrors.tuna.tsinghua.edu.cn/debian-security bullseye-security main contrib non-free\n' > /etc/apt/sources.list
RUN apt-get update -qq && apt-get install -qq libbtrfs-dev libseccomp-dev sudo psmisc jq lsof net-tools
RUN go install github.com/go-delve/delve/cmd/dlv@v"$DELVE_VER"
# Install containerd
RUN wget -q "$DOWNLOADS_MIRROR"/containerd/containerd/releases/download/v"$CONTAINERD_VER"/containerd-"$CONTAINERD_VER"-linux-"$TARGETARCH".tar.gz && \
tar xzf containerd-"$CONTAINERD_VER"-linux-"$TARGETARCH".tar.gz && \
install -D -m 755 bin/* /usr/local/bin/
COPY misc/example/containerd-config.toml /etc/containerd/config.toml
# Install runc
RUN wget -q "$DOWNLOADS_MIRROR"/opencontainers/runc/releases/download/v"$RUNC_VER"/runc."$TARGETARCH" && \
install -D -m 755 runc."$TARGETARCH" /usr/local/bin/runc
# Install nydusd nydus-image
RUN wget -q "$DOWNLOADS_MIRROR"/dragonflyoss/nydus/releases/download/v"$NYDUS_VER"/nydus-static-v"$NYDUS_VER"-linux-"$TARGETARCH".tgz && \
tar xzf nydus-static-v"$NYDUS_VER"-linux-"$TARGETARCH".tgz && \
install -D -m 755 nydus-static/nydusd /usr/local/bin/nydusd && \
install -D -m 755 nydus-static/nydus-image /usr/local/bin/nydus-image && \
install -D -m 755 nydus-static/nydusctl /usr/local/bin/nydusctl
# Install nerdctl
RUN wget -q "$DOWNLOADS_MIRROR"/containerd/nerdctl/releases/download/v"$NERDCTL_VER"/nerdctl-"$NERDCTL_VER"-linux-"$TARGETARCH".tar.gz && \
tar xzf nerdctl-"$NERDCTL_VER"-linux-"$TARGETARCH".tar.gz && \
install -D -m 755 nerdctl /usr/local/bin/nerdctl
# Install fscache driver configuration file
COPY misc/snapshotter/nydusd-config.fscache.json /etc/nydus/nydusd-config.fscache.json
COPY misc/snapshotter/nydusd-config-localfs.json /etc/nydus/nydusd-config-localfs.json
COPY misc/snapshotter/config.toml /etc/nydus/config.toml
VOLUME [ "/var/lib" ]
COPY integration/entrypoint.sh /
WORKDIR /nydus-snapshotter
ENV PATH="${PATH}:/usr/local/bin/"
# Prevent git from complaining about ownership
RUN git config --global --add safe.directory /nydus-snapshotter
ENTRYPOINT [ "/bin/bash", "-c", "make install && /entrypoint.sh"]

611
integration/entrypoint.sh Executable file
View File

@ -0,0 +1,611 @@
#!/bin/bash
# Copyright (c) 2022. Nydus Developers. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
set -eEuo pipefail
FSCACHE_NYDUSD_CONFIG=/etc/nydus/nydusd-config.fscache.json
FUSE_NYDUSD_LOCALFS_CONFIG=/etc/nydus/nydusd-config-localfs.json
SNAPSHOTTER_CONFIG=/etc/nydus/config.toml
CONTAINERD_ROOT=/var/lib/containerd/
CONTAINERD_STATUS=/run/containerd/
REMOTE_SNAPSHOTTER_SOCKET=/run/containerd-nydus/containerd-nydus-grpc.sock
REMOTE_SNAPSHOTTER_ROOT=/var/lib/containerd/io.containerd.snapshotter.v1.nydus
CONTAINERD_SOCKET=/run/containerd/containerd.sock
SNAPSHOTTER_SHARED_MNT=${REMOTE_SNAPSHOTTER_ROOT}/mnt
SNAPSHOTTER_CACHE_DIR=${REMOTE_SNAPSHOTTER_ROOT}/cache
JAVA_IMAGE=${JAVA_IMAGE:-ghcr.io/dragonflyoss/image-service/java:nydus-nightly-v6}
WORDPRESS_IMAGE=${WORDPRESS_IMAGE:-ghcr.io/dragonflyoss/image-service/wordpress:nydus-nightly-v6}
TOMCAT_IMAGE=${TOMCAT_IMAGE:-ghcr.io/dragonflyoss/image-service/tomcat:nydus-nightly-v5}
STARGZ_IMAGE=${STARGZ_IMAGE:-ghcr.io/stargz-containers/wordpress:5.9.2-esgz}
REDIS_OCI_IMAGE=${REDIS_OCI_IMAGE:-ghcr.io/stargz-containers/redis:6.2.6-org}
WORDPRESS_OCI_IMAGE=${WORDPRESS_OCI_IMAGE:-ghcr.io/dragonflyoss/image-service/wordpress:latest}
PLUGIN=nydus
RETRYNUM=30
RETRYINTERVAL=1
TIMEOUTSEC=180
GORACE_REPORT="$(pwd)/go_race_report"
export GORACE="log_path=${GORACE_REPORT}"
# trap "{ pause 1000; }" ERR
function detect_go_race {
if [ -n "$(ls -A ${GORACE_REPORT}.* 2>/dev/null)" ]; then
echo "go race detected"
reports=$(ls -A ${GORACE_REPORT}.* 2>/dev/null)
for r in ${reports}; do
cat "$r"
done
exit 1
fi
}
function stop_all_containers {
containers=$(nerdctl ps -q | tr '\n' ' ')
if [[ ${containers} == "" ]]; then
return 0
else
echo "Killing containers ${containers}"
for C in ${containers}; do
nerdctl kill "${C}" || true
nerdctl stop "${C}" || true
nerdctl rm "${C}" || true
done
return 1
fi
}
function pause {
echo "I am going to wait for ${1} seconds only ..."
sleep "${1}"
}
function func_retry {
local SUCCESS=false
for i in $(seq ${RETRYNUM}); do
if "${*}"; then
SUCCESS=true
break
fi
echo "Fail(${i}). Retrying function..."
sleep ${RETRYINTERVAL}
done
if [ "${SUCCESS}" == "true" ]; then
return 0
else
return 1
fi
}
function retry {
local SUCCESS=false
for i in $(seq ${RETRYNUM}); do
if eval "timeout ${TIMEOUTSEC} ${@}"; then
SUCCESS=true
break
fi
echo "Fail(${i}). Retrying..."
sleep ${RETRYINTERVAL}
done
if [ "${SUCCESS}" == "true" ]; then
return 0
else
return 1
fi
}
function can_erofs_ondemand_read {
return 1
# grep 'CONFIG_EROFS_FS_ONDEMAND=[ym]' /usr/src/linux-headers-"$(uname -r)"/.config 1>/dev/null
# echo $?
}
function validate_mnt_number {
expected="${1}"
found=$(mount -t fuse | wc -l)
if [[ $found != "$expected" ]]; then
echo "expecting $expected mountpoints, but found $found"
return 1
else
return 0
fi
}
function set_config_option {
KEY="${1}"
VALUE="${2}"
sed -i "s/\($KEY *= *\).*/\1$VALUE/" "${SNAPSHOTTER_CONFIG}"
}
function set_recover_policy {
policy="${1}"
set_config_option "recover_policy" \"${policy}\"
}
function set_enable_referrer_detect {
set_config_option "enable_referrer_detect" "true"
}
function reboot_containerd {
killall "containerd" || true
killall "containerd-nydus-grpc" || true
# In case nydusd is using cache dir
killall "nydusd" || true
# Let snapshotter shutdown all its services.
sleep 2
# FIXME
echo "umount globally shared mountpoint"
umount_global_shared_mnt
rm -rf "${CONTAINERD_STATUS}"*
rm -rf "${CONTAINERD_ROOT}"*
if [ -f "${REMOTE_SNAPSHOTTER_SOCKET}" ]; then
rm "${REMOTE_SNAPSHOTTER_SOCKET}"
fi
local daemon_mode=${1}
local fs_driver=${2:-fusedev}
local recover_policy=${3:-none}
if [ -d "${REMOTE_SNAPSHOTTER_ROOT:?}/snapshotter/snapshots/" ]; then
umount -t fuse --all
fi
if [[ "${fs_driver}" == fusedev ]]; then
nydusd_config=/etc/nydus/nydusd-config.json
else
nydusd_config="$FSCACHE_NYDUSD_CONFIG"
fi
# Override nydus configuration, this configuration is usually set by each case
if [[ -n ${NYDUS_CONFIG_PATH:-} ]]; then
nydusd_config=${NYDUS_CONFIG_PATH}
fi
# rm -rf "${REMOTE_SNAPSHOTTER_ROOT:?}"/* || fuser -m "${REMOTE_SNAPSHOTTER_ROOT}/mnt" && false
rm -rf "${REMOTE_SNAPSHOTTER_ROOT:?}"/*
set_recover_policy "${recover_policy}"
containerd-nydus-grpc --log-to-stdout \
--daemon-mode "${daemon_mode}" --fs-driver "${fs_driver}" \
--config "${SNAPSHOTTER_CONFIG}" --nydusd-config "${nydusd_config}" &
retry ls "${REMOTE_SNAPSHOTTER_SOCKET}"
containerd --log-level info --config=/etc/containerd/config.toml &
retry ls "${CONTAINERD_SOCKET}"
# Makes sure containerd and containerd-nydus-grpc are up-and-running.
UNIQUE_SUFFIX=$(date +%s%N | shasum | base64 | fold -w 10 | head -1)
retry ctr snapshots --snapshotter="${PLUGIN}" prepare "connectiontest-dummy-${UNIQUE_SUFFIX}" ""
}
function restart_snapshotter {
killall -INT containerd-nydus-grpc
local daemon_mode=$1
}
function umount_global_shared_mnt {
umount "${SNAPSHOTTER_SHARED_MNT}" || true
}
function is_cache_cleared {
# With fscache driver, 2.1 nydusd don't have API to release the cache files.
# Thy locate at directory ${SNAPSHOTTER_CACHE_DIR}/cache
if [[ $(ls -A -p "${SNAPSHOTTER_CACHE_DIR}" | grep -v /) == "" ]]; then
true
else
echo "ERROR: Cache is not cleared"
false
fi
}
function nerdctl_prune_images {
# Wait for containers observation.
sleep 1
func_retry stop_all_containers
nerdctl container prune -f
nerdctl image prune --all -f
nerdctl images
is_cache_cleared
}
function start_single_container_multiple_daemons {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}"
detect_go_race
}
function start_multiple_containers_multiple_daemons {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${TOMCAT_IMAGE}"
nerdctl_prune_images
nerdctl --snapshotter nydus run -d --net none "${TOMCAT_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}"
detect_go_race
}
function start_multiple_containers_shared_daemon {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd shared
nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${TOMCAT_IMAGE}"
detect_go_race
}
function start_single_container_on_stargz {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
killall "containerd-nydus-grpc" || true
sleep 2
containerd-nydus-grpc --enable-stargz --daemon-mode multiple --fs-driver fusedev \
--recover-policy none --log-to-stdout --config-path /etc/nydus/nydusd-config.json &
nerdctl --snapshotter nydus run -d --net none "${STARGZ_IMAGE}"
detect_go_race
}
function start_container_on_oci {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
nerdctl --snapshotter nydus run -d --net none "${REDIS_OCI_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_OCI_IMAGE}"
pause 2
func_retry stop_all_containers
# Deleteing with flag --async as a fuzzer
nerdctl image rm --async --force "${REDIS_OCI_IMAGE}"
nerdctl image rm --force "${WORDPRESS_OCI_IMAGE}"
}
function start_container_with_referrer_detect {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
set_enable_referrer_detect
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_OCI_IMAGE}"
detect_go_race
}
function pull_remove_one_image {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd multiple
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
nerdctl --snapshotter nydus image rm "${JAVA_IMAGE}"
detect_go_race
}
function pull_remove_multiple_images {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}"
# Because nydusd is not started right after image pull.
# Nydusd is started when preparing the writable active snapshot as the
# uppermost layer. So we must create a container to start nydusd.
# Then to test if snapshotter's nydusd daemons management works well
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${TOMCAT_IMAGE}"
nerdctl --snapshotter nydus create --rm --net none "${TOMCAT_IMAGE}"
nerdctl --snapshotter nydus create --rm --net none "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image rm --force "${JAVA_IMAGE}"
nerdctl --snapshotter nydus image rm --force "${WORDPRESS_IMAGE}"
# Deleteing with flag --async as a fuzzer
nerdctl --snapshotter nydus image rm --force --async "${TOMCAT_IMAGE}"
nerdctl --snapshotter nydus image pull "${TOMCAT_IMAGE}"
nerdctl --snapshotter nydus create --net none "${TOMCAT_IMAGE}"
detect_go_race
# TODO: Validate running nydusd number
}
function start_multiple_containers_shared_daemon_fscache {
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd shared fscache
nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}"
nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}"
detect_go_race
}
function kill_snapshotter_and_nydusd_recover {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}"
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
sleep 1
echo "killing nydusd"
killall -9 nydusd || true
echo "killing nydus-snapshotter"
killall -9 containerd-nydus-grpc || true
rm "${REMOTE_SNAPSHOTTER_SOCKET:?}"
containerd-nydus-grpc --config "${SNAPSHOTTER_CONFIG}" \
--daemon-mode "${daemon_mode}" --log-to-stdout --config-path /etc/nydus/nydusd-config.json &
retry ls "${REMOTE_SNAPSHOTTER_SOCKET}"
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
detect_go_race
}
# No restart or failover recover policy. Just let snapshotter start a new nydusd when it refreshes.
function fscache_kill_snapshotter_and_nydusd_recover {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}" fscache
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
sleep 1
echo "killing nydusd"
killall -9 nydusd || true
killall -9 containerd-nydus-grpc || true
sleep 1
rm "${REMOTE_SNAPSHOTTER_SOCKET:?}"
containerd-nydus-grpc --log-to-stdout --config "${SNAPSHOTTER_CONFIG}" \
--daemon-mode "${daemon_mode}" --fs-driver fscache --config-path /etc/nydus/nydusd-config.fscache.json &
retry ls "${REMOTE_SNAPSHOTTER_SOCKET}"
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
# killall -9 nydusd
sleep 0.2
detect_go_race
}
function fscache_kill_nydusd_failover() {
local daemon_mode=shared
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}" fscache failover
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
killall -9 nydusd
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
sleep 1
detect_go_race
}
function only_restart_snapshotter {
local daemon_mode=$1
echo "testing $FUNCNAME ${daemon_mode}"
nerdctl_prune_images
reboot_containerd "${daemon_mode}"
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
echo "killing snapshotter"
killall -9 containerd-nydus-grpc || true
rm "${REMOTE_SNAPSHOTTER_SOCKET:?}"
containerd-nydus-grpc --config "${SNAPSHOTTER_CONFIG}" --daemon-mode \
"${daemon_mode}" --log-to-stdout --config-path /etc/nydus/nydusd-config.json &
retry ls "${REMOTE_SNAPSHOTTER_SOCKET}"
if [[ "${daemon_mode}" == "shared" ]]; then
validate_mnt_number 1
else
validate_mnt_number 2
fi
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
detect_go_race
}
function kill_nydusd_recover_nydusd {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}" fusedev restart
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
pause 1
echo "killing nydusd"
killall -9 nydusd || true
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
detect_go_race
}
function ctr_snapshot_usage {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}" fusedev restart
nerdctl --snapshotter nydus image pull "${WORDPRESS_IMAGE}"
nerdctl --snapshotter nydus image pull "${JAVA_IMAGE}"
c1=$(nerdctl --snapshotter nydus create --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus create --net none "${WORDPRESS_IMAGE}")
pause 1
ctr snapshot --snapshotter nydus ls
ctr snapshot --snapshotter nydus usage
echo "start new containers"
nerdctl --snapshotter nydus start "$c1"
nerdctl --snapshotter nydus start "$c2"
ctr snapshot --snapshotter nydus ls
ctr snapshot --snapshotter nydus usage
detect_go_race
}
function kill_multiple_nydusd_recover_failover {
local daemon_mode=$1
echo "testing $FUNCNAME"
nerdctl_prune_images
reboot_containerd "${daemon_mode}" fusedev failover
c1=$(nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}")
pause 1
nerdctl kill "$c1" || true
nerdctl kill "$c2 " || true
echo "killing nydusd"
killall -9 nydusd || true
echo "start new containers"
c1=$(nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}")
pause 1
nerdctl kill "$c1" || true
nerdctl kill "$c2 " || true
echo "killing nydusd again"
killall -9 nydusd || true
c1=$(nerdctl --snapshotter nydus run -d --net none "${JAVA_IMAGE}")
c2=$(nerdctl --snapshotter nydus run -d --net none "${WORDPRESS_IMAGE}")
detect_go_race
}
# Refer to https://github.com/moby/moby/blob/088afc99e4bf8adb78e29733396182417d67ada2/hack/dind#L28-L38
function enable_nesting_for_cgroup_v2() {
if [ -f /sys/fs/cgroup/cgroup.controllers ]; then
mkdir -p /sys/fs/cgroup/init
xargs -rn1 </sys/fs/cgroup/cgroup.procs >/sys/fs/cgroup/init/cgroup.procs || :
sed -e 's/ / +/g' -e 's/^/-/' </sys/fs/cgroup/cgroup.controllers \
>/sys/fs/cgroup/cgroup.subtree_control
fi
}
enable_nesting_for_cgroup_v2
reboot_containerd multiple
start_single_container_multiple_daemons
start_multiple_containers_multiple_daemons
start_multiple_containers_shared_daemon
pull_remove_one_image
pull_remove_multiple_images shared
pull_remove_multiple_images multiple
# start_single_container_on_stargz
only_restart_snapshotter shared
only_restart_snapshotter multiple
kill_snapshotter_and_nydusd_recover shared
kill_snapshotter_and_nydusd_recover multiple
ctr_snapshot_usage multiple
ctr_snapshot_usage shared
if [[ $(can_erofs_ondemand_read) == 0 ]]; then
kill_multiple_nydusd_recover_failover multiple
kill_multiple_nydusd_recover_failover shared
start_multiple_containers_shared_daemon_fscache
fscache_kill_snapshotter_and_nydusd_recover shared
fscache_kill_nydusd_failover
fi
start_container_on_oci
start_container_with_referrer_detect

View File

@ -0,0 +1,55 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
// constants of nydus snapshotter CLI config
package constant
const (
DaemonModeMultiple string = "multiple"
DaemonModeDedicated string = "dedicated"
DaemonModeShared string = "shared"
DaemonModeNone string = "none"
DaemonModeInvalid string = ""
)
const (
// Mount RAFS filesystem by using EROFS over block devices.
FsDriverBlockdev string = "blockdev"
// Mount RAFS filesystem by using FUSE subsystem
FsDriverFusedev string = "fusedev"
// Mount RAFS filesystem by using fscache/EROFS.
FsDriverFscache string = "fscache"
// Only prepare/supply meta/data blobs, do not mount RAFS filesystem.
FsDriverNodev string = "nodev"
// Relay layer content download operation to other agents.
FsDriverProxy string = "proxy"
)
const (
DefaultDaemonMode string = DaemonModeMultiple
DefaultFsDriver string = FsDriverFusedev
DefaultLogLevel string = "info"
DefaultGCPeriod string = "24h"
DefaultNydusDaemonConfigPath string = "/etc/nydus/nydusd-config.json"
NydusdBinaryName string = "nydusd"
NydusImageBinaryName string = "nydus-image"
DefaultRootDir = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus"
DefaultAddress = "/run/containerd-nydus/containerd-nydus-grpc.sock"
DefaultSystemControllerAddress = "/run/containerd-nydus/system.sock"
// Log rotation
DefaultDaemonRotateLogMaxSize = 100 // 100 megabytes
DefaultRotateLogMaxSize = 200 // 200 megabytes
DefaultRotateLogMaxBackups = 5
DefaultRotateLogMaxAge = 0 // days
DefaultRotateLogLocalTime = true
DefaultRotateLogCompress = true
)

115
internal/flags/flags.go Normal file
View File

@ -0,0 +1,115 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package flags
import (
"github.com/containerd/nydus-snapshotter/internal/constant"
"github.com/urfave/cli/v2"
)
type Args struct {
Address string
NydusdConfigPath string
SnapshotterConfigPath string
RootDir string
NydusdPath string
NydusImagePath string
NydusOverlayFSPath string
DaemonMode string
FsDriver string
LogLevel string
LogToStdout bool
LogToStdoutCount int
PrintVersion bool
}
type Flags struct {
Args *Args
F []cli.Flag
}
func buildFlags(args *Args) []cli.Flag {
return []cli.Flag{
&cli.StringFlag{
Name: "root",
Usage: "directory to store snapshotter data and working states",
Destination: &args.RootDir,
DefaultText: constant.DefaultRootDir,
},
&cli.StringFlag{
Name: "address",
Usage: "remote snapshotter gRPC socket path",
Destination: &args.Address,
DefaultText: constant.DefaultAddress,
},
&cli.StringFlag{
Name: "config",
Usage: "path to nydus-snapshotter configuration (such as: config.toml)",
Destination: &args.SnapshotterConfigPath,
},
&cli.StringFlag{
Name: "nydus-image",
Usage: "path to `nydus-image` binary, default to search in $PATH (such as: /usr/local/bin/nydus-image)",
Destination: &args.NydusImagePath,
},
&cli.StringFlag{
Name: "nydusd",
Usage: "path to `nydusd` binary, default to search in $PATH (such as: /usr/local/bin/nydusd)",
Destination: &args.NydusdPath,
},
&cli.StringFlag{
Name: "nydusd-config",
Aliases: []string{"config-path"},
Usage: "path to nydusd configuration (such as: nydusd-config.json or nydusd-config-v2.toml)",
Destination: &args.NydusdConfigPath,
DefaultText: constant.DefaultNydusDaemonConfigPath,
},
&cli.StringFlag{
Name: "nydus-overlayfs-path",
Usage: "path of nydus-overlayfs or name of binary from $PATH, defaults to 'nydus-overlayfs'",
Destination: &args.NydusOverlayFSPath,
},
&cli.StringFlag{
Name: "daemon-mode",
Usage: "nydusd daemon working mode, possible values: \"dedicated\", \"multiple\", \"shared\" or \"none\". \"multiple\" is an alias of \"dedicated\" and will be deprecated in v1.0",
Destination: &args.DaemonMode,
DefaultText: constant.DaemonModeMultiple,
},
&cli.StringFlag{
Name: "fs-driver",
Usage: "driver to mount RAFS filesystem, possible values: \"fusedev\", \"fscache\"",
Destination: &args.FsDriver,
DefaultText: constant.FsDriverFusedev,
},
&cli.StringFlag{
Name: "log-level",
Usage: "logging level, possible values: \"trace\", \"debug\", \"info\", \"warn\", \"error\"",
Destination: &args.LogLevel,
DefaultText: constant.DefaultLogLevel,
},
&cli.BoolFlag{
Name: "log-to-stdout",
Usage: "print log messages to standard output",
Destination: &args.LogToStdout,
Count: &args.LogToStdoutCount,
},
&cli.BoolFlag{
Name: "version",
Usage: "print version and build information",
Destination: &args.PrintVersion,
},
}
}
func NewFlags() *Flags {
var args Args
return &Flags{
Args: &args,
F: buildFlags(&args),
}
}

View File

@ -4,7 +4,7 @@
* SPDX-License-Identifier: Apache-2.0
*/
package command
package flags
import (
"flag"
@ -17,11 +17,12 @@ func TestNewFlags(t *testing.T) {
set := flag.NewFlagSet("test", 0)
flags := NewFlags()
for _, i := range flags.F {
i.Apply(set)
err := i.Apply(set)
assert.Nil(t, err)
}
err := set.Parse([]string{"--config-path", "/etc/testconfig", "--root", "/root"})
err := set.Parse([]string{"--config-path", "/etc/testconfig", "--root", "/root", "--log-level", "info"})
assert.Nil(t, err)
assert.Equal(t, flags.Args.ConfigPath, "/etc/testconfig")
assert.Equal(t, flags.Args.NydusdConfigPath, "/etc/testconfig")
assert.Equal(t, flags.Args.LogLevel, "info")
assert.Equal(t, flags.Args.RootDir, "/root")
}

View File

@ -1,5 +1,6 @@
/*
* Copyright (c) 2020. Ant Group. All rights reserved.
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
@ -11,7 +12,7 @@ import (
"os"
"path/filepath"
"github.com/containerd/containerd/log"
"github.com/containerd/log"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
lumberjack "gopkg.in/natefinch/lumberjack.v2"
@ -30,8 +31,7 @@ type RotateLogArgs struct {
RotateLogCompress bool
}
func SetUp(logLevel string, logToStdout bool, logDir string,
rootDir string, logRotateArgs *RotateLogArgs) error {
func SetUp(logLevel string, logToStdout bool, logDir string, logRotateArgs *RotateLogArgs) error {
lvl, err := logrus.ParseLevel(logLevel)
if err != nil {
return err
@ -44,9 +44,7 @@ func SetUp(logLevel string, logToStdout bool, logDir string,
if logRotateArgs == nil {
return errors.New("logRotateArgs is needed when logToStdout is false")
}
if len(logDir) == 0 {
logDir = filepath.Join(rootDir, DefaultLogDirName)
}
if err := os.MkdirAll(logDir, 0755); err != nil {
return errors.Wrapf(err, "create log dir %s", logDir)
}

View File

@ -13,7 +13,7 @@ import (
"testing"
"time"
"github.com/containerd/containerd/log"
"github.com/containerd/log"
"github.com/sirupsen/logrus"
"gotest.tools/assert"
)
@ -25,16 +25,20 @@ const (
func GetRotateLogFileNumbers(testLogDir string, suffix string) int {
i := 0
filepath.Walk(testLogDir, func(fname string, fi os.FileInfo, err error) error {
err := filepath.Walk(testLogDir, func(fname string, fi os.FileInfo, _ error) error {
if !fi.IsDir() && strings.HasSuffix(fname, suffix) {
i++
}
return nil
})
if err != nil {
log.L.Fatal("walk path")
}
return i
}
func TestSetUp(t *testing.T) {
// Try to clean previously created test directory.
os.RemoveAll(TestLogDirName)
logRotateArgs := &RotateLogArgs{
@ -46,16 +50,18 @@ func TestSetUp(t *testing.T) {
}
logLevel := logrus.InfoLevel.String()
err := SetUp(logLevel, true, TestLogDirName, TestRootDirName, nil)
err := SetUp(logLevel, true, TestLogDirName, nil)
assert.NilError(t, err, nil)
err = SetUp(logLevel, false, TestLogDirName, TestRootDirName, nil)
err = SetUp(logLevel, false, TestLogDirName, nil)
assert.ErrorContains(t, err, "logRotateArgs is needed when logToStdout is false")
err = SetUp(logLevel, false, TestLogDirName, TestRootDirName, logRotateArgs)
err = SetUp(logLevel, false, TestLogDirName, logRotateArgs)
assert.NilError(t, err)
for i := 0; i < 100000; i++ { // total 9.1MB
log.L.Infof("test log, now: %s", time.Now().Format("2006-01-02 15:04:05"))
}
assert.Equal(t, GetRotateLogFileNumbers(TestLogDirName, "log.gz"), logRotateArgs.RotateLogMaxBackups)
os.RemoveAll(TestLogDirName)
}

View File

@ -1,4 +1,4 @@
## Example to setup and test nydus-snapshoter
## Example to setup and test nydus-snapshotter
The directory holds a few example config files to setup a nydus POC environment that saves its all state files in `/var/lib/containerd-test`, as specified in `containerd-test-config.toml`.
For now it contains following files:
@ -26,8 +26,8 @@ sudo tar xzf cni-plugins-linux-amd64-$CNI_VERSION.tgz -C /opt/cni/bin/
wget https://github.com/kubernetes-sigs/cri-tools/releases/download/$CRICTL_VERSION/crictl-$CRICTL_VERSION-linux-amd64.tar.gz
tar xzf crictl-$CRICTL_VERSION-linux-amd64.tar.gz -C /usr/local/bin/
# install nydus-overlayfs
NYDUS_VER=v$(curl -s "https://api.github.com/repos/dragonflyoss/image-service/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget https://github.com/dragonflyoss/image-service/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz
NYDUS_VER=v$(curl -s "https://api.github.com/repos/dragonflyoss/nydus/releases/latest" | jq -r .tag_name | sed 's/^v//')
wget https://github.com/dragonflyoss/nydus/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz
tar xzf nydus-static-$NYDUS_VER-linux-amd64.tgz
sudo cp nydus-static/nydus-overlayfs /usr/local/sbin/
```

View File

@ -1,28 +0,0 @@
root = "/var/lib/containerd"
state = "/run/containerd"
oom_score = 0
[grpc]
address = "/run/containerd/containerd.sock"
[debug]
level = "debug"
[plugins]
[plugins.cgroups]
no_prometheus = false
[plugins.cri]
[plugins.cri.containerd]
snapshotter = "nydus"
disable_snapshot_annotations = false
[plugins.cri.containerd.runtimes]
[plugins.cri.containerd.runtimes.kata]
runtime_type = "io.containerd.kata.v2"
privileged_without_host_devices = true
[plugins.cri.cni]
bin_dir = "/opt/cni/bin"
conf_dir = "/etc/cni/net.d"
[proxy_plugins]
[proxy_plugins.nydus]
type = "snapshot"
address = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus/containerd-nydus-grpc.sock"

View File

@ -3,9 +3,6 @@ root = "/var/lib/containerd"
state = "/run/containerd"
oom_score = 0
[grpc]
address = "/run/containerd/containerd.sock"
[debug]
level = "debug"
@ -24,5 +21,6 @@ oom_score = 0
[proxy_plugins]
[proxy_plugins.nydus]
type = "snapshot"
address = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus/containerd-nydus-grpc.sock"
type = "snapshot"
address = "/run/containerd-nydus/containerd-nydus-grpc.sock"

View File

@ -24,5 +24,5 @@ oom_score = 0
[proxy_plugins]
[proxy_plugins.nydus]
type = "snapshot"
address = "/var/lib/containerd-test/io.containerd.snapshotter.v1.nydus/containerd-nydus-grpc.sock"
type = "snapshot"
address = "/var/lib/containerd-test/io.containerd.snapshotter.v1.nydus/containerd-nydus-grpc.sock"

View File

@ -0,0 +1,13 @@
# The directory to persist accessed files list for container.
persist_dir = "/opt/nri/optimizer/results"
# Whether to make the csv file human readable.
readable = false
# The path of optimizer server binary.
server_path = "/usr/local/bin/optimizer-server"
# The timeout to kill optimizer server, 0 to disable it.
timeout = 0
# Whether to overwrite the existed persistent files.
overwrite = false
# The events that containerd subscribes to.
# Do not change this element.
events = [ "StartContainer", "StopContainer" ]

View File

@ -0,0 +1,3 @@
[file_prefetch]
# This is used to configure the socket address for the file prefetch.
socket_address = "/run/containerd-nydus/system.sock"

View File

@ -0,0 +1,26 @@
# Copyright 2018-2022 Docker Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
version = 2
[proxy_plugins]
[proxy_plugins.nydus]
type = "snapshot"
address = "/run/containerd-nydus/containerd-nydus-grpc.sock"
[plugins."io.containerd.nri.v1.nri"]
config_file = "/etc/nri/nri.conf"
disable = false
plugin_path = "/opt/nri/plugins"
socket_path = "/var/run/nri.sock"

View File

@ -0,0 +1,5 @@
runtime-endpoint: unix:///run/containerd/containerd.sock
image-endpoint: unix:////run/containerd/containerd.sock
timeout: 2
debug: false
pull-image-on-create: false

18
misc/optimizer/nginx.yaml Normal file
View File

@ -0,0 +1,18 @@
metadata:
name: nginx
image:
image: nginx:1.23.3
mounts:
- host_path: script
container_path: /script
command:
- /script/entrypoint.sh
args:
- /script/file_list.txt
log_path: nginx.0.log
linux: {}

View File

@ -0,0 +1,7 @@
metadata:
name: nginx-sandbox
namespace: default
attempt: 1
uid: hdishd83djaidwnduwk28bcsb
log_directory: /tmp
linux: {}

View File

@ -0,0 +1,20 @@
#!/usr/bin/env bash
path=$1
default_path=file_list_path.txt
if [[ $# -eq 0 ]]; then
path=${default_path}
fi
files=($(cat ${path} | tr "\n" " "))
files_number=${#files[@]}
echo "file number: $files_number"
for file in "${files[@]}"; do
file_size=$(stat -c%s "${file}")
echo "file: ${file} size: ${file_size}"
cat ${file} >/dev/null
done
echo "Read file list done."

View File

@ -0,0 +1,12 @@
/lib/x86_64-linux-gnu/ld-2.31.so
/lib/x86_64-linux-gnu/libc-2.31.so
/lib/x86_64-linux-gnu/libtinfo.so.6.2
/lib/x86_64-linux-gnu/libdl-2.31.so
/lib/x86_64-linux-gnu/libnss_files-2.31.so
/lib/x86_64-linux-gnu/libselinux.so.1
/usr/lib/x86_64-linux-gnu/libpcre2-8.so.0.10.1
/lib/x86_64-linux-gnu/libpthread-2.31.so
/docker-entrypoint.sh
/docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
/docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.d/30-tune-worker-processes.sh

View File

@ -1,22 +1,46 @@
FROM ubuntu:20.04 AS sourcer
FROM alpine:3.17.0 AS base
RUN apt update; apt install --no-install-recommends -y curl wget ca-certificates
RUN export NYDUS_VERSION=$(curl --silent "https://api.github.com/repos/dragonflyoss/image-service/releases/latest" | grep -Po '"tag_name": "\K.*?(?=")'); \
wget https://github.com/dragonflyoss/image-service/releases/download/$NYDUS_VERSION/nydus-static-$NYDUS_VERSION-linux-amd64.tgz; \
tar xzf nydus-static-$NYDUS_VERSION-linux-amd64.tgz
RUN mv nydus-static/* /; mv nydusd-fusedev nydusd
FROM base AS sourcer
ARG TARGETARCH
ARG NYDUS_VER=v2.3.0
FROM ubuntu:20.04
RUN apk add -q --no-cache curl && \
apk add -q --no-cache --upgrade grep && \
curl -fsSL -O https://github.com/dragonflyoss/nydus/releases/download/$NYDUS_VER/nydus-static-$NYDUS_VER-linux-amd64.tgz && \
echo $NYDUS_VER > /.nydus_version && \
tar xzf nydus-static-$NYDUS_VER-linux-amd64.tgz && \
rm nydus-static-$NYDUS_VER-linux-amd64.tgz && \
mv nydus-static/* / \
&& rm -rf /nydus-overlayfs
FROM base AS kubectl-sourcer
ARG TARGETARCH
RUN apk add -q --no-cache curl && \
curl -fsSL -o /usr/bin/kubectl https://dl.k8s.io/release/"$(curl -L -s https://dl.k8s.io/release/stable.txt)"/bin/linux/"$TARGETARCH"/kubectl && \
chmod +x /usr/bin/kubectl
FROM base
ARG DESTINATION=/opt/nydus-artifacts
ARG CONFIG_DESTINATION=${DESTINATION}/etc/nydus
ARG BINARY_DESTINATION=${DESTINATION}/usr/local/bin
ARG SCRIPT_DESTINATION=${DESTINATION}/opt/nydus
WORKDIR /root/
RUN mkdir -p /usr/local/bin/ /etc/nydus/ /var/lib/nydus/cache/ /tmp/blobs/
COPY --from=sourcer /nydusd /nydus-image /usr/local/bin/
COPY containerd-nydus-grpc /usr/local/bin/
COPY nydusd-config.fusedev.json /etc/nydus/config.json
COPY nydusd-config-localfs.json /etc/nydus/localfs.json
RUN apt update && \
apt install --no-install-recommends -y ca-certificates && \
rm -rf /var/cache/apt/* /var/lib/apt/lists/*
COPY entrypoint.sh /
RUN apk add -q --no-cache libc6-compat bash
ENTRYPOINT ["/entrypoint.sh"]
VOLUME /var/lib/containerd/io.containerd.snapshotter.v1.nydus
VOLUME /run/containerd-nydus
COPY --from=sourcer /.nydus_version /.nydus_version
COPY --from=kubectl-sourcer /usr/bin/kubectl /usr/bin/kubectl
RUN mkdir -p ${CONFIG_DESTINATION} ${BINARY_DESTINATION} ${SCRIPT_DESTINATION} /var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache /tmp/blobs/
COPY --from=sourcer /nydus* ${BINARY_DESTINATION}/
COPY --chmod=755 containerd-nydus-grpc nydus-overlayfs ${BINARY_DESTINATION}/
COPY --chmod=755 snapshotter.sh ${SCRIPT_DESTINATION}/snapshotter.sh
COPY nydusd-config.fusedev.json ${CONFIG_DESTINATION}/nydusd-fusedev.json
COPY nydusd-config-localfs.json ${CONFIG_DESTINATION}/nydusd-localfs.json
COPY nydusd-config.fscache.json ${CONFIG_DESTINATION}/nydusd-fscache.json
COPY config.toml ${CONFIG_DESTINATION}/config.toml
COPY nydus-snapshotter.service ${DESTINATION}/etc/systemd/system/nydus-snapshotter.service

View File

@ -0,0 +1,5 @@
resources:
- nydus-snapshotter.yaml
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

View File

@ -0,0 +1,140 @@
---
apiVersion: v1
kind: ConfigMap
metadata:
name: nydus-snapshotter-configs
labels:
app: nydus-snapshotter
namespace: nydus-system
data:
FS_DRIVER: "fusedev"
ENABLE_CONFIG_FROM_VOLUME: "false"
ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER: "false"
ENABLE_SYSTEMD_SERVICE: "true"
---
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nydus-snapshotter
namespace: nydus-system
labels:
app: nydus-snapshotter
spec:
selector:
matchLabels:
app: nydus-snapshotter
updateStrategy:
type: RollingUpdate
rollingUpdate:
maxUnavailable: 1
template:
metadata:
labels:
app: nydus-snapshotter
spec:
serviceAccountName: nydus-snapshotter-sa
hostNetwork: true
hostPID: true
containers:
- name: nydus-snapshotter
image: "ghcr.io/containerd/nydus-snapshotter:latest"
imagePullPolicy: Always
env:
- name: NODE_NAME
valueFrom:
fieldRef:
fieldPath: spec.nodeName
- name: FS_DRIVER
valueFrom:
configMapKeyRef:
name: nydus-snapshotter-configs
key: FS_DRIVER
optional: true
- name: ENABLE_CONFIG_FROM_VOLUME
valueFrom:
configMapKeyRef:
name: nydus-snapshotter-configs
key: ENABLE_CONFIG_FROM_VOLUME
optional: true
- name: ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER
valueFrom:
configMapKeyRef:
name: nydus-snapshotter-configs
key: ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER
optional: true
- name: ENABLE_SYSTEMD_SERVICE
valueFrom:
configMapKeyRef:
name: nydus-snapshotter-configs
key: ENABLE_SYSTEMD_SERVICE
optional: true
lifecycle:
preStop:
exec:
command:
- "bash"
- "-c"
- |
/opt/nydus-artifacts/opt/nydus/snapshotter.sh cleanup
command:
- bash
- -c
- |-
/opt/nydus-artifacts/opt/nydus/snapshotter.sh deploy
volumeMounts:
- name: config-volume
mountPath: "/etc/nydus-snapshotter"
- name: nydus-lib
mountPath: "/var/lib/containerd/io.containerd.snapshotter.v1.nydus"
mountPropagation: Bidirectional
- name: nydus-run
mountPath: "/run/containerd-nydus"
mountPropagation: Bidirectional
- name: nydus-opt
mountPath: "/opt/nydus"
mountPropagation: Bidirectional
- name: nydus-etc
mountPath: "/etc/nydus"
mountPropagation: Bidirectional
- name: containerd-conf
mountPath: "/etc/containerd/"
- name: local-bin
mountPath: "/usr/local/bin/"
- name: etc-systemd-system
mountPath: "/etc/systemd/system/"
securityContext:
privileged: true
volumes:
- name: config-volume
configMap:
name: nydus-snapshotter-configs
optional: true
- name: nydus-run
hostPath:
path: /run/containerd-nydus
type: DirectoryOrCreate
- name: nydus-lib
hostPath:
path: /var/lib/containerd/io.containerd.snapshotter.v1.nydus
type: DirectoryOrCreate
- name: nydus-opt
hostPath:
path: /opt/nydus
type: DirectoryOrCreate
- name: nydus-etc
hostPath:
path: /etc/nydus
type: DirectoryOrCreate
- name: containerd-conf
hostPath:
path: /etc/containerd/
- name: local-bin
hostPath:
path: /usr/local/bin/
- name: etc-systemd-system
hostPath:
path: /etc/systemd/system/

View File

@ -0,0 +1,39 @@
version = 1
# Snapshotter's own home directory where it stores and creates necessary resources
root = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus"
# The snapshotter's GRPC server socket, containerd will connect to plugin on this socket
address = "/run/containerd-nydus/containerd-nydus-grpc.sock"
# No nydusd daemon needed
daemon_mode = "none"
[daemon]
# Use `blockdev` for tarfs
fs_driver = "blockdev"
# Path to nydus-image binary
nydusimage_path = "/usr/local/bin/nydus-image"
[remote]
skip_ssl_verify = true
[snapshot]
# Insert Kata volume information to `Mount.Options`
enable_kata_volume = true
[experimental.tarfs]
# Whether to enable nydus tarfs mode. Tarfs is supported by:
# - The EROFS filesystem driver since Linux 6.4
# - Nydus Image Service release v2.3
enable_tarfs = true
# Mount rafs on host by loopdev and EROFS
mount_tarfs_on_host = false
# Mode to export tarfs images:
# - "none" or "": do not export tarfs
# - "layer_verity_only": only generate disk verity information for a layer blob
# - "image_verity_only": only generate disk verity information for all blobs of an image
# - "layer_block": generate a raw block disk image with tarfs for a layer
# - "image_block": generate a raw block disk image with tarfs for an image
# - "layer_block_with_verity": generate a raw block disk image with tarfs for a layer with dm-verity info
# - "image_block_with_verity": generate a raw block disk image with tarfs for an image with dm-verity info
export_mode = "image_block_with_verity"

View File

@ -0,0 +1,15 @@
version = 1
# Snapshotter's own home directory where it stores and creates necessary resources
root = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus"
# The snapshotter's GRPC server socket, containerd will connect to plugin on this socket
address = "/run/containerd-nydus/containerd-nydus-grpc.sock"
# No nydusd daemon needed
daemon_mode = "none"
[daemon]
# Enable proxy mode
fs_driver = "proxy"
[snapshot]
# Insert Kata volume information to `Mount.Options`
enable_kata_volume = true

View File

@ -0,0 +1,137 @@
version = 1
# Snapshotter's own home directory where it stores and creates necessary resources
root = "/var/lib/containerd/io.containerd.snapshotter.v1.nydus"
# The snapshotter's GRPC server socket, containerd will connect to plugin on this socket
address = "/run/containerd-nydus/containerd-nydus-grpc.sock"
# The nydus daemon mode can be one of the following options: multiple, dedicated, shared, or none.
# If `daemon_mode` option is not specified, the default value is multiple.
daemon_mode = "dedicated"
# Whether snapshotter should try to clean up resources when it is closed
cleanup_on_close = false
[system]
# Snapshotter's debug and trace HTTP server interface
enable = true
# Unix domain socket path where system controller is listening on
address = "/run/containerd-nydus/system.sock"
[system.debug]
# Snapshotter can profile the CPU utilization of each nydusd daemon when it is being started.
# This option specifies the profile duration when nydusd is downloading and uncomproessing data.
daemon_cpu_profile_duration_secs = 5
# Enable by assigning an address, empty indicates pprof server is disabled
pprof_address = ""
[daemon]
# Specify a configuration file for nydusd
nydusd_config = "/etc/nydus/nydusd-config.fusedev.json"
nydusd_path = "/usr/local/bin/nydusd"
nydusimage_path = "/usr/local/bin/nydus-image"
# The fs driver can be one of the following options: fusedev, fscache, blockdev, proxy, or nodev.
# If `fs_driver` option is not specified, the default value is fusedev.
fs_driver = "fusedev"
# How to process when daemon dies: "none", "restart" or "failover"
recover_policy = "restart"
# Nydusd worker thread number to handle FUSE or fscache requests, [0-1024].
# Setting to 0 will use the default configuration of nydusd.
threads_number = 4
# Log rotation size for nydusd, in unit MB(megabytes). (default 100MB)
log_rotation_size = 100
[cgroup]
# Whether to use separate cgroup for nydusd.
enable = true
# The memory limit for nydusd cgroup, which contains all nydusd processes.
# Percentage is supported as well, please ensure it is end with "%".
# The default unit is bytes. Acceptable values include "209715200", "200MiB", "200Mi" and "10%".
memory_limit = ""
[log]
# Print logs to stdout rather than logging files
log_to_stdout = false
# Snapshotter's log level
level = "info"
log_rotation_compress = true
log_rotation_local_time = true
# Max number of days to retain logs
log_rotation_max_age = 7
log_rotation_max_backups = 5
# In unit MB(megabytes)
log_rotation_max_size = 100
[metrics]
# Enable by assigning an address, empty indicates metrics server is disabled
address = ":9110"
[remote]
convert_vpc_registry = false
[remote.mirrors_config]
# Snapshotter will overwrite daemon's mirrors configuration
# if the values loaded from this driectory are not null before starting a daemon.
# Set to "" or an empty directory to disable it.
#dir = "/etc/nydus/certs.d"
[remote.auth]
# Fetch the private registry auth by listening to K8s API server
enable_kubeconfig_keychain = false
# synchronize `kubernetes.io/dockerconfigjson` secret from kubernetes API server with specified kubeconfig (default `$KUBECONFIG` or `~/.kube/config`)
kubeconfig_path = ""
# Fetch the private registry auth as CRI image service proxy
enable_cri_keychain = false
# the target image service when using image proxy
#image_service_address = "/run/containerd/containerd.sock"
[snapshot]
# Let containerd use nydus-overlayfs mount helper
enable_nydus_overlayfs = false
# Path to the nydus-overlayfs binary or name of the binary in $PATH
nydus_overlayfs_path = "nydus-overlayfs"
# Insert Kata Virtual Volume option to `Mount.Options`
enable_kata_volume = false
# Whether to remove resources when a snapshot is removed
sync_remove = false
[cache_manager]
# Disable or enable recyclebin
disable = false
# How long to keep deleted files in recyclebin
gc_period = "24h"
# Directory to host cached files
cache_dir = ""
[image]
public_key_file = ""
validate_signature = false
# The configuraions for features that are not production ready
[experimental]
# Whether to enable stargz support
enable_stargz = false
# Whether to enable referrers support
# The option enables trying to fetch the Nydus image associated with the OCI image and run it.
# Also see https://github.com/opencontainers/distribution-spec/blob/main/spec.md#listing-referrers
enable_referrer_detect = false
# Whether to enable authentication support
# The option enables nydus snapshot to provide backend information to nydusd.
enable_backend_source = false
[experimental.tarfs]
# Whether to enable nydus tarfs mode. Tarfs is supported by:
# - The EROFS filesystem driver since Linux 6.4
# - Nydus Image Service release v2.3
enable_tarfs = false
# Mount rafs on host by loopdev and EROFS
mount_tarfs_on_host = false
# Only enable nydus tarfs mode for images with `tarfs hint` label when true
tarfs_hint = false
# Maximum of concurrence to converting OCIv1 images to tarfs, 0 means default
max_concurrent_proc = 0
# Mode to export tarfs images:
# - "none" or "": do not export tarfs
# - "layer_verity_only": only generate disk verity information for a layer blob
# - "image_verity_only": only generate disk verity information for all blobs of an image
# - "layer_block": generate a raw block disk image with tarfs for a layer
# - "image_block": generate a raw block disk image with tarfs for an image
# - "layer_block_with_verity": generate a raw block disk image with tarfs for a layer with dm-verity info
# - "image_block_with_verity": generate a raw block disk image with tarfs for an image with dm-verity info
export_mode = ""

View File

@ -1,22 +0,0 @@
#! /bin/bash
CONTAINERD_ROOT="${CONTAINERD_ROOT:-/var/lib/containerd/}"
set -eu
BACKEND_TYPE="${BACKEND_TYPE:-config}"
NYDUSD_DAEMON_MODE="${NYDUSD_DAEMON_MODE:-shared}"
if [ "$#" -eq 0 ]; then
containerd-nydus-grpc \
--log-level info \
--nydusd-path /usr/local/bin/nydusd \
--config-path /etc/nydus/${BACKEND_TYPE}.json \
--root ${CONTAINERD_ROOT}/io.containerd.snapshotter.v1.nydus \
--address ${CONTAINERD_ROOT}/io.containerd.snapshotter.v1.nydus/containerd-nydus-grpc.sock \
--enable-nydus-overlayfs \
--daemon-mode ${NYDUSD_DAEMON_MODE} \
--enable-stargz \
--log-to-stdout
fi
exec $@

View File

@ -0,0 +1,34 @@
---
apiVersion: v1
kind: Namespace
metadata:
name: nydus-system
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: nydus-snapshotter-sa
namespace: nydus-system
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: nydus-snapshotter-role
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "patch"]
---
kind: ClusterRoleBinding
apiVersion: rbac.authorization.k8s.io/v1
metadata:
name: nydus-snapshotter-role-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: nydus-snapshotter-role
subjects:
- kind: ServiceAccount
name: nydus-snapshotter-sa
namespace: nydus-system

View File

@ -6,7 +6,7 @@ Before=containerd.service
[Service]
Type=simple
Environment=HOME=/root
ExecStart=/usr/local/bin/containerd-nydus-grpc --fs-driver fscache --daemon-mode shared --config-path /etc/nydus/config.json
ExecStart=/usr/local/bin/containerd-nydus-grpc --config /etc/nydus/config.toml --fs-driver fscache --nydusd-config /etc/nydus/nydusd-config.fscache.json
Restart=always
RestartSec=1
KillMode=process

View File

@ -6,7 +6,7 @@ Before=containerd.service
[Service]
Type=simple
Environment=HOME=/root
ExecStart=/usr/local/bin/containerd-nydus-grpc --config-path /etc/nydus/config.json
ExecStart=/usr/local/bin/containerd-nydus-grpc --config /etc/nydus/config.toml
Restart=always
RestartSec=1
KillMode=process

View File

@ -0,0 +1,18 @@
[Unit]
Description=nydus snapshotter
After=network.target
Before=containerd.service
[Service]
Type=simple
Environment=HOME=/root
ExecStart=/usr/local/bin/containerd-nydus-grpc --config /etc/nydus/config-proxy.toml
Restart=always
RestartSec=1
KillMode=process
OOMScoreAdjust=-999
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

View File

@ -1,25 +1,22 @@
{
"device": {
"backend": {
"type": "localfs",
"config": {
"dir": "/tmp/blobs/"
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/var/lib/nydus/cache"
}
"device": {
"backend": {
"type": "localfs",
"config": {
"dir": "/var/lib/containerd/io.containerd.snapshotter.v1.nydus/cache/"
}
},
"mode": "direct",
"digest_validate": false,
"iostats_files": false,
"enable_xattr": true,
"fs_prefetch": {
"enable": true,
"threads_count": 2
"cache": {
"type": "blobcache"
}
},
"mode": "direct",
"digest_validate": false,
"iostats_files": false,
"enable_xattr": true,
"amplify_io": 1048576,
"fs_prefetch": {
"enable": true,
"threads_count": 2
}
}

View File

@ -2,9 +2,12 @@
"type": "bootstrap",
"config": {
"backend_type": "registry",
"backend_config": {
"scheme": "https"
},
"cache_type": "fscache"
"backend_config": {},
"cache_type": "fscache",
"prefetch_config": {
"enable": true,
"threads_count": 8,
"merging_size": 1048576
}
}
}
}

View File

@ -3,27 +3,24 @@
"backend": {
"type": "registry",
"config": {
"scheme": "https",
"timeout": 5,
"connect_timeout": 5,
"retry_limit": 2
}
},
"cache": {
"type": "blobcache",
"config": {
"work_dir": "/var/lib/nydus/cache"
}
"type": "blobcache"
}
},
"mode": "direct",
"digest_validate": false,
"iostats_files": false,
"enable_xattr": true,
"amplify_io": 1048576,
"fs_prefetch": {
"enable": true,
"threads_count": 8,
"merging_size": 1048576,
"prefetch_all": true
}
}
}

View File

@ -0,0 +1,6 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
patches:
- path: mount_k3s_conf.yaml

View File

@ -0,0 +1,12 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nydus-snapshotter
namespace: nydus-system
spec:
template:
spec:
volumes:
- name: containerd-conf
hostPath:
path: /var/lib/rancher/k3s/agent/etc/containerd/

View File

@ -0,0 +1,6 @@
apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization
resources:
- ../../base
patches:
- path: mount_rke2_conf.yaml

View File

@ -0,0 +1,12 @@
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nydus-snapshotter
namespace: nydus-system
spec:
template:
spec:
volumes:
- name: containerd-conf
hostPath:
path: /var/lib/rancher/rke2/agent/etc/containerd/

View File

@ -0,0 +1,347 @@
#!/usr/bin/env bash
# Copyright (c) 2023. Nydus Developers. All rights reserved.
#
# SPDX-License-Identifier: Apache-2.0
#
set -o errexit
set -o pipefail
set -o nounset
SNAPSHOTTER_ARTIFACTS_DIR="/opt/nydus-artifacts"
# Container runtime config, the default container runtime is containerd
CONTAINER_RUNTIME="${CONTAINER_RUNTIME:-containerd}"
CONTAINER_RUNTIME_CONFIG="/etc/containerd/config.toml"
# Common nydus snapshotter config options
FS_DRIVER="${FS_DRIVER:-fusedev}"
SNAPSHOTTER_GRPC_SOCKET="${SNAPSHOTTER_GRPC_SOCKET:-/run/containerd-nydus/containerd-nydus-grpc.sock}"
# The directory about nydus and nydus snapshotter
NYDUS_CONFIG_DIR="${NYDUS_CONFIG_DIR:-/etc/nydus}"
NYDUS_LIB_DIR="${NYDUS_LIB_DIR:-/var/lib/containerd/io.containerd.snapshotter.v1.nydus}"
NYDUS_BINARY_DIR="${NYDUS_BINARY_DIR:-/usr/local/bin}"
SNAPSHOTTER_SCRYPT_DIR="${SNAPSHOTTER_SCRYPT_DIR:-/opt/nydus}"
# The binary about nydus-snapshotter
SNAPSHOTTER_BINARY="${SNAPSHOTTER_BINARY:-${NYDUS_BINARY_DIR}/containerd-nydus-grpc}"
# The config about nydus snapshotter
SNAPSHOTTER_CONFIG="${SNAPSHOTTER_CONFIG:-${NYDUS_CONFIG_DIR}/config.toml}"
# The systemd service config about nydus snapshotter
SNAPSHOTTER_SERVICE="${SNAPSHOTTER_SERVICE:-/etc/systemd/system/nydus-snapshotter.service}"
# If true, the script would read the config from env.
ENABLE_CONFIG_FROM_VOLUME="${ENABLE_CONFIG_FROM_VOLUME:-false}"
# If true, the script would enable the "runtime specific snapshotter" in containerd config.
ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER="${ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER:-false}"
# If true, the snapshotter would be running as a systemd service
ENABLE_SYSTEMD_SERVICE="${ENABLE_SYSTEMD_SERVICE:-false}"
COMMANDLINE=""
# If we fail for any reason a message will be displayed
die() {
msg="$*"
echo "ERROR: $msg" >&2
exit 1
}
print_usage() {
echo "Usage: $0 [deploy/cleanup]"
}
wait_service_active(){
local wait_time="$1"
local sleep_time="$2"
local service="$3"
nsenter -t 1 -m systemctl restart $service
# Wait for containerd to be running
while [ "$wait_time" -gt 0 ]; do
if nsenter -t 1 -m systemctl is-active --quiet $service; then
echo "$service is running"
return 0
else
sleep "$sleep_time"
wait_time=$((wait_time-sleep_time))
fi
done
echo "Timeout reached. $service may not be running."
nsenter -t 1 -m systemctl status $service
return 1
}
function fs_driver_handler() {
if [ "${ENABLE_CONFIG_FROM_VOLUME}" == "true" ]; then
SNAPSHOTTER_CONFIG="${NYDUS_CONFIG_DIR}/config.toml"
else
case "${FS_DRIVER}" in
fusedev)
sed -i -e "s|nydusd_config = .*|nydusd_config = \"${NYDUS_CONFIG_DIR}/nydusd-fusedev.json\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|fs_driver = .*|fs_driver = \"fusedev\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|daemon_mode = .*|daemon_mode = \"multiple\"|" "${SNAPSHOTTER_CONFIG}"
;;
fscache)
sed -i -e "s|nydusd_config = .*|nydusd_config = \"${NYDUS_CONFIG_DIR}/nydusd-fscache.json\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|fs_driver = .*|fs_driver = \"fscache\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|daemon_mode = .*|daemon_mode = \"multiple\"|" "${SNAPSHOTTER_CONFIG}"
;;
blockdev)
sed -i -e "s|fs_driver = .*|fs_driver = \"blockdev\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|enable_kata_volume = .*|enable_kata_volume = true|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|enable_tarfs = .*|enable_tarfs = true|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|daemon_mode = .*|daemon_mode = \"none\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|export_mode = .*|export_mode = \"layer_block_with_verity\"|" "${SNAPSHOTTER_CONFIG}"
;;
proxy)
sed -i -e "s|fs_driver = .*|fs_driver = \"proxy\"|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|enable_kata_volume = .*|enable_kata_volume = true|" "${SNAPSHOTTER_CONFIG}"
sed -i -e "s|daemon_mode = .*|daemon_mode = \"none\"|" "${SNAPSHOTTER_CONFIG}"
;;
*) die "invalid fs driver ${FS_DRIVER}" ;;
esac
fi
COMMANDLINE+=" --config ${SNAPSHOTTER_CONFIG}"
}
function configure_snapshotter() {
echo "configuring snapshotter"
# Copy the container runtime config to a backup
cp "$CONTAINER_RUNTIME_CONFIG" "$CONTAINER_RUNTIME_CONFIG".bak.nydus
# When trying to edit the config file that is mounted by docker with `sed -i`, the error would happend:
# sed: cannot rename /etc/containerd/config.tomlpmdkIP: Device or resource busy
# The reason is that `sed`` with option `-i` creates new file, and then replaces the old file with the new one,
# which definitely will change the file inode. But the file is mounted by docker, which means we are not allowed to
# change its inode from within docker container.
#
# So we copy the original file to a backup, make changes to the backup, and then overwrite the original file with the backup.
cp "$CONTAINER_RUNTIME_CONFIG" "$CONTAINER_RUNTIME_CONFIG".bak
# Check and add nydus proxy plugin in the config
if grep -q '\[proxy_plugins.nydus\]' "$CONTAINER_RUNTIME_CONFIG".bak; then
echo "the config has configured the nydus proxy plugin!"
else
echo "Not found nydus proxy plugin!"
cat <<EOF >>"$CONTAINER_RUNTIME_CONFIG".bak
[proxy_plugins.nydus]
type = "snapshot"
address = "$SNAPSHOTTER_GRPC_SOCKET"
EOF
fi
if grep -q 'disable_snapshot_annotations' "$CONTAINER_RUNTIME_CONFIG".bak; then
sed -i -e "s|disable_snapshot_annotations = .*|disable_snapshot_annotations = false|" \
"${CONTAINER_RUNTIME_CONFIG}".bak
else
sed -i '/\[plugins\..*\.containerd\]/a\disable_snapshot_annotations = false' \
"${CONTAINER_RUNTIME_CONFIG}".bak
fi
if grep -q 'discard_unpacked_layers' "$CONTAINER_RUNTIME_CONFIG".bak; then
sed -i -e "s|discard_unpacked_layers = .*|discard_unpacked_layers = false|" \
"${CONTAINER_RUNTIME_CONFIG}".bak
else
sed -i '/\[plugins\..*\.containerd\]/a\discard_unpacked_layers = false' \
"${CONTAINER_RUNTIME_CONFIG}".bak
fi
if [ "${ENABLE_RUNTIME_SPECIFIC_SNAPSHOTTER}" == "false" ]; then
sed -i -e '/\[plugins\..*\.containerd\]/,/snapshotter =/ s/snapshotter = "[^"]*"/snapshotter = "nydus"/' "${CONTAINER_RUNTIME_CONFIG}".bak
fi
cat "${CONTAINER_RUNTIME_CONFIG}".bak > "${CONTAINER_RUNTIME_CONFIG}"
}
function install_snapshotter() {
echo "install nydus snapshotter artifacts"
find "${SNAPSHOTTER_ARTIFACTS_DIR}${NYDUS_BINARY_DIR}" -type f -exec install -Dm 755 -t "${NYDUS_BINARY_DIR}" "{}" \;
find "${SNAPSHOTTER_ARTIFACTS_DIR}${NYDUS_CONFIG_DIR}" -type f -exec install -Dm 644 -t "${NYDUS_CONFIG_DIR}" "{}" \;
install -D -m 644 "${SNAPSHOTTER_ARTIFACTS_DIR}${SNAPSHOTTER_SCRYPT_DIR}/snapshotter.sh" "${SNAPSHOTTER_SCRYPT_DIR}/snapshotter.sh"
if [ "${ENABLE_SYSTEMD_SERVICE}" == "true" ]; then
install -D -m 644 "${SNAPSHOTTER_ARTIFACTS_DIR}${SNAPSHOTTER_SERVICE}" "${SNAPSHOTTER_SERVICE}"
fi
if [ "${ENABLE_CONFIG_FROM_VOLUME}" == "true" ]; then
find "/etc/nydus-snapshotter" -type f -exec install -Dm 644 -t "${NYDUS_CONFIG_DIR}" "{}" \;
fi
}
function deploy_snapshotter() {
echo "deploying snapshotter"
install_snapshotter
COMMANDLINE="${SNAPSHOTTER_BINARY}"
fs_driver_handler
configure_snapshotter
if [ "${ENABLE_SYSTEMD_SERVICE}" == "true" ]; then
echo "running snapshotter as systemd service"
sed -i "s|^ExecStart=.*$|ExecStart=$COMMANDLINE|" "${SNAPSHOTTER_SERVICE}"
nsenter -t 1 -m systemctl daemon-reload
nsenter -t 1 -m systemctl enable nydus-snapshotter.service
wait_service_active 30 5 nydus-snapshotter
else
echo "running snapshotter as standalone process"
${COMMANDLINE} &
fi
wait_service_active 30 5 ${CONTAINER_RUNTIME}
}
function remove_images() {
local SNAPSHOTTER="nydus"
local NAMESPACE="k8s.io"
local ctr_args="nsenter -t 1 -m ctr"
if [[ " k3s k3s-agent rke2-agent rke2-server " =~ " ${CONTAINER_RUNTIME} " ]]; then
ctr_args+=" --address /run/k3s/containerd/containerd.sock"
fi
ctr_args+=" --namespace $NAMESPACE"
# List all snapshots for nydus snapshotter
local SNAPSHOTS=$($ctr_args snapshot --snapshotter $SNAPSHOTTER ls | awk 'NR>1 {print $1}')
echo "Images associated with snapshotter $SNAPSHOTTER:"
# Loop through each snapshot and find associated contents
for SNAPSHOT in $SNAPSHOTS; do
local CONTENTS=$($ctr_args content ls | grep $SNAPSHOT | awk '{print $1}')
echo "Snapshot: $SNAPSHOT, Contents: $CONTENTS"
if [ -z "$CONTENTS" ]; then
continue
fi
# Loop through each content and find associated digests of images
for CONTENT in $CONTENTS; do
local DIGESTS=$($ctr_args image ls | grep $CONTENT | awk '{print $3}')
echo "Content: $CONTENT, Digests: $DIGESTS"
if [ -z "$DIGESTS" ]; then
continue
fi
# Loop through each digest and find associated image references
for DIGEST in $DIGESTS; do
local IMAGES=$($ctr_args image ls | grep $DIGEST | awk '{print $1}')
echo "Digest: $DIGEST, Images: $IMAGES"
if [ -z "$IMAGES" ]; then
continue
fi
for IMAGE in $IMAGES; do
# Delete the image
$ctr_args images rm $IMAGE > /dev/null 2>&1 || true
echo "Image $IMAGE removed"
done
done
# Delete the content
$ctr_args content rm $CONTENT > /dev/null 2>&1 || true
echo "content $CONTENT removed"
done
# Delete the snapshot
$ctr_args snapshot --snapshotter $SNAPSHOTTER rm $SNAPSHOT > /dev/null 2>&1 || true
echo "snapshot $SNAPSHOT removed"
done
echo "INFO: Images removed"
}
function cleanup_snapshotter() {
echo "cleaning up snapshotter"
pid=$(ps -ef | grep containerd-nydus-grpc | grep -v grep | awk '{print $1}' || true)
if [ ! -z "$pid" ]; then
remove_images
fi
echo "Recover containerd config"
cat "$CONTAINER_RUNTIME_CONFIG".bak.nydus >"$CONTAINER_RUNTIME_CONFIG"
if [ "${ENABLE_SYSTEMD_SERVICE}" == "true" ]; then
nsenter -t 1 -m systemctl stop nydus-snapshotter.service
nsenter -t 1 -m systemctl disable --now nydus-snapshotter.service
rm -f "${SNAPSHOTTER_SERVICE}" || true
else
kill -9 $pid || true
fi
wait_service_active 30 5 ${CONTAINER_RUNTIME}
echo "Removing nydus-snapshotter artifacts from host"
rm -f "${NYDUS_BINARY_DIR}"/nydus*
rm -rf "${NYDUS_CONFIG_DIR}"/*
rm -rf "${SNAPSHOTTER_SCRYPT_DIR}"/*
rm -rf "${NYDUS_LIB_DIR}"/*
echo "cleaned up snapshotter"
}
function get_container_runtime() {
local runtime=$(kubectl get node ${NODE_NAME} -o jsonpath='{.status.nodeInfo.containerRuntimeVersion}')
if [ "$?" -ne 0 ]; then
die "\"$NODE_NAME\" is an invalid node name"
fi
if echo "$runtime" | grep -qE 'containerd.*-k3s'; then
if nsenter -t 1 -m systemctl is-active --quiet rke2-agent; then
echo "rke2-agent"
elif nsenter -t 1 -m systemctl is-active --quiet rke2-server; then
echo "rke2-server"
elif nsenter -t 1 -m systemctl is-active --quiet k3s-agent; then
echo "k3s-agent"
else
echo "k3s"
fi
elif nsenter -t 1 -m systemctl is-active --quiet k0scontroller; then
echo "k0s-controller"
elif nsenter -t 1 -m systemctl is-active --quiet k0sworker; then
echo "k0s-worker"
else
echo "$runtime" | awk -F '[:]' '{print $1}'
fi
}
function main() {
# script requires that user is root
euid=$(id -u)
if [[ $euid -ne 0 ]]; then
die "This script must be run as root"
fi
CONTAINER_RUNTIME=$(get_container_runtime)
if [[ " k3s k3s-agent rke2-agent rke2-server " =~ " ${CONTAINER_RUNTIME} " ]]; then
CONTAINER_RUNTIME_CONFIG_TMPL="${CONTAINER_RUNTIME_CONFIG}.tmpl"
if [ ! -f "${CONTAINER_RUNTIME_CONFIG_TMPL}" ]; then
cp "${CONTAINER_RUNTIME_CONFIG}" "${CONTAINER_RUNTIME_CONFIG_TMPL}"
fi
CONTAINER_RUNTIME_CONFIG="${CONTAINER_RUNTIME_CONFIG_TMPL}"
elif [ "${CONTAINER_RUNTIME}" == "containerd" ]; then
if [ ! -f "${CONTAINER_RUNTIME_CONFIG}" ]; then
mkdir -p $(dirname ${CONTAINER_RUNTIME_CONFIG}) || true
if [ -x $(command -v ${CONTAINER_RUNTIME}) ]; then
${CONTAINER_RUNTIME} config default > ${CONTAINER_RUNTIME_CONFIG}
else
die "Not able to find an executable ${CONTAINER_RUNTIME} binary to create the default config"
fi
fi
else
die "${CONTAINER_RUNTIME} is a unsupported containe runtime"
fi
action=${1:-}
if [ -z "$action" ]; then
print_usage
die "invalid arguments"
fi
case "$action" in
deploy)
deploy_snapshotter
;;
cleanup)
cleanup_snapshotter
;;
*)
die "invalid arguments"
print_usage
;;
esac
sleep infinity
}
main "$@"

View File

@ -9,7 +9,6 @@ package auth
import (
"encoding/base64"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
@ -42,13 +41,13 @@ const (
var oldDockerConfig = os.Getenv("DOCKER_CONFIG")
func setupDockerConfig() (string, error) {
dir, err := ioutil.TempDir("", "testdocker-")
dir, err := os.MkdirTemp("", "testdocker-")
if err != nil {
return "", err
}
os.Setenv("DOCKER_CONFIG", dir)
err = ioutil.WriteFile(filepath.Join(dir, configFile),
err = os.WriteFile(filepath.Join(dir, configFile),
[]byte(fmt.Sprintf(testConfigFmt, dockerHost, base64.StdEncoding.EncodeToString([]byte(dockerUser+":"+dockerPass)),
extraHost, base64.StdEncoding.EncodeToString([]byte(extraUser+":"+extraPass)))),
0600)

114
pkg/auth/image_proxy.go Normal file
View File

@ -0,0 +1,114 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package auth
import (
"context"
"fmt"
"time"
"github.com/containerd/containerd/v2/defaults"
"github.com/containerd/containerd/v2/pkg/dialer"
"github.com/containerd/containerd/v2/pkg/reference"
"github.com/containerd/log"
"github.com/containerd/stargz-snapshotter/service/keychain/cri"
"github.com/containerd/stargz-snapshotter/service/resolver"
distribution "github.com/distribution/reference"
"github.com/pkg/errors"
"google.golang.org/grpc"
"google.golang.org/grpc/backoff"
"google.golang.org/grpc/credentials/insecure"
runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
)
const DefaultImageServiceAddress = "/run/containerd/containerd.sock"
// Should be concurrency safe
var Credentials []resolver.Credential = make([]resolver.Credential, 0, 8)
// This function is borrowed from stargz
func newCRIConn(criAddr string) (*grpc.ClientConn, error) {
// TODO: make gRPC options configurable from config.toml
backoffConfig := backoff.DefaultConfig
backoffConfig.MaxDelay = 3 * time.Second
connParams := grpc.ConnectParams{
Backoff: backoffConfig,
}
gopts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithConnectParams(connParams),
grpc.WithContextDialer(dialer.ContextDialer),
grpc.WithDefaultCallOptions(grpc.MaxCallRecvMsgSize(defaults.DefaultMaxRecvMsgSize)),
grpc.WithDefaultCallOptions(grpc.MaxCallSendMsgSize(defaults.DefaultMaxSendMsgSize)),
}
return grpc.NewClient(dialer.DialAddress(criAddr), gopts...)
}
// from stargz-snapshotter/cmd/containerd-stargz-grpc/main.go#main
func AddImageProxy(ctx context.Context, rpc *grpc.Server, imageServiceAddress string) {
criAddr := DefaultImageServiceAddress
if imageServiceAddress != "" {
criAddr = imageServiceAddress
}
criCred, criServer := cri.NewCRIKeychain(ctx, func() (runtime.ImageServiceClient, error) {
conn, err := newCRIConn(criAddr)
if err != nil {
return nil, err
}
return runtime.NewImageServiceClient(conn), nil
})
runtime.RegisterImageServiceServer(rpc, criServer)
Credentials = append(Credentials, criCred)
log.G(ctx).WithField("target-image-service", criAddr).Info("setup image proxy keychain")
}
func FromCRI(host, ref string) (*PassKeyChain, error) {
if Credentials == nil {
return nil, errors.New("No Credentials parsers")
}
refSpec, err := parseReference(ref)
if err != nil {
log.L.WithError(err).Error("parse ref failed")
return nil, errors.Wrapf(err, "parse image reference %s", ref)
}
var u, p string
var keychain *PassKeyChain
for _, cred := range Credentials {
if username, secret, err := cred(host, refSpec); err != nil {
return nil, err
} else if !(username == "" && secret == "") {
u = username
p = secret
keychain = &PassKeyChain{
Username: u,
Password: p,
}
break
}
}
return keychain, nil
}
// from stargz-snapshotter/service/keychain/cri/cri.go
func parseReference(ref string) (reference.Spec, error) {
namedRef, err := distribution.ParseDockerRef(ref)
if err != nil {
return reference.Spec{}, fmt.Errorf("failed to parse image reference %q: %w", ref, err)
}
return reference.Parse(namedRef.String())
}

View File

@ -0,0 +1,145 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package auth
import (
"context"
"net"
"path/filepath"
"testing"
"github.com/containerd/containerd/v2/pkg/dialer"
"github.com/stretchr/testify/assert"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials/insecure"
runtime "k8s.io/cri-api/pkg/apis/runtime/v1"
)
type MockImageService struct {
runtime.UnimplementedImageServiceServer
}
func (*MockImageService) PullImage(_ context.Context, _ *runtime.PullImageRequest) (*runtime.PullImageResponse, error) {
return &runtime.PullImageResponse{}, nil
}
func TestFromImagePull(t *testing.T) {
var err error
assertions := assert.New(t)
ctx := context.TODO()
d := t.TempDir()
tagImage := "docker.io/library/busybox:latest"
// should return nil if no proxy
kc, err := FromCRI("docker.io", tagImage)
assertions.Nil(kc)
assertions.NoError(err)
// Mocking the end CRI request consumer.
mockRPC := grpc.NewServer()
mockSocket := filepath.Join(d, "mock.sock")
listenMock, err := net.Listen("unix", mockSocket)
assertions.NoError(err)
// Mocking the end CRI request consumer.
server := &MockImageService{}
runtime.RegisterImageServiceServer(mockRPC, server)
go func() {
err := mockRPC.Serve(listenMock)
assertions.NoError(err)
}()
defer mockRPC.Stop()
// The server of CRI image service proxy.
proxyRPC := grpc.NewServer()
proxySocket := filepath.Join(d, "proxy.sock")
listenProxy, err := net.Listen("unix", proxySocket)
assertions.NoError(err)
AddImageProxy(ctx, proxyRPC, mockSocket)
go func() {
err := proxyRPC.Serve(listenProxy)
assertions.NoError(err)
}()
defer proxyRPC.Stop()
// should return empty kc before pulling
kc, err = FromCRI("docker.io", tagImage)
assertions.Nil(kc)
assertions.NoError(err)
gopts := []grpc.DialOption{
grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(dialer.ContextDialer),
}
conn, err := grpc.NewClient(dialer.DialAddress(proxySocket), gopts...)
assertions.NoError(err)
criClient := runtime.NewImageServiceClient(conn)
_, err = criClient.PullImage(ctx, &runtime.PullImageRequest{
Image: &runtime.ImageSpec{
Image: tagImage,
},
Auth: &runtime.AuthConfig{
Username: "test",
Password: "passwd",
},
})
assertions.NoError(err)
// get correct kc after pulling
kc, err = FromCRI("docker.io", tagImage)
assertions.Equal("test", kc.Username)
assertions.Equal("passwd", kc.Password)
assertions.NoError(err)
// get empty kc with wrong tag
kc, err = FromCRI("docker.io", "docker.io/library/busybox:another")
assertions.Nil(kc)
assertions.NoError(err)
image2 := "ghcr.io/busybox:latest"
_, err = criClient.PullImage(ctx, &runtime.PullImageRequest{
Image: &runtime.ImageSpec{
Image: image2,
},
Auth: &runtime.AuthConfig{
Username: "test_1",
Password: "passwd_1",
},
})
assertions.NoError(err)
// get correct kc after pulling
kc, err = FromCRI("ghcr.io", image2)
assertions.NoError(err)
assertions.Equal(kc.Username, "test_1")
assertions.Equal(kc.Password, "passwd_1")
// should work with digest
digestImage := "docker.io/library/busybox@sha256:7cc4b5aefd1d0cadf8d97d4350462ba51c694ebca145b08d7d41b41acc8db5aa"
_, err = criClient.PullImage(ctx, &runtime.PullImageRequest{
Image: &runtime.ImageSpec{
Image: digestImage,
},
Auth: &runtime.AuthConfig{
Username: "digest",
Password: "dpwd",
},
})
assertions.NoError(err)
// get correct kc after pulling
kc, err = FromCRI("docker.io", digestImage)
assertions.NoError(err)
assertions.Equal("digest", kc.Username)
assertions.Equal("dpwd", kc.Password)
}

View File

@ -13,8 +13,8 @@ import (
"github.com/pkg/errors"
"github.com/containerd/containerd/reference/docker"
"github.com/containerd/nydus-snapshotter/pkg/label"
distribution "github.com/distribution/reference"
"github.com/google/go-containerregistry/pkg/authn"
)
@ -35,7 +35,7 @@ type PassKeyChain struct {
func FromBase64(str string) (PassKeyChain, error) {
decoded, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return emptyPassKeyChain, nil
return emptyPassKeyChain, err
}
pair := strings.Split(string(decoded), sep)
if len(pair) != 2 {
@ -80,35 +80,44 @@ func FromLabels(labels map[string]string) *PassKeyChain {
}
}
// GetRegistryKeyChain get image pull kaychain from (ordered):
// GetRegistryKeyChain get image pull keychain from (ordered):
// 1. username and secrets labels
// 2. docker config
// 3. k8s docker config secret
func GetRegistryKeyChain(host string, labels map[string]string) *PassKeyChain {
// 2. cri request
// 3. docker config
// 4. k8s docker config secret
func GetRegistryKeyChain(host, ref string, labels map[string]string) *PassKeyChain {
kc := FromLabels(labels)
if kc != nil {
return kc
}
// TODO: Handle error
kc, _ = FromCRI(host, ref)
if kc != nil {
return kc
}
kc = FromDockerConfig(host)
if kc != nil {
return kc
}
return FromKubeSecretDockerConfig(host)
}
func GetKeyChainByRef(ref string, labels map[string]string) (*PassKeyChain, error) {
named, err := docker.ParseDockerRef(ref)
named, err := distribution.ParseDockerRef(ref)
if err != nil {
return nil, errors.Wrapf(err, "parse ref %s", ref)
}
host := docker.Domain(named)
keychain := GetRegistryKeyChain(host, labels)
host := distribution.Domain(named)
keychain := GetRegistryKeyChain(host, ref, labels)
return keychain, nil
}
func (kc PassKeyChain) Resolve(target authn.Resource) (authn.Authenticator, error) {
func (kc PassKeyChain) Resolve(_ authn.Resource) (authn.Authenticator, error) {
return authn.FromConfig(kc.toAuthConfig()), nil
}

View File

@ -30,46 +30,47 @@ type KubeSecretListener struct {
informer cache.SharedIndexInformer
}
func InitKubeSecretListener(ctx context.Context, kubeconfigPath string) {
func InitKubeSecretListener(ctx context.Context, kubeconfigPath string) error {
configMu.Lock()
defer configMu.Unlock()
if kubeSecretListener != nil {
return
return nil
}
kubeSecretListener = &KubeSecretListener{
dockerConfigs: make(map[string]*configfile.ConfigFile),
}
go func() {
if kubeconfigPath != "" {
_, err := os.Stat(kubeconfigPath)
if err != nil && !os.IsNotExist(err) {
logrus.WithError(err).Warningf("kubeconfig does not exist, kubeconfigPath %s", kubeconfigPath)
return
} else if err != nil {
logrus.WithError(err).Warningf("failed to detect kubeconfig existence, kubeconfigPath %s", kubeconfigPath)
return
}
if kubeconfigPath != "" {
_, err := os.Stat(kubeconfigPath)
if err != nil && !os.IsNotExist(err) {
logrus.WithError(err).Warningf("kubeconfig does not exist, kubeconfigPath %s", kubeconfigPath)
return err
} else if err != nil {
logrus.WithError(err).Warningf("failed to detect kubeconfig existence, kubeconfigPath %s", kubeconfigPath)
return err
}
loadingRule := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRule.ExplicitPath = kubeconfigPath
clientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRule,
&clientcmd.ConfigOverrides{},
).ClientConfig()
if err != nil {
logrus.WithError(err).Warningf("failed to load kubeconfig")
return
}
clientset, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
logrus.WithError(err).Warningf("failed to create kubernetes client")
return
}
if err := kubeSecretListener.SyncKubeSecrets(ctx, clientset); err != nil {
logrus.WithError(err).Warningf("failed to sync secrets")
return
}
}()
}
loadingRule := clientcmd.NewDefaultClientConfigLoadingRules()
loadingRule.ExplicitPath = kubeconfigPath
clientConfig, err := clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
loadingRule,
&clientcmd.ConfigOverrides{},
).ClientConfig()
if err != nil {
logrus.WithError(err).Warningf("failed to load kubeconfig")
return err
}
clientset, err := kubernetes.NewForConfig(clientConfig)
if err != nil {
logrus.WithError(err).Warningf("failed to create kubernetes client")
return err
}
if err := kubeSecretListener.SyncKubeSecrets(ctx, clientset); err != nil {
logrus.WithError(err).Warningf("failed to sync secrets")
return err
}
return nil
}
func (kubelistener *KubeSecretListener) addDockerConfig(key string, obj interface{}) error {
@ -112,7 +113,7 @@ func (kubelistener *KubeSecretListener) SyncKubeSecrets(ctx context.Context, cli
cache.Indexers{},
)
kubelistener.informer = informer
kubelistener.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
_, err := kubelistener.informer.AddEventHandler(cache.ResourceEventHandlerFuncs{
AddFunc: func(obj interface{}) {
key, err := cache.MetaNamespaceKeyFunc(obj)
if err != nil {
@ -124,7 +125,7 @@ func (kubelistener *KubeSecretListener) SyncKubeSecrets(ctx context.Context, cli
return
}
},
UpdateFunc: func(old, new interface{}) {
UpdateFunc: func(_, new interface{}) {
key, err := cache.MetaNamespaceKeyFunc(new)
if err != nil {
logrus.WithError(err).Errorf("failed to get key for secret from cache")
@ -143,6 +144,9 @@ func (kubelistener *KubeSecretListener) SyncKubeSecrets(ctx context.Context, cli
kubelistener.deleteDockerConfig(key)
}},
)
if err != nil {
return errors.Wrap(err, "add event handler to informer")
}
go kubelistener.informer.Run(ctx.Done())
if !cache.WaitForCacheSync(ctx.Done(), informer.HasSynced) {
return fmt.Errorf("timed out for syncing cache")

View File

@ -13,14 +13,14 @@ import (
const (
testDockerConfigJSONFmt = `
{
"auths": {
"%s": {
"username": "%s",
"password": "%s",
"email": "%s",
"auth": "%s"
}
}
"auths": {
"%s": {
"username": "%s",
"password": "%s",
"email": "%s",
"auth": "%s"
}
}
}
`
dockerConfigKey = "testKey"
@ -33,7 +33,8 @@ func TestGetCredentialsStore(t *testing.T) {
assert := assert.New(t)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
InitKubeSecretListener(ctx, "")
// Host may not has kubeconfig, so ignore the error and continue the test
_ = InitKubeSecretListener(ctx, "")
assert.NotNil(kubeSecretListener)
var obj interface{} = &corev1.Secret{

View File

@ -10,20 +10,27 @@ import (
"context"
"fmt"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/v2/core/content"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)
const (
BackendTypeOSS = "oss"
BackendTypeS3 = "s3"
BackendTypeLocalFS = "localfs"
)
// Backend uploads blobs generated by nydus-image builder to a backend storage such as:
// - oss: A object storage backend, which uses its SDK to upload blob file.
var (
// We always use multipart upload for backend, and limit the
// multipart chunk size to 500MB by default.
MultipartChunkSize int64 = 500 * 1024 * 1024
)
// Backend uploads blobs generated by nydus-image builder to a backend storage.
type Backend interface {
// Push pushes specified blob file to remote storage backend.
Push(ctx context.Context, ra content.ReaderAt, blobDigest digest.Digest) error
Push(ctx context.Context, cs content.Store, desc ocispec.Descriptor) error
// Check checks whether a blob exists in remote storage backend,
// blob exists -> return (blobPath, nil)
// blob not exists -> return ("", err)
@ -36,12 +43,14 @@ type Backend interface {
// registry as per OCI distribution specification. But nydus can also make OSS or
// other storage services as backend storage. Pass config as byte slice here because
// we haven't find a way to represent all backend config at the same time.
func NewBackend(_type string, config []byte) (Backend, error) {
func NewBackend(_type string, config []byte, forcePush bool) (Backend, error) {
switch _type {
case BackendTypeOSS:
return newOSSBackend(config)
return newOSSBackend(config, forcePush)
case BackendTypeS3:
return newS3Backend(config, forcePush)
case BackendTypeLocalFS:
return newLocalFSBackend(config)
return newLocalFSBackend(config, forcePush)
default:
return nil, fmt.Errorf("unsupported backend type %s", _type)
}

View File

@ -14,17 +14,19 @@ import (
"os"
"path"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/v2/core/content"
"github.com/containerd/errdefs"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
type LocalFSBackend struct {
dir string
dir string
forcePush bool
}
func newLocalFSBackend(rawConfig []byte) (*LocalFSBackend, error) {
func newLocalFSBackend(rawConfig []byte, forcePush bool) (*LocalFSBackend, error) {
var configMap map[string]string
if err := json.Unmarshal(rawConfig, &configMap); err != nil {
return nil, errors.Wrap(err, "parse LocalFS storage backend configuration")
@ -36,7 +38,8 @@ func newLocalFSBackend(rawConfig []byte) (*LocalFSBackend, error) {
}
return &LocalFSBackend{
dir: dir,
dir: dir,
forcePush: forcePush,
}, nil
}
@ -44,12 +47,22 @@ func (b *LocalFSBackend) dstPath(blobID string) string {
return path.Join(b.dir, blobID)
}
func (b *LocalFSBackend) Push(ctx context.Context, ra content.ReaderAt, blobDigest digest.Digest) error {
func (b *LocalFSBackend) Push(ctx context.Context, cs content.Store, desc ocispec.Descriptor) error {
if _, err := b.Check(desc.Digest); err == nil && !b.forcePush {
return nil
}
if err := os.MkdirAll(b.dir, 0755); err != nil {
return errors.Wrap(err, "create directory in localfs backend")
}
blobID := blobDigest.Hex()
ra, err := cs.ReaderAt(ctx, desc)
if err != nil {
return errors.Wrap(err, "get reader from content store")
}
defer ra.Close()
blobID := desc.Digest.Hex()
dstPath := b.dstPath(blobID)
dstFile, err := os.Create(dstPath)

View File

@ -14,27 +14,23 @@ import (
"time"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/containerd/containerd/content"
"github.com/containerd/containerd/errdefs"
"github.com/containerd/containerd/v2/core/content"
"github.com/containerd/errdefs"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
"golang.org/x/sync/errgroup"
)
const (
splitPartsCount = 4
// Blob size bigger than 100MB, apply multiparts upload.
multipartsUploadThreshold = 100 * 1024 * 1024
)
type OSSBackend struct {
// OSS storage does not support directory. Therefore add a prefix to each object
// to make it a path-like object.
objectPrefix string
bucket *oss.Bucket
forcePush bool
}
func newOSSBackend(rawConfig []byte) (*OSSBackend, error) {
func newOSSBackend(rawConfig []byte, forcePush bool) (*OSSBackend, error) {
var configMap map[string]string
if err := json.Unmarshal(rawConfig, &configMap); err != nil {
return nil, errors.Wrap(err, "Parse OSS storage backend configuration")
@ -65,30 +61,34 @@ func newOSSBackend(rawConfig []byte) (*OSSBackend, error) {
return &OSSBackend{
objectPrefix: objectPrefix,
bucket: bucket,
forcePush: forcePush,
}, nil
}
// Ported from https://github.com/aliyun/aliyun-oss-go-sdk/blob/c82fb81e272d84f716d3f13c36fe0542a49adfeb/oss/utils.go#L207.
func splitBlobByPartNum(blobSize int64, chunkNum int) ([]oss.FileChunk, error) {
if chunkNum <= 0 || chunkNum > 10000 {
return nil, errors.New("chunkNum invalid")
// Ported from https://github.com/aliyun/aliyun-oss-go-sdk/blob/v2.2.6/oss/utils.go#L259
func splitFileByPartSize(blobSize, chunkSize int64) ([]oss.FileChunk, error) {
if chunkSize <= 0 {
return nil, errors.New("invalid chunk size")
}
if int64(chunkNum) > blobSize {
return nil, errors.New("oss: chunkNum invalid")
var chunkN = blobSize / chunkSize
if chunkN >= 10000 {
return nil, errors.New("too many parts, please increase chunk size")
}
var chunks []oss.FileChunk
var chunk = oss.FileChunk{}
var chunkN = (int64)(chunkNum)
for i := int64(0); i < chunkN; i++ {
chunk.Number = int(i + 1)
chunk.Offset = i * (blobSize / chunkN)
if i == chunkN-1 {
chunk.Size = blobSize/chunkN + blobSize%chunkN
} else {
chunk.Size = blobSize / chunkN
}
chunk.Offset = i * chunkSize
chunk.Size = chunkSize
chunks = append(chunks, chunk)
}
if blobSize%chunkSize > 0 {
chunk.Number = len(chunks) + 1
chunk.Offset = int64(len(chunks)) * chunkSize
chunk.Size = blobSize % chunkSize
chunks = append(chunks, chunk)
}
@ -96,80 +96,70 @@ func splitBlobByPartNum(blobSize int64, chunkNum int) ([]oss.FileChunk, error) {
}
// Upload nydus blob to oss storage backend.
func (b *OSSBackend) push(ctx context.Context, ra content.ReaderAt, blobDigest digest.Digest) error {
blobID := blobDigest.Hex()
func (b *OSSBackend) push(ctx context.Context, cs content.Store, desc ocispec.Descriptor) error {
blobID := desc.Digest.Hex()
blobObjectKey := b.objectPrefix + blobID
ra, err := cs.ReaderAt(ctx, desc)
if err != nil {
return errors.Wrapf(err, "get reader for compression blob %q", desc.Digest)
}
defer ra.Close()
if exist, err := b.bucket.IsObjectExist(blobObjectKey); err != nil {
return errors.Wrap(err, "check object existence")
} else if exist {
} else if exist && !b.forcePush {
return nil
}
blobSize := ra.Size()
var needMultiparts = false
// Blob size bigger than 100MB, apply multiparts upload.
if blobSize >= multipartsUploadThreshold {
needMultiparts = true
chunks, err := splitFileByPartSize(ra.Size(), MultipartChunkSize)
if err != nil {
return errors.Wrap(err, "split blob by part num")
}
if needMultiparts {
chunks, err := splitBlobByPartNum(blobSize, splitPartsCount)
if err != nil {
return errors.Wrap(err, "split blob by part num")
}
imur, err := b.bucket.InitiateMultipartUpload(blobObjectKey)
if err != nil {
return errors.Wrap(err, "initiate multipart upload")
}
partsChan := make(chan oss.UploadPart, len(chunks))
imur, err := b.bucket.InitiateMultipartUpload(blobObjectKey)
if err != nil {
return errors.Wrap(err, "initiate multipart upload")
}
// It always splits the blob into splitPartsCount=4 parts
partsChan := make(chan oss.UploadPart, splitPartsCount)
g := new(errgroup.Group)
for _, chunk := range chunks {
ck := chunk
g.Go(func() error {
p, err := b.bucket.UploadPart(imur, io.NewSectionReader(ra, ck.Offset, ck.Size), ck.Size, ck.Number)
if err != nil {
return errors.Wrap(err, "upload part")
}
partsChan <- p
return nil
})
}
if err := g.Wait(); err != nil {
b.bucket.AbortMultipartUpload(imur)
close(partsChan)
return errors.Wrap(err, "upload parts")
}
g := new(errgroup.Group)
for _, chunk := range chunks {
ck := chunk
g.Go(func() error {
p, err := b.bucket.UploadPart(imur, io.NewSectionReader(ra, ck.Offset, ck.Size), ck.Size, ck.Number)
if err != nil {
return errors.Wrap(err, "upload part")
}
partsChan <- p
return nil
})
}
if err := g.Wait(); err != nil {
_ = b.bucket.AbortMultipartUpload(imur)
close(partsChan)
return errors.Wrap(err, "upload parts")
}
close(partsChan)
var parts []oss.UploadPart
for p := range partsChan {
parts = append(parts, p)
}
parts := make([]oss.UploadPart, 0, 16)
for p := range partsChan {
parts = append(parts, p)
}
if _, err = b.bucket.CompleteMultipartUpload(imur, parts); err != nil {
return errors.Wrap(err, "complete multipart upload")
}
} else {
reader := content.NewReader(ra)
if err := b.bucket.PutObject(blobObjectKey, reader); err != nil {
return errors.Wrap(err, "put blob object")
}
_, err = b.bucket.CompleteMultipartUpload(imur, parts)
if err != nil {
return errors.Wrap(err, "complete multipart upload")
}
return nil
}
func (b *OSSBackend) Push(ctx context.Context, ra content.ReaderAt, blobDigest digest.Digest) error {
func (b *OSSBackend) Push(ctx context.Context, cs content.Store, desc ocispec.Descriptor) error {
backoff := time.Second
for {
err := b.push(ctx, ra, blobDigest)
err := b.push(ctx, cs, desc)
if err != nil {
select {
case <-ctx.Done():

168
pkg/backend/s3.go Normal file
View File

@ -0,0 +1,168 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package backend
import (
"context"
"encoding/json"
"fmt"
"net/http"
"github.com/aws/aws-sdk-go-v2/aws"
awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http"
awscfg "github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/service/s3/types"
"github.com/containerd/containerd/v2/core/content"
"github.com/containerd/errdefs"
"github.com/opencontainers/go-digest"
ocispec "github.com/opencontainers/image-spec/specs-go/v1"
"github.com/pkg/errors"
)
type S3Backend struct {
// objectPrefix is the path prefix of the uploaded object.
// For example, if the blobID which should be uploaded is "abc",
// and the objectPrefix is "path/to/my-registry/", then the object key will be
// "path/to/my-registry/abc".
objectPrefix string
bucketName string
endpointWithScheme string
region string
accessKeySecret string
accessKeyID string
forcePush bool
}
type S3Config struct {
AccessKeyID string `json:"access_key_id,omitempty"`
AccessKeySecret string `json:"access_key_secret,omitempty"`
Endpoint string `json:"endpoint,omitempty"`
Scheme string `json:"scheme,omitempty"`
BucketName string `json:"bucket_name,omitempty"`
Region string `json:"region,omitempty"`
ObjectPrefix string `json:"object_prefix,omitempty"`
}
func newS3Backend(rawConfig []byte, forcePush bool) (*S3Backend, error) {
cfg := &S3Config{}
if err := json.Unmarshal(rawConfig, cfg); err != nil {
return nil, errors.Wrap(err, "parse S3 storage backend configuration")
}
if cfg.Endpoint == "" {
cfg.Endpoint = "s3.amazonaws.com"
}
if cfg.Scheme == "" {
cfg.Scheme = "https"
}
endpointWithScheme := fmt.Sprintf("%s://%s", cfg.Scheme, cfg.Endpoint)
if cfg.BucketName == "" || cfg.Region == "" {
return nil, fmt.Errorf("invalid S3 configuration: missing 'bucket_name' or 'region'")
}
return &S3Backend{
objectPrefix: cfg.ObjectPrefix,
bucketName: cfg.BucketName,
region: cfg.Region,
endpointWithScheme: endpointWithScheme,
accessKeySecret: cfg.AccessKeySecret,
accessKeyID: cfg.AccessKeyID,
forcePush: forcePush,
}, nil
}
func (b *S3Backend) client() (*s3.Client, error) {
s3AWSConfig, err := awscfg.LoadDefaultConfig(context.TODO())
if err != nil {
return nil, errors.Wrap(err, "load default AWS config")
}
client := s3.NewFromConfig(s3AWSConfig, func(o *s3.Options) {
o.BaseEndpoint = &b.endpointWithScheme
o.Region = b.region
o.UsePathStyle = true
if len(b.accessKeySecret) > 0 && len(b.accessKeyID) > 0 {
o.Credentials = credentials.NewStaticCredentialsProvider(b.accessKeyID, b.accessKeySecret, "")
}
o.UsePathStyle = true
})
return client, nil
}
func (b *S3Backend) existObject(ctx context.Context, objectKey string) (bool, error) {
client, err := b.client()
if err != nil {
return false, errors.Wrap(err, "failed to create s3 client")
}
_, err = client.HeadObject(ctx, &s3.HeadObjectInput{
Bucket: &b.bucketName,
Key: &objectKey,
})
if err != nil {
var responseError *awshttp.ResponseError
if errors.As(err, &responseError) && responseError.ResponseError.HTTPStatusCode() == http.StatusNotFound {
return false, nil
}
return false, err
}
return true, nil
}
func (b *S3Backend) Push(ctx context.Context, cs content.Store, desc ocispec.Descriptor) error {
blobID := desc.Digest.Hex()
blobObjectKey := b.objectPrefix + blobID
if exist, err := b.existObject(ctx, blobObjectKey); err != nil {
return errors.Wrap(err, "check object existence")
} else if exist && !b.forcePush {
return nil
}
ra, err := cs.ReaderAt(ctx, desc)
if err != nil {
return errors.Wrap(err, "get reader from content store")
}
defer ra.Close()
reader := content.NewReader(ra)
client, err := b.client()
if err != nil {
return errors.Wrap(err, "failed to create s3 client")
}
uploader := manager.NewUploader(client, func(u *manager.Uploader) {
u.PartSize = MultipartChunkSize
})
if _, err := uploader.Upload(ctx, &s3.PutObjectInput{
Bucket: aws.String(b.bucketName),
Key: aws.String(blobObjectKey),
Body: reader,
ChecksumAlgorithm: types.ChecksumAlgorithmCrc32,
}); err != nil {
return errors.Wrap(err, "push blob to s3 backend")
}
return nil
}
func (b *S3Backend) Check(blobDigest digest.Digest) (string, error) {
blobID := blobDigest.Hex()
objectKey := b.objectPrefix + blobDigest.Hex()
if exist, err := b.existObject(context.Background(), objectKey); err != nil {
return "", err
} else if exist {
return blobID, nil
}
return "", errdefs.ErrNotFound
}
func (b *S3Backend) Type() string {
return BackendTypeS3
}

61
pkg/backend/s3_test.go Normal file
View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package backend
import (
"reflect"
"testing"
)
func Test_newS3Backend(t *testing.T) {
type args struct {
rawConfig []byte
}
tests := []struct {
name string
args args
want *S3Backend
wantErr bool
}{
{
name: "test1, no error",
args: args{
rawConfig: []byte(`{
"endpoint": "localhost:9000",
"scheme": "http",
"bucket_name": "nydus",
"region": "us-east-1",
"object_prefix": "path/to/my-registry/",
"access_key_id": "minio",
"access_key_secret": "minio123"
}`),
},
want: &S3Backend{
objectPrefix: "path/to/my-registry/",
bucketName: "nydus",
endpointWithScheme: "http://localhost:9000",
region: "us-east-1",
accessKeySecret: "minio123",
accessKeyID: "minio",
},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := newS3Backend(tt.args.rawConfig, false)
if (err != nil) != tt.wantErr {
t.Errorf("newS3Backend() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("newS3Backend() = %+#v\nwant %+#v\n\n", got, tt.want)
}
})
}
}

13
pkg/cache/db.go vendored
View File

@ -1,13 +0,0 @@
package cache
import (
"github.com/containerd/nydus-snapshotter/pkg/store"
)
type DB interface {
AddSnapshot(imageID string, blobs []string) error
DelSnapshot(imageID string) error
GC(delFunc func(blob string) error) ([]string, error)
}
var _ DB = &store.CacheStore{}

132
pkg/cache/manager.go vendored
View File

@ -1,29 +1,46 @@
/*
* Copyright (c) 2022. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package cache
import (
"context"
"os"
"path"
"time"
"github.com/containerd/containerd/log"
"github.com/containerd/nydus-snapshotter/config"
"github.com/containerd/nydus-snapshotter/pkg/store"
"github.com/pkg/errors"
"github.com/containerd/containerd/v2/core/snapshots"
"github.com/containerd/continuity/fs"
"github.com/containerd/log"
"github.com/containerd/nydus-snapshotter/pkg/store"
)
const (
imageDiskFileSuffix = ".image.disk"
layerDiskFileSuffix = ".layer.disk"
chunkMapFileSuffix = ".chunk_map"
metaFileSuffix = ".blob.meta"
// Blob cache is suffixed after nydus v2.1
dataFileSuffix = ".blob.data"
)
// Disk cache manager for fusedev.
type Manager struct {
db DB
store *Store
cacheDir string
period time.Duration
eventCh chan struct{}
fsDriver string
}
type Opt struct {
Disabled bool
CacheDir string
Period time.Duration
Database *store.Database
FsDriver string
}
func NewManager(opt Opt) (*Manager, error) {
@ -32,32 +49,13 @@ func NewManager(opt Opt) (*Manager, error) {
return nil, errors.Wrapf(err, "failed to create cache dir %s", opt.CacheDir)
}
db, err := store.NewCacheStore(opt.Database)
if err != nil {
return nil, err
}
s := NewStore(opt.CacheDir)
eventCh := make(chan struct{})
m := &Manager{
db: db,
store: s,
cacheDir: opt.CacheDir,
period: opt.Period,
eventCh: eventCh,
fsDriver: opt.FsDriver,
}
// For fscache backend, the cache is maintained by the kernel fscache module,
// so here we ignore gc for now, and in the future we need another design
// to remove the cache.
if opt.FsDriver == config.FsDriverFscache {
return m, nil
}
go m.runGC()
log.L.Info("gc goroutine start...")
return m, nil
}
@ -65,44 +63,60 @@ func (m *Manager) CacheDir() string {
return m.cacheDir
}
func (m *Manager) SchedGC() {
if m.fsDriver == config.FsDriverFscache {
return
// Report each blob disk usage
// TODO: For fscache cache files, the cache files are managed by nydusd and Linux kernel
// We don't know how it manages cache files. A method to address this is to query nydusd.
// So we can't report cache usage in the case of fscache now
func (m *Manager) CacheUsage(ctx context.Context, blobID string) (snapshots.Usage, error) {
var usage snapshots.Usage
blobCachePath := path.Join(m.cacheDir, blobID)
blobChunkMap := path.Join(m.cacheDir, blobID+chunkMapFileSuffix)
// For backward compatibility
blobCacheSuffixedPath := path.Join(m.cacheDir, blobID+dataFileSuffix)
blobChunkMapSuffixedPath := path.Join(m.cacheDir, blobID+dataFileSuffix+chunkMapFileSuffix)
blobMeta := path.Join(m.cacheDir, blobID+metaFileSuffix)
imageDisk := path.Join(m.cacheDir, blobID+imageDiskFileSuffix)
layerDisk := path.Join(m.cacheDir, blobID+layerDiskFileSuffix)
stuffs := []string{blobCachePath, blobChunkMap, blobCacheSuffixedPath, blobChunkMapSuffixedPath, blobMeta, imageDisk, layerDisk}
for _, f := range stuffs {
du, err := fs.DiskUsage(ctx, f)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.L.Debugf("Cache %s does not exist", f)
continue
}
return snapshots.Usage{}, err
}
usage.Add(snapshots.Usage(du))
}
m.eventCh <- struct{}{}
return usage, nil
}
func (m *Manager) runGC() {
tick := time.NewTicker(m.period)
defer tick.Stop()
for {
select {
case <-m.eventCh:
if err := m.gc(); err != nil {
log.L.Infof("[event] cache gc err, %v", err)
}
tick.Reset(m.period)
case <-tick.C:
if err := m.gc(); err != nil {
log.L.Infof("[tick] cache gc err, %v", err)
func (m *Manager) RemoveBlobCache(blobID string) error {
blobCachePath := path.Join(m.cacheDir, blobID)
blobChunkMap := path.Join(m.cacheDir, blobID+chunkMapFileSuffix)
blobCacheSuffixedPath := path.Join(m.cacheDir, blobID+dataFileSuffix)
blobChunkMapSuffixedPath := path.Join(m.cacheDir, blobID+dataFileSuffix+chunkMapFileSuffix)
blobMeta := path.Join(m.cacheDir, blobID+metaFileSuffix)
imageDisk := path.Join(m.cacheDir, blobID+imageDiskFileSuffix)
layerDisk := path.Join(m.cacheDir, blobID+layerDiskFileSuffix)
// NOTE: Delete chunk bitmap file before data blob
stuffs := []string{blobChunkMap, blobChunkMapSuffixedPath, blobMeta, blobCachePath, blobCacheSuffixedPath, imageDisk, layerDisk}
for _, f := range stuffs {
err := os.Remove(f)
if err != nil {
if errors.Is(err, os.ErrNotExist) {
log.L.Debugf("file %s doest not exist.", f)
continue
}
return err
}
}
}
func (m *Manager) gc() error {
delBlobs, err := m.db.GC(m.store.DelBlob)
if err != nil {
return errors.Wrapf(err, "cache gc err")
}
log.L.Debugf("remove %d unused blobs successfully", len(delBlobs))
return nil
}
func (m *Manager) AddSnapshot(imageID string, blobs []string) error {
return m.db.AddSnapshot(imageID, blobs)
}
func (m *Manager) DelSnapshot(imageID string) error {
return m.db.DelSnapshot(imageID)
}

51
pkg/cache/store.go vendored
View File

@ -1,51 +0,0 @@
package cache
import (
"os"
"path/filepath"
"github.com/pkg/errors"
)
const (
chunkMapFileSuffix = ".chunk_map"
metaFileSuffix = ".blob.meta"
)
type Store struct {
cacheDir string
}
func NewStore(cacheDir string) *Store {
return &Store{cacheDir: cacheDir}
}
func (cs *Store) DelBlob(blob string) error {
blobPath := cs.blobPath(blob)
// Remove the blob chunkmap file named $blob_id.chunk_map first.
chunkMapPath := blobPath + chunkMapFileSuffix
if err := os.Remove(chunkMapPath); err != nil {
// Older versions of nydusd do not support chunkmap, and there
// is no chunkmap file generation, so just ignore the error.
if !os.IsNotExist(err) {
return errors.Wrapf(err, "remove blob chunkmap %v err", chunkMapPath)
}
}
// Then remove the blob file named $blob_id.
if err := os.Remove(blobPath); err != nil {
return errors.Wrapf(err, "remove blob %v err", blobPath)
}
metaPath := blobPath + metaFileSuffix
if err := os.Remove(metaPath); err != nil {
return errors.Wrapf(err, "remove blob meta file %v err", metaPath)
}
return nil
}
func (cs *Store) blobPath(blob string) string {
return filepath.Join(cs.cacheDir, blob)
}

61
pkg/cgroup/cgroup.go Normal file
View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2023. Nydus Developers. All rights reserved.
*
* SPDX-License-Identifier: Apache-2.0
*/
package cgroup
import (
"errors"
"github.com/containerd/cgroups/v3"
v1 "github.com/containerd/nydus-snapshotter/pkg/cgroup/v1"
v2 "github.com/containerd/nydus-snapshotter/pkg/cgroup/v2"
)
const (
defaultSlice = "system.slice"
)
var (
ErrCgroupNotSupported = errors.New("cgroups: cgroup not supported")
)
type Config struct {
MemoryLimitInBytes int64
}
type DaemonCgroup interface {
// Delete the current cgroup.
Delete() error
// Add a process to current cgroup.
AddProc(pid int) error
}
func createCgroup(name string, config Config) (DaemonCgroup, error) {
if cgroups.Mode() == cgroups.Unified {
return v2.NewCgroup(defaultSlice, name, config.MemoryLimitInBytes)
}
return v1.NewCgroup(defaultSlice, name, config.MemoryLimitInBytes)
}
func supported() bool {
return cgroups.Mode() != cgroups.Unavailable
}
func displayMode() string {
switch cgroups.Mode() {
case cgroups.Legacy:
return "legacy"
case cgroups.Hybrid:
return "hybrid"
case cgroups.Unified:
return "unified"
case cgroups.Unavailable:
return "unavailable"
default:
return "unknown"
}
}

Some files were not shown because too many files have changed in this diff Show More