-
Notifications
You must be signed in to change notification settings - Fork 17
/
sandbox.go
367 lines (300 loc) · 7.88 KB
/
sandbox.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
package sandbox
import (
"context"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"time"
"go.opentelemetry.io/otel/trace"
"github.com/e2b-dev/infra/packages/shared/pkg/consts"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
consul "github.com/hashicorp/consul/api"
)
const (
fcVersionsDir = "/fc-versions"
kernelsDir = "/fc-kernels"
kernelMountDir = "/fc-vm"
kernelName = "vmlinux.bin"
uffdBinaryName = "uffd"
fcBinaryName = "firecracker"
waitForUffd = 80 * time.Millisecond
uffdCheckInterval = 10 * time.Millisecond
)
var logsProxyAddress = os.Getenv("LOGS_PROXY_ADDRESS")
var httpClient = http.Client{
Timeout: 5 * time.Second,
}
type Sandbox struct {
slot *IPSlot
files *SandboxFiles
fc *fc
uffd *uffd
Sandbox *orchestrator.SandboxConfig
StartedAt time.Time
TraceID string
}
func uffdBinaryPath(fcVersion string) string {
return filepath.Join(fcVersionsDir, fcVersion, uffdBinaryName)
}
func fcBinaryPath(fcVersion string) string {
return filepath.Join(fcVersionsDir, fcVersion, fcBinaryName)
}
func NewSandbox(
ctx context.Context,
tracer trace.Tracer,
consul *consul.Client,
dns *DNS,
config *orchestrator.SandboxConfig,
traceID string,
) (*Sandbox, error) {
childCtx, childSpan := tracer.Start(ctx, "new-sandbox")
defer childSpan.End()
// Get slot from Consul KV
ips, err := NewSlot(
childCtx,
tracer,
consul,
config.SandboxID,
)
if err != nil {
errMsg := fmt.Errorf("failed to get IP slot: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "reserved ip slot")
defer func() {
if err != nil {
slotErr := ips.Release(childCtx, tracer, consul)
if slotErr != nil {
errMsg := fmt.Errorf("error removing network namespace after failed instance start: %w", slotErr)
telemetry.ReportError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "released ip slot")
}
}
}()
defer func() {
if err != nil {
ntErr := ips.RemoveNetwork(childCtx, tracer, dns)
if ntErr != nil {
errMsg := fmt.Errorf("error removing network namespace after failed instance start: %w", ntErr)
telemetry.ReportError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "removed network namespace")
}
}
}()
err = ips.CreateNetwork(childCtx, tracer, dns)
if err != nil {
errMsg := fmt.Errorf("failed to create namespaces: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "created network")
fsEnv, err := newSandboxFiles(
childCtx,
tracer,
ips,
config.TemplateID,
config.KernelVersion,
kernelsDir,
kernelMountDir,
kernelName,
fcBinaryPath(config.FirecrackerVersion),
uffdBinaryPath(config.FirecrackerVersion),
config.HugePages,
)
if err != nil {
errMsg := fmt.Errorf("failed to assemble env files info for FC: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "assembled env files info")
err = fsEnv.Ensure(childCtx)
if err != nil {
errMsg := fmt.Errorf("failed to create env for FC: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "created env for FC")
defer func() {
if err != nil {
envErr := fsEnv.Cleanup(childCtx, tracer)
if envErr != nil {
errMsg := fmt.Errorf("error deleting env after failed fc start: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "deleted env")
}
}
}()
var uffd *uffd
if fsEnv.UFFDSocketPath != nil {
uffd = newUFFD(fsEnv)
uffdErr := uffd.start()
if err != nil {
errMsg := fmt.Errorf("failed to start uffd: %w", uffdErr)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
// Wait for uffd to initialize — it should be possible to handle this better?
uffdWait:
for {
select {
case <-time.After(waitForUffd):
fmt.Printf("waiting for uffd to initialize")
return nil, fmt.Errorf("timeout waiting to uffd to initialize")
case <-childCtx.Done():
return nil, childCtx.Err()
default:
isRunning, _ := checkIsRunning(uffd.cmd.Process)
fmt.Printf("uffd is running: %v", isRunning)
if isRunning {
break uffdWait
}
time.Sleep(uffdCheckInterval)
}
}
}
fc := newFC(
childCtx,
tracer,
ips,
fsEnv,
&MmdsMetadata{
InstanceID: config.SandboxID,
EnvID: config.TemplateID,
Address: logsProxyAddress,
TraceID: traceID,
TeamID: config.TeamID,
},
)
err = fc.start(childCtx, tracer)
if err != nil {
if uffd != nil {
uffd.stop(childCtx, tracer)
}
errMsg := fmt.Errorf("failed to start FC: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
return nil, errMsg
}
telemetry.ReportEvent(childCtx, "initialized FC")
instance := &Sandbox{
files: fsEnv,
slot: ips,
fc: fc,
uffd: uffd,
Sandbox: config,
}
telemetry.ReportEvent(childCtx, "ensuring clock sync")
go func() {
backgroundCtx := context.Background()
clockErr := instance.EnsureClockSync(backgroundCtx)
if clockErr != nil {
telemetry.ReportError(backgroundCtx, fmt.Errorf("failed to sync clock: %w", clockErr))
} else {
telemetry.ReportEvent(backgroundCtx, "clock synced")
}
}()
instance.StartedAt = time.Now()
return instance, nil
}
func (s *Sandbox) syncClock(ctx context.Context) error {
address := fmt.Sprintf("http://%s:%d/sync", s.slot.HostSnapshotIP(), consts.DefaultEnvdServerPort)
request, err := http.NewRequestWithContext(ctx, "POST", address, nil)
if err != nil {
return err
}
response, err := httpClient.Do(request)
if err != nil {
return err
}
if _, err := io.Copy(io.Discard, response.Body); err != nil {
return err
}
defer response.Body.Close()
return nil
}
func (s *Sandbox) EnsureClockSync(ctx context.Context) error {
syncLoop:
for {
select {
case <-time.After(10 * time.Second):
case <-ctx.Done():
return ctx.Err()
default:
err := s.syncClock(ctx)
if err != nil {
telemetry.ReportError(ctx, fmt.Errorf("error syncing clock: %w", err))
continue
}
break syncLoop
}
}
return nil
}
func (s *Sandbox) CleanupAfterFCStop(
ctx context.Context,
tracer trace.Tracer,
consul *consul.Client,
dns *DNS,
) {
childCtx, childSpan := tracer.Start(ctx, "delete-instance")
defer childSpan.End()
err := s.slot.RemoveNetwork(childCtx, tracer, dns)
if err != nil {
errMsg := fmt.Errorf("cannot remove network when destroying task: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "removed network")
}
err = s.files.Cleanup(childCtx, tracer)
if err != nil {
errMsg := fmt.Errorf("failed to delete instance files: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "deleted instance files")
}
err = s.slot.Release(childCtx, tracer, consul)
if err != nil {
errMsg := fmt.Errorf("failed to release slot: %w", err)
telemetry.ReportCriticalError(childCtx, errMsg)
} else {
telemetry.ReportEvent(childCtx, "released slot")
}
}
func (s *Sandbox) Wait(ctx context.Context, tracer trace.Tracer) (err error) {
defer s.Stop(ctx, tracer)
if s.uffd != nil {
go func() {
err := s.uffd.wait()
fmt.Printf("uffd wait error: %v", err)
}()
}
return s.fc.wait()
}
func (s *Sandbox) Stop(ctx context.Context, tracer trace.Tracer) {
childCtx, childSpan := tracer.Start(ctx, "stop-sandbox", trace.WithAttributes())
defer childSpan.End()
s.fc.stop(childCtx, tracer)
if s.uffd != nil {
// Wait until we stop uffd if it exists
time.Sleep(1 * time.Second)
s.uffd.stop(childCtx, tracer)
}
}
func (s *Sandbox) SlotIdx() int {
return s.slot.SlotIdx
}
func (s *Sandbox) FcPid() int {
return s.fc.pid
}
func (s *Sandbox) UffdPid() *int {
if s.uffd == nil {
return nil
}
return &s.uffd.pid
}