Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions lib/fluent/env.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@

require 'securerandom'

require 'serverengine/utils'
require 'fluent/platform'
require 'fluent/oj_options'

module Fluent
Expand All @@ -30,16 +30,4 @@ module Fluent
DEFAULT_DIR_PERMISSION = 0755
DEFAULT_FILE_PERMISSION = 0644
INSTANCE_ID = ENV['FLUENT_INSTANCE_ID'] || SecureRandom.uuid

def self.windows?
ServerEngine.windows?
end

def self.linux?
RUBY_PLATFORM.include?("linux")
end

def self.macos?
RUBY_PLATFORM.include?("darwin")
end
end
2 changes: 2 additions & 0 deletions lib/fluent/file_wrapper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
# limitations under the License.
#

require 'fluent/platform'

unless Fluent.windows?
Fluent::FileWrapper = File
else
Expand Down
66 changes: 66 additions & 0 deletions lib/fluent/log.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

require 'forwardable'
require 'logger'
require 'fluent/platform'

module Fluent
class Log
Expand Down Expand Up @@ -771,5 +772,70 @@ def reopen(path, mode)
end
super(path)
end

private

if Fluent.windows? && Gem::Version.new(::Logger::VERSION) >= Gem::Version.new("1.6.3")
require 'fluent/win32api'

# A byte far beyond EOF. Readers of the log never touch it.
ROTATION_LOCK_OFFSET = 2**63 - 2
private_constant :ROTATION_LOCK_OFFSET

# Override Logger::LogDevice#lock_shift_log to work around a problem in logger on Windows.
# Since logger 1.6.3, it locks the whole log file with flock while rotating it. flock on
# Windows is a mandatory lock, so in_tail fails to read the file during the rotation.
# This is the same as the implementation in logger 1.7.0 except that it locks only
# ROTATION_LOCK_OFFSET. The flock of logger 1.6.3 or later covers that byte too, so
# other processes rotating the file with either of them still wait for each other.
# See https://github.com/ruby/logger/issues/188
def lock_shift_log
retry_limit = 8
retry_sleep = 0.1
begin
File.open(@filename, File::WRONLY | File::APPEND | File::SHARE_DELETE | File::BINARY) do |lock|
lock_beyond_eof(lock) do
if File.identical?(@filename, lock) && File.identical?(lock, @dev)
yield
else
# Another process has already rotated the log file.
@dev.close rescue nil
@dev = open_logfile(@filename)
@dev.sync = true
end
end
end
true
rescue Errno::ENOENT
# The log file doesn't exist between the rename and the creation in another process.
if retry_limit <= 0
warn("log rotation inter-process lock failed. #{$!}")
else
sleep retry_sleep
retry_limit -= 1
retry_sleep *= 2
retry
end
end
rescue
warn("log rotation inter-process lock failed. #{$!}")
end

def lock_beyond_eof(file)
handle = Fluent::Win32API._get_osfhandle(file.fileno)
overlapped = [0, 0, ROTATION_LOCK_OFFSET & 0xFFFFFFFF, ROTATION_LOCK_OFFSET >> 32, 0].pack("J2L2J")
# Poll instead of blocking in LockFileEx, so that Thread#raise and Timeout can stop the wait.
while Fluent::Win32API.lock_file_ex_nonblocking(handle, Fluent::Win32API::LOCKFILE_EXCLUSIVE_LOCK, 0, 1, 0, overlapped).zero?
error = Fiddle.win32_last_error
raise IOError, "LockFileEx failed with error #{error}" unless error == Fluent::Win32API::ERROR_LOCK_VIOLATION
sleep 0.01
end
begin
yield
ensure
Fluent::Win32API.UnlockFileEx(handle, 0, 1, 0, overlapped)
end
end
end
end
end
31 changes: 31 additions & 0 deletions lib/fluent/platform.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#
# Fluentd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require 'serverengine/utils'

module Fluent
def self.windows?
ServerEngine.windows?
end

def self.linux?
RUBY_PLATFORM.include?("linux")
end

def self.macos?
RUBY_PLATFORM.include?("darwin")
end
end
21 changes: 20 additions & 1 deletion lib/fluent/win32api.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# limitations under the License.
#

require 'fluent/env'
require 'fluent/platform'

module Fluent
module Win32API
Expand All @@ -34,5 +34,24 @@ module Win32API
extern "intptr_t _get_osfhandle(int)"
extern "BOOL GetFileInformationByHandle(HANDLE, void *)"
extern "BOOL GetFileInformationByHandleEx(HANDLE, int, void *, DWORD)"
extern "BOOL UnlockFileEx(HANDLE, DWORD, DWORD, DWORD, void *)"

LOCKFILE_FAIL_IMMEDIATELY = 0x00000001
LOCKFILE_EXCLUSIVE_LOCK = 0x00000002
ERROR_LOCK_VIOLATION = 33

# Only for LockFileEx with LOCKFILE_FAIL_IMMEDIATELY, which doesn't block. Keep the GVL during the call.
# Otherwise Fiddle reads GetLastError after taking the GVL back, and the error code may be lost.
LOCK_FILE_EX = Fiddle::Function.new(
handler.sym("LockFileEx"),
[Fiddle::TYPE_VOIDP, -Fiddle::TYPE_INT32_T, -Fiddle::TYPE_INT32_T, -Fiddle::TYPE_INT32_T, -Fiddle::TYPE_INT32_T, Fiddle::TYPE_VOIDP],
Fiddle::TYPE_INT,
need_gvl: true,
)
private_constant :LOCK_FILE_EX

def self.lock_file_ex_nonblocking(handle, flags, reserved, bytes_low, bytes_high, overlapped)
LOCK_FILE_EX.call(handle, flags | LOCKFILE_FAIL_IMMEDIATELY, reserved, bytes_low, bytes_high, overlapped)
end
end if Fluent.windows?
end
163 changes: 163 additions & 0 deletions test/test_log.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
require 'fluent/test/driver/input'
require 'fluent/engine'
require 'fluent/log'
require 'fluent/file_wrapper'
require 'timecop'
require 'timeout'
require 'logger'
require 'securerandom'
require 'pathname'
Expand Down Expand Up @@ -763,6 +765,167 @@ def test_log_rotates_specified_size_with_logdevio
end
end

def test_log_can_be_read_by_another_handle_during_rotation
path = "#{@tmp_dir}/log-dev-io-read-during-rotation"
logdev = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)
reader = Fluent::FileWrapper.open(path)

logdev.write("a" * 101 + "\n")

read_during_rotation = nil
logdev.singleton_class.prepend(Module.new do
define_method(:shift_log_age) do
read_during_rotation = begin
reader.read
rescue => e
e
end
super()
end
end)
logdev.write("b\n")

assert_true File.exist?(path + ".0")
assert_kind_of String, read_during_rotation
assert_true read_during_rotation.include?("a" * 101)
ensure
reader&.close
logdev&.close
end

def test_log_rotation_holds_the_inter_process_lock
if Fluent.windows? && Gem::Version.new(Logger::VERSION) < Gem::Version.new("1.6.3")
omit "logger < 1.6.3 doesn't lock the log for rotation on Windows"
end
path = "#{@tmp_dir}/log-dev-io-lock-during-rotation"
logdev = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)

logdev.write("a" * 101 + "\n")

locked_during_rotation = nil
logdev.singleton_class.prepend(Module.new do
define_method(:shift_log_age) do
File.open(path, File::WRONLY | File::APPEND | File::SHARE_DELETE | File::BINARY) do |other|
locked_during_rotation = !other.flock(File::LOCK_EX | File::LOCK_NB)
end
super()
end
end)
logdev.write("b\n")

assert_true File.exist?(path + ".0")
assert_true locked_during_rotation
ensure
logdev&.close
end

def test_log_rotation_waits_for_the_inter_process_lock
omit "LogDeviceIO polls LockFileEx only on Windows" unless Fluent.windows?
if Gem::Version.new(Logger::VERSION) < Gem::Version.new("1.6.3")
omit "logger < 1.6.3 doesn't lock the log for rotation on Windows"
end
path = "#{@tmp_dir}/log-dev-io-wait-for-lock"
logdev = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)
logdev.write("a" * 101 + "\n")

File.open(path, File::WRONLY | File::APPEND | File::SHARE_DELETE | File::BINARY) do |other|
other.flock(File::LOCK_EX)
polls = 0
# Release the lock when the rotation polls for it, instead of sleeping.
logdev.define_singleton_method(:sleep) do |seconds|
return super(seconds) unless caller_locations(1, 1).first.base_label == "lock_beyond_eof"
polls += 1
other.flock(File::LOCK_UN)
end
writer = Thread.new { logdev.write("b\n") }
# A wait that doesn't poll blocks until the lock is released.
unless writer.join(10)
other.flock(File::LOCK_UN)
writer.join
end
assert_equal 1, polls
end

assert_true File.exist?(path + ".0")
assert_equal ["b\n"], File.readlines(path).reject { |line| line.start_with?("#") }
ensure
logdev&.close
end

def test_log_rotation_wait_can_be_interrupted
omit "LogDeviceIO polls LockFileEx only on Windows" unless Fluent.windows?
if Gem::Version.new(Logger::VERSION) < Gem::Version.new("1.6.3")
omit "logger < 1.6.3 doesn't lock the log for rotation on Windows"
end
path = "#{@tmp_dir}/log-dev-io-interrupt-wait"
logdev = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)
logdev.write("a" * 101 + "\n")

File.open(path, File::WRONLY | File::APPEND | File::SHARE_DELETE | File::BINARY) do |other|
other.flock(File::LOCK_EX)
polls = 0
logdev.define_singleton_method(:sleep) do |seconds|
polls += 1 if caller_locations(1, 1).first.base_label == "lock_beyond_eof"
super(seconds)
end
# Release the lock after a while anyway, so that a wait that can't be interrupted fails instead of hanging.
unlocker = Thread.new { sleep 3; other.flock(File::LOCK_UN) }
begin
started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
assert_raise(Timeout::Error) { Timeout.timeout(0.5) { logdev.write("b\n") } }
assert_operator Process.clock_gettime(Process::CLOCK_MONOTONIC) - started, :<, 2
assert_operator polls, :>, 0
ensure
unlocker.kill
unlocker.join
end
end
ensure
logdev&.close
end

def test_log_rotated_by_another_logdevio_is_reopened
if Fluent.windows? && Gem::Version.new(Logger::VERSION) < Gem::Version.new("1.6.3")
omit "logger < 1.6.3 opens the log without File::SHARE_DELETE on Windows, so another device can't rename it"
end
path = "#{@tmp_dir}/log-dev-io-rotated-by-another"
logdev1 = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)
logdev2 = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)

logdev1.write("a" * 101 + "\n")
logdev1.write("b\n")
# logdev2 still writes to the rotated file, which is over shift_size.
logdev2.write("c\n")

assert_false File.exist?(path + ".1")
assert_true File.read(path + ".0").include?("a" * 101)
assert_equal ["b\n", "c\n"], File.readlines(path).reject { |line| line.start_with?("#") }
ensure
logdev1&.close
logdev2&.close
end

def test_log_moved_away_is_reopened_after_retry
if Fluent.windows? && Gem::Version.new(Logger::VERSION) < Gem::Version.new("1.6.3")
omit "logger < 1.6.3 opens the log without File::SHARE_DELETE on Windows, so it can't be moved"
end
path = "#{@tmp_dir}/log-dev-io-moved-away"
logdev = Fluent::LogDeviceIO.new(path, shift_age: 5, shift_size: 100)
logdev.write("a" * 101 + "\n")
File.rename(path, path + ".moved")
# Create the log file again while the rotation waits for it, instead of sleeping.
logdev.define_singleton_method(:sleep) do |_seconds|
File.write(path, "") unless File.exist?(path)
end
logdev.write("b\n")
logdev.write("c\n")

assert_false logdev.dev.closed?
assert_equal ["b\n", "c\n"], File.readlines(path)
ensure
logdev&.close
end

def test_reopen
path = Pathname(@tmp_dir) + "fluent.log"

Expand Down
Loading