diff options
author | GitLab Bot <gitlab-bot@gitlab.com> | 2022-01-20 12:16:11 +0300 |
---|---|---|
committer | GitLab Bot <gitlab-bot@gitlab.com> | 2022-01-20 12:16:11 +0300 |
commit | edaa33dee2ff2f7ea3fac488d41558eb5f86d68c (patch) | |
tree | 11f143effbfeba52329fb7afbd05e6e2a3790241 /app/services/clusters/agent_tokens/track_usage_service.rb | |
parent | d8a5691316400a0f7ec4f83832698f1988eb27c1 (diff) |
Add latest changes from gitlab-org/gitlab@14-7-stable-eev14.7.0-rc42
Diffstat (limited to 'app/services/clusters/agent_tokens/track_usage_service.rb')
-rw-r--r-- | app/services/clusters/agent_tokens/track_usage_service.rb | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/app/services/clusters/agent_tokens/track_usage_service.rb b/app/services/clusters/agent_tokens/track_usage_service.rb new file mode 100644 index 00000000000..fdc79ac0f8b --- /dev/null +++ b/app/services/clusters/agent_tokens/track_usage_service.rb @@ -0,0 +1,54 @@ +# frozen_string_literal: true + +module Clusters + module AgentTokens + class TrackUsageService + # The `UPDATE_USED_COLUMN_EVERY` defines how often the token DB entry can be updated + UPDATE_USED_COLUMN_EVERY = (40.minutes..55.minutes).freeze + + delegate :agent, to: :token + + def initialize(token) + @token = token + end + + def execute + track_values = { last_used_at: Time.current.utc } + + token.cache_attributes(track_values) + + if can_update_track_values? + log_activity_event!(track_values[:last_used_at]) unless agent.connected? + + # Use update_column so updated_at is skipped + token.update_columns(track_values) + end + end + + private + + attr_reader :token + + def can_update_track_values? + # Use a random threshold to prevent beating DB updates. + last_used_at_max_age = Random.rand(UPDATE_USED_COLUMN_EVERY) + + real_last_used_at = token.read_attribute(:last_used_at) + + # Handle too many updates from high token traffic + real_last_used_at.nil? || + (Time.current - real_last_used_at) >= last_used_at_max_age + end + + def log_activity_event!(recorded_at) + Clusters::Agents::CreateActivityEventService.new( + agent, + kind: :agent_connected, + level: :info, + recorded_at: recorded_at, + agent_token: token + ).execute + end + end + end +end |