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 35 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
30 changes: 30 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.

106 changes: 54 additions & 52 deletions packages/api/internal/api/spec.gen.go

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

18 changes: 18 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.

103 changes: 103 additions & 0 deletions packages/api/internal/handlers/sanbox_metrics.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
package handlers

import (
"encoding/json"
"fmt"
"net/http"
"slices"
"strings"
"time"

"github.com/gin-gonic/gin"
"github.com/grafana/loki/pkg/loghttp"
"github.com/grafana/loki/pkg/logproto"
"go.opentelemetry.io/otel/attribute"

"github.com/e2b-dev/infra/packages/api/internal/api"
"github.com/e2b-dev/infra/packages/api/internal/auth"
authcache "github.com/e2b-dev/infra/packages/api/internal/cache/auth"
"github.com/e2b-dev/infra/packages/api/internal/utils"
"github.com/e2b-dev/infra/packages/shared/pkg/telemetry"
)

func (a *APIStore) GetSandboxesSandboxIDMetrics(
c *gin.Context,
sandboxID string,
) {
ctx := c.Request.Context()
sandboxID = utils.ShortID(sandboxID)

teamID := c.Value(auth.TeamContextKey).(authcache.AuthTeamInfo).Team.ID

telemetry.SetAttributes(ctx,
attribute.String("instance.id", sandboxID),
attribute.String("team.id", teamID.String()),
)

end := time.Now()
start := end.Add(-oldestLogsLimit)

// Sanitize ID
// https://grafana.com/blog/2021/01/05/how-to-escape-special-characters-with-lokis-logql/
id := strings.ReplaceAll(sandboxID, "`", "")

// equivalent CLI query:
// logcli query '{source="logs-collector", service="envd", teamID="65d165ab-69f6-4b5c-9165-6b93cd341503", sandboxID="izuhqjlfabd8ataeixrtl", category="metrics"}' --from="2025-01-19T10:00:00Z"
query := fmt.Sprintf(
"{source=\"logs-collector\", service=\"envd\", teamID=\"%s\", sandboxID=\"%s\", category=\"metrics\"}", teamID.String(), id)

res, err := a.lokiClient.QueryRange(query, 100, start, end, logproto.FORWARD, time.Duration(0), time.Duration(0), true)
if err != nil {
errMsg := fmt.Errorf("error when returning metrics for sandbox: %w\tquery:%s", err, query)
0div marked this conversation as resolved.
Show resolved Hide resolved
telemetry.ReportCriticalError(ctx, errMsg)
a.sendAPIStoreError(c, http.StatusNotFound, fmt.Sprintf("Error returning metrics for sandbox '%s'", sandboxID))

return
}

switch res.Data.Result.Type() {
case loghttp.ResultTypeStream:
value := res.Data.Result.(loghttp.Streams)

metrics := make([]api.SandboxMetric, 0)

for _, stream := range value {
for _, entry := range stream.Entries {

var metric struct {
CPUPct float32 `json:"cpuPct"`
CPUCount int32 `json:"cpuCount"`
MemTotalMiB int64 `json:"memTotalMiB"`
MemUsedMiB int64 `json:"memUsedMiB"`
}

err := json.Unmarshal([]byte(entry.Line), &metric)
if err != nil {
telemetry.ReportCriticalError(ctx, fmt.Errorf("failed to unmarshal metric: %w", err))
continue
}
metrics = append(metrics, api.SandboxMetric{
Timestamp: entry.Timestamp,
CpuPct: metric.CPUPct,
CpuCount: metric.CPUCount,
MemMiBTotal: metric.MemTotalMiB,
MemMiBUsed: metric.MemUsedMiB,
})
}
}

// Sort metrics by timestamp (they are returned by the time they arrived in Loki)
slices.SortFunc(metrics, func(a, b api.SandboxMetric) int {
return a.Timestamp.Compare(b.Timestamp)
})

c.JSON(http.StatusOK, metrics)

default:
errMsg := fmt.Errorf("unexpected value type %T", res.Data.Result.Type())
telemetry.ReportCriticalError(ctx, errMsg)
a.sendAPIStoreError(c, http.StatusInternalServerError, fmt.Sprintf("Error returning metrics for sandbox '%s", sandboxID))

return
}
}
24 changes: 18 additions & 6 deletions packages/envd/internal/host/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@ 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
Timestamp int64 `json:"ts"` // Unix Timestamp in UTC
CPUTotal uint32 `json:"cpu_total"` // Total CPU cores
CPUPercent float64 `json:"cpu_pct"` // Percent rounded to 2 decimal places
MemTotalMiB uint64 `json:"mem_total_mib"` // Total virtual memory in MiB
MemUsedMiB uint64 `json:"mem_used_mib"` // Used virtual memory in MiB
}

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

memUsedMiB := v.Used / 1024 / 1024
memTotalMiB := v.Total / 1024 / 1024

cpuTotal, err := cpu.Counts(true)
if err != nil {
return nil, err
}

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

return &Metrics{
CPU: cpuPctRounded,
Mem: v.Total,
Timestamp: time.Now().UTC().Unix(),
Timestamp: time.Now().UTC().Unix(),
CPUTotal: uint32(cpuTotal),
CPUPercent: cpuPctRounded,
MemUsedMiB: memUsedMiB,
MemTotalMiB: memTotalMiB,
}, 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.4"
Version = "0.1.5"

debug bool
port int64
Expand Down
1 change: 1 addition & 0 deletions packages/nomad/logs-collector.hcl
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,7 @@ service = "{{ service }}"
teamID = "{{ teamID }}"
envID = "{{ envID }}"
sandboxID = "{{ sandboxID }}"
category = "{{ category }}"

%{ if var.grafana_logs_endpoint != " " }
[sinks.grafana]
Expand Down
Loading