summaryrefslogtreecommitdiff
path: root/lib/gitlab
diff options
context:
space:
mode:
Diffstat (limited to 'lib/gitlab')
-rw-r--r--lib/gitlab/access.rb11
-rw-r--r--lib/gitlab/action_rate_limiter.rb40
-rw-r--r--lib/gitlab/auth/activity.rb7
-rw-r--r--lib/gitlab/auth/o_auth/auth_hash.rb3
-rw-r--r--lib/gitlab/auth/user_auth_finders.rb17
-rw-r--r--lib/gitlab/background_migration/backfill_project_repositories.rb2
-rw-r--r--lib/gitlab/background_migration/fill_valid_time_for_pages_domain_certificate.rb17
-rw-r--r--lib/gitlab/background_migration/fix_pages_access_level.rb128
-rw-r--r--lib/gitlab/background_migration/migrate_stage_index.rb42
-rw-r--r--lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb15
-rw-r--r--lib/gitlab/background_migration/prepare_untracked_uploads.rb15
-rw-r--r--lib/gitlab/background_migration/remove_restricted_todos.rb17
-rw-r--r--lib/gitlab/badge/coverage/report.rb2
-rw-r--r--lib/gitlab/blob_helper.rb2
-rw-r--r--lib/gitlab/chaos.rb49
-rw-r--r--lib/gitlab/ci/ansi2html.rb27
-rw-r--r--lib/gitlab/ci/charts.rb14
-rw-r--r--lib/gitlab/ci/config/entry/job.rb20
-rw-r--r--lib/gitlab/ci/config/normalizer.rb64
-rw-r--r--lib/gitlab/ci/pipeline/seed/build.rb31
-rw-r--r--lib/gitlab/ci/pipeline/seed/stage.rb19
-rw-r--r--lib/gitlab/ci/status/build/manual.rb2
-rw-r--r--lib/gitlab/ci/status/factory.rb6
-rw-r--r--lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml5
-rw-r--r--lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml2
-rw-r--r--lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml2
-rw-r--r--lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml1
-rw-r--r--lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml420
-rw-r--r--lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml5
-rw-r--r--lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml4
-rw-r--r--lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml1
-rw-r--r--lib/gitlab/ci/templates/Serverless.gitlab-ci.yml13
-rw-r--r--lib/gitlab/ci/trace.rb14
-rw-r--r--lib/gitlab/ci/trace/chunked_io.rb7
-rw-r--r--lib/gitlab/ci/yaml_processor.rb22
-rw-r--r--lib/gitlab/contributions_calendar.rb6
-rw-r--r--lib/gitlab/cycle_analytics/base_event_fetcher.rb12
-rw-r--r--lib/gitlab/cycle_analytics/base_query.rb14
-rw-r--r--lib/gitlab/cycle_analytics/base_stage.rb19
-rw-r--r--lib/gitlab/cycle_analytics/code_event_fetcher.rb6
-rw-r--r--lib/gitlab/cycle_analytics/group_projects_provider.rb27
-rw-r--r--lib/gitlab/cycle_analytics/group_stage_summary.rb27
-rw-r--r--lib/gitlab/cycle_analytics/issue_event_fetcher.rb6
-rw-r--r--lib/gitlab/cycle_analytics/issue_helper.rb3
-rw-r--r--lib/gitlab/cycle_analytics/metrics_tables.rb8
-rw-r--r--lib/gitlab/cycle_analytics/permissions.rb2
-rw-r--r--lib/gitlab/cycle_analytics/plan_event_fetcher.rb6
-rw-r--r--lib/gitlab/cycle_analytics/plan_helper.rb13
-rw-r--r--lib/gitlab/cycle_analytics/production_event_fetcher.rb6
-rw-r--r--lib/gitlab/cycle_analytics/review_event_fetcher.rb6
-rw-r--r--lib/gitlab/cycle_analytics/summary/group/base.rb27
-rw-r--r--lib/gitlab/cycle_analytics/summary/group/deploy.rb30
-rw-r--r--lib/gitlab/cycle_analytics/summary/group/issue.rb36
-rw-r--r--lib/gitlab/danger/helper.rb26
-rw-r--r--lib/gitlab/danger/teammate.rb2
-rw-r--r--lib/gitlab/database.rb85
-rw-r--r--lib/gitlab/database/count.rb12
-rw-r--r--lib/gitlab/database/count/exact_count_strategy.rb4
-rw-r--r--lib/gitlab/database/count/reltuples_count_strategy.rb4
-rw-r--r--lib/gitlab/database/count/tablesample_count_strategy.rb4
-rw-r--r--lib/gitlab/database/date_time.rb18
-rw-r--r--lib/gitlab/database/grant.rb50
-rw-r--r--lib/gitlab/database/median.rb47
-rw-r--r--lib/gitlab/database/migration_helpers.rb205
-rw-r--r--lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb12
-rw-r--r--lib/gitlab/database/sha_attribute.rb11
-rw-r--r--lib/gitlab/database/subquery.rb6
-rw-r--r--lib/gitlab/ee_compat_check.rb2
-rw-r--r--lib/gitlab/exclusive_lease_helpers.rb5
-rw-r--r--lib/gitlab/git.rb5
-rw-r--r--lib/gitlab/git/repository.rb30
-rw-r--r--lib/gitlab/git/rugged_impl/blob.rb2
-rw-r--r--lib/gitlab/git/rugged_impl/commit.rb6
-rw-r--r--lib/gitlab/git/rugged_impl/repository.rb2
-rw-r--r--lib/gitlab/git/rugged_impl/tree.rb2
-rw-r--r--lib/gitlab/git/rugged_impl/use_rugged.rb23
-rw-r--r--lib/gitlab/git_logger.rb6
-rw-r--r--lib/gitlab/gitaly_client.rb25
-rw-r--r--lib/gitlab/gitaly_client/operation_service.rb9
-rw-r--r--lib/gitlab/github_import/client.rb4
-rw-r--r--lib/gitlab/grape_logging/loggers/perf_logger.rb19
-rw-r--r--lib/gitlab/graphql/representation/submodule_tree_entry.rb34
-rw-r--r--lib/gitlab/health_checks/db_check.rb6
-rw-r--r--lib/gitlab/http_connection_adapter.rb4
-rw-r--r--lib/gitlab/import/database_helpers.rb10
-rw-r--r--lib/gitlab/import_export.rb12
-rw-r--r--lib/gitlab/import_export/attributes_finder.rb2
-rw-r--r--lib/gitlab/import_export/json_hash_builder.rb2
-rw-r--r--lib/gitlab/import_export/lfs_restorer.rb51
-rw-r--r--lib/gitlab/import_export/lfs_saver.rb47
-rw-r--r--lib/gitlab/import_export/members_mapper.rb4
-rw-r--r--lib/gitlab/import_export/project_tree_restorer.rb1
-rw-r--r--lib/gitlab/import_export/relation_factory.rb2
-rw-r--r--lib/gitlab/kubernetes/helm/delete_command.rb20
-rw-r--r--lib/gitlab/kubernetes/helm/install_command.rb12
-rw-r--r--lib/gitlab/kubernetes/helm/reset_command.rb54
-rw-r--r--lib/gitlab/kubernetes/kube_client.rb2
-rw-r--r--lib/gitlab/legacy_github_import/client.rb2
-rw-r--r--lib/gitlab/metrics/dashboard/base_service.rb72
-rw-r--r--lib/gitlab/metrics/dashboard/dynamic_dashboard_service.rb65
-rw-r--r--lib/gitlab/metrics/dashboard/finder.rb10
-rw-r--r--lib/gitlab/metrics/dashboard/project_dashboard_service.rb50
-rw-r--r--lib/gitlab/metrics/dashboard/system_dashboard_service.rb49
-rw-r--r--lib/gitlab/metrics/samplers/influx_sampler.rb22
-rw-r--r--lib/gitlab/metrics/samplers/ruby_sampler.rb56
-rw-r--r--lib/gitlab/metrics/subscribers/rails_cache.rb15
-rw-r--r--lib/gitlab/object_hierarchy.rb17
-rw-r--r--lib/gitlab/octokit/middleware.rb23
-rw-r--r--lib/gitlab/path_regex.rb4
-rw-r--r--lib/gitlab/performance_bar/peek_query_tracker.rb45
-rw-r--r--lib/gitlab/profiler.rb5
-rw-r--r--lib/gitlab/project_authorizations.rb121
-rw-r--r--lib/gitlab/project_authorizations/with_nested_groups.rb125
-rw-r--r--lib/gitlab/project_authorizations/without_nested_groups.rb35
-rw-r--r--lib/gitlab/project_search_results.rb2
-rw-r--r--lib/gitlab/project_template.rb10
-rw-r--r--lib/gitlab/push_options.rb9
-rw-r--r--lib/gitlab/quick_actions/command_definition.rb21
-rw-r--r--lib/gitlab/quick_actions/commit_actions.rb7
-rw-r--r--lib/gitlab/quick_actions/dsl.rb37
-rw-r--r--lib/gitlab/quick_actions/issuable_actions.rb116
-rw-r--r--lib/gitlab/quick_actions/issue_actions.rb43
-rw-r--r--lib/gitlab/quick_actions/issue_and_merge_request_actions.rb103
-rw-r--r--lib/gitlab/quick_actions/merge_request_actions.rb28
-rw-r--r--lib/gitlab/regex.rb6
-rw-r--r--lib/gitlab/request_profiler.rb15
-rw-r--r--lib/gitlab/request_profiler/middleware.rb62
-rw-r--r--lib/gitlab/request_profiler/profile.rb42
-rw-r--r--lib/gitlab/rugged_instrumentation.rb47
-rw-r--r--lib/gitlab/sherlock/query.rb7
-rw-r--r--lib/gitlab/sidekiq_logging/structured_logger.rb6
-rw-r--r--lib/gitlab/sidekiq_middleware/memory_killer.rb23
-rw-r--r--lib/gitlab/sidekiq_middleware/metrics.rb48
-rw-r--r--lib/gitlab/slug/environment.rb58
-rw-r--r--lib/gitlab/submodule_links.rb31
-rw-r--r--lib/gitlab/url_blocker.rb45
-rw-r--r--lib/gitlab/usage_data.rb18
-rw-r--r--lib/gitlab/usage_data_counters/redis_counter.rb17
-rw-r--r--lib/gitlab/usage_data_counters/search_counter.rb27
-rw-r--r--lib/gitlab/usage_data_counters/web_ide_counter.rb47
-rw-r--r--lib/gitlab/usage_data_counters/wiki_page_counter.rb32
-rw-r--r--lib/gitlab/utils.rb9
-rw-r--r--lib/gitlab/utils/sanitize_node_link.rb61
-rw-r--r--lib/gitlab/web_ide_commits_counter.rb17
-rw-r--r--lib/gitlab/workhorse.rb2
-rw-r--r--lib/gitlab/zoom_link_extractor.rb25
146 files changed, 2267 insertions, 1659 deletions
diff --git a/lib/gitlab/access.rb b/lib/gitlab/access.rb
index 6eb08f674c2..7ef9f7ef630 100644
--- a/lib/gitlab/access.rb
+++ b/lib/gitlab/access.rb
@@ -29,6 +29,10 @@ module Gitlab
MAINTAINER_PROJECT_ACCESS = 1
DEVELOPER_MAINTAINER_PROJECT_ACCESS = 2
+ # Default subgroup creation level
+ OWNER_SUBGROUP_ACCESS = 0
+ MAINTAINER_SUBGROUP_ACCESS = 1
+
class << self
delegate :values, to: :options
@@ -106,6 +110,13 @@ module Gitlab
def project_creation_level_name(name)
project_creation_options.key(name)
end
+
+ def subgroup_creation_options
+ {
+ s_('SubgroupCreationlevel|Owners') => OWNER_SUBGROUP_ACCESS,
+ s_('SubgroupCreationlevel|Maintainers') => MAINTAINER_SUBGROUP_ACCESS
+ }
+ end
end
def human_access
diff --git a/lib/gitlab/action_rate_limiter.rb b/lib/gitlab/action_rate_limiter.rb
index c442211e073..fdb06d00548 100644
--- a/lib/gitlab/action_rate_limiter.rb
+++ b/lib/gitlab/action_rate_limiter.rb
@@ -33,16 +33,48 @@ module Gitlab
# Increments the given key and returns true if the action should
# be throttled.
#
- # key - An array of ActiveRecord instances
- # threshold_value - The maximum number of times this action should occur in the given time interval
+ # key - An array of ActiveRecord instances or strings
+ # threshold_value - The maximum number of times this action should occur in the given time interval. If number is zero is considered disabled.
def throttled?(key, threshold_value)
- self.increment(key) > threshold_value
+ threshold_value > 0 &&
+ self.increment(key) > threshold_value
+ end
+
+ # Logs request into auth.log
+ #
+ # request - Web request to be logged
+ # type - A symbol key that represents the request.
+ # current_user - Current user of the request, it can be nil.
+ def log_request(request, type, current_user)
+ request_information = {
+ message: 'Action_Rate_Limiter_Request',
+ env: type,
+ ip: request.ip,
+ request_method: request.request_method,
+ fullpath: request.fullpath
+ }
+
+ if current_user
+ request_information.merge!({
+ user_id: current_user.id,
+ username: current_user.username
+ })
+ end
+
+ Gitlab::AuthLogger.error(request_information)
end
private
def action_key(key)
- serialized = key.map { |obj| "#{obj.class.model_name.to_s.underscore}:#{obj.id}" }.join(":")
+ serialized = key.map do |obj|
+ if obj.is_a?(String)
+ "#{obj}"
+ else
+ "#{obj.class.model_name.to_s.underscore}:#{obj.id}"
+ end
+ end.join(":")
+
"action_rate_limiter:#{action}:#{serialized}"
end
end
diff --git a/lib/gitlab/auth/activity.rb b/lib/gitlab/auth/activity.rb
index 558628b5422..988ff196193 100644
--- a/lib/gitlab/auth/activity.rb
+++ b/lib/gitlab/auth/activity.rb
@@ -37,14 +37,17 @@ module Gitlab
def user_authenticated!
self.class.user_authenticated_counter_increment!
+
+ case @opts[:message]
+ when :two_factor_authenticated
+ self.class.user_two_factor_authenticated_counter_increment!
+ end
end
def user_session_override!
self.class.user_session_override_counter_increment!
case @opts[:message]
- when :two_factor_authenticated
- self.class.user_two_factor_authenticated_counter_increment!
when :sessionless_sign_in
self.class.user_sessionless_authentication_counter_increment!
end
diff --git a/lib/gitlab/auth/o_auth/auth_hash.rb b/lib/gitlab/auth/o_auth/auth_hash.rb
index 72a187377d0..91b9ddc0d00 100644
--- a/lib/gitlab/auth/o_auth/auth_hash.rb
+++ b/lib/gitlab/auth/o_auth/auth_hash.rb
@@ -60,8 +60,7 @@ module Gitlab
def get_info(key)
value = info[key]
- Gitlab::Utils.force_utf8(value) if value
- value
+ value.is_a?(String) ? Gitlab::Utils.force_utf8(value) : value
end
def username_and_email
diff --git a/lib/gitlab/auth/user_auth_finders.rb b/lib/gitlab/auth/user_auth_finders.rb
index a5efe33bdc6..bba7e2cbb3c 100644
--- a/lib/gitlab/auth/user_auth_finders.rb
+++ b/lib/gitlab/auth/user_auth_finders.rb
@@ -90,8 +90,8 @@ module Gitlab
def find_personal_access_token
token =
current_request.params[PRIVATE_TOKEN_PARAM].presence ||
- current_request.env[PRIVATE_TOKEN_HEADER].presence
-
+ current_request.env[PRIVATE_TOKEN_HEADER].presence ||
+ parsed_oauth_token
return unless token
# Expiration, revocation and scopes are verified in `validate_access_token!`
@@ -99,9 +99,12 @@ module Gitlab
end
def find_oauth_access_token
- token = Doorkeeper::OAuth::Token.from_request(current_request, *Doorkeeper.configuration.access_token_methods)
+ token = parsed_oauth_token
return unless token
+ # PATs with OAuth headers are not handled by OauthAccessToken
+ return if matches_personal_access_token_length?(token)
+
# Expiration, revocation and scopes are verified in `validate_access_token!`
oauth_token = OauthAccessToken.by_token(token)
raise UnauthorizedError unless oauth_token
@@ -110,6 +113,14 @@ module Gitlab
oauth_token
end
+ def parsed_oauth_token
+ Doorkeeper::OAuth::Token.from_request(current_request, *Doorkeeper.configuration.access_token_methods)
+ end
+
+ def matches_personal_access_token_length?(token)
+ token.length == PersonalAccessToken::TOKEN_LENGTH
+ end
+
# Check if the request is GET/HEAD, or if CSRF token is valid.
def verified_request?
Gitlab::RequestForgeryProtection.verified?(current_request.env)
diff --git a/lib/gitlab/background_migration/backfill_project_repositories.rb b/lib/gitlab/background_migration/backfill_project_repositories.rb
index c8d83cc1803..1d9aa050041 100644
--- a/lib/gitlab/background_migration/backfill_project_repositories.rb
+++ b/lib/gitlab/background_migration/backfill_project_repositories.rb
@@ -40,7 +40,7 @@ module Gitlab
end
def reload!
- @shards = Hash[*Shard.all.map { |shard| [shard.name, shard.id] }.flatten]
+ @shards = Hash[*Shard.all.flat_map { |shard| [shard.name, shard.id] }]
end
end
diff --git a/lib/gitlab/background_migration/fill_valid_time_for_pages_domain_certificate.rb b/lib/gitlab/background_migration/fill_valid_time_for_pages_domain_certificate.rb
index 6046d33aeac..4016b807f21 100644
--- a/lib/gitlab/background_migration/fill_valid_time_for_pages_domain_certificate.rb
+++ b/lib/gitlab/background_migration/fill_valid_time_for_pages_domain_certificate.rb
@@ -19,18 +19,11 @@ module Gitlab
def perform(start_id, stop_id)
PagesDomain.where(id: start_id..stop_id).find_each do |domain|
- if Gitlab::Database.mysql?
- domain.update_columns(
- certificate_valid_not_before: domain.x509&.not_before,
- certificate_valid_not_after: domain.x509&.not_after
- )
- else
- # for some reason activerecord doesn't append timezone, iso8601 forces this
- domain.update_columns(
- certificate_valid_not_before: domain.x509&.not_before&.iso8601,
- certificate_valid_not_after: domain.x509&.not_after&.iso8601
- )
- end
+ # for some reason activerecord doesn't append timezone, iso8601 forces this
+ domain.update_columns(
+ certificate_valid_not_before: domain.x509&.not_before&.iso8601,
+ certificate_valid_not_after: domain.x509&.not_after&.iso8601
+ )
rescue => e
Rails.logger.error "Failed to update pages domain certificate valid time. id: #{domain.id}, message: #{e.message}" # rubocop:disable Gitlab/RailsLogger
end
diff --git a/lib/gitlab/background_migration/fix_pages_access_level.rb b/lib/gitlab/background_migration/fix_pages_access_level.rb
new file mode 100644
index 00000000000..0d49f3dd8c5
--- /dev/null
+++ b/lib/gitlab/background_migration/fix_pages_access_level.rb
@@ -0,0 +1,128 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module BackgroundMigration
+ # corrects stored pages access level on db depending on project visibility
+ class FixPagesAccessLevel
+ # Copy routable here to avoid relying on application logic
+ module Routable
+ def build_full_path
+ if parent && path
+ parent.build_full_path + '/' + path
+ else
+ path
+ end
+ end
+ end
+
+ # Namespace
+ class Namespace < ApplicationRecord
+ self.table_name = 'namespaces'
+ self.inheritance_column = :_type_disabled
+
+ include Routable
+
+ belongs_to :parent, class_name: "Namespace"
+ end
+
+ # Project
+ class Project < ActiveRecord::Base
+ self.table_name = 'projects'
+ self.inheritance_column = :_type_disabled
+
+ include Routable
+
+ belongs_to :namespace
+ alias_method :parent, :namespace
+ alias_attribute :parent_id, :namespace_id
+
+ PRIVATE = 0
+ INTERNAL = 10
+ PUBLIC = 20
+
+ def pages_deployed?
+ Dir.exist?(public_pages_path)
+ end
+
+ def public_pages_path
+ File.join(pages_path, 'public')
+ end
+
+ def pages_path
+ # TODO: when we migrate Pages to work with new storage types, change here to use disk_path
+ File.join(Settings.pages.path, build_full_path)
+ end
+ end
+
+ # ProjectFeature
+ class ProjectFeature < ActiveRecord::Base
+ include ::EachBatch
+
+ self.table_name = 'project_features'
+
+ belongs_to :project
+
+ PRIVATE = 10
+ ENABLED = 20
+ PUBLIC = 30
+ end
+
+ def perform(start_id, stop_id)
+ fix_public_access_level(start_id, stop_id)
+
+ make_internal_projects_public(start_id, stop_id)
+
+ fix_private_access_level(start_id, stop_id)
+ end
+
+ private
+
+ def access_control_is_enabled
+ @access_control_is_enabled = Gitlab.config.pages.access_control
+ end
+
+ # Public projects are allowed to have only enabled pages_access_level
+ # which is equivalent to public
+ def fix_public_access_level(start_id, stop_id)
+ project_features(start_id, stop_id, ProjectFeature::PUBLIC, Project::PUBLIC).each_batch do |features|
+ features.update_all(pages_access_level: ProjectFeature::ENABLED)
+ end
+ end
+
+ # If access control is disabled and project has pages deployed
+ # project will become unavailable when access control will become enabled
+ # we make these projects public to avoid negative surprise to user
+ def make_internal_projects_public(start_id, stop_id)
+ return if access_control_is_enabled
+
+ project_features(start_id, stop_id, ProjectFeature::ENABLED, Project::INTERNAL).find_each do |project_feature|
+ next unless project_feature.project.pages_deployed?
+
+ project_feature.update(pages_access_level: ProjectFeature::PUBLIC)
+ end
+ end
+
+ # Private projects are not allowed to have enabled access level, only `private` and `public`
+ # If access control is enabled, these projects currently behave as if the have `private` pages_access_level
+ # if access control is disabled, these projects currently behave as if the have `public` pages_access_level
+ # so we preserve this behaviour for projects with pages already deployed
+ # for project without pages we always set `private` access_level
+ def fix_private_access_level(start_id, stop_id)
+ project_features(start_id, stop_id, ProjectFeature::ENABLED, Project::PRIVATE).find_each do |project_feature|
+ if access_control_is_enabled
+ project_feature.update!(pages_access_level: ProjectFeature::PRIVATE)
+ else
+ fixed_access_level = project_feature.project.pages_deployed? ? ProjectFeature::PUBLIC : ProjectFeature::PRIVATE
+ project_feature.update!(pages_access_level: fixed_access_level)
+ end
+ end
+ end
+
+ def project_features(start_id, stop_id, pages_access_level, project_visibility_level)
+ ProjectFeature.where(id: start_id..stop_id).joins(:project)
+ .where(pages_access_level: pages_access_level)
+ .where(projects: { visibility_level: project_visibility_level })
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/background_migration/migrate_stage_index.rb b/lib/gitlab/background_migration/migrate_stage_index.rb
index f921233460d..55608529cee 100644
--- a/lib/gitlab/background_migration/migrate_stage_index.rb
+++ b/lib/gitlab/background_migration/migrate_stage_index.rb
@@ -13,34 +13,22 @@ module Gitlab
private
def migrate_stage_index_sql(start_id, stop_id)
- if Gitlab::Database.postgresql?
- <<~SQL
- WITH freqs AS (
- SELECT stage_id, stage_idx, COUNT(*) AS freq FROM ci_builds
- WHERE stage_id BETWEEN #{start_id} AND #{stop_id}
- AND stage_idx IS NOT NULL
- GROUP BY stage_id, stage_idx
- ), indexes AS (
- SELECT DISTINCT stage_id, first_value(stage_idx)
- OVER (PARTITION BY stage_id ORDER BY freq DESC) AS index
- FROM freqs
- )
+ <<~SQL
+ WITH freqs AS (
+ SELECT stage_id, stage_idx, COUNT(*) AS freq FROM ci_builds
+ WHERE stage_id BETWEEN #{start_id} AND #{stop_id}
+ AND stage_idx IS NOT NULL
+ GROUP BY stage_id, stage_idx
+ ), indexes AS (
+ SELECT DISTINCT stage_id, first_value(stage_idx)
+ OVER (PARTITION BY stage_id ORDER BY freq DESC) AS index
+ FROM freqs
+ )
- UPDATE ci_stages SET position = indexes.index
- FROM indexes WHERE indexes.stage_id = ci_stages.id
- AND ci_stages.position IS NULL;
- SQL
- else
- <<~SQL
- UPDATE ci_stages
- SET position =
- (SELECT stage_idx FROM ci_builds
- WHERE ci_builds.stage_id = ci_stages.id
- GROUP BY ci_builds.stage_idx ORDER BY COUNT(*) DESC LIMIT 1)
- WHERE ci_stages.id BETWEEN #{start_id} AND #{stop_id}
- AND ci_stages.position IS NULL
- SQL
- end
+ UPDATE ci_stages SET position = indexes.index
+ FROM indexes WHERE indexes.stage_id = ci_stages.id
+ AND ci_stages.position IS NULL;
+ SQL
end
end
end
diff --git a/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb b/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
index 1924f2ffee2..f5fb33f1660 100644
--- a/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
+++ b/lib/gitlab/background_migration/populate_untracked_uploads_dependencies.rb
@@ -176,23 +176,12 @@ module Gitlab
self.table_name = 'projects'
def self.find_by_full_path(path)
- binary = Gitlab::Database.mysql? ? 'BINARY' : ''
- order_sql = "(CASE WHEN #{binary} routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)"
+ order_sql = "(CASE WHEN routes.path = #{connection.quote(path)} THEN 0 ELSE 1 END)"
where_full_path_in(path).reorder(order_sql).take
end
def self.where_full_path_in(path)
- cast_lower = Gitlab::Database.postgresql?
-
- path = connection.quote(path)
-
- where =
- if cast_lower
- "(LOWER(routes.path) = LOWER(#{path}))"
- else
- "(routes.path = #{path})"
- end
-
+ where = "(LOWER(routes.path) = LOWER(#{connection.quote(path)}))"
joins("INNER JOIN routes ON routes.source_id = projects.id AND routes.source_type = 'Project'").where(where)
end
end
diff --git a/lib/gitlab/background_migration/prepare_untracked_uploads.rb b/lib/gitlab/background_migration/prepare_untracked_uploads.rb
index cce2a82c098..2ac51dd7b55 100644
--- a/lib/gitlab/background_migration/prepare_untracked_uploads.rb
+++ b/lib/gitlab/background_migration/prepare_untracked_uploads.rb
@@ -55,7 +55,7 @@ module Gitlab
def ensure_temporary_tracking_table_exists
table_name = :untracked_files_for_uploads
- unless ActiveRecord::Base.connection.data_source_exists?(table_name)
+ unless ActiveRecord::Base.connection.table_exists?(table_name)
UntrackedFile.connection.create_table table_name do |t|
t.string :path, limit: 600, null: false
t.index :path, unique: true
@@ -133,12 +133,9 @@ module Gitlab
def insert_sql(file_paths)
if postgresql_pre_9_5?
"INSERT INTO #{table_columns_and_values_for_insert(file_paths)};"
- elsif postgresql?
+ else
"INSERT INTO #{table_columns_and_values_for_insert(file_paths)}"\
" ON CONFLICT DO NOTHING;"
- else # MySQL
- "INSERT IGNORE INTO"\
- " #{table_columns_and_values_for_insert(file_paths)};"
end
end
@@ -150,19 +147,13 @@ module Gitlab
"#{UntrackedFile.table_name} (path) VALUES #{values}"
end
- def postgresql?
- strong_memoize(:postgresql) do
- Gitlab::Database.postgresql?
- end
- end
-
def can_bulk_insert_and_ignore_duplicates?
!postgresql_pre_9_5?
end
def postgresql_pre_9_5?
strong_memoize(:postgresql_pre_9_5) do
- postgresql? && Gitlab::Database.version.to_f < 9.5
+ Gitlab::Database.version.to_f < 9.5
end
end
diff --git a/lib/gitlab/background_migration/remove_restricted_todos.rb b/lib/gitlab/background_migration/remove_restricted_todos.rb
index 47579d46c1b..9ef6d8654ae 100644
--- a/lib/gitlab/background_migration/remove_restricted_todos.rb
+++ b/lib/gitlab/background_migration/remove_restricted_todos.rb
@@ -50,14 +50,7 @@ module Gitlab
private
def remove_non_members_todos(project_id)
- if Gitlab::Database.postgresql?
- batch_remove_todos_cte(project_id)
- else
- unauthorized_project_todos(project_id)
- .each_batch(of: 5000) do |batch|
- batch.delete_all
- end
- end
+ batch_remove_todos_cte(project_id)
end
def remove_confidential_issue_todos(project_id)
@@ -90,13 +83,7 @@ module Gitlab
next if target_types.empty?
- if Gitlab::Database.postgresql?
- batch_remove_todos_cte(project_id, target_types)
- else
- unauthorized_project_todos(project_id)
- .where(target_type: target_types)
- .delete_all
- end
+ batch_remove_todos_cte(project_id, target_types)
end
end
diff --git a/lib/gitlab/badge/coverage/report.rb b/lib/gitlab/badge/coverage/report.rb
index 7f7cc62c8ef..15cccc6f287 100644
--- a/lib/gitlab/badge/coverage/report.rb
+++ b/lib/gitlab/badge/coverage/report.rb
@@ -14,7 +14,7 @@ module Gitlab
@ref = ref
@job = job
- @pipeline = @project.ci_pipelines.latest_successful_for(@ref)
+ @pipeline = @project.ci_pipelines.latest_successful_for_ref(@ref)
end
def entity
diff --git a/lib/gitlab/blob_helper.rb b/lib/gitlab/blob_helper.rb
index d3e15a79a8b..fc579ad8d2a 100644
--- a/lib/gitlab/blob_helper.rb
+++ b/lib/gitlab/blob_helper.rb
@@ -45,7 +45,7 @@ module Gitlab
end
def image?
- ['.png', '.jpg', '.jpeg', '.gif'].include?(extname.downcase)
+ ['.png', '.jpg', '.jpeg', '.gif', '.svg'].include?(extname.downcase)
end
# Internal: Lookup mime type for extension.
diff --git a/lib/gitlab/chaos.rb b/lib/gitlab/chaos.rb
new file mode 100644
index 00000000000..4f47cdef971
--- /dev/null
+++ b/lib/gitlab/chaos.rb
@@ -0,0 +1,49 @@
+# frozen_string_literal: true
+
+module Gitlab
+ # Chaos methods for GitLab.
+ # See https://docs.gitlab.com/ee/development/chaos_endpoints.html for more details.
+ class Chaos
+ # leak_mem will retain the specified amount of memory and sleep.
+ # On return, the memory will be released.
+ def self.leak_mem(memory_mb, duration_s)
+ start_time = Time.now
+
+ retainer = []
+ # Add `n` 1mb chunks of memory to the retainer array
+ memory_mb.times { retainer << "x" * 1.megabyte }
+
+ duration_left = [start_time + duration_s - Time.now, 0].max
+ Kernel.sleep(duration_left)
+ end
+
+ # cpu_spin will consume all CPU on a single core for the specified duration
+ def self.cpu_spin(duration_s)
+ expected_end_time = Time.now + duration_s
+
+ rand while Time.now < expected_end_time
+ end
+
+ # db_spin will query the database in a tight loop for the specified duration
+ def self.db_spin(duration_s, interval_s)
+ expected_end_time = Time.now + duration_s
+
+ while Time.now < expected_end_time
+ ActiveRecord::Base.connection.execute("SELECT 1")
+
+ end_interval_time = Time.now + [duration_s, interval_s].min
+ rand while Time.now < end_interval_time
+ end
+ end
+
+ # sleep will sleep for the specified duration
+ def self.sleep(duration_s)
+ Kernel.sleep(duration_s)
+ end
+
+ # Kill will send a SIGKILL signal to the current process
+ def self.kill
+ Process.kill("KILL", Process.pid)
+ end
+ end
+end
diff --git a/lib/gitlab/ci/ansi2html.rb b/lib/gitlab/ci/ansi2html.rb
index fc3223e7442..7e348763e81 100644
--- a/lib/gitlab/ci/ansi2html.rb
+++ b/lib/gitlab/ci/ansi2html.rb
@@ -194,16 +194,10 @@ module Gitlab
end
def handle_new_line
- css_classes = []
-
- if @sections.any?
- css_classes = %w[section line] + sections.map { |section| "s_#{section}" }
- end
-
write_in_tag %{<br/>}
- write_raw %{<span class="#{css_classes.join(' ')}"></span>} if css_classes.any?
+
+ close_open_tags if @sections.any? && @lineno_in_section == 0
@lineno_in_section += 1
- open_new_tag
end
def handle_section(scanner)
@@ -310,11 +304,24 @@ module Gitlab
if @sections.any?
css_classes << "section"
- css_classes << "js-section-header section-header" if @lineno_in_section == 0
+
+ css_classes << if @lineno_in_section == 0
+ "js-section-header section-header"
+ else
+ "line"
+ end
+
css_classes += sections.map { |section| "js-s-#{section}" }
end
- @out << %{<span class="#{css_classes.join(' ')}">}
+ close_open_tags
+
+ @out << if css_classes.any?
+ %{<span class="#{css_classes.join(' ')}">}
+ else
+ %{<span>}
+ end
+
@n_open_tags += 1
end
diff --git a/lib/gitlab/ci/charts.rb b/lib/gitlab/ci/charts.rb
index 7cabaadb122..3fbfdffe277 100644
--- a/lib/gitlab/ci/charts.rb
+++ b/lib/gitlab/ci/charts.rb
@@ -21,16 +21,10 @@ module Gitlab
module MonthlyInterval
# rubocop: disable CodeReuse/ActiveRecord
def grouped_count(query)
- if Gitlab::Database.postgresql?
- query
- .group("to_char(#{::Ci::Pipeline.table_name}.created_at, '01 Month YYYY')")
- .count(:created_at)
- .transform_keys(&:squish)
- else
- query
- .group("DATE_FORMAT(#{::Ci::Pipeline.table_name}.created_at, '01 %M %Y')")
- .count(:created_at)
- end
+ query
+ .group("to_char(#{::Ci::Pipeline.table_name}.created_at, '01 Month YYYY')")
+ .count(:created_at)
+ .transform_keys(&:squish)
end
# rubocop: enable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/ci/config/entry/job.rb b/lib/gitlab/ci/config/entry/job.rb
index 5ab795359b8..2fd76bc3690 100644
--- a/lib/gitlab/ci/config/entry/job.rb
+++ b/lib/gitlab/ci/config/entry/job.rb
@@ -13,7 +13,7 @@ module Gitlab
ALLOWED_KEYS = %i[tags script only except type image services
allow_failure type stage when start_in artifacts cache
- dependencies before_script after_script variables
+ dependencies needs before_script after_script variables
environment coverage retry parallel extends].freeze
validations do
@@ -34,11 +34,22 @@ module Gitlab
message: 'should be on_success, on_failure, ' \
'always, manual or delayed' }
validates :dependencies, array_of_strings: true
+ validates :needs, array_of_strings: true
validates :extends, array_of_strings_or_string: true
end
validates :start_in, duration: { limit: '1 day' }, if: :delayed?
validates :start_in, absence: true, unless: :delayed?
+
+ validate do
+ next unless dependencies.present?
+ next unless needs.present?
+
+ missing_needs = dependencies - needs
+ if missing_needs.any?
+ errors.add(:dependencies, "the #{missing_needs.join(", ")} should be part of needs")
+ end
+ end
end
entry :before_script, Entry::Script,
@@ -95,10 +106,10 @@ module Gitlab
helpers :before_script, :script, :stage, :type, :after_script,
:cache, :image, :services, :only, :except, :variables,
:artifacts, :environment, :coverage, :retry,
- :parallel
+ :parallel, :needs
attributes :script, :tags, :allow_failure, :when, :dependencies,
- :retry, :parallel, :extends, :start_in
+ :needs, :retry, :parallel, :extends, :start_in
def self.matching?(name, config)
!name.to_s.start_with?('.') &&
@@ -178,7 +189,8 @@ module Gitlab
parallel: parallel_defined? ? parallel_value.to_i : nil,
artifacts: artifacts_value,
after_script: after_script_value,
- ignore: ignored? }
+ ignore: ignored?,
+ needs: needs_defined? ? needs_value : nil }
end
end
end
diff --git a/lib/gitlab/ci/config/normalizer.rb b/lib/gitlab/ci/config/normalizer.rb
index 191f5d09645..09f9bf5f69f 100644
--- a/lib/gitlab/ci/config/normalizer.rb
+++ b/lib/gitlab/ci/config/normalizer.rb
@@ -4,61 +4,63 @@ module Gitlab
module Ci
class Config
class Normalizer
+ include Gitlab::Utils::StrongMemoize
+
def initialize(jobs_config)
@jobs_config = jobs_config
end
def normalize_jobs
- extract_parallelized_jobs!
- return @jobs_config if @parallelized_jobs.empty?
+ return @jobs_config if parallelized_jobs.empty?
+
+ expand_parallelize_jobs do |job_name, config|
+ if config[:dependencies]
+ config[:dependencies] = expand_names(config[:dependencies])
+ end
- parallelized_config = parallelize_jobs
- parallelize_dependencies(parallelized_config)
+ if config[:needs]
+ config[:needs] = expand_names(config[:needs])
+ end
+
+ config
+ end
end
private
- def extract_parallelized_jobs!
- @parallelized_jobs = {}
+ def expand_names(job_names)
+ return unless job_names
- @jobs_config.each do |job_name, config|
- if config[:parallel]
- @parallelized_jobs[job_name] = self.class.parallelize_job_names(job_name, config[:parallel])
- end
+ job_names.flat_map do |job_name|
+ parallelized_jobs[job_name.to_sym] || job_name
end
-
- @parallelized_jobs
end
- def parallelize_jobs
- @jobs_config.each_with_object({}) do |(job_name, config), hash|
- if @parallelized_jobs.key?(job_name)
- @parallelized_jobs[job_name].each { |name, index| hash[name.to_sym] = config.merge(name: name, instance: index) }
- else
- hash[job_name] = config
- end
+ def parallelized_jobs
+ strong_memoize(:parallelized_jobs) do
+ @jobs_config.each_with_object({}) do |(job_name, config), hash|
+ next unless config[:parallel]
- hash
+ hash[job_name] = self.class.parallelize_job_names(job_name, config[:parallel])
+ end
end
end
- def parallelize_dependencies(parallelized_config)
- parallelized_job_names = @parallelized_jobs.keys.map(&:to_s)
- parallelized_config.each_with_object({}) do |(job_name, config), hash|
- if config[:dependencies] && (intersection = config[:dependencies] & parallelized_job_names).any?
- parallelized_deps = intersection.map { |dep| @parallelized_jobs[dep.to_sym].map(&:first) }.flatten
- deps = config[:dependencies] - intersection + parallelized_deps
- hash[job_name] = config.merge(dependencies: deps)
+ def expand_parallelize_jobs
+ @jobs_config.each_with_object({}) do |(job_name, config), hash|
+ if parallelized_jobs.key?(job_name)
+ parallelized_jobs[job_name].each_with_index do |name, index|
+ hash[name.to_sym] =
+ yield(name, config.merge(name: name, instance: index + 1))
+ end
else
- hash[job_name] = config
+ hash[job_name] = yield(job_name, config)
end
-
- hash
end
end
def self.parallelize_job_names(name, total)
- Array.new(total) { |index| ["#{name} #{index + 1}/#{total}", index + 1] }
+ Array.new(total) { |index| "#{name} #{index + 1}/#{total}" }
end
end
end
diff --git a/lib/gitlab/ci/pipeline/seed/build.rb b/lib/gitlab/ci/pipeline/seed/build.rb
index d8296940a04..ab0d4c38ab6 100644
--- a/lib/gitlab/ci/pipeline/seed/build.rb
+++ b/lib/gitlab/ci/pipeline/seed/build.rb
@@ -9,9 +9,10 @@ module Gitlab
delegate :dig, to: :@attributes
- def initialize(pipeline, attributes)
+ def initialize(pipeline, attributes, previous_stages)
@pipeline = pipeline
@attributes = attributes
+ @previous_stages = previous_stages
@only = Gitlab::Ci::Build::Policy
.fabricate(attributes.delete(:only))
@@ -19,10 +20,15 @@ module Gitlab
.fabricate(attributes.delete(:except))
end
+ def name
+ dig(:name)
+ end
+
def included?
strong_memoize(:inclusion) do
- @only.all? { |spec| spec.satisfied_by?(@pipeline, self) } &&
- @except.none? { |spec| spec.satisfied_by?(@pipeline, self) }
+ all_of_only? &&
+ none_of_except? &&
+ all_of_needs?
end
end
@@ -42,6 +48,25 @@ module Gitlab
@attributes.to_h.dig(:options, :trigger).present?
end
+ def all_of_only?
+ @only.all? { |spec| spec.satisfied_by?(@pipeline, self) }
+ end
+
+ def none_of_except?
+ @except.none? { |spec| spec.satisfied_by?(@pipeline, self) }
+ end
+
+ def all_of_needs?
+ return true unless Feature.enabled?(:ci_dag_support, @pipeline.project)
+ return true if dig(:needs_attributes).nil?
+
+ dig(:needs_attributes).all? do |need|
+ @previous_stages.any? do |stage|
+ stage.seeds_names.include?(need[:name])
+ end
+ end
+ end
+
def to_resource
strong_memoize(:resource) do
if bridge?
diff --git a/lib/gitlab/ci/pipeline/seed/stage.rb b/lib/gitlab/ci/pipeline/seed/stage.rb
index 9c15064756a..7c737027445 100644
--- a/lib/gitlab/ci/pipeline/seed/stage.rb
+++ b/lib/gitlab/ci/pipeline/seed/stage.rb
@@ -10,12 +10,13 @@ module Gitlab
delegate :size, to: :seeds
delegate :dig, to: :seeds
- def initialize(pipeline, attributes)
+ def initialize(pipeline, attributes, previous_stages)
@pipeline = pipeline
@attributes = attributes
+ @previous_stages = previous_stages
@builds = attributes.fetch(:builds).map do |attributes|
- Seed::Build.new(@pipeline, attributes)
+ Seed::Build.new(@pipeline, attributes, previous_stages)
end
end
@@ -32,6 +33,12 @@ module Gitlab
end
end
+ def seeds_names
+ strong_memoize(:seeds_names) do
+ seeds.map(&:name).to_set
+ end
+ end
+
def included?
seeds.any?
end
@@ -39,13 +46,7 @@ module Gitlab
def to_resource
strong_memoize(:stage) do
::Ci::Stage.new(attributes).tap do |stage|
- seeds.each do |seed|
- if seed.bridge?
- stage.bridges << seed.to_resource
- else
- stage.builds << seed.to_resource
- end
- end
+ stage.statuses = seeds.map(&:to_resource)
end
end
end
diff --git a/lib/gitlab/ci/status/build/manual.rb b/lib/gitlab/ci/status/build/manual.rb
index d01b09f1398..df572188194 100644
--- a/lib/gitlab/ci/status/build/manual.rb
+++ b/lib/gitlab/ci/status/build/manual.rb
@@ -10,7 +10,7 @@ module Gitlab
image: 'illustrations/manual_action.svg',
size: 'svg-394',
title: _('This job requires a manual action'),
- content: _('This job depends on a user to trigger its process. Often they are used to deploy code to production environments')
+ content: _('This job requires manual intervention to start. Before starting this job, you can add variables below for last-minute configuration changes.')
}
end
diff --git a/lib/gitlab/ci/status/factory.rb b/lib/gitlab/ci/status/factory.rb
index 3446644eff8..2a0bf060c9b 100644
--- a/lib/gitlab/ci/status/factory.rb
+++ b/lib/gitlab/ci/status/factory.rb
@@ -34,11 +34,9 @@ module Gitlab
def extended_statuses
return @extended_statuses if defined?(@extended_statuses)
- groups = self.class.extended_statuses.map do |group|
+ @extended_statuses = self.class.extended_statuses.flat_map do |group|
Array(group).find { |status| status.matches?(@subject, @user) }
- end
-
- @extended_statuses = groups.flatten.compact
+ end.compact
end
def self.extended_statuses
diff --git a/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml b/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml
index cf3d261c1cb..5c1c0c142e5 100644
--- a/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Auto-DevOps.gitlab-ci.yml
@@ -50,13 +50,12 @@ variables:
POSTGRES_DB: $CI_ENVIRONMENT_SLUG
POSTGRES_VERSION: 9.6.2
- KUBERNETES_VERSION: 1.11.10
- HELM_VERSION: 2.14.0
-
DOCKER_DRIVER: overlay2
ROLLOUT_RESOURCE_TYPE: deployment
+ DOCKER_TLS_CERTDIR: "" # https://gitlab.com/gitlab-org/gitlab-runner/issues/4501
+
stages:
- build
- test
diff --git a/lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml b/lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml
index a09217e8cf0..b0a79950667 100644
--- a/lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Jobs/Browser-Performance-Testing.gitlab-ci.yml
@@ -2,6 +2,8 @@ performance:
stage: performance
image: docker:stable
allow_failure: true
+ variables:
+ DOCKER_TLS_CERTDIR: ""
services:
- docker:stable-dind
script:
diff --git a/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml b/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml
index 18f7290e1d9..8061da968ed 100644
--- a/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Jobs/Build.gitlab-ci.yml
@@ -1,6 +1,8 @@
build:
stage: build
image: "registry.gitlab.com/gitlab-org/cluster-integration/auto-build-image/master:stable"
+ variables:
+ DOCKER_TLS_CERTDIR: ""
services:
- docker:stable-dind
script:
diff --git a/lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml b/lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml
index 005ea4b7a46..3adc6a72874 100644
--- a/lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Jobs/Code-Quality.gitlab-ci.yml
@@ -6,6 +6,7 @@ code_quality:
- docker:stable-dind
variables:
DOCKER_DRIVER: overlay2
+ DOCKER_TLS_CERTDIR: ""
script:
- |
if ! docker info &>/dev/null; then
diff --git a/lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml b/lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml
index 108f0119ae1..a8ec2d4781d 100644
--- a/lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Jobs/Deploy.gitlab-ci.yml
@@ -1,14 +1,17 @@
+.auto-deploy:
+ image: "registry.gitlab.com/gitlab-org/cluster-integration/auto-deploy-image:v0.1.0"
+
review:
+ extends: .auto-deploy
stage: review
script:
- - check_kube_domain
- - install_dependencies
- - download_chart
- - ensure_namespace
- - initialize_tiller
- - create_secret
- - deploy
- - persist_environment_url
+ - auto-deploy check_kube_domain
+ - auto-deploy download_chart
+ - auto-deploy ensure_namespace
+ - auto-deploy initialize_tiller
+ - auto-deploy create_secret
+ - auto-deploy deploy
+ - auto-deploy persist_environment_url
environment:
name: review/$CI_COMMIT_REF_NAME
url: http://$CI_PROJECT_ID-$CI_ENVIRONMENT_SLUG.$KUBE_INGRESS_BASE_DOMAIN
@@ -27,13 +30,13 @@ review:
- $REVIEW_DISABLED
stop_review:
+ extends: .auto-deploy
stage: cleanup
variables:
GIT_STRATEGY: none
script:
- - install_dependencies
- - initialize_tiller
- - delete
+ - auto-deploy initialize_tiller
+ - auto-deploy delete
environment:
name: review/$CI_COMMIT_REF_NAME
action: stop
@@ -57,15 +60,15 @@ stop_review:
# STAGING_ENABLED.
staging:
+ extends: .auto-deploy
stage: staging
script:
- - check_kube_domain
- - install_dependencies
- - download_chart
- - ensure_namespace
- - initialize_tiller
- - create_secret
- - deploy
+ - auto-deploy check_kube_domain
+ - auto-deploy download_chart
+ - auto-deploy ensure_namespace
+ - auto-deploy initialize_tiller
+ - auto-deploy create_secret
+ - auto-deploy deploy
environment:
name: staging
url: http://$CI_PROJECT_PATH_SLUG-staging.$KUBE_INGRESS_BASE_DOMAIN
@@ -81,15 +84,15 @@ staging:
# CANARY_ENABLED.
canary:
+ extends: .auto-deploy
stage: canary
script:
- - check_kube_domain
- - install_dependencies
- - download_chart
- - ensure_namespace
- - initialize_tiller
- - create_secret
- - deploy canary
+ - auto-deploy check_kube_domain
+ - auto-deploy download_chart
+ - auto-deploy ensure_namespace
+ - auto-deploy initialize_tiller
+ - auto-deploy create_secret
+ - auto-deploy deploy canary
environment:
name: production
url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
@@ -102,18 +105,18 @@ canary:
- $CANARY_ENABLED
.production: &production_template
+ extends: .auto-deploy
stage: production
script:
- - check_kube_domain
- - install_dependencies
- - download_chart
- - ensure_namespace
- - initialize_tiller
- - create_secret
- - deploy
- - delete canary
- - delete rollout
- - persist_environment_url
+ - auto-deploy check_kube_domain
+ - auto-deploy download_chart
+ - auto-deploy ensure_namespace
+ - auto-deploy initialize_tiller
+ - auto-deploy create_secret
+ - auto-deploy deploy
+ - auto-deploy delete canary
+ - auto-deploy delete rollout
+ - auto-deploy persist_environment_url
environment:
name: production
url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
@@ -152,17 +155,17 @@ production_manual:
# This job implements incremental rollout on for every push to `master`.
.rollout: &rollout_template
+ extends: .auto-deploy
script:
- - check_kube_domain
- - install_dependencies
- - download_chart
- - ensure_namespace
- - initialize_tiller
- - create_secret
- - deploy rollout $ROLLOUT_PERCENTAGE
- - scale stable $((100-ROLLOUT_PERCENTAGE))
- - delete canary
- - persist_environment_url
+ - auto-deploy check_kube_domain
+ - auto-deploy download_chart
+ - auto-deploy ensure_namespace
+ - auto-deploy initialize_tiller
+ - auto-deploy create_secret
+ - auto-deploy deploy rollout $ROLLOUT_PERCENTAGE
+ - auto-deploy scale stable $((100-ROLLOUT_PERCENTAGE))
+ - auto-deploy delete canary
+ - auto-deploy persist_environment_url
environment:
name: production
url: http://$CI_PROJECT_PATH_SLUG.$KUBE_INGRESS_BASE_DOMAIN
@@ -240,330 +243,3 @@ rollout 100%:
<<: *manual_rollout_template
<<: *production_template
allow_failure: false
-
-.deploy_helpers: &deploy_helpers |
- [[ "$TRACE" ]] && set -x
- auto_database_url=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@${CI_ENVIRONMENT_SLUG}-postgres:5432/${POSTGRES_DB}
- export DATABASE_URL=${DATABASE_URL-$auto_database_url}
- export TILLER_NAMESPACE=$KUBE_NAMESPACE
-
- function get_replicas() {
- track="${1:-stable}"
- percentage="${2:-100}"
-
- env_track=$( echo $track | tr -s '[:lower:]' '[:upper:]' )
- env_slug=$( echo ${CI_ENVIRONMENT_SLUG//-/_} | tr -s '[:lower:]' '[:upper:]' )
-
- if [[ "$track" == "stable" ]] || [[ "$track" == "rollout" ]]; then
- # for stable track get number of replicas from `PRODUCTION_REPLICAS`
- eval new_replicas=\$${env_slug}_REPLICAS
- if [[ -z "$new_replicas" ]]; then
- new_replicas=$REPLICAS
- fi
- else
- # for all tracks get number of replicas from `CANARY_PRODUCTION_REPLICAS`
- eval new_replicas=\$${env_track}_${env_slug}_REPLICAS
- if [[ -z "$new_replicas" ]]; then
- eval new_replicas=\${env_track}_REPLICAS
- fi
- fi
-
- replicas="${new_replicas:-1}"
- replicas="$(($replicas * $percentage / 100))"
-
- # always return at least one replicas
- if [[ $replicas -gt 0 ]]; then
- echo "$replicas"
- else
- echo 1
- fi
- }
-
- # Extracts variables prefixed with K8S_SECRET_
- # and creates a Kubernetes secret.
- #
- # e.g. If we have the following environment variables:
- # K8S_SECRET_A=value1
- # K8S_SECRET_B=multi\ word\ value
- #
- # Then we will create a secret with the following key-value pairs:
- # data:
- # A: dmFsdWUxCg==
- # B: bXVsdGkgd29yZCB2YWx1ZQo=
- function create_application_secret() {
- track="${1-stable}"
- export APPLICATION_SECRET_NAME=$(application_secret_name "$track")
-
- env | sed -n "s/^K8S_SECRET_\(.*\)$/\1/p" > k8s_prefixed_variables
-
- kubectl create secret \
- -n "$KUBE_NAMESPACE" generic "$APPLICATION_SECRET_NAME" \
- --from-env-file k8s_prefixed_variables -o yaml --dry-run |
- kubectl replace -n "$KUBE_NAMESPACE" --force -f -
-
- export APPLICATION_SECRET_CHECKSUM=$(cat k8s_prefixed_variables | sha256sum | cut -d ' ' -f 1)
-
- rm k8s_prefixed_variables
- }
-
- function deploy_name() {
- name="$CI_ENVIRONMENT_SLUG"
- track="${1-stable}"
-
- if [[ "$track" != "stable" ]]; then
- name="$name-$track"
- fi
-
- echo $name
- }
-
- function application_secret_name() {
- track="${1-stable}"
- name=$(deploy_name "$track")
-
- echo "${name}-secret"
- }
-
- function deploy() {
- track="${1-stable}"
- percentage="${2:-100}"
- name=$(deploy_name "$track")
-
- if [[ -z "$CI_COMMIT_TAG" ]]; then
- image_repository=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG}
- image_tag=${CI_APPLICATION_TAG:-$CI_COMMIT_SHA}
- else
- image_repository=${CI_APPLICATION_REPOSITORY:-$CI_REGISTRY_IMAGE}
- image_tag=${CI_APPLICATION_TAG:-$CI_COMMIT_TAG}
- fi
-
- service_enabled="true"
- postgres_enabled="$POSTGRES_ENABLED"
-
- # if track is different than stable,
- # re-use all attached resources
- if [[ "$track" != "stable" ]]; then
- service_enabled="false"
- postgres_enabled="false"
- fi
-
- replicas=$(get_replicas "$track" "$percentage")
-
- if [[ "$CI_PROJECT_VISIBILITY" != "public" ]]; then
- secret_name='gitlab-registry'
- else
- secret_name=''
- fi
-
- create_application_secret "$track"
-
- env_slug=$(echo ${CI_ENVIRONMENT_SLUG//-/_} | tr -s '[:lower:]' '[:upper:]')
- eval env_ADDITIONAL_HOSTS=\$${env_slug}_ADDITIONAL_HOSTS
- if [ -n "$env_ADDITIONAL_HOSTS" ]; then
- additional_hosts="{$env_ADDITIONAL_HOSTS}"
- elif [ -n "$ADDITIONAL_HOSTS" ]; then
- additional_hosts="{$ADDITIONAL_HOSTS}"
- fi
-
- if [[ -n "$DB_INITIALIZE" && -z "$(helm ls -q "^$name$")" ]]; then
- echo "Deploying first release with database initialization..."
- helm upgrade --install \
- --wait \
- --set service.enabled="$service_enabled" \
- --set gitlab.app="$CI_PROJECT_PATH_SLUG" \
- --set gitlab.env="$CI_ENVIRONMENT_SLUG" \
- --set releaseOverride="$CI_ENVIRONMENT_SLUG" \
- --set image.repository="$image_repository" \
- --set image.tag="$image_tag" \
- --set image.pullPolicy=IfNotPresent \
- --set image.secrets[0].name="$secret_name" \
- --set application.track="$track" \
- --set application.database_url="$DATABASE_URL" \
- --set application.secretName="$APPLICATION_SECRET_NAME" \
- --set application.secretChecksum="$APPLICATION_SECRET_CHECKSUM" \
- --set service.commonName="le-$CI_PROJECT_ID.$KUBE_INGRESS_BASE_DOMAIN" \
- --set service.url="$CI_ENVIRONMENT_URL" \
- --set service.additionalHosts="$additional_hosts" \
- --set replicaCount="$replicas" \
- --set postgresql.enabled="$postgres_enabled" \
- --set postgresql.nameOverride="postgres" \
- --set postgresql.postgresUser="$POSTGRES_USER" \
- --set postgresql.postgresPassword="$POSTGRES_PASSWORD" \
- --set postgresql.postgresDatabase="$POSTGRES_DB" \
- --set postgresql.imageTag="$POSTGRES_VERSION" \
- --set application.initializeCommand="$DB_INITIALIZE" \
- $HELM_UPGRADE_EXTRA_ARGS \
- --namespace="$KUBE_NAMESPACE" \
- "$name" \
- chart/
-
- echo "Deploying second release..."
- helm upgrade --reuse-values \
- --wait \
- --set application.initializeCommand="" \
- --set application.migrateCommand="$DB_MIGRATE" \
- $HELM_UPGRADE_EXTRA_ARGS \
- --namespace="$KUBE_NAMESPACE" \
- "$name" \
- chart/
- else
- echo "Deploying new release..."
- helm upgrade --install \
- --wait \
- --set service.enabled="$service_enabled" \
- --set gitlab.app="$CI_PROJECT_PATH_SLUG" \
- --set gitlab.env="$CI_ENVIRONMENT_SLUG" \
- --set releaseOverride="$CI_ENVIRONMENT_SLUG" \
- --set image.repository="$image_repository" \
- --set image.tag="$image_tag" \
- --set image.pullPolicy=IfNotPresent \
- --set image.secrets[0].name="$secret_name" \
- --set application.track="$track" \
- --set application.database_url="$DATABASE_URL" \
- --set application.secretName="$APPLICATION_SECRET_NAME" \
- --set application.secretChecksum="$APPLICATION_SECRET_CHECKSUM" \
- --set service.commonName="le-$CI_PROJECT_ID.$KUBE_INGRESS_BASE_DOMAIN" \
- --set service.url="$CI_ENVIRONMENT_URL" \
- --set service.additionalHosts="$additional_hosts" \
- --set replicaCount="$replicas" \
- --set postgresql.enabled="$postgres_enabled" \
- --set postgresql.nameOverride="postgres" \
- --set postgresql.postgresUser="$POSTGRES_USER" \
- --set postgresql.postgresPassword="$POSTGRES_PASSWORD" \
- --set postgresql.postgresDatabase="$POSTGRES_DB" \
- --set postgresql.imageTag="$POSTGRES_VERSION" \
- --set application.migrateCommand="$DB_MIGRATE" \
- $HELM_UPGRADE_EXTRA_ARGS \
- --namespace="$KUBE_NAMESPACE" \
- "$name" \
- chart/
- fi
-
- if [[ -z "$ROLLOUT_STATUS_DISABLED" ]]; then
- kubectl rollout status -n "$KUBE_NAMESPACE" -w "$ROLLOUT_RESOURCE_TYPE/$name"
- fi
- }
-
- function scale() {
- track="${1-stable}"
- percentage="${2-100}"
- name=$(deploy_name "$track")
-
- replicas=$(get_replicas "$track" "$percentage")
-
- if [[ -n "$(helm ls -q "^$name$")" ]]; then
- helm upgrade --reuse-values \
- --wait \
- --set replicaCount="$replicas" \
- --namespace="$KUBE_NAMESPACE" \
- "$name" \
- chart/
- fi
- }
-
- function install_dependencies() {
- apk add -U openssl curl tar gzip bash ca-certificates git
- curl -sSL -o /etc/apk/keys/sgerrand.rsa.pub https://alpine-pkgs.sgerrand.com/sgerrand.rsa.pub
- curl -sSL -O https://github.com/sgerrand/alpine-pkg-glibc/releases/download/2.28-r0/glibc-2.28-r0.apk
- apk add glibc-2.28-r0.apk
- rm glibc-2.28-r0.apk
-
- curl -sS "https://kubernetes-helm.storage.googleapis.com/helm-v${HELM_VERSION}-linux-amd64.tar.gz" | tar zx
- mv linux-amd64/helm /usr/bin/
- mv linux-amd64/tiller /usr/bin/
- helm version --client
- tiller -version
-
- curl -sSL -o /usr/bin/kubectl "https://storage.googleapis.com/kubernetes-release/release/v${KUBERNETES_VERSION}/bin/linux/amd64/kubectl"
- chmod +x /usr/bin/kubectl
- kubectl version --client
- }
-
- function download_chart() {
- if [[ ! -d chart ]]; then
- auto_chart=${AUTO_DEVOPS_CHART:-gitlab/auto-deploy-app}
- auto_chart_name=$(basename $auto_chart)
- auto_chart_name=${auto_chart_name%.tgz}
- auto_chart_name=${auto_chart_name%.tar.gz}
- else
- auto_chart="chart"
- auto_chart_name="chart"
- fi
-
- helm init --client-only
- helm repo add ${AUTO_DEVOPS_CHART_REPOSITORY_NAME:-gitlab} ${AUTO_DEVOPS_CHART_REPOSITORY:-https://charts.gitlab.io} ${AUTO_DEVOPS_CHART_REPOSITORY_USERNAME:+"--username" "$AUTO_DEVOPS_CHART_REPOSITORY_USERNAME"} ${AUTO_DEVOPS_CHART_REPOSITORY_PASSWORD:+"--password" "$AUTO_DEVOPS_CHART_REPOSITORY_PASSWORD"}
- if [[ ! -d "$auto_chart" ]]; then
- helm fetch ${auto_chart} --untar
- fi
- if [ "$auto_chart_name" != "chart" ]; then
- mv ${auto_chart_name} chart
- fi
-
- helm dependency update chart/
- helm dependency build chart/
- }
-
- function ensure_namespace() {
- kubectl get namespace "$KUBE_NAMESPACE" || kubectl create namespace "$KUBE_NAMESPACE"
- }
-
- function check_kube_domain() {
- if [[ -z "$KUBE_INGRESS_BASE_DOMAIN" ]]; then
- echo "In order to deploy or use Review Apps,"
- echo "KUBE_INGRESS_BASE_DOMAIN variables must be set"
- echo "From 11.8, you can set KUBE_INGRESS_BASE_DOMAIN in cluster settings"
- echo "or by defining a variable at group or project level."
- echo "You can also manually add it in .gitlab-ci.yml"
- false
- else
- true
- fi
- }
-
- function initialize_tiller() {
- echo "Checking Tiller..."
-
- export HELM_HOST="localhost:44134"
- tiller -listen ${HELM_HOST} -alsologtostderr > /dev/null 2>&1 &
- echo "Tiller is listening on ${HELM_HOST}"
-
- if ! helm version --debug; then
- echo "Failed to init Tiller."
- return 1
- fi
- echo ""
- }
-
- function create_secret() {
- echo "Create secret..."
- if [[ "$CI_PROJECT_VISIBILITY" == "public" ]]; then
- return
- fi
-
- kubectl create secret -n "$KUBE_NAMESPACE" \
- docker-registry gitlab-registry \
- --docker-server="$CI_REGISTRY" \
- --docker-username="${CI_DEPLOY_USER:-$CI_REGISTRY_USER}" \
- --docker-password="${CI_DEPLOY_PASSWORD:-$CI_REGISTRY_PASSWORD}" \
- --docker-email="$GITLAB_USER_EMAIL" \
- -o yaml --dry-run | kubectl replace -n "$KUBE_NAMESPACE" --force -f -
- }
-
- function persist_environment_url() {
- echo $CI_ENVIRONMENT_URL > environment_url.txt
- }
-
- function delete() {
- track="${1-stable}"
- name=$(deploy_name "$track")
-
- if [[ -n "$(helm ls -q "^$name$")" ]]; then
- helm delete --purge "$name"
- fi
-
- secret_name=$(application_secret_name "$track")
- kubectl delete secret --ignore-not-found -n "$KUBE_NAMESPACE" "$secret_name"
- }
-
-before_script:
- - *deploy_helpers
diff --git a/lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml b/lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml
index 5ad624bb15f..c963d6ed1c4 100644
--- a/lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Security/Container-Scanning.gitlab-ci.yml
@@ -5,6 +5,7 @@ container_scanning:
image: docker:stable
variables:
DOCKER_DRIVER: overlay2
+ DOCKER_TLS_CERTDIR: ""
# Defining two new variables based on GitLab's CI/CD predefined variables
# https://docs.gitlab.com/ee/ci/variables/#predefined-environment-variables
CI_APPLICATION_REPOSITORY: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_SLUG
@@ -22,8 +23,8 @@ container_scanning:
DOCKER_SERVICE: docker
DOCKER_HOST: tcp://${DOCKER_SERVICE}:2375/
# https://hub.docker.com/r/arminc/clair-local-scan/tags
- CLAIR_LOCAL_SCAN_VERSION: v2.0.8_fe9b059d930314b54c78f75afe265955faf4fdc1
- CLAIR_EXECUTABLE_VERSION: v11
+ CLAIR_LOCAL_SCAN_VERSION: v2.0.8_0ed98e9ead65a51ba53f7cc53fa5e80c92169207
+ CLAIR_EXECUTABLE_VERSION: v12
## Disable the proxy for clair-local-scan, otherwise Container Scanning will
## fail when a proxy is used.
NO_PROXY: ${DOCKER_SERVICE},localhost
diff --git a/lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml b/lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml
index f176771775e..15b84f1540d 100644
--- a/lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Security/Dependency-Scanning.gitlab-ci.yml
@@ -9,6 +9,7 @@ dependency_scanning:
image: docker:stable
variables:
DOCKER_DRIVER: overlay2
+ DOCKER_TLS_CERTDIR: ""
allow_failure: true
services:
- docker:stable-dind
@@ -41,6 +42,9 @@ dependency_scanning:
DS_PULL_ANALYZER_IMAGE_TIMEOUT \
DS_RUN_ANALYZER_TIMEOUT \
DS_PYTHON_VERSION \
+ DS_PIP_DEPENDENCY_PATH \
+ PIP_INDEX_URL \
+ PIP_EXTRA_INDEX_URL \
) \
--volume "$PWD:/code" \
--volume /var/run/docker.sock:/var/run/docker.sock \
diff --git a/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml b/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml
index 0a97a16b83c..4190de73e1f 100644
--- a/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Security/SAST.gitlab-ci.yml
@@ -9,6 +9,7 @@ sast:
image: docker:stable
variables:
DOCKER_DRIVER: overlay2
+ DOCKER_TLS_CERTDIR: ""
allow_failure: true
services:
- docker:stable-dind
diff --git a/lib/gitlab/ci/templates/Serverless.gitlab-ci.yml b/lib/gitlab/ci/templates/Serverless.gitlab-ci.yml
index a3db2705bf6..280e75d46f5 100644
--- a/lib/gitlab/ci/templates/Serverless.gitlab-ci.yml
+++ b/lib/gitlab/ci/templates/Serverless.gitlab-ci.yml
@@ -8,26 +8,23 @@ stages:
- deploy
.serverless:build:image:
- stage: build
image: registry.gitlab.com/gitlab-org/gitlabktl:latest
+ stage: build
script: /usr/bin/gitlabktl app build
.serverless:deploy:image:
+ image: registry.gitlab.com/gitlab-org/gitlabktl:latest
stage: deploy
- image: gcr.io/triggermesh/tm@sha256:3cfdd470a66b741004fb02354319d79f1598c70117ce79978d2e07e192bfb336 # v0.0.11
environment: development
- script:
- - echo "$CI_REGISTRY_IMAGE"
- - tm -n "$KUBE_NAMESPACE" --config "$KUBECONFIG" deploy service "$CI_PROJECT_NAME" --from-image "$CI_REGISTRY_IMAGE" --wait
+ script: /usr/bin/gitlabktl app deploy
.serverless:build:functions:
- stage: build
- environment: development
image: registry.gitlab.com/gitlab-org/gitlabktl:latest
+ stage: build
script: /usr/bin/gitlabktl serverless build
.serverless:deploy:functions:
+ image: registry.gitlab.com/gitlab-org/gitlabktl:latest
stage: deploy
environment: development
- image: registry.gitlab.com/gitlab-org/gitlabktl:latest
script: /usr/bin/gitlabktl serverless deploy
diff --git a/lib/gitlab/ci/trace.rb b/lib/gitlab/ci/trace.rb
index ce5857965bf..9550bc6d39c 100644
--- a/lib/gitlab/ci/trace.rb
+++ b/lib/gitlab/ci/trace.rb
@@ -63,7 +63,15 @@ module Gitlab
end
def exist?
- trace_artifact&.exists? || job.trace_chunks.any? || current_path.present? || old_trace.present?
+ archived_trace_exist? || live_trace_exist?
+ end
+
+ def archived_trace_exist?
+ trace_artifact&.exists?
+ end
+
+ def live_trace_exist?
+ job.trace_chunks.any? || current_path.present? || old_trace.present?
end
def read
@@ -118,7 +126,7 @@ module Gitlab
raise AlreadyArchivedError, 'Could not write to the archived trace'
elsif current_path
File.open(current_path, mode)
- elsif Feature.enabled?('ci_enable_live_trace')
+ elsif Feature.enabled?('ci_enable_live_trace', job.project)
Gitlab::Ci::Trace::ChunkedIO.new(job)
else
File.open(ensure_path, mode)
@@ -167,7 +175,7 @@ module Gitlab
def clone_file!(src_stream, temp_dir)
FileUtils.mkdir_p(temp_dir)
- Dir.mktmpdir('tmp-trace', temp_dir) do |dir_path|
+ Dir.mktmpdir("tmp-trace-#{job.id}", temp_dir) do |dir_path|
temp_path = File.join(dir_path, "job.log")
FileUtils.touch(temp_path)
size = IO.copy_stream(src_stream, temp_path)
diff --git a/lib/gitlab/ci/trace/chunked_io.rb b/lib/gitlab/ci/trace/chunked_io.rb
index 8c6fd56493f..e99889f4a25 100644
--- a/lib/gitlab/ci/trace/chunked_io.rb
+++ b/lib/gitlab/ci/trace/chunked_io.rb
@@ -166,6 +166,13 @@ module Gitlab
end
def destroy!
+ # TODO: Remove this logging once we confirmed new live trace architecture is functional.
+ # See https://gitlab.com/gitlab-com/gl-infra/infrastructure/issues/4667.
+ unless build.has_archived_trace?
+ Sidekiq.logger.warn(message: 'The job does not have archived trace but going to be destroyed.',
+ job_id: build.id)
+ end
+
trace_chunks.fast_destroy_all
@tell = @size = 0
ensure
diff --git a/lib/gitlab/ci/yaml_processor.rb b/lib/gitlab/ci/yaml_processor.rb
index a5693dc4f81..998130e5bd0 100644
--- a/lib/gitlab/ci/yaml_processor.rb
+++ b/lib/gitlab/ci/yaml_processor.rb
@@ -40,6 +40,7 @@ module Gitlab
environment: job[:environment_name],
coverage_regex: job[:coverage],
yaml_variables: yaml_variables(name),
+ needs_attributes: job[:needs]&.map { |need| { name: need } },
options: {
image: job[:image],
services: job[:services],
@@ -108,6 +109,7 @@ module Gitlab
validate_job_stage!(name, job)
validate_job_dependencies!(name, job)
+ validate_job_needs!(name, job)
validate_job_environment!(name, job)
end
end
@@ -144,12 +146,30 @@ module Gitlab
job[:dependencies].each do |dependency|
raise ValidationError, "#{name} job: undefined dependency: #{dependency}" unless @jobs[dependency.to_sym]
- unless @stages.index(@jobs[dependency.to_sym][:stage]) < stage_index
+ dependency_stage_index = @stages.index(@jobs[dependency.to_sym][:stage])
+
+ unless dependency_stage_index.present? && dependency_stage_index < stage_index
raise ValidationError, "#{name} job: dependency #{dependency} is not defined in prior stages"
end
end
end
+ def validate_job_needs!(name, job)
+ return unless job[:needs]
+
+ stage_index = @stages.index(job[:stage])
+
+ job[:needs].each do |need|
+ raise ValidationError, "#{name} job: undefined need: #{need}" unless @jobs[need.to_sym]
+
+ needs_stage_index = @stages.index(@jobs[need.to_sym][:stage])
+
+ unless needs_stage_index.present? && needs_stage_index < stage_index
+ raise ValidationError, "#{name} job: need #{need} is not defined in prior stages"
+ end
+ end
+ end
+
def validate_job_environment!(name, job)
return unless job[:environment]
return unless job[:environment].is_a?(Hash)
diff --git a/lib/gitlab/contributions_calendar.rb b/lib/gitlab/contributions_calendar.rb
index f7d046600e8..5b0b91de5da 100644
--- a/lib/gitlab/contributions_calendar.rb
+++ b/lib/gitlab/contributions_calendar.rb
@@ -84,11 +84,7 @@ module Gitlab
.and(t[:created_at].lteq(Date.current.end_of_day))
.and(t[:author_id].eq(contributor.id))
- date_interval = if Gitlab::Database.postgresql?
- "INTERVAL '#{Time.zone.now.utc_offset} seconds'"
- else
- "INTERVAL #{Time.zone.now.utc_offset} SECOND"
- end
+ date_interval = "INTERVAL '#{Time.zone.now.utc_offset} seconds'"
Event.reorder(nil)
.select(t[:project_id], t[:target_type], t[:action], "date(created_at + #{date_interval}) AS date", 'count(id) as total_amount')
diff --git a/lib/gitlab/cycle_analytics/base_event_fetcher.rb b/lib/gitlab/cycle_analytics/base_event_fetcher.rb
index 0cacef5b278..07ae430c45e 100644
--- a/lib/gitlab/cycle_analytics/base_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/base_event_fetcher.rb
@@ -4,13 +4,13 @@ module Gitlab
module CycleAnalytics
class BaseEventFetcher
include BaseQuery
+ include GroupProjectsProvider
- attr_reader :projections, :query, :stage, :order, :project, :options
+ attr_reader :projections, :query, :stage, :order, :options
MAX_EVENTS = 50
- def initialize(project: nil, stage:, options:)
- @project = project
+ def initialize(stage:, options:)
@stage = stage
@options = options
end
@@ -68,11 +68,11 @@ module Gitlab
end
def allowed_ids_source
- { project_id: project.id }
+ group ? { group_id: group.id, include_subgroups: true } : { project_id: project.id }
end
- def projects
- [project]
+ def serialization_context
+ {}
end
end
end
diff --git a/lib/gitlab/cycle_analytics/base_query.rb b/lib/gitlab/cycle_analytics/base_query.rb
index 39fc1759cfc..9c98c0bfbf2 100644
--- a/lib/gitlab/cycle_analytics/base_query.rb
+++ b/lib/gitlab/cycle_analytics/base_query.rb
@@ -16,17 +16,25 @@ module Gitlab
def stage_query(project_ids)
query = mr_closing_issues_table.join(issue_table).on(issue_table[:id].eq(mr_closing_issues_table[:issue_id]))
.join(issue_metrics_table).on(issue_table[:id].eq(issue_metrics_table[:issue_id]))
+ .join(projects_table).on(issue_table[:project_id].eq(projects_table[:id]))
+ .join(routes_table).on(projects_table[:namespace_id].eq(routes_table[:source_id]))
.project(issue_table[:project_id].as("project_id"))
.where(issue_table[:project_id].in(project_ids))
+ .where(routes_table[:source_type].eq('Namespace'))
.where(issue_table[:created_at].gteq(options[:from]))
# Load merge_requests
- query = query.join(mr_table, Arel::Nodes::OuterJoin)
+
+ query = load_merge_requests(query)
+
+ query
+ end
+
+ def load_merge_requests(query)
+ query.join(mr_table, Arel::Nodes::OuterJoin)
.on(mr_table[:id].eq(mr_closing_issues_table[:merge_request_id]))
.join(mr_metrics_table)
.on(mr_table[:id].eq(mr_metrics_table[:merge_request_id]))
-
- query
end
end
end
diff --git a/lib/gitlab/cycle_analytics/base_stage.rb b/lib/gitlab/cycle_analytics/base_stage.rb
index 98b86e54340..1cd54238bb4 100644
--- a/lib/gitlab/cycle_analytics/base_stage.rb
+++ b/lib/gitlab/cycle_analytics/base_stage.rb
@@ -4,11 +4,11 @@ module Gitlab
module CycleAnalytics
class BaseStage
include BaseQuery
+ include GroupProjectsProvider
- attr_reader :project, :options
+ attr_reader :options
- def initialize(project: nil, options:)
- @project = project
+ def initialize(options:)
@options = options
end
@@ -24,7 +24,7 @@ module Gitlab
raise NotImplementedError.new("Expected #{self.name} to implement title")
end
- def median
+ def project_median
return if project.nil?
BatchLoader.for(project.id).batch(key: name) do |project_ids, loader|
@@ -42,6 +42,10 @@ module Gitlab
end
end
+ def group_median
+ median_query(projects.map(&:id))
+ end
+
def median_query(project_ids)
# Build a `SELECT` query. We find the first of the `end_time_attrs` that isn't `NULL` (call this end_time).
# Next, we find the first of the start_time_attrs that isn't `NULL` (call this start_time).
@@ -67,18 +71,13 @@ module Gitlab
private
def event_fetcher
- @event_fetcher ||= Gitlab::CycleAnalytics::EventFetcher[name].new(project: project,
- stage: name,
+ @event_fetcher ||= Gitlab::CycleAnalytics::EventFetcher[name].new(stage: name,
options: event_options)
end
def event_options
options.merge(start_time_attrs: start_time_attrs, end_time_attrs: end_time_attrs)
end
-
- def projects
- [project]
- end
end
end
end
diff --git a/lib/gitlab/cycle_analytics/code_event_fetcher.rb b/lib/gitlab/cycle_analytics/code_event_fetcher.rb
index 9e7ca529579..1e4e9b9e02c 100644
--- a/lib/gitlab/cycle_analytics/code_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/code_event_fetcher.rb
@@ -11,7 +11,9 @@ module Gitlab
mr_table[:id],
mr_table[:created_at],
mr_table[:state],
- mr_table[:author_id]]
+ mr_table[:author_id],
+ projects_table[:name],
+ routes_table[:path]]
@order = mr_table[:created_at]
super(*args)
@@ -20,7 +22,7 @@ module Gitlab
private
def serialize(event)
- AnalyticsMergeRequestSerializer.new(project: project).represent(event)
+ AnalyticsMergeRequestSerializer.new(serialization_context).represent(event)
end
def allowed_ids_finder_class
diff --git a/lib/gitlab/cycle_analytics/group_projects_provider.rb b/lib/gitlab/cycle_analytics/group_projects_provider.rb
new file mode 100644
index 00000000000..1287a48daaa
--- /dev/null
+++ b/lib/gitlab/cycle_analytics/group_projects_provider.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module CycleAnalytics
+ module GroupProjectsProvider
+ def projects
+ group ? projects_for_group : [project]
+ end
+
+ def group
+ @group ||= options.fetch(:group, nil)
+ end
+
+ def project
+ @project ||= options.fetch(:project, nil)
+ end
+
+ private
+
+ def projects_for_group
+ projects = Project.inside_path(group.full_path)
+ projects = projects.where(id: options[:projects]) if options[:projects]
+ projects
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/cycle_analytics/group_stage_summary.rb b/lib/gitlab/cycle_analytics/group_stage_summary.rb
new file mode 100644
index 00000000000..a1fc941495d
--- /dev/null
+++ b/lib/gitlab/cycle_analytics/group_stage_summary.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module CycleAnalytics
+ class GroupStageSummary
+ attr_reader :group, :from, :current_user, :options
+
+ def initialize(group, options:)
+ @group = group
+ @from = options[:from]
+ @current_user = options[:current_user]
+ @options = options
+ end
+
+ def data
+ [serialize(Summary::Group::Issue.new(group: group, from: from, current_user: current_user, options: options)),
+ serialize(Summary::Group::Deploy.new(group: group, from: from, options: options))]
+ end
+
+ private
+
+ def serialize(summary_object)
+ AnalyticsSummarySerializer.new.represent(summary_object)
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/cycle_analytics/issue_event_fetcher.rb b/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
index bb3520ae920..2d03e425a6a 100644
--- a/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/issue_event_fetcher.rb
@@ -10,7 +10,9 @@ module Gitlab
issue_table[:iid],
issue_table[:id],
issue_table[:created_at],
- issue_table[:author_id]]
+ issue_table[:author_id],
+ projects_table[:name],
+ routes_table[:path]]
super(*args)
end
@@ -18,7 +20,7 @@ module Gitlab
private
def serialize(event)
- AnalyticsIssueSerializer.new(project: project).represent(event)
+ AnalyticsIssueSerializer.new(serialization_context).represent(event)
end
def allowed_ids_finder_class
diff --git a/lib/gitlab/cycle_analytics/issue_helper.rb b/lib/gitlab/cycle_analytics/issue_helper.rb
index ac836b8bf0f..0fc4f1dd41a 100644
--- a/lib/gitlab/cycle_analytics/issue_helper.rb
+++ b/lib/gitlab/cycle_analytics/issue_helper.rb
@@ -5,8 +5,11 @@ module Gitlab
module IssueHelper
def stage_query(project_ids)
query = issue_table.join(issue_metrics_table).on(issue_table[:id].eq(issue_metrics_table[:issue_id]))
+ .join(projects_table).on(issue_table[:project_id].eq(projects_table[:id]))
+ .join(routes_table).on(projects_table[:namespace_id].eq(routes_table[:source_id]))
.project(issue_table[:project_id].as("project_id"))
.where(issue_table[:project_id].in(project_ids))
+ .where(routes_table[:source_type].eq('Namespace'))
.where(issue_table[:created_at].gteq(options[:from]))
.where(issue_metrics_table[:first_added_to_board_at].not_eq(nil).or(issue_metrics_table[:first_associated_with_milestone_at].not_eq(nil)))
diff --git a/lib/gitlab/cycle_analytics/metrics_tables.rb b/lib/gitlab/cycle_analytics/metrics_tables.rb
index 3e0302d308d..015f7bfde24 100644
--- a/lib/gitlab/cycle_analytics/metrics_tables.rb
+++ b/lib/gitlab/cycle_analytics/metrics_tables.rb
@@ -35,6 +35,14 @@ module Gitlab
User.arel_table
end
+ def projects_table
+ Project.arel_table
+ end
+
+ def routes_table
+ Route.arel_table
+ end
+
def build_table
::CommitStatus.arel_table
end
diff --git a/lib/gitlab/cycle_analytics/permissions.rb b/lib/gitlab/cycle_analytics/permissions.rb
index 03ba98b4dfb..55214e6b896 100644
--- a/lib/gitlab/cycle_analytics/permissions.rb
+++ b/lib/gitlab/cycle_analytics/permissions.rb
@@ -23,7 +23,7 @@ module Gitlab
end
def get
- ::CycleAnalytics::Base::STAGES.each do |stage|
+ ::CycleAnalytics::LevelBase::STAGES.each do |stage|
@stage_permission_hash[stage] = authorized_stage?(stage)
end
diff --git a/lib/gitlab/cycle_analytics/plan_event_fetcher.rb b/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
index 49a6b099f34..77cc358daa9 100644
--- a/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/plan_event_fetcher.rb
@@ -10,7 +10,9 @@ module Gitlab
issue_table[:iid],
issue_table[:id],
issue_table[:created_at],
- issue_table[:author_id]]
+ issue_table[:author_id],
+ projects_table[:name],
+ routes_table[:path]]
super(*args)
end
@@ -18,7 +20,7 @@ module Gitlab
private
def serialize(event)
- AnalyticsIssueSerializer.new(project: project).represent(event)
+ AnalyticsIssueSerializer.new(serialization_context).represent(event)
end
def allowed_ids_finder_class
diff --git a/lib/gitlab/cycle_analytics/plan_helper.rb b/lib/gitlab/cycle_analytics/plan_helper.rb
index ae578d45ad5..c3f742503a9 100644
--- a/lib/gitlab/cycle_analytics/plan_helper.rb
+++ b/lib/gitlab/cycle_analytics/plan_helper.rb
@@ -5,14 +5,21 @@ module Gitlab
module PlanHelper
def stage_query(project_ids)
query = issue_table.join(issue_metrics_table).on(issue_table[:id].eq(issue_metrics_table[:issue_id]))
+ .join(projects_table).on(issue_table[:project_id].eq(projects_table[:id]))
+ .join(routes_table).on(projects_table[:namespace_id].eq(routes_table[:source_id]))
.project(issue_table[:project_id].as("project_id"))
.where(issue_table[:project_id].in(project_ids))
- .where(issue_table[:created_at].gteq(options[:from]))
- .where(issue_metrics_table[:first_added_to_board_at].not_eq(nil).or(issue_metrics_table[:first_associated_with_milestone_at].not_eq(nil)))
- .where(issue_metrics_table[:first_mentioned_in_commit_at].not_eq(nil))
+ .where(routes_table[:source_type].eq('Namespace'))
+ query = add_conditions_to_query(query)
query
end
+
+ def add_conditions_to_query(query)
+ query.where(issue_table[:created_at].gteq(options[:from]))
+ .where(issue_metrics_table[:first_added_to_board_at].not_eq(nil).or(issue_metrics_table[:first_associated_with_milestone_at].not_eq(nil)))
+ .where(issue_metrics_table[:first_mentioned_in_commit_at].not_eq(nil))
+ end
end
end
end
diff --git a/lib/gitlab/cycle_analytics/production_event_fetcher.rb b/lib/gitlab/cycle_analytics/production_event_fetcher.rb
index 949119d69a0..404b2460814 100644
--- a/lib/gitlab/cycle_analytics/production_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/production_event_fetcher.rb
@@ -10,7 +10,9 @@ module Gitlab
issue_table[:iid],
issue_table[:id],
issue_table[:created_at],
- issue_table[:author_id]]
+ issue_table[:author_id],
+ projects_table[:name],
+ routes_table[:path]]
super(*args)
end
@@ -18,7 +20,7 @@ module Gitlab
private
def serialize(event)
- AnalyticsIssueSerializer.new(project: project).represent(event)
+ AnalyticsIssueSerializer.new(serialization_context).represent(event)
end
def allowed_ids_finder_class
diff --git a/lib/gitlab/cycle_analytics/review_event_fetcher.rb b/lib/gitlab/cycle_analytics/review_event_fetcher.rb
index d31736e755d..6acd12517fa 100644
--- a/lib/gitlab/cycle_analytics/review_event_fetcher.rb
+++ b/lib/gitlab/cycle_analytics/review_event_fetcher.rb
@@ -11,7 +11,9 @@ module Gitlab
mr_table[:id],
mr_table[:created_at],
mr_table[:state],
- mr_table[:author_id]]
+ mr_table[:author_id],
+ projects_table[:name],
+ routes_table[:path]]
super(*args)
end
@@ -19,7 +21,7 @@ module Gitlab
private
def serialize(event)
- AnalyticsMergeRequestSerializer.new(project: project).represent(event)
+ AnalyticsMergeRequestSerializer.new(serialization_context).represent(event)
end
def allowed_ids_finder_class
diff --git a/lib/gitlab/cycle_analytics/summary/group/base.rb b/lib/gitlab/cycle_analytics/summary/group/base.rb
new file mode 100644
index 00000000000..48d8164bde1
--- /dev/null
+++ b/lib/gitlab/cycle_analytics/summary/group/base.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module CycleAnalytics
+ module Summary
+ module Group
+ class Base
+ attr_reader :group, :from, :options
+
+ def initialize(group:, from:, options:)
+ @group = group
+ @from = from
+ @options = options
+ end
+
+ def title
+ raise NotImplementedError.new("Expected #{self.name} to implement title")
+ end
+
+ def value
+ raise NotImplementedError.new("Expected #{self.name} to implement value")
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/cycle_analytics/summary/group/deploy.rb b/lib/gitlab/cycle_analytics/summary/group/deploy.rb
new file mode 100644
index 00000000000..78d677cf558
--- /dev/null
+++ b/lib/gitlab/cycle_analytics/summary/group/deploy.rb
@@ -0,0 +1,30 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module CycleAnalytics
+ module Summary
+ module Group
+ class Deploy < Group::Base
+ include GroupProjectsProvider
+
+ def title
+ n_('Deploy', 'Deploys', value)
+ end
+
+ def value
+ @value ||= find_deployments
+ end
+
+ private
+
+ def find_deployments
+ deployments = Deployment.joins(:project).merge(Project.inside_path(group.full_path))
+ deployments = deployments.where(projects: { id: options[:projects] }) if options[:projects]
+ deployments = deployments.where("deployments.created_at > ?", from)
+ deployments.success.count
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/cycle_analytics/summary/group/issue.rb b/lib/gitlab/cycle_analytics/summary/group/issue.rb
new file mode 100644
index 00000000000..9daae8531d8
--- /dev/null
+++ b/lib/gitlab/cycle_analytics/summary/group/issue.rb
@@ -0,0 +1,36 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module CycleAnalytics
+ module Summary
+ module Group
+ class Issue < Group::Base
+ attr_reader :group, :from, :current_user, :options
+
+ def initialize(group:, from:, current_user:, options:)
+ @group = group
+ @from = from
+ @current_user = current_user
+ @options = options
+ end
+
+ def title
+ n_('New Issue', 'New Issues', value)
+ end
+
+ def value
+ @value ||= find_issues
+ end
+
+ private
+
+ def find_issues
+ issues = IssuesFinder.new(current_user, group_id: group.id, include_subgroups: true, created_after: from).execute
+ issues = issues.where(projects: { id: options[:projects] }) if options[:projects]
+ issues.count
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/danger/helper.rb b/lib/gitlab/danger/helper.rb
index 0fc145534bf..c0a12318990 100644
--- a/lib/gitlab/danger/helper.rb
+++ b/lib/gitlab/danger/helper.rb
@@ -46,6 +46,16 @@ module Gitlab
ee? ? 'gitlab-ee' : 'gitlab-ce'
end
+ def markdown_list(items)
+ list = items.map { |item| "* `#{item}`" }.join("\n")
+
+ if items.size > 10
+ "\n<details>\n\n#{list}\n\n</details>\n"
+ else
+ list
+ end
+ end
+
# @return [Hash<String,Array<String>>]
def changes_by_category
all_changed_files.each_with_object(Hash.new { |h, k| h[k] = [] }) do |file, hash|
@@ -132,6 +142,22 @@ module Gitlab
def new_teammates(usernames)
usernames.map { |u| Gitlab::Danger::Teammate.new('username' => u) }
end
+
+ def missing_database_labels(current_mr_labels)
+ labels = if has_database_scoped_labels?(current_mr_labels)
+ ['database']
+ else
+ ['database', 'database::review pending']
+ end
+
+ labels - current_mr_labels
+ end
+
+ private
+
+ def has_database_scoped_labels?(current_mr_labels)
+ current_mr_labels.any? { |label| label.start_with?('database::') }
+ end
end
end
end
diff --git a/lib/gitlab/danger/teammate.rb b/lib/gitlab/danger/teammate.rb
index b44f134f2c1..74cbcc11255 100644
--- a/lib/gitlab/danger/teammate.rb
+++ b/lib/gitlab/danger/teammate.rb
@@ -39,7 +39,7 @@ module Gitlab
def has_capability?(project, category, kind, labels)
case category
when :test
- area = role[/Test Automation Engineer, (\w+)/, 1]
+ area = role[/Test Automation Engineer(?:.*?, (\w+))/, 1]
area && labels.any?(area) if kind == :reviewer
else
diff --git a/lib/gitlab/database.rb b/lib/gitlab/database.rb
index 3e4c720b49a..cbdff0ab060 100644
--- a/lib/gitlab/database.rb
+++ b/lib/gitlab/database.rb
@@ -4,13 +4,13 @@ module Gitlab
module Database
include Gitlab::Metrics::Methods
- # The max value of INTEGER type is the same between MySQL and PostgreSQL:
# https://www.postgresql.org/docs/9.2/static/datatype-numeric.html
- # http://dev.mysql.com/doc/refman/5.7/en/integer-types.html
MAX_INT_VALUE = 2147483647
+
# The max value between MySQL's TIMESTAMP and PostgreSQL's timestampz:
# https://www.postgresql.org/docs/9.1/static/datatype-datetime.html
# https://dev.mysql.com/doc/refman/5.7/en/datetime.html
+ # FIXME: this should just be the max value of timestampz
MAX_TIMESTAMP_VALUE = Time.at((1 << 31) - 1).freeze
# Minimum schema version from which migrations are supported
@@ -39,13 +39,14 @@ module Gitlab
end
def self.human_adapter_name
- postgresql? ? 'PostgreSQL' : 'MySQL'
- end
-
- def self.mysql?
- adapter_name.casecmp('mysql2').zero?
+ if postgresql?
+ 'PostgreSQL'
+ else
+ 'Unknown'
+ end
end
+ # @deprecated
def self.postgresql?
adapter_name.casecmp('postgresql').zero?
end
@@ -60,15 +61,14 @@ module Gitlab
# Check whether the underlying database is in read-only mode
def self.db_read_only?
- if postgresql?
- pg_is_in_recovery =
- ActiveRecord::Base.connection.execute('SELECT pg_is_in_recovery()')
- .first.fetch('pg_is_in_recovery')
+ pg_is_in_recovery =
+ ActiveRecord::Base
+ .connection
+ .execute('SELECT pg_is_in_recovery()')
+ .first
+ .fetch('pg_is_in_recovery')
- Gitlab::Utils.to_boolean(pg_is_in_recovery)
- else
- false
- end
+ Gitlab::Utils.to_boolean(pg_is_in_recovery)
end
def self.db_read_write?
@@ -80,19 +80,19 @@ module Gitlab
end
def self.postgresql_9_or_less?
- postgresql? && version.to_f < 10
+ version.to_f < 10
end
def self.join_lateral_supported?
- postgresql? && version.to_f >= 9.3
+ version.to_f >= 9.3
end
def self.replication_slots_supported?
- postgresql? && version.to_f >= 9.4
+ version.to_f >= 9.4
end
def self.postgresql_minimum_supported_version?
- postgresql? && version.to_f >= 9.6
+ version.to_f >= 9.6
end
# map some of the function names that changed between PostgreSQL 9 and 10
@@ -118,51 +118,23 @@ module Gitlab
end
def self.nulls_last_order(field, direction = 'ASC')
- order = "#{field} #{direction}"
-
- if postgresql?
- order = "#{order} NULLS LAST"
- else
- # `field IS NULL` will be `0` for non-NULL columns and `1` for NULL
- # columns. In the (default) ascending order, `0` comes first.
- order = "#{field} IS NULL, #{order}" if direction == 'ASC'
- end
-
- Arel.sql(order)
+ Arel.sql("#{field} #{direction} NULLS LAST")
end
def self.nulls_first_order(field, direction = 'ASC')
- order = "#{field} #{direction}"
-
- if postgresql?
- order = "#{order} NULLS FIRST"
- else
- # `field IS NULL` will be `0` for non-NULL columns and `1` for NULL
- # columns. In the (default) ascending order, `0` comes first.
- order = "#{field} IS NULL, #{order}" if direction == 'DESC'
- end
-
- Arel.sql(order)
+ Arel.sql("#{field} #{direction} NULLS FIRST")
end
def self.random
- postgresql? ? "RANDOM()" : "RAND()"
+ "RANDOM()"
end
def self.true_value
- if postgresql?
- "'t'"
- else
- 1
- end
+ "'t'"
end
def self.false_value
- if postgresql?
- "'f'"
- else
- 0
- end
+ "'f'"
end
def self.with_connection_pool(pool_size)
@@ -182,7 +154,7 @@ module Gitlab
# rows - An Array of Hash instances, each mapping the columns to their
# values.
# return_ids - When set to true the return value will be an Array of IDs of
- # the inserted rows, this only works on PostgreSQL.
+ # the inserted rows
# disable_quote - A key or an Array of keys to exclude from quoting (You
# become responsible for protection from SQL injection for
# these keys!)
@@ -191,7 +163,6 @@ module Gitlab
keys = rows.first.keys
columns = keys.map { |key| connection.quote_column_name(key) }
- return_ids = false if mysql?
disable_quote = Array(disable_quote).to_set
tuples = rows.map do |row|
@@ -258,11 +229,7 @@ module Gitlab
def self.database_version
row = connection.execute("SELECT VERSION()").first
- if postgresql?
- row['version']
- else
- row.first
- end
+ row['version']
end
private_class_method :database_version
diff --git a/lib/gitlab/database/count.rb b/lib/gitlab/database/count.rb
index f3d37ccd72a..eac61254bdf 100644
--- a/lib/gitlab/database/count.rb
+++ b/lib/gitlab/database/count.rb
@@ -37,16 +37,14 @@ module Gitlab
# @return [Hash] of Model -> count mapping
def self.approximate_counts(models, strategies: [TablesampleCountStrategy, ReltuplesCountStrategy, ExactCountStrategy])
strategies.each_with_object({}) do |strategy, counts_by_model|
- if strategy.enabled?
- models_with_missing_counts = models - counts_by_model.keys
+ models_with_missing_counts = models - counts_by_model.keys
- break counts_by_model if models_with_missing_counts.empty?
+ break counts_by_model if models_with_missing_counts.empty?
- counts = strategy.new(models_with_missing_counts).count
+ counts = strategy.new(models_with_missing_counts).count
- counts.each do |model, count|
- counts_by_model[model] = count
- end
+ counts.each do |model, count|
+ counts_by_model[model] = count
end
end
end
diff --git a/lib/gitlab/database/count/exact_count_strategy.rb b/lib/gitlab/database/count/exact_count_strategy.rb
index fa6951eda22..0b8fe640bf8 100644
--- a/lib/gitlab/database/count/exact_count_strategy.rb
+++ b/lib/gitlab/database/count/exact_count_strategy.rb
@@ -23,10 +23,6 @@ module Gitlab
rescue *CONNECTION_ERRORS
{}
end
-
- def self.enabled?
- true
- end
end
end
end
diff --git a/lib/gitlab/database/count/reltuples_count_strategy.rb b/lib/gitlab/database/count/reltuples_count_strategy.rb
index 695f6fa766e..6cd90c01ab2 100644
--- a/lib/gitlab/database/count/reltuples_count_strategy.rb
+++ b/lib/gitlab/database/count/reltuples_count_strategy.rb
@@ -31,10 +31,6 @@ module Gitlab
{}
end
- def self.enabled?
- Gitlab::Database.postgresql?
- end
-
private
# Models using single-type inheritance (STI) don't work with
diff --git a/lib/gitlab/database/count/tablesample_count_strategy.rb b/lib/gitlab/database/count/tablesample_count_strategy.rb
index 7777f31f702..e9387a91a14 100644
--- a/lib/gitlab/database/count/tablesample_count_strategy.rb
+++ b/lib/gitlab/database/count/tablesample_count_strategy.rb
@@ -28,10 +28,6 @@ module Gitlab
{}
end
- def self.enabled?
- Gitlab::Database.postgresql? && Feature.enabled?(:tablesample_counts)
- end
-
private
def perform_count(model, estimate)
diff --git a/lib/gitlab/database/date_time.rb b/lib/gitlab/database/date_time.rb
index 79d2caff151..1392b397012 100644
--- a/lib/gitlab/database/date_time.rb
+++ b/lib/gitlab/database/date_time.rb
@@ -7,8 +7,7 @@ module Gitlab
# the first of the `start_time_attrs` that isn't NULL. `SELECT` the resulting interval
# along with an alias specified by the `as` parameter.
#
- # Note: For MySQL, the interval is returned in seconds.
- # For PostgreSQL, the interval is returned as an INTERVAL type.
+ # Note: the interval is returned as an INTERVAL type.
def subtract_datetimes(query_so_far, start_time_attrs, end_time_attrs, as)
diff_fn = subtract_datetimes_diff(query_so_far, start_time_attrs, end_time_attrs)
@@ -16,17 +15,10 @@ module Gitlab
end
def subtract_datetimes_diff(query_so_far, start_time_attrs, end_time_attrs)
- if Gitlab::Database.postgresql?
- Arel::Nodes::Subtraction.new(
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs)),
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)))
- elsif Gitlab::Database.mysql?
- Arel::Nodes::NamedFunction.new(
- "TIMESTAMPDIFF",
- [Arel.sql('second'),
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs)),
- Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs))])
- end
+ Arel::Nodes::Subtraction.new(
+ Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(end_time_attrs)),
+ Arel::Nodes::NamedFunction.new("COALESCE", Array.wrap(start_time_attrs))
+ )
end
end
end
diff --git a/lib/gitlab/database/grant.rb b/lib/gitlab/database/grant.rb
index 26adf4e221b..1f47f320a29 100644
--- a/lib/gitlab/database/grant.rb
+++ b/lib/gitlab/database/grant.rb
@@ -6,47 +6,25 @@ module Gitlab
class Grant < ActiveRecord::Base
include FromUnion
- self.table_name =
- if Database.postgresql?
- 'information_schema.role_table_grants'
- else
- 'information_schema.schema_privileges'
- end
+ self.table_name = 'information_schema.role_table_grants'
# Returns true if the current user can create and execute triggers on the
# given table.
def self.create_and_execute_trigger?(table)
- if Database.postgresql?
- # We _must not_ use quote_table_name as this will produce double
- # quotes on PostgreSQL and for "has_table_privilege" we need single
- # quotes.
- quoted_table = connection.quote(table)
-
- begin
- from(nil)
- .pluck(Arel.sql("has_table_privilege(#{quoted_table}, 'TRIGGER')"))
- .first
- rescue ActiveRecord::StatementInvalid
- # This error is raised when using a non-existing table name. In this
- # case we just want to return false as a user technically can't
- # create triggers for such a table.
- false
- end
- else
- queries = [
- Grant.select(1)
- .from('information_schema.user_privileges')
- .where("PRIVILEGE_TYPE = 'SUPER'")
- .where("GRANTEE = CONCAT('\\'', REPLACE(CURRENT_USER(), '@', '\\'@\\''), '\\'')"),
-
- Grant.select(1)
- .from('information_schema.schema_privileges')
- .where("PRIVILEGE_TYPE = 'TRIGGER'")
- .where('TABLE_SCHEMA = ?', Gitlab::Database.database_name)
- .where("GRANTEE = CONCAT('\\'', REPLACE(CURRENT_USER(), '@', '\\'@\\''), '\\'')")
- ]
+ # We _must not_ use quote_table_name as this will produce double
+ # quotes on PostgreSQL and for "has_table_privilege" we need single
+ # quotes.
+ quoted_table = connection.quote(table)
- Grant.from_union(queries, alias_as: 'privs').any?
+ begin
+ from(nil)
+ .pluck(Arel.sql("has_table_privilege(#{quoted_table}, 'TRIGGER')"))
+ .first
+ rescue ActiveRecord::StatementInvalid
+ # This error is raised when using a non-existing table name. In this
+ # case we just want to return false as a user technically can't
+ # create triggers for such a table.
+ false
end
end
end
diff --git a/lib/gitlab/database/median.rb b/lib/gitlab/database/median.rb
index b8d895dee7d..603b125d8b4 100644
--- a/lib/gitlab/database/median.rb
+++ b/lib/gitlab/database/median.rb
@@ -17,13 +17,9 @@ module Gitlab
def extract_median(results)
result = results.compact.first
- if Gitlab::Database.postgresql?
- result = result.first.presence
+ result = result.first.presence
- result['median']&.to_f if result
- elsif Gitlab::Database.mysql?
- result.to_a.flatten.first
- end
+ result['median']&.to_f if result
end
def extract_medians(results)
@@ -34,31 +30,6 @@ module Gitlab
end
end
- def mysql_median_datetime_sql(arel_table, query_so_far, column_sym)
- query = arel_table.from
- .from(arel_table.project(Arel.sql('*')).order(arel_table[column_sym]).as(arel_table.table_name))
- .project(average([arel_table[column_sym]], 'median'))
- .where(
- Arel::Nodes::Between.new(
- Arel.sql("(select @row_id := @row_id + 1)"),
- Arel::Nodes::And.new(
- [Arel.sql('@ct/2.0'),
- Arel.sql('@ct/2.0 + 1')]
- )
- )
- ).
- # Disallow negative values
- where(arel_table[column_sym].gteq(0))
-
- [
- Arel.sql("CREATE TEMPORARY TABLE IF NOT EXISTS #{query_so_far.to_sql}"),
- Arel.sql("set @ct := (select count(1) from #{arel_table.table_name});"),
- Arel.sql("set @row_id := 0;"),
- query.to_sql,
- Arel.sql("DROP TEMPORARY TABLE IF EXISTS #{arel_table.table_name};")
- ]
- end
-
def pg_median_datetime_sql(arel_table, query_so_far, column_sym, partition_column = nil)
# Create a CTE with the column we're operating on, row number (after sorting by the column
# we're operating on), and count of the table we're operating on (duplicated across) all rows
@@ -113,18 +84,8 @@ module Gitlab
private
- def median_queries(arel_table, query_so_far, column_sym, partition_column = nil)
- if Gitlab::Database.postgresql?
- pg_median_datetime_sql(arel_table, query_so_far, column_sym, partition_column)
- elsif Gitlab::Database.mysql?
- raise NotSupportedError, "partition_column is not supported for MySQL" if partition_column
-
- mysql_median_datetime_sql(arel_table, query_so_far, column_sym)
- end
- end
-
def execute_queries(arel_table, query_so_far, column_sym, partition_column = nil)
- queries = median_queries(arel_table, query_so_far, column_sym, partition_column)
+ queries = pg_median_datetime_sql(arel_table, query_so_far, column_sym, partition_column)
Array.wrap(queries).map { |query| ActiveRecord::Base.connection.execute(query) }
end
@@ -176,8 +137,6 @@ module Gitlab
end
def extract_diff_epoch(diff)
- return diff unless Gitlab::Database.postgresql?
-
Arel.sql(%Q{EXTRACT(EPOCH FROM (#{diff.to_sql}))})
end
diff --git a/lib/gitlab/database/migration_helpers.rb b/lib/gitlab/database/migration_helpers.rb
index 0c5f33e1b2a..9bba4f6ce1e 100644
--- a/lib/gitlab/database/migration_helpers.rb
+++ b/lib/gitlab/database/migration_helpers.rb
@@ -6,31 +6,45 @@ module Gitlab
BACKGROUND_MIGRATION_BATCH_SIZE = 1000 # Number of rows to process per job
BACKGROUND_MIGRATION_JOB_BUFFER_SIZE = 1000 # Number of jobs to bulk queue at a time
+ PERMITTED_TIMESTAMP_COLUMNS = %i[created_at updated_at deleted_at].to_set.freeze
+ DEFAULT_TIMESTAMP_COLUMNS = %i[created_at updated_at].freeze
+
# Adds `created_at` and `updated_at` columns with timezone information.
#
# This method is an improved version of Rails' built-in method `add_timestamps`.
#
+ # By default, adds `created_at` and `updated_at` columns, but these can be specified as:
+ #
+ # add_timestamps_with_timezone(:my_table, columns: [:created_at, :deleted_at])
+ #
+ # This allows you to create just the timestamps you need, saving space.
+ #
# Available options are:
- # default - The default value for the column.
- # null - When set to `true` the column will allow NULL values.
+ # :default - The default value for the column.
+ # :null - When set to `true` the column will allow NULL values.
# The default is to not allow NULL values.
+ # :columns - the column names to create. Must be one
+ # of `Gitlab::Database::MigrationHelpers::PERMITTED_TIMESTAMP_COLUMNS`.
+ # Default value: `DEFAULT_TIMESTAMP_COLUMNS`
+ #
+ # All options are optional.
def add_timestamps_with_timezone(table_name, options = {})
options[:null] = false if options[:null].nil?
+ columns = options.fetch(:columns, DEFAULT_TIMESTAMP_COLUMNS)
+ default_value = options[:default]
- [:created_at, :updated_at].each do |column_name|
- if options[:default] && transaction_open?
- raise '`add_timestamps_with_timezone` with default value cannot be run inside a transaction. ' \
- 'You can disable transactions by calling `disable_ddl_transaction!` ' \
- 'in the body of your migration class'
- end
+ validate_not_in_transaction!(:add_timestamps_with_timezone, 'with default value') if default_value
+
+ columns.each do |column_name|
+ validate_timestamp_column_name!(column_name)
# If default value is presented, use `add_column_with_default` method instead.
- if options[:default]
+ if default_value
add_column_with_default(
table_name,
column_name,
:datetime_with_timezone,
- default: options[:default],
+ default: default_value,
allow_null: options[:null]
)
else
@@ -39,10 +53,22 @@ module Gitlab
end
end
- # Creates a new index, concurrently when supported
+ # To be used in the `#down` method of migrations that
+ # use `#add_timestamps_with_timezone`.
#
- # On PostgreSQL this method creates an index concurrently, on MySQL this
- # creates a regular index.
+ # Available options are:
+ # :columns - the column names to remove. Must be one
+ # Default value: `DEFAULT_TIMESTAMP_COLUMNS`
+ #
+ # All options are optional.
+ def remove_timestamps(table_name, options = {})
+ columns = options.fetch(:columns, DEFAULT_TIMESTAMP_COLUMNS)
+ columns.each do |column_name|
+ remove_column(table_name, column_name)
+ end
+ end
+
+ # Creates a new index, concurrently
#
# Example:
#
@@ -56,9 +82,7 @@ module Gitlab
'in the body of your migration class'
end
- if Database.postgresql?
- options = options.merge({ algorithm: :concurrently })
- end
+ options = options.merge({ algorithm: :concurrently })
if index_exists?(table_name, column_name, options)
Rails.logger.warn "Index not created because it already exists (this may be due to an aborted migration or similar): table_name: #{table_name}, column_name: #{column_name}" # rubocop:disable Gitlab/RailsLogger
@@ -70,9 +94,7 @@ module Gitlab
end
end
- # Removes an existed index, concurrently when supported
- #
- # On PostgreSQL this method removes an index concurrently.
+ # Removes an existed index, concurrently
#
# Example:
#
@@ -100,9 +122,7 @@ module Gitlab
end
end
- # Removes an existing index, concurrently when supported
- #
- # On PostgreSQL this method removes an index concurrently.
+ # Removes an existing index, concurrently
#
# Example:
#
@@ -132,8 +152,6 @@ module Gitlab
# Only available on Postgresql >= 9.2
def supports_drop_index_concurrently?
- return false unless Database.postgresql?
-
version = select_one("SELECT current_setting('server_version_num') AS v")['v'].to_i
version >= 90200
@@ -141,8 +159,7 @@ module Gitlab
# Adds a foreign key with only minimal locking on the tables involved.
#
- # This method only requires minimal locking when using PostgreSQL. When
- # using MySQL this method will use Rails' default `add_foreign_key`.
+ # This method only requires minimal locking
#
# source - The source table containing the foreign key.
# target - The target table the key points to.
@@ -158,27 +175,7 @@ module Gitlab
raise 'add_concurrent_foreign_key can not be run inside a transaction'
end
- # While MySQL does allow disabling of foreign keys it has no equivalent
- # of PostgreSQL's "VALIDATE CONSTRAINT". As a result we'll just fall
- # back to the normal foreign key procedure.
- if Database.mysql?
- if foreign_key_exists?(source, target, column: column)
- Rails.logger.warn "Foreign key not created because it exists already " \
- "(this may be due to an aborted migration or similar): " \
- "source: #{source}, target: #{target}, column: #{column}"
- return
- end
-
- key_options = { column: column, on_delete: on_delete }
-
- # The MySQL adapter tries to create a foreign key without a name when
- # `:name` is nil, instead of generating a name for us.
- key_options[:name] = name if name
-
- return add_foreign_key(source, target, key_options)
- else
- on_delete = 'SET NULL' if on_delete == :nullify
- end
+ on_delete = 'SET NULL' if on_delete == :nullify
key_name = name || concurrent_foreign_key_name(source, column)
@@ -236,7 +233,7 @@ module Gitlab
# Long-running migrations may take more than the timeout allowed by
# the database. Disable the session's statement timeout to ensure
- # migrations don't get killed prematurely. (PostgreSQL only)
+ # migrations don't get killed prematurely.
#
# There are two possible ways to disable the statement timeout:
#
@@ -248,15 +245,6 @@ module Gitlab
# otherwise the statement will still be disabled until connection is dropped
# or `RESET ALL` is executed
def disable_statement_timeout
- # bypass disabled_statement logic when not using postgres, but still execute block when one is given
- unless Database.postgresql?
- if block_given?
- yield
- end
-
- return
- end
-
if block_given?
begin
execute('SET statement_timeout TO 0')
@@ -506,13 +494,12 @@ module Gitlab
quoted_old = quote_column_name(old_column)
quoted_new = quote_column_name(new_column)
- if Database.postgresql?
- install_rename_triggers_for_postgresql(trigger_name, quoted_table,
- quoted_old, quoted_new)
- else
- install_rename_triggers_for_mysql(trigger_name, quoted_table,
- quoted_old, quoted_new)
- end
+ install_rename_triggers_for_postgresql(
+ trigger_name,
+ quoted_table,
+ quoted_old,
+ quoted_new
+ )
end
# Changes the type of a column concurrently.
@@ -555,11 +542,7 @@ module Gitlab
check_trigger_permissions!(table)
- if Database.postgresql?
- remove_rename_triggers_for_postgresql(table, trigger_name)
- else
- remove_rename_triggers_for_mysql(trigger_name)
- end
+ remove_rename_triggers_for_postgresql(table, trigger_name)
remove_column(table, old)
end
@@ -772,38 +755,12 @@ module Gitlab
EOF
end
- # Installs the triggers necessary to perform a concurrent column rename on
- # MySQL.
- def install_rename_triggers_for_mysql(trigger, table, old, new)
- execute <<-EOF.strip_heredoc
- CREATE TRIGGER #{trigger}_insert
- BEFORE INSERT
- ON #{table}
- FOR EACH ROW
- SET NEW.#{new} = NEW.#{old}
- EOF
-
- execute <<-EOF.strip_heredoc
- CREATE TRIGGER #{trigger}_update
- BEFORE UPDATE
- ON #{table}
- FOR EACH ROW
- SET NEW.#{new} = NEW.#{old}
- EOF
- end
-
# Removes the triggers used for renaming a PostgreSQL column concurrently.
def remove_rename_triggers_for_postgresql(table, trigger)
execute("DROP TRIGGER IF EXISTS #{trigger} ON #{table}")
execute("DROP FUNCTION IF EXISTS #{trigger}()")
end
- # Removes the triggers used for renaming a MySQL column concurrently.
- def remove_rename_triggers_for_mysql(trigger)
- execute("DROP TRIGGER IF EXISTS #{trigger}_insert")
- execute("DROP TRIGGER IF EXISTS #{trigger}_update")
- end
-
# Returns the (base) name to use for triggers when renaming columns.
def rename_trigger_name(table, old, new)
'trigger_' + Digest::SHA256.hexdigest("#{table}_#{old}_#{new}").first(12)
@@ -853,8 +810,6 @@ module Gitlab
order: index.orders
}
- # These options are not supported by MySQL, so we only add them if
- # they were previously set.
options[:using] = index.using if index.using
options[:where] = index.where if index.where
@@ -894,26 +849,16 @@ module Gitlab
end
# This will replace the first occurrence of a string in a column with
- # the replacement
- # On postgresql we can use `regexp_replace` for that.
- # On mysql we find the location of the pattern, and overwrite it
- # with the replacement
+ # the replacement using `regexp_replace`
def replace_sql(column, pattern, replacement)
quoted_pattern = Arel::Nodes::Quoted.new(pattern.to_s)
quoted_replacement = Arel::Nodes::Quoted.new(replacement.to_s)
- if Database.mysql?
- locate = Arel::Nodes::NamedFunction
- .new('locate', [quoted_pattern, column])
- insert_in_place = Arel::Nodes::NamedFunction
- .new('insert', [column, locate, pattern.size, quoted_replacement])
+ replace = Arel::Nodes::NamedFunction.new(
+ "regexp_replace", [column, quoted_pattern, quoted_replacement]
+ )
- Arel::Nodes::SqlLiteral.new(insert_in_place.to_sql)
- else
- replace = Arel::Nodes::NamedFunction
- .new("regexp_replace", [column, quoted_pattern, quoted_replacement])
- Arel::Nodes::SqlLiteral.new(replace.to_sql)
- end
+ Arel::Nodes::SqlLiteral.new(replace.to_sql)
end
def remove_foreign_key_if_exists(*args)
@@ -955,11 +900,7 @@ database (#{dbname}) using a super user and running:
ALTER #{user} WITH SUPERUSER
-For MySQL you instead need to run:
-
- GRANT ALL PRIVILEGES ON #{dbname}.* TO #{user}@'%'
-
-Both queries will grant the user super user permissions, ensuring you don't run
+This query will grant the user super user permissions, ensuring you don't run
into similar problems in the future (e.g. when new tables are created).
EOF
end
@@ -1062,10 +1003,6 @@ into similar problems in the future (e.g. when new tables are created).
# This will include indexes using an expression on the column, for example:
# `CREATE INDEX CONCURRENTLY index_name ON table (LOWER(column));`
#
- # For mysql, it falls back to the default ActiveRecord implementation that
- # will not find custom indexes. But it will select by name without passing
- # a column.
- #
# We can remove this when upgrading to Rails 5 with an updated `index_exists?`:
# - https://github.com/rails/rails/commit/edc2b7718725016e988089b5fb6d6fb9d6e16882
#
@@ -1076,10 +1013,8 @@ into similar problems in the future (e.g. when new tables are created).
# does not find indexes without passing a column name.
if indexes(table).map(&:name).include?(index.to_s)
true
- elsif Gitlab::Database.postgresql?
- postgres_exists_by_name?(table, index)
else
- false
+ postgres_exists_by_name?(table, index)
end
end
@@ -1095,8 +1030,26 @@ into similar problems in the future (e.g. when new tables are created).
connection.select_value(index_sql).to_i > 0
end
- def mysql_compatible_index_length
- Gitlab::Database.mysql? ? 20 : nil
+ private
+
+ def validate_timestamp_column_name!(column_name)
+ return if PERMITTED_TIMESTAMP_COLUMNS.member?(column_name)
+
+ raise <<~MESSAGE
+ Illegal timestamp column name! Got #{column_name}.
+ Must be one of: #{PERMITTED_TIMESTAMP_COLUMNS.to_a}
+ MESSAGE
+ end
+
+ def validate_not_in_transaction!(method_name, modifier = nil)
+ return unless transaction_open?
+
+ raise <<~ERROR
+ #{["`#{method_name}`", modifier].compact.join(' ')} cannot be run inside a transaction.
+
+ You can disable transactions by calling `disable_ddl_transaction!` in the body of
+ your migration class
+ ERROR
end
end
end
diff --git a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
index 60afa4bcd52..565f34b78b7 100644
--- a/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
+++ b/lib/gitlab/database/rename_reserved_paths_migration/v1/rename_base.rb
@@ -51,14 +51,10 @@ module Gitlab
quoted_old_full_path = quote_string(old_full_path)
quoted_old_wildcard_path = quote_string("#{old_full_path}/%")
- filter = if Database.mysql?
- "lower(routes.path) = lower('#{quoted_old_full_path}') "\
- "OR routes.path LIKE '#{quoted_old_wildcard_path}'"
- else
- "routes.id IN "\
- "( SELECT routes.id FROM routes WHERE lower(routes.path) = lower('#{quoted_old_full_path}') "\
- "UNION SELECT routes.id FROM routes WHERE routes.path ILIKE '#{quoted_old_wildcard_path}' )"
- end
+ filter =
+ "routes.id IN "\
+ "( SELECT routes.id FROM routes WHERE lower(routes.path) = lower('#{quoted_old_full_path}') "\
+ "UNION SELECT routes.id FROM routes WHERE routes.path ILIKE '#{quoted_old_wildcard_path}' )"
replace_statement = replace_sql(Route.arel_table[:path],
old_full_path,
diff --git a/lib/gitlab/database/sha_attribute.rb b/lib/gitlab/database/sha_attribute.rb
index 109ae7893da..ddbabc9098e 100644
--- a/lib/gitlab/database/sha_attribute.rb
+++ b/lib/gitlab/database/sha_attribute.rb
@@ -2,14 +2,9 @@
module Gitlab
module Database
- BINARY_TYPE =
- if Gitlab::Database.postgresql?
- # PostgreSQL defines its own class with slightly different
- # behaviour from the default Binary type.
- ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea
- else
- ActiveModel::Type::Binary
- end
+ # PostgreSQL defines its own class with slightly different
+ # behaviour from the default Binary type.
+ BINARY_TYPE = ActiveRecord::ConnectionAdapters::PostgreSQL::OID::Bytea
# Class for casting binary data to hexadecimal SHA1 hashes (and vice-versa).
#
diff --git a/lib/gitlab/database/subquery.rb b/lib/gitlab/database/subquery.rb
index 10971d2b274..2a6f39c6a27 100644
--- a/lib/gitlab/database/subquery.rb
+++ b/lib/gitlab/database/subquery.rb
@@ -6,11 +6,7 @@ module Gitlab
class << self
def self_join(relation)
t = relation.arel_table
- # Work around a bug in Rails 5, where LIMIT causes trouble
- # See https://gitlab.com/gitlab-org/gitlab-ce/issues/51729
- r = relation.limit(nil).arel
- r.take(relation.limit_value) if relation.limit_value
- t2 = r.as('t2')
+ t2 = relation.arel.as('t2')
relation.unscoped.joins(t.join(t2).on(t[:id].eq(t2[:id])).join_sources.first)
end
diff --git a/lib/gitlab/ee_compat_check.rb b/lib/gitlab/ee_compat_check.rb
index 01fd261404b..86e532766b1 100644
--- a/lib/gitlab/ee_compat_check.rb
+++ b/lib/gitlab/ee_compat_check.rb
@@ -7,7 +7,7 @@ module Gitlab
CANONICAL_CE_PROJECT_URL = 'https://gitlab.com/gitlab-org/gitlab-ce'.freeze
CANONICAL_EE_REPO_URL = 'https://gitlab.com/gitlab-org/gitlab-ee.git'.freeze
CHECK_DIR = Rails.root.join('ee_compat_check')
- IGNORED_FILES_REGEX = /VERSION|CHANGELOG\.md/i.freeze
+ IGNORED_FILES_REGEX = /VERSION|CHANGELOG\.md|doc\/.+/i.freeze
PLEASE_READ_THIS_BANNER = %Q{
============================================================
===================== PLEASE READ THIS =====================
diff --git a/lib/gitlab/exclusive_lease_helpers.rb b/lib/gitlab/exclusive_lease_helpers.rb
index 7961d4bbd6e..61eb030563d 100644
--- a/lib/gitlab/exclusive_lease_helpers.rb
+++ b/lib/gitlab/exclusive_lease_helpers.rb
@@ -15,17 +15,18 @@ module Gitlab
raise ArgumentError, 'Key needs to be specified' unless key
lease = Gitlab::ExclusiveLease.new(key, timeout: ttl)
+ retried = false
until uuid = lease.try_obtain
# Keep trying until we obtain the lease. To prevent hammering Redis too
# much we'll wait for a bit.
sleep(sleep_sec)
- break if (retries -= 1) < 0
+ (retries -= 1) < 0 ? break : retried ||= true
end
raise FailedToObtainLockError, 'Failed to obtain a lock' unless uuid
- yield
+ yield(retried)
ensure
Gitlab::ExclusiveLease.cancel(key, uuid)
end
diff --git a/lib/gitlab/git.rb b/lib/gitlab/git.rb
index 44a62586a23..df9f33baec2 100644
--- a/lib/gitlab/git.rb
+++ b/lib/gitlab/git.rb
@@ -9,6 +9,7 @@ module Gitlab
# https://github.com/git/git/blob/3ad8b5bf26362ac67c9020bf8c30eee54a84f56d/cache.h#L1011-L1012
EMPTY_TREE_ID = '4b825dc642cb6eb9a060e54bf8d69288fbee4904'.freeze
BLANK_SHA = ('0' * 40).freeze
+ COMMIT_ID = /\A[0-9a-f]{40}\z/.freeze
TAG_REF_PREFIX = "refs/tags/".freeze
BRANCH_REF_PREFIX = "refs/heads/".freeze
@@ -65,6 +66,10 @@ module Gitlab
ref == BLANK_SHA
end
+ def commit_id?(ref)
+ COMMIT_ID.match?(ref)
+ end
+
def version
Gitlab::Git::Version.git_version
end
diff --git a/lib/gitlab/git/repository.rb b/lib/gitlab/git/repository.rb
index b7b7578cef9..27032602828 100644
--- a/lib/gitlab/git/repository.rb
+++ b/lib/gitlab/git/repository.rb
@@ -55,6 +55,10 @@ module Gitlab
@name = @relative_path.split("/").last
end
+ def to_s
+ "<#{self.class.name}: #{self.gl_project_path}>"
+ end
+
def ==(other)
other.is_a?(self.class) && [storage, relative_path] == [other.storage, other.relative_path]
end
@@ -464,6 +468,18 @@ module Gitlab
end
end
+ # Returns path to url mappings for submodules
+ #
+ # Ex.
+ # @repository.submodule_urls_for('master')
+ # # => { 'rack' => 'git@localhost:rack.git' }
+ #
+ def submodule_urls_for(ref)
+ wrapped_gitaly_errors do
+ gitaly_submodule_urls_for(ref)
+ end
+ end
+
# Return total commits count accessible from passed ref
def commit_count(ref)
wrapped_gitaly_errors do
@@ -861,13 +877,13 @@ module Gitlab
def multi_action(
user, branch_name:, message:, actions:,
author_email: nil, author_name: nil,
- start_branch_name: nil, start_repository: self,
+ start_branch_name: nil, start_sha: nil, start_repository: self,
force: false)
wrapped_gitaly_errors do
gitaly_operation_client.user_commit_files(user, branch_name,
message, actions, author_email, author_name,
- start_branch_name, start_repository, force)
+ start_branch_name, start_repository, force, start_sha)
end
end
# rubocop:enable Metrics/ParameterLists
@@ -1059,12 +1075,16 @@ module Gitlab
return unless commit_object && commit_object.type == :COMMIT
+ urls = gitaly_submodule_urls_for(ref)
+ urls && urls[path]
+ end
+
+ def gitaly_submodule_urls_for(ref)
gitmodules = gitaly_commit_client.tree_entry(ref, '.gitmodules', Gitlab::Git::Blob::MAX_DATA_DISPLAY_SIZE)
return unless gitmodules
- found_module = GitmodulesParser.new(gitmodules.data).parse[path]
-
- found_module && found_module['url']
+ submodules = GitmodulesParser.new(gitmodules.data).parse
+ submodules.transform_values { |submodule| submodule['url'] }
end
# Returns true if the given ref name exists
diff --git a/lib/gitlab/git/rugged_impl/blob.rb b/lib/gitlab/git/rugged_impl/blob.rb
index 86c9f33d82a..5c73c0c66a9 100644
--- a/lib/gitlab/git/rugged_impl/blob.rb
+++ b/lib/gitlab/git/rugged_impl/blob.rb
@@ -16,7 +16,7 @@ module Gitlab
override :tree_entry
def tree_entry(repository, sha, path, limit)
if use_rugged?(repository, :rugged_tree_entry)
- rugged_tree_entry(repository, sha, path, limit)
+ execute_rugged_call(:rugged_tree_entry, repository, sha, path, limit)
else
super
end
diff --git a/lib/gitlab/git/rugged_impl/commit.rb b/lib/gitlab/git/rugged_impl/commit.rb
index 971a33b2e99..0eff35ab1c4 100644
--- a/lib/gitlab/git/rugged_impl/commit.rb
+++ b/lib/gitlab/git/rugged_impl/commit.rb
@@ -36,7 +36,7 @@ module Gitlab
override :find_commit
def find_commit(repo, commit_id)
if use_rugged?(repo, :rugged_find_commit)
- rugged_find(repo, commit_id)
+ execute_rugged_call(:rugged_find, repo, commit_id)
else
super
end
@@ -45,7 +45,7 @@ module Gitlab
override :batch_by_oid
def batch_by_oid(repo, oids)
if use_rugged?(repo, :rugged_list_commits_by_oid)
- rugged_batch_by_oid(repo, oids)
+ execute_rugged_call(:rugged_batch_by_oid, repo, oids)
else
super
end
@@ -68,7 +68,7 @@ module Gitlab
override :commit_tree_entry
def commit_tree_entry(path)
if use_rugged?(@repository, :rugged_commit_tree_entry)
- rugged_tree_entry(path)
+ execute_rugged_call(:rugged_tree_entry, path)
else
super
end
diff --git a/lib/gitlab/git/rugged_impl/repository.rb b/lib/gitlab/git/rugged_impl/repository.rb
index 9268abdfed9..8fde93e71e2 100644
--- a/lib/gitlab/git/rugged_impl/repository.rb
+++ b/lib/gitlab/git/rugged_impl/repository.rb
@@ -48,7 +48,7 @@ module Gitlab
override :ancestor?
def ancestor?(from, to)
if use_rugged?(self, :rugged_commit_is_ancestor)
- rugged_is_ancestor?(from, to)
+ execute_rugged_call(:rugged_is_ancestor?, from, to)
else
super
end
diff --git a/lib/gitlab/git/rugged_impl/tree.rb b/lib/gitlab/git/rugged_impl/tree.rb
index f3721a3f1b7..389c9d32ccb 100644
--- a/lib/gitlab/git/rugged_impl/tree.rb
+++ b/lib/gitlab/git/rugged_impl/tree.rb
@@ -16,7 +16,7 @@ module Gitlab
override :tree_entries
def tree_entries(repository, sha, path, recursive)
if use_rugged?(repository, :rugged_tree_entries)
- tree_entries_with_flat_path_from_rugged(repository, sha, path, recursive)
+ execute_rugged_call(:tree_entries_with_flat_path_from_rugged, repository, sha, path, recursive)
else
super
end
diff --git a/lib/gitlab/git/rugged_impl/use_rugged.rb b/lib/gitlab/git/rugged_impl/use_rugged.rb
index 99091b03cd1..80b75689334 100644
--- a/lib/gitlab/git/rugged_impl/use_rugged.rb
+++ b/lib/gitlab/git/rugged_impl/use_rugged.rb
@@ -10,6 +10,29 @@ module Gitlab
Gitlab::GitalyClient.can_use_disk?(repo.storage)
end
+
+ def execute_rugged_call(method_name, *args)
+ Gitlab::GitalyClient::StorageSettings.allow_disk_access do
+ start = Gitlab::Metrics::System.monotonic_time
+
+ result = send(method_name, *args) # rubocop:disable GitlabSecurity/PublicSend
+
+ duration = Gitlab::Metrics::System.monotonic_time - start
+
+ if Gitlab::RuggedInstrumentation.active?
+ Gitlab::RuggedInstrumentation.increment_query_count
+ Gitlab::RuggedInstrumentation.query_time += duration
+
+ Gitlab::RuggedInstrumentation.add_call_details(
+ feature: method_name,
+ args: args,
+ duration: duration,
+ backtrace: Gitlab::Profiler.clean_backtrace(caller))
+ end
+
+ result
+ end
+ end
end
end
end
diff --git a/lib/gitlab/git_logger.rb b/lib/gitlab/git_logger.rb
index dac4ddd320f..ded5349be01 100644
--- a/lib/gitlab/git_logger.rb
+++ b/lib/gitlab/git_logger.rb
@@ -1,13 +1,9 @@
# frozen_string_literal: true
module Gitlab
- class GitLogger < Gitlab::Logger
+ class GitLogger < JsonLogger
def self.file_name_noext
'githost'
end
-
- def format_message(severity, timestamp, progname, msg)
- "#{timestamp.to_s(:long)} -> #{severity} -> #{msg}\n"
- end
end
end
diff --git a/lib/gitlab/gitaly_client.rb b/lib/gitlab/gitaly_client.rb
index 0b6321c66ab..4783832961d 100644
--- a/lib/gitlab/gitaly_client.rb
+++ b/lib/gitlab/gitaly_client.rb
@@ -387,21 +387,20 @@ module Gitlab
end
def self.can_use_disk?(storage)
- false
- # cached_value = MUTEX.synchronize do
- # @can_use_disk ||= {}
- # @can_use_disk[storage]
- # end
+ cached_value = MUTEX.synchronize do
+ @can_use_disk ||= {}
+ @can_use_disk[storage]
+ end
- # return cached_value unless cached_value.nil?
+ return cached_value unless cached_value.nil?
- # gitaly_filesystem_id = filesystem_id(storage)
- # direct_filesystem_id = filesystem_id_from_disk(storage)
+ gitaly_filesystem_id = filesystem_id(storage)
+ direct_filesystem_id = filesystem_id_from_disk(storage)
- # MUTEX.synchronize do
- # @can_use_disk[storage] = gitaly_filesystem_id.present? &&
- # gitaly_filesystem_id == direct_filesystem_id
- # end
+ MUTEX.synchronize do
+ @can_use_disk[storage] = gitaly_filesystem_id.present? &&
+ gitaly_filesystem_id == direct_filesystem_id
+ end
end
def self.filesystem_id(storage)
@@ -414,7 +413,7 @@ module Gitlab
metadata_file = File.read(storage_metadata_file_path(storage))
metadata_hash = JSON.parse(metadata_file)
metadata_hash['gitaly_filesystem_id']
- rescue Errno::ENOENT, JSON::ParserError
+ rescue Errno::ENOENT, Errno::EACCES, JSON::ParserError
nil
end
diff --git a/lib/gitlab/gitaly_client/operation_service.rb b/lib/gitlab/gitaly_client/operation_service.rb
index 783c2ff0915..33ca428a942 100644
--- a/lib/gitlab/gitaly_client/operation_service.rb
+++ b/lib/gitlab/gitaly_client/operation_service.rb
@@ -325,11 +325,11 @@ module Gitlab
# rubocop:disable Metrics/ParameterLists
def user_commit_files(
user, branch_name, commit_message, actions, author_email, author_name,
- start_branch_name, start_repository, force = false)
+ start_branch_name, start_repository, force = false, start_sha = nil)
req_enum = Enumerator.new do |y|
header = user_commit_files_request_header(user, branch_name,
commit_message, actions, author_email, author_name,
- start_branch_name, start_repository, force)
+ start_branch_name, start_repository, force, start_sha)
y.yield Gitaly::UserCommitFilesRequest.new(header: header)
@@ -445,7 +445,7 @@ module Gitlab
# rubocop:disable Metrics/ParameterLists
def user_commit_files_request_header(
user, branch_name, commit_message, actions, author_email, author_name,
- start_branch_name, start_repository, force)
+ start_branch_name, start_repository, force, start_sha)
Gitaly::UserCommitFilesRequestHeader.new(
repository: @gitaly_repo,
@@ -456,7 +456,8 @@ module Gitlab
commit_author_email: encode_binary(author_email),
start_branch_name: encode_binary(start_branch_name),
start_repository: start_repository.gitaly_repository,
- force: force
+ force: force,
+ start_sha: encode_binary(start_sha)
)
end
# rubocop:enable Metrics/ParameterLists
diff --git a/lib/gitlab/github_import/client.rb b/lib/gitlab/github_import/client.rb
index a61beafae0d..826b35d685c 100644
--- a/lib/gitlab/github_import/client.rb
+++ b/lib/gitlab/github_import/client.rb
@@ -40,7 +40,7 @@ module Gitlab
# otherwise hitting the rate limit will result in a thread
# being blocked in a `sleep()` call for up to an hour.
def initialize(token, per_page: 100, parallel: true)
- @octokit = Octokit::Client.new(
+ @octokit = ::Octokit::Client.new(
access_token: token,
per_page: per_page,
api_endpoint: api_endpoint
@@ -139,7 +139,7 @@ module Gitlab
begin
yield
- rescue Octokit::TooManyRequests
+ rescue ::Octokit::TooManyRequests
raise_or_wait_for_rate_limit
# This retry will only happen when running in sequential mode as we'll
diff --git a/lib/gitlab/grape_logging/loggers/perf_logger.rb b/lib/gitlab/grape_logging/loggers/perf_logger.rb
index 18ea3a8d2f3..7e86b35a215 100644
--- a/lib/gitlab/grape_logging/loggers/perf_logger.rb
+++ b/lib/gitlab/grape_logging/loggers/perf_logger.rb
@@ -6,11 +6,30 @@ module Gitlab
module Loggers
class PerfLogger < ::GrapeLogging::Loggers::Base
def parameters(_, _)
+ gitaly_data.merge(rugged_data)
+ end
+
+ def gitaly_data
+ gitaly_calls = Gitlab::GitalyClient.get_request_count
+
+ return {} if gitaly_calls.zero?
+
{
gitaly_calls: Gitlab::GitalyClient.get_request_count,
gitaly_duration: Gitlab::GitalyClient.query_time_ms
}
end
+
+ def rugged_data
+ rugged_calls = Gitlab::RuggedInstrumentation.query_count
+
+ return {} if rugged_calls.zero?
+
+ {
+ rugged_calls: rugged_calls,
+ rugged_duration_ms: Gitlab::RuggedInstrumentation.query_time_ms
+ }
+ end
end
end
end
diff --git a/lib/gitlab/graphql/representation/submodule_tree_entry.rb b/lib/gitlab/graphql/representation/submodule_tree_entry.rb
new file mode 100644
index 00000000000..65716dff75d
--- /dev/null
+++ b/lib/gitlab/graphql/representation/submodule_tree_entry.rb
@@ -0,0 +1,34 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module Graphql
+ module Representation
+ class SubmoduleTreeEntry < SimpleDelegator
+ class << self
+ def decorate(submodules, tree)
+ repository = tree.repository
+ submodule_links = Gitlab::SubmoduleLinks.new(repository)
+
+ submodules.map do |submodule|
+ self.new(submodule, submodule_links.for(submodule, tree.sha))
+ end
+ end
+ end
+
+ def initialize(submodule, submodule_links)
+ @submodule_links = submodule_links
+
+ super(submodule)
+ end
+
+ def web_url
+ @submodule_links.first
+ end
+
+ def tree_url
+ @submodule_links.last
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/health_checks/db_check.rb b/lib/gitlab/health_checks/db_check.rb
index 2bcd25cd3cc..ec4b97eaca4 100644
--- a/lib/gitlab/health_checks/db_check.rb
+++ b/lib/gitlab/health_checks/db_check.rb
@@ -18,11 +18,7 @@ module Gitlab
def check
catch_timeout 10.seconds do
- if Gitlab::Database.postgresql?
- ActiveRecord::Base.connection.execute('SELECT 1 as ping')&.first&.[]('ping')&.to_s
- else
- ActiveRecord::Base.connection.execute('SELECT 1 as ping')&.first&.first&.to_s
- end
+ ActiveRecord::Base.connection.execute('SELECT 1 as ping')&.first&.[]('ping')&.to_s
end
end
end
diff --git a/lib/gitlab/http_connection_adapter.rb b/lib/gitlab/http_connection_adapter.rb
index 41eab3658bc..84eb60f3a5d 100644
--- a/lib/gitlab/http_connection_adapter.rb
+++ b/lib/gitlab/http_connection_adapter.rb
@@ -1,7 +1,7 @@
# frozen_string_literal: true
# This class is part of the Gitlab::HTTP wrapper. Depending on the value
-# of the global setting allow_local_requests_from_hooks_and_services this adapter
+# of the global setting allow_local_requests_from_web_hooks_and_services this adapter
# will allow/block connection to internal IPs and/or urls.
#
# This functionality can be overridden by providing the setting the option
@@ -38,7 +38,7 @@ module Gitlab
end
def allow_settings_local_requests?
- Gitlab::CurrentSettings.allow_local_requests_from_hooks_and_services?
+ Gitlab::CurrentSettings.allow_local_requests_from_web_hooks_and_services?
end
end
end
diff --git a/lib/gitlab/import/database_helpers.rb b/lib/gitlab/import/database_helpers.rb
index 5b3f30d894a..aaade39dd62 100644
--- a/lib/gitlab/import/database_helpers.rb
+++ b/lib/gitlab/import/database_helpers.rb
@@ -6,9 +6,7 @@ module Gitlab
# Inserts a raw row and returns the ID of the inserted row.
#
# attributes - The attributes/columns to set.
- # relation - An ActiveRecord::Relation to use for finding the ID of the row
- # when using MySQL.
- # rubocop: disable CodeReuse/ActiveRecord
+ # relation - An ActiveRecord::Relation to use for finding the table name
def insert_and_return_id(attributes, relation)
# We use bulk_insert here so we can bypass any queries executed by
# callbacks or validation rules, as doing this wouldn't scale when
@@ -16,12 +14,8 @@ module Gitlab
result = Gitlab::Database
.bulk_insert(relation.table_name, [attributes], return_ids: true)
- # MySQL doesn't support returning the IDs of a bulk insert in a way that
- # is not a pain, so in this case we'll issue an extra query instead.
- result.first ||
- relation.where(iid: attributes[:iid]).limit(1).pluck(:id).first
+ result.first
end
- # rubocop: enable CodeReuse/ActiveRecord
end
end
end
diff --git a/lib/gitlab/import_export.rb b/lib/gitlab/import_export.rb
index f63a5ece71e..bb46bd657e8 100644
--- a/lib/gitlab/import_export.rb
+++ b/lib/gitlab/import_export.rb
@@ -4,7 +4,9 @@ module Gitlab
module ImportExport
extend self
- # For every version update, the version history in import_export.md has to be kept up to date.
+ # For every version update the version history in these docs must be kept up to date:
+ # - development/import_export.md
+ # - user/project/settings/import_export.md
VERSION = '0.2.4'.freeze
FILENAME_LIMIT = 50
@@ -28,6 +30,14 @@ module Gitlab
"project.bundle"
end
+ def lfs_objects_filename
+ "lfs-objects.json"
+ end
+
+ def lfs_objects_storage
+ "lfs-objects"
+ end
+
def config_file
Rails.root.join('lib/gitlab/import_export/import_export.yml')
end
diff --git a/lib/gitlab/import_export/attributes_finder.rb b/lib/gitlab/import_export/attributes_finder.rb
index 409243e68a5..42cd94add79 100644
--- a/lib/gitlab/import_export/attributes_finder.rb
+++ b/lib/gitlab/import_export/attributes_finder.rb
@@ -45,7 +45,7 @@ module Gitlab
end
def key_from_hash(value)
- value.is_a?(Hash) ? value.keys.first : value
+ value.is_a?(Hash) ? value.first.first : value
end
end
end
diff --git a/lib/gitlab/import_export/json_hash_builder.rb b/lib/gitlab/import_export/json_hash_builder.rb
index b145f37c052..a92e3862361 100644
--- a/lib/gitlab/import_export/json_hash_builder.rb
+++ b/lib/gitlab/import_export/json_hash_builder.rb
@@ -27,7 +27,7 @@ module Gitlab
# {:merge_requests=>[:merge_request_diff, :notes]}
def process_model_objects(model_object_hash)
json_config_hash = {}
- current_key = model_object_hash.keys.first
+ current_key = model_object_hash.first.first
model_object_hash.values.flatten.each do |model_object|
@attributes_finder.parse(current_key) { |hash| json_config_hash[current_key] ||= hash }
diff --git a/lib/gitlab/import_export/lfs_restorer.rb b/lib/gitlab/import_export/lfs_restorer.rb
index 345c7880e30..1de8a5bf9ec 100644
--- a/lib/gitlab/import_export/lfs_restorer.rb
+++ b/lib/gitlab/import_export/lfs_restorer.rb
@@ -3,6 +3,10 @@
module Gitlab
module ImportExport
class LfsRestorer
+ include Gitlab::Utils::StrongMemoize
+
+ attr_accessor :project, :shared
+
def initialize(project:, shared:)
@project = project
@shared = shared
@@ -17,7 +21,7 @@ module Gitlab
true
rescue => e
- @shared.error(e)
+ shared.error(e)
false
end
@@ -29,16 +33,57 @@ module Gitlab
lfs_object = LfsObject.find_or_initialize_by(oid: oid, size: size)
lfs_object.file = File.open(path) unless lfs_object.file&.exists?
+ lfs_object.save! if lfs_object.changed?
- @project.all_lfs_objects << lfs_object
+ repository_types(oid).each do |repository_type|
+ LfsObjectsProject.create!(
+ project: project,
+ lfs_object: lfs_object,
+ repository_type: repository_type
+ )
+ end
+ end
+
+ def repository_types(oid)
+ # We allow support for imports created before the `lfs-objects.json`
+ # file was generated. In this case, the restorer will link an LFS object
+ # with a single `lfs_objects_projects` relation.
+ #
+ # This allows us backwards-compatibility without version bumping.
+ # See https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/30830#note_192608870
+ return ['project'] unless has_lfs_json?
+
+ lfs_json[oid]
end
def lfs_file_paths
@lfs_file_paths ||= Dir.glob("#{lfs_storage_path}/*")
end
+ def has_lfs_json?
+ strong_memoize(:has_lfs_json) do
+ File.exist?(lfs_json_path)
+ end
+ end
+
+ def lfs_json
+ return {} unless has_lfs_json?
+
+ @lfs_json ||=
+ begin
+ json = IO.read(lfs_json_path)
+ ActiveSupport::JSON.decode(json)
+ rescue
+ raise Gitlab::ImportExport::Error.new('Incorrect JSON format')
+ end
+ end
+
def lfs_storage_path
- File.join(@shared.export_path, 'lfs-objects')
+ File.join(shared.export_path, ImportExport.lfs_objects_storage)
+ end
+
+ def lfs_json_path
+ File.join(shared.export_path, ImportExport.lfs_objects_filename)
end
end
end
diff --git a/lib/gitlab/import_export/lfs_saver.rb b/lib/gitlab/import_export/lfs_saver.rb
index 954f6f00078..18c590e1ca9 100644
--- a/lib/gitlab/import_export/lfs_saver.rb
+++ b/lib/gitlab/import_export/lfs_saver.rb
@@ -5,25 +5,40 @@ module Gitlab
class LfsSaver
include Gitlab::ImportExport::CommandLineUtil
+ attr_accessor :lfs_json, :project, :shared
+
+ BATCH_SIZE = 100
+
def initialize(project:, shared:)
@project = project
@shared = shared
+ @lfs_json = {}
end
def save
- @project.all_lfs_objects.each do |lfs_object|
- save_lfs_object(lfs_object)
+ project.all_lfs_objects.find_in_batches(batch_size: BATCH_SIZE) do |batch|
+ batch.each do |lfs_object|
+ save_lfs_object(lfs_object)
+ end
+
+ append_lfs_json_for_batch(batch) if write_lfs_json_enabled?
end
+ write_lfs_json if write_lfs_json_enabled?
+
true
rescue => e
- @shared.error(e)
+ shared.error(e)
false
end
private
+ def write_lfs_json_enabled?
+ ::Feature.enabled?(:export_lfs_objects_projects, default_enabled: true)
+ end
+
def save_lfs_object(lfs_object)
if lfs_object.local_store?
copy_file_for_lfs_object(lfs_object)
@@ -45,12 +60,36 @@ module Gitlab
copy_files(lfs_object.file.path, destination_path_for_object(lfs_object))
end
+ def append_lfs_json_for_batch(lfs_objects_batch)
+ lfs_objects_projects = LfsObjectsProject
+ .select('lfs_objects.oid, array_agg(distinct lfs_objects_projects.repository_type) as repository_types')
+ .joins(:lfs_object)
+ .where(project: project, lfs_object: lfs_objects_batch)
+ .group('lfs_objects.oid')
+
+ lfs_objects_projects.each do |group|
+ oid = group.oid
+
+ lfs_json[oid] ||= []
+ lfs_json[oid] += group.repository_types
+ end
+ end
+
+ def write_lfs_json
+ mkdir_p(shared.export_path)
+ File.write(lfs_json_path, lfs_json.to_json)
+ end
+
def destination_path_for_object(lfs_object)
File.join(lfs_export_path, lfs_object.oid)
end
def lfs_export_path
- File.join(@shared.export_path, 'lfs-objects')
+ File.join(shared.export_path, ImportExport.lfs_objects_storage)
+ end
+
+ def lfs_json_path
+ File.join(shared.export_path, ImportExport.lfs_objects_filename)
end
end
end
diff --git a/lib/gitlab/import_export/members_mapper.rb b/lib/gitlab/import_export/members_mapper.rb
index a154de5419e..4e976cfca3a 100644
--- a/lib/gitlab/import_export/members_mapper.rb
+++ b/lib/gitlab/import_export/members_mapper.rb
@@ -35,7 +35,7 @@ module Gitlab
end
def include?(old_author_id)
- map.keys.include?(old_author_id) && map[old_author_id] != default_user_id
+ map.has_key?(old_author_id) && map[old_author_id] != default_user_id
end
private
@@ -50,6 +50,8 @@ module Gitlab
@project.project_members.destroy_all # rubocop: disable DestroyAll
ProjectMember.create!(user: @user, access_level: ProjectMember::MAINTAINER, source_id: @project.id, importing: true)
+ rescue => e
+ raise e, "Error adding importer user to project members. #{e.message}"
end
def add_team_member(member, existing_user = nil)
diff --git a/lib/gitlab/import_export/project_tree_restorer.rb b/lib/gitlab/import_export/project_tree_restorer.rb
index dec99c23a2d..91fe4e5d074 100644
--- a/lib/gitlab/import_export/project_tree_restorer.rb
+++ b/lib/gitlab/import_export/project_tree_restorer.rb
@@ -130,6 +130,7 @@ module Gitlab
def visibility_level
level = override_params['visibility_level'] || json_params['visibility_level'] || @project.visibility_level
level = @project.group.visibility_level if @project.group && level.to_i > @project.group.visibility_level
+ level = Gitlab::VisibilityLevel::PRIVATE if level == Gitlab::VisibilityLevel::INTERNAL && Gitlab::CurrentSettings.restricted_visibility_levels.include?(level)
{ 'visibility_level' => level }
end
diff --git a/lib/gitlab/import_export/relation_factory.rb b/lib/gitlab/import_export/relation_factory.rb
index 1b545b1d049..0be49e27acb 100644
--- a/lib/gitlab/import_export/relation_factory.rb
+++ b/lib/gitlab/import_export/relation_factory.rb
@@ -185,7 +185,7 @@ module Gitlab
return unless EXISTING_OBJECT_CHECK.include?(@relation_name)
return unless @relation_hash['group_id']
- @relation_hash['group_id'] = @project.group&.id
+ @relation_hash['group_id'] = @project.namespace_id
end
def reset_tokens!
diff --git a/lib/gitlab/kubernetes/helm/delete_command.rb b/lib/gitlab/kubernetes/helm/delete_command.rb
index 876994d2678..dcf22e7abb6 100644
--- a/lib/gitlab/kubernetes/helm/delete_command.rb
+++ b/lib/gitlab/kubernetes/helm/delete_command.rb
@@ -7,19 +7,24 @@ module Gitlab
include BaseCommand
include ClientCommand
+ attr_reader :predelete, :postdelete
attr_accessor :name, :files
- def initialize(name:, rbac:, files:)
+ def initialize(name:, rbac:, files:, predelete: nil, postdelete: nil)
@name = name
@files = files
@rbac = rbac
+ @predelete = predelete
+ @postdelete = postdelete
end
def generate_script
super + [
init_command,
wait_for_tiller_command,
- delete_command
+ predelete,
+ delete_command,
+ postdelete
].compact.join("\n")
end
@@ -38,17 +43,6 @@ module Gitlab
command.shelljoin
end
-
- def optional_tls_flags
- return [] unless files.key?(:'ca.pem')
-
- [
- '--tls',
- '--tls-ca-cert', "#{files_dir}/ca.pem",
- '--tls-cert', "#{files_dir}/cert.pem",
- '--tls-key', "#{files_dir}/key.pem"
- ]
- end
end
end
end
diff --git a/lib/gitlab/kubernetes/helm/install_command.rb b/lib/gitlab/kubernetes/helm/install_command.rb
index 9744a5f3d8a..f572bc43533 100644
--- a/lib/gitlab/kubernetes/helm/install_command.rb
+++ b/lib/gitlab/kubernetes/helm/install_command.rb
@@ -27,9 +27,9 @@ module Gitlab
wait_for_tiller_command,
repository_command,
repository_update_command,
- preinstall_command,
+ preinstall,
install_command,
- postinstall_command
+ postinstall
].compact.join("\n")
end
@@ -58,14 +58,6 @@ module Gitlab
command.shelljoin
end
- def preinstall_command
- preinstall.join("\n") if preinstall
- end
-
- def postinstall_command
- postinstall.join("\n") if postinstall
- end
-
def install_flag
['--install']
end
diff --git a/lib/gitlab/kubernetes/helm/reset_command.rb b/lib/gitlab/kubernetes/helm/reset_command.rb
new file mode 100644
index 00000000000..37e1d8573ab
--- /dev/null
+++ b/lib/gitlab/kubernetes/helm/reset_command.rb
@@ -0,0 +1,54 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module Kubernetes
+ module Helm
+ class ResetCommand
+ include BaseCommand
+ include ClientCommand
+
+ attr_reader :name, :files
+
+ def initialize(name:, rbac:, files:)
+ @name = name
+ @files = files
+ @rbac = rbac
+ end
+
+ def generate_script
+ super + [
+ reset_helm_command,
+ delete_tiller_replicaset
+ ].join("\n")
+ end
+
+ def rbac?
+ @rbac
+ end
+
+ def pod_name
+ "uninstall-#{name}"
+ end
+
+ private
+
+ # This method can be delete once we upgrade Helm to > 12.13.0
+ # https://gitlab.com/gitlab-org/gitlab-ce/merge_requests/27096#note_159695900
+ #
+ # Tracking this method to be removed here:
+ # https://gitlab.com/gitlab-org/gitlab-ce/issues/52791#note_199374155
+ def delete_tiller_replicaset
+ command = %w[kubectl delete replicaset -n gitlab-managed-apps -l name=tiller]
+
+ command.shelljoin
+ end
+
+ def reset_helm_command
+ command = %w[helm reset] + optional_tls_flags
+
+ command.shelljoin
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/kubernetes/kube_client.rb b/lib/gitlab/kubernetes/kube_client.rb
index 1350924cd76..64317225ec6 100644
--- a/lib/gitlab/kubernetes/kube_client.rb
+++ b/lib/gitlab/kubernetes/kube_client.rb
@@ -128,7 +128,7 @@ module Gitlab
private
def validate_url!
- return if Gitlab::CurrentSettings.allow_local_requests_from_hooks_and_services?
+ return if Gitlab::CurrentSettings.allow_local_requests_from_web_hooks_and_services?
Gitlab::UrlBlocker.validate!(api_prefix, allow_local_network: false)
end
diff --git a/lib/gitlab/legacy_github_import/client.rb b/lib/gitlab/legacy_github_import/client.rb
index bbdd094e33b..b23efd64dee 100644
--- a/lib/gitlab/legacy_github_import/client.rb
+++ b/lib/gitlab/legacy_github_import/client.rb
@@ -101,7 +101,7 @@ module Gitlab
# GitHub Rate Limit API returns 404 when the rate limit is
# disabled. In this case we just want to return gracefully
# instead of spitting out an error.
- rescue Octokit::NotFound
+ rescue ::Octokit::NotFound
nil
end
diff --git a/lib/gitlab/metrics/dashboard/base_service.rb b/lib/gitlab/metrics/dashboard/base_service.rb
deleted file mode 100644
index 0628e82e592..00000000000
--- a/lib/gitlab/metrics/dashboard/base_service.rb
+++ /dev/null
@@ -1,72 +0,0 @@
-# frozen_string_literal: true
-
-# Searches a projects repository for a metrics dashboard and formats the output.
-# Expects any custom dashboards will be located in `.gitlab/dashboards`
-module Gitlab
- module Metrics
- module Dashboard
- class BaseService < ::BaseService
- PROCESSING_ERROR = Gitlab::Metrics::Dashboard::Stages::BaseStage::DashboardProcessingError
- NOT_FOUND_ERROR = Gitlab::Template::Finders::RepoTemplateFinder::FileNotFoundError
-
- def get_dashboard
- return error('Insufficient permissions.', :unauthorized) unless allowed?
-
- success(dashboard: process_dashboard)
- rescue NOT_FOUND_ERROR
- error("#{dashboard_path} could not be found.", :not_found)
- rescue PROCESSING_ERROR => e
- error(e.message, :unprocessable_entity)
- end
-
- # Summary of all known dashboards for the service.
- # @return [Array<Hash>] ex) [{ path: String, default: Boolean }]
- def self.all_dashboard_paths(_project)
- raise NotImplementedError
- end
-
- # Returns an un-processed dashboard from the cache.
- def raw_dashboard
- Gitlab::Metrics::Dashboard::Cache.fetch(cache_key) { get_raw_dashboard }
- end
-
- private
-
- # Determines whether users should be able to view
- # dashboards at all.
- def allowed?
- Ability.allowed?(current_user, :read_environment, project)
- end
-
- # Returns a new dashboard Hash, supplemented with DB info
- def process_dashboard
- Gitlab::Metrics::Dashboard::Processor
- .new(project, params[:environment], raw_dashboard)
- .process(insert_project_metrics: insert_project_metrics?)
- end
-
- # @return [String] Relative filepath of the dashboard yml
- def dashboard_path
- params[:dashboard_path]
- end
-
- # @return [Hash] an unmodified dashboard
- def get_raw_dashboard
- raise NotImplementedError
- end
-
- # @return [String]
- def cache_key
- raise NotImplementedError
- end
-
- # Determines whether custom metrics should be included
- # in the processed output.
- # @return [Boolean]
- def insert_project_metrics?
- false
- end
- end
- end
- end
-end
diff --git a/lib/gitlab/metrics/dashboard/dynamic_dashboard_service.rb b/lib/gitlab/metrics/dashboard/dynamic_dashboard_service.rb
deleted file mode 100644
index 81ed8922e17..00000000000
--- a/lib/gitlab/metrics/dashboard/dynamic_dashboard_service.rb
+++ /dev/null
@@ -1,65 +0,0 @@
-# frozen_string_literal: true
-
-# Responsible for returning a filtered system dashboard
-# containing only the default embedded metrics. In future,
-# this class may be updated to support filtering to
-# alternate metrics/panels.
-#
-# Why isn't this filtering in a processing stage? By filtering
-# here, we ensure the dynamically-determined dashboard is cached.
-#
-# Use Gitlab::Metrics::Dashboard::Finder to retrive dashboards.
-module Gitlab
- module Metrics
- module Dashboard
- class DynamicDashboardService < Gitlab::Metrics::Dashboard::BaseService
- # For the default filtering for embedded metrics,
- # uses the 'id' key in dashboard-yml definition for
- # identification.
- DEFAULT_EMBEDDED_METRICS_IDENTIFIERS = %w(
- system_metrics_kubernetes_container_memory_total
- system_metrics_kubernetes_container_cores_total
- ).freeze
-
- # Returns a new dashboard with only the matching
- # metrics from the system dashboard, stripped of groups.
- # @return [Hash]
- def raw_dashboard
- panels = panel_groups.each_with_object([]) do |group, panels|
- matched_panels = group['panels'].select { |panel| matching_panel?(panel) }
-
- panels.concat(matched_panels)
- end
-
- { 'panel_groups' => [{ 'panels' => panels }] }
- end
-
- def cache_key
- "dynamic_metrics_dashboard_#{metric_identifiers.join('_')}"
- end
-
- private
-
- # Returns an array of the panels groups on the
- # system dashboard
- def panel_groups
- Gitlab::Metrics::Dashboard::SystemDashboardService
- .new(project, nil)
- .raw_dashboard['panel_groups']
- end
-
- # Identifies a panel as "matching" if any metric ids in
- # the panel is in the list of identifiers to collect.
- def matching_panel?(panel)
- panel['metrics'].any? do |metric|
- metric_identifiers.include?(metric['id'])
- end
- end
-
- def metric_identifiers
- DEFAULT_EMBEDDED_METRICS_IDENTIFIERS
- end
- end
- end
- end
-end
diff --git a/lib/gitlab/metrics/dashboard/finder.rb b/lib/gitlab/metrics/dashboard/finder.rb
index d7491d1553d..1373830844b 100644
--- a/lib/gitlab/metrics/dashboard/finder.rb
+++ b/lib/gitlab/metrics/dashboard/finder.rb
@@ -47,22 +47,22 @@ module Gitlab
private
def service_for_path(dashboard_path, embedded:)
- return dynamic_service if embedded
+ return embed_service if embedded
return system_service if system_dashboard?(dashboard_path)
project_service
end
def system_service
- Gitlab::Metrics::Dashboard::SystemDashboardService
+ ::Metrics::Dashboard::SystemDashboardService
end
def project_service
- Gitlab::Metrics::Dashboard::ProjectDashboardService
+ ::Metrics::Dashboard::ProjectDashboardService
end
- def dynamic_service
- Gitlab::Metrics::Dashboard::DynamicDashboardService
+ def embed_service
+ ::Metrics::Dashboard::DefaultEmbedService
end
def system_dashboard?(filepath)
diff --git a/lib/gitlab/metrics/dashboard/project_dashboard_service.rb b/lib/gitlab/metrics/dashboard/project_dashboard_service.rb
deleted file mode 100644
index 5a1c4ecf886..00000000000
--- a/lib/gitlab/metrics/dashboard/project_dashboard_service.rb
+++ /dev/null
@@ -1,50 +0,0 @@
-# frozen_string_literal: true
-
-# Searches a projects repository for a metrics dashboard and formats the output.
-# Expects any custom dashboards will be located in `.gitlab/dashboards`
-# Use Gitlab::Metrics::Dashboard::Finder to retrive dashboards.
-module Gitlab
- module Metrics
- module Dashboard
- class ProjectDashboardService < Gitlab::Metrics::Dashboard::BaseService
- DASHBOARD_ROOT = ".gitlab/dashboards"
-
- class << self
- def all_dashboard_paths(project)
- file_finder(project)
- .list_files_for(DASHBOARD_ROOT)
- .map do |filepath|
- {
- path: filepath,
- display_name: name_for_path(filepath),
- default: false
- }
- end
- end
-
- def file_finder(project)
- Gitlab::Template::Finders::RepoTemplateFinder.new(project, DASHBOARD_ROOT, '.yml')
- end
-
- # Grabs the filepath after the base directory.
- def name_for_path(filepath)
- filepath.delete_prefix("#{DASHBOARD_ROOT}/")
- end
- end
-
- private
-
- # Searches the project repo for a custom-defined dashboard.
- def get_raw_dashboard
- yml = self.class.file_finder(project).read(dashboard_path)
-
- YAML.safe_load(yml)
- end
-
- def cache_key
- "project_#{project.id}_metrics_dashboard_#{dashboard_path}"
- end
- end
- end
- end
-end
diff --git a/lib/gitlab/metrics/dashboard/system_dashboard_service.rb b/lib/gitlab/metrics/dashboard/system_dashboard_service.rb
deleted file mode 100644
index 82421572f4a..00000000000
--- a/lib/gitlab/metrics/dashboard/system_dashboard_service.rb
+++ /dev/null
@@ -1,49 +0,0 @@
-# frozen_string_literal: true
-
-# Fetches the system metrics dashboard and formats the output.
-# Use Gitlab::Metrics::Dashboard::Finder to retrive dashboards.
-module Gitlab
- module Metrics
- module Dashboard
- class SystemDashboardService < Gitlab::Metrics::Dashboard::BaseService
- SYSTEM_DASHBOARD_PATH = 'config/prometheus/common_metrics.yml'
- SYSTEM_DASHBOARD_NAME = 'Default'
-
- class << self
- def all_dashboard_paths(_project)
- [{
- path: SYSTEM_DASHBOARD_PATH,
- display_name: SYSTEM_DASHBOARD_NAME,
- default: true
- }]
- end
-
- def system_dashboard?(filepath)
- filepath == SYSTEM_DASHBOARD_PATH
- end
- end
-
- private
-
- def dashboard_path
- SYSTEM_DASHBOARD_PATH
- end
-
- # Returns the base metrics shipped with every GitLab service.
- def get_raw_dashboard
- yml = File.read(Rails.root.join(dashboard_path))
-
- YAML.safe_load(yml)
- end
-
- def cache_key
- "metrics_dashboard_#{dashboard_path}"
- end
-
- def insert_project_metrics?
- true
- end
- end
- end
- end
-end
diff --git a/lib/gitlab/metrics/samplers/influx_sampler.rb b/lib/gitlab/metrics/samplers/influx_sampler.rb
index 5138b37f83e..1eae0a7bf45 100644
--- a/lib/gitlab/metrics/samplers/influx_sampler.rb
+++ b/lib/gitlab/metrics/samplers/influx_sampler.rb
@@ -15,19 +15,14 @@ module Gitlab
@last_step = nil
@metrics = []
-
- @last_minor_gc = Delta.new(GC.stat[:minor_gc_count])
- @last_major_gc = Delta.new(GC.stat[:major_gc_count])
end
def sample
sample_memory_usage
sample_file_descriptors
- sample_gc
flush
ensure
- GC::Profiler.clear
@metrics.clear
end
@@ -43,23 +38,6 @@ module Gitlab
add_metric('file_descriptors', value: System.file_descriptor_count)
end
- def sample_gc
- time = GC::Profiler.total_time * 1000.0
- stats = GC.stat.merge(total_time: time)
-
- # We want the difference of GC runs compared to the last sample, not the
- # total amount since the process started.
- stats[:minor_gc_count] =
- @last_minor_gc.compared_with(stats[:minor_gc_count])
-
- stats[:major_gc_count] =
- @last_major_gc.compared_with(stats[:major_gc_count])
-
- stats[:count] = stats[:minor_gc_count] + stats[:major_gc_count]
-
- add_metric('gc_statistics', stats)
- end
-
def add_metric(series, values, tags = {})
prefix = sidekiq? ? 'sidekiq_' : 'rails_'
diff --git a/lib/gitlab/metrics/samplers/ruby_sampler.rb b/lib/gitlab/metrics/samplers/ruby_sampler.rb
index eef802caabb..3bfa3da35e0 100644
--- a/lib/gitlab/metrics/samplers/ruby_sampler.rb
+++ b/lib/gitlab/metrics/samplers/ruby_sampler.rb
@@ -6,8 +6,12 @@ module Gitlab
module Metrics
module Samplers
class RubySampler < BaseSampler
+ GC_REPORT_BUCKETS = [0.001, 0.002, 0.005, 0.01, 0.05, 0.1, 0.5].freeze
+
def initialize(interval)
- metrics[:process_start_time_seconds].set(labels.merge(worker_label), Time.now.to_i)
+ GC::Profiler.clear
+
+ metrics[:process_start_time_seconds].set(labels, Time.now.to_i)
super
end
@@ -30,18 +34,18 @@ module Gitlab
def init_metrics
metrics = {
- file_descriptors: ::Gitlab::Metrics.gauge(with_prefix(:file, :descriptors), 'File descriptors used', labels, :livesum),
- memory_bytes: ::Gitlab::Metrics.gauge(with_prefix(:memory, :bytes), 'Memory used', labels, :livesum),
+ file_descriptors: ::Gitlab::Metrics.gauge(with_prefix(:file, :descriptors), 'File descriptors used', labels),
+ memory_bytes: ::Gitlab::Metrics.gauge(with_prefix(:memory, :bytes), 'Memory used', labels),
process_cpu_seconds_total: ::Gitlab::Metrics.gauge(with_prefix(:process, :cpu_seconds_total), 'Process CPU seconds total'),
process_max_fds: ::Gitlab::Metrics.gauge(with_prefix(:process, :max_fds), 'Process max fds'),
- process_resident_memory_bytes: ::Gitlab::Metrics.gauge(with_prefix(:process, :resident_memory_bytes), 'Memory used', labels, :livesum),
+ process_resident_memory_bytes: ::Gitlab::Metrics.gauge(with_prefix(:process, :resident_memory_bytes), 'Memory used', labels),
process_start_time_seconds: ::Gitlab::Metrics.gauge(with_prefix(:process, :start_time_seconds), 'Process start time seconds'),
sampler_duration: ::Gitlab::Metrics.counter(with_prefix(:sampler, :duration_seconds_total), 'Sampler time', labels),
- total_time: ::Gitlab::Metrics.counter(with_prefix(:gc, :duration_seconds_total), 'Total GC time', labels)
+ gc_duration_seconds: ::Gitlab::Metrics.histogram(with_prefix(:gc, :duration_seconds), 'GC time', labels, GC_REPORT_BUCKETS)
}
GC.stat.keys.each do |key|
- metrics[key] = ::Gitlab::Metrics.gauge(with_prefix(:gc_stat, key), to_doc_string(key), labels, :livesum)
+ metrics[key] = ::Gitlab::Metrics.gauge(with_prefix(:gc_stat, key), to_doc_string(key), labels)
end
metrics
@@ -50,47 +54,41 @@ module Gitlab
def sample
start_time = System.monotonic_time
- metrics[:file_descriptors].set(labels.merge(worker_label), System.file_descriptor_count)
- metrics[:process_cpu_seconds_total].set(labels.merge(worker_label), ::Gitlab::Metrics::System.cpu_time)
- metrics[:process_max_fds].set(labels.merge(worker_label), ::Gitlab::Metrics::System.max_open_file_descriptors)
+ metrics[:file_descriptors].set(labels, System.file_descriptor_count)
+ metrics[:process_cpu_seconds_total].set(labels, ::Gitlab::Metrics::System.cpu_time)
+ metrics[:process_max_fds].set(labels, ::Gitlab::Metrics::System.max_open_file_descriptors)
set_memory_usage_metrics
sample_gc
metrics[:sampler_duration].increment(labels, System.monotonic_time - start_time)
- ensure
- GC::Profiler.clear
end
private
def sample_gc
- # Collect generic GC stats.
+ # Observe all GC samples
+ sample_gc_reports.each do |report|
+ metrics[:gc_duration_seconds].observe(labels, report[:GC_TIME])
+ end
+
+ # Collect generic GC stats
GC.stat.each do |key, value|
metrics[key].set(labels, value)
end
+ end
- # Collect the GC time since last sample in float seconds.
- metrics[:total_time].increment(labels, GC::Profiler.total_time)
+ def sample_gc_reports
+ GC::Profiler.enable
+ GC::Profiler.raw_data
+ ensure
+ GC::Profiler.clear
end
def set_memory_usage_metrics
memory_usage = System.memory_usage
- memory_labels = labels.merge(worker_label)
- metrics[:memory_bytes].set(memory_labels, memory_usage)
- metrics[:process_resident_memory_bytes].set(memory_labels, memory_usage)
- end
-
- def worker_label
- return { worker: 'sidekiq' } if Sidekiq.server?
- return {} unless defined?(Unicorn::Worker)
-
- worker_no = ::Prometheus::Client::Support::Unicorn.worker_id
- if worker_no
- { worker: worker_no }
- else
- { worker: 'master' }
- end
+ metrics[:memory_bytes].set(labels, memory_usage)
+ metrics[:process_resident_memory_bytes].set(labels, memory_usage)
end
end
end
diff --git a/lib/gitlab/metrics/subscribers/rails_cache.rb b/lib/gitlab/metrics/subscribers/rails_cache.rb
index 01db507761b..2ee7144fe2f 100644
--- a/lib/gitlab/metrics/subscribers/rails_cache.rb
+++ b/lib/gitlab/metrics/subscribers/rails_cache.rb
@@ -50,7 +50,8 @@ module Gitlab
def observe(key, duration)
return unless current_transaction
- metric_cache_operation_duration_seconds.observe(current_transaction.labels.merge({ operation: key }), duration / 1000.0)
+ metric_cache_operations_total.increment(current_transaction.labels.merge({ operation: key }))
+ metric_cache_operation_duration_seconds.observe({ operation: key }, duration / 1000.0)
current_transaction.increment(:cache_duration, duration, false)
current_transaction.increment(:cache_count, 1, false)
current_transaction.increment("cache_#{key}_duration".to_sym, duration, false)
@@ -63,12 +64,20 @@ module Gitlab
Transaction.current
end
+ def metric_cache_operations_total
+ @metric_cache_operations_total ||= ::Gitlab::Metrics.counter(
+ :gitlab_cache_operations_total,
+ 'Cache operations',
+ Transaction::BASE_LABELS
+ )
+ end
+
def metric_cache_operation_duration_seconds
@metric_cache_operation_duration_seconds ||= ::Gitlab::Metrics.histogram(
:gitlab_cache_operation_duration_seconds,
'Cache access time',
- Transaction::BASE_LABELS.merge({ action: nil }),
- [0.001, 0.01, 0.1, 1, 10]
+ {},
+ [0.00001, 0.0001, 0.001, 0.01, 0.1, 1.0]
)
end
diff --git a/lib/gitlab/object_hierarchy.rb b/lib/gitlab/object_hierarchy.rb
index 38b32770e90..c06f106ffe1 100644
--- a/lib/gitlab/object_hierarchy.rb
+++ b/lib/gitlab/object_hierarchy.rb
@@ -32,11 +32,6 @@ module Gitlab
# Returns the maximum depth starting from the base
# A base object with no children has a maximum depth of `1`
def max_descendants_depth
- unless hierarchy_supported?
- # This makes the return value consistent with the case where hierarchy is supported
- return descendants_base.exists? ? 1 : nil
- end
-
base_and_descendants(with_depth: true).maximum(DEPTH_COLUMN)
end
@@ -66,8 +61,6 @@ module Gitlab
# each parent.
# rubocop: disable CodeReuse/ActiveRecord
def base_and_ancestors(upto: nil, hierarchy_order: nil)
- return ancestors_base unless hierarchy_supported?
-
recursive_query = base_and_ancestors_cte(upto, hierarchy_order).apply_to(model.all)
recursive_query = recursive_query.order(depth: hierarchy_order) if hierarchy_order
@@ -81,10 +74,6 @@ module Gitlab
# When `with_depth` is `true`, a `depth` column is included where it starts with `1` for the base objects
# and incremented as we go down the descendant tree
def base_and_descendants(with_depth: false)
- unless hierarchy_supported?
- return with_depth ? descendants_base.select("1 as #{DEPTH_COLUMN}", objects_table[Arel.star]) : descendants_base
- end
-
read_only(base_and_descendants_cte(with_depth: with_depth).apply_to(model.all))
end
@@ -112,8 +101,6 @@ module Gitlab
# If nested objects are not supported, ancestors_base is returned.
# rubocop: disable CodeReuse/ActiveRecord
def all_objects
- return ancestors_base unless hierarchy_supported?
-
ancestors = base_and_ancestors_cte
descendants = base_and_descendants_cte
@@ -135,10 +122,6 @@ module Gitlab
private
- def hierarchy_supported?
- Gitlab::Database.postgresql?
- end
-
# rubocop: disable CodeReuse/ActiveRecord
def base_and_ancestors_cte(stop_id = nil, hierarchy_order = nil)
cte = SQL::RecursiveCTE.new(:base_and_ancestors)
diff --git a/lib/gitlab/octokit/middleware.rb b/lib/gitlab/octokit/middleware.rb
new file mode 100644
index 00000000000..2dd7d08a58b
--- /dev/null
+++ b/lib/gitlab/octokit/middleware.rb
@@ -0,0 +1,23 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module Octokit
+ class Middleware
+ def initialize(app)
+ @app = app
+ end
+
+ def call(env)
+ Gitlab::UrlBlocker.validate!(env[:url], { allow_localhost: allow_local_requests?, allow_local_network: allow_local_requests? })
+
+ @app.call(env)
+ end
+
+ private
+
+ def allow_local_requests?
+ Gitlab::CurrentSettings.allow_local_requests_from_web_hooks_and_services?
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/path_regex.rb b/lib/gitlab/path_regex.rb
index a13b3f9e069..f96466b2b00 100644
--- a/lib/gitlab/path_regex.rb
+++ b/lib/gitlab/path_regex.rb
@@ -175,6 +175,10 @@ module Gitlab
@project_git_route_regex ||= /#{project_route_regex}\.git/.freeze
end
+ def project_wiki_git_route_regex
+ @project_wiki_git_route_regex ||= /#{PATH_REGEX_STR}\.wiki/.freeze
+ end
+
def full_namespace_path_regex
@full_namespace_path_regex ||= %r{\A#{full_namespace_route_regex}/\z}
end
diff --git a/lib/gitlab/performance_bar/peek_query_tracker.rb b/lib/gitlab/performance_bar/peek_query_tracker.rb
deleted file mode 100644
index 3a27e26eaba..00000000000
--- a/lib/gitlab/performance_bar/peek_query_tracker.rb
+++ /dev/null
@@ -1,45 +0,0 @@
-# frozen_string_literal: true
-
-# Inspired by https://github.com/peek/peek-pg/blob/master/lib/peek/views/pg.rb
-# PEEK_DB_CLIENT is a constant set in config/initializers/peek.rb
-module Gitlab
- module PerformanceBar
- module PeekQueryTracker
- def sorted_queries
- PEEK_DB_CLIENT.query_details
- .sort { |a, b| b[:duration] <=> a[:duration] }
- end
-
- def results
- super.merge(queries: sorted_queries)
- end
-
- private
-
- def setup_subscribers
- super
-
- # Reset each counter when a new request starts
- before_request do
- PEEK_DB_CLIENT.query_details = []
- end
-
- subscribe('sql.active_record') do |_, start, finish, _, data|
- if Gitlab::SafeRequestStore.store[:peek_enabled]
- unless data[:cached]
- backtrace = Gitlab::Profiler.clean_backtrace(caller)
- track_query(data[:sql].strip, data[:binds], backtrace, start, finish)
- end
- end
- end
- end
-
- def track_query(raw_query, bindings, backtrace, start, finish)
- duration = (finish - start) * 1000.0
- query_info = { duration: duration.round(3), sql: raw_query, backtrace: backtrace }
-
- PEEK_DB_CLIENT.query_details << query_info
- end
- end
- end
-end
diff --git a/lib/gitlab/profiler.rb b/lib/gitlab/profiler.rb
index 890228e5e78..ec7671f9a8b 100644
--- a/lib/gitlab/profiler.rb
+++ b/lib/gitlab/profiler.rb
@@ -21,6 +21,9 @@ module Gitlab
lib/gitlab/profiler.rb
lib/gitlab/correlation_id.rb
lib/gitlab/webpack/dev_server_middleware.rb
+ lib/gitlab/sidekiq_status/
+ lib/gitlab/sidekiq_logging/
+ lib/gitlab/sidekiq_middleware/
].freeze
# Takes a URL to profile (can be a fully-qualified URL, or an absolute path)
@@ -166,7 +169,7 @@ module Gitlab
[model, times.count, times.sum]
end
- summarised_load_times.sort_by(&:last).reverse.each do |(model, query_count, time)|
+ summarised_load_times.sort_by(&:last).reverse_each do |(model, query_count, time)|
logger.info("#{model} total (#{query_count}): #{time.round(2)}ms")
end
end
diff --git a/lib/gitlab/project_authorizations.rb b/lib/gitlab/project_authorizations.rb
new file mode 100644
index 00000000000..a9270cd536e
--- /dev/null
+++ b/lib/gitlab/project_authorizations.rb
@@ -0,0 +1,121 @@
+# frozen_string_literal: true
+
+# This class relies on Common Table Expressions to efficiently get all data,
+# including data for nested groups.
+module Gitlab
+ class ProjectAuthorizations
+ attr_reader :user
+
+ # user - The User object for which to calculate the authorizations.
+ def initialize(user)
+ @user = user
+ end
+
+ def calculate
+ cte = recursive_cte
+ cte_alias = cte.table.alias(Group.table_name)
+ projects = Project.arel_table
+ links = ProjectGroupLink.arel_table
+
+ relations = [
+ # The project a user has direct access to.
+ user.projects.select_for_project_authorization,
+
+ # The personal projects of the user.
+ user.personal_projects.select_as_maintainer_for_project_authorization,
+
+ # Projects that belong directly to any of the groups the user has
+ # access to.
+ Namespace
+ .unscoped
+ .select([alias_as_column(projects[:id], 'project_id'),
+ cte_alias[:access_level]])
+ .from(cte_alias)
+ .joins(:projects),
+
+ # Projects shared with any of the namespaces the user has access to.
+ Namespace
+ .unscoped
+ .select([
+ links[:project_id],
+ least(cte_alias[:access_level], links[:group_access], 'access_level')
+ ])
+ .from(cte_alias)
+ .joins('INNER JOIN project_group_links ON project_group_links.group_id = namespaces.id')
+ .joins('INNER JOIN projects ON projects.id = project_group_links.project_id')
+ .joins('INNER JOIN namespaces p_ns ON p_ns.id = projects.namespace_id')
+ .where('p_ns.share_with_group_lock IS FALSE')
+ ]
+
+ ProjectAuthorization
+ .unscoped
+ .with
+ .recursive(cte.to_arel)
+ .select_from_union(relations)
+ end
+
+ private
+
+ # Builds a recursive CTE that gets all the groups the current user has
+ # access to, including any nested groups.
+ def recursive_cte
+ cte = Gitlab::SQL::RecursiveCTE.new(:namespaces_cte)
+ members = Member.arel_table
+ namespaces = Namespace.arel_table
+
+ # Namespaces the user is a member of.
+ cte << user.groups
+ .select([namespaces[:id], members[:access_level]])
+ .except(:order)
+
+ # Sub groups of any groups the user is a member of.
+ cte << Group.select([
+ namespaces[:id],
+ greatest(members[:access_level], cte.table[:access_level], 'access_level')
+ ])
+ .joins(join_cte(cte))
+ .joins(join_members)
+ .except(:order)
+
+ cte
+ end
+
+ # Builds a LEFT JOIN to join optional memberships onto the CTE.
+ def join_members
+ members = Member.arel_table
+ namespaces = Namespace.arel_table
+
+ cond = members[:source_id]
+ .eq(namespaces[:id])
+ .and(members[:source_type].eq('Namespace'))
+ .and(members[:requested_at].eq(nil))
+ .and(members[:user_id].eq(user.id))
+
+ Arel::Nodes::OuterJoin.new(members, Arel::Nodes::On.new(cond))
+ end
+
+ # Builds an INNER JOIN to join namespaces onto the CTE.
+ def join_cte(cte)
+ namespaces = Namespace.arel_table
+ cond = cte.table[:id].eq(namespaces[:parent_id])
+
+ Arel::Nodes::InnerJoin.new(cte.table, Arel::Nodes::On.new(cond))
+ end
+
+ def greatest(left, right, column_alias)
+ sql_function('GREATEST', [left, right], column_alias)
+ end
+
+ def least(left, right, column_alias)
+ sql_function('LEAST', [left, right], column_alias)
+ end
+
+ def sql_function(name, args, column_alias)
+ alias_as_column(Arel::Nodes::NamedFunction.new(name, args), column_alias)
+ end
+
+ def alias_as_column(value, alias_to)
+ Arel::Nodes::As.new(value, Arel::Nodes::SqlLiteral.new(alias_to))
+ end
+ end
+end
diff --git a/lib/gitlab/project_authorizations/with_nested_groups.rb b/lib/gitlab/project_authorizations/with_nested_groups.rb
deleted file mode 100644
index 2372a316ab0..00000000000
--- a/lib/gitlab/project_authorizations/with_nested_groups.rb
+++ /dev/null
@@ -1,125 +0,0 @@
-# frozen_string_literal: true
-
-module Gitlab
- module ProjectAuthorizations
- # Calculating new project authorizations when supporting nested groups.
- #
- # This class relies on Common Table Expressions to efficiently get all data,
- # including data for nested groups. As a result this class can only be used
- # on PostgreSQL.
- class WithNestedGroups
- attr_reader :user
-
- # user - The User object for which to calculate the authorizations.
- def initialize(user)
- @user = user
- end
-
- def calculate
- cte = recursive_cte
- cte_alias = cte.table.alias(Group.table_name)
- projects = Project.arel_table
- links = ProjectGroupLink.arel_table
-
- relations = [
- # The project a user has direct access to.
- user.projects.select_for_project_authorization,
-
- # The personal projects of the user.
- user.personal_projects.select_as_maintainer_for_project_authorization,
-
- # Projects that belong directly to any of the groups the user has
- # access to.
- Namespace
- .unscoped
- .select([alias_as_column(projects[:id], 'project_id'),
- cte_alias[:access_level]])
- .from(cte_alias)
- .joins(:projects),
-
- # Projects shared with any of the namespaces the user has access to.
- Namespace
- .unscoped
- .select([links[:project_id],
- least(cte_alias[:access_level],
- links[:group_access],
- 'access_level')])
- .from(cte_alias)
- .joins('INNER JOIN project_group_links ON project_group_links.group_id = namespaces.id')
- .joins('INNER JOIN projects ON projects.id = project_group_links.project_id')
- .joins('INNER JOIN namespaces p_ns ON p_ns.id = projects.namespace_id')
- .where('p_ns.share_with_group_lock IS FALSE')
- ]
-
- ProjectAuthorization
- .unscoped
- .with
- .recursive(cte.to_arel)
- .select_from_union(relations)
- end
-
- private
-
- # Builds a recursive CTE that gets all the groups the current user has
- # access to, including any nested groups.
- def recursive_cte
- cte = Gitlab::SQL::RecursiveCTE.new(:namespaces_cte)
- members = Member.arel_table
- namespaces = Namespace.arel_table
-
- # Namespaces the user is a member of.
- cte << user.groups
- .select([namespaces[:id], members[:access_level]])
- .except(:order)
-
- # Sub groups of any groups the user is a member of.
- cte << Group.select([namespaces[:id],
- greatest(members[:access_level],
- cte.table[:access_level], 'access_level')])
- .joins(join_cte(cte))
- .joins(join_members)
- .except(:order)
-
- cte
- end
-
- # Builds a LEFT JOIN to join optional memberships onto the CTE.
- def join_members
- members = Member.arel_table
- namespaces = Namespace.arel_table
-
- cond = members[:source_id]
- .eq(namespaces[:id])
- .and(members[:source_type].eq('Namespace'))
- .and(members[:requested_at].eq(nil))
- .and(members[:user_id].eq(user.id))
-
- Arel::Nodes::OuterJoin.new(members, Arel::Nodes::On.new(cond))
- end
-
- # Builds an INNER JOIN to join namespaces onto the CTE.
- def join_cte(cte)
- namespaces = Namespace.arel_table
- cond = cte.table[:id].eq(namespaces[:parent_id])
-
- Arel::Nodes::InnerJoin.new(cte.table, Arel::Nodes::On.new(cond))
- end
-
- def greatest(left, right, column_alias)
- sql_function('GREATEST', [left, right], column_alias)
- end
-
- def least(left, right, column_alias)
- sql_function('LEAST', [left, right], column_alias)
- end
-
- def sql_function(name, args, column_alias)
- alias_as_column(Arel::Nodes::NamedFunction.new(name, args), column_alias)
- end
-
- def alias_as_column(value, alias_to)
- Arel::Nodes::As.new(value, Arel::Nodes::SqlLiteral.new(alias_to))
- end
- end
- end
-end
diff --git a/lib/gitlab/project_authorizations/without_nested_groups.rb b/lib/gitlab/project_authorizations/without_nested_groups.rb
deleted file mode 100644
index 50b41b17649..00000000000
--- a/lib/gitlab/project_authorizations/without_nested_groups.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-# frozen_string_literal: true
-
-module Gitlab
- module ProjectAuthorizations
- # Calculating new project authorizations when not supporting nested groups.
- class WithoutNestedGroups
- attr_reader :user
-
- # user - The User object for which to calculate the authorizations.
- def initialize(user)
- @user = user
- end
-
- def calculate
- relations = [
- # Projects the user is a direct member of
- user.projects.select_for_project_authorization,
-
- # Personal projects
- user.personal_projects.select_as_maintainer_for_project_authorization,
-
- # Projects of groups the user is a member of
- user.groups_projects.select_for_project_authorization,
-
- # Projects shared with groups the user is a member of
- user.groups.joins(:shared_projects).select_for_project_authorization
- ]
-
- ProjectAuthorization
- .unscoped
- .select_from_union(relations)
- end
- end
- end
-end
diff --git a/lib/gitlab/project_search_results.rb b/lib/gitlab/project_search_results.rb
index 0f3b97e2317..827f4f77f36 100644
--- a/lib/gitlab/project_search_results.rb
+++ b/lib/gitlab/project_search_results.rb
@@ -108,7 +108,7 @@ module Gitlab
# rubocop: disable CodeReuse/ActiveRecord
def notes_finder(type)
- NotesFinder.new(project, @current_user, search: query, target_type: type).execute.user.order('updated_at DESC')
+ NotesFinder.new(@current_user, search: query, target_type: type, project: project).execute.user.order('updated_at DESC')
end
# rubocop: enable CodeReuse/ActiveRecord
diff --git a/lib/gitlab/project_template.rb b/lib/gitlab/project_template.rb
index 99885be8755..dbf469a44c1 100644
--- a/lib/gitlab/project_template.rb
+++ b/lib/gitlab/project_template.rb
@@ -13,11 +13,15 @@ module Gitlab
end
def archive_path
- Rails.root.join("vendor/project_templates/#{name}.tar.gz")
+ self.class.archive_directory.join(archive_filename)
+ end
+
+ def archive_filename
+ "#{name}.tar.gz"
end
def clone_url
- "https://gitlab.com/gitlab-org/project-templates/#{name}.git"
+ "#{preview}.git"
end
def ==(other)
@@ -54,7 +58,7 @@ module Gitlab
end
def archive_directory
- Rails.root.join("vendor_directory/project_templates")
+ Rails.root.join("vendor/project_templates")
end
end
end
diff --git a/lib/gitlab/push_options.rb b/lib/gitlab/push_options.rb
index 3137676ba4b..682edfc4259 100644
--- a/lib/gitlab/push_options.rb
+++ b/lib/gitlab/push_options.rb
@@ -4,7 +4,14 @@ module Gitlab
class PushOptions
VALID_OPTIONS = HashWithIndifferentAccess.new({
merge_request: {
- keys: [:create, :merge_when_pipeline_succeeds, :target]
+ keys: [
+ :create,
+ :description,
+ :merge_when_pipeline_succeeds,
+ :remove_source_branch,
+ :target,
+ :title
+ ]
},
ci: {
keys: [:skip]
diff --git a/lib/gitlab/quick_actions/command_definition.rb b/lib/gitlab/quick_actions/command_definition.rb
index 93030fd454e..ebdae139315 100644
--- a/lib/gitlab/quick_actions/command_definition.rb
+++ b/lib/gitlab/quick_actions/command_definition.rb
@@ -3,8 +3,8 @@
module Gitlab
module QuickActions
class CommandDefinition
- attr_accessor :name, :aliases, :description, :explanation, :params,
- :condition_block, :parse_params_block, :action_block, :warning, :types
+ attr_accessor :name, :aliases, :description, :explanation, :execution_message,
+ :params, :condition_block, :parse_params_block, :action_block, :warning, :types
def initialize(name, attributes = {})
@name = name
@@ -13,6 +13,7 @@ module Gitlab
@description = attributes[:description] || ''
@warning = attributes[:warning] || ''
@explanation = attributes[:explanation] || ''
+ @execution_message = attributes[:execution_message] || ''
@params = attributes[:params] || []
@condition_block = attributes[:condition_block]
@parse_params_block = attributes[:parse_params_block]
@@ -48,13 +49,23 @@ module Gitlab
end
def execute(context, arg)
- return if noop? || !available?(context)
+ return unless executable?(context)
count_commands_executed_in(context)
execute_block(action_block, context, arg)
end
+ def execute_message(context, arg)
+ return unless executable?(context)
+
+ if execution_message.respond_to?(:call)
+ execute_block(execution_message, context, arg)
+ else
+ execution_message
+ end
+ end
+
def to_h(context)
desc = description
if desc.respond_to?(:call)
@@ -77,6 +88,10 @@ module Gitlab
private
+ def executable?(context)
+ !noop? && available?(context)
+ end
+
def count_commands_executed_in(context)
return unless context.respond_to?(:commands_executed_count=)
diff --git a/lib/gitlab/quick_actions/commit_actions.rb b/lib/gitlab/quick_actions/commit_actions.rb
index 1018910e8e9..49f5ddf24eb 100644
--- a/lib/gitlab/quick_actions/commit_actions.rb
+++ b/lib/gitlab/quick_actions/commit_actions.rb
@@ -16,6 +16,13 @@ module Gitlab
_("Tags this commit to %{tag_name}.") % { tag_name: tag_name }
end
end
+ execution_message do |tag_name, message|
+ if message.present?
+ _("Tagged this commit to %{tag_name} with \"%{message}\".") % { tag_name: tag_name, message: message }
+ else
+ _("Tagged this commit to %{tag_name}.") % { tag_name: tag_name }
+ end
+ end
params 'v1.2.3 <message>'
parse_params do |tag_name_and_message|
tag_name_and_message.split(' ', 2)
diff --git a/lib/gitlab/quick_actions/dsl.rb b/lib/gitlab/quick_actions/dsl.rb
index ecb2169151e..5abbd377642 100644
--- a/lib/gitlab/quick_actions/dsl.rb
+++ b/lib/gitlab/quick_actions/dsl.rb
@@ -66,6 +66,35 @@ module Gitlab
@explanation = block_given? ? block : text
end
+ # Allows to provide a message about quick action execution result, success or failure.
+ # This message is shown after quick action execution and after saving the note.
+ #
+ # Example:
+ #
+ # execution_message do |arguments|
+ # "Added label(s) #{arguments.join(' ')}"
+ # end
+ # command :command_key do |arguments|
+ # # Awesome code block
+ # end
+ #
+ # Note: The execution_message won't be executed unless the condition block returns true.
+ # execution_message block is executed always after the command block has run,
+ # for this reason if the condition block doesn't return true after the command block has
+ # run you need to set the @execution_message variable inside the command block instead as
+ # shown in the following example.
+ #
+ # Example using instance variable:
+ #
+ # command :command_key do |arguments|
+ # # Awesome code block
+ # @execution_message[:command_key] = 'command_key executed successfully'
+ # end
+ #
+ def execution_message(text = '', &block)
+ @execution_message = block_given? ? block : text
+ end
+
# Allows to define type(s) that must be met in order for the command
# to be returned by `.command_names` & `.command_definitions`.
#
@@ -121,10 +150,16 @@ module Gitlab
# comment.
# It accepts aliases and takes a block.
#
+ # You can also set the @execution_message instance variable, on conflicts with
+ # execution_message method the instance variable has precedence.
+ #
# Example:
#
# command :my_command, :alias_for_my_command do |arguments|
# # Awesome code block
+ # @updates[:my_command] = 'foo'
+ #
+ # @execution_message[:my_command] = 'my_command executed successfully'
# end
def command(*command_names, &block)
define_command(CommandDefinition, *command_names, &block)
@@ -158,6 +193,7 @@ module Gitlab
description: @description,
warning: @warning,
explanation: @explanation,
+ execution_message: @execution_message,
params: @params,
condition_block: @condition_block,
parse_params_block: @parse_params_block,
@@ -173,6 +209,7 @@ module Gitlab
@description = nil
@explanation = nil
+ @execution_message = nil
@params = nil
@condition_block = nil
@warning = nil
diff --git a/lib/gitlab/quick_actions/issuable_actions.rb b/lib/gitlab/quick_actions/issuable_actions.rb
index f7f89d4e897..b975a967d03 100644
--- a/lib/gitlab/quick_actions/issuable_actions.rb
+++ b/lib/gitlab/quick_actions/issuable_actions.rb
@@ -12,10 +12,16 @@ module Gitlab
included do
# Issue, MergeRequest, Epic: quick actions definitions
desc do
- "Close this #{quick_action_target.to_ability_name.humanize(capitalize: false)}"
+ _('Close this %{quick_action_target}') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
explanation do
- "Closes this #{quick_action_target.to_ability_name.humanize(capitalize: false)}."
+ _('Closes this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
+ end
+ execution_message do
+ _('Closed this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
types Issuable
condition do
@@ -28,10 +34,16 @@ module Gitlab
end
desc do
- "Reopen this #{quick_action_target.to_ability_name.humanize(capitalize: false)}"
+ _('Reopen this %{quick_action_target}') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
explanation do
- "Reopens this #{quick_action_target.to_ability_name.humanize(capitalize: false)}."
+ _('Reopens this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
+ end
+ execution_message do
+ _('Reopened this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
types Issuable
condition do
@@ -45,7 +57,10 @@ module Gitlab
desc _('Change title')
explanation do |title_param|
- _("Changes the title to \"%{title_param}\".") % { title_param: title_param }
+ _('Changes the title to "%{title_param}".') % { title_param: title_param }
+ end
+ execution_message do |title_param|
+ _('Changed the title to "%{title_param}".') % { title_param: title_param }
end
params '<New title>'
types Issuable
@@ -61,7 +76,10 @@ module Gitlab
explanation do |labels_param|
labels = find_label_references(labels_param)
- "Adds #{labels.join(' ')} #{'label'.pluralize(labels.count)}." if labels.any?
+ if labels.any?
+ _("Adds %{labels} %{label_text}.") %
+ { labels: labels.join(' '), label_text: 'label'.pluralize(labels.count) }
+ end
end
params '~label1 ~"label 2"'
types Issuable
@@ -71,21 +89,15 @@ module Gitlab
find_labels.any?
end
command :label do |labels_param|
- label_ids = find_label_ids(labels_param)
-
- if label_ids.any?
- @updates[:add_label_ids] ||= []
- @updates[:add_label_ids] += label_ids
-
- @updates[:add_label_ids].uniq!
- end
+ run_label_command(labels: find_labels(labels_param), command: :label, updates_key: :add_label_ids)
end
desc _('Remove all or specific label(s)')
explanation do |labels_param = nil|
- if labels_param.present?
- labels = find_label_references(labels_param)
- "Removes #{labels.join(' ')} #{'label'.pluralize(labels.count)}." if labels.any?
+ label_references = labels_param.present? ? find_label_references(labels_param) : []
+ if label_references.any?
+ _("Removes %{label_references} %{label_text}.") %
+ { label_references: label_references.join(' '), label_text: 'label'.pluralize(label_references.count) }
else
_('Removes all labels.')
end
@@ -99,7 +111,9 @@ module Gitlab
end
command :unlabel do |labels_param = nil|
if labels_param.present?
- label_ids = find_label_ids(labels_param)
+ labels = find_labels(labels_param)
+ label_ids = labels.map(&:id)
+ label_references = labels_to_reference(labels, :name)
if label_ids.any?
@updates[:remove_label_ids] ||= []
@@ -109,7 +123,10 @@ module Gitlab
end
else
@updates[:label_ids] = []
+ label_references = []
end
+
+ @execution_message[:unlabel] = remove_label_message(label_references)
end
desc _('Replace all label(s)')
@@ -125,18 +142,12 @@ module Gitlab
current_user.can?(:"admin_#{quick_action_target.to_ability_name}", parent)
end
command :relabel do |labels_param|
- label_ids = find_label_ids(labels_param)
-
- if label_ids.any?
- @updates[:label_ids] ||= []
- @updates[:label_ids] += label_ids
-
- @updates[:label_ids].uniq!
- end
+ run_label_command(labels: find_labels(labels_param), command: :relabel, updates_key: :label_ids)
end
desc _('Add a todo')
explanation _('Adds a todo.')
+ execution_message _('Added a todo.')
types Issuable
condition do
quick_action_target.persisted? &&
@@ -148,6 +159,7 @@ module Gitlab
desc _('Mark to do as done')
explanation _('Marks to do as done.')
+ execution_message _('Marked to do as done.')
types Issuable
condition do
quick_action_target.persisted? &&
@@ -159,7 +171,12 @@ module Gitlab
desc _('Subscribe')
explanation do
- "Subscribes to this #{quick_action_target.to_ability_name.humanize(capitalize: false)}."
+ _('Subscribes to this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
+ end
+ execution_message do
+ _('Subscribed to this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
types Issuable
condition do
@@ -172,7 +189,12 @@ module Gitlab
desc _('Unsubscribe')
explanation do
- "Unsubscribes from this #{quick_action_target.to_ability_name.humanize(capitalize: false)}."
+ _('Unsubscribes from this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
+ end
+ execution_message do
+ _('Unsubscribed from this %{quick_action_target}.') %
+ { quick_action_target: quick_action_target.to_ability_name.humanize(capitalize: false) }
end
types Issuable
condition do
@@ -187,6 +209,9 @@ module Gitlab
explanation do |name|
_("Toggles :%{name}: emoji award.") % { name: name } if name
end
+ execution_message do |name|
+ _("Toggled :%{name}: emoji award.") % { name: name } if name
+ end
params ':emoji:'
types Issuable
condition do
@@ -215,6 +240,41 @@ module Gitlab
substitution :tableflip do |comment|
"#{comment} #{TABLEFLIP}"
end
+
+ private
+
+ def run_label_command(labels:, command:, updates_key:)
+ return if labels.empty?
+
+ @updates[updates_key] ||= []
+ @updates[updates_key] += labels.map(&:id)
+ @updates[updates_key].uniq!
+
+ label_references = labels_to_reference(labels, :name)
+ @execution_message[command] = case command
+ when :relabel
+ _('Replaced all labels with %{label_references} %{label_text}.') %
+ {
+ label_references: label_references.join(' '),
+ label_text: 'label'.pluralize(label_references.count)
+ }
+ when :label
+ _('Added %{label_references} %{label_text}.') %
+ {
+ label_references: label_references.join(' '),
+ label_text: 'label'.pluralize(labels.count)
+ }
+ end
+ end
+
+ def remove_label_message(label_references)
+ if label_references.any?
+ _("Removed %{label_references} %{label_text}.") %
+ { label_references: label_references.join(' '), label_text: 'label'.pluralize(label_references.count) }
+ else
+ _('Removed all labels.')
+ end
+ end
end
end
end
diff --git a/lib/gitlab/quick_actions/issue_actions.rb b/lib/gitlab/quick_actions/issue_actions.rb
index 85e62f950c8..0868bd85600 100644
--- a/lib/gitlab/quick_actions/issue_actions.rb
+++ b/lib/gitlab/quick_actions/issue_actions.rb
@@ -12,6 +12,9 @@ module Gitlab
explanation do |due_date|
_("Sets the due date to %{due_date}.") % { due_date: due_date.strftime('%b %-d, %Y') } if due_date
end
+ execution_message do |due_date|
+ _("Set the due date to %{due_date}.") % { due_date: due_date.strftime('%b %-d, %Y') } if due_date
+ end
params '<in 2 days | this Friday | December 31st>'
types Issue
condition do
@@ -27,6 +30,7 @@ module Gitlab
desc _('Remove due date')
explanation _('Removes the due date.')
+ execution_message _('Removed the due date.')
types Issue
condition do
quick_action_target.persisted? &&
@@ -49,22 +53,27 @@ module Gitlab
current_user.can?(:"update_#{quick_action_target.to_ability_name}", quick_action_target) &&
quick_action_target.project.boards.count == 1
end
- # rubocop: disable CodeReuse/ActiveRecord
command :board_move do |target_list_name|
- label_ids = find_label_ids(target_list_name)
+ labels = find_labels(target_list_name)
+ label_ids = labels.map(&:id)
if label_ids.size == 1
label_id = label_ids.first
# Ensure this label corresponds to a list on the board
- next unless Label.on_project_boards(quick_action_target.project_id).where(id: label_id).exists?
+ next unless Label.on_project_board?(quick_action_target.project_id, label_id)
@updates[:remove_label_ids] =
- quick_action_target.labels.on_project_boards(quick_action_target.project_id).where.not(id: label_id).pluck(:id)
+ quick_action_target.labels.on_project_boards(quick_action_target.project_id).where.not(id: label_id).pluck(:id) # rubocop: disable CodeReuse/ActiveRecord
@updates[:add_label_ids] = [label_id]
+
+ message = _("Moved issue to %{label} column in the board.") % { label: labels_to_reference(labels).first }
+ else
+ message = _('Move this issue failed because you need to specify only one label.')
end
+
+ @execution_message[:board_move] = message
end
- # rubocop: enable CodeReuse/ActiveRecord
desc _('Mark this issue as a duplicate of another issue')
explanation do |duplicate_reference|
@@ -81,7 +90,13 @@ module Gitlab
if canonical_issue.present?
@updates[:canonical_issue_id] = canonical_issue.id
+
+ message = _("Marked this issue as a duplicate of %{duplicate_param}.") % { duplicate_param: duplicate_param }
+ else
+ message = _('Mark as duplicate failed because referenced issue was not found')
end
+
+ @execution_message[:duplicate] = message
end
desc _('Move this issue to another project.')
@@ -99,13 +114,22 @@ module Gitlab
if target_project.present?
@updates[:target_project] = target_project
+
+ message = _("Moved this issue to %{path_to_project}.") % { path_to_project: target_project_path }
+ else
+ message = _("Move this issue failed because target project doesn't exists")
end
+
+ @execution_message[:move] = message
end
desc _('Make issue confidential.')
explanation do
_('Makes this issue confidential')
end
+ execution_message do
+ _('Made this issue confidential')
+ end
types Issue
condition do
current_user.can?(:"admin_#{quick_action_target.to_ability_name}", quick_action_target)
@@ -119,7 +143,14 @@ module Gitlab
if branch_name
_("Creates branch '%{branch_name}' and a merge request to resolve this issue") % { branch_name: branch_name }
else
- "Creates a branch and a merge request to resolve this issue"
+ _('Creates a branch and a merge request to resolve this issue')
+ end
+ end
+ execution_message do |branch_name = nil|
+ if branch_name
+ _("Created branch '%{branch_name}' and a merge request to resolve this issue") % { branch_name: branch_name }
+ else
+ _('Created a branch and a merge request to resolve this issue')
end
end
params "<branch name>"
diff --git a/lib/gitlab/quick_actions/issue_and_merge_request_actions.rb b/lib/gitlab/quick_actions/issue_and_merge_request_actions.rb
index e1579cfddc0..41ffd51cde8 100644
--- a/lib/gitlab/quick_actions/issue_and_merge_request_actions.rb
+++ b/lib/gitlab/quick_actions/issue_and_merge_request_actions.rb
@@ -9,12 +9,9 @@ module Gitlab
included do
# Issue, MergeRequest: quick actions definitions
desc _('Assign')
- # rubocop: disable CodeReuse/ActiveRecord
explanation do |users|
- users = quick_action_target.allows_multiple_assignees? ? users : users.take(1)
- "Assigns #{users.map(&:to_reference).to_sentence}."
+ _('Assigns %{assignee_users_sentence}.') % { assignee_users_sentence: assignee_users_sentence(users) }
end
- # rubocop: enable CodeReuse/ActiveRecord
params do
quick_action_target.allows_multiple_assignees? ? '@user1 @user2' : '@user'
end
@@ -26,7 +23,10 @@ module Gitlab
extract_users(assignee_param)
end
command :assign do |users|
- next if users.empty?
+ if users.empty?
+ @execution_message[:assign] = _("Assign command failed because no user was found")
+ next
+ end
if quick_action_target.allows_multiple_assignees?
@updates[:assignee_ids] ||= quick_action_target.assignees.map(&:id)
@@ -34,6 +34,8 @@ module Gitlab
else
@updates[:assignee_ids] = [users.first.id]
end
+
+ @execution_message[:assign] = _('Assigned %{assignee_users_sentence}.') % { assignee_users_sentence: assignee_users_sentence(users) }
end
desc do
@@ -44,9 +46,14 @@ module Gitlab
end
end
explanation do |users = nil|
- assignees = quick_action_target.assignees
- assignees &= users if users.present? && quick_action_target.allows_multiple_assignees?
- "Removes #{'assignee'.pluralize(assignees.size)} #{assignees.map(&:to_reference).to_sentence}."
+ assignees = assignees_for_removal(users)
+ _("Removes %{assignee_text} %{assignee_references}.") %
+ { assignee_text: 'assignee'.pluralize(assignees.size), assignee_references: assignees.map(&:to_reference).to_sentence }
+ end
+ execution_message do |users = nil|
+ assignees = assignees_for_removal(users)
+ _("Removed %{assignee_text} %{assignee_references}.") %
+ { assignee_text: 'assignee'.pluralize(assignees.size), assignee_references: assignees.map(&:to_reference).to_sentence }
end
params do
quick_action_target.allows_multiple_assignees? ? '@user1 @user2' : ''
@@ -74,6 +81,9 @@ module Gitlab
explanation do |milestone|
_("Sets the milestone to %{milestone_reference}.") % { milestone_reference: milestone.to_reference } if milestone
end
+ execution_message do |milestone|
+ _("Set the milestone to %{milestone_reference}.") % { milestone_reference: milestone.to_reference } if milestone
+ end
params '%"milestone"'
types Issue, MergeRequest
condition do
@@ -92,6 +102,9 @@ module Gitlab
explanation do
_("Removes %{milestone_reference} milestone.") % { milestone_reference: quick_action_target.milestone.to_reference(format: :name) }
end
+ execution_message do
+ _("Removed %{milestone_reference} milestone.") % { milestone_reference: quick_action_target.milestone.to_reference(format: :name) }
+ end
types Issue, MergeRequest
condition do
quick_action_target.persisted? &&
@@ -116,17 +129,22 @@ module Gitlab
extract_references(issuable_param, :merge_request).first
end
command :copy_metadata do |source_issuable|
- if source_issuable.present? && source_issuable.project.id == quick_action_target.project.id
+ if can_copy_metadata?(source_issuable)
@updates[:add_label_ids] = source_issuable.labels.map(&:id)
@updates[:milestone_id] = source_issuable.milestone.id if source_issuable.milestone
+
+ @execution_message[:copy_metadata] = _("Copied labels and milestone from %{source_issuable_reference}.") % { source_issuable_reference: source_issuable.to_reference }
end
end
desc _('Set time estimate')
explanation do |time_estimate|
- time_estimate = Gitlab::TimeTrackingFormatter.output(time_estimate)
-
- _("Sets time estimate to %{time_estimate}.") % { time_estimate: time_estimate } if time_estimate
+ formatted_time_estimate = format_time_estimate(time_estimate)
+ _("Sets time estimate to %{time_estimate}.") % { time_estimate: formatted_time_estimate } if formatted_time_estimate
+ end
+ execution_message do |time_estimate|
+ formatted_time_estimate = format_time_estimate(time_estimate)
+ _("Set time estimate to %{time_estimate}.") % { time_estimate: formatted_time_estimate } if formatted_time_estimate
end
params '<1w 3d 2h 14m>'
types Issue, MergeRequest
@@ -144,18 +162,12 @@ module Gitlab
desc _('Add or subtract spent time')
explanation do |time_spent, time_spent_date|
- if time_spent
- if time_spent > 0
- verb = _('Adds')
- value = time_spent
- else
- verb = _('Subtracts')
- value = -time_spent
- end
-
- _("%{verb} %{time_spent_value} spent time.") % { verb: verb, time_spent_value: Gitlab::TimeTrackingFormatter.output(value) }
- end
+ spend_time_message(time_spent, time_spent_date, false)
end
+ execution_message do |time_spent, time_spent_date|
+ spend_time_message(time_spent, time_spent_date, true)
+ end
+
params '<time(1h30m | -1h30m)> <date(YYYY-MM-DD)>'
types Issue, MergeRequest
condition do
@@ -176,6 +188,7 @@ module Gitlab
desc _('Remove time estimate')
explanation _('Removes time estimate.')
+ execution_message _('Removed time estimate.')
types Issue, MergeRequest
condition do
quick_action_target.persisted? &&
@@ -187,6 +200,7 @@ module Gitlab
desc _('Remove spent time')
explanation _('Removes spent time.')
+ execution_message _('Removed spent time.')
condition do
quick_action_target.persisted? &&
current_user.can?(:"admin_#{quick_action_target.to_ability_name}", project)
@@ -198,6 +212,7 @@ module Gitlab
desc _("Lock the discussion")
explanation _("Locks the discussion")
+ execution_message _("Locked the discussion")
types Issue, MergeRequest
condition do
quick_action_target.persisted? &&
@@ -210,6 +225,7 @@ module Gitlab
desc _("Unlock the discussion")
explanation _("Unlocks the discussion")
+ execution_message _("Unlocked the discussion")
types Issue, MergeRequest
condition do
quick_action_target.persisted? &&
@@ -219,6 +235,47 @@ module Gitlab
command :unlock do
@updates[:discussion_locked] = false
end
+
+ private
+
+ def assignee_users_sentence(users)
+ if quick_action_target.allows_multiple_assignees?
+ users
+ else
+ [users.first]
+ end.map(&:to_reference).to_sentence
+ end
+
+ def assignees_for_removal(users)
+ assignees = quick_action_target.assignees
+ if users.present? && quick_action_target.allows_multiple_assignees?
+ assignees & users
+ else
+ assignees
+ end
+ end
+
+ def can_copy_metadata?(source_issuable)
+ source_issuable.present? && source_issuable.project_id == quick_action_target.project_id
+ end
+
+ def format_time_estimate(time_estimate)
+ Gitlab::TimeTrackingFormatter.output(time_estimate)
+ end
+
+ def spend_time_message(time_spent, time_spent_date, paste_tense)
+ return unless time_spent
+
+ if time_spent > 0
+ verb = paste_tense ? _('Added') : _('Adds')
+ value = time_spent
+ else
+ verb = paste_tense ? _('Subtracted') : _('Subtracts')
+ value = -time_spent
+ end
+
+ _("%{verb} %{time_spent_value} spent time.") % { verb: verb, time_spent_value: format_time_estimate(value) }
+ end
end
end
end
diff --git a/lib/gitlab/quick_actions/merge_request_actions.rb b/lib/gitlab/quick_actions/merge_request_actions.rb
index bade59182a1..e9127095a0d 100644
--- a/lib/gitlab/quick_actions/merge_request_actions.rb
+++ b/lib/gitlab/quick_actions/merge_request_actions.rb
@@ -8,8 +8,9 @@ module Gitlab
included do
# MergeRequest only quick actions definitions
- desc 'Merge (when the pipeline succeeds)'
- explanation 'Merges this merge request when the pipeline succeeds.'
+ desc _('Merge (when the pipeline succeeds)')
+ explanation _('Merges this merge request when the pipeline succeeds.')
+ execution_message _('Scheduled to merge this merge request when the pipeline succeeds.')
types MergeRequest
condition do
last_diff_sha = params && params[:merge_request_diff_head_sha]
@@ -22,10 +23,22 @@ module Gitlab
desc 'Toggle the Work In Progress status'
explanation do
- verb = quick_action_target.work_in_progress? ? 'Unmarks' : 'Marks'
noun = quick_action_target.to_ability_name.humanize(capitalize: false)
- "#{verb} this #{noun} as Work In Progress."
+ if quick_action_target.work_in_progress?
+ _("Unmarks this %{noun} as Work In Progress.")
+ else
+ _("Marks this %{noun} as Work In Progress.")
+ end % { noun: noun }
end
+ execution_message do
+ noun = quick_action_target.to_ability_name.humanize(capitalize: false)
+ if quick_action_target.work_in_progress?
+ _("Unmarked this %{noun} as Work In Progress.")
+ else
+ _("Marked this %{noun} as Work In Progress.")
+ end % { noun: noun }
+ end
+
types MergeRequest
condition do
quick_action_target.respond_to?(:work_in_progress?) &&
@@ -36,9 +49,12 @@ module Gitlab
@updates[:wip_event] = quick_action_target.work_in_progress? ? 'unwip' : 'wip'
end
- desc 'Set target branch'
+ desc _('Set target branch')
explanation do |branch_name|
- "Sets target branch to #{branch_name}."
+ _('Sets target branch to %{branch_name}.') % { branch_name: branch_name }
+ end
+ execution_message do |branch_name|
+ _('Set target branch to %{branch_name}.') % { branch_name: branch_name }
end
params '<Local branch name>'
types MergeRequest
diff --git a/lib/gitlab/regex.rb b/lib/gitlab/regex.rb
index e43147a3f37..21614ea003e 100644
--- a/lib/gitlab/regex.rb
+++ b/lib/gitlab/regex.rb
@@ -94,6 +94,12 @@ module Gitlab
}mx
end
+ # Based on Jira's project key format
+ # https://confluence.atlassian.com/adminjiraserver073/changing-the-project-key-format-861253229.html
+ def jira_issue_key_regex
+ @jira_issue_key_regex ||= /[A-Z][A-Z_0-9]+-\d+/
+ end
+
def jira_transition_id_regex
@jira_transition_id_regex ||= /\d+/
end
diff --git a/lib/gitlab/request_profiler.rb b/lib/gitlab/request_profiler.rb
index 64593153686..033e451dbee 100644
--- a/lib/gitlab/request_profiler.rb
+++ b/lib/gitlab/request_profiler.rb
@@ -6,6 +6,21 @@ module Gitlab
module RequestProfiler
PROFILES_DIR = "#{Gitlab.config.shared.path}/tmp/requests_profiles".freeze
+ def all
+ Dir["#{PROFILES_DIR}/*.{html,txt}"].map do |path|
+ Profile.new(File.basename(path))
+ end.select(&:valid?)
+ end
+ module_function :all
+
+ def find(name)
+ file_path = File.join(PROFILES_DIR, name)
+ return unless File.exist?(file_path)
+
+ Profile.new(name)
+ end
+ module_function :find
+
def profile_token
Rails.cache.fetch('profile-token') do
Devise.friendly_token
diff --git a/lib/gitlab/request_profiler/middleware.rb b/lib/gitlab/request_profiler/middleware.rb
index 7615f6f443b..99958d7a211 100644
--- a/lib/gitlab/request_profiler/middleware.rb
+++ b/lib/gitlab/request_profiler/middleware.rb
@@ -1,6 +1,7 @@
# frozen_string_literal: true
require 'ruby-prof'
+require 'memory_profiler'
module Gitlab
module RequestProfiler
@@ -28,22 +29,73 @@ module Gitlab
end
def call_with_profiling(env)
+ case env['HTTP_X_PROFILE_MODE']
+ when 'execution', nil
+ call_with_call_stack_profiling(env)
+ when 'memory'
+ call_with_memory_profiling(env)
+ else
+ raise ActionController::BadRequest, invalid_profile_mode(env)
+ end
+ end
+
+ def invalid_profile_mode(env)
+ <<~HEREDOC
+ Invalid X-Profile-Mode: #{env['HTTP_X_PROFILE_MODE']}.
+ Supported profile mode request header:
+ - X-Profile-Mode: execution
+ - X-Profile-Mode: memory
+ HEREDOC
+ end
+
+ def call_with_call_stack_profiling(env)
ret = nil
- result = RubyProf::Profile.profile do
+ report = RubyProf::Profile.profile do
ret = catch(:warden) do
@app.call(env)
end
end
- printer = RubyProf::CallStackPrinter.new(result)
- file_name = "#{env['PATH_INFO'].tr('/', '|')}_#{Time.current.to_i}.html"
+ generate_report(env, 'execution', 'html') do |file|
+ printer = RubyProf::CallStackPrinter.new(report)
+ printer.print(file)
+ end
+
+ handle_request_ret(ret)
+ end
+
+ def call_with_memory_profiling(env)
+ ret = nil
+ report = MemoryProfiler.report do
+ ret = catch(:warden) do
+ @app.call(env)
+ end
+ end
+
+ generate_report(env, 'memory', 'txt') do |file|
+ report.pretty_print(to_file: file)
+ end
+
+ handle_request_ret(ret)
+ end
+
+ def generate_report(env, report_type, extension)
+ file_name = "#{env['PATH_INFO'].tr('/', '|')}_#{Time.current.to_i}"\
+ "_#{report_type}.#{extension}"
file_path = "#{PROFILES_DIR}/#{file_name}"
FileUtils.mkdir_p(PROFILES_DIR)
- File.open(file_path, 'wb') do |file|
- printer.print(file)
+
+ begin
+ File.open(file_path, 'wb') do |file|
+ yield(file)
+ end
+ rescue
+ FileUtils.rm(file_path)
end
+ end
+ def handle_request_ret(ret)
if ret.is_a?(Array)
ret
else
diff --git a/lib/gitlab/request_profiler/profile.rb b/lib/gitlab/request_profiler/profile.rb
index 46996ef8c51..76c675658b1 100644
--- a/lib/gitlab/request_profiler/profile.rb
+++ b/lib/gitlab/request_profiler/profile.rb
@@ -3,42 +3,40 @@
module Gitlab
module RequestProfiler
class Profile
- attr_reader :name, :time, :request_path
+ attr_reader :name, :time, :file_path, :request_path, :profile_mode, :type
alias_method :to_param, :name
- def self.all
- Dir["#{PROFILES_DIR}/*.html"].map do |path|
- new(File.basename(path))
- end
- end
-
- def self.find(name)
- name_dup = name.dup
- name_dup << '.html' unless name.end_with?('.html')
-
- file_path = "#{PROFILES_DIR}/#{name_dup}"
- return unless File.exist?(file_path)
-
- new(name_dup)
- end
-
def initialize(name)
@name = name
+ @file_path = File.join(PROFILES_DIR, name)
set_attributes
end
- def content
- File.read("#{PROFILES_DIR}/#{name}")
+ def valid?
+ @request_path.present?
+ end
+
+ def content_type
+ case type
+ when 'html'
+ 'text/html'
+ when 'txt'
+ 'text/plain'
+ end
end
private
def set_attributes
- _, path, timestamp = name.split(/(.*)_(\d+)\.html$/)
- @request_path = path.tr('|', '/')
- @time = Time.at(timestamp.to_i).utc
+ matches = name.match(/^(?<path>.*)_(?<timestamp>\d+)(_(?<profile_mode>\w+))?\.(?<type>html|txt)$/)
+ return unless matches
+
+ @request_path = matches[:path].tr('|', '/')
+ @time = Time.at(matches[:timestamp].to_i).utc
+ @profile_mode = matches[:profile_mode] || 'unknown'
+ @type = matches[:type]
end
end
end
diff --git a/lib/gitlab/rugged_instrumentation.rb b/lib/gitlab/rugged_instrumentation.rb
new file mode 100644
index 00000000000..8bb8c547ae1
--- /dev/null
+++ b/lib/gitlab/rugged_instrumentation.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module RuggedInstrumentation
+ def self.query_time
+ SafeRequestStore[:rugged_query_time] ||= 0
+ end
+
+ def self.query_time=(duration)
+ SafeRequestStore[:rugged_query_time] = duration
+ end
+
+ def self.query_time_ms
+ (self.query_time * 1000).round(2)
+ end
+
+ def self.query_count
+ SafeRequestStore[:rugged_call_count] ||= 0
+ end
+
+ def self.increment_query_count
+ SafeRequestStore[:rugged_call_count] ||= 0
+ SafeRequestStore[:rugged_call_count] += 1
+ end
+
+ def self.active?
+ SafeRequestStore.active?
+ end
+
+ def self.peek_enabled?
+ SafeRequestStore[:peek_enabled]
+ end
+
+ def self.add_call_details(details)
+ return unless peek_enabled?
+
+ Gitlab::SafeRequestStore[:rugged_call_details] ||= []
+ Gitlab::SafeRequestStore[:rugged_call_details] << details
+ end
+
+ def self.list_call_details
+ return [] unless peek_enabled?
+
+ Gitlab::SafeRequestStore[:rugged_call_details] || []
+ end
+ end
+end
diff --git a/lib/gitlab/sherlock/query.rb b/lib/gitlab/sherlock/query.rb
index 159ce27e702..cbd89b7629f 100644
--- a/lib/gitlab/sherlock/query.rb
+++ b/lib/gitlab/sherlock/query.rb
@@ -96,12 +96,7 @@ module Gitlab
private
def raw_explain(query)
- explain =
- if Gitlab::Database.postgresql?
- "EXPLAIN ANALYZE #{query};"
- else
- "EXPLAIN #{query};"
- end
+ explain = "EXPLAIN ANALYZE #{query};"
ActiveRecord::Base.connection.execute(explain)
end
diff --git a/lib/gitlab/sidekiq_logging/structured_logger.rb b/lib/gitlab/sidekiq_logging/structured_logger.rb
index fdc0d518c59..d556d5ef129 100644
--- a/lib/gitlab/sidekiq_logging/structured_logger.rb
+++ b/lib/gitlab/sidekiq_logging/structured_logger.rb
@@ -32,6 +32,12 @@ module Gitlab
payload['message'] = "#{base_message(payload)}: start"
payload['job_status'] = 'start'
+ # Old gitlab-shell messages don't provide enqueued_at/created_at attributes
+ enqueued_at = payload['enqueued_at'] || payload['created_at']
+ if enqueued_at
+ payload['scheduling_latency_s'] = elapsed(Time.iso8601(enqueued_at).to_f)
+ end
+
payload
end
diff --git a/lib/gitlab/sidekiq_middleware/memory_killer.rb b/lib/gitlab/sidekiq_middleware/memory_killer.rb
index 671d795ec33..49c4fdc3033 100644
--- a/lib/gitlab/sidekiq_middleware/memory_killer.rb
+++ b/lib/gitlab/sidekiq_middleware/memory_killer.rb
@@ -14,9 +14,12 @@ module Gitlab
# shut Sidekiq down
MUTEX = Mutex.new
+ attr_reader :worker
+
def call(worker, job, queue)
yield
+ @worker = worker
current_rss = get_rss
return unless MAX_RSS > 0 && current_rss > MAX_RSS
@@ -25,9 +28,11 @@ module Gitlab
# Return if another thread is already waiting to shut Sidekiq down
next unless MUTEX.try_lock
- Sidekiq.logger.warn "Sidekiq worker PID-#{pid} current RSS #{current_rss}"\
- " exceeds maximum RSS #{MAX_RSS} after finishing job #{worker.class} JID-#{job['jid']}"
- Sidekiq.logger.warn "Sidekiq worker PID-#{pid} will stop fetching new jobs in #{GRACE_TIME} seconds, and will be shut down #{SHUTDOWN_WAIT} seconds later"
+ warn("Sidekiq worker PID-#{pid} current RSS #{current_rss}"\
+ " exceeds maximum RSS #{MAX_RSS} after finishing job #{worker.class} JID-#{job['jid']}")
+
+ warn("Sidekiq worker PID-#{pid} will stop fetching new jobs"\
+ " in #{GRACE_TIME} seconds, and will be shut down #{SHUTDOWN_WAIT} seconds later")
# Wait `GRACE_TIME` to give the memory intensive job time to finish.
# Then, tell Sidekiq to stop fetching new jobs.
@@ -59,24 +64,28 @@ module Gitlab
def wait_and_signal_pgroup(time, signal, explanation)
return wait_and_signal(time, signal, explanation) unless Process.getpgrp == pid
- Sidekiq.logger.warn "waiting #{time} seconds before sending Sidekiq worker PGRP-#{pid} #{signal} (#{explanation})"
+ warn("waiting #{time} seconds before sending Sidekiq worker PGRP-#{pid} #{signal} (#{explanation})", signal: signal)
sleep(time)
- Sidekiq.logger.warn "sending Sidekiq worker PGRP-#{pid} #{signal} (#{explanation})"
+ warn("sending Sidekiq worker PGRP-#{pid} #{signal} (#{explanation})", signal: signal)
Process.kill(signal, 0)
end
def wait_and_signal(time, signal, explanation)
- Sidekiq.logger.warn "waiting #{time} seconds before sending Sidekiq worker PID-#{pid} #{signal} (#{explanation})"
+ warn("waiting #{time} seconds before sending Sidekiq worker PID-#{pid} #{signal} (#{explanation})", signal: signal)
sleep(time)
- Sidekiq.logger.warn "sending Sidekiq worker PID-#{pid} #{signal} (#{explanation})"
+ warn("sending Sidekiq worker PID-#{pid} #{signal} (#{explanation})", signal: signal)
Process.kill(signal, pid)
end
def pid
Process.pid
end
+
+ def warn(message, signal: nil)
+ Sidekiq.logger.warn(class: worker.class.name, pid: pid, signal: signal, message: message)
+ end
end
end
end
diff --git a/lib/gitlab/sidekiq_middleware/metrics.rb b/lib/gitlab/sidekiq_middleware/metrics.rb
new file mode 100644
index 00000000000..b06ffa9c121
--- /dev/null
+++ b/lib/gitlab/sidekiq_middleware/metrics.rb
@@ -0,0 +1,48 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module SidekiqMiddleware
+ class Metrics
+ def initialize
+ @metrics = init_metrics
+ end
+
+ def call(_worker, job, queue)
+ labels = create_labels(queue)
+ @metrics[:sidekiq_running_jobs].increment(labels, 1)
+
+ if job['retry_count'].present?
+ @metrics[:sidekiq_jobs_retried_total].increment(labels, 1)
+ end
+
+ realtime = Benchmark.realtime do
+ yield
+ end
+
+ @metrics[:sidekiq_jobs_completion_seconds].observe(labels, realtime)
+ rescue Exception # rubocop: disable Lint/RescueException
+ @metrics[:sidekiq_jobs_failed_total].increment(labels, 1)
+ raise
+ ensure
+ @metrics[:sidekiq_running_jobs].increment(labels, -1)
+ end
+
+ private
+
+ def init_metrics
+ {
+ sidekiq_jobs_completion_seconds: ::Gitlab::Metrics.histogram(:sidekiq_jobs_completion_seconds, 'Seconds to complete sidekiq job'),
+ sidekiq_jobs_failed_total: ::Gitlab::Metrics.counter(:sidekiq_jobs_failed_total, 'Sidekiq jobs failed'),
+ sidekiq_jobs_retried_total: ::Gitlab::Metrics.counter(:sidekiq_jobs_retried_total, 'Sidekiq jobs retried'),
+ sidekiq_running_jobs: ::Gitlab::Metrics.gauge(:sidekiq_running_jobs, 'Number of Sidekiq jobs running', {}, :livesum)
+ }
+ end
+
+ def create_labels(queue)
+ {
+ queue: queue
+ }
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/slug/environment.rb b/lib/gitlab/slug/environment.rb
new file mode 100644
index 00000000000..1b87d3bb626
--- /dev/null
+++ b/lib/gitlab/slug/environment.rb
@@ -0,0 +1,58 @@
+# frozen_string_literal: true
+
+# An environment name is not necessarily suitable for use in URLs, DNS
+# or other third-party contexts, so provide a slugified version. A slug has
+# the following properties:
+# * contains only lowercase letters (a-z), numbers (0-9), and '-'
+# * begins with a letter
+# * has a maximum length of 24 bytes (OpenShift limitation)
+# * cannot end with `-`
+module Gitlab
+ module Slug
+ class Environment
+ attr_reader :name
+
+ def initialize(name)
+ @name = name
+ end
+
+ def generate
+ # Lowercase letters and numbers only
+ slugified = name.to_s.downcase.gsub(/[^a-z0-9]/, '-')
+
+ # Must start with a letter
+ slugified = 'env-' + slugified unless slugified.match?(/^[a-z]/)
+
+ # Repeated dashes are invalid (OpenShift limitation)
+ slugified.squeeze!('-')
+
+ slugified =
+ if slugified.size > 24 || slugified != name
+ # Maximum length: 24 characters (OpenShift limitation)
+ shorten_and_add_suffix(slugified)
+ else
+ # Cannot end with a dash (Kubernetes label limitation)
+ slugified.chomp('-')
+ end
+
+ slugified
+ end
+
+ private
+
+ def shorten_and_add_suffix(slug)
+ slug = slug[0..16]
+ slug << '-' unless slug.ends_with?('-')
+ slug << suffix
+ end
+
+ # Slugifying a name may remove the uniqueness guarantee afforded by it being
+ # based on name (which must be unique). To compensate, we add a predictable
+ # 6-byte suffix in those circumstances. This is not *guaranteed* uniqueness,
+ # but the chance of collisions is vanishingly small
+ def suffix
+ Digest::SHA2.hexdigest(name.to_s).to_i(16).to_s(36).last(6)
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/submodule_links.rb b/lib/gitlab/submodule_links.rb
new file mode 100644
index 00000000000..18fd604a3b0
--- /dev/null
+++ b/lib/gitlab/submodule_links.rb
@@ -0,0 +1,31 @@
+# frozen_string_literal: true
+
+module Gitlab
+ class SubmoduleLinks
+ include Gitlab::Utils::StrongMemoize
+
+ def initialize(repository)
+ @repository = repository
+ end
+
+ def for(submodule, sha)
+ submodule_url = submodule_url_for(sha, submodule.path)
+ SubmoduleHelper.submodule_links_for_url(submodule.id, submodule_url, repository)
+ end
+
+ private
+
+ attr_reader :repository
+
+ def submodule_urls_for(sha)
+ strong_memoize(:"submodule_urls_for_#{sha}") do
+ repository.submodule_urls_for(sha)
+ end
+ end
+
+ def submodule_url_for(sha, path)
+ urls = submodule_urls_for(sha)
+ urls && urls[path]
+ end
+ end
+end
diff --git a/lib/gitlab/url_blocker.rb b/lib/gitlab/url_blocker.rb
index f6b2e2acf16..9c35d200dcb 100644
--- a/lib/gitlab/url_blocker.rb
+++ b/lib/gitlab/url_blocker.rb
@@ -45,18 +45,21 @@ module Gitlab
ascii_only: ascii_only
)
+ normalized_hostname = uri.normalized_host
hostname = uri.hostname
port = get_port(uri)
address_info = get_address_info(hostname, port)
return [uri, nil] unless address_info
- protected_uri_with_hostname = enforce_uri_hostname(address_info, uri, hostname, dns_rebind_protection)
+ ip_address = ip_address(address_info)
+ protected_uri_with_hostname = enforce_uri_hostname(ip_address, uri, hostname, dns_rebind_protection)
# Allow url from the GitLab instance itself but only for the configured hostname and ports
return protected_uri_with_hostname if internal?(uri)
validate_local_request(
+ normalized_hostname: normalized_hostname,
address_info: address_info,
allow_localhost: allow_localhost,
allow_local_network: allow_local_network
@@ -83,10 +86,7 @@ module Gitlab
#
# The original hostname is used to validate the SSL, given in that scenario
# we'll be making the request to the IP address, instead of using the hostname.
- def enforce_uri_hostname(addrs_info, uri, hostname, dns_rebind_protection)
- address = addrs_info.first
- ip_address = address&.ip_address
-
+ def enforce_uri_hostname(ip_address, uri, hostname, dns_rebind_protection)
return [uri, nil] unless dns_rebind_protection && ip_address && ip_address != hostname
uri = uri.dup
@@ -94,6 +94,10 @@ module Gitlab
[uri, hostname]
end
+ def ip_address(address_info)
+ address_info.first&.ip_address
+ end
+
def validate_uri(uri:, schemes:, ports:, enforce_sanitization:, enforce_user:, ascii_only:)
validate_html_tags(uri) if enforce_sanitization
@@ -111,11 +115,30 @@ module Gitlab
addr.ipv6_v4mapped? ? addr.ipv6_to_ipv4 : addr
end
rescue SocketError
+ # In the test suite we use a lot of mocked urls that are either invalid or
+ # don't exist. In order to avoid modifying a ton of tests and factories
+ # we allow invalid urls unless the environment variable RSPEC_ALLOW_INVALID_URLS
+ # is not true
+ return if Rails.env.test? && ENV['RSPEC_ALLOW_INVALID_URLS'] == 'true'
+
+ # If the addr can't be resolved or the url is invalid (i.e http://1.1.1.1.1)
+ # we block the url
+ raise BlockedUrlError, "Host cannot be resolved or invalid"
end
- def validate_local_request(address_info:, allow_localhost:, allow_local_network:)
+ def validate_local_request(
+ normalized_hostname:,
+ address_info:,
+ allow_localhost:,
+ allow_local_network:)
return if allow_local_network && allow_localhost
+ ip_whitelist, domain_whitelist =
+ Gitlab::CurrentSettings.outbound_local_requests_whitelist_arrays
+
+ return if local_domain_whitelisted?(domain_whitelist, normalized_hostname) ||
+ local_ip_whitelisted?(ip_whitelist, ip_address(address_info))
+
unless allow_localhost
validate_localhost(address_info)
validate_loopback(address_info)
@@ -231,6 +254,16 @@ module Gitlab
(uri.port.blank? || uri.port == config.gitlab_shell.ssh_port)
end
+ def local_ip_whitelisted?(ip_whitelist, ip_string)
+ ip_obj = Gitlab::Utils.string_to_ip_object(ip_string)
+
+ ip_whitelist.any? { |ip| ip.include?(ip_obj) }
+ end
+
+ def local_domain_whitelisted?(domain_whitelist, domain_string)
+ domain_whitelist.include?(domain_string)
+ end
+
def config
Gitlab.config
end
diff --git a/lib/gitlab/usage_data.rb b/lib/gitlab/usage_data.rb
index 0180fe7fa71..d5657c474c8 100644
--- a/lib/gitlab/usage_data.rb
+++ b/lib/gitlab/usage_data.rb
@@ -6,7 +6,9 @@ module Gitlab
class << self
def data(force_refresh: false)
- Rails.cache.fetch('usage_data', force: force_refresh, expires_in: 2.weeks) { uncached_data }
+ Rails.cache.fetch('usage_data', force: force_refresh, expires_in: 2.weeks) do
+ uncached_data
+ end
end
def uncached_data
@@ -128,10 +130,18 @@ module Gitlab
}
end
+ # @return [Hash<Symbol, Integer>]
def usage_counters
- {
- web_ide_commits: Gitlab::WebIdeCommitsCounter.total_count
- }
+ usage_data_counters.map(&:totals).reduce({}) { |a, b| a.merge(b) }
+ end
+
+ # @return [Array<#totals>] An array of objects that respond to `#totals`
+ def usage_data_counters
+ [
+ Gitlab::UsageDataCounters::WikiPageCounter,
+ Gitlab::UsageDataCounters::WebIdeCounter,
+ Gitlab::UsageDataCounters::SearchCounter
+ ]
end
def components_usage_data
diff --git a/lib/gitlab/usage_data_counters/redis_counter.rb b/lib/gitlab/usage_data_counters/redis_counter.rb
new file mode 100644
index 00000000000..75d5a75e3a4
--- /dev/null
+++ b/lib/gitlab/usage_data_counters/redis_counter.rb
@@ -0,0 +1,17 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module UsageDataCounters
+ module RedisCounter
+ def increment(redis_counter_key)
+ return unless Gitlab::CurrentSettings.usage_ping_enabled
+
+ Gitlab::Redis::SharedState.with { |redis| redis.incr(redis_counter_key) }
+ end
+
+ def total_count(redis_counter_key)
+ Gitlab::Redis::SharedState.with { |redis| redis.get(redis_counter_key).to_i }
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/usage_data_counters/search_counter.rb b/lib/gitlab/usage_data_counters/search_counter.rb
new file mode 100644
index 00000000000..5f0735347e1
--- /dev/null
+++ b/lib/gitlab/usage_data_counters/search_counter.rb
@@ -0,0 +1,27 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module UsageDataCounters
+ class SearchCounter
+ extend RedisCounter
+
+ NAVBAR_SEARCHES_COUNT_KEY = 'NAVBAR_SEARCHES_COUNT'
+
+ class << self
+ def increment_navbar_searches_count
+ increment(NAVBAR_SEARCHES_COUNT_KEY)
+ end
+
+ def total_navbar_searches_count
+ total_count(NAVBAR_SEARCHES_COUNT_KEY)
+ end
+
+ def totals
+ {
+ navbar_searches: total_navbar_searches_count
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/usage_data_counters/web_ide_counter.rb b/lib/gitlab/usage_data_counters/web_ide_counter.rb
new file mode 100644
index 00000000000..0718c1dd761
--- /dev/null
+++ b/lib/gitlab/usage_data_counters/web_ide_counter.rb
@@ -0,0 +1,47 @@
+# frozen_string_literal: true
+
+module Gitlab
+ module UsageDataCounters
+ class WebIdeCounter
+ extend RedisCounter
+
+ COMMITS_COUNT_KEY = 'WEB_IDE_COMMITS_COUNT'
+ MERGE_REQUEST_COUNT_KEY = 'WEB_IDE_MERGE_REQUESTS_COUNT'
+ VIEWS_COUNT_KEY = 'WEB_IDE_VIEWS_COUNT'
+
+ class << self
+ def increment_commits_count
+ increment(COMMITS_COUNT_KEY)
+ end
+
+ def total_commits_count
+ total_count(COMMITS_COUNT_KEY)
+ end
+
+ def increment_merge_requests_count
+ increment(MERGE_REQUEST_COUNT_KEY)
+ end
+
+ def total_merge_requests_count
+ total_count(MERGE_REQUEST_COUNT_KEY)
+ end
+
+ def increment_views_count
+ increment(VIEWS_COUNT_KEY)
+ end
+
+ def total_views_count
+ total_count(VIEWS_COUNT_KEY)
+ end
+
+ def totals
+ {
+ web_ide_commits: total_commits_count,
+ web_ide_views: total_views_count,
+ web_ide_merge_requests: total_merge_requests_count
+ }
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/usage_data_counters/wiki_page_counter.rb b/lib/gitlab/usage_data_counters/wiki_page_counter.rb
new file mode 100644
index 00000000000..c8b59a3160c
--- /dev/null
+++ b/lib/gitlab/usage_data_counters/wiki_page_counter.rb
@@ -0,0 +1,32 @@
+# frozen_string_literal: true
+
+module Gitlab::UsageDataCounters
+ class WikiPageCounter
+ extend RedisCounter
+
+ KNOWN_EVENTS = %w[create update delete].map(&:freeze).freeze
+
+ UnknownEvent = Class.new(StandardError)
+
+ class << self
+ # Each event gets a unique Redis key
+ def redis_key(event)
+ raise UnknownEvent, event unless KNOWN_EVENTS.include?(event.to_s)
+
+ "USAGE_WIKI_PAGES_#{event}".upcase
+ end
+
+ def count(event)
+ increment(redis_key event)
+ end
+
+ def read(event)
+ total_count(redis_key event)
+ end
+
+ def totals
+ KNOWN_EVENTS.map { |e| ["wiki_pages_#{e}".to_sym, read(e)] }.to_h
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/utils.rb b/lib/gitlab/utils.rb
index 16ec8a8bb28..c66ce0434a4 100644
--- a/lib/gitlab/utils.rb
+++ b/lib/gitlab/utils.rb
@@ -22,7 +22,7 @@ module Gitlab
end
def force_utf8(str)
- str.force_encoding(Encoding::UTF_8)
+ str.dup.force_encoding(Encoding::UTF_8)
end
def ensure_utf8_size(str, bytes:)
@@ -131,5 +131,12 @@ module Gitlab
data
end
end
+
+ def string_to_ip_object(str)
+ return unless str
+
+ IPAddr.new(str)
+ rescue IPAddr::InvalidAddressError
+ end
end
end
diff --git a/lib/gitlab/utils/sanitize_node_link.rb b/lib/gitlab/utils/sanitize_node_link.rb
new file mode 100644
index 00000000000..620d71a7814
--- /dev/null
+++ b/lib/gitlab/utils/sanitize_node_link.rb
@@ -0,0 +1,61 @@
+# frozen_string_literal: true
+
+require_dependency 'gitlab/utils'
+
+module Gitlab
+ module Utils
+ module SanitizeNodeLink
+ UNSAFE_PROTOCOLS = %w(data javascript vbscript).freeze
+ ATTRS_TO_SANITIZE = %w(href src data-src).freeze
+
+ def remove_unsafe_links(env, remove_invalid_links: true)
+ node = env[:node]
+
+ sanitize_node(node: node, remove_invalid_links: remove_invalid_links)
+
+ # HTML entities such as <video></video> have scannable attrs in
+ # children elements, which also need to be sanitized.
+ #
+ node.children.each do |child_node|
+ sanitize_node(node: child_node, remove_invalid_links: remove_invalid_links)
+ end
+ end
+
+ # Remove all invalid scheme characters before checking against the
+ # list of unsafe protocols.
+ #
+ # See https://tools.ietf.org/html/rfc3986#section-3.1
+ #
+ def safe_protocol?(scheme)
+ return false unless scheme
+
+ scheme = scheme
+ .strip
+ .downcase
+ .gsub(/[^A-Za-z\+\.\-]+/, '')
+
+ UNSAFE_PROTOCOLS.none?(scheme)
+ end
+
+ private
+
+ def sanitize_node(node:, remove_invalid_links: true)
+ ATTRS_TO_SANITIZE.each do |attr|
+ next unless node.has_attribute?(attr)
+
+ begin
+ node[attr] = node[attr].strip
+ uri = Addressable::URI.parse(node[attr])
+
+ next unless uri.scheme
+ next if safe_protocol?(uri.scheme)
+
+ node.remove_attribute(attr)
+ rescue Addressable::URI::InvalidURIError
+ node.remove_attribute(attr) if remove_invalid_links
+ end
+ end
+ end
+ end
+ end
+end
diff --git a/lib/gitlab/web_ide_commits_counter.rb b/lib/gitlab/web_ide_commits_counter.rb
deleted file mode 100644
index 1cd9b5295b9..00000000000
--- a/lib/gitlab/web_ide_commits_counter.rb
+++ /dev/null
@@ -1,17 +0,0 @@
-# frozen_string_literal: true
-
-module Gitlab
- module WebIdeCommitsCounter
- WEB_IDE_COMMITS_KEY = "WEB_IDE_COMMITS_COUNT".freeze
-
- class << self
- def increment
- Gitlab::Redis::SharedState.with { |redis| redis.incr(WEB_IDE_COMMITS_KEY) }
- end
-
- def total_count
- Gitlab::Redis::SharedState.with { |redis| redis.get(WEB_IDE_COMMITS_KEY).to_i }
- end
- end
- end
-end
diff --git a/lib/gitlab/workhorse.rb b/lib/gitlab/workhorse.rb
index 46a7b5b982a..3b77fe838ae 100644
--- a/lib/gitlab/workhorse.rb
+++ b/lib/gitlab/workhorse.rb
@@ -221,7 +221,7 @@ module Gitlab
end
def set_key_and_notify(key, value, expire: nil, overwrite: true)
- Gitlab::Redis::Queues.with do |redis|
+ Gitlab::Redis::SharedState.with do |redis|
result = redis.set(key, value, ex: expire, nx: !overwrite)
if result
redis.publish(NOTIFICATION_CHANNEL, "#{key}=#{value}")
diff --git a/lib/gitlab/zoom_link_extractor.rb b/lib/gitlab/zoom_link_extractor.rb
new file mode 100644
index 00000000000..7ac14eb2d4f
--- /dev/null
+++ b/lib/gitlab/zoom_link_extractor.rb
@@ -0,0 +1,25 @@
+# frozen_string_literal: true
+
+# Detect links matching the following formats:
+# Zoom Start links: https://zoom.us/s/<meeting-id>
+# Zoom Join links: https://zoom.us/j/<meeting-id>
+# Personal Zoom links: https://zoom.us/my/<meeting-id>
+# Vanity Zoom links: https://gitlab.zoom.us/j/<meeting-id> (also /s and /my)
+
+module Gitlab
+ class ZoomLinkExtractor
+ ZOOM_REGEXP = %r{https://(?:[\w-]+\.)?zoom\.us/(?:s|j|my)/\S+}.freeze
+
+ def initialize(text)
+ @text = text.to_s
+ end
+
+ def links
+ @text.scan(ZOOM_REGEXP)
+ end
+
+ def match?
+ ZOOM_REGEXP.match?(@text)
+ end
+ end
+end