Skip to content
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 34 additions & 0 deletions packages/api/internal/api/api.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

189 changes: 95 additions & 94 deletions packages/api/internal/api/spec.gen.go

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions packages/api/internal/api/types.gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions packages/api/internal/cache/instance/instance.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,14 @@ func (i *InstanceInfo) LoggerMetadata() sbxlogger.SandboxMetadata {
}
}

func (i *InstanceInfo) Lock() {
i.mu.Lock()
}

func (i *InstanceInfo) Unlock() {
i.mu.Unlock()
}

func (i *InstanceInfo) IsExpired() bool {
i.mu.RLock()
defer i.mu.RUnlock()
Expand Down
92 changes: 92 additions & 0 deletions packages/api/internal/handlers/sandbox_update.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package handlers

import (
"fmt"
"net/http"

"github.com/gin-gonic/gin"
"go.uber.org/zap"

"github.com/e2b-dev/infra/packages/api/internal/api"
"github.com/e2b-dev/infra/packages/api/internal/utils"
"github.com/e2b-dev/infra/packages/db/queries"
"github.com/e2b-dev/infra/packages/db/types"
"github.com/e2b-dev/infra/packages/shared/pkg/logger"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
)

func (a *APIStore) PutSandboxesSandboxIDMetadata(
c *gin.Context,
sandboxID api.SandboxID,
) {
ctx := c.Request.Context()
sandboxID = utils.ShortID(sandboxID)

// Get team from context
teamID := a.GetTeamInfo(c).Team.ID

metadata, err := utils.ParseBody[api.PutSandboxesSandboxIDMetadataJSONRequestBody](ctx, c)
if err != nil {
a.sendAPIStoreError(c, http.StatusBadRequest, fmt.Sprintf("Error when parsing request: %s", err))

telemetry.ReportCriticalError(ctx, "error when parsing request", err)

return
}

telemetry.SetAttributes(ctx,
telemetry.WithSandboxID(sandboxID),
telemetry.WithTeamID(teamID.String()),
)

sbx, err := a.orchestrator.GetSandbox(sandboxID)
if err == nil {
// Verify the sandbox belongs to the team
if sbx.TeamID != teamID {
telemetry.ReportCriticalError(ctx, fmt.Sprintf("sandbox '%s' doesn't belong to team '%s'", sandboxID, teamID.String()), nil)
a.sendAPIStoreError(c, http.StatusUnauthorized, fmt.Sprintf("Error updating sandbox - sandbox '%s' does not belong to your team '%s'", sandboxID, teamID.String()))

return
}

sbx.Lock()
defer sbx.Unlock()

apiErr := a.orchestrator.UpdateSandboxMetadata(ctx, sbx, metadata)
if apiErr != nil {
telemetry.ReportError(ctx, "error when updating sandbox metadata", apiErr.Err)
a.sendAPIStoreError(c, apiErr.Code, apiErr.ClientMsg)

return
}
} else {
// Sandbox not found in cache, might be paused
// Try to update the snapshot metadata in the database
zap.L().Debug("Sandbox not found in cache, checking if it's paused",
logger.WithSandboxID(sandboxID),
zap.String("team.id", teamID.String()))

updated, err := a.sqlcDB.UpdateSnapshotMetadata(ctx, queries.UpdateSnapshotMetadataParams{
SandboxID: sandboxID,
TeamID: teamID,
Metadata: types.JSONBStringMap(metadata),
})
if err != nil {
telemetry.ReportCriticalError(ctx, "error when updating paused sandbox metadata", err)
a.sendAPIStoreError(c, http.StatusInternalServerError, fmt.Sprintf("Error when updating paused sandbox metadata: %s", err))

return
}

if len(updated) == 0 {
telemetry.ReportCriticalError(ctx, "sandbox not found", nil)
a.sendAPIStoreError(c, http.StatusNotFound, fmt.Sprintf("Sandbox '%s' not found", sandboxID))

return
}

telemetry.ReportEvent(ctx, "Updated paused sandbox metadata")
}

c.Status(http.StatusOK)
}
55 changes: 55 additions & 0 deletions packages/api/internal/orchestrator/update_sandbox_metadata.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
package orchestrator

import (
"context"
"net/http"

"github.com/e2b-dev/infra/packages/api/internal/api"
"github.com/e2b-dev/infra/packages/api/internal/cache/instance"
"github.com/e2b-dev/infra/packages/api/internal/utils"
"github.com/e2b-dev/infra/packages/shared/pkg/grpc/orchestrator"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
)

func (o *Orchestrator) UpdateSandboxMetadata(
ctx context.Context,
sbx *instance.InstanceInfo,
metadata map[string]string,
) *api.APIError {
Comment on lines +14 to +18
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is there a missing lock for concurrent metadata updates? e.g. first request succeeds second on the orchestrator, but second request sets the metadata on the API -> inconsistency

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I refactor how we lock, now if there's some handler or background process working with sandbox it should always acquire lock

childCtx, childSpan := o.tracer.Start(ctx, "update-sandbox-metadata")
defer childSpan.End()

client, childCtx, err := o.GetClient(childCtx, sbx.ClusterID, sbx.NodeID)
if err != nil {
return &api.APIError{
Err: err,
ClientMsg: "Failed to connect to sandbox node",
Code: http.StatusInternalServerError,
}
}

// Replace metadata completely instead of merging
// Send metadata to the orchestrator first - don't update local cache until success
_, err = client.Sandbox.Update(
childCtx, &orchestrator.SandboxUpdateRequest{
SandboxId: sbx.SandboxID,
Metadata: metadata,
},
)

err = utils.UnwrapGRPCError(err)
if err != nil {
return &api.APIError{
Err: err,
ClientMsg: "Failed to update sandbox metadata",
Code: http.StatusInternalServerError,
}
}

// Only update local cache after orchestrator call succeeds
sbx.Metadata = metadata

telemetry.ReportEvent(childCtx, "Updated running sandbox metadata")

return nil
}
7 changes: 7 additions & 0 deletions packages/db/queries/update_snapshot_metadata.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
-- name: UpdateSnapshotMetadata :many
UPDATE "public"."snapshots" s
SET metadata = $3
FROM "public"."envs" e
WHERE s.env_id = e.id
AND s.sandbox_id = $1
AND e.team_id = $2 RETURNING s.id;
48 changes: 48 additions & 0 deletions packages/db/queries/update_snapshot_metadata.sql.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/orchestrator/internal/sandbox/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"net/http"
"os"
"sync"
"time"

"github.com/google/uuid"
Expand Down Expand Up @@ -89,6 +90,8 @@ type Sandbox struct {
*Resources
*Metadata

Mu sync.Mutex

files *storage.SandboxFiles
cleanup *Cleanup

Expand Down
45 changes: 38 additions & 7 deletions packages/orchestrator/internal/server/sandboxes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package server
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
Expand Down Expand Up @@ -181,6 +182,11 @@ func (s *server) Create(ctxConn context.Context, req *orchestrator.SandboxCreate
}, nil
}

type eventData struct {
SetTimeout string `json:"set_timeout,omitempty"`
Metadata map[string]string `json:"metadata,omitempty"`
}

func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequest) (*emptypb.Empty, error) {
ctx, childSpan := s.tracer.Start(ctx, "sandbox-update")
defer childSpan.End()
Expand All @@ -197,18 +203,37 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ
return nil, status.Error(codes.NotFound, "sandbox not found")
}

item.EndAt = req.EndTime.AsTime()
item.Mu.Lock()
defer item.Mu.Unlock()

updated := false

event := &eventData{}
// Update end time if provided
if req.EndTime != nil {
item.EndAt = req.EndTime.AsTime()
updated = true
event.SetTimeout = req.EndTime.AsTime().Format(time.RFC3339)

telemetry.ReportEvent(ctx, "Updated sandbox timeout")
}

// Update metadata if provided
if req.Metadata != nil {
item.APIStoredConfig.Metadata = req.Metadata
updated = true
event.Metadata = req.Metadata

// TODO: adapt to new types of update events
eventData := fmt.Sprintf(`{"set_timeout": "%s"}`, req.EndTime.AsTime().Format(time.RFC3339))
telemetry.ReportEvent(ctx, "Updated sandbox metadata")
}

sandboxLifeCycleEventsWriteFlag, flagErr := s.featureFlags.BoolFlag(
featureflags.SandboxLifeCycleEventsWriteFlagName, item.Runtime.SandboxID)
if flagErr != nil {
zap.L().Error("soft failing during sandbox lifecycle events write feature flag receive", zap.Error(flagErr))
}
if sandboxLifeCycleEventsWriteFlag {
go func(eventData string) {
if updated && sandboxLifeCycleEventsWriteFlag {
go func() {
buildId := ""
if item.APIStoredConfig != nil {
buildId = item.APIStoredConfig.BuildId
Expand All @@ -220,6 +245,12 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ
return
}

eventDataMarshalled, err := json.Marshal(event)
if err != nil {
sbxlogger.I(item).Error("error marshaling sandbox lifecycle event", zap.Error(err))
return
}

err = s.sandboxEventBatcher.Push(clickhouse.SandboxEvent{
Timestamp: time.Now().UTC(),
SandboxID: item.Runtime.SandboxID,
Expand All @@ -229,13 +260,13 @@ func (s *server) Update(ctx context.Context, req *orchestrator.SandboxUpdateRequ
SandboxExecutionID: item.Runtime.ExecutionID,
EventCategory: string(clickhouse.SandboxEventCategoryLifecycle),
EventLabel: string(clickhouse.SandboxEventLabelUpdate),
EventData: sql.NullString{String: eventData, Valid: true},
EventData: sql.NullString{String: string(eventDataMarshalled), Valid: true},
})
if err != nil {
sbxlogger.I(item).Error(
"error inserting sandbox lifecycle event", zap.String("event_label", string(clickhouse.SandboxEventLabelUpdate)), zap.Error(err))
}
}(eventData)
}()
}

return &emptypb.Empty{}, nil
Expand Down
Loading
Loading