summary refs log tree commit diff
path: root/cmd/c2vm/main.go
blob: c416e473b073d5b45b569806f432e5b377bfbc17 (plain) (blame)
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
package main

import (
	"context"
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"os/exec"
	"path/filepath"

	"github.com/containerd/containerd"
	"github.com/containerd/containerd/content"
	"github.com/containerd/containerd/images"
	"github.com/containerd/containerd/namespaces"
	"github.com/containerd/containerd/platforms"
	"github.com/docker/docker/pkg/archive"
	"github.com/google/renameio"
	ocispec "github.com/opencontainers/image-spec/specs-go/v1"
)

const (
	containerdSock   = "/run/containerd/containerd.sock"
	defaultNamespace = "c2vm"
)

var (
	platform = platforms.Only(ocispec.Platform{
		OS:           "linux",
		Architecture: "amd64",
	})
)

func main() {
	var (
		containerName = flag.String("container", "", "Name of the container")
		outFile       = flag.String("out", "container.img", "firecracker output to create")
	)

	flag.Parse()

	if *containerName == "" {
		log.Fatal("a container is required")
	}

	client, err := containerd.New(containerdSock)
	if err != nil {
		log.Fatalf("failed to create a client for containerd: %v", err)
	}
	defer client.Close()

	ctx := namespaces.WithNamespace(context.Background(), defaultNamespace)
	ctx, done, err := client.WithLease(ctx)
	if err != nil {
		log.Fatalf("failed to get a lease: %v", err)
	}
	defer done(ctx)

	image, err := client.Pull(ctx, *containerName, containerd.WithPlatformMatcher(platform))
	if err != nil {
		log.Fatalf("failed to pull the container %s: %v\n", *containerName, err)
	}

	imageSize, err := image.Usage(ctx, containerd.WithUsageManifestLimit(1))
	if err != nil {
		log.Fatalf("failed to get the size of the image: %v", err)
	}

	log.Printf("pulled %s (%d bytes)\n", image.Name(), imageSize)

	mntDir, err := ioutil.TempDir("", "c2vm")
	if err != nil {
		log.Fatalf("Failed to create mount temp dir: %v\n", err)
	}

	if err := createLoopDevice(*outFile, mntDir); err != nil {
		log.Fatalf("%v\n", err)
	}

	if err := extract(ctx, client, image, mntDir); err != nil {
		log.Fatalf("failed to extract the container: %v\n", err)
	}

	if err = extraFiles(mntDir); err != nil {
		log.Fatalf("failed to add extra files to the image: %v\n", err)
	}

	if err := detachLoopDevice(mntDir); err != nil {
		log.Fatalf("failed to umount %s: %v\n", mntDir, err)
	}

	if err := resizeImage(*outFile); err != nil {
		log.Fatalf("failed to resize the image %s: %s\n", *outFile, err)
	}
}

func extract(ctx context.Context, client *containerd.Client, image containerd.Image, mntDir string) error {
	manifest, err := images.Manifest(ctx, client.ContentStore(), image.Target(), platform)
	if err != nil {
		log.Fatalf("failed to get the manifest: %v\n", err)
	}

	for _, desc := range manifest.Layers {
		log.Printf("extracting layer %s\n", desc.Digest.String())
		layer, err := client.ContentStore().ReaderAt(ctx, desc)
		if err != nil {
			return err
		}
		if err := archive.Untar(content.NewReader(layer), mntDir, &archive.TarOptions{NoLchown: true}); err != nil {
			return err
		}
	}

	return nil
}

func createLoopDevice(rawFile, mntDir string) error {
	f, err := renameio.TempFile("", rawFile)
	if err != nil {
		return err
	}
	defer f.Cleanup()

	command := exec.Command("fallocate", "-l", "2G", f.Name())
	if err := command.Run(); err != nil {
		return fmt.Errorf("fallocate error: %s", err)
	}

	command = exec.Command("mkfs.ext4", "-F", f.Name())
	if err := command.Run(); err != nil {
		return fmt.Errorf("mkfs.ext4 error: %s", err)
	}

	f.CloseAtomicallyReplace()

	command = exec.Command("mount", "-o", "loop", rawFile, mntDir)
	if err := command.Run(); err != nil {
		return fmt.Errorf("mount error: %s", err)
	}
	log.Printf("mounted %s on %s\n", rawFile, mntDir)
	return nil
}

func detachLoopDevice(mntDir string) error {
	log.Printf("umount %s\n", mntDir)
	command := exec.Command("umount", mntDir)
	return command.Run()
}

func resizeImage(rawFile string) error {
	// let's bring the image to a more reasonable size. We do this by
	// first running e2fsck on the image then we can resize the image.
	command := exec.Command("/usr/bin/e2fsck", "-p", "-f", rawFile)
	if err := command.Run(); err != nil {
		return fmt.Errorf("e2fsck error: %s", err)
	}

	command = exec.Command("resize2fs", "-M", rawFile)
	if err := command.Run(); err != nil {
		return fmt.Errorf("resize2fs error: %s", err)
	}
	return nil
}

func extraFiles(mntDir string) error {
	if err := writeToFile(filepath.Join(mntDir, "etc", "hosts"), "127.0.0.1\tlocalhost\n"); err != nil {
		return err
	}
	if err := writeToFile(filepath.Join(mntDir, "etc", "resolv.conf"), "nameserver 192.168.0.1\n"); err != nil {
		return err
	}
	return nil
}

func writeToFile(filepath string, content string) error {
	if err := ioutil.WriteFile(filepath, []byte(content), 0644); err != nil {
		return fmt.Errorf("writeToFile %s: %v", filepath, err)
	}
	return nil
}