From 7f5337c0e25608252d978196851a2785d8b2c5eb Mon Sep 17 00:00:00 2001 From: Holger Just Date: Wed, 2 Oct 2019 16:29:17 +0200 Subject: [PATCH] Refactor exclusive file locking and include error handling --- lib/rackstash/adapter/file.rb | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/lib/rackstash/adapter/file.rb b/lib/rackstash/adapter/file.rb index 5a90b8d..7943d41 100644 --- a/lib/rackstash/adapter/file.rb +++ b/lib/rackstash/adapter/file.rb @@ -200,11 +200,7 @@ module Rackstash @mutex.synchronize do rotate_file - - with_exclusive_lock = lock? - @file.flock(::File::LOCK_EX) if with_exclusive_lock - @file.syswrite(line) - @file.flock(::File::LOCK_UN) if with_exclusive_lock + with_flock { @file.syswrite(line) } end nil end @@ -296,6 +292,17 @@ module Rackstash suffix = ".#{suffix}" @base_path.sub(/\A(.*?)(\.[^.\/]+)?\z/) { "#{$1}#{suffix}#{$2}" } end + + def with_flock + return yield unless lock? + + begin + @file.flock(::File::LOCK_EX) + yield + ensure + @file.flock(::File::LOCK_UN) + end + end end end end