|
| 1 | +package sandbox |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + |
| 6 | + "go.opentelemetry.io/otel/attribute" |
| 7 | + "go.opentelemetry.io/otel/metric" |
| 8 | + |
| 9 | + "github.com/e2b-dev/infra/packages/shared/pkg/storage/header" |
| 10 | + "github.com/e2b-dev/infra/packages/shared/pkg/telemetry" |
| 11 | + "github.com/e2b-dev/infra/packages/shared/pkg/utils" |
| 12 | +) |
| 13 | + |
| 14 | +var ( |
| 15 | + snapshotDiffBytes = utils.Must(telemetry.GetHistogram(meter, telemetry.SnapshotDiffBytes)) |
| 16 | + snapshotDiffRatioBp = utils.Must(telemetry.GetHistogram(meter, telemetry.SnapshotDiffRatioBp)) |
| 17 | + snapshotTotalBytes = utils.Must(telemetry.GetHistogram(meter, telemetry.SnapshotTotalBytes)) |
| 18 | +) |
| 19 | + |
| 20 | +type SnapshotUseCase string |
| 21 | + |
| 22 | +const ( |
| 23 | + SnapshotUseCasePause SnapshotUseCase = "pause" |
| 24 | + SnapshotUseCaseBuild SnapshotUseCase = "build" |
| 25 | +) |
| 26 | + |
| 27 | +func recordSnapshotDiff( |
| 28 | + ctx context.Context, |
| 29 | + fileType string, |
| 30 | + dm *header.DiffMetadata, |
| 31 | + original *header.Header, |
| 32 | + useCase SnapshotUseCase, |
| 33 | +) { |
| 34 | + if dm == nil || original == nil || original.Metadata == nil { |
| 35 | + return |
| 36 | + } |
| 37 | + bs := int64(original.Metadata.BlockSize) |
| 38 | + total := int64(original.Metadata.Size) |
| 39 | + |
| 40 | + ft := attribute.String("file_type", fileType) |
| 41 | + uc := attribute.String("use_case", string(useCase)) |
| 42 | + |
| 43 | + snapshotTotalBytes.Record(ctx, total, metric.WithAttributes(ft, uc)) |
| 44 | + |
| 45 | + var dirtyBytes, emptyBytes int64 |
| 46 | + if dm.Dirty != nil { |
| 47 | + dirtyBytes = int64(dm.Dirty.GetCardinality()) * bs |
| 48 | + } |
| 49 | + if dm.Empty != nil { |
| 50 | + emptyBytes = int64(dm.Empty.GetCardinality()) * bs |
| 51 | + } |
| 52 | + for kind, b := range map[string]int64{ |
| 53 | + "dirty": dirtyBytes, |
| 54 | + "empty": emptyBytes, |
| 55 | + } { |
| 56 | + attrs := metric.WithAttributes(ft, attribute.String("kind", kind), uc) |
| 57 | + snapshotDiffBytes.Record(ctx, b, attrs) |
| 58 | + snapshotDiffRatioBp.Record(ctx, ratioBp(b, total), attrs) |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +// ratioBp returns num/denom in basis points (10000 = 100.00%) so we keep |
| 63 | +// sub-percent resolution. Grafana panels divide by 100 to display percent. |
| 64 | +func ratioBp(num, denom int64) int64 { |
| 65 | + if denom <= 0 { |
| 66 | + return 0 |
| 67 | + } |
| 68 | + bp := num * 10000 / denom |
| 69 | + if bp < 0 { |
| 70 | + return 0 |
| 71 | + } |
| 72 | + if bp > 10000 { |
| 73 | + return 10000 |
| 74 | + } |
| 75 | + |
| 76 | + return bp |
| 77 | +} |
0 commit comments