runner.rb 9.5 KB
Newer Older
1 2
# frozen_string_literal: true

D
Douwe Maan 已提交
3 4
module Ci
  class Runner < ActiveRecord::Base
5
    extend Gitlab::Ci::Model
6
    include Gitlab::SQL::Pattern
7
    include IgnorableColumn
8
    include RedisCacheable
9
    include ChronicDurationAttribute
10
    include FromUnion
11 12 13
    include TokenAuthenticatable

    add_authentication_token_field :token, encrypted: true, fallback: true
14

A
Alexis Reigel 已提交
15 16 17 18 19 20 21 22 23 24 25
    enum access_level: {
      not_protected: 0,
      ref_protected: 1
    }

    enum runner_type: {
      instance_type: 1,
      group_type: 2,
      project_type: 3
    }

26
    RUNNER_QUEUE_EXPIRY_TIME = 60.minutes
A
Alessio Caiazza 已提交
27
    ONLINE_CONTACT_TIMEOUT = 1.hour
28
    UPDATE_DB_RUNNER_INFO_EVERY = 40.minutes
A
Alexis Reigel 已提交
29 30
    AVAILABLE_TYPES_LEGACY = %w[specific shared].freeze
    AVAILABLE_TYPES = runner_types.keys.freeze
31
    AVAILABLE_STATUSES = %w[active paused online offline].freeze
A
Alexis Reigel 已提交
32
    AVAILABLE_SCOPES = (AVAILABLE_TYPES_LEGACY + AVAILABLE_TYPES + AVAILABLE_STATUSES).freeze
33
    FORM_EDITABLE = %i[description tag_list active run_untagged locked access_level maximum_timeout_human_readable].freeze
34

35 36
    ignore_column :is_shared

37
    has_many :builds
K
Kamil Trzciński 已提交
38
    has_many :runner_projects, inverse_of: :runner, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
39
    has_many :projects, through: :runner_projects
K
Kamil Trzciński 已提交
40
    has_many :runner_namespaces, inverse_of: :runner
41
    has_many :groups, through: :runner_namespaces
D
Douwe Maan 已提交
42 43 44

    has_one :last_build, ->() { order('id DESC') }, class_name: 'Ci::Build'

45
    before_save :ensure_token
D
Douwe Maan 已提交
46

47 48 49
    scope :active, -> { where(active: true) }
    scope :paused, -> { where(active: false) }
    scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
50 51 52 53 54 55
    # The following query using negation is cheaper than using `contacted_at <= ?`
    # because there are less runners online than have been created. The
    # resulting query is quickly finding online ones and then uses the regular
    # indexed search and rejects the ones that are in the previous set. If we
    # did `contacted_at <= ?` the query would effectively have to do a seq
    # scan.
A
Alexis Reigel 已提交
56
    scope :offline, -> { where.not(id: online) }
57
    scope :ordered, -> { order(id: :desc) }
58

59
    # BACKWARD COMPATIBILITY: There are needed to maintain compatibility with `AVAILABLE_SCOPES` used by `lib/api/runners.rb`
60
    scope :deprecated_shared, -> { instance_type }
61
    # this should get replaced with `project_type.or(group_type)` once using Rails5
62
    scope :deprecated_specific, -> { where(runner_type: [runner_types[:project_type], runner_types[:group_type]]) }
63

64 65 66
    scope :belonging_to_project, -> (project_id) {
      joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
    }
67

68
    scope :belonging_to_parent_group_of_project, -> (project_id) {
69 70 71 72
      project_groups = ::Group.joins(:projects).where(projects: { id: project_id })
      hierarchy_groups = Gitlab::GroupHierarchy.new(project_groups).base_and_ancestors

      joins(:groups).where(namespaces: { id: hierarchy_groups })
73
    }
74

75
    scope :owned_or_instance_wide, -> (project_id) do
76 77 78 79 80 81
      from_union(
        [
          belonging_to_project(project_id),
          belonging_to_parent_group_of_project(project_id),
          instance_type
        ],
82 83
        remove_duplicates: false
      )
84 85
    end

L
Lin Jen-Shin 已提交
86
    scope :assignable_for, ->(project) do
L
Lin Jen-Shin 已提交
87 88
      # FIXME: That `to_sql` is needed to workaround a weird Rails bug.
      #        Without that, placeholders would miss one and couldn't match.
89 90 91 92 93
      #
      # We use "unscoped" here so that any current Ci::Runner filters don't
      # apply to the inner query, which is not necessary.
      exclude_runners = unscoped { project.runners.select(:id) }.to_sql

94
      where(locked: false)
95
        .where.not("ci_runners.id IN (#{exclude_runners})")
96
        .project_type
97 98
    end

99 100 101
    scope :order_contacted_at_asc, -> { order(contacted_at: :asc) }
    scope :order_created_at_desc, -> { order(created_at: :desc) }

102
    validate :tag_constraints
103
    validates :access_level, presence: true
104
    validates :runner_type, presence: true
105

106 107 108 109 110
    validate :no_projects, unless: :project_type?
    validate :no_groups, unless: :group_type?
    validate :any_project, if: :project_type?
    validate :exactly_one_group, if: :group_type?

D
Douwe Maan 已提交
111 112
    acts_as_taggable

113 114
    after_destroy :cleanup_runner_queue

115
    cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
116

117
    chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout
118

119 120 121 122
    validates :maximum_timeout, allow_nil: true,
                                numericality: { greater_than_or_equal_to: 600,
                                                message: 'needs to be at least 10 minutes' }

123 124 125 126 127 128 129 130 131 132 133 134
    # Searches for runners matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # This method performs a *partial* match on tokens, thus a query for "a"
    # will match any runner where the token contains the letter "a". As a result
    # you should *not* use this method for non-admin purposes as otherwise users
    # might be able to query a list of all runners.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation.
D
Douwe Maan 已提交
135
    def self.search(query)
136
      fuzzy_search(query, [:token, :description])
D
Douwe Maan 已提交
137 138
    end

A
Alessio Caiazza 已提交
139 140 141 142
    def self.contact_time_deadline
      ONLINE_CONTACT_TIMEOUT.ago
    end

143 144 145 146 147 148 149 150
    def self.order_by(order)
      if order == 'contacted_asc'
        order_contacted_at_asc
      else
        order_created_at_desc
      end
    end

D
Douwe Maan 已提交
151
    def assign_to(project, current_user = nil)
152
      if instance_type?
153
        self.runner_type = :project_type
154 155
      elsif group_type?
        raise ArgumentError, 'Transitioning a group runner to a project runner is not supported'
156 157
      end

158 159 160 161 162 163 164 165 166
      begin
        transaction do
          self.projects << project
          self.save!
        end
      rescue ActiveRecord::RecordInvalid => e
        self.errors.add(:assign_to, e.message)
        false
      end
D
Douwe Maan 已提交
167 168 169
    end

    def display_name
170
      return short_sha if description.blank?
D
Douwe Maan 已提交
171 172 173 174

      description
    end

175
    def online?
176
      contacted_at && contacted_at > self.class.contact_time_deadline
177 178 179 180 181 182 183 184 185 186 187 188
    end

    def status
      if contacted_at.nil?
        :not_connected
      elsif active?
        online? ? :online : :offline
      else
        :paused
      end
    end

D
Douwe Maan 已提交
189 190 191 192
    def belongs_to_one_project?
      runner_projects.count == 1
    end

193
    def assigned_to_group?
194
      runner_namespaces.any?
A
Alexis Reigel 已提交
195 196
    end

197
    def assigned_to_project?
A
Alexis Reigel 已提交
198 199 200
      runner_projects.any?
    end

201
    def can_pick?(build)
202
      return false if self.ref_protected? && !build.protected?
S
Shinya Maeda 已提交
203

204
      assignable_for?(build.project_id) && accepting_tags?(build)
205 206
    end

D
Douwe Maan 已提交
207 208 209 210 211
    def only_for?(project)
      projects == [project]
    end

    def short_sha
K
Kamil Trzcinski 已提交
212
      token[0...8] if token
D
Douwe Maan 已提交
213
    end
214 215 216 217

    def has_tags?
      tag_list.any?
    end
218

219
    def predefined_variables
220 221 222 223
      Gitlab::Ci::Variables::Collection.new
        .append(key: 'CI_RUNNER_ID', value: id.to_s)
        .append(key: 'CI_RUNNER_DESCRIPTION', value: description)
        .append(key: 'CI_RUNNER_TAGS', value: tag_list.to_s)
224 225
    end

K
Kim "BKC" Carlbäcker 已提交
226
    def tick_runner_queue
227
      SecureRandom.hex.tap do |new_update|
K
Kamil Trzcinski 已提交
228
        ::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_update,
229
          expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: true)
230
      end
231 232
    end

K
Kim "BKC" Carlbäcker 已提交
233
    def ensure_runner_queue_value
K
Kamil Trzcinski 已提交
234 235 236
      new_value = SecureRandom.hex
      ::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_value,
        expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: false)
K
Kim "BKC" Carlbäcker 已提交
237 238
    end

239
    def runner_queue_value_latest?(value)
K
Kim "BKC" Carlbäcker 已提交
240
      ensure_runner_queue_value == value if value.present?
241 242
    end

243
    def update_cached_info(values)
244
      values = values&.slice(:version, :revision, :platform, :architecture, :ip_address) || {}
245
      values[:contacted_at] = Time.now
246

247
      cache_attributes(values)
248

K
Kamil Trzciński 已提交
249 250
      # We save data without validation, it will always change due to `contacted_at`
      self.update_columns(values) if persist_cached_data?
251 252
    end

253
    def pick_build!(build)
254 255 256 257 258
      if can_pick?(build)
        tick_runner_queue
      end
    end

259 260
    private

261
    def cleanup_runner_queue
262
      Gitlab::Redis::Queues.with do |redis|
263 264 265 266
        redis.del(runner_queue_key)
      end
    end

K
Kim "BKC" Carlbäcker 已提交
267
    def runner_queue_key
K
Kim "BKC" Carlbäcker 已提交
268
      "runner:build_queue:#{self.token}"
269 270
    end

271 272 273
    def persist_cached_data?
      # Use a random threshold to prevent beating DB updates.
      # It generates a distribution between [40m, 80m].
274

275 276 277 278 279 280 281
      contacted_at_max_age = UPDATE_DB_RUNNER_INFO_EVERY + Random.rand(UPDATE_DB_RUNNER_INFO_EVERY)

      real_contacted_at = read_attribute(:contacted_at)
      real_contacted_at.nil? ||
        (Time.now - real_contacted_at) >= contacted_at_max_age
    end

282
    def tag_constraints
283 284 285 286 287
      unless has_tags? || run_untagged?
        errors.add(:tags_list,
          'can not be empty when runner is not allowed to pick untagged jobs')
      end
    end
288

289
    def assignable_for?(project_id)
290
      self.class.owned_or_instance_wide(project_id).where(id: self.id).any?
291 292
    end

293 294
    def no_projects
      if projects.any?
295
        errors.add(:runner, 'cannot have projects assigned')
296 297 298 299 300
      end
    end

    def no_groups
      if groups.any?
301 302 303 304 305 306 307 308 309 310 311 312 313
        errors.add(:runner, 'cannot have groups assigned')
      end
    end

    def any_project
      unless projects.any?
        errors.add(:runner, 'needs to be assigned to at least one project')
      end
    end

    def exactly_one_group
      unless groups.one?
        errors.add(:runner, 'needs to be assigned to exactly one group')
314
      end
315
    end
316

317 318
    def accepting_tags?(build)
      (run_untagged? || build.has_tags?) && (build.tag_list - tag_list).empty?
319
    end
D
Douwe Maan 已提交
320 321
  end
end