Skip to content

Commit 9021685

Browse files
djeebusjakubno
andauthored
Refactor the Create/Resume functions to avoid globals/reduce args (#1258)
Co-authored-by: Jakub Novak <jakub@e2b.dev>
1 parent 2d3b154 commit 9021685

16 files changed

Lines changed: 123 additions & 123 deletions

File tree

packages/orchestrator/cmd/build-template/main.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,13 +155,15 @@ func buildTemplate(
155155
if err != nil {
156156
zap.L().Fatal("failed to create build metrics", zap.Error(err))
157157
}
158+
159+
sandboxFactory := sandbox.NewFactory(networkPool, devicePool, featureFlags, true)
160+
158161
builder := build.NewBuilder(
159162
logger,
163+
sandboxFactory,
160164
persistenceTemplate,
161165
persistenceBuild,
162166
artifactRegistry,
163-
devicePool,
164-
networkPool,
165167
sandboxProxy,
166168
sandboxes,
167169
templateCache,

packages/orchestrator/internal/config/config.go

Lines changed: 0 additions & 5 deletions
This file was deleted.

packages/orchestrator/internal/sandbox/sandbox.go

Lines changed: 39 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,6 @@ import (
1313
"go.opentelemetry.io/otel/trace"
1414
"go.uber.org/zap"
1515

16-
globalconfig "github.com/e2b-dev/infra/packages/orchestrator/internal/config"
1716
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/block"
1817
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/build"
1918
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/fc"
@@ -24,6 +23,7 @@ import (
2423
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/uffd"
2524
"github.com/e2b-dev/infra/packages/orchestrator/internal/template/metadata"
2625
"github.com/e2b-dev/infra/packages/shared/pkg/env"
26+
featureflags "github.com/e2b-dev/infra/packages/shared/pkg/feature-flags"
2727
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator"
2828
sbxlogger "github.com/e2b-dev/infra/packages/shared/pkg/logger/sandbox"
2929
"github.com/e2b-dev/infra/packages/shared/pkg/storage"
@@ -117,12 +117,32 @@ type networkSlotRes struct {
117117
err error
118118
}
119119

120+
type Factory struct {
121+
networkPool *network.Pool
122+
devicePool *nbd.DevicePool
123+
featureFlags *featureflags.Client
124+
125+
defaultAllowInternetAccess bool
126+
}
127+
128+
func NewFactory(
129+
networkPool *network.Pool,
130+
devicePool *nbd.DevicePool,
131+
featureFlags *featureflags.Client,
132+
defaultAllowInternetAccess bool,
133+
) *Factory {
134+
return &Factory{
135+
networkPool: networkPool,
136+
devicePool: devicePool,
137+
featureFlags: featureFlags,
138+
defaultAllowInternetAccess: defaultAllowInternetAccess,
139+
}
140+
}
141+
120142
// CreateSandbox creates the sandbox.
121143
// IMPORTANT: You must Close() the sandbox after you are done with it.
122-
func CreateSandbox(
144+
func (f *Factory) CreateSandbox(
123145
ctx context.Context,
124-
networkPool *network.Pool,
125-
devicePool *nbd.DevicePool,
126146
config Config,
127147
runtime RuntimeMetadata,
128148
fcVersions fc.FirecrackerVersions,
@@ -148,12 +168,13 @@ func CreateSandbox(
148168
}
149169
}()
150170

151-
allowInternet := globalconfig.AllowSandboxInternet
171+
// TODO: Temporarily set this based on global config, should be removed later (it should be passed as a parameter in build)
172+
allowInternet := f.defaultAllowInternetAccess
152173
if config.AllowInternetAccess != nil {
153174
allowInternet = *config.AllowInternetAccess
154175
}
155176

156-
ipsCh := getNetworkSlotAsync(ctx, networkPool, cleanup, allowInternet)
177+
ipsCh := getNetworkSlotAsync(ctx, f.networkPool, cleanup, allowInternet)
157178
defer func() {
158179
// Ensure the slot is received from chan so the slot is cleaned up properly in cleanup
159180
<-ipsCh
@@ -172,7 +193,7 @@ func CreateSandbox(
172193
rootfsProvider, err = rootfs.NewNBDProvider(
173194
rootFS,
174195
sandboxFiles.SandboxCacheRootfsPath(),
175-
devicePool,
196+
f.devicePool,
176197
)
177198
} else {
178199
rootfsProvider, err = rootfs.NewDirectProvider(
@@ -305,17 +326,14 @@ func endSpan(span trace.Span, err error) {
305326

306327
// ResumeSandbox resumes the sandbox from already saved template or snapshot.
307328
// IMPORTANT: You must Close() the sandbox after you are done with it.
308-
func ResumeSandbox(
329+
func (f *Factory) ResumeSandbox(
309330
ctx context.Context,
310-
networkPool *network.Pool,
311331
t template.Template,
312332
config Config,
313333
runtime RuntimeMetadata,
314334
traceID string,
315335
startedAt time.Time,
316336
endAt time.Time,
317-
devicePool *nbd.DevicePool,
318-
useClickhouseMetrics bool,
319337
apiConfigToStore *orchestrator.SandboxConfig,
320338
) (s *Sandbox, e error) {
321339
ctx, span := tracer.Start(ctx, "resume sandbox")
@@ -334,12 +352,14 @@ func ResumeSandbox(
334352
}
335353
}()
336354

337-
allowInternet := globalconfig.AllowSandboxInternet
355+
// TODO: Temporarily set this based on global config, should be removed later
356+
// (it should be passed as a non nil parameter from API)
357+
allowInternet := f.defaultAllowInternetAccess
338358
if config.AllowInternetAccess != nil {
339359
allowInternet = *config.AllowInternetAccess
340360
}
341361

342-
ipsCh := getNetworkSlotAsync(ctx, networkPool, cleanup, allowInternet)
362+
ipsCh := getNetworkSlotAsync(ctx, f.networkPool, cleanup, allowInternet)
343363
defer func() {
344364
// Ensure the slot is received from chan before ResumeSandbox returns so the slot is cleaned up properly in cleanup
345365
<-ipsCh
@@ -360,7 +380,7 @@ func ResumeSandbox(
360380
rootfsOverlay, err := rootfs.NewNBDProvider(
361381
readonlyRootfs,
362382
sandboxFiles.SandboxCacheRootfsPath(),
363-
devicePool,
383+
f.devicePool,
364384
)
365385
if err != nil {
366386
return nil, fmt.Errorf("failed to create rootfs overlay: %w", err)
@@ -508,6 +528,11 @@ func ResumeSandbox(
508528
exit: exit,
509529
}
510530

531+
useClickhouseMetrics, flagErr := f.featureFlags.BoolFlag(ctx, featureflags.MetricsWriteFlagName)
532+
if flagErr != nil {
533+
zap.L().Error("soft failing during metrics write feature flag receive", zap.Error(flagErr))
534+
}
535+
511536
// Part of the sandbox as we need to stop Checks before pausing the sandbox
512537
// This is to prevent race condition of reporting unhealthy sandbox
513538
sbx.Checks = NewChecks(sbx, useClickhouseMetrics)

packages/orchestrator/internal/server/main.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ import (
2727
type server struct {
2828
orchestrator.UnimplementedSandboxServiceServer
2929

30+
sandboxFactory *sandbox.Factory
3031
info *service.ServiceInfo
3132
sandboxes *smap.Map[*sandbox.Sandbox]
3233
proxy *proxy.SandboxProxy
@@ -56,22 +57,21 @@ type ServiceConfig struct {
5657
TemplateCache *template.Cache
5758
Info *service.ServiceInfo
5859
Proxy *proxy.SandboxProxy
60+
SandboxFactory *sandbox.Factory
5961
Sandboxes *smap.Map[*sandbox.Sandbox]
6062
Persistence storage.StorageProvider
6163
FeatureFlags *featureflags.Client
6264
SbxEventsService events.EventsService[event.SandboxEvent]
6365
}
6466

65-
func New(
66-
ctx context.Context,
67-
cfg ServiceConfig,
68-
) (*Service, error) {
67+
func New(cfg ServiceConfig) *Service {
6968
srv := &Service{
7069
info: cfg.Info,
7170
proxy: cfg.Proxy,
7271
persistence: cfg.Persistence,
7372
}
7473
srv.server = &server{
74+
sandboxFactory: cfg.SandboxFactory,
7575
info: cfg.Info,
7676
proxy: srv.proxy,
7777
sandboxes: cfg.Sandboxes,
@@ -96,5 +96,5 @@ func New(
9696

9797
orchestrator.RegisterSandboxServiceServer(cfg.GRPC.GRPCServer(), srv.server)
9898

99-
return srv, nil
99+
return srv
100100
}

packages/orchestrator/internal/server/sandboxes.go

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -87,11 +87,6 @@ func (s *server) Create(ctx context.Context, req *orchestrator.SandboxCreateRequ
8787
}
8888
defer s.startingSandboxes.Release(1)
8989

90-
metricsWriteFlag, flagErr := s.featureFlags.BoolFlag(ctx, featureflags.MetricsWriteFlagName)
91-
if flagErr != nil {
92-
zap.L().Error("soft failing during metrics write feature flag receive", zap.Error(flagErr))
93-
}
94-
9590
template, err := s.templateCache.GetTemplate(
9691
ctx,
9792
req.GetSandbox().GetBuildId(),
@@ -104,9 +99,8 @@ func (s *server) Create(ctx context.Context, req *orchestrator.SandboxCreateRequ
10499
return nil, fmt.Errorf("failed to get template snapshot data: %w", err)
105100
}
106101

107-
sbx, err := sandbox.ResumeSandbox(
102+
sbx, err := s.sandboxFactory.ResumeSandbox(
108103
ctx,
109-
s.networkPool,
110104
template,
111105
sandbox.Config{
112106
BaseTemplateID: req.Sandbox.BaseTemplateId,
@@ -133,8 +127,6 @@ func (s *server) Create(ctx context.Context, req *orchestrator.SandboxCreateRequ
133127
childSpan.SpanContext().TraceID().String(),
134128
req.StartTime.AsTime(),
135129
req.EndTime.AsTime(),
136-
s.devicePool,
137-
metricsWriteFlag,
138130
req.Sandbox,
139131
)
140132
if err != nil {

packages/orchestrator/internal/template/build/builder.go

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@ import (
1313

1414
"github.com/e2b-dev/infra/packages/orchestrator/internal/proxy"
1515
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox"
16-
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/nbd"
17-
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/network"
1816
sbxtemplate "github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/template"
1917
"github.com/e2b-dev/infra/packages/orchestrator/internal/template/build/buildcontext"
2018
"github.com/e2b-dev/infra/packages/orchestrator/internal/template/build/commands"
@@ -42,10 +40,9 @@ var tracer = otel.Tracer("github.com/e2b-dev/infra/packages/orchestrator/interna
4240
type Builder struct {
4341
logger *zap.Logger
4442

43+
sandboxFactory *sandbox.Factory
4544
templateStorage storage.StorageProvider
4645
buildStorage storage.StorageProvider
47-
devicePool *nbd.DevicePool
48-
networkPool *network.Pool
4946
artifactRegistry artifactsregistry.ArtifactsRegistry
5047
proxy *proxy.SandboxProxy
5148
sandboxes *smap.Map[*sandbox.Sandbox]
@@ -55,11 +52,10 @@ type Builder struct {
5552

5653
func NewBuilder(
5754
logger *zap.Logger,
55+
sandboxFactory *sandbox.Factory,
5856
templateStorage storage.StorageProvider,
5957
buildStorage storage.StorageProvider,
6058
artifactRegistry artifactsregistry.ArtifactsRegistry,
61-
devicePool *nbd.DevicePool,
62-
networkPool *network.Pool,
6359
proxy *proxy.SandboxProxy,
6460
sandboxes *smap.Map[*sandbox.Sandbox],
6561
templateCache *sbxtemplate.Cache,
@@ -70,12 +66,11 @@ func NewBuilder(
7066
templateStorage: templateStorage,
7167
buildStorage: buildStorage,
7268
artifactRegistry: artifactRegistry,
73-
devicePool: devicePool,
74-
networkPool: networkPool,
7569
proxy: proxy,
7670
sandboxes: sandboxes,
7771
templateCache: templateCache,
7872
metrics: buildMetrics,
73+
sandboxFactory: sandboxFactory,
7974
}
8075
}
8176

@@ -189,10 +184,9 @@ func runBuild(
189184
) (*Result, error) {
190185
index := cache.NewHashIndex(bc.CacheScope, builder.buildStorage, builder.templateStorage)
191186

192-
layerExecutor := layer.NewLayerExecutor(bc,
187+
layerExecutor := layer.NewLayerExecutor(
188+
bc,
193189
builder.logger,
194-
builder.networkPool,
195-
builder.devicePool,
196190
builder.templateCache,
197191
builder.proxy,
198192
builder.sandboxes,
@@ -206,12 +200,11 @@ func runBuild(
206200
builder.logger,
207201
builder.proxy,
208202
builder.templateStorage,
209-
builder.devicePool,
210-
builder.networkPool,
211203
builder.artifactRegistry,
212204
layerExecutor,
213205
index,
214206
builder.metrics,
207+
builder.sandboxFactory,
215208
)
216209

217210
commandExecutor := commands.NewCommandExecutor(
@@ -222,6 +215,7 @@ func runBuild(
222215

223216
stepBuilders := steps.CreateStepPhases(
224217
bc,
218+
builder.sandboxFactory,
225219
builder.logger,
226220
builder.proxy,
227221
layerExecutor,
@@ -232,6 +226,7 @@ func runBuild(
232226

233227
postProcessingBuilder := finalize.New(
234228
bc,
229+
builder.sandboxFactory,
235230
builder.templateStorage,
236231
builder.proxy,
237232
layerExecutor,

packages/orchestrator/internal/template/build/layer/create_sandbox.go

Lines changed: 21 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,10 @@ import (
2020

2121
// CreateSandbox creates sandboxes for new templates
2222
type CreateSandbox struct {
23-
config sandbox.Config
24-
timeout time.Duration
25-
fcVersions fc.FirecrackerVersions
23+
config sandbox.Config
24+
timeout time.Duration
25+
fcVersions fc.FirecrackerVersions
26+
sandboxFactory *sandbox.Factory
2627

2728
rootfsCachePath string
2829
}
@@ -33,12 +34,24 @@ const (
3334

3435
var _ SandboxCreator = (*CreateSandbox)(nil)
3536

36-
func NewCreateSandbox(config sandbox.Config, timeout time.Duration, fcVersions fc.FirecrackerVersions) *CreateSandbox {
37-
return &CreateSandbox{config: config, timeout: timeout, fcVersions: fcVersions, rootfsCachePath: ""}
37+
func NewCreateSandbox(config sandbox.Config, sandboxFactory *sandbox.Factory, timeout time.Duration, fcVersions fc.FirecrackerVersions) *CreateSandbox {
38+
return &CreateSandbox{
39+
config: config,
40+
sandboxFactory: sandboxFactory,
41+
timeout: timeout,
42+
fcVersions: fcVersions,
43+
rootfsCachePath: "",
44+
}
3845
}
3946

40-
func NewCreateSandboxFromCache(config sandbox.Config, timeout time.Duration, fcVersions fc.FirecrackerVersions, rootfsCachePath string) *CreateSandbox {
41-
return &CreateSandbox{config: config, timeout: timeout, fcVersions: fcVersions, rootfsCachePath: rootfsCachePath}
47+
func NewCreateSandboxFromCache(config sandbox.Config, sandboxFactory *sandbox.Factory, timeout time.Duration, fcVersions fc.FirecrackerVersions, rootfsCachePath string) *CreateSandbox {
48+
return &CreateSandbox{
49+
config: config,
50+
timeout: timeout,
51+
fcVersions: fcVersions,
52+
rootfsCachePath: rootfsCachePath,
53+
sandboxFactory: sandboxFactory,
54+
}
4255
}
4356

4457
func (cs *CreateSandbox) Sandbox(
@@ -65,10 +78,8 @@ func (cs *CreateSandbox) Sandbox(
6578
}
6679

6780
// In case of a new sandbox, base template ID is now used as the potentially exported template base ID.
68-
sbx, err := sandbox.CreateSandbox(
81+
sbx, err := cs.sandboxFactory.CreateSandbox(
6982
ctx,
70-
layerExecutor.networkPool,
71-
layerExecutor.devicePool,
7283
cs.config,
7384
sandbox.RuntimeMetadata{
7485
TemplateID: layerExecutor.Config.TemplateID,

0 commit comments

Comments
 (0)