/
snapshot.go
488 lines (380 loc) · 12.1 KB
/
snapshot.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
package env
import (
"bufio"
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"sync"
"time"
"github.com/firecracker-microvm/firecracker-go-sdk"
"github.com/go-openapi/strfmt"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"github.com/e2b-dev/infra/packages/shared/pkg/fc/client"
"github.com/e2b-dev/infra/packages/shared/pkg/fc/client/operations"
"github.com/e2b-dev/infra/packages/shared/pkg/fc/models"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
)
const (
fcMaskLong = "255.255.255.252"
fcMacAddress = "02:FC:00:00:00:05"
fcAddr = "169.254.0.21"
fcMask = "/30"
fcIfaceID = "eth0"
tmpDirPath = "/tmp"
socketReadyCheckInterval = 100 * time.Millisecond
socketWaitTimeout = 2 * time.Second
waitTimeForFCConfig = 500 * time.Millisecond
waitTimeForFCStart = 10 * time.Second
waitTimeForStartCmd = 15 * time.Second
)
type Snapshot struct {
fc *exec.Cmd
client *client.Firecracker
env *Env
socketPath string
}
func waitForSocket(socketPath string, timeout time.Duration) error {
start := time.Now()
for {
_, err := os.Stat(socketPath)
if err == nil {
// Socket file exists
return nil
} else if os.IsNotExist(err) {
// Socket file doesn't exist yet
// Check if timeout has been reached
elapsed := time.Since(start)
if elapsed >= timeout {
return fmt.Errorf("timeout reached while waiting for socket file")
}
// Wait for a short duration before checking again
time.Sleep(socketReadyCheckInterval)
} else {
// Error occurred while checking for socket file
return err
}
}
}
func newFirecrackerClient(socketPath string) *client.Firecracker {
httpClient := client.NewHTTPClient(strfmt.NewFormats())
transport := firecracker.NewUnixSocketTransport(socketPath, nil, false)
httpClient.SetTransport(transport)
return httpClient
}
func NewSnapshot(ctx context.Context, tracer trace.Tracer, env *Env, network *FCNetwork, rootfs *Rootfs) (*Snapshot, error) {
childCtx, childSpan := tracer.Start(ctx, "new-snapshot")
defer childSpan.End()
socketFileName := fmt.Sprintf("fc-sock-%s.sock", env.BuildID)
socketPath := filepath.Join(tmpDirPath, socketFileName)
client := newFirecrackerClient(socketPath)
telemetry.ReportEvent(childCtx, "created fc client")
snapshot := &Snapshot{
socketPath: socketPath,
client: client,
env: env,
fc: nil,
}
defer snapshot.cleanupFC(childCtx, tracer)
err := snapshot.startFCProcess(
childCtx,
tracer,
env.FirecrackerBinaryPath,
network.namespaceID,
env.KernelMountDir,
env.KernelDirPath(),
)
if err != nil {
errMsg := fmt.Errorf("error starting fc process: %w", err)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "started fc process")
err = snapshot.configureFC(childCtx, tracer)
if err != nil {
errMsg := fmt.Errorf("error configuring fc: %w", err)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "configured fc")
// Wait for all necessary things in FC to start
// TODO: Maybe init should signalize when it's ready?
time.Sleep(waitTimeForFCStart)
telemetry.ReportEvent(childCtx, "waited for fc to start", attribute.Float64("seconds", float64(waitTimeForFCStart/time.Second)))
if env.StartCmd != "" {
time.Sleep(waitTimeForStartCmd)
telemetry.ReportEvent(childCtx, "waited for start command", attribute.Float64("seconds", float64(waitTimeForStartCmd/time.Second)))
}
err = snapshot.pauseFC(childCtx, tracer)
if err != nil {
errMsg := fmt.Errorf("error pausing fc: %w", err)
return nil, errMsg
}
err = snapshot.snapshotFC(childCtx, tracer)
if err != nil {
errMsg := fmt.Errorf("error snapshotting fc: %w", err)
return nil, errMsg
}
return snapshot, nil
}
func (s *Snapshot) startFCProcess(
ctx context.Context,
tracer trace.Tracer,
fcBinaryPath,
networkNamespaceID,
kernelMountDir,
kernelDirPath string,
) error {
childCtx, childSpan := tracer.Start(ctx, "start-fc-process")
defer childSpan.End()
kernelMountCmd := fmt.Sprintf(
"mount --bind %s %s && ",
kernelDirPath,
kernelMountDir,
)
inNetNSCmd := fmt.Sprintf("ip netns exec %s ", networkNamespaceID)
fcCmd := fmt.Sprintf("%s --api-sock %s", fcBinaryPath, s.socketPath)
s.fc = exec.CommandContext(childCtx, "unshare", "-pm", "--kill-child", "--", "bash", "-c", kernelMountCmd+inNetNSCmd+fcCmd)
fcVMStdoutWriter := telemetry.NewEventWriter(childCtx, "stdout")
fcVMStderrWriter := telemetry.NewEventWriter(childCtx, "stderr")
stdoutPipe, err := s.fc.StdoutPipe()
if err != nil {
errMsg := fmt.Errorf("error creating fc stdout pipe: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
stderrPipe, err := s.fc.StderrPipe()
if err != nil {
errMsg := fmt.Errorf("error creating fc stderr pipe: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
closeErr := stdoutPipe.Close()
if closeErr != nil {
closeErrMsg := fmt.Errorf("error closing fc stdout pipe: %w", closeErr)
telemetry.ReportError(childCtx, closeErrMsg)
}
return errMsg
}
var outputWaitGroup sync.WaitGroup
outputWaitGroup.Add(1)
go func() {
scanner := bufio.NewScanner(stdoutPipe)
for scanner.Scan() {
line := scanner.Text()
fcVMStdoutWriter.Write([]byte(line))
}
outputWaitGroup.Done()
}()
outputWaitGroup.Add(1)
go func() {
scanner := bufio.NewScanner(stderrPipe)
for scanner.Scan() {
line := scanner.Text()
fcVMStderrWriter.Write([]byte(line))
}
outputWaitGroup.Done()
}()
err = s.fc.Start()
if err != nil {
errMsg := fmt.Errorf("error starting fc process: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "started fc process")
go func() {
anonymousChildCtx, anonymousChildSpan := tracer.Start(ctx, "handle-fc-process-wait")
defer anonymousChildSpan.End()
outputWaitGroup.Wait()
waitErr := s.fc.Wait()
if err != nil {
errMsg := fmt.Errorf("error waiting for fc process: %w", waitErr)
telemetry.ReportError(anonymousChildCtx, errMsg)
} else {
telemetry.ReportEvent(anonymousChildCtx, "fc process exited")
}
}()
// Wait for the FC process to start so we can use FC API
err = waitForSocket(s.socketPath, socketWaitTimeout)
if err != nil {
errMsg := fmt.Errorf("error waiting for fc socket: %w", err)
return errMsg
}
telemetry.ReportEvent(childCtx, "fc process created socket")
return nil
}
func (s *Snapshot) configureFC(ctx context.Context, tracer trace.Tracer) error {
childCtx, childSpan := tracer.Start(ctx, "configure-fc")
defer childSpan.End()
ip := fmt.Sprintf("%s::%s:%s:instance:eth0:off:8.8.8.8", fcAddr, fcTapAddress, fcMaskLong)
kernelArgs := fmt.Sprintf("quiet loglevel=1 ip=%s reboot=k panic=1 pci=off nomodules i8042.nokbd i8042.noaux ipv6.disable=1 random.trust_cpu=on", ip)
kernelImagePath := s.env.KernelMountedPath()
bootSourceConfig := operations.PutGuestBootSourceParams{
Context: childCtx,
Body: &models.BootSource{
BootArgs: kernelArgs,
KernelImagePath: &kernelImagePath,
},
}
_, err := s.client.Operations.PutGuestBootSource(&bootSourceConfig)
if err != nil {
errMsg := fmt.Errorf("error setting fc boot source config: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "set fc boot source config")
rootfs := "rootfs"
ioEngine := "Async"
isRootDevice := true
isReadOnly := false
pathOnHost := s.env.tmpRootfsPath()
driversConfig := operations.PutGuestDriveByIDParams{
Context: childCtx,
DriveID: rootfs,
Body: &models.Drive{
DriveID: &rootfs,
PathOnHost: pathOnHost,
IsRootDevice: &isRootDevice,
IsReadOnly: isReadOnly,
IoEngine: &ioEngine,
},
}
_, err = s.client.Operations.PutGuestDriveByID(&driversConfig)
if err != nil {
errMsg := fmt.Errorf("error setting fc drivers config: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "set fc drivers config")
ifaceID := fcIfaceID
hostDevName := fcTapName
networkConfig := operations.PutGuestNetworkInterfaceByIDParams{
Context: childCtx,
IfaceID: ifaceID,
Body: &models.NetworkInterface{
IfaceID: &ifaceID,
GuestMac: fcMacAddress,
HostDevName: &hostDevName,
},
}
_, err = s.client.Operations.PutGuestNetworkInterfaceByID(&networkConfig)
if err != nil {
errMsg := fmt.Errorf("error setting fc network config: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "set fc network config")
smt := true
trackDirtyPages := false
machineConfig := &models.MachineConfiguration{
VcpuCount: &s.env.VCpuCount,
MemSizeMib: &s.env.MemoryMB,
Smt: &smt,
TrackDirtyPages: &trackDirtyPages,
}
if s.env.HugePages {
machineConfig.HugePages = models.MachineConfigurationHugePagesNr2M
}
machineConfigParams := operations.PutMachineConfigurationParams{
Context: childCtx,
Body: machineConfig,
}
_, err = s.client.Operations.PutMachineConfiguration(&machineConfigParams)
if err != nil {
errMsg := fmt.Errorf("error setting fc machine config: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "set fc machine config")
mmdsVersion := "V2"
mmdsConfig := operations.PutMmdsConfigParams{
Context: childCtx,
Body: &models.MmdsConfig{
Version: &mmdsVersion,
NetworkInterfaces: []string{fcIfaceID},
},
}
_, err = s.client.Operations.PutMmdsConfig(&mmdsConfig)
if err != nil {
errMsg := fmt.Errorf("error setting fc mmds config: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "set fc mmds config")
// We may need to sleep before start - previous configuration is processes asynchronously. How to do this sync or in one go?
time.Sleep(waitTimeForFCConfig)
start := models.InstanceActionInfoActionTypeInstanceStart
startActionParams := operations.CreateSyncActionParams{
Context: childCtx,
Info: &models.InstanceActionInfo{
ActionType: &start,
},
}
_, err = s.client.Operations.CreateSyncAction(&startActionParams)
if err != nil {
errMsg := fmt.Errorf("error starting fc: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "started fc")
return nil
}
func (s *Snapshot) pauseFC(ctx context.Context, tracer trace.Tracer) error {
childCtx, childSpan := tracer.Start(ctx, "pause-fc")
defer childSpan.End()
state := models.VMStatePaused
pauseConfig := operations.PatchVMParams{
Context: childCtx,
Body: &models.VM{
State: &state,
},
}
_, err := s.client.Operations.PatchVM(&pauseConfig)
if err != nil {
errMsg := fmt.Errorf("error pausing vm: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "paused fc")
return nil
}
func (s *Snapshot) snapshotFC(ctx context.Context, tracer trace.Tracer) error {
childCtx, childSpan := tracer.Start(ctx, "snapshot-fc")
defer childSpan.End()
memfilePath := s.env.tmpMemfilePath()
snapfilePath := s.env.tmpSnapfilePath()
snapshotConfig := operations.CreateSnapshotParams{
Context: childCtx,
Body: &models.SnapshotCreateParams{
SnapshotType: models.SnapshotCreateParamsSnapshotTypeFull,
MemFilePath: &memfilePath,
SnapshotPath: &snapfilePath,
},
}
_, err := s.client.Operations.CreateSnapshot(&snapshotConfig)
if err != nil {
errMsg := fmt.Errorf("error creating vm snapshot: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return errMsg
}
telemetry.ReportEvent(childCtx, "created vm snapshot")
return nil
}
func (s *Snapshot) cleanupFC(ctx context.Context, tracer trace.Tracer) {
childCtx, childSpan := tracer.Start(ctx, "cleanup-fc")
defer childSpan.End()
if s.fc != nil {
err := s.fc.Cancel()
if err != nil {
errMsg := fmt.Errorf("error killing fc process: %w", err)
telemetry.ReportError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "killed fc process")
}
}
err := os.RemoveAll(s.socketPath)
if err != nil {
errMsg := fmt.Errorf("error removing fc socket %w", err)
telemetry.ReportError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "removed fc socket")
}
}