| index 01fe8aa82..353bfafba 100644 |
| --- a/internal/console/usagedays.go |
| +++ b/internal/console/usagedays.go |
| @@ -1,10 +1,13 @@ |
| package console |
| |
| import ( |
| + "bytes" |
| "context" |
| "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| "os" |
| - "slices" |
| "strings" |
| "sync" |
| "time" |
| @@ -26,9 +29,13 @@ import ( |
| // bodies held at once, and the same answer, since the sweep's own code |
| // decides on exactly the bytes it read before. |
| // - Settled days are kept across views. A day's objects stop changing a |
| -// known time after the day ends (usageDaySettled), so a day before |
| -// that horizon is read once and kept; today and yesterday are read on |
| -// every cold view. |
| +// known time after the day ends (usageDaySettled), so a day before that |
| +// horizon is read once and kept for up to usageDayMaxAge; today and |
| +// yesterday are read on every cold view. |
| +// |
| +// Every usage object is read streaming and no further than usageDayReadCap |
| +// and one byte (a box writes what it likes under its own prefix): an object |
| +// over the cap is skipped as an unreadable day is, and logged. |
| // |
| // The hourly economics pass (statementsPass) already reads every day of the |
| // month to date from the bucket. It keeps reading them all, and leaves each |
| @@ -37,21 +44,38 @@ import ( |
| // and yesterday. That adds no request. |
| |
| // The cache's bounds. A body over usageDayCacheMaxBody is read on every |
| -// view and never kept (a box can write what it likes under its own |
| -// prefix); the whole cache holds at most usageDayCacheMaxBytes, counting |
| -// usageDayEntryOverhead and the key for every entry, a remembered absence |
| -// included. Past the budget the oldest days go first: month to date, the |
| -// page's default, is the last to lose its days. |
| +// view and never kept; the whole cache holds at most usageDayCacheMaxBytes, |
| +// counting usageDayEntryOverhead and the key for every entry, a remembered |
| +// absence included. Past the budget the oldest days go first: month to |
| +// date, the page's default, is the last to lose its days. An entry is |
| +// trusted for usageDayMaxAge after it was read, then read again. |
| const ( |
| usageDayCacheMaxBody = 1 << 20 |
| usageDayCacheMaxBytes = 64 << 20 |
| usageDayEntryOverhead = 64 |
| + usageDayMaxAge = 6 * time.Hour |
| ) |
| |
| -// usageDayEntry is one settled day object: its body and ETag, or the error |
| -// that said it does not exist (os.ErrNotExist), returned again as it was. |
| +// usageDayReadCap is the most bytes the console reads of one usage day |
| +// object; past it the object is skipped. A day rollup indented as the box |
| +// agent writes it is about 23 KB per instance (cpu and memory, tagged with |
| +// its tenant) and an edge day about 5 KB per host, so 8 MiB holds a box |
| +// running some 350 instances, or serving some 1,600 hosts, all day: well |
| +// past any box today. Ten reads at a time (readConcurrency) hold at most |
| +// 80 MiB. A variable only so a test can show the bound with small objects. |
| +var usageDayReadCap int64 = 8 << 20 |
| + |
| +// errUsageDayTooLarge is the read error of a usage day object over |
| +// usageDayReadCap. The sweep skips it as it skips any day it cannot read. |
| +var errUsageDayTooLarge = errors.New("console: usage day object over the read cap") |
| + |
| +// usageDayEntry is one settled day object read at at: its body and ETag, |
| +// or the error the read gave and will give again for the same object (it |
| +// does not exist, os.ErrNotExist, or it is over the cap, |
| +// errUsageDayTooLarge), returned again as it was. |
| type usageDayEntry struct { |
| date string |
| + at time.Time |
| body []byte |
| etag string |
| absent error |
| @@ -131,11 +155,15 @@ func daysDirBox(dir, prefix string) (string, bool) { |
| // fleet's prefix) is written when an hour closes: metricsFlush rolls up |
| // every hour older than the current one still in its buffer |
| // (internal/host/metrics_loop.go:221-245), and that buffer holds at most |
| -// samplerMaxBuf (120) one-minute samples, about two hours |
| -// (metrics_loop.go:44, the cap enforced in tick, :148-152). The restart |
| -// repair backfillPrevHourRollup rolls up only the hour before the |
| -// process started (metrics_loop.go:291-322). So the last write to a day |
| -// lands about two hours after it ends, plus a five-minute flush. |
| +// samplerMaxBuf (120) one-minute samples, about two hours of a running |
| +// box (metrics_loop.go:44, the cap enforced in tick, :148-152). The |
| +// restart repair backfillPrevHourRollup rolls up only the hour before |
| +// the process started (metrics_loop.go:291-322). So the last write to a |
| +// day lands about two hours after it ends, plus a five-minute flush. |
| +// The cap counts samples, not their age: a box suspended with samples |
| +// in its buffer (a device asleep across a month end, say) writes them |
| +// to their old day when it wakes, however late. usageDayMaxAge is what |
| +// brings such a write to the page. |
| // - A box's edge day takes deltas for the day the flush runs in, never an |
| // earlier one (usage.UpsertEdgeDay, internal/usage/edge.go:117-122, |
| // called every five minutes with time.Now(), internal/host/usage_loop.go). |
| @@ -144,7 +172,13 @@ func daysDirBox(dir, prefix string) (string, bool) { |
| // (internal/console/economicspass.go censusPass and storagePass). |
| // |
| // A day becomes settled at least 24 hours after its end, past all of these |
| -// with a day's margin for clock skew and retries. |
| +// with a day's margin for clock skew and retries. A late write past that |
| +// (a suspended box, a box whose clock was wrong) is not caught by the |
| +// horizon: a kept day is read again once it is usageDayMaxAge old, and the |
| +// hourly pass reads every day of the month to date again, so such a write |
| +// shows within six hours, within an hour for this month's days. The sweep |
| +// lists only the box prefixes, never the day objects, so there is no |
| +// listing ETag to check a kept day against without a request. |
| func usageDaySettled(date string, now time.Time) bool { |
| d, err := time.Parse("2006-01-02", date) |
| if err != nil { |
| @@ -162,29 +196,35 @@ func usageDayFirstKept(now time.Time) string { |
| return usage.DayOf(first.AddDate(0, -1, 0)) |
| } |
| |
| -func (c *usageDayCache) get(key string) (usageDayEntry, bool) { |
| +// get is key's entry, when it was read less than usageDayMaxAge before now. |
| +func (c *usageDayCache) get(key string, now time.Time) (usageDayEntry, bool) { |
| c.mu.Lock() |
| defer c.mu.Unlock() |
| e, ok := c.entries[key] |
| - return e, ok |
| + if !ok || now.Sub(e.at) >= usageDayMaxAge { |
| + return usageDayEntry{}, false |
| + } |
| + return e, true |
| } |
| |
| -// put keeps one settled read: a body no larger than usageDayCacheMaxBody, |
| -// or a not-found. Any other error says nothing about the day and changes |
| -// nothing; an oversized body drops a copy held from before. Past the |
| -// budget, the oldest days are dropped first, which may be this one. |
| +// put keeps one settled read, made at now: a body no larger than |
| +// usageDayCacheMaxBody (put keeps it; the caller must not change it), a |
| +// not-found or an object over the read cap. Any other error says nothing |
| +// about the day and changes nothing; tooBig (a body read whole but too |
| +// large to keep) drops a copy held from before. Past the budget, the |
| +// oldest days are dropped first, which may be this one. |
| func (c *usageDayCache) put(key, date string, body []byte, etag string, err error, now time.Time) { |
| var e usageDayEntry |
| switch { |
| - case err == nil && len(body) <= usageDayCacheMaxBody: |
| - e = usageDayEntry{date: date, body: slices.Clone(body), etag: etag} |
| case err == nil: |
| + e = usageDayEntry{date: date, at: now, body: body, etag: etag} |
| + case errors.Is(err, errUsageDayTooBigToKeep): |
| c.mu.Lock() |
| c.dropLocked(key) |
| c.mu.Unlock() |
| return |
| - case errors.Is(err, os.ErrNotExist): |
| - e = usageDayEntry{date: date, absent: err} |
| + case errors.Is(err, os.ErrNotExist), errors.Is(err, errUsageDayTooLarge): |
| + e = usageDayEntry{date: date, at: now, absent: err} |
| default: |
| return |
| } |
| @@ -237,17 +277,24 @@ func (c *usageDayCache) held() (n int, bytes int64) { |
| } |
| |
| // usageDayStore reads usage day objects through the settled-day cache. |
| -// Every other request passes through to the store untouched. |
| +// Every other request passes through to the store untouched, Open included. |
| +// |
| +// A usage day object is read streaming (Open) and no further than |
| +// usageDayReadCap and one byte. While it is read, a copy is kept of a body |
| +// no larger than usageDayCacheMaxBody for the cache; a larger one is only |
| +// passed on. So one read holds at most the body its reader takes, plus a |
| +// copy of at most usageDayCacheMaxBody. |
| // |
| // A page view's store (use true) answers a settled day from the cache when |
| -// it holds it, and keeps each settled day it reads. Today's and yesterday's |
| -// storage days are read once per view rather than twice (sweepUsage reads |
| -// them for coverage and foldStorageAndCensus for bytes): at most two |
| -// bodies, each no larger than usageDayCacheMaxBody, held for the view. |
| +// it holds a read younger than usageDayMaxAge, and keeps each settled day it |
| +// reads. Today's and yesterday's storage days are read once per view rather |
| +// than twice (sweepUsage reads them for coverage and foldStorageAndCensus |
| +// for bytes): at most two bodies, each no larger than usageDayCacheMaxBody, |
| +// held for the view. |
| // |
| -// The economics pass's store (use false) reads everything from the bucket, |
| -// exactly as before, and keeps each settled day it read, replacing what |
| -// was held: so a day the pass has read is never older than the pass. |
| +// The economics pass's store (use false) reads everything from the bucket |
| +// and keeps each settled day it read, replacing what was held: so a day the |
| +// pass has read is never older than the pass. |
| type usageDayStore struct { |
| release.Store |
| cache *usageDayCache |
| @@ -258,6 +305,10 @@ type usageDayStore struct { |
| view map[string]fetched |
| } |
| |
| +// errUsageDayTooBigToKeep is what a read leaves for the cache when it read |
| +// a body whole that is too large to keep: drop any copy held from before. |
| +var errUsageDayTooBigToKeep = errors.New("console: usage day object too large to keep") |
| + |
| // usageDayReader is a page view's store over the cache, at now. |
| func (s *Server) usageDayReader(now time.Time) *usageDayStore { |
| s.usageDays.prune(now) |
| @@ -271,18 +322,54 @@ func (s *Server) usageDayFiller(now time.Time) *usageDayStore { |
| return &usageDayStore{Store: s.cfg.Releases, cache: &s.usageDays, now: now} |
| } |
| |
| +// usageDayLimit is readConcurrently's limit for the economics sweep: the |
| +// read cap for a usage day object, none for anything else. |
| +func usageDayLimit(key string) int64 { |
| + if _, ok := usageDayDate(key); ok { |
| + return usageDayReadCap |
| + } |
| + return 0 |
| +} |
| + |
| +// Get is Open read whole: for a usage day object, no further than the cap. |
| func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, error) { |
| + if _, ok := usageDayDate(key); !ok { |
| + return d.Store.Get(ctx, key) |
| + } |
| + rc, etag, err := d.open(ctx, key) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + defer rc.Close() |
| + body, err := io.ReadAll(rc) |
| + if err != nil { |
| + return nil, "", err |
| + } |
| + return body, etag, nil |
| +} |
| + |
| +// Open streams key (release.Opener). A usage day object comes from the |
| +// cache when it holds it, and otherwise from the store through a |
| +// usageDayRead. |
| +func (d *usageDayStore) Open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| + return d.open(ctx, key) |
| +} |
| + |
| +// open is Open, under a name of its own: the claim authority census |
| +// (claim_authority_census_test.go) reviews every call of a method named |
| +// Open, and this one opens nothing but a read. |
| +func (d *usageDayStore) open(ctx context.Context, key string) (io.ReadCloser, string, error) { |
| date, ok := usageDayDate(key) |
| if !ok { |
| - return d.Store.Get(ctx, key) |
| + return release.OpenObject(ctx, d.Store, key) |
| } |
| settled := usageDaySettled(date, d.now) |
| if settled && d.use { |
| - if e, hit := d.cache.get(key); hit { |
| + if e, hit := d.cache.get(key, d.now); hit { |
| if e.absent != nil { |
| return nil, "", e.absent |
| } |
| - return e.body, e.etag, nil |
| + return io.NopCloser(bytes.NewReader(e.body)), e.etag, nil |
| } |
| } |
| once := d.use && !settled && key == usage.StorageDayKey(date) |
| @@ -291,21 +378,92 @@ func (d *usageDayStore) Get(ctx context.Context, key string) ([]byte, string, er |
| f, seen := d.view[key] |
| d.mu.Unlock() |
| if seen { |
| - return f.body, f.etag, f.err |
| + if f.err != nil { |
| + return nil, "", f.err |
| + } |
| + return io.NopCloser(bytes.NewReader(f.body)), f.etag, nil |
| } |
| } |
| - body, etag, err := d.Store.Get(ctx, key) |
| - if settled { |
| - d.cache.put(key, date, body, etag, err, d.now) |
| + // keep takes what a finished read leaves behind: a body small enough to |
| + // keep, or an error that will be the same next time. |
| + keep := func(body []byte, etag string, err error) { |
| + if settled { |
| + d.cache.put(key, date, body, etag, err, d.now) |
| + } |
| + if once && (err == nil || errors.Is(err, os.ErrNotExist) || errors.Is(err, errUsageDayTooLarge)) { |
| + d.mu.Lock() |
| + d.view[key] = fetched{body: body, etag: etag, err: err} |
| + d.mu.Unlock() |
| + } |
| } |
| - if once && (err == nil && len(body) <= usageDayCacheMaxBody || errors.Is(err, os.ErrNotExist)) { |
| - d.mu.Lock() |
| - d.view[key] = fetched{body: body, etag: etag, err: err} |
| - d.mu.Unlock() |
| + rc, etag, err := release.OpenObject(ctx, d.Store, key) |
| + if err != nil { |
| + keep(nil, "", err) |
| + return nil, "", err |
| + } |
| + return &usageDayRead{ctx: ctx, rc: rc, key: key, etag: etag, keeping: settled || once, keep: keep}, etag, nil |
| +} |
| + |
| +// usageDayRead is one usage day object streaming from the store. It never |
| +// asks for more than one byte past usageDayReadCap, and fails with |
| +// errUsageDayTooLarge once that byte has come. While the body is no larger |
| +// than usageDayCacheMaxBody it keeps a copy for the cache. When the read |
| +// ends, at the end of the body or at the cap, it hands keep the copy or |
| +// the error, once. |
| +type usageDayRead struct { |
| + ctx context.Context |
| + rc io.ReadCloser |
| + key string |
| + etag string |
| + n int64 |
| + copy []byte |
| + keeping bool |
| + done bool |
| + keep func(body []byte, etag string, err error) |
| +} |
| + |
| +func (r *usageDayRead) Read(p []byte) (int, error) { |
| + if r.n > usageDayReadCap { |
| + return 0, fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge) |
| } |
| - return body, etag, err |
| + if room := usageDayReadCap + 1 - r.n; int64(len(p)) > room { |
| + p = p[:room] |
| + } |
| + n, err := r.rc.Read(p) |
| + r.n += int64(n) |
| + if r.keeping { |
| + if int64(len(r.copy)+n) > usageDayCacheMaxBody { |
| + r.keeping, r.copy = false, nil |
| + } else { |
| + r.copy = append(r.copy, p[:n]...) |
| + } |
| + } |
| + if r.n > usageDayReadCap { |
| + tooLarge := fmt.Errorf("%s: %w", r.key, errUsageDayTooLarge) |
| + if !r.done { |
| + r.done = true |
| + log.Printf("console: sweep usage: %s is over %d bytes; skipped like an unreadable day", r.key, usageDayReadCap) |
| + jobFailed(r.ctx, fmt.Errorf("sweep usage: %w", tooLarge)) |
| + r.keep(nil, "", tooLarge) |
| + } |
| + return n, tooLarge |
| + } |
| + if err == io.EOF && !r.done { |
| + r.done = true |
| + if r.keeping { |
| + if r.copy == nil { |
| + r.copy = []byte{} |
| + } |
| + r.keep(r.copy, r.etag, nil) |
| + } else { |
| + r.keep(nil, "", errUsageDayTooBigToKeep) |
| + } |
| + } |
| + return n, err |
| } |
| |
| +func (r *usageDayRead) Close() error { return r.rc.Close() } |
| + |
| // economicsUsage is what the dashboard reads per day for one period: the |
| // sweep with storage and census folded in (or the error either returned), |
| // and the fleet meters (or the error that degrades them to a warning). |
| @@ -324,7 +482,7 @@ func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, att |
| st := s.usageDayReader(now) |
| // "{}" decodes to an empty rollup, edge, storage and census day, which |
| // every reader here takes without a word. |
| - return readConcurrentlyStats(ctx, st, []byte("{}"), nil, func(rs release.Store) economicsUsage { |
| + out, held := readConcurrentlyStats(ctx, st, []byte("{}"), usageDayLimit, func(rs release.Store) economicsUsage { |
| sweep, err := s.sweepUsage(ctx, rs, from, to, attrib) |
| if err != nil { |
| return economicsUsage{err: err} |
| @@ -338,4 +496,11 @@ func (s *Server) readEconomicsUsage(ctx context.Context, from, to time.Time, att |
| } |
| return out |
| }) |
| + // The sweep skips a day it cannot read, and a read cut off by the |
| + // deadline is one: a sweep that ran out of time is a failed sweep, never |
| + // partial totals. |
| + if err := ctx.Err(); err != nil && out.err == nil { |
| + out = economicsUsage{err: fmt.Errorf("console: sweep usage: %w", err)} |
| + } |
| + return out, held |
| } |