This instance was upgraded to Heptapod 0.31.0 (final) today.

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

3
class Namespace < ActiveRecord::Base
4
  include CacheMarkdownField
5
  include Sortable
6
  include Gitlab::ShellAdapter
7
  include Gitlab::VisibilityLevel
8
  include Routable
9
  include AfterCommitQueue
10
  include Storage::LegacyNamespace
11
  include Gitlab::SQL::Pattern
12
  include IgnorableColumn
13
  include FeatureGate
14
  include FromUnion
15
16

  ignore_column :deleted_at
17

18
19
20
21
22
  # 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

23
24
  cache_markdown_field :description, pipeline: :description

25
  has_many :projects, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
Markus Koller's avatar
Markus Koller committed
26
  has_many :project_statistics
27

28
  has_many :runner_namespaces, inverse_of: :namespace, class_name: 'Ci::RunnerNamespace'
29
30
  has_many :runners, through: :runner_namespaces, source: :runner, class_name: 'Ci::Runner'

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

35
36
  belongs_to :parent, class_name: "Namespace"
  has_many :children, class_name: "Namespace", foreign_key: :parent_id
37
  has_one :chat_team, dependent: :destroy # rubocop:disable Cop/ActiveRecordDependent
38

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

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

51
52
  validate :nesting_level_allowed

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

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

57
58
  before_create :sync_share_with_group_lock_with_parent
  before_update :sync_share_with_group_lock_with_parent, if: :parent_changed?
Michael Kozono's avatar
Michael Kozono committed
59
  after_update :force_share_with_group_lock_on_descendants, if: -> { share_with_group_lock_changed? && share_with_group_lock? }
60

61
62
  # Legacy Storage specific hooks

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

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

Markus Koller's avatar
Markus Koller committed
69
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',
        'COALESCE(SUM(ps.lfs_objects_size), 0) AS lfs_objects_size',
77
        'COALESCE(SUM(ps.build_artifacts_size), 0) AS build_artifacts_size'
Markus Koller's avatar
Markus Koller committed
78
79
80
      )
  end

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

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

91
92
93
94
95
96
97
    # 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
98
    def search(query)
99
      fuzzy_search(query, [:name, :path])
100
101
102
    end

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

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

117
      uniquify = Uniquify.new
118
      uniquify.string(path) { |s| Namespace.find_by_path_or_name(s) }
119
    end
120
121
  end

122
123
124
125
  def visibility_level_field
    :visibility_level
  end

126
  def to_param
127
    full_path
128
  end
129
130
131
132

  def human_name
    owner_name
  end
133

134
  def any_project_has_container_registry_tags?
135
    all_projects.any?(&:has_container_registry_tags?)
136
137
138
139
  end

  def first_project_with_container_registry_tags
    all_projects.find(&:has_container_registry_tags?)
140
141
  end

142
143
144
145
146
147
  def send_update_instructions
    projects.each do |project|
      project.send_move_instructions("#{full_path_was}/#{project.path}")
    end
  end

148
149
150
  def kind
    type == 'Group' ? 'group' : 'user'
  end
151
152

  def find_fork_of(project)
153
154
    return nil unless project.fork_network

155
156
    if Gitlab::SafeRequestStore.active?
      forks_in_namespace = Gitlab::SafeRequestStore.fetch("namespaces:#{id}:forked_projects") do
157
158
159
160
161
162
163
164
165
        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
166
  end
167

168
169
170
171
172
  def lfs_enabled?
    # User namespace will always default to the global setting
    Gitlab.config.lfs.enabled
  end

173
174
175
176
  def shared_runners_enabled?
    projects.with_shared_runners.any?
  end

177
178
179
180
181
182
183
  # Returns all ancestors, self, and descendants of the current namespace.
  def self_and_hierarchy
    Gitlab::GroupHierarchy
      .new(self.class.where(id: id))
      .all_groups
  end

184
  # Returns all the ancestors of the current namespaces.
185
  def ancestors
186
    return self.class.none unless parent_id
187

188
189
190
    Gitlab::GroupHierarchy
      .new(self.class.where(id: parent_id))
      .base_and_ancestors
191
192
  end

193
194
195
196
197
198
199
  # returns all ancestors upto but excluding the the given namespace
  # when no namespace is given, all ancestors upto the top are returned
  def ancestors_upto(top = nil)
    Gitlab::GroupHierarchy.new(self.class.where(id: id))
      .ancestors(upto: top)
  end

200
201
202
203
204
205
206
207
  def self_and_ancestors
    return self.class.where(id: id) unless parent_id

    Gitlab::GroupHierarchy
      .new(self.class.where(id: id))
      .base_and_ancestors
  end

208
  # Returns all the descendants of the current namespace.
209
  def descendants
210
211
212
    Gitlab::GroupHierarchy
      .new(self.class.where(parent_id: id))
      .base_and_descendants
213
214
  end

215
216
217
218
219
220
  def self_and_descendants
    Gitlab::GroupHierarchy
      .new(self.class.where(id: id))
      .base_and_descendants
  end

221
222
223
224
  def user_ids_for_project_authorizations
    [owner_id]
  end

225
226
227
228
  def parent_changed?
    parent_id_changed?
  end

229
230
231
232
233
234
  # Includes projects from this namespace and projects from all subgroups
  # that belongs to this namespace
  def all_projects
    Project.inside_path(full_path)
  end

235
236
237
238
  def has_parent?
    parent.present?
  end

239
240
241
242
  def root_ancestor
    ancestors.reorder(nil).find_by(parent_id: nil)
  end

243
244
245
246
  def subgroup?
    has_parent?
  end

247
  # Overridden on EE module
Felipe Artur's avatar
Felipe Artur committed
248
249
250
251
  def multiple_issue_boards_available?
    false
  end

252
  def full_path_was
253
254
255
256
257
258
    if parent_id_was.nil?
      path_was
    else
      previous_parent = Group.find_by(id: parent_id_was)
      previous_parent.full_path + '/' + path_was
    end
259
260
  end

261
262
263
264
  def refresh_project_authorizations
    owner.refresh_authorized_projects
  end

265
266
  private

267
268
269
270
  def path_or_parent_changed?
    path_changed? || parent_changed?
  end

271
  def refresh_access_of_projects_invited_groups
272
273
274
275
    Group
      .joins(project_group_links: :project)
      .where(projects: { namespace_id: id })
      .find_each(&:refresh_members_authorized_projects)
276
  end
277

278
279
280
281
282
  def nesting_level_allowed
    if ancestors.count > Group::NUMBER_OF_ANCESTORS_ALLOWED
      errors.add(:parent_id, "has too deep level of nesting")
    end
  end
283
284

  def sync_share_with_group_lock_with_parent
Michael Kozono's avatar
Michael Kozono committed
285
    if parent&.share_with_group_lock?
286
287
288
289
290
      self.share_with_group_lock = true
    end
  end

  def force_share_with_group_lock_on_descendants
291
292
293
294
295
296
297
298
    return unless Group.supports_nested_groups?

    # 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)
299
  end
300

301
302
  def write_projects_repository_config
    all_projects.find_each do |project|
303
      project.write_repository_config
304
305
    end
  end
306
end