Skip to content

Commit

Permalink
Add testcase for worker lock functions
Browse files Browse the repository at this point in the history
Signed-off-by: Fujimoto Seiji <[email protected]>
  • Loading branch information
fujimotos committed Jul 1, 2022
1 parent 0a7a590 commit d31631e
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
10 changes: 6 additions & 4 deletions lib/fluent/plugin/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,16 @@ def multi_workers_ready?
true
end

def worker_lockfile(name)
name = name.gsub(/[^a-zA-Z0-9]/, "_")
File.join(fluentd_lockdir, "fluentd-#{name}.lock")
end

def acquire_worker_lock(name)
if fluentd_lockdir.nil?
raise InvalidLockDirectory, "can't acquire lock because FLUENTD_LOCKDIR isn't set"
end

name = name.gsub(/[^a-zA-Z0-9]/, "_")
lockfile = "fluentd-#{name}.lock"
File.open(File.join(fluentd_lockdir, lockfile), "w") do |f|
File.open(worker_lockfile(name), "w") do |f|
f.flock(File::LOCK_EX)
yield
end
Expand Down
22 changes: 22 additions & 0 deletions test/plugin/test_base.rb
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
require_relative '../helper'
require 'tmpdir'
require 'fluent/plugin/base'

module FluentPluginBaseTest
Expand Down Expand Up @@ -112,4 +113,25 @@ class FluentPluginBaseTest::DummyPlugin2 < Fluent::Plugin::TestBase
assert_equal 1, logger.logs.size
assert{ logger.logs.first.include?("invalid byte sequence is replaced in ") }
end

test 'acquire worker lock' do
Dir.mktmpdir("test-fluentd-lock-") do |lockdir|
ENV['FLUENTD_LOCKDIR'] = lockdir
lockfile = @p.worker_lockfile("worker_test")

@p.acquire_worker_lock("worker_test") do
# With LOCK_NB set, flock() returns `false` when the
# file is already locked.
File.open(lockfile, "w") do |f|
assert_equal false, f.flock(File::LOCK_EX|File::LOCK_NB)
end
end

# Lock should be release by now. In that case, flock
# must return 0.
File.open(lockfile, "w") do |f|
assert_equal 0, f.flock(File::LOCK_EX|File::LOCK_NB)
end
end
end
end

0 comments on commit d31631e

Please sign in to comment.