Read about our upcoming Code of Conduct on this issue

namespace.rb 10.7 KB
Newer Older
1
2
# frozen_string_literal: true

Mark Chao's avatar
Mark Chao committed
3
class Namespace < ApplicationRecord
4
  include CacheMarkdownField
5
  include Sortable
6
  include Gitlab::VisibilityLevel
7
  include Routable
8
  include AfterCommitQueue
9
  include Storage::LegacyNamespace
10
  include Gitlab::SQL::Pattern
11
  include FeatureGate
12
  include FromUnion
13
  include Gitlab::Utils::StrongMemoize
14

15
16
17
18
19
  # Prevent users from creating unreasonably deep level of nesting.
  # The number 20 was taken based on maximum nesting level of
  # Android repo (15) + some extra backup.
  NUMBER_OF_ANCESTORS_ALLOWED = 20

20
21
  cache_markdown_field :description, pipeline: :description

22
  has_many :projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
Markus Koller's avatar
Markus Koller committed
23
  has_many :project_statistics
24

25
  has_many :runner_namespaces, inverse_of: :namespace, class_name: 'Ci::RunnerNamespace'
26
27
  has_many :runners, through: :runner_namespaces, source: :runner, class_name: 'Ci::Runner'

28
29
  # This should _not_ be `inverse_of: :namespace`, because that would also set
  # `user.namespace` when this user creates a group with themselves as `owner`.
30
31
  belongs_to :owner, class_name: "User"

32
33
  belongs_to :parent, class_name: "Namespace"
  has_many :children, class_name: "Namespace", foreign_key: :parent_id
34
  has_one :chat_team, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
35
36
  has_one :root_storage_statistics, class_name: 'Namespace::RootStorageStatistics'
  has_one :aggregation_schedule, class_name: 'Namespace::AggregationSchedule'
37

38
  validates :owner, presence: true, unless: ->(n) { n.type == "Group" }
39
  validates :name,
40
    presence: true,
41
    length: { maximum: 255 }
42

43
  validates :description, length: { maximum: 255 }
44
  validates :path,
45
    presence: true,
46
    length: { maximum: 255 },
47
    namespace_path: true
48

49
50
  validate :nesting_level_allowed

Jasper Maes's avatar
Jasper Maes committed
51
52
  validates_associated :runners

53
  delegate :name, to: :owner, allow_nil: true, prefix: true
54
  delegate :avatar_url, to: :owner, allow_nil: true
55

56
  after_commit :refresh_access_of_projects_invited_groups, on: :update, if: -> { previous_changes.key?('share_with_group_lock') }
57

58
59
  before_create :sync_share_with_group_lock_with_parent
  before_update :sync_share_with_group_lock_with_parent, if: :parent_changed?
Jasper Maes's avatar
Jasper Maes committed
60
  after_update :force_share_with_group_lock_on_descendants, if: -> { saved_change_to_share_with_group_lock? && share_with_group_lock? }
61

62
63
  # Legacy Storage specific hooks

64
  after_update :move_dir, if: :saved_change_to_path_or_parent?
65
  before_destroy(prepend: true) { prepare_for_destroy }
66
  after_destroy :rm_dir
67

68
  scope :for_user, -> { where('type IS NULL') }
69

Markus Koller's avatar
Markus Koller committed
70
71
72
73
74
75
76
  scope :with_statistics, -> do
    joins('LEFT JOIN project_statistics ps ON ps.namespace_id = namespaces.id')
      .group('namespaces.id')
      .select(
        'namespaces.*',
        'COALESCE(SUM(ps.storage_size), 0) AS storage_size',
        'COALESCE(SUM(ps.repository_size), 0) AS repository_size',
77
        'COALESCE(SUM(ps.wiki_size), 0) AS wiki_size',
Markus Koller's avatar
Markus Koller committed
78
        'COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size',
79
80
        'COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size',
        'COALESCE(SUM(ps.packages_size), 0) AS packages_size'
Markus Koller's avatar
Markus Koller committed
81
82
83
      )
  end

84
85
  class << self
    def by_path(path)
Gabriel Mazetto's avatar
Gabriel Mazetto committed
86
      find_by('lower(path) = :value', value: path.downcase)
87
88
    end

89
    # Case insensitive search for namespace by path or name
90
91
92
93
    def find_by_path_or_name(path)
      find_by("lower(path) = :path OR lower(name) = :path", path: path.downcase)
    end

94
95
96
97
98
99
100
    # Searches for namespaces matching the given query.
    #
    # This method uses ILIKE on PostgreSQL and LIKE on MySQL.
    #
    # query - The search query as a String
    #
    # Returns an ActiveRecord::Relation
101
    def search(query)
102
      fuzzy_search(query, [:name, :path])
103
104
105
    end

    def clean_path(path)
106
      path = path.dup
Douwe Maan's avatar
Douwe Maan committed
107
      # Get the email username by removing everything after an `@` sign.
108
      path.gsub!(/@.*\z/,                "")
Douwe Maan's avatar
Douwe Maan committed
109
      # Remove everything that's not in the list of allowed characters.
110
111
112
113
114
      path.gsub!(/[^a-zA-Z0-9_\-\.]/,    "")
      # Remove trailing violations ('.atom', '.git', or '.')
      path.gsub!(/(\.atom|\.git|\.)*\z/, "")
      # Remove leading violations ('-')
      path.gsub!(/\A\-+/,                "")
115

116
      # Users with the great usernames of "." or ".." would end up with a blank username.
117
      # Work around that by setting their username to "blank", followed by a counter.
118
119
      path = "blank" if path.blank?

120
      uniquify = Uniquify.new
121
      uniquify.string(path) { |s| Namespace.find_by_path_or_name(s) }
122
    end
123
124
125
126
127
128
129

    def find_by_pages_host(host)
      gitlab_host = "." + Settings.pages.host.downcase
      name = host.downcase.delete_suffix(gitlab_host)

      Namespace.find_by_full_path(name)
    end
130
131
  end

132
133
134
135
  def visibility_level_field
    :visibility_level
  end

136
  def to_param
137
    full_path
138
  end
139
140
141
142

  def human_name
    owner_name
  end
143

144
  def any_project_has_container_registry_tags?
145
    all_projects.any?(&:has_container_registry_tags?)
146
147
148
149
  end

  def first_project_with_container_registry_tags
    all_projects.find(&:has_container_registry_tags?)
150
151
  end

152
153
  def send_update_instructions
    projects.each do |project|
154
      project.send_move_instructions("#{full_path_before_last_save}/#{project.path}")
155
156
157
    end
  end

158
159
160
  def kind
    type == 'Group' ? 'group' : 'user'
  end
161

162
163
164
165
  def user?
    kind == 'user'
  end

166
  def find_fork_of(project)
167
    return unless project.fork_network
168

169
170
    if Gitlab::SafeRequestStore.active?
      forks_in_namespace = Gitlab::SafeRequestStore.fetch("namespaces:#{id}:forked_projects") do
171
172
173
174
175
176
177
178
179
        Hash.new do |found_forks, project|
          found_forks[project] = project.fork_network.find_forks_in(projects).first
        end
      end

      forks_in_namespace[project]
    else
      project.fork_network.find_forks_in(projects).first
    end
180
  end
181

182
183
184
  # any ancestor can disable emails for all descendants
  def emails_disabled?
    strong_memoize(:emails_disabled) do
185
      self_and_ancestors.where(emails_disabled: true).exists?
186
187
188
    end
  end

189
190
191
192
193
  def lfs_enabled?
    # User namespace will always default to the global setting
    Gitlab.config.lfs.enabled
  end

194
195
196
197
  def shared_runners_enabled?
    projects.with_shared_runners.any?
  end

198
199
  # Returns all ancestors, self, and descendants of the current namespace.
  def self_and_hierarchy
200
    Gitlab::ObjectHierarchy
201
      .new(self.class.where(id: id))
202
      .all_objects
203
204
  end

205
  # Returns all the ancestors of the current namespaces.
206
  def ancestors
207
    return self.class.none unless parent_id
208

209
    Gitlab::ObjectHierarchy
210
211
      .new(self.class.where(id: parent_id))
      .base_and_ancestors
212
213
  end

Takuya Noguchi's avatar
Takuya Noguchi committed
214
  # returns all ancestors upto but excluding the given namespace
215
  # when no namespace is given, all ancestors upto the top are returned
216
  def ancestors_upto(top = nil, hierarchy_order: nil)
217
    Gitlab::ObjectHierarchy.new(self.class.where(id: id))
218
      .ancestors(upto: top, hierarchy_order: hierarchy_order)
219
220
  end

221
  def self_and_ancestors(hierarchy_order: nil)
222
223
    return self.class.where(id: id) unless parent_id

224
    Gitlab::ObjectHierarchy
225
      .new(self.class.where(id: id))
226
      .base_and_ancestors(hierarchy_order: hierarchy_order)
227
228
  end

229
  # Returns all the descendants of the current namespace.
230
  def descendants
231
    Gitlab::ObjectHierarchy
232
233
      .new(self.class.where(parent_id: id))
      .base_and_descendants
234
235
  end

236
  def self_and_descendants
237
    Gitlab::ObjectHierarchy
238
239
240
241
      .new(self.class.where(id: id))
      .base_and_descendants
  end

242
243
244
245
  def user_ids_for_project_authorizations
    [owner_id]
  end

246
247
248
249
250
251
  # Includes projects from this namespace and projects from all subgroups
  # that belongs to this namespace
  def all_projects
    Project.inside_path(full_path)
  end

252
253
254
255
256
257
  # Includes pipelines from this namespace and pipelines from all subgroups
  # that belongs to this namespace
  def all_pipelines
    Ci::Pipeline.where(project: all_projects)
  end

258
259
260
261
  def has_parent?
    parent.present?
  end

262
  def root_ancestor
263
264
265
    strong_memoize(:root_ancestor) do
      self_and_ancestors.reorder(nil).find_by(parent_id: nil)
    end
266
267
  end

268
269
270
271
  def subgroup?
    has_parent?
  end

272
  # Overridden on EE module
Felipe Artur's avatar
Felipe Artur committed
273
274
275
276
  def multiple_issue_boards_available?
    false
  end

277
278
279
280
281
  # Overridden in EE::Namespace
  def feature_available?(_feature)
    false
  end

282
283
284
  def full_path_before_last_save
    if parent_id_before_last_save.nil?
      path_before_last_save
285
    else
286
287
      previous_parent = Group.find_by(id: parent_id_before_last_save)
      previous_parent.full_path + '/' + path_before_last_save
288
    end
289
290
  end

291
292
293
294
  def refresh_project_authorizations
    owner.refresh_authorized_projects
  end

295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
  def auto_devops_enabled?
    first_auto_devops_config[:status]
  end

  def first_auto_devops_config
    return { scope: :group, status: auto_devops_enabled } unless auto_devops_enabled.nil?

    strong_memoize(:first_auto_devops_config) do
      if has_parent?
        parent.first_auto_devops_config
      else
        { scope: :instance, status: Gitlab::CurrentSettings.auto_devops_enabled? }
      end
    end
  end

311
312
313
314
  def aggregation_scheduled?
    aggregation_schedule.present?
  end

315
316
317
318
  def pages_virtual_domain
    Pages::VirtualDomain.new(all_projects_with_pages, trim_prefix: full_path)
  end

319
320
  private

321
  def all_projects_with_pages
322
323
324
325
326
327
    if all_projects.pages_metadata_not_migrated.exists?
      Gitlab::BackgroundMigration::MigratePagesMetadata.new.perform_on_relation(
        all_projects.pages_metadata_not_migrated
      )
    end

328
329
330
    all_projects.with_pages_deployed
  end

331
332
333
334
335
336
337
338
339
  def parent_changed?
    parent_id_changed?
  end

  def saved_change_to_parent?
    saved_change_to_parent_id?
  end

  def saved_change_to_path_or_parent?
Jasper Maes's avatar
Jasper Maes committed
340
    saved_change_to_path? || saved_change_to_parent_id?
341
342
  end

343
  def refresh_access_of_projects_invited_groups
344
345
346
347
    Group
      .joins(project_group_links: :project)
      .where(projects: { namespace_id: id })
      .find_each(&:refresh_members_authorized_projects)
348
  end
349

350
351
352
353
354
  def nesting_level_allowed
    if ancestors.count > Group::NUMBER_OF_ANCESTORS_ALLOWED
      errors.add(:parent_id, "has too deep level of nesting")
    end
  end
355
356

  def sync_share_with_group_lock_with_parent
Michael Kozono's avatar
Michael Kozono committed
357
    if parent&.share_with_group_lock?
358
359
360
361
362
      self.share_with_group_lock = true
    end
  end

  def force_share_with_group_lock_on_descendants
363
364
365
366
367
368
    # We can't use `descendants.update_all` since Rails will throw away the WITH
    # RECURSIVE statement. We also can't use WHERE EXISTS since we can't use
    # different table aliases, hence we're just using WHERE IN. Since we have a
    # maximum of 20 nested groups this should be fine.
    Namespace.where(id: descendants.select(:id))
      .update_all(share_with_group_lock: true)
369
  end
370

371
372
  def write_projects_repository_config
    all_projects.find_each do |project|
373
      project.write_repository_config
374
      project.track_project_repository
375
376
    end
  end
377
end
378
379

Namespace.prepend_if_ee('EE::Namespace')