Repository navigation
feat(health): record application health history #425
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
Merged
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
3 changes: 3 additions & 0 deletions
3
backend/internal/hub/db/migrations/000036_create_application_health_changes_table.down.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,3 @@ | ||
| DROP INDEX IF EXISTS idx_application_health_changes_changed; | ||
| DROP INDEX IF EXISTS idx_application_health_changes_app_changed; | ||
| DROP TABLE IF EXISTS application_health_changes; |
14 changes: 14 additions & 0 deletions
14
backend/internal/hub/db/migrations/000036_create_application_health_changes_table.up.sql
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| CREATE TABLE IF NOT EXISTS application_health_changes ( | ||
| id TEXT PRIMARY KEY, | ||
| application_id TEXT NOT NULL, | ||
| status TEXT NOT NULL, | ||
| reason TEXT, | ||
| services TEXT, | ||
| changed_at DATETIME NOT NULL DEFAULT (datetime('now')), | ||
| FOREIGN KEY (application_id) REFERENCES applications(id) ON DELETE CASCADE | ||
| ); | ||
|
|
||
| CREATE INDEX IF NOT EXISTS idx_application_health_changes_app_changed | ||
| ON application_health_changes(application_id, changed_at DESC, id DESC); | ||
| CREATE INDEX IF NOT EXISTS idx_application_health_changes_changed | ||
| ON application_health_changes(changed_at); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,179 @@ | ||
| // Package healthhistory records application health changes and keeps them | ||
| // for the availability statistics. | ||
| package healthhistory | ||
|
|
||
| import ( | ||
| "context" | ||
| "errors" | ||
| "strings" | ||
| "sync" | ||
| "time" | ||
| "unicode/utf8" | ||
|
|
||
| "github.com/OrcaCD/orca-cd/internal/hub/db" | ||
| "github.com/OrcaCD/orca-cd/internal/hub/models" | ||
| "github.com/rs/zerolog" | ||
| "gorm.io/gorm" | ||
| ) | ||
|
|
||
| // Retention is how long health changes are kept. The longest statistics range | ||
| // must fit into it. | ||
| const Retention = 30 * 24 * time.Hour | ||
|
|
||
| const ( | ||
| pruneInterval = 24 * time.Hour | ||
| // Services and their names come from agents, so both are bounded before | ||
| // they are persisted. | ||
| maxServices = 32 | ||
| maxServiceNameLength = 128 | ||
| ) | ||
|
|
||
| // Record stores a health change unless the application's latest recorded | ||
| // status is the same. A change dated before the latest one is moved to the | ||
| // latest change's time so the history stays ordered. The very first change of | ||
| // an application is not recorded when it is unknown, as no data is implied | ||
| // before the first change anyway. | ||
| // | ||
| // Callers must serialize changes per application; the hub does so by | ||
| // handling each agent's messages sequentially. | ||
| func Record(ctx context.Context, change models.ApplicationHealthChange) (bool, error) { | ||
| if change.ChangedAt.IsZero() { | ||
| change.ChangedAt = time.Now() | ||
| } | ||
|
|
||
| latest, err := Latest(ctx, change.ApplicationId) | ||
| switch { | ||
| case errors.Is(err, gorm.ErrRecordNotFound): | ||
| if change.Status == models.UnknownHealth { | ||
| return false, nil | ||
| } | ||
| case err != nil: | ||
| return false, err | ||
| case latest.Status == change.Status: | ||
| return false, nil | ||
| case change.ChangedAt.Before(latest.ChangedAt): | ||
| change.ChangedAt = latest.ChangedAt | ||
| } | ||
|
|
||
| change.Services = sanitizeServices(change.Services) | ||
| if err := gorm.G[models.ApplicationHealthChange](db.DB).Create(ctx, &change); err != nil { | ||
| return false, err | ||
| } | ||
| return true, nil | ||
| } | ||
|
|
||
| // Latest returns the most recent health change of an application. | ||
| func Latest(ctx context.Context, applicationID string) (models.ApplicationHealthChange, error) { | ||
| return gorm.G[models.ApplicationHealthChange](db.DB). | ||
| Where("application_id = ?", applicationID). | ||
| Order("changed_at DESC, id DESC"). | ||
| First(ctx) | ||
| } | ||
|
|
||
| // RecordAgentOffline marks the health of all applications of an agent as | ||
| // unknown because the agent is no longer connected. | ||
| func RecordAgentOffline(ctx context.Context, agentID string, at time.Time) error { | ||
| apps, err := gorm.G[models.Application](db.DB).Select("id").Where("agent_id = ?", agentID).Find(ctx) | ||
| if err != nil { | ||
| return err | ||
| } | ||
|
|
||
| reason := models.HealthChangeReasonAgentOffline | ||
| var errs []error | ||
| for _, app := range apps { | ||
| if _, err := Record(ctx, models.ApplicationHealthChange{ | ||
| ApplicationId: app.Id, | ||
| Status: models.UnknownHealth, | ||
| Reason: &reason, | ||
| ChangedAt: at, | ||
| }); err != nil { | ||
| errs = append(errs, err) | ||
| } | ||
| } | ||
| return errors.Join(errs...) | ||
| } | ||
|
|
||
| // Prune deletes health changes older than the retention. The latest change | ||
| // before the cutoff is kept per application, as it defines the status at the | ||
| // start of the longest range. | ||
| func Prune(ctx context.Context, now time.Time) (int, error) { | ||
| cutoff := now.Add(-Retention).UTC() | ||
| return gorm.G[models.ApplicationHealthChange](db.DB). | ||
| Where(`changed_at < ? AND id NOT IN ( | ||
| SELECT id FROM ( | ||
| SELECT id, ROW_NUMBER() OVER (PARTITION BY application_id ORDER BY changed_at DESC, id DESC) AS position | ||
| FROM application_health_changes | ||
| WHERE changed_at < ? | ||
| ) WHERE position = 1 | ||
| )`, cutoff, cutoff). | ||
| Delete(ctx) | ||
| } | ||
|
|
||
| // StartPruner prunes the health history now and then once a day. The returned | ||
| // stop function cancels a running prune and waits for the pruner to exit, so | ||
| // the database can be closed afterwards. | ||
| func StartPruner(log *zerolog.Logger) (stop func()) { | ||
|
alex289 marked this conversation as resolved.
|
||
| ctx, cancel := context.WithCancel(context.Background()) | ||
| stopped := make(chan struct{}) | ||
| prune := func() { | ||
| pruneCtx, cancelPrune := context.WithTimeout(ctx, time.Minute) | ||
| defer cancelPrune() | ||
| deleted, err := Prune(pruneCtx, time.Now()) | ||
| if err != nil { | ||
| if ctx.Err() == nil { | ||
| log.Error().Err(err).Msg("failed to prune application health history") | ||
| } | ||
| return | ||
| } | ||
| if deleted > 0 { | ||
| log.Debug().Int("count", deleted).Msg("pruned application health history") | ||
| } | ||
| } | ||
|
|
||
| go func() { | ||
| defer close(stopped) | ||
| prune() | ||
| ticker := time.NewTicker(pruneInterval) | ||
| defer ticker.Stop() | ||
| for { | ||
| select { | ||
| case <-ticker.C: | ||
| prune() | ||
| case <-ctx.Done(): | ||
| return | ||
| } | ||
| } | ||
| }() | ||
| var once sync.Once | ||
| return func() { | ||
| once.Do(func() { | ||
| cancel() | ||
| <-stopped | ||
| }) | ||
| } | ||
| } | ||
|
|
||
| func sanitizeServices(services []models.ServiceHealth) []models.ServiceHealth { | ||
| if len(services) == 0 { | ||
| return nil | ||
| } | ||
| services = services[:min(len(services), maxServices)] | ||
| sanitized := make([]models.ServiceHealth, 0, len(services)) | ||
| for _, service := range services { | ||
| name := strings.ToValidUTF8(service.Name, "") | ||
| name = strings.TrimSpace(truncate(strings.TrimSpace(name), maxServiceNameLength)) | ||
| sanitized = append(sanitized, models.ServiceHealth{Name: name, Status: service.Status}) | ||
| } | ||
| return sanitized | ||
| } | ||
|
|
||
| // truncate cuts s to at most maxBytes without splitting a UTF-8 character. | ||
| func truncate(s string, maxBytes int) string { | ||
| if len(s) <= maxBytes { | ||
| return s | ||
| } | ||
| for maxBytes > 0 && !utf8.RuneStart(s[maxBytes]) { | ||
| maxBytes-- | ||
| } | ||
| return s[:maxBytes] | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.