- Notifications
You must be signed in to change notification settings - Fork1.1k
fix: refactor agent resource monitoring API to avoid excessive calls to DB#20430
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 ourterms of service andprivacy statement. We’ll occasionally send you account related emails.
Already on GitHub?Sign in to your account
Merged
Uh oh!
There was an error while loading.Please reload this page.
Merged
Changes fromall commits
Commits
Show all changes
6 commits Select commitHold shift + click to select a range
d00ce62 refactor agent resource monitoring API to avoid excessive calls to DB
cstyan82a6fd0 fix linting
cstyanffcb43b address review comments
cstyan8743e8e ctx is no longer used in this function
cstyan6701660 Merge branch 'main' into callum/workspace-agent-call-volume
cstyan87934c3 remove unnecessary OR condition in monitorMemory
cstyanFile filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
4 changes: 4 additions & 0 deletionscoderd/agentapi/api.go
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
87 changes: 52 additions & 35 deletionscoderd/agentapi/resources_monitoring.go
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 |
|---|---|---|
| @@ -5,6 +5,7 @@ import ( | ||
| "database/sql" | ||
| "errors" | ||
| "fmt" | ||
| "sync" | ||
| "time" | ||
| "golang.org/x/xerrors" | ||
| @@ -33,42 +34,60 @@ type ResourcesMonitoringAPI struct { | ||
| Debounce time.Duration | ||
| Config resourcesmonitor.Config | ||
| // Cache resource monitors on first call to avoid millions of DB queries per day. | ||
| memoryMonitor database.WorkspaceAgentMemoryResourceMonitor | ||
| volumeMonitors []database.WorkspaceAgentVolumeResourceMonitor | ||
| monitorsLock sync.RWMutex | ||
| } | ||
| // InitMonitors fetches resource monitors from the database and caches them. | ||
| // This must be called once after creating a ResourcesMonitoringAPI, the context should be | ||
| // the agent per-RPC connection context. If fetching fails with a real error (not sql.ErrNoRows), the | ||
| // connection should be torn down. | ||
| func (a *ResourcesMonitoringAPI) InitMonitors(ctx context.Context) error { | ||
| memMon, err := a.Database.FetchMemoryResourceMonitorsByAgentID(ctx, a.AgentID) | ||
| if err != nil && !errors.Is(err, sql.ErrNoRows) { | ||
| return xerrors.Errorf("fetch memory resource monitor: %w", err) | ||
| } | ||
| // If sql.ErrNoRows, memoryMonitor stays as zero value (CreatedAt.IsZero() = true). | ||
| // Otherwise, store the fetched monitor. | ||
| if err == nil { | ||
| a.memoryMonitor = memMon | ||
| } | ||
| volMons, err := a.Database.FetchVolumesResourceMonitorsByAgentID(ctx, a.AgentID) | ||
| if err != nil { | ||
| return xerrors.Errorf("fetch volume resource monitors: %w", err) | ||
| } | ||
| // 0 length is valid, indicating none configured, since the volume monitors in the DB can be many. | ||
| a.volumeMonitors = volMons | ||
| return nil | ||
| } | ||
| func (a *ResourcesMonitoringAPI) GetResourcesMonitoringConfiguration(_ context.Context, _ *proto.GetResourcesMonitoringConfigurationRequest) (*proto.GetResourcesMonitoringConfigurationResponse, error) { | ||
cstyan marked this conversation as resolved. Show resolvedHide resolvedUh oh!There was an error while loading.Please reload this page. | ||
| return &proto.GetResourcesMonitoringConfigurationResponse{ | ||
| Config: &proto.GetResourcesMonitoringConfigurationResponse_Config{ | ||
| CollectionIntervalSeconds: int32(a.Config.CollectionInterval.Seconds()), | ||
| NumDatapoints: a.Config.NumDatapoints, | ||
| }, | ||
| Memory: func() *proto.GetResourcesMonitoringConfigurationResponse_Memory { | ||
| ifa.memoryMonitor.CreatedAt.IsZero() { | ||
| return nil | ||
| } | ||
| return &proto.GetResourcesMonitoringConfigurationResponse_Memory{ | ||
| Enabled:a.memoryMonitor.Enabled, | ||
| } | ||
| }(), | ||
| Volumes: func() []*proto.GetResourcesMonitoringConfigurationResponse_Volume { | ||
| volumes := make([]*proto.GetResourcesMonitoringConfigurationResponse_Volume, 0, len(a.volumeMonitors)) | ||
| for _, monitor := rangea.volumeMonitors { | ||
| volumes = append(volumes, &proto.GetResourcesMonitoringConfigurationResponse_Volume{ | ||
| Enabled: monitor.Enabled, | ||
| Path: monitor.Path, | ||
| }) | ||
| } | ||
| return volumes | ||
| }(), | ||
| }, nil | ||
| @@ -77,6 +96,10 @@ func (a *ResourcesMonitoringAPI) GetResourcesMonitoringConfiguration(ctx context | ||
| func (a *ResourcesMonitoringAPI) PushResourcesMonitoringUsage(ctx context.Context, req *proto.PushResourcesMonitoringUsageRequest) (*proto.PushResourcesMonitoringUsageResponse, error) { | ||
| var err error | ||
| // Lock for the entire push operation since calls are sequential from the agent | ||
| a.monitorsLock.Lock() | ||
| defer a.monitorsLock.Unlock() | ||
| if memoryErr := a.monitorMemory(ctx, req.Datapoints); memoryErr != nil { | ||
| err = errors.Join(err, xerrors.Errorf("monitor memory: %w", memoryErr)) | ||
| } | ||
| @@ -89,18 +112,7 @@ func (a *ResourcesMonitoringAPI) PushResourcesMonitoringUsage(ctx context.Contex | ||
| } | ||
| func (a *ResourcesMonitoringAPI) monitorMemory(ctx context.Context, datapoints []*proto.PushResourcesMonitoringUsageRequest_Datapoint) error { | ||
| if !a.memoryMonitor.Enabled { | ||
| return nil | ||
| } | ||
| @@ -109,15 +121,15 @@ func (a *ResourcesMonitoringAPI) monitorMemory(ctx context.Context, datapoints [ | ||
| usageDatapoints = append(usageDatapoints, datapoint.Memory) | ||
| } | ||
| usageStates := resourcesmonitor.CalculateMemoryUsageStates(a.memoryMonitor, usageDatapoints) | ||
| oldState :=a.memoryMonitor.State | ||
| newState := resourcesmonitor.NextState(a.Config, oldState, usageStates) | ||
| debouncedUntil, shouldNotify :=a.memoryMonitor.Debounce(a.Debounce, a.Clock.Now(), oldState, newState) | ||
| //nolint:gocritic // We need to be able to update the resource monitor here. | ||
| err:= a.Database.UpdateMemoryResourceMonitor(dbauthz.AsResourceMonitor(ctx), database.UpdateMemoryResourceMonitorParams{ | ||
| AgentID: a.AgentID, | ||
| State: newState, | ||
| UpdatedAt: dbtime.Time(a.Clock.Now()), | ||
| @@ -127,6 +139,11 @@ func (a *ResourcesMonitoringAPI) monitorMemory(ctx context.Context, datapoints [ | ||
| return xerrors.Errorf("update workspace monitor: %w", err) | ||
| } | ||
| // Update cached state | ||
| a.memoryMonitor.State = newState | ||
| a.memoryMonitor.DebouncedUntil = dbtime.Time(debouncedUntil) | ||
| a.memoryMonitor.UpdatedAt = dbtime.Time(a.Clock.Now()) | ||
| if !shouldNotify { | ||
| return nil | ||
| } | ||
| @@ -143,7 +160,7 @@ func (a *ResourcesMonitoringAPI) monitorMemory(ctx context.Context, datapoints [ | ||
| notifications.TemplateWorkspaceOutOfMemory, | ||
| map[string]string{ | ||
| "workspace": workspace.Name, | ||
| "threshold": fmt.Sprintf("%d%%",a.memoryMonitor.Threshold), | ||
| }, | ||
| map[string]any{ | ||
| // NOTE(DanielleMaywood): | ||
| @@ -169,14 +186,9 @@ func (a *ResourcesMonitoringAPI) monitorMemory(ctx context.Context, datapoints [ | ||
| } | ||
| func (a *ResourcesMonitoringAPI) monitorVolumes(ctx context.Context, datapoints []*proto.PushResourcesMonitoringUsageRequest_Datapoint) error { | ||
| outOfDiskVolumes := make([]map[string]any, 0) | ||
| fori, monitor := rangea.volumeMonitors { | ||
| if !monitor.Enabled { | ||
| continue | ||
| } | ||
| @@ -219,6 +231,11 @@ func (a *ResourcesMonitoringAPI) monitorVolumes(ctx context.Context, datapoints | ||
| }); err != nil { | ||
| return xerrors.Errorf("update workspace monitor: %w", err) | ||
| } | ||
| // Update cached state | ||
| a.volumeMonitors[i].State = newState | ||
| a.volumeMonitors[i].DebouncedUntil = dbtime.Time(debouncedUntil) | ||
| a.volumeMonitors[i].UpdatedAt = dbtime.Time(a.Clock.Now()) | ||
| } | ||
| if len(outOfDiskVolumes) == 0 { | ||
26 changes: 26 additions & 0 deletionscoderd/agentapi/resources_monitoring_test.go
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
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
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.