2020-10-24 23:57:45 +05:30
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
module Clusters
|
|
|
|
class AgentToken < ApplicationRecord
|
2021-04-29 21:17:54 +05:30
|
|
|
include RedisCacheable
|
2020-10-24 23:57:45 +05:30
|
|
|
include TokenAuthenticatable
|
2021-04-29 21:17:54 +05:30
|
|
|
|
2021-01-29 00:20:46 +05:30
|
|
|
add_authentication_token_field :token, encrypted: :required, token_generator: -> { Devise.friendly_token(50) }
|
2021-06-08 01:23:25 +05:30
|
|
|
cached_attr_reader :last_used_at
|
2020-10-24 23:57:45 +05:30
|
|
|
|
|
|
|
self.table_name = 'cluster_agent_tokens'
|
|
|
|
|
2021-04-29 21:17:54 +05:30
|
|
|
# The `UPDATE_USED_COLUMN_EVERY` defines how often the token DB entry can be updated
|
|
|
|
UPDATE_USED_COLUMN_EVERY = (40.minutes..55.minutes).freeze
|
|
|
|
|
2021-04-17 20:07:23 +05:30
|
|
|
belongs_to :agent, class_name: 'Clusters::Agent', optional: false
|
2021-03-11 19:13:27 +05:30
|
|
|
belongs_to :created_by_user, class_name: 'User', optional: true
|
2020-10-24 23:57:45 +05:30
|
|
|
|
|
|
|
before_save :ensure_token
|
2021-04-17 20:07:23 +05:30
|
|
|
|
|
|
|
validates :description, length: { maximum: 1024 }
|
2021-04-29 21:17:54 +05:30
|
|
|
validates :name, presence: true, length: { maximum: 255 }
|
|
|
|
|
2021-06-08 01:23:25 +05:30
|
|
|
scope :order_last_used_at_desc, -> { order(::Gitlab::Database.nulls_last_order('last_used_at', 'DESC')) }
|
|
|
|
|
2021-04-29 21:17:54 +05:30
|
|
|
def track_usage
|
|
|
|
track_values = { last_used_at: Time.current.utc }
|
|
|
|
|
|
|
|
cache_attributes(track_values)
|
|
|
|
|
2022-01-26 12:08:38 +05:30
|
|
|
if can_update_track_values?
|
|
|
|
log_activity_event!(track_values[:last_used_at]) unless agent.active?
|
|
|
|
|
|
|
|
# Use update_column so updated_at is skipped
|
|
|
|
update_columns(track_values)
|
|
|
|
end
|
2021-04-29 21:17:54 +05:30
|
|
|
end
|
|
|
|
|
|
|
|
private
|
|
|
|
|
|
|
|
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 = 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
|
2022-01-26 12:08:38 +05:30
|
|
|
|
|
|
|
def log_activity_event!(recorded_at)
|
|
|
|
agent.activity_events.create!(
|
|
|
|
kind: :agent_connected,
|
|
|
|
level: :info,
|
|
|
|
recorded_at: recorded_at,
|
|
|
|
agent_token: self
|
|
|
|
)
|
|
|
|
end
|
2020-10-24 23:57:45 +05:30
|
|
|
end
|
|
|
|
end
|