Skip to content

Commit b2e7af7

Browse files
committed
[WIP] added container export functionality.
Signed-off-by: Yasin Turan <[email protected]>
1 parent 009000b commit b2e7af7

File tree

7 files changed

+353
-0
lines changed

7 files changed

+353
-0
lines changed

cmd/nerdctl/container.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ func newContainerCommand() *cobra.Command {
4949
newCommitCommand(),
5050
newRenameCommand(),
5151
newContainerPruneCommand(),
52+
newExportCommand(),
5253
)
5354
addCpCommand(containerCommand)
5455
return containerCommand

cmd/nerdctl/container_export.go

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package main
18+
19+
import (
20+
"fmt"
21+
"os"
22+
23+
"github.com/containerd/nerdctl/pkg/clientutil"
24+
"github.com/containerd/nerdctl/pkg/cmd/container"
25+
"github.com/mattn/go-isatty"
26+
"github.com/spf13/cobra"
27+
)
28+
29+
func newExportCommand() *cobra.Command {
30+
var exportCommand = &cobra.Command{
31+
Use: "export CONTAINER",
32+
Args: cobra.MinimumNArgs(1),
33+
Short: "Export a containers filesystem as a tar archive",
34+
Long: "Export a containers filesystem as a tar archive",
35+
RunE: exportAction,
36+
ValidArgsFunction: exportShellComplete,
37+
SilenceUsage: true,
38+
SilenceErrors: true,
39+
}
40+
exportCommand.Flags().StringP("output", "o", "", "Write to a file, instead of STDOUT")
41+
42+
return exportCommand
43+
}
44+
45+
func exportAction(cmd *cobra.Command, args []string) error {
46+
globalOptions, err := processRootCmdFlags(cmd)
47+
if err != nil {
48+
return err
49+
}
50+
if len(args) == 0 {
51+
return fmt.Errorf("requires at least 1 argument")
52+
}
53+
54+
output, err := cmd.Flags().GetString("output")
55+
if err != nil {
56+
return err
57+
}
58+
59+
client, ctx, cancel, err := clientutil.NewClient(cmd.Context(), globalOptions.Namespace, globalOptions.Address)
60+
if err != nil {
61+
return err
62+
}
63+
defer cancel()
64+
65+
writer := cmd.OutOrStdout()
66+
if output != "" {
67+
f, err := os.OpenFile(output, os.O_CREATE|os.O_WRONLY, 0644)
68+
if err != nil {
69+
return err
70+
}
71+
defer f.Close()
72+
writer = f
73+
} else {
74+
if isatty.IsTerminal(os.Stdout.Fd()) {
75+
return fmt.Errorf("cowardly refusing to save to a terminal. Use the -o flag or redirect")
76+
}
77+
}
78+
return container.Export(ctx, client, args, writer)
79+
80+
}
81+
82+
func exportShellComplete(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
83+
// show container names
84+
return shellCompleteContainerNames(cmd, nil)
85+
}

cmd/nerdctl/main.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,7 @@ Config file ($NERDCTL_TOML): %s
259259
newCommitCommand(),
260260
newWaitCommand(),
261261
newRenameCommand(),
262+
newExportCommand(),
262263
// #endregion
263264

264265
// Build

pkg/cmd/container/export.go

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package container
18+
19+
import (
20+
"context"
21+
"fmt"
22+
"io"
23+
24+
"github.com/containerd/containerd"
25+
"github.com/containerd/containerd/containers"
26+
"github.com/containerd/containerd/mount"
27+
"github.com/containerd/nerdctl/pkg/idutil/containerwalker"
28+
"github.com/containerd/nerdctl/pkg/tarutil"
29+
)
30+
31+
func Export(ctx context.Context, client *containerd.Client, args []string, w io.Writer) error {
32+
walker := &containerwalker.ContainerWalker{
33+
Client: client,
34+
OnFound: func(ctx context.Context, found containerwalker.Found) error {
35+
if found.MatchCount > 1 {
36+
return fmt.Errorf("multiple IDs found with provided prefix: %s", found.Req)
37+
}
38+
container := found.Container
39+
c, err := container.Info(ctx)
40+
if err != nil {
41+
return err
42+
}
43+
return performWithBaseFS(ctx, client, c, func(root string) error {
44+
tb := tarutil.NewTarballer(w)
45+
return tb.Tar(root)
46+
})
47+
48+
},
49+
}
50+
req := args[0]
51+
n, err := walker.Walk(ctx, req)
52+
if err != nil {
53+
return fmt.Errorf("failed to export container %s: %w", req, err)
54+
} else if n == 0 {
55+
return fmt.Errorf("no such container %s", req)
56+
}
57+
return nil
58+
}
59+
60+
// performWithBaseFS will execute a given function with respect to the root filesystem of a container.
61+
// copied over from: https://github.com/moby/moby/blob/master/daemon/containerd/image_exporter.go#L24
62+
func performWithBaseFS(ctx context.Context, client *containerd.Client, c containers.Container, fn func(root string) error) error {
63+
mounts, err := client.SnapshotService(c.Snapshotter).Mounts(ctx, c.SnapshotKey)
64+
if err != nil {
65+
return err
66+
}
67+
return mount.WithTempMount(ctx, mounts, fn)
68+
}

pkg/tarutil/tarutil.go

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,28 @@
1717
package tarutil
1818

1919
import (
20+
"archive/tar"
21+
"bufio"
2022
"fmt"
23+
"io"
2124
"os"
2225
"os/exec"
26+
"path/filepath"
2327
"strings"
28+
"time"
2429

30+
"github.com/containerd/containerd/archive/tarheader"
31+
cfs "github.com/containerd/continuity/fs"
32+
"github.com/docker/docker/pkg/pools"
33+
"github.com/moby/sys/sequential"
2534
"github.com/sirupsen/logrus"
2635
)
2736

37+
const (
38+
paxSchilyXattr = "SCHILY.xattr."
39+
securityCapabilityXattr = "security.capability"
40+
)
41+
2842
// FindTarBinary returns a path to the tar binary and whether it is GNU tar.
2943
func FindTarBinary() (string, bool, error) {
3044
isGNU := func(exe string) bool {
@@ -55,3 +69,118 @@ func FindTarBinary() (string, bool, error) {
5569
}
5670
return "", false, fmt.Errorf("failed to find `tar` binary")
5771
}
72+
73+
type Tarballer struct {
74+
Buffer *bufio.Writer
75+
TarWriter *tar.Writer
76+
seenFiles map[uint64]string
77+
}
78+
79+
// TODO: Add tar options for compression, whiteout files, chown ..etc
80+
81+
func NewTarballer(writer io.Writer) *Tarballer {
82+
return &Tarballer{
83+
Buffer: pools.BufioWriter32KPool.Get(nil),
84+
TarWriter: tar.NewWriter(writer),
85+
seenFiles: make(map[uint64]string),
86+
}
87+
}
88+
89+
// TODO: Add unit test
90+
91+
// Tar creates an archive from the directory at `root`.
92+
// Mostly copied over from https://github.com/containerd/containerd/blob/main/archive/tar.go#L552
93+
func (tb *Tarballer) Tar(root string) error {
94+
defer func() error {
95+
pools.BufioWriter32KPool.Put(tb.Buffer)
96+
return tb.TarWriter.Close()
97+
}()
98+
return filepath.WalkDir(root, func(path string, d os.DirEntry, err error) error {
99+
if err != nil {
100+
return fmt.Errorf("failed to Lstat: %w", err)
101+
}
102+
relPath, err := filepath.Rel(root, path)
103+
if err != nil {
104+
return err
105+
}
106+
info, err := d.Info()
107+
if err != nil {
108+
return err
109+
}
110+
var link string
111+
if info.Mode()&os.ModeSymlink != 0 {
112+
link, err = os.Readlink(path)
113+
if err != nil {
114+
return err
115+
}
116+
}
117+
header, err := FileInfoHeader(info, relPath, link)
118+
if err != nil {
119+
return err
120+
}
121+
inode, isHardlink := cfs.GetLinkInfo(info)
122+
123+
if isHardlink {
124+
if oldpath, ok := tb.seenFiles[inode]; ok {
125+
header.Typeflag = tar.TypeLink
126+
header.Linkname = oldpath
127+
header.Size = 0
128+
} else {
129+
tb.seenFiles[inode] = relPath
130+
}
131+
}
132+
if capability, err := getxattr(path, securityCapabilityXattr); err != nil {
133+
return fmt.Errorf("failed to get capabilities xattr: %w", err)
134+
} else if len(capability) > 0 {
135+
if header.PAXRecords == nil {
136+
header.PAXRecords = map[string]string{}
137+
}
138+
header.PAXRecords[paxSchilyXattr+securityCapabilityXattr] = string(capability)
139+
}
140+
141+
// TODO: Currently not setting UID/GID. Handle remapping UID/GID in container to that of host
142+
143+
err = tb.TarWriter.WriteHeader(header)
144+
if err != nil {
145+
return err
146+
}
147+
if info.Mode().IsRegular() && header.Size > 0 {
148+
f, err := sequential.Open(path)
149+
if err != nil {
150+
return err
151+
}
152+
tb.Buffer.Reset(tb.TarWriter)
153+
defer tb.Buffer.Reset(tb.TarWriter)
154+
if _, err = io.Copy(tb.Buffer, f); err != nil {
155+
return err
156+
}
157+
if err = f.Close(); err != nil {
158+
return err
159+
}
160+
if err = tb.Buffer.Flush(); err != nil {
161+
return err
162+
}
163+
}
164+
return nil
165+
})
166+
}
167+
168+
func FileInfoHeader(info os.FileInfo, path, link string) (*tar.Header, error) {
169+
header, err := tarheader.FileInfoHeaderNoLookups(info, link)
170+
if err != nil {
171+
return nil, err
172+
}
173+
header.Mode = int64(chmodTarEntry(os.FileMode(header.Mode)))
174+
header.Format = tar.FormatPAX
175+
header.ModTime = header.ModTime.Truncate(time.Second)
176+
header.AccessTime = time.Time{}
177+
header.ChangeTime = time.Time{}
178+
179+
name := filepath.ToSlash(path)
180+
if info.IsDir() && !strings.HasSuffix(path, "/") {
181+
name += "/"
182+
}
183+
header.Name = name
184+
185+
return header, nil
186+
}

pkg/tarutil/tarutil_unix.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
//go:build freebsd || linux
2+
3+
/*
4+
Copyright The containerd Authors.
5+
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing, software
13+
distributed under the License is distributed on an "AS IS" BASIS,
14+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
See the License for the specific language governing permissions and
16+
limitations under the License.
17+
*/
18+
19+
package tarutil
20+
21+
import (
22+
"os"
23+
24+
"github.com/containerd/continuity/sysx"
25+
"golang.org/x/sys/unix"
26+
)
27+
28+
func chmodTarEntry(perm os.FileMode) os.FileMode {
29+
return perm
30+
}
31+
32+
func getxattr(path, attr string) ([]byte, error) {
33+
b, err := sysx.LGetxattr(path, attr)
34+
if err == unix.ENOTSUP || err == sysx.ENODATA {
35+
return nil, nil
36+
}
37+
return b, err
38+
}

pkg/tarutil/tarutil_windows.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/*
2+
Copyright The containerd Authors.
3+
4+
Licensed under the Apache License, Version 2.0 (the "License");
5+
you may not use this file except in compliance with the License.
6+
You may obtain a copy of the License at
7+
8+
http://www.apache.org/licenses/LICENSE-2.0
9+
10+
Unless required by applicable law or agreed to in writing, software
11+
distributed under the License is distributed on an "AS IS" BASIS,
12+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
See the License for the specific language governing permissions and
14+
limitations under the License.
15+
*/
16+
17+
package tarutil
18+
19+
import "os"
20+
21+
func chmodTarEntry(perm os.FileMode) os.FileMode {
22+
perm &= 0755
23+
// Add the x bit: make everything +x from windows
24+
perm |= 0111
25+
26+
return perm
27+
}
28+
29+
func getxattr(path, attr string) ([]byte, error) {
30+
return nil, nil
31+
}

0 commit comments

Comments
 (0)