helpers.rb 1.9 KB
Newer Older
D
Douwe Maan 已提交
1 2 3
module Ci
  module API
    module Helpers
K
Kamil Trzcinski 已提交
4 5
      BUILD_TOKEN_HEADER = "HTTP_BUILD_TOKEN"
      BUILD_TOKEN_PARAM = :token
6
      UPDATE_RUNNER_EVERY = 40 * 60
K
Kamil Trzcinski 已提交
7

D
Douwe Maan 已提交
8
      def authenticate_runners!
9
        forbidden! unless runner_registration_token_valid?
D
Douwe Maan 已提交
10 11 12 13 14 15
      end

      def authenticate_runner!
        forbidden! unless current_runner
      end

K
Kamil Trzcinski 已提交
16 17 18 19 20
      def authenticate_build_token!(build)
        token = (params[BUILD_TOKEN_PARAM] || env[BUILD_TOKEN_HEADER]).to_s
        forbidden! unless token && build.valid_token?(token)
      end

21
      def runner_registration_token_valid?
22
        params[:token] == current_application_settings.runners_registration_token
23 24
      end

25
      def update_runner_last_contact(save: true)
26
        # Use a random threshold to prevent beating DB updates
27
        # it generates a distribution between: [40m, 80m]
28 29
        contacted_at_max_age = UPDATE_RUNNER_EVERY + Random.rand(UPDATE_RUNNER_EVERY)
        if current_runner.contacted_at.nil? || Time.now - current_runner.contacted_at >= contacted_at_max_age
30 31
          current_runner.contacted_at = Time.now
          current_runner.save if current_runner.changed? && save
D
Douwe Maan 已提交
32 33 34
        end
      end

35 36 37 38 39 40 41 42
      def build_not_found!
        if headers['User-Agent'].match(/gitlab-ci-multi-runner \d+\.\d+\.\d+(~beta\.\d+\.g[0-9a-f]+)? /)
          no_content!
        else
          not_found!
        end
      end

V
Valery Sizov 已提交
43 44 45 46
      def current_runner
        @runner ||= Runner.find_by_token(params[:token].to_s)
      end

47
      def get_runner_version_from_params
D
Douwe Maan 已提交
48
        return unless params["info"].present?
49 50 51 52 53 54
        attributes_for_keys(["name", "version", "revision", "platform", "architecture"], params["info"])
      end

      def update_runner_info
        current_runner.assign_attributes(get_runner_version_from_params)
        current_runner.save if current_runner.changed?
D
Douwe Maan 已提交
55
      end
K
Kamil Trzcinski 已提交
56 57 58 59

      def max_artifacts_size
        current_application_settings.max_artifacts_size.megabytes.to_i
      end
D
Douwe Maan 已提交
60 61 62
    end
  end
end