summaryrefslogtreecommitdiff
path: root/app/models/project.rb
blob: f648833c7c10076b02c4fe68cd17a5b10f422387 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# == Schema Information
#
# Table name: projects
#
#  id                       :integer          not null, primary key
#  name                     :string(255)      not null
#  timeout                  :integer          default(1800), not null
#  created_at               :datetime
#  updated_at               :datetime
#  token                    :string(255)
#  default_ref              :string(255)
#  path                     :string(255)
#  always_build             :boolean          default(FALSE), not null
#  polling_interval         :integer
#  public                   :boolean          default(FALSE), not null
#  ssh_url_to_repo          :string(255)
#  gitlab_id                :integer
#  allow_git_fetch          :boolean          default(TRUE), not null
#  email_recipients         :string(255)      default(""), not null
#  email_add_pusher         :boolean          default(TRUE), not null
#  email_only_broken_builds :boolean          default(TRUE), not null
#  skip_refs                :string(255)
#  coverage_regex           :string(255)
#  shared_runners_enabled   :boolean          default(FALSE)
#

class Project < ActiveRecord::Base
  include ProjectStatus

  has_many :commits, dependent: :destroy
  has_many :builds, through: :commits, dependent: :destroy
  has_many :runner_projects, dependent: :destroy
  has_many :runners, through: :runner_projects
  has_many :web_hooks, dependent: :destroy
  has_many :jobs, dependent: :destroy
  has_many :events, dependent: :destroy

  # Project services
  has_many :services, dependent: :destroy
  has_one :hip_chat_service, dependent: :destroy
  has_one :slack_service, dependent: :destroy
  has_one :mail_service, dependent: :destroy

  accepts_nested_attributes_for :jobs, allow_destroy: true

  #
  # Validations
  #
  validates_presence_of :name, :timeout, :token, :default_ref,
    :path, :ssh_url_to_repo, :gitlab_id

  validates_uniqueness_of :name

  validates :polling_interval,
    presence: true,
    if: ->(project) { project.always_build.present? }

  validate :validate_jobs

  scope :public_only, ->() { where(public: true) }

  before_validation :set_default_values

  class << self
    def base_build_script
      <<-eos
git submodule update --init
ls -la
      eos
    end

    def parse(project_params)
      project = if project_params.is_a?(String)
                  YAML.load(project_params)
                else
                  project_params
                end

      params = {
        name:                    project.name_with_namespace,
        gitlab_id:               project.id,
        path:                    project.path_with_namespace,
        default_ref:             project.default_branch || 'master',
        ssh_url_to_repo:         project.ssh_url_to_repo,
        email_add_pusher:        GitlabCi.config.gitlab_ci.add_pusher,
        email_only_broken_builds: GitlabCi.config.gitlab_ci.all_broken_builds,
      }

      project = Project.new(params)
      project.build_missing_services
      project
    end

    def from_gitlab(user, scope = :owned, options)
      opts = { private_token: user.private_token }
      opts.merge! options

      projects = Network.new.projects(opts.compact, scope)

      if projects
        projects.map { |pr| OpenStruct.new(pr) }
      else
        []
      end
    end

    def already_added?(project)
      where(gitlab_id: project.id).any?
    end

    def unassigned(runner)
      joins('LEFT JOIN runner_projects ON runner_projects.project_id = projects.id ' \
        "AND runner_projects.runner_id = #{runner.id}").
      where('runner_projects.project_id' => nil)
    end

    def ordered_by_last_commit_date
      last_commit_subquery = "(SELECT project_id, MAX(created_at) created_at FROM commits GROUP BY project_id)"
      joins("LEFT JOIN #{last_commit_subquery} AS last_commit ON projects.id = last_commit.project_id").
        order("CASE WHEN last_commit.created_at IS NULL THEN 1 ELSE 0 END, last_commit.created_at DESC")
    end

    def search(query)
      where('LOWER(projects.name) LIKE :query',
            query: "%#{query.try(:downcase)}%")
    end
  end

  def set_default_values
    self.token = SecureRandom.hex(15) if self.token.blank?
  end

  def tracked_refs
    @tracked_refs ||= default_ref.split(",").map{|ref| ref.strip}
  end

  def valid_token? token
    self.token && self.token == token
  end

  def no_running_builds?
    # Get running builds not later than 3 days ago to ignore hangs
    builds.running.where("updated_at > ?", 3.days.ago).empty?
  end

  def email_notification?
    email_add_pusher || email_recipients.present?
  end

  def web_hooks?
    web_hooks.any?
  end

  def services?
    services.any?
  end

  def timeout_in_minutes
    timeout / 60
  end

  def timeout_in_minutes=(value)
    self.timeout = value.to_i * 60
  end

  def skip_ref?(ref_name)
    if skip_refs.present?
      skip_refs.delete(" ").split(",").each do |ref|
        return true if File.fnmatch(ref, ref_name)
      end

      false
    else
      false
    end
  end

  def create_commit_for_tag?(tag)
    jobs.where(build_tags: true).active.parallel.any? ||
    jobs.active.deploy.any?{ |job| job.run_for_ref?(tag)}
  end

  def coverage_enabled?
    coverage_regex.present?
  end

  def build_default_job
    jobs.build(commands: Project.base_build_script)
  end

  def validate_jobs
    remaining_jobs = jobs.reject(&:marked_for_destruction?)

    if remaining_jobs.empty?
      errors.add(:jobs, "At least one foo")
    end
  end

  # Build a clone-able repo url
  # using http and basic auth
  def repo_url_with_auth
    auth = "gitlab-ci-token:#{token}@"
    url = gitlab_url + ".git"
    url.sub(/^https?:\/\//) do |prefix|
      prefix + auth
    end
  end

  def available_services_names
    %w(slack mail hip_chat)
  end

  def build_missing_services
    available_services_names.each do |service_name|
      service = services.find { |service| service.to_param == service_name }

      # If service is available but missing in db
      # we should create an instance. Ex `create_gitlab_ci_service`
      service = self.send :"create_#{service_name}_service" if service.nil?
    end
  end

  def execute_services(data)
    services.each do |service|

      # Call service hook only if it is active
      begin
        service.execute(data) if service.active
      rescue => e
        logger.error(e)
      end
    end
  end

  def gitlab_url
    File.join(GitlabCi.config.gitlab_server.url, path)
  end

  def setup_finished?
    commits.any?
  end
end