runner.rb 8.6 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
14 15 16
    AVAILABLE_TYPES = %w[specific shared].freeze
    AVAILABLE_STATUSES = %w[active paused online offline].freeze
    AVAILABLE_SCOPES = (AVAILABLE_TYPES + AVAILABLE_STATUSES).freeze
17
    FORM_EDITABLE = %i[description tag_list active run_untagged locked access_level maximum_timeout_human_readable].freeze
18

19 20
    ignore_column :is_shared

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

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

    before_validation :set_default_values

31 32 33
    scope :active, -> { where(active: true) }
    scope :paused, -> { where(active: false) }
    scope :online, -> { where('contacted_at > ?', contact_time_deadline) }
A
Alexis Reigel 已提交
34
    scope :offline, -> { where.not(id: online) }
35
    scope :ordered, -> { order(id: :desc) }
36

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

42 43 44
    scope :belonging_to_project, -> (project_id) {
      joins(:runner_projects).where(ci_runner_projects: { project_id: project_id })
    }
45

46
    scope :belonging_to_parent_group_of_project, -> (project_id) {
47 48 49 50
      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 })
51
    }
52

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

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

69
    validate :tag_constraints
70
    validates :access_level, presence: true
71
    validates :runner_type, presence: true
72

73 74 75 76 77
    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 已提交
78 79
    acts_as_taggable

80 81
    after_destroy :cleanup_runner_queue

82
    enum access_level: {
83 84
      not_protected: 0,
      ref_protected: 1
85 86
    }

87 88 89 90 91 92
    enum runner_type: {
      instance_type: 1,
      group_type: 2,
      project_type: 3
    }

93
    cached_attr_reader :version, :revision, :platform, :architecture, :ip_address, :contacted_at
94

95
    chronic_duration_attr :maximum_timeout_human_readable, :maximum_timeout
96

97 98 99 100
    validates :maximum_timeout, allow_nil: true,
                                numericality: { greater_than_or_equal_to: 600,
                                                message: 'needs to be at least 10 minutes' }

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

A
Alessio Caiazza 已提交
117 118 119 120
    def self.contact_time_deadline
      ONLINE_CONTACT_TIMEOUT.ago
    end

D
Douwe Maan 已提交
121 122 123 124 125
    def set_default_values
      self.token = SecureRandom.hex(15) if self.token.blank?
    end

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

132 133 134 135 136 137 138 139 140
      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 已提交
141 142 143
    end

    def display_name
144
      return short_sha if description.blank?
D
Douwe Maan 已提交
145 146 147 148

      description
    end

149
    def online?
150
      contacted_at && contacted_at > self.class.contact_time_deadline
151 152 153 154 155 156 157 158 159 160 161 162
    end

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

D
Douwe Maan 已提交
163 164 165 166
    def belongs_to_one_project?
      runner_projects.count == 1
    end

167
    def assigned_to_group?
168
      runner_namespaces.any?
A
Alexis Reigel 已提交
169 170
    end

171
    def assigned_to_project?
A
Alexis Reigel 已提交
172 173 174
      runner_projects.any?
    end

175
    def can_pick?(build)
176
      return false if self.ref_protected? && !build.protected?
S
Shinya Maeda 已提交
177

178
      assignable_for?(build.project_id) && accepting_tags?(build)
179 180
    end

D
Douwe Maan 已提交
181 182 183 184 185
    def only_for?(project)
      projects == [project]
    end

    def short_sha
K
Kamil Trzcinski 已提交
186
      token[0...8] if token
D
Douwe Maan 已提交
187
    end
188 189 190 191

    def has_tags?
      tag_list.any?
    end
192

193
    def predefined_variables
194 195 196 197
      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)
198 199
    end

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

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

213
    def runner_queue_value_latest?(value)
K
Kim "BKC" Carlbäcker 已提交
214
      ensure_runner_queue_value == value if value.present?
215 216
    end

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

221
      cache_attributes(values)
222

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

227
    def pick_build!(build)
228 229 230 231 232
      if can_pick?(build)
        tick_runner_queue
      end
    end

233 234
    private

235
    def cleanup_runner_queue
236
      Gitlab::Redis::Queues.with do |redis|
237 238 239 240
        redis.del(runner_queue_key)
      end
    end

K
Kim "BKC" Carlbäcker 已提交
241
    def runner_queue_key
K
Kim "BKC" Carlbäcker 已提交
242
      "runner:build_queue:#{self.token}"
243 244
    end

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

249 250 251 252 253 254 255
      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

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

263
    def assignable_for?(project_id)
264
      self.class.owned_or_instance_wide(project_id).where(id: self.id).any?
265 266
    end

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

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

291 292
    def accepting_tags?(build)
      (run_untagged? || build.has_tags?) && (build.tag_list - tag_list).empty?
293
    end
D
Douwe Maan 已提交
294 295
  end
end