Commit 0f98b0e3 authored by Bob Van Landuyt's avatar Bob Van Landuyt

Add caller_id to the context for cron workers

This always sets the caller_id to "Cronjob" for these workers, this
would otherwise be nil.

Sometimes we do call the cron worker from somewhere else, in this case
we don't want to overwrite the caller id.
parent 9d0e91a0
......@@ -10,4 +10,14 @@ module CronjobQueue
sidekiq_options retry: false
worker_context project: nil, namespace: nil, user: nil
end
class_methods do
# Cronjobs never get scheduled with arguments, so this is safe to
# override
def context_for_arguments(_args)
return if Gitlab::ApplicationContext.current_context_include?('meta.caller_id')
Gitlab::ApplicationContext.new(caller_id: "Cronjob")
end
end
end
......@@ -25,6 +25,10 @@ module Gitlab
Labkit::Context.push(application_context.to_lazy_hash)
end
def self.current_context_include?(attribute_name)
Labkit::Context.current.to_h.include?(Labkit::Context.log_key(attribute_name))
end
def initialize(**args)
unknown_attributes = args.keys - APPLICATION_ATTRIBUTES.map(&:name)
raise ArgumentError, "#{unknown_attributes} are not known keys" if unknown_attributes.any?
......
......@@ -42,6 +42,18 @@ describe Gitlab::ApplicationContext do
end
end
describe '.current_context_include?' do
it 'returns true if the key was present in the context' do
described_class.with_context(caller_id: "Hello") do
expect(described_class.current_context_include?(:caller_id)).to be(true)
end
end
it 'returns false if the key was not present in the current context' do
expect(described_class.current_context_include?(:caller_id)).to be(false)
end
end
describe '#to_lazy_hash' do
let(:user) { build(:user) }
let(:project) { build(:project) }
......
......@@ -14,6 +14,10 @@ describe CronjobQueue do
end
end
before do
stub_const("DummyWorker", worker)
end
it 'sets the queue name of a worker' do
expect(worker.sidekiq_options['queue'].to_s).to eq('cronjob:dummy')
end
......@@ -29,4 +33,22 @@ describe CronjobQueue do
expect(worker_context[:root_namespace]).to be_nil
expect(worker_context[:project]).to be_nil
end
it 'gets scheduled with caller_id set to Cronjob' do
worker.perform_async
job = worker.jobs.last
expect(job).to include('meta.caller_id' => 'Cronjob')
end
it 'does not set the caller_id if there was already one in the context' do
Gitlab::ApplicationContext.with_context(caller_id: 'already set') do
worker.perform_async
end
job = worker.jobs.last
expect(job).to include('meta.caller_id' => 'already set')
end
end
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment