Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Periodically capture resource metrics for every sandbox #216

Merged
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
47 commits
Select commit Hold shift + click to select a range
749fbf2
make metrics struct more readable and bump env version
0div Dec 5, 2024
882f847
update orchestrator checks to use ticker and check metrics at differe…
0div Dec 5, 2024
c1c4994
add logger methods to log cpu percent and memory MB
0div Dec 5, 2024
203e525
log metrics on start and on end; reduce httpClient timeout to one second
0div Dec 5, 2024
290bbd3
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Dec 6, 2024
419b581
check if envd version is correct on every metrics log attempt
0div Dec 6, 2024
ff936ff
make CPU and MEM logger send event
0div Dec 6, 2024
f49461a
address PR comments
0div Dec 6, 2024
5ccbb3d
Update packages/envd/internal/host/metrics.go
0div Dec 6, 2024
2baee66
Update packages/envd/internal/host/metrics.go
0div Dec 6, 2024
805b77d
fix old method name
0div Dec 6, 2024
3c0343f
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Dec 6, 2024
c705e1c
remove legacu stats logic
0div Dec 6, 2024
9c94a61
specify platform/arch in docker image tf resrource to avoid docker pu…
0div Dec 6, 2024
5f859c6
report more memory data for debugging purposes; attempt to calculte f…
0div Dec 7, 2024
5df1d59
Update packages/shared/pkg/logs/logger.go
0div Dec 9, 2024
d1df2ac
Update packages/shared/pkg/logs/logger.go
0div Dec 9, 2024
1eb4d77
Update packages/shared/pkg/logs/logger.go
0div Dec 9, 2024
d7589b2
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Dec 9, 2024
27e9859
address PR review comments
0div Dec 9, 2024
c1294a1
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Dec 16, 2024
bbd42e6
add metrics endpoint to api spec and generate
0div Dec 17, 2024
9f44dc9
unmarshall log line into metric
0div Dec 18, 2024
4736cdf
fix merge conflicts
0div Jan 17, 2025
562e22c
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 17, 2025
11880e6
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 18, 2025
a3034c1
* add cpuTotal to spec
0div Jan 18, 2025
fc49ae0
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 20, 2025
8545560
update metrics model and fix logger
0div Jan 20, 2025
017eb99
update envd minor version
0div Jan 20, 2025
80be000
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 20, 2025
698f010
fix spec typos and Sandbox properties in checks
0div Jan 21, 2025
f4a3bd8
bump version of envd for version checks of the metrics endpoint
0div Jan 21, 2025
0269598
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 22, 2025
9bd0db4
use "category" label and update log-collector sink to index it
0div Jan 22, 2025
edb28c5
fix naming mismatch and log all cpu and mem in same row
0div Jan 23, 2025
84cf9d6
Fix spacing in envd.yaml
jakubno Jan 23, 2025
044ca36
Fix typo
jakubno Jan 24, 2025
4d544bd
Increase cpu for logs collector
jakubno Jan 24, 2025
66a07a9
lower metrics interval to 2s; update cpuPct field to cpuUsedPct
0div Jan 24, 2025
5468546
Merge branch 'periodically-capture-resource-metrics-for-every-sandbox…
0div Jan 24, 2025
63b33e8
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 24, 2025
e83d1c3
Regenerate API
jakubno Jan 24, 2025
585efe6
Update spec
jakubno Jan 24, 2025
17ef0a5
fix typo cpuUsedPCt
0div Jan 24, 2025
41a5011
Merge branch 'main' of https://github.com/e2b-dev/infra into periodic…
0div Jan 24, 2025
8c1fbbd
remove debug log and escape loki query params
0div Jan 24, 2025
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
14 changes: 8 additions & 6 deletions packages/envd/internal/host/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ import (
)

type Metrics struct {
CPU float64 `json:"cpu_pct"` // Percent rounded to 2 decimal places
Mem uint64 `json:"mem_bytes"` // Total virtual memory in bytes
Timestamp int64 `json:"ts"` // Unix Timestamp in UTC
CPUPercent float64 `json:"cpu_pct"` // Percent rounded to 2 decimal places
MemMiB uint64 `json:"mem_mib"` // Total virtual memory in MiB
Timestamp int64 `json:"ts"` // Unix Timestamp in UTC
}

func GetMetrics() (*Metrics, error) {
Expand All @@ -20,6 +20,8 @@ func GetMetrics() (*Metrics, error) {
return nil, err
}

memMB := v.Total / 1024 / 1024
0div marked this conversation as resolved.
Show resolved Hide resolved

cpuPcts, err := cpu.Percent(0, false)
if err != nil {
return nil, err
Expand All @@ -32,8 +34,8 @@ func GetMetrics() (*Metrics, error) {
}

return &Metrics{
CPU: cpuPctRounded,
Mem: v.Total,
Timestamp: time.Now().UTC().Unix(),
CPUPercent: cpuPctRounded,
MemMiB: memMB,
0div marked this conversation as resolved.
Show resolved Hide resolved
Timestamp: time.Now().UTC().Unix(),
}, nil
}
2 changes: 1 addition & 1 deletion packages/envd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const (

var (
// These vars are automatically set by goreleaser.
Version = "0.1.2"
Version = "0.1.3"

debug bool
port int64
Expand Down
74 changes: 73 additions & 1 deletion packages/orchestrator/internal/sandbox/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,37 @@ package sandbox

import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"

"github.com/e2b-dev/infra/packages/shared/pkg/consts"
"github.com/e2b-dev/infra/packages/shared/pkg/utils"
"golang.org/x/mod/semver"
)

const (
healthCheckInterval = 10 * time.Second
metricsCheckInterval = 5 * time.Second
minEnvdVersionForMetrcis = "0.1.3"
0div marked this conversation as resolved.
Show resolved Hide resolved
)

func (s *Sandbox) logHeathAndUsage(ctx *utils.LockableCancelableContext) {
healthTicker := time.NewTicker(healthCheckInterval)
metricsTicker := time.NewTicker(metricsCheckInterval)
defer func() {
healthTicker.Stop()
metricsTicker.Stop()
}()

// Get metrics on sandbox startup
go s.LogMetrics(ctx)
0div marked this conversation as resolved.
Show resolved Hide resolved

for {
select {
case <-time.After(10 * time.Second):
case <-healthTicker.C:
childCtx, cancel := context.WithTimeout(ctx, time.Second)

ctx.Lock()
Expand All @@ -30,6 +48,8 @@ func (s *Sandbox) logHeathAndUsage(ctx *utils.LockableCancelableContext) {
s.Logger.CPUUsage(stats.CPUCount)
s.Logger.MemoryUsage(stats.MemoryMB)
}
case <-metricsTicker.C:
s.LogMetrics(ctx)
case <-ctx.Done():
return
}
Expand Down Expand Up @@ -65,3 +85,55 @@ func (s *Sandbox) Healthcheck(ctx context.Context, alwaysReport bool) {
return
}
}

func (s *Sandbox) GetMetrics(ctx context.Context) (SandboxMetrics, error) {
address := fmt.Sprintf("http://%s:%d/metrics", s.slot.HostIP(), consts.DefaultEnvdServerPort)

request, err := http.NewRequestWithContext(ctx, "GET", address, nil)
if err != nil {
return SandboxMetrics{}, err
}

response, err := httpClient.Do(request)
if err != nil {
return SandboxMetrics{}, err
}
defer response.Body.Close()

if response.StatusCode != http.StatusOK {
err = fmt.Errorf("unexpected status code: %d", response.StatusCode)
return SandboxMetrics{}, err
}

var metrics SandboxMetrics
err = json.NewDecoder(response.Body).Decode(&metrics)
if err != nil {
return SandboxMetrics{}, err
}

return metrics, nil
}

func (s *Sandbox) LogMetrics(ctx context.Context) {
if isGTEVersion(s.Sandbox.EnvdVersion, minEnvdVersionForMetrcis) {
metrics, err := s.GetMetrics(ctx)
if err != nil {
s.Logger.Warnf("failed to get metrics: %s", err)
} else {
s.Logger.CPUPct(metrics.CPUPercent)
s.Logger.MemMB(metrics.MemMiB)
}
}
}

func isGTEVersion(curVersion, minVersion string) bool {
if len(curVersion) > 0 && curVersion[0] != 'v' {
curVersion = "v" + curVersion
}

if !semver.IsValid(curVersion) {
return false
}

return semver.Compare(curVersion, minVersion) >= 0
}
7 changes: 7 additions & 0 deletions packages/orchestrator/internal/sandbox/metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package sandbox

type SandboxMetrics struct {
CPUPercent float64 `json:"cpu_pct"` // Percent rounded to 2 decimal places
MemMiB uint64 `json:"mem_mib"` // Total virtual memory in MiB
Timestamp int64 `json:"ts"` // Unix Timestamp in UTC
}
6 changes: 3 additions & 3 deletions packages/orchestrator/internal/sandbox/sandbox.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
consul "github.com/hashicorp/consul/api"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"golang.org/x/mod/semver"

"github.com/e2b-dev/infra/packages/orchestrator/internal/dns"
"github.com/e2b-dev/infra/packages/orchestrator/internal/sandbox/uffd"
Expand All @@ -29,10 +28,11 @@ const (
kernelMountDir = "/fc-vm"
kernelName = "vmlinux.bin"
fcBinaryName = "firecracker"
newEnvdVersion = "v0.1.1"
)

var httpClient = http.Client{
Timeout: 5 * time.Second,
Timeout: time.Second,
jakubno marked this conversation as resolved.
Show resolved Hide resolved
}

type Sandbox struct {
Expand Down Expand Up @@ -245,7 +245,7 @@ func NewSandbox(
telemetry.ReportEvent(childCtx, "ensuring clock sync")

// Sync envds.
if semver.Compare(fmt.Sprintf("v%s", config.EnvdVersion), "v0.1.1") >= 0 {
if isGTEVersion(config.EnvdVersion, newEnvdVersion) {
err = instance.initEnvd(ctx, tracer, config.EnvVars)
if err != nil {
return nil, fmt.Errorf("failed to init new envd: %w", err)
Expand Down
2 changes: 2 additions & 0 deletions packages/orchestrator/internal/server/sandboxes.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,9 @@ func (s *server) Delete(ctx context.Context, in *orchestrator.SandboxRequest) (*
return nil, status.New(codes.NotFound, errMsg.Error()).Err()
}

// Check health metrics before stopping the sandbox
sbx.Healthcheck(ctx, true)
sbx.LogMetrics(ctx)
0div marked this conversation as resolved.
Show resolved Hide resolved

childSpan.SetAttributes(
attribute.String("env.id", sbx.Sandbox.TemplateID),
Expand Down
46 changes: 33 additions & 13 deletions packages/shared/pkg/logs/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ type SandboxLogger struct {
teamID string
cpuMax int32
cpuWasAboveTreshold atomic.Bool
memoryMBMax int32
memoryMiBMax int32
memoryWasAbove atomic.Int32
healthCheckWasFailing atomic.Bool
}
Expand All @@ -83,13 +83,13 @@ func NewSandboxLogger(
) *SandboxLogger {
sbxLogExporter := getSandboxLogExporter()
return &SandboxLogger{
exporter: sbxLogExporter,
instanceID: instanceID,
internal: internal,
envID: envID,
teamID: teamID,
cpuMax: cpuMax,
memoryMBMax: memoryMax,
exporter: sbxLogExporter,
instanceID: instanceID,
internal: internal,
envID: envID,
teamID: teamID,
cpuMax: cpuMax,
memoryMiBMax: memoryMax,
}
}

Expand All @@ -107,7 +107,7 @@ func (l *SandboxLogger) GetInternalLogger() *SandboxLogger {
return l
}

return NewSandboxLogger(l.instanceID, l.envID, l.teamID, l.cpuMax, l.memoryMBMax, true)
return NewSandboxLogger(l.instanceID, l.envID, l.teamID, l.cpuMax, l.memoryMiBMax, true)
}

func (l *SandboxLogger) Errorf(
Expand Down Expand Up @@ -165,20 +165,40 @@ func (l *SandboxLogger) CPUUsage(cpu float64) {

func (l *SandboxLogger) MemoryUsage(memoryMB float64) {
0div marked this conversation as resolved.
Show resolved Hide resolved
// Cap at memoryMBMax
memoryMB = math.Min(memoryMB, float64(l.memoryMBMax))
if memoryMB > memoryUsageThreshold*float64(l.memoryMBMax) && int32(memoryMB) > l.memoryWasAbove.Load() {
memoryMB = math.Min(memoryMB, float64(l.memoryMiBMax))
if memoryMB > memoryUsageThreshold*float64(l.memoryMiBMax) && int32(memoryMB) > l.memoryWasAbove.Load() {
0div marked this conversation as resolved.
Show resolved Hide resolved
l.memoryWasAbove.Store(int32(memoryMB))
l.exporter.logger.Warn().
Str("instanceID", l.instanceID).
Str("envID", l.envID).
Str("teamID", l.teamID).
Float64("memoryMBUsed", memoryMB).
Int32("memoryMBTotal", l.memoryMBMax).
Msgf("Sandbox memory used %d %% of RAM", int(memoryMB/float64(l.memoryMBMax)*100))
Int32("memoryMBTotal", l.memoryMiBMax).
0div marked this conversation as resolved.
Show resolved Hide resolved
Msgf("Sandbox memory used %d %% of RAM", int(memoryMB/float64(l.memoryMiBMax)*100))
return
}
}

func (l *SandboxLogger) CPUPct(cpuPct float64) {
l.exporter.logger.Info().
Str("instanceID", l.instanceID).
Str("envID", l.envID).
Str("teamID", l.teamID).
Float64("cpuPct", cpuPct).
Int32("cpuCount", l.cpuMax).
Msg("CPU usage")
}

func (l *SandboxLogger) MemMiB(memMiB uint64) {
l.exporter.logger.Info().
Str("instanceID", l.instanceID).
Str("envID", l.envID).
Str("teamID", l.teamID).
Uint64("memMiBUsed", memMiB).
Int32("memoryMiBTotal", l.memoryMiBMax).
Msg("Memory usage")
}

func (l *SandboxLogger) Healthcheck(ok bool, alwaysReport bool) {
if !ok && !l.healthCheckWasFailing.Load() {
l.healthCheckWasFailing.Store(true)
Expand Down