remote-instance-metrics: console shows a remote reading only with its tenant's tag
Remote rows read only samples their box tagged with the record's own account and app, since the record's created_at: the newest sample must carry the tag, and graphs are drawn from tagged samples alone. carlos instances list counts a tagged reading as awake, as the Running tab does. Local rows are unchanged. Note review round 2 (Astra): READY AFTER FIXES; its P2 (remote-only views can now start the existing sweep) is documented and pinned by TestRemoteMetricsRequestBudget.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
10 files changed,
+665
−58
docs/superpowers/notes/remote-instance-metrics.md+23 −7docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md+17 −0internal/console/apiinstances.go+40 −7internal/console/metricsview.go+88 −14internal/console/remoteinstances.go+8 −3internal/console/remoteinstances_round2_test.go+1 −1internal/console/remoteinstances_round6_test.go+13 −8internal/console/remotemetrics_test.go+448 −0internal/console/server.go+12 −8internal/console/view.go+15 −10
diff --git a/docs/superpowers/notes/remote-instance-metrics.md b/docs/superpowers/notes/remote-instance-metrics.md| index 336afff76..e9bd0b6c4 100644 |
| --- a/docs/superpowers/notes/remote-instance-metrics.md |
| +++ b/docs/superpowers/notes/remote-instance-metrics.md |
| @@ -176,13 +176,24 @@ their history is bounded by the record's `created_at` as now. |
| ## Request budget |
| -No new request anywhere. Boxes write the same chunk keys on the same |
| -five-minute flush; the console sweeps the same 48 hourly keys per box on |
| -the same cache. Steady state, nothing changing: 0 new requests per box per |
| -day, 0 new console requests. Bodies grow by about 40 bytes per tagged unit |
| -per sample: about 2.4 KB per awake instance-hour in the raw chunk. |
| - |
| -## Tests (to write first) |
| +Boxes: no new request. They write the same chunk keys on the same |
| +five-minute flush; bodies grow by about 40 bytes per tagged unit per |
| +sample, about 2.4 KB per awake instance-hour in the raw chunk. Steady |
| +state, nothing changing: 0 new requests per box per day. |
| + |
| +Console: no new kind of read and no new loop. The sweep's cost per run is |
| +unchanged (a LIST of `metrics/boxes/`, 48 hourly GETs per box, a LIST |
| +and the GETs of `alerts/boxes/`), and it still runs only when a page asks |
| +and its 60-second cache is stale, shared by every page and account. What |
| +changes is who can ask: an app whose instances all live on other boxes |
| +used to skip the sweep (`ownerAppMetricsFrom` returns before |
| +`LoadMetrics` with no hosts), and now its views read it like any app |
| +with a local instance. On a quiet console, one such view can start a |
| +sweep that would not otherwise have run; every view within the cache's |
| +minute pays nothing. Idle, with nobody browsing: 0 requests. |
| +`TestRemoteMetricsRequestBudget` pins it (Astra round 2, P2). |
| + |
| +## Tests |
| Production-wired where the code allows: |
| @@ -248,3 +259,8 @@ Round 1 (Astra, 98caa5f4): NOT READY, one P1 in the fault family. |
| tenant), which also replaced round 1's per-process checks (unproven |
| wakes, stray sidecars, incomplete stops): with one tenant ever, those |
| leftovers are the same tenant's. |
| + |
| +Round 2 (Astra, 0a90c4c3): READY AFTER FIXES. Round 1's P1 resolved. |
| +One P2 (request-budget accounting): remote-only views can now start the |
| +existing sweep. Fixed above, with `TestRemoteMetricsRequestBudget`. The |
| +note's review stops here (AGENTS.md stopping rule 1). |
diff --git a/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md| new file mode 100644 |
| index 000000000..bdaa4e827 |
| --- /dev/null |
| +++ b/docs/superpowers/reviews/CODEX-FINDINGS-remote-instance-metrics-note-r2.md |
| @@ -0,0 +1,17 @@ |
| +Round 1 P1 — **resolved**: `CarryTags` checks the previous counter observation’s tenant before retaining the tag ([owner.go:85](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/metrics/owner.go:85)); mixed-host history provides the broader protection. Fault family: **tenant identity of samples**. |
| + |
| +1. **P2 — Request budget omits sweeps newly triggered by remote-only views.** |
| + |
| + **Section:** [Request budget, line 179](/home/paulca/amadan.net/carlos/platform-remote-metrics/docs/superpowers/notes/remote-instance-metrics.md:179). “No new request anywhere” and “0 new console requests” are incorrect. |
| + |
| + **Evidence:** Today, `appResourceMetrics` skips remote rows ([server.go:3860](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/server.go:3860)). With no local hosts, `ownerAppMetricsFrom` returns before calling `LoadMetrics` ([metricsview.go:828](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:828)). Including remote hosts crosses that guard. A cold cache triggers `sweepAll` ([metricsview.go:343](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:343)), including 48 raw-chunk GETs per discovered box ([metricsview.go:520](/home/paulca/amadan.net/carlos/platform-remote-metrics/internal/console/metricsview.go:520)). |
| + |
| + **Failure scenario:** On a quiet console with a cold cache, opening an app whose instances are all remote previously made no metrics requests. Under the proposed design, that same visit triggers the fleet-wide sweep, including discovery and alert reads. Subsequent visits can trigger refreshes after cache expiry. |
| + |
| + **Fix:** State that idle background traffic and requests per sweep remain unchanged, but remote-only views can now initiate the existing sweep. Document its cost and add a request-budget test covering cold and fresh-cache visits. |
| + |
| + **Fault family:** request-budget accounting. The prohibition on new per-box polling remains satisfied. |
| + |
| +No outstanding P1 or P3 findings. Reviewed commit `0a90c4c3e15203654e17aae773dc9ca623f19829`; no files edited. Targeted tests could not start because the read-only filesystem prevented Go from creating its build directory. Fix the P2 without another review round. |
| + |
| +**READY AFTER FIXES** |
| \ No newline at end of file |
diff --git a/internal/console/apiinstances.go b/internal/console/apiinstances.go| index ab11b4593..1dd1b037e 100644 |
| --- a/internal/console/apiinstances.go |
| +++ b/internal/console/apiinstances.go |
| @@ -40,6 +40,7 @@ import ( |
| "github.com/carlosframework/platform/internal/gate" |
| "github.com/carlosframework/platform/internal/hostops" |
| + "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/ratelimit" |
| "github.com/carlosframework/platform/internal/regionlabel" |
| @@ -352,14 +353,23 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| // A record whose route is on another box has no row here. Its health |
| // comes from the box that reports it, the same join the app pages make |
| // (remoteinstances.go): only a report whose rollout names this record's |
| - // own account and app. It takes no metrics readings at all: the word |
| - // comes from the rollout's awake, down and transient alone. A record no |
| - // box reports stays "Setting up" when every box was read; when the read |
| - // was incomplete, the record is placed on a customer fleet, or the only |
| - // report names no tenant, its state is unknown and says so. |
| + // own account and app. Its word comes from the rollout's awake, down |
| + // and transient, and, as on the Running tab, a reading its box tagged |
| + // with this record's own account and app counts as awake |
| + // (ownerAppMetricsFrom's tenant rule). A record no box reports stays |
| + // "Setting up" when every box was read; when the read was incomplete, |
| + // the record is placed on a customer fleet, or the only report names no |
| + // tenant, its state is unknown and says so. |
| if s.cfg.Releases != nil { |
| var facts appFacts |
| loaded := false |
| + type remoteWord struct { |
| + rec provision.Record |
| + kind string |
| + status string |
| + awake bool |
| + } |
| + var pending []remoteWord |
| for _, rec := range recs { |
| if _, local := byHost[rec.Host]; local { |
| continue |
| @@ -389,7 +399,30 @@ func (s *Server) instanceHealth(ctx context.Context, recs []provision.Record) ma |
| // page says. |
| status = "failed" |
| } |
| - out[rec.Host] = healthWord(kind, status, rec.HibernateOrDefault(), rep.awake, true) |
| + pending = append(pending, remoteWord{rec: rec, kind: kind, status: status, awake: rep.awake}) |
| + } |
| + if len(pending) > 0 { |
| + hosts := make([]string, 0, len(pending)) |
| + since := make(map[string]time.Time, len(pending)) |
| + tenants := make(map[string]metrics.Owner, len(pending)) |
| + for _, p := range pending { |
| + hosts = append(hosts, p.rec.Host) |
| + since[p.rec.Host] = p.rec.CreatedAt |
| + tenants[p.rec.Host] = metrics.Owner{Account: p.rec.Account, App: p.rec.App} |
| + } |
| + reporting := map[string]bool{} |
| + am, err := s.ownerAppMetricsFrom(ctx, hosts, nil, since, tenants) |
| + if err != nil { |
| + log.Printf("console: api instances health: remote metrics: %v", err) |
| + } |
| + for _, m := range am { |
| + if m.Reporting() { |
| + reporting[m.Host] = true |
| + } |
| + } |
| + for _, p := range pending { |
| + out[p.rec.Host] = healthWord(p.kind, p.status, p.rec.HibernateOrDefault(), p.awake || reporting[p.rec.Host], true) |
| + } |
| } |
| } |
| // Readings start with each record's created_at, as on the app pages: a |
| @@ -431,7 +464,7 @@ func (s *Server) healthByHost(ctx context.Context, routeFor map[string]registry. |
| unitByHost[h] = rt.Unit |
| } |
| } |
| - am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost) |
| + am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost, nil) |
| if err != nil { |
| // An unreadable sweep is not knowledge that these instances are |
| // down: every host reads as not-reporting below, which healthWord |
diff --git a/internal/console/metricsview.go b/internal/console/metricsview.go| index 70587ba37..5e6142844 100644 |
| --- a/internal/console/metricsview.go |
| +++ b/internal/console/metricsview.go |
| @@ -51,6 +51,11 @@ type UnitRow struct { |
| // float32 and one int64 per sample per running unit. |
| cpu []float32 |
| mem []int64 |
| + // owner is the tenant the box tagged the unit's reading with at each |
| + // swept sample, as an index into BoxMetricsView.owners, -1 where it |
| + // tagged none (metrics.UnitSample.Owner). A remote row reads only the |
| + // samples tagged with its record's tenant (ownerAppMetricsFrom). |
| + owner []int32 |
| } |
| // BoxMetricsView is one box's assembled dashboard row: latest host readings |
| @@ -65,6 +70,19 @@ type BoxMetricsView struct { |
| // times is each swept sample's time, oldest first: the x axis of every |
| // unit's cpu and mem series. |
| times []time.Time |
| + // owners is the distinct tenants the box's samples were tagged with, |
| + // indexed by UnitRow.owner. |
| + owners []metrics.Owner |
| +} |
| + |
| +// ownerIndex is tenant's index in v.owners, -1 when no sample carries it. |
| +func (v BoxMetricsView) ownerIndex(tenant metrics.Owner) int32 { |
| + for i, o := range v.owners { |
| + if o == tenant { |
| + return int32(i) |
| + } |
| + } |
| + return -1 |
| } |
| // AlertRow is one currently-firing rule on one box. LoadMetrics only ever |
| @@ -593,6 +611,26 @@ func buildBoxView(box string, samples []metrics.Sample) BoxMetricsView { |
| for i, sm := range samples { |
| view.times[i] = sm.At |
| } |
| + index := map[metrics.Owner]int32{} |
| + for r := range view.Units { |
| + name := view.Units[r].Unit |
| + series := make([]int32, len(samples)) |
| + for i, sm := range samples { |
| + series[i] = -1 |
| + u, ok := sm.Units[name] |
| + if !ok || u.Owner == nil { |
| + continue |
| + } |
| + k, seen := index[*u.Owner] |
| + if !seen { |
| + k = int32(len(view.owners)) |
| + index[*u.Owner] = k |
| + view.owners = append(view.owners, *u.Owner) |
| + } |
| + series[i] = k |
| + } |
| + view.Units[r].owner = series |
| + } |
| return view |
| } |
| @@ -666,20 +704,33 @@ func unitRawMem(samples []metrics.Sample, unit string) []int64 { |
| // since, the memory one scaled to the peak within them. ok is false when |
| // the unit has no sample there at all. |
| func sparksSince(times []time.Time, u UnitRow, since time.Time) (cpu, mem string, ok bool) { |
| + return sparksWhere(times, u, since, nil) |
| +} |
| + |
| +// sparksWhere is sparksSince drawn from only the samples keep accepts (all |
| +// of them when keep is nil): a remote row's graph is redrawn from the |
| +// samples tagged with its tenant alone, the memory one scaled to the peak |
| +// within those. ok is false when no sample qualifies. |
| +func sparksWhere(times []time.Time, u UnitRow, since time.Time, keep func(i int) bool) (cpu, mem string, ok bool) { |
| if len(times) != len(u.cpu) || len(times) != len(u.mem) { |
| return "", "", false |
| } |
| k := sort.Search(len(times), func(i int) bool { return !times[i].Before(since) }) |
| - if k >= len(times) { |
| + var idx []int |
| + for i := k; i < len(times); i++ { |
| + if keep == nil || keep(i) { |
| + idx = append(idx, i) |
| + } |
| + } |
| + if len(idx) == 0 { |
| return "", "", false |
| } |
| - n := len(times) - k |
| - cs := make([]*float64, n) |
| + cs := make([]*float64, len(idx)) |
| var peak int64 |
| - for i := k; i < len(times); i++ { |
| + for j, i := range idx { |
| if c := u.cpu[i]; !math.IsNaN(float64(c)) { |
| f := float64(c) |
| - cs[i-k] = &f |
| + cs[j] = &f |
| } |
| if u.mem[i] > peak { |
| peak = u.mem[i] |
| @@ -687,11 +738,11 @@ func sparksSince(times []time.Time, u UnitRow, since time.Time) (cpu, mem string |
| } |
| var ms []*float64 |
| if peak > 0 { |
| - ms = make([]*float64, n) |
| - for i := k; i < len(times); i++ { |
| + ms = make([]*float64, len(idx)) |
| + for j, i := range idx { |
| if u.mem[i] >= 0 { |
| f := float64(u.mem[i]) / float64(peak) |
| - ms[i-k] = &f |
| + ms[j] = &f |
| } |
| } |
| } |
| @@ -791,16 +842,23 @@ func (m InstanceMetrics) Reporting() bool { return m.Box != "" } |
| // readings, Reporting false), never zeros and never silently dropped — an |
| // owner whose instance is asleep must still see it listed. |
| func (s *Server) OwnerAppMetrics(ctx context.Context, hosts []string, unitByHost map[string]string) ([]InstanceMetrics, error) { |
| - return s.ownerAppMetricsFrom(ctx, hosts, unitByHost, nil) |
| + return s.ownerAppMetricsFrom(ctx, hosts, unitByHost, nil, nil) |
| } |
| // ownerAppMetricsFrom is OwnerAppMetrics where sinceByHost bounds a host's |
| // readings by when its current owner's route or record came to exist |
| // (graphs redrawn from later samples only; a zero time is no readings). A |
| -// host not named there reads as before: the freshest box's sample. Only |
| -// instances on the console's own box are ever asked for: an instance on |
| -// another box takes no readings (remoteinstances.go). |
| -func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitByHost map[string]string, sinceByHost map[string]time.Time) ([]InstanceMetrics, error) { |
| +// host not named there reads as before: the freshest box's sample. |
| +// |
| +// tenantByHost names the hosts that live on another box (remote rows) and |
| +// the tenant their record names. Such a host reads ONLY samples the box |
| +// tagged with exactly that tenant (docs/superpowers/notes/remote-instance-metrics.md): |
| +// a box counts only when the unit's newest sample carries the tag, and the |
| +// graphs are drawn from tagged samples alone. No tag (a box built before |
| +// tagging, or a reading the box would not vouch for), another tenant's tag |
| +// or no start in sinceByHost means nothing from that box. The hostname is |
| +// never enough: it changes hands. This is the one place the rule lives. |
| +func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitByHost map[string]string, sinceByHost map[string]time.Time, tenantByHost map[string]metrics.Owner) ([]InstanceMetrics, error) { |
| // The allowlist, keyed by the unit names each host can legally match. |
| // Matching is exact-string on this map: a unit the caller did not ask |
| // for cannot be reached by any path below. |
| @@ -856,9 +914,22 @@ func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitBy |
| // readings at all; with a newest sample older than the start, |
| // not even the current one. |
| since, bounded := sinceByHost[host] |
| + tenant, strict := tenantByHost[host] |
| + if strict && !bounded { |
| + continue // a remote row with no known start reads nothing |
| + } |
| if bounded && (since.IsZero() || box.At.Before(since)) { |
| continue |
| } |
| + var tagged func(i int) bool |
| + if strict { |
| + k := box.ownerIndex(tenant) |
| + n := len(u.owner) |
| + if k < 0 || n == 0 || n != len(box.times) || u.owner[n-1] != k { |
| + continue // the newest reading is not this tenant's |
| + } |
| + tagged = func(i int) bool { return u.owner[i] == k } |
| + } |
| // A host that reports on two boxes at once (a move in flight) |
| // shows the freshest box's reading, not whichever sorted first. |
| if prev, taken := at[host]; taken && !box.At.After(prev) { |
| @@ -874,7 +945,10 @@ func (s *Server) ownerAppMetricsFrom(ctx context.Context, hosts []string, unitBy |
| SparkCPU: u.SparkCPU, |
| SparkMem: u.SparkMem, |
| } |
| - if bounded && (len(box.times) == 0 || box.times[0].Before(since)) { |
| + if strict { |
| + // Only this tenant's tagged samples since its record. |
| + row.SparkCPU, row.SparkMem, _ = sparksWhere(box.times, u, since, tagged) |
| + } else if bounded && (len(box.times) == 0 || box.times[0].Before(since)) { |
| // Part of the window predates the owner: redraw from only |
| // their samples, or draw nothing when that cannot be done. |
| row.SparkCPU, row.SparkMem, _ = sparksSince(box.times, u, since) |
diff --git a/internal/console/remoteinstances.go b/internal/console/remoteinstances.go| index 60bf9f849..d7096fdf0 100644 |
| --- a/internal/console/remoteinstances.go |
| +++ b/internal/console/remoteinstances.go |
| @@ -36,6 +36,7 @@ import ( |
| "sync" |
| "time" |
| + "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/provision" |
| "github.com/carlosframework/platform/internal/regionlabel" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -391,9 +392,10 @@ type remoteRows struct { |
| // Asleep, Not responding or Serving. That includes static sites and |
| // instances that never sleep, which the rollout report does not cover. |
| // |
| -// No metrics: a remote row takes no CPU or memory readings and no graphs |
| -// (appResourceMetrics skips it), since no sample on any box is proven to |
| -// be this owner's. Unit and Caps are deliberately empty. Restartable is false: the browser restart door acts on the console box's |
| +// Metrics: a remote row reads only samples its box tagged with the |
| +// record's own account and app, from the record's created_at on |
| +// (RouteView.tenant and since; ownerAppMetricsFrom). The hostname alone is |
| +// never enough. Unit and Caps are deliberately empty. Restartable is false: the browser restart door acts on the console box's |
| // registry only. |
| func remoteRoute(rec provision.Record, rep *hostReport, f appFacts, acct string, dns DNSTargets) (RouteView, DomainView) { |
| kind := rec.Kind |
| @@ -412,6 +414,9 @@ func remoteRoute(rec provision.Record, rep *hostReport, f appFacts, acct string, |
| Environment: rec.Environment, |
| Provisioned: true, |
| remote: true, |
| + tenant: metrics.Owner{Account: rec.Account, App: rec.App}, |
| + since: rec.CreatedAt, |
| + bounded: true, |
| } |
| typ := "custom" |
| if strings.HasPrefix(ch, "canary/") { |
diff --git a/internal/console/remoteinstances_round2_test.go b/internal/console/remoteinstances_round2_test.go| index ae36f2a9c..afa015f08 100644 |
| --- a/internal/console/remoteinstances_round2_test.go |
| +++ b/internal/console/remoteinstances_round2_test.go |
| @@ -75,7 +75,7 @@ func TestOwnerMetricsSinceRules(t *testing.T) { |
| twoSamples(t, fx.rel, "box-x", "carlos-exec@"+host, time.Now().Add(-3*time.Hour), time.Now().Add(-90*time.Second)) |
| for name, since := range map[string]time.Time{"unknown start": {}, "start after the newest sample": time.Now().Add(-time.Minute)} { |
| fx.srv.metricsCache = metricsCache{} |
| - am, err := fx.srv.ownerAppMetricsFrom(context.Background(), []string{host}, nil, map[string]time.Time{host: since}) |
| + am, err := fx.srv.ownerAppMetricsFrom(context.Background(), []string{host}, nil, map[string]time.Time{host: since}, nil) |
| if err != nil { |
| t.Fatal(err) |
| } |
diff --git a/internal/console/remoteinstances_round6_test.go b/internal/console/remoteinstances_round6_test.go| index ec0a917ee..6258057b2 100644 |
| --- a/internal/console/remoteinstances_round6_test.go |
| +++ b/internal/console/remoteinstances_round6_test.go |
| @@ -12,12 +12,15 @@ import ( |
| "github.com/carlosframework/platform/internal/status" |
| ) |
| -// Astra round 6, P1 #1: remote rows take no metrics. Every box that could |
| -// hold a sample of the remote host's unit has a fresh one (its own box, the |
| -// console's box, a third box), and its own box's rollout says it is asleep. |
| -// No remote row on any page, nor `carlos instances list`, may carry a |
| -// reading, a graph or a Running word drawn from a sample. The local row on |
| -// the console's box keeps its readings. |
| +// Astra round 6, P1 #1: remote rows took no metrics. Since |
| +// remote-instance-metrics they take only samples their box tagged with the |
| +// record's tenant, so this is now the untagged case (a box built before |
| +// tagging): every box that could hold a sample of the remote host's unit |
| +// has a fresh, untagged one (its own box, the console's box, a third box), |
| +// and its own box's rollout says it is asleep. No remote row on any page, |
| +// nor `carlos instances list`, may carry a reading, a graph or a Running |
| +// word drawn from a sample. The local row on the console's box keeps its |
| +// readings. |
| func TestRemoteRowsNeverCarrySamples(t *testing.T) { |
| tb := newTwoBoxes(t) |
| tb.setUp(t, true) |
| @@ -47,8 +50,10 @@ func TestRemoteRowsNeverCarrySamples(t *testing.T) { |
| } |
| local := false |
| for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) { |
| - if remote[m.Host] { |
| - t.Fatalf("a remote row carries a metrics row: %+v", m) |
| + // Since remote-instance-metrics a remote row has a metrics row, but |
| + // an untagged sample is never its reading. |
| + if remote[m.Host] && (m.Reporting() || m.CPUFrac != nil || m.MemBytes != nil || m.SparkCPU != "") { |
| + t.Fatalf("a remote row carries an untagged reading: %+v", m) |
| } |
| if m.Host == localHost && m.Reporting() && m.CPUFrac != nil { |
| local = true |
diff --git a/internal/console/remotemetrics_test.go b/internal/console/remotemetrics_test.go| new file mode 100644 |
| index 000000000..2f98674ac |
| --- /dev/null |
| +++ b/internal/console/remotemetrics_test.go |
| @@ -0,0 +1,448 @@ |
| +package console |
| + |
| +// CPU and memory for instances on other boxes, with samples tagged by the |
| +// box with the tenant whose process they measured |
| +// (docs/superpowers/notes/remote-instance-metrics.md). The fixture is |
| +// remoteinstances_test.go's: two boxes and one bucket, instances created |
| +// through the console's create and delete doors, minted by each box's real |
| +// reconcile pass, reported by each box's real status snapshot. Each box's |
| +// samples are tagged by the box's own rule (metrics.Vouched over the box's |
| +// real registry rows, then metrics.TagUnits), with the box activator's |
| +// view of its live entries as the one stand-in, and written with |
| +// metrics.WriteRaw as the sampler's flush writes them. |
| + |
| +import ( |
| + "context" |
| + "net/http" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/metrics" |
| + "github.com/carlosframework/platform/internal/provision" |
| + "github.com/carlosframework/platform/internal/registry" |
| + "github.com/carlosframework/platform/internal/release" |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// boxSample is one sampler tick on a box: units read at at, tagged by the |
| +// box's rule over its own registry rows and its activator's live entries. |
| +func boxSample(t *testing.T, reg *registry.Registry, live map[string]metrics.Live, at time.Time, units map[string]metrics.UnitSample) metrics.Sample { |
| + t.Helper() |
| + routes, err := reg.List() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + v := metrics.Vouched(routes, live, nil) |
| + metrics.TagUnits(units, v, v) |
| + return metrics.Sample{At: at, Units: units} |
| +} |
| + |
| +// writeSamples flushes a box's samples, one raw chunk per hour, replacing |
| +// what the hour held. |
| +func writeSamples(t *testing.T, rel release.Store, box string, samples ...metrics.Sample) { |
| + t.Helper() |
| + byHour := map[string][]metrics.Sample{} |
| + var hours []string |
| + for _, s := range samples { |
| + h := metrics.HourOf(s.At) |
| + if _, ok := byHour[h]; !ok { |
| + hours = append(hours, h) |
| + } |
| + byHour[h] = append(byHour[h], s) |
| + } |
| + for _, h := range hours { |
| + if err := metrics.WriteRaw(context.Background(), rel, metrics.RawChunk{V: 1, Box: box, Hour: h, Samples: byHour[h]}); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| +} |
| + |
| +// fresh drops the console's held reads, as a minute passing would. |
| +func (tb *twoBoxes) fresh() { |
| + tb.fx.srv.boxReports.expire() |
| + tb.fx.srv.metricsCache = metricsCache{} |
| +} |
| + |
| +func execUnit(host string) string { return "carlos-exec@" + host } |
| + |
| +// remoteMetricsRow is the remote row's metrics row from the app pages' own |
| +// reader (appResourceMetrics), or a zero row. |
| +func (tb *twoBoxes) remoteMetricsRow(t *testing.T, host string) InstanceMetrics { |
| + t.Helper() |
| + views, err := tb.fx.srv.assembleApps(context.Background(), tb.sqid, []string{"shop"}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, m := range tb.fx.srv.appResourceMetrics(context.Background(), &views[0], tb.account(t)) { |
| + if m.Host == host { |
| + return m |
| + } |
| + } |
| + return InstanceMetrics{} |
| +} |
| + |
| +// noRemoteReadings fails if any app page, the remote row's metrics or |
| +// `carlos instances list` carries one of bad, or calls the remote row |
| +// Running from a reading. |
| +func (tb *twoBoxes) noRemoteReadings(t *testing.T, bad ...string) { |
| + t.Helper() |
| + if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.CPUFrac != nil || m.MemBytes != nil || m.SparkCPU != "" || m.SparkMem != "" { |
| + t.Fatalf("the remote row carries a reading: %+v", m) |
| + } |
| + for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} { |
| + body := tb.page(t, path) |
| + for _, b := range bad { |
| + if strings.Contains(body, b) { |
| + t.Fatalf("%s shows %q:\n%s", path, b, body) |
| + } |
| + } |
| + } |
| + if row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost); strings.Contains(row, "<polyline") { |
| + t.Fatalf("the remote row drew a graph: %s", row) |
| + } |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s", code, out) |
| + } |
| +} |
| + |
| +// TestRemoteMetricsShowTheOwnersTaggedSamples is the feature: B's samples |
| +// of this account's instance, tagged with this account and app, are its |
| +// readings, graphs and Running state on every page. |
| +func TestRemoteMetricsShowTheOwnersTaggedSamples(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + // Asleep by B's rollout report: Running comes from the reading alone. |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + live := map[string]metrics.Live{remoteHost: {Account: tb.sqid, App: "shop", Entry: 1}} |
| + now := time.Now().UTC() |
| + var samples []metrics.Sample |
| + for i, cpu := range []float64{0.10, 0.18, 0.27} { |
| + samples = append(samples, boxSample(t, tb.regB, live, now.Add(time.Duration(i)*time.Second), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(cpu), MemBytes: pi64(int64(i+1) << 20)}, |
| + })) |
| + } |
| + if o := samples[2].Units[execUnit(remoteHost)].Owner; o == nil || o.Account != tb.sqid { |
| + t.Fatalf("fixture: box B did not tag its own tenant's sample: %+v", o) |
| + } |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), samples...) |
| + tb.fresh() |
| + |
| + m := tb.remoteMetricsRow(t, remoteHost) |
| + if !m.Reporting() || m.CPUFrac == nil || *m.CPUFrac != 0.27 || m.MemBytes == nil || *m.MemBytes != 3<<20 { |
| + t.Fatalf("remote metrics row = %+v", m) |
| + } |
| + if n := len(strings.Fields(m.SparkCPU)); n != 3 { |
| + t.Fatalf("CPU graph has %d points, want the 3 tagged samples: %q", n, m.SparkCPU) |
| + } |
| + ov := tb.page(t, "/apps/shop") |
| + for _, want := range []string{"27%", "3.0 MB"} { |
| + if !strings.Contains(ov, want) { |
| + t.Fatalf("overview is missing %q:\n%s", want, ov) |
| + } |
| + } |
| + if strings.Contains(ov, "no data right now") { |
| + t.Fatalf("overview still says no data:\n%s", ov) |
| + } |
| + row := instanceRow(t, tb.page(t, "/apps/shop/instances"), remoteHost) |
| + if !strings.Contains(row, "Running") || !strings.Contains(row, "27%") || !strings.Contains(row, "<polyline") { |
| + t.Fatalf("Running row = %s", row) |
| + } |
| + if inst := tb.page(t, "/apps/shop/instances/"+remoteHost); !strings.Contains(inst, "27%") || !strings.Contains(inst, "3.0 MB") { |
| + t.Fatalf("instance page lacks the readings:\n%s", inst) |
| + } |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK || !strings.Contains(out, `"health":"Running"`) { |
| + t.Fatalf("instances list = %d %s", code, out) |
| + } |
| +} |
| + |
| +// TestRemoteMetricsReusedHostname: another account held the hostname on B |
| +// and deleted it; this account created it again. Until B reconciles, B |
| +// still runs the predecessor's process under the predecessor's row, and |
| +// its samples, taken after this account's record was created, are tagged |
| +// with the predecessor. After B reconciles, the predecessor's entry may |
| +// still be stopping: B's row names this account and its activator the |
| +// predecessor, so B vouches nothing. Neither ever shows here. |
| +func TestRemoteMetricsReusedHostname(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + ctx := context.Background() |
| + now := time.Now() |
| + const rivalID int64 = 6363 |
| + rival := accountSqid(rivalID) |
| + if err := tb.fx.st.CreateAccount(rivalID, rival, "Rival", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := tb.fx.st.CreateAppIn(rivalID, "shop", "bob@keymail.dev", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := WriteAccountManifest(ctx, tb.fx.rel, rivalID, rival, "Rival", now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := provision.PutManifest(ctx, tb.fx.rel, rival, "shop", shopManifest("shop", "shop.example.com")); err != nil { |
| + t.Fatal(err) |
| + } |
| + shipAndPromote(t, tb.fx, rival, "shop", "v3", "stable") |
| + bob := cliToken(t, tb.fx, "bob@keymail.dev", "code-reuse-bob") |
| + tb.fx.setUser("paul@keymail.dev") |
| + |
| + // The predecessor: the rival's instance, minted on B. |
| + tb.create(t, bob, rival, "shop", remoteHost, "uk", "") |
| + tb.reconcile(t, "v3") |
| + if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != rival { |
| + t.Fatalf("fixture: B's row = %+v, want the rival's", rt) |
| + } |
| + rivalLive := map[string]metrics.Live{remoteHost: {Account: rival, App: "shop", Entry: 1}} |
| + before := boxSample(t, tb.regB, rivalLive, time.Now().UTC(), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.61), MemBytes: pi64(11 << 20)}, |
| + }) |
| + |
| + // The rival deletes it; this account creates the same hostname. B has |
| + // not reconciled. |
| + if code, _, out := rawReq(t, http.MethodDelete, instancesURL(tb.fx, rival, "shop")+"/"+remoteHost, bob, ""); code/100 != 2 { |
| + t.Fatalf("rival delete = %d %s", code, out) |
| + } |
| + tb.create(t, tb.token, tb.sqid, "shop", remoteHost, "uk", "") |
| + recs, _, err := provision.ListRecords(ctx, tb.fx.rel, tb.sqid, "shop", 10) |
| + if err != nil || len(recs) != 1 { |
| + t.Fatalf("records = %+v %v", recs, err) |
| + } |
| + afterCreate := recs[0].CreatedAt.Add(2 * time.Second) |
| + pending := boxSample(t, tb.regB, rivalLive, afterCreate, map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if o := pending.Units[execUnit(remoteHost)].Owner; o == nil || o.Account != rival { |
| + t.Fatalf("fixture: B tagged its predecessor's sample %+v, want the rival", o) |
| + } |
| + |
| + // B reconciles. With no lifetime judge it leaves another tenant's row |
| + // alone while this account's record exists, so it still runs the |
| + // predecessor as the predecessor's. |
| + tb.reconcile(t, "v3") |
| + if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != rival { |
| + t.Fatalf("fixture: B's row = %+v, want the rival's still", rt) |
| + } |
| + stuck := boxSample(t, tb.regB, rivalLive, afterCreate.Add(30*time.Second), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.63), MemBytes: pi64(13 << 20)}, |
| + }) |
| + // A box with a lifetime judge withdraws the predecessor's row first |
| + // (TestCrossOwnerRecreationWithdrawsThePredecessorRow), then mints this |
| + // account's; the rival's entry is still stopping. |
| + if err := tb.regB.Delete(remoteHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + tb.reconcile(t, "v3") |
| + if rt, _ := tb.regB.Get(remoteHost); rt == nil || rt.Account != tb.sqid { |
| + t.Fatalf("fixture: B's row after reconcile = %+v", rt) |
| + } |
| + stopping := boxSample(t, tb.regB, rivalLive, afterCreate.Add(time.Minute), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.55), MemBytes: pi64(9 << 20)}, |
| + }) |
| + if o := stopping.Units[execUnit(remoteHost)].Owner; o != nil { |
| + t.Fatalf("fixture: B vouched %+v while its row and activator disagree", o) |
| + } |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), before, pending, stuck, stopping) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) |
| + tb.fresh() |
| + |
| + tb.noRemoteReadings(t, "61%", "11 MB", "66%", "7.0 MB", "63%", "13 MB", "55%", "9.0 MB") |
| +} |
| + |
| +// TestRemoteMetricsSuccessorNotShownToOldOwner: this account's page still |
| +// shows its record while B already runs the hostname for another account |
| +// (B reconciled the successor; the console's read of the records is up to |
| +// a minute old). B's samples are tagged with the successor, and none show. |
| +func TestRemoteMetricsSuccessorNotShownToOldOwner(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + const successor = "rvl" |
| + rt, err := tb.regB.Get(remoteHost) |
| + if err != nil || rt == nil { |
| + t.Fatalf("fixture: %+v %v", rt, err) |
| + } |
| + // B's row as B minted it for the successor's record. |
| + if err := tb.regB.Delete(remoteHost); err != nil { |
| + t.Fatal(err) |
| + } |
| + next := *rt |
| + next.Account, next.CreatedAt = successor, 0 |
| + if err := tb.regB.Upsert(next); err != nil { |
| + t.Fatal(err) |
| + } |
| + live := map[string]metrics.Live{remoteHost: {Account: successor, App: "shop", Entry: 2}} |
| + s := boxSample(t, tb.regB, live, time.Now().UTC(), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + if o := s.Units[execUnit(remoteHost)].Owner; o == nil || o.Account != successor { |
| + t.Fatalf("fixture: B tagged %+v, want the successor", o) |
| + } |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), s) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) // asleep |
| + tb.fresh() |
| + tb.noRemoteReadings(t, "66%", "7.0 MB") |
| +} |
| + |
| +// TestRemoteMetricsAnotherAccountsBox: another box, C, serves the same |
| +// hostname for another account (a stale copy, or that account's own |
| +// instance) and tags its samples with that account. B, this instance's box, |
| +// has no sample. Nothing of C's shows. |
| +func TestRemoteMetricsAnotherAccountsBox(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + regC, err := registry.Open(filepath.Join(t.TempDir(), "registry-c.db")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { regC.Close() }) |
| + if err := regC.Upsert(registry.Route{Host: remoteHost, Kind: "instance", Account: "rvl", App: "shop", Provisioned: true, Hibernate: true}); err != nil { |
| + t.Fatal(err) |
| + } |
| + live := map[string]metrics.Live{remoteHost: {Account: "rvl", App: "shop", Entry: 1}} |
| + s := boxSample(t, regC, live, time.Now().UTC(), map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(0.66), MemBytes: pi64(7 << 20)}, |
| + }) |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), metrics.Sample{At: time.Now().UTC()}) |
| + writeSamples(t, tb.fx.rel, status.Label("box-c"), s) |
| + report(t, tb.fx.rel, tb.regB, "box-b", "uk", time.Now(), nil, 4096) // asleep |
| + tb.fresh() |
| + tb.noRemoteReadings(t, "66%", "7.0 MB") |
| +} |
| + |
| +// TestRemoteMetricsGraphOnlyTheOwnersSamples: B's window for the unit |
| +// holds samples of three kinds: this account's before its record was |
| +// created (an earlier instance of the same hostname), another account's, |
| +// and this account's since. The graph is drawn from the last kind alone; |
| +// and once the newest sample is not this account's, there is no current |
| +// reading at all. |
| +func TestRemoteMetricsGraphOnlyTheOwnersSamples(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + recs, _, err := provision.ListRecords(context.Background(), tb.fx.rel, tb.sqid, "shop", 10) |
| + if err != nil || len(recs) != 1 { |
| + t.Fatalf("records = %+v %v", recs, err) |
| + } |
| + created := recs[0].CreatedAt |
| + own := &metrics.Owner{Account: tb.sqid, App: "shop"} |
| + other := &metrics.Owner{Account: "rvl", App: "shop"} |
| + sample := func(at time.Time, cpu float64, o *metrics.Owner) metrics.Sample { |
| + return metrics.Sample{At: at.UTC(), Units: map[string]metrics.UnitSample{ |
| + execUnit(remoteHost): {CPUFrac: p(cpu), MemBytes: pi64(1 << 20), Owner: o}, |
| + }} |
| + } |
| + window := []metrics.Sample{ |
| + sample(created.Add(-2*time.Minute), 0.91, own), // before the record |
| + sample(created.Add(-time.Minute), 0.92, other), // another tenant |
| + sample(created.Add(time.Second), 0.20, own), // this tenant |
| + sample(created.Add(2*time.Second), 0.93, other), // another tenant |
| + sample(created.Add(3*time.Second), 0.30, own), // this tenant, newest |
| + } |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), window...) |
| + tb.fresh() |
| + m := tb.remoteMetricsRow(t, remoteHost) |
| + if !m.Reporting() || m.CPUFrac == nil || *m.CPUFrac != 0.30 { |
| + t.Fatalf("current reading = %+v", m) |
| + } |
| + if n := len(strings.Fields(m.SparkCPU)); n != 2 { |
| + t.Fatalf("graph drawn from %d samples, want this tenant's 2 since its record: %q", n, m.SparkCPU) |
| + } |
| + if n := len(strings.Fields(m.SparkMem)); n != 2 { |
| + t.Fatalf("memory graph drawn from %d samples, want 2: %q", n, m.SparkMem) |
| + } |
| + |
| + // The newest sample is another tenant's: no current reading. |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, other))...) |
| + tb.fresh() |
| + if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() || m.SparkCPU != "" { |
| + t.Fatalf("a remote row read through another tenant's newest sample: %+v", m) |
| + } |
| + // The newest is untagged (an old box, or a reading the box would not |
| + // vouch for): no current reading either. |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, nil))...) |
| + tb.fresh() |
| + if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() { |
| + t.Fatalf("a remote row read through an untagged newest sample: %+v", m) |
| + } |
| + // The newest is this account's but another app's. |
| + otherApp := &metrics.Owner{Account: tb.sqid, App: "web"} |
| + writeSamples(t, tb.fx.rel, status.Label("box-b"), append(window, sample(created.Add(4*time.Second), 0.94, otherApp))...) |
| + tb.fresh() |
| + if m := tb.remoteMetricsRow(t, remoteHost); m.Reporting() { |
| + t.Fatalf("a remote row read another app's sample: %+v", m) |
| + } |
| +} |
| + |
| +// metricsBudgetStore counts the metrics sweep's reads: LISTs and GETs under |
| +// metrics/ and alerts/. |
| +type metricsBudgetStore struct { |
| + release.Store |
| + mu sync.Mutex |
| + lists, gets int |
| +} |
| + |
| +func (c *metricsBudgetStore) metricsKey(key string) bool { |
| + return strings.HasPrefix(key, "metrics/") || strings.HasPrefix(key, "alerts/") |
| +} |
| + |
| +func (c *metricsBudgetStore) List(ctx context.Context, prefix string) ([]string, error) { |
| + if c.metricsKey(prefix) { |
| + c.mu.Lock() |
| + c.lists++ |
| + c.mu.Unlock() |
| + } |
| + return c.Store.List(ctx, prefix) |
| +} |
| + |
| +func (c *metricsBudgetStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if c.metricsKey(key) { |
| + c.mu.Lock() |
| + c.gets++ |
| + c.mu.Unlock() |
| + } |
| + return c.Store.Get(ctx, key) |
| +} |
| + |
| +func (c *metricsBudgetStore) take() (lists, gets int) { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + lists, gets = c.lists, c.gets |
| + c.lists, c.gets = 0, 0 |
| + return lists, gets |
| +} |
| + |
| +// TestRemoteMetricsRequestBudget (Astra round 2 on the note, P2): an app |
| +// whose instances all live on other boxes used to make no metrics reads. |
| +// Now its pages read the console's existing shared sweep: on a cold cache, |
| +// one view pays the sweep's usual cost (a LIST of metrics/boxes/, 48 |
| +// hourly GETs per box, a LIST of alerts/boxes/), and every view, tab and |
| +// `carlos instances list` within the cache's minute pays nothing. Boxes |
| +// write nothing new: tags ride the chunks they already flush. |
| +func TestRemoteMetricsRequestBudget(t *testing.T) { |
| + tb := newTwoBoxes(t) |
| + tb.setUp(t, false) |
| + cs := &metricsBudgetStore{Store: tb.fx.rel} |
| + tb.fx.srv.cfg.Releases = cs |
| + tb.fresh() |
| + cs.take() |
| + |
| + tb.page(t, "/apps/shop") |
| + boxes, err := tb.fx.srv.discoverBoxes(context.Background()) |
| + if err != nil || len(boxes) != 1 { |
| + t.Fatalf("fixture: metrics boxes = %v %v", boxes, err) |
| + } |
| + cs.take() // discoverBoxes' own LIST above |
| + tb.fresh() |
| + tb.page(t, "/apps/shop") |
| + if lists, gets := cs.take(); lists != 2 || gets != metricsSweepHours*len(boxes) { |
| + t.Fatalf("cold overview: metrics LISTs %d GETs %d, want 2 and %d", lists, gets, metricsSweepHours*len(boxes)) |
| + } |
| + for _, path := range []string{"/apps/shop", "/apps/shop/instances", "/apps/shop/instances/" + remoteHost} { |
| + tb.page(t, path) |
| + } |
| + if code, _, out := rawReq(t, http.MethodGet, instancesURL(tb.fx, tb.sqid, "shop"), tb.token, ""); code != http.StatusOK { |
| + t.Fatalf("instances list = %d %s", code, out) |
| + } |
| + if lists, gets := cs.take(); lists != 0 || gets != 0 { |
| + t.Fatalf("views within the cache's minute: metrics LISTs %d GETs %d, want none", lists, gets) |
| + } |
| +} |
diff --git a/internal/console/server.go b/internal/console/server.go| index 93ce5ce98..d9884cc49 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -50,6 +50,7 @@ import ( |
| "github.com/carlosframework/platform/internal/infraview" |
| "github.com/carlosframework/platform/internal/lease" |
| "github.com/carlosframework/platform/internal/mail" |
| + "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/objstore" |
| "github.com/carlosframework/platform/internal/perf" |
| @@ -3849,21 +3850,24 @@ func (s *Server) appResourceMetrics(ctx context.Context, view *AppView, acct *Ac |
| hib := make(map[string]bool, len(view.Routes)) |
| unitByHost := make(map[string]string, len(view.Routes)) |
| sinceByHost := map[string]time.Time{} |
| + tenantByHost := map[string]metrics.Owner{} |
| for _, rt := range view.Routes { |
| if rt.Account != acct.Sqid { |
| continue |
| } |
| - // An instance on another box takes no readings at all: its host |
| - // name alone is not this tenant's, since another box may serve it |
| - // for someone else, and no sample on any box is proven theirs. Its |
| - // row shows the no-data state (remoteinstances.go). |
| + // An instance on another box reads only samples its box tagged |
| + // with this record's account and app: its host name alone is not |
| + // this tenant's, since the name changes hands and another box may |
| + // serve it for someone else (remoteinstances.go, |
| + // docs/superpowers/notes/remote-instance-metrics.md). |
| if rt.remote { |
| - continue |
| + tenantByHost[rt.Host] = rt.tenant |
| } |
| // History starts when this owner came to have the host: samples |
| // from a previous tenant of the same hostname are not theirs. A |
| - // local row that is provisioned or has a record is bounded |
| - // (RouteView.bounded); only a hand route with no record is not. |
| + // remote row, and a local row that is provisioned or has a record, |
| + // is bounded (RouteView.bounded); only a hand route with no record |
| + // is not. |
| if rt.bounded { |
| sinceByHost[rt.Host] = rt.since |
| } |
| @@ -3873,7 +3877,7 @@ func (s *Server) appResourceMetrics(ctx context.Context, view *AppView, acct *Ac |
| unitByHost[rt.Host] = rt.Unit |
| } |
| } |
| - am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost) |
| + am, err := s.ownerAppMetricsFrom(ctx, hosts, unitByHost, sinceByHost, tenantByHost) |
| if err != nil { |
| log.Printf("console: app metrics %s: %v", view.App, err) |
| return nil |
diff --git a/internal/console/view.go b/internal/console/view.go| index 51ac01480..bb2d26eb2 100644 |
| --- a/internal/console/view.go |
| +++ b/internal/console/view.go |
| @@ -19,6 +19,7 @@ import ( |
| "golang.org/x/net/publicsuffix" |
| + "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/perf" |
| "github.com/carlosframework/platform/internal/regionlabel" |
| "github.com/carlosframework/platform/internal/registry" |
| @@ -360,18 +361,22 @@ type RouteView struct { |
| aliases []string |
| boxAwake bool |
| // unknown says the row's process state is not known (remoteRoute): |
| - // its health reads "Can't tell right now". A remote row takes no |
| - // metrics readings at all (appResourceMetrics skips it). |
| + // its health reads "Can't tell right now". |
| unknown bool |
| - // since is when this local row's owner came to have the host: its |
| - // instance record's created_at (addRemoteRows). Metrics samples before |
| - // it are not this owner's (ownerAppMetricsFrom). |
| + // tenant is a remote row's record's account and app: the only tag its |
| + // metrics samples may carry (ownerAppMetricsFrom, |
| + // docs/superpowers/notes/remote-instance-metrics.md). Zero on a local |
| + // row, whose readings are not filtered by tag. |
| + tenant metrics.Owner |
| + // since is when this row's owner came to have the host: its instance |
| + // record's created_at (addRemoteRows, remoteRoute). Metrics samples |
| + // before it are not this owner's (ownerAppMetricsFrom). |
| since time.Time |
| - // bounded says since applies to this local row's readings, zero |
| - // meaning no readings at all: every local row that is provisioned or |
| - // has a record. A provisioned local row whose record could not be read |
| - // has an unknown start, so it shows nothing rather than the whole |
| - // window. Only a hand route with no record is unbounded. |
| + // bounded says since applies to this row's readings, zero meaning no |
| + // readings at all: every remote row, and every local row that is |
| + // provisioned or has a record. A provisioned local row whose record |
| + // could not be read has an unknown start, so it shows nothing rather |
| + // than the whole window. Only a hand route with no record is unbounded. |
| bounded bool |
| } |