An open-source, faster Devin alternative
TypeScript
Ship per-org GB-seconds memory usage to Segment
motatoes582482557357
diff --git a/cmd/worker/main.go b/cmd/worker/main.goindex c91ed0d5..a8f888da 100644--- a/cmd/worker/main.go+++ b/cmd/worker/main.go@@ -12,6 +12,7 @@ import ("syscall""time"+ "github.com/opensandbox/opensandbox/internal/analytics""github.com/opensandbox/opensandbox/internal/auth""github.com/opensandbox/opensandbox/internal/config""github.com/opensandbox/opensandbox/internal/db"@@ -378,9 +379,16 @@ func main() {autosaver := worker.NewWorkspaceAutosaver(mgr, autosaverSyncer, 5*time.Minute)autosaver.Start()+ // Segment analytics — ships per-org GB-seconds memory usage. nil if SEGMENT_WRITE_KEY unset.+ segmentClient := analytics.New(cfg.SegmentWriteKey)+ if segmentClient != nil {+ log.Println("opensandbox-worker: Segment analytics enabled")+ defer segmentClient.Close()+ }+// Usage collector for billing (samples cgroup stats every 60s, flushes to DB every 5 min)if store != nil {- usageCollector := worker.NewUsageCollector(mgr, store)+ usageCollector := worker.NewUsageCollector(mgr, store, segmentClient)usageCollector.Start()defer usageCollector.Stop()}diff --git a/go.mod b/go.modindex 4797ff94..13fc07f8 100644--- a/go.mod+++ b/go.mod@@ -8,6 +8,7 @@ require (github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/compute/armcompute v1.0.0github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0+ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4github.com/aws/aws-sdk-go-v2 v1.41.2github.com/aws/aws-sdk-go-v2/config v1.32.10github.com/aws/aws-sdk-go-v2/credentials v1.19.10@@ -25,6 +26,7 @@ require (github.com/nats-io/nats.go v1.48.0github.com/prometheus/client_golang v1.20.5github.com/redis/go-redis/v9 v9.18.0+ github.com/segmentio/analytics-go/v3 v3.3.0github.com/spf13/cobra v1.10.2github.com/stripe/stripe-go/v82 v82.5.1github.com/workos/workos-go/v4 v4.46.1@@ -37,7 +39,6 @@ require (require (github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirectgithub.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 // indirect- github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirectgithub.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirectgithub.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.4 // indirectgithub.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.18 // indirect@@ -55,6 +56,7 @@ require (github.com/aws/aws-sdk-go-v2/service/sts v1.41.7 // indirectgithub.com/aws/smithy-go v1.24.1 // indirectgithub.com/beorn7/perks v1.0.1 // indirect+ github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 // indirectgithub.com/cespare/xxhash/v2 v2.3.0 // indirectgithub.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirectgithub.com/golang-jwt/jwt v3.2.2+incompatible // indirect@@ -74,6 +76,7 @@ require (github.com/prometheus/client_model v0.6.1 // indirectgithub.com/prometheus/common v0.55.0 // indirectgithub.com/prometheus/procfs v0.15.1 // indirect+ github.com/segmentio/backo-go v1.0.0 // indirectgithub.com/spf13/pflag v1.0.9 // indirectgithub.com/valyala/bytebufferpool v1.0.0 // indirectgithub.com/valyala/fasttemplate v1.2.2 // indirectdiff --git a/go.sum b/go.sumindex 1fcf3cbc..1ba47037 100644--- a/go.sum+++ b/go.sum@@ -14,6 +14,8 @@ github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/network/armnetwork v1.1.0/go.mod h1:243D9iHbcQXoFUtgHJwL7gl2zx1aDuDMjvBZVGr2uW0=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0 h1:ECsQtyERDVz3NP3kvDOTLvbQhqWp/x9EsGKtb4ogUr8=github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/resources/armresources v1.0.0/go.mod h1:s1tW/At+xHqjNFvWU4G0c0Qv33KOhvbGNj0RCTQDV8s=+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1 h1:/Zt+cDPnpC3OVDm/JKLOs7M2DKmLRIIp3XIx9pHHiig=+github.com/Azure/azure-sdk-for-go/sdk/resourcemanager/storage/armstorage v1.8.1/go.mod h1:Ng3urmn6dYe8gnbCMoHHVl5APYz2txho3koEkV2o2HA=github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0 h1:/g8S6wk65vfC6m3FIxJ+i5QDyN9JWwXI8Hb0Img10hU=github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azsecrets v1.4.0/go.mod h1:gpl+q95AzZlKVI3xSoseF9QPrypk0hQqBiJYeB/cR/I=github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/internal v1.2.0 h1:nCYfgcSyHZXJI8J0IWE5MsCGlb2xp9fJiXyxWgmOFg4=@@ -68,6 +70,8 @@ github.com/aws/smithy-go v1.24.1 h1:VbyeNfmYkWoxMVpGUAbQumkODcYmfMRfZ8yQiH30SK0=github.com/aws/smithy-go v1.24.1/go.mod h1:LEj2LM3rBRQJxPZTB4KuzZkaZYnZPnvgIhb4pu07mx0=github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=+github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869 h1:DDGfHa7BWjL4YnC6+E63dPcxHo2sUxDIu8g3QgEJdRY=+github.com/bmizerany/assert v0.0.0-20160611221934-b7ed37b82869/go.mod h1:Ekp36dRnpXw/yCqJaO+ZrUyxD+3VXMFFr56k5XYrpB4=github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=@@ -116,6 +120,10 @@ github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Ztgithub.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4=github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=+github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=+github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=+github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=+github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=github.com/labstack/echo/v4 v4.12.0 h1:IKpw49IMryVB2p1a4dzwlhP1O2Tf2E0Ir/450lH+kI0=@@ -151,7 +159,13 @@ github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0leargggithub.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk=github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs=github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0=+github.com/rogpeppe/go-internal v1.12.0 h1:exVL4IDcn6na9z1rAb56Vxr+CgyK3nn3O+epU5NdKM8=+github.com/rogpeppe/go-internal v1.12.0/go.mod h1:E+RYuTGaKKdloAfM02xzb0FW3Paa99yedzYV+kq4uf4=github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=+github.com/segmentio/analytics-go/v3 v3.3.0 h1:8VOMaVGBW03pdBrj1CMFfY9o/rnjJC+1wyQHlVxjw5o=+github.com/segmentio/analytics-go/v3 v3.3.0/go.mod h1:p8owAF8X+5o27jmvUognuXxdtqvSGtD0ZrfY2kcS9bE=+github.com/segmentio/backo-go v1.0.0 h1:kbOAtGJY2DqOR0jfRkYEorx/b18RgtepGtY3+Cpe6qA=+github.com/segmentio/backo-go v1.0.0/go.mod h1:kJ9mm9YmoWSkk+oQ+5Cj8DEoRCX2JT6As4kEtIIOp1M=github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY=diff --git a/internal/analytics/segment.go b/internal/analytics/segment.gonew file mode 100644index 00000000..525c8c9d--- /dev/null+++ b/internal/analytics/segment.go@@ -0,0 +1,55 @@+// Package analytics ships per-org usage metrics to Segment.+//+// The only metric we care about is GB-seconds of memory consumed, tagged with+// the org_id (the entity being billed). Everything in this package is a no-op+// when the client is nil, so call sites don't need to branch on configuration.+package analytics++import (+ "log"++ "github.com/segmentio/analytics-go/v3"+)++// Client is a thin wrapper around the Segment Go client. The zero value and a+// nil pointer are both safe to use — Track and Close become no-ops.+type Client struct {+ c analytics.Client+}++// New returns a Client. If writeKey is empty, returns nil (no-op client).+func New(writeKey string) *Client {+ if writeKey == "" {+ return nil+ }+ return &Client{c: analytics.New(writeKey)}+}++// TrackGBSeconds enqueues a "Sandbox Memory Usage" event with GB-seconds for+// the given org. sandboxID is included as an event property for debugging but+// the metric of record is gb_seconds bucketed by org.+func (c *Client) TrackGBSeconds(orgID, sandboxID string, gbSeconds float64) {+ if c == nil || c.c == nil || orgID == "" || gbSeconds <= 0 {+ return+ }+ if err := c.c.Enqueue(analytics.Track{+ UserId: orgID,+ Event: "Sandbox Memory Usage",+ Properties: analytics.NewProperties().+ Set("gb_seconds", gbSeconds).+ Set("sandbox_id", sandboxID).+ Set("org_id", orgID),+ }); err != nil {+ log.Printf("segment: enqueue failed: %v", err)+ }+}++// Close flushes pending events. Safe on nil.+func (c *Client) Close() {+ if c == nil || c.c == nil {+ return+ }+ if err := c.c.Close(); err != nil {+ log.Printf("segment: close failed: %v", err)+ }+}diff --git a/internal/config/config.go b/internal/config/config.goindex 5d84cd33..4f205200 100644--- a/internal/config/config.go+++ b/internal/config/config.go@@ -103,6 +103,9 @@ type Config struct {StripeSuccessURL stringStripeCancelURL string+ // Segment analytics — if set, GB-minute usage events are shipped per org.+ SegmentWriteKey string+// AWS Secrets Manager — if set, secrets are fetched at startup using IAM credentials.// The secret should be a JSON object with keys matching env var names (e.g. OPENSANDBOX_JWT_SECRET).// Env vars take precedence over secret values (for local overrides).@@ -194,6 +197,8 @@ func Load() (*Config, error) {StripeSuccessURL: envOrDefault("STRIPE_SUCCESS_URL", "http://localhost:3000/billing?success=true"),StripeCancelURL: envOrDefault("STRIPE_CANCEL_URL", "http://localhost:3000/billing?cancelled=true"),+ SegmentWriteKey: os.Getenv("SEGMENT_WRITE_KEY"),+SecretsARN: os.Getenv("OPENSANDBOX_SECRETS_ARN"),SecretEncryptionKey: os.Getenv("OPENSANDBOX_SECRET_ENCRYPTION_KEY"),diff --git a/internal/worker/usage_collector.go b/internal/worker/usage_collector.goindex 1f42363e..e03351cb 100644--- a/internal/worker/usage_collector.go+++ b/internal/worker/usage_collector.go@@ -6,6 +6,7 @@ import ("sync""time"+ "github.com/opensandbox/opensandbox/internal/analytics""github.com/opensandbox/opensandbox/internal/db""github.com/opensandbox/opensandbox/internal/sandbox")@@ -15,8 +16,9 @@ import (type UsageCollector struct {manager sandbox.Managerstore *db.Store- interval time.Duration // how often to sample (default 60s)- flushN int // flush to DB every N samples (default 5 = every 5 min)+ segment *analytics.Client // optional; nil = no Segment shipping+ interval time.Duration // how often to sample (default 60s)+ flushN int // flush to DB every N samples (default 5 = every 5 min)mu sync.Mutexbuffer []db.UsageSample@@ -26,10 +28,12 @@ type UsageCollector struct {}// NewUsageCollector creates a collector that samples every interval.-func NewUsageCollector(manager sandbox.Manager, store *db.Store) *UsageCollector {+// segment may be nil to disable analytics shipping.+func NewUsageCollector(manager sandbox.Manager, store *db.Store, segment *analytics.Client) *UsageCollector {return &UsageCollector{manager: manager,store: store,+ segment: segment,interval: 60 * time.Second,flushN: 5,stopCh: make(chan struct{}),@@ -77,6 +81,7 @@ func (c *UsageCollector) sample() {}now := time.Now()+ intervalSec := c.interval.Seconds()var samples []db.UsageSamplefor _, sb := range sandboxes {@@ -85,15 +90,26 @@ func (c *UsageCollector) sample() {continue // sandbox might be shutting down}+ orgID, err := c.store.GetSandboxOrgID(ctx, sb.ID)+ if err != nil || orgID == "" {+ continue // no billable owner, skip+ }+samples = append(samples, db.UsageSample{SandboxID: sb.ID,- OrgID: "00000000-0000-0000-0000-000000000001", // TODO: get from sandbox session+ OrgID: orgID,SampledAt: now,MemoryMB: sb.MemoryMB,CPUUsec: 0, // TODO: parse from cgroup cpu.statMemoryBytes: int64(stats.MemUsage),PIDs: int(stats.PIDs),})++ // Ship to Segment: GB-seconds based on PROVISIONED memory (the tier the+ // customer reserved), not actual RSS. Reservation is what we bill for —+ // actual usage is gameable and punishes well-behaved tenants.+ gbSeconds := (float64(sb.MemoryMB) / 1024.0) * intervalSec+ c.segment.TrackGBSeconds(orgID, sb.ID, gbSeconds)}if len(samples) == 0 {