runner.rb 8.4 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

11
    RUNNER_QUEUE_EXPIRY_TIME = 60.minutes
A
Alessio Caiazza 已提交
12
    ONLINE_CONTACT_TIMEOUT = 1.hour
13
    UPDATE_DB_RUNNER_INFO_EVERY = 40.minutes
D
Douwe Maan 已提交
14
    AVAILABLE_SCOPES = %w[specific shared active paused online].freeze
15
    FORM_EDITABLE = %i[description tag_list active run_untagged locked access_level maximum_timeout_human_readable].freeze
16

17 18
    ignore_column :is_shared

19
    has_many :builds
K
Kamil Trzciński 已提交
20
    has_many :runner_projects, inverse_of: :runner, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
21
    has_many :projects, through: :runner_projects
K
Kamil Trzciński 已提交
22
    has_many :runner_namespaces, inverse_of: :runner
23
    has_many :groups, through: :runner_namespaces
D
Douwe Maan 已提交
24 25 26 27 28

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

    before_validation :set_default_values

29 30 31 32
    scope :active, -> { where(active: true) }
    scope :paused, -> { where(active: false) }
    scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
    scope :ordered, -> { order(id: :desc) }
33

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

39 40 41
    scope :belonging_to_project, -> (project_id) {
      joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
    }
42

43
    scope :belonging_to_parent_group_of_project, -> (project_id) {
44 45 46 47
      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 })
48
    }
49

50
    scope :owned_or_instance_wide, -> (project_id) do
51
      union = Gitlab::SQL::Union.new(
52
        [belonging_to_project(project_id), belonging_to_parent_group_of_project(project_id), instance_type],
53 54
        remove_duplicates: false
      )
55
      from("(#{union.to_sql}) ci_runners")
56 57
    end

L
Lin Jen-Shin 已提交
58
    scope :assignable_for, ->(project) do
L
Lin Jen-Shin 已提交
59 60
      # FIXME: That `to_sql` is needed to workaround a weird Rails bug.
      #        Without that, placeholders would miss one and couldn't match.
61
      where(locked: false)
62
        .where.not("ci_runners.id IN (#{project.runners.select(:id).to_sql})")
63
        .project_type
64 65
    end

66
    validate :tag_constraints
67
    validates :access_level, presence: true
68
    validates :runner_type, presence: true
69

70 71 72 73 74
    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 已提交
75 76
    acts_as_taggable

77 78
    after_destroy :cleanup_runner_queue

79
    enum access_level: {
80 81
      not_protected: 0,
      ref_protected: 1
82 83
    }

84 85 86 87 88 89
    enum runner_type: {
      instance_type: 1,
      group_type: 2,
      project_type: 3
    }

90
    cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
91

92
    chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout
93

94 95 96 97
    validates :maximum_timeout, allow_nil: true,
                                numericality: { greater_than_or_equal_to: 600,
                                                message: 'needs to be at least 10 minutes' }

98 99 100 101 102 103 104 105 106 107 108 109
    # 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 已提交
110
    def self.search(query)
111
      fuzzy_search(query, [:token, :description])
D
Douwe Maan 已提交
112 113
    end

A
Alessio Caiazza 已提交
114 115 116 117
    def self.contact_time_deadline
      ONLINE_CONTACT_TIMEOUT.ago
    end

D
Douwe Maan 已提交
118 119 120 121 122
    def set_default_values
      self.token = SecureRandom.hex(15) if self.token.blank?
    end

    def assign_to(project, current_user = nil)
123
      if instance_type?
124
        self.runner_type = :project_type
125 126
      elsif group_type?
        raise ArgumentError, 'Transitioning a group runner to a project runner is not supported'
127 128
      end

129 130 131 132 133 134 135 136 137
      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 已提交
138 139 140
    end

    def display_name
141
      return short_sha if description.blank?
D
Douwe Maan 已提交
142 143 144 145

      description
    end

146
    def online?
147
      contacted_at && contacted_at > self.class.contact_time_deadline
148 149 150 151 152 153 154 155 156 157 158 159
    end

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

D
Douwe Maan 已提交
160 161 162 163
    def belongs_to_one_project?
      runner_projects.count == 1
    end

164
    def assigned_to_group?
165
      runner_namespaces.any?
A
Alexis Reigel 已提交
166 167
    end

168
    def assigned_to_project?
A
Alexis Reigel 已提交
169 170 171
      runner_projects.any?
    end

172
    def can_pick?(build)
173
      return false if self.ref_protected? && !build.protected?
S
Shinya Maeda 已提交
174

175
      assignable_for?(build.project_id) && accepting_tags?(build)
176 177
    end

D
Douwe Maan 已提交
178 179 180 181 182
    def only_for?(project)
      projects == [project]
    end

    def short_sha
K
Kamil Trzcinski 已提交
183
      token[0...8] if token
D
Douwe Maan 已提交
184
    end
185 186 187 188

    def has_tags?
      tag_list.any?
    end
189

190
    def predefined_variables
191 192 193 194
      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)
195 196
    end

K
Kim "BKC" Carlbäcker 已提交
197
    def tick_runner_queue
198
      SecureRandom.hex.tap do |new_update|
K
Kamil Trzcinski 已提交
199
        ::Gitlab::Workhorse.set_key_and_notify(runner_queue_key, new_update,
200
          expire: RUNNER_QUEUE_EXPIRY_TIME, overwrite: true)
201
      end
202 203
    end

K
Kim "BKC" Carlbäcker 已提交
204
    def ensure_runner_queue_value
K
Kamil Trzcinski 已提交
205 206 207
      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 已提交
208 209
    end

210
    def runner_queue_value_latest?(value)
K
Kim "BKC" Carlbäcker 已提交
211
      ensure_runner_queue_value == value if value.present?
212 213
    end

214
    def update_cached_info(values)
215
      values = values&.slice(:version, :revision, :platform, :architecture, :ip_address) || {}
216
      values[:contacted_at] = Time.now
217

218
      cache_attributes(values)
219

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

224
    def pick_build!(build)
225 226 227 228 229
      if can_pick?(build)
        tick_runner_queue
      end
    end

230 231
    private

232
    def cleanup_runner_queue
233
      Gitlab::Redis::Queues.with do |redis|
234 235 236 237
        redis.del(runner_queue_key)
      end
    end

K
Kim "BKC" Carlbäcker 已提交
238
    def runner_queue_key
K
Kim "BKC" Carlbäcker 已提交
239
      "runner:build_queue:#{self.token}"
240 241
    end

242 243 244
    def persist_cached_data?
      # Use a random threshold to prevent beating DB updates.
      # It generates a distribution between [40m, 80m].
245

246 247 248 249 250 251 252
      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

253
    def tag_constraints
254 255 256 257 258
      unless has_tags? || run_untagged?
        errors.add(:tags_list,
          'can not be empty when runner is not allowed to pick untagged jobs')
      end
    end
259

260
    def assignable_for?(project_id)
261
      self.class.owned_or_instance_wide(project_id).where(id: self.id).any?
262 263
    end

264 265
    def no_projects
      if projects.any?
266
        errors.add(:runner, 'cannot have projects assigned')
267 268 269 270 271
      end
    end

    def no_groups
      if groups.any?
272 273 274 275 276 277 278 279 280 281 282 283 284
        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')
285
      end
286
    end
287

288 289
    def accepting_tags?(build)
      (run_untagged? || build.has_tags?) && (build.tag_list - tag_list).empty?
290
    end
D
Douwe Maan 已提交
291 292
  end
end