Skip to content
Snippets Groups Projects
Unverified Commit 88e627cf authored by Yorick Peterse's avatar Yorick Peterse
Browse files

Fix race conditions for AuthorizedProjectsWorker

There were two cases that could be problematic:

1. Because sometimes AuthorizedProjectsWorker would be scheduled in a
   transaction it was possible for a job to run/complete before a
   COMMIT; resulting in it either producing an error, or producing no
   new data.

2. When scheduling jobs the code would not wait until completion. This
   could lead to a user creating a project and then immediately trying
   to push to it. Usually this will work fine, but given enough load it
   might take a few seconds before a user has access.

The first one is problematic, the second one is mostly just annoying
(but annoying enough to warrant a solution).

This commit changes two things to deal with this:

1. Sidekiq scheduling now takes places after a COMMIT, this is ensured
   by scheduling using Rails' after_commit hook instead of doing so in
   an arbitrary method.

2. When scheduling jobs the calling thread now waits for all jobs to
   complete.

Solution 2 requires tracking of job completions. Sidekiq provides a way
to find a job by its ID, but this involves scanning over the entire
queue; something that is very in-efficient for large queues. As such a
more efficient solution is necessary. There are two main Gems that can
do this in a more efficient manner:

* sidekiq-status
* sidekiq_status

No, this is not a joke. Both Gems do a similar thing (but slightly
different), and the only difference in their name is a dash vs an
underscore. Both Gems however provide far more than just checking if a
job has been completed, and both have their problems. sidekiq-status
does not appear to be actively maintained, with the last release being
in 2015. It also has some issues during testing as API calls are not
stubbed in any way. sidekiq_status on the other hand does not appear to
be very popular, and introduces a similar amount of code.

Because of this I opted to write a simple home grown solution. After
all, all we need is storing a job ID somewhere so we can efficiently
look it up; we don't need extra web UIs (as provided by sidekiq-status)
or complex APIs to update progress, etc.

This is where Gitlab::SidekiqStatus comes in handy. This namespace
contains some code used for tracking, removing, and looking up job IDs;
all without having to scan over an entire queue. Data is removed
explicitly, but also expires automatically just in case.

Using this API we can now schedule jobs in a fork-join like manner: we
schedule the jobs in Sidekiq, process them in parallel, then wait for
completion. By using Sidekiq we can leverage all the benefits such as
being able to scale across multiple cores and hosts, retrying failed
jobs, etc.

The one downside is that we need to make sure we can deal with
unexpected increases in job processing timings. To deal with this the
class Gitlab::JobWaiter (used for waiting for jobs to complete) will
only wait a number of seconds (30 by default). Once this timeout is
reached it will simply return.

For GitLab.com almost all AuthorizedProjectWorker jobs complete in
seconds, only very rarely do we spike to job timings of around a minute.
These in turn seem to be the result of external factors (e.g. deploys),
in which case a user is most likely not able to use the system anyway.

In short, this new solution should ensure that jobs are processed
properly and that in almost all cases a user has access to their
resources whenever they need to have access.
parent 3a54128d
No related branches found
No related tags found
No related merge requests found
Showing
with 70 additions and 25 deletions
Loading
Loading
@@ -322,7 +322,7 @@ group :test do
gem 'email_spec', '~> 1.6.0'
gem 'json-schema', '~> 2.6.2'
gem 'webmock', '~> 1.21.0'
gem 'test_after_commit', '~> 0.4.2'
gem 'test_after_commit', '~> 1.1'
gem 'sham_rack', '~> 1.3.6'
gem 'timecop', '~> 0.8.0'
end
Loading
Loading
Loading
Loading
@@ -760,7 +760,7 @@ GEM
teaspoon-jasmine (2.2.0)
teaspoon (>= 1.0.0)
temple (0.7.7)
test_after_commit (0.4.2)
test_after_commit (1.1.0)
activerecord (>= 3.2)
thin (1.7.0)
daemons (~> 1.0, >= 1.0.9)
Loading
Loading
@@ -997,7 +997,7 @@ DEPENDENCIES
sys-filesystem (~> 1.1.6)
teaspoon (~> 1.1.0)
teaspoon-jasmine (~> 2.2.0)
test_after_commit (~> 0.4.2)
test_after_commit (~> 1.1)
thin (~> 1.7.0)
timecop (~> 0.8.0)
truncato (~> 0.7.8)
Loading
Loading
Loading
Loading
@@ -68,9 +68,9 @@ class Member < ActiveRecord::Base
after_create :send_request, if: :request?, unless: :importing?
after_create :create_notification_setting, unless: [:pending?, :importing?]
after_create :post_create_hook, unless: [:pending?, :importing?]
after_create :refresh_member_authorized_projects, if: :importing?
after_update :post_update_hook, unless: [:pending?, :importing?]
after_destroy :post_destroy_hook, unless: :pending?
after_commit :refresh_member_authorized_projects
 
delegate :name, :username, :email, to: :user, prefix: true
 
Loading
Loading
@@ -147,8 +147,6 @@ class Member < ActiveRecord::Base
member.save
end
 
UserProjectAccessChangedService.new(user.id).execute if user.is_a?(User)
member
end
 
Loading
Loading
@@ -275,23 +273,27 @@ class Member < ActiveRecord::Base
end
 
def post_create_hook
UserProjectAccessChangedService.new(user.id).execute
system_hook_service.execute_hooks_for(self, :create)
end
 
def post_update_hook
UserProjectAccessChangedService.new(user.id).execute if access_level_changed?
# override in sub class
end
 
def post_destroy_hook
refresh_member_authorized_projects
system_hook_service.execute_hooks_for(self, :destroy)
end
 
# Refreshes authorizations of the current member.
#
# This method schedules a job using Sidekiq and as such **must not** be called
# in a transaction. Doing so can lead to the job running before the
# transaction has been committed, resulting in the job either throwing an
# error or not doing any meaningful work.
def refresh_member_authorized_projects
# If user/source is being destroyed, project access are gonna be destroyed eventually
# because of DB foreign keys, so we shouldn't bother with refreshing after each
# member is destroyed through association
# If user/source is being destroyed, project access are going to be
# destroyed eventually because of DB foreign keys, so we shouldn't bother
# with refreshing after each member is destroyed through association
return if destroyed_by_association.present?
 
UserProjectAccessChangedService.new(user_id).execute
Loading
Loading
Loading
Loading
@@ -16,8 +16,7 @@ class ProjectGroupLink < ActiveRecord::Base
validates :group_access, inclusion: { in: Gitlab::Access.values }, presence: true
validate :different_group
 
after_create :refresh_group_members_authorized_projects
after_destroy :refresh_group_members_authorized_projects
after_commit :refresh_group_members_authorized_projects
 
def self.access_options
Gitlab::Access.options
Loading
Loading
Loading
Loading
@@ -4,6 +4,6 @@ class UserProjectAccessChangedService
end
 
def execute
AuthorizedProjectsWorker.bulk_perform_async(@user_ids.map { |id| [id] })
AuthorizedProjectsWorker.bulk_perform_and_wait(@user_ids.map { |id| [id] })
end
end
Loading
Loading
@@ -2,6 +2,13 @@ class AuthorizedProjectsWorker
include Sidekiq::Worker
include DedicatedSidekiqQueue
 
# Schedules multiple jobs and waits for them to be completed.
def self.bulk_perform_and_wait(args_list)
job_ids = bulk_perform_async(args_list)
Gitlab::JobWaiter.new(job_ids).wait
end
def self.bulk_perform_async(args_list)
Sidekiq::Client.push_bulk('class' => self, 'args' => args_list)
end
Loading
Loading
---
title: Fix race conditions for AuthorizedProjectsWorker
merge_request:
author:
Loading
Loading
@@ -12,6 +12,11 @@ Sidekiq.configure_server do |config|
chain.add Gitlab::SidekiqMiddleware::ArgumentsLogger if ENV['SIDEKIQ_LOG_ARGUMENTS']
chain.add Gitlab::SidekiqMiddleware::MemoryKiller if ENV['SIDEKIQ_MEMORY_KILLER_MAX_RSS']
chain.add Gitlab::SidekiqMiddleware::RequestStoreMiddleware unless ENV['SIDEKIQ_REQUEST_STORE'] == '0'
chain.add Gitlab::SidekiqStatus::ServerMiddleware
end
config.client_middleware do |chain|
chain.add Gitlab::SidekiqStatus::ClientMiddleware
end
 
# Sidekiq-cron: load recurring jobs from gitlab.yml
Loading
Loading
@@ -46,6 +51,10 @@ end
 
Sidekiq.configure_client do |config|
config.redis = redis_config_hash
config.client_middleware do |chain|
chain.add Gitlab::SidekiqStatus::ClientMiddleware
end
end
 
# The Sidekiq client API always adds the queue to the Sidekiq queue
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
User.seed do |s|
s.id = 1
Loading
Loading
require 'sidekiq/testing'
require './spec/support/sidekiq'
 
Sidekiq::Testing.inline! do
Gitlab::Seeder.quiet do
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
20.times do |i|
begin
Loading
Loading
require 'sidekiq/testing'
require './spec/support/sidekiq'
 
Sidekiq::Testing.inline! do
Gitlab::Seeder.quiet do
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
Project.all.each do |project|
5.times do |i|
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
Project.all.each do |project|
10.times do
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
# Limit the number of merge requests per project to avoid long seeds
MAX_NUM_MERGE_REQUESTS = 10
Loading
Loading
Gitlab::Seeder.quiet do
User.first(10).each do |user|
key = "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt#{user.id + 100}6k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9wa++Oi7Qkr8prgHc4soW6NUlfDzpvZK2H5E7eQaSeP3SAwGmQKUFHCddNaP0L+hM7zhFNzjFvpaMgJw0="
require './spec/support/sidekiq'
 
user.keys.create(
title: "Sample key #{user.id}",
key: key
)
# Creating keys runs a gitlab-shell worker. Since we may not have the right
# gitlab-shell path set (yet) we need to disable this for these fixtures.
Sidekiq::Testing.disable! do
Gitlab::Seeder.quiet do
User.first(10).each do |user|
key = "ssh-rsa AAAAB3NzaC1yc2EAAAABJQAAAIEAiPWx6WM4lhHNedGfBpPJNPpZ7yKu+dnn1SJejgt#{user.id + 100}6k6YjzGGphH2TUxwKzxcKDKKezwkpfnxPkSMkuEspGRt/aZZ9wa++Oi7Qkr8prgHc4soW6NUlfDzpvZK2H5E7eQaSeP3SAwGmQKUFHCddNaP0L+hM7zhFNzjFvpaMgJw0="
 
print '.'
user.keys.create(
title: "Sample key #{user.id}",
key: key
)
print '.'
end
end
end
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
content =<<eos
class Member < ActiveRecord::Base
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
Issue.all.each do |issue|
project = issue.project
Loading
Loading
require './spec/support/sidekiq'
class Gitlab::Seeder::Pipelines
STAGES = %w[build test deploy notify]
BUILDS = [
Loading
Loading
require './spec/support/sidekiq'
Gitlab::Seeder.quiet do
emoji = Gitlab::AwardEmoji.emojis.keys
 
Loading
Loading
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment