/
containerd.go
249 lines (205 loc) · 6.91 KB
/
containerd.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
package ctrd
import (
"context"
"fmt"
"os"
"os/exec"
"path"
"runtime"
"strings"
"syscall"
"github.com/pouchcontainer/d2p-migrator/ctrd/image"
"github.com/pouchcontainer/d2p-migrator/utils"
pouchtypes "github.com/alibaba/pouch/apis/types"
"github.com/alibaba/pouch/pkg/reference"
"github.com/containerd/containerd"
"github.com/containerd/containerd/containers"
"github.com/containerd/containerd/leases"
"github.com/containerd/containerd/linux/runctypes"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/namespaces"
"github.com/containerd/containerd/oci"
"github.com/containerd/containerd/platforms"
"github.com/containerd/containerd/snapshots"
"github.com/opencontainers/image-spec/identity"
)
const (
defaultSnapshotterName = "overlayfs"
socketAddr = "/tmp/containerd-migrator.sock"
defaultRegistry = "registry.hub.docker.com"
defaultNamespace = "library"
)
// StartContainerd create a new containerd instance.
func StartContainerd(homeDir string, debug bool) (int, error) {
// if socket file exists, delete it.
if _, err := os.Stat(socketAddr); err == nil {
os.RemoveAll(socketAddr)
}
// notes: we use a containerd binary named 'd2p-containerd'
// to avoid the name conflict with the original containerd.
containerdPath, err := exec.LookPath("d2p-containerd")
if err != nil {
return -1, fmt.Errorf("failed to find containerd binary %v", err)
}
// Start a new containerd instance.
cmd, err := newContainerdCmd(homeDir, containerdPath, debug)
if err != nil {
return -1, err
}
go cmd.Wait()
return cmd.Process.Pid, nil
}
func newContainerdCmd(homeDir, containerdPath string, debug bool) (*exec.Cmd, error) {
args := []string{
"-a", socketAddr,
"--root", path.Join(homeDir, "containerd/root"),
"--state", path.Join(homeDir, "containerd/state"),
"-l", utils.IfThenElse(debug, "debug", "info").(string),
}
cmd := exec.Command(containerdPath, args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid: true, Pdeathsig: syscall.SIGKILL}
cmd.Env = nil
for _, e := range os.Environ() {
if !strings.HasPrefix(e, "NOTIFY_SOCKET") {
cmd.Env = append(cmd.Env, e)
}
}
if err := cmd.Start(); err != nil {
return nil, err
}
return cmd, nil
}
// Cleanup kill containerd instance process
func Cleanup(pid int) error {
if pid != -1 {
// delete containerd process forcely.
syscall.Kill(pid, syscall.SIGKILL)
}
os.Remove(socketAddr)
return nil
}
// Client is the wrapper of a containerd client.
type Client struct {
client *containerd.Client
lease *containerd.Lease
}
// NewCtrdClient create a client of containerd
func NewCtrdClient() (*Client, error) {
client, err := containerd.New(socketAddr, containerd.WithDefaultNamespace("default"))
if err != nil {
return nil, err
}
// create a new lease or reuse the existed.
var lease containerd.Lease
leases, err := client.ListLeases(context.TODO())
if err != nil {
return nil, err
}
if len(leases) != 0 {
lease = leases[0]
} else {
if lease, err = client.CreateLease(context.TODO()); err != nil {
return nil, err
}
}
return &Client{
client: client,
lease: &lease,
}, nil
}
// CreateSnapshot creates an active snapshot with image's name and id.
func (cli *Client) CreateSnapshot(ctx context.Context, id, ref string) error {
ctx = leases.WithLease(ctx, cli.lease.ID())
image, err := cli.client.ImageService().Get(ctx, ref)
if err != nil {
return err
}
diffIDs, err := image.RootFS(ctx, cli.client.ContentStore(), platforms.Default())
if err != nil {
return err
}
parent := identity.ChainID(diffIDs).String()
_, err = cli.client.SnapshotService(defaultSnapshotterName).Prepare(ctx, id, parent)
return err
}
// GetSnapshot returns the snapshot's info by id.
func (cli *Client) GetSnapshot(ctx context.Context, id string) (snapshots.Info, error) {
service := cli.client.SnapshotService(defaultSnapshotterName)
defer service.Close()
return service.Stat(ctx, id)
}
// GetMounts returns the mounts for the active snapshot transaction identified by key.
func (cli *Client) GetMounts(ctx context.Context, id string) ([]mount.Mount, error) {
service := cli.client.SnapshotService(defaultSnapshotterName)
defer service.Close()
return service.Mounts(ctx, id)
}
// RemoveSnapshot remove the snapshot by id.
func (cli *Client) RemoveSnapshot(ctx context.Context, id string) error {
service := cli.client.SnapshotService(defaultSnapshotterName)
defer service.Close()
return service.Remove(ctx, id)
}
// NewContainer just create a very simple container for migration
// just load container id to boltdb
func (cli *Client) NewContainer(ctx context.Context, id string) error {
ctx = namespaces.WithNamespace(ctx, namespaces.Default)
spec, err := oci.GenerateSpec(ctx, nil, &containers.Container{ID: id})
if err != nil {
return fmt.Errorf("fail to generate spec for container %s: %v", id, err)
}
options := []containerd.NewContainerOpts{
containerd.WithSpec(spec),
containerd.WithRuntime(fmt.Sprintf("io.containerd.runtime.v1.%s", runtime.GOOS), &runctypes.RuncOptions{
Runtime: "docker-runc",
}),
}
if _, err := cli.client.NewContainer(ctx, id, options...); err != nil {
return fmt.Errorf("failed to create new containerd container %s: %v", id, err)
}
return nil
}
// GetContainer is to fetch a container info from containerd
func (cli *Client) GetContainer(ctx context.Context, id string) (containers.Container, error) {
ctx = namespaces.WithNamespace(ctx, namespaces.Default)
return cli.client.ContainerService().Get(ctx, id)
}
// DeleteContainer deletes a containerd container
func (cli *Client) DeleteContainer(ctx context.Context, id string) error {
ctx = namespaces.WithNamespace(ctx, namespaces.Default)
return cli.client.ContainerService().Delete(ctx, id)
}
// GetImage inspect a containerd image
func (cli *Client) GetImage(ctx context.Context, imageName string) (containerd.Image, error) {
ctx = namespaces.WithNamespace(ctx, namespaces.Default)
return cli.client.GetImage(ctx, imageName)
}
// PullImage prepares all images using by docker containers,
// that will be used to create new pouch container.
func (cli *Client) PullImage(ctx context.Context, ref, snapshotter string, manifestOnly bool) error {
var err error
newRef := image.AddDefaultRegistryIfMissing(ref, defaultRegistry, defaultNamespace)
namedRef, err := reference.Parse(newRef)
if err != nil {
return err
}
namedRef = reference.TrimTagForDigest(reference.WithDefaultTagIfMissing(namedRef))
resolver, err := resolver(&pouchtypes.AuthConfig{})
if err != nil {
return err
}
options := []containerd.RemoteOpt{
containerd.WithSchema1Conversion,
containerd.WithResolver(resolver),
containerd.WithPullSnapshotter(snapshotter),
}
if manifestOnly {
err = image.PullManifest(ctx, cli.client, namedRef.String(), options...)
} else {
options = append(options, containerd.WithPullUnpack)
_, err = cli.client.Pull(ctx, namedRef.String(), options...)
}
return err
}