Later writes fail with "closed stream" when renaming the log fails during rotation on Windows

Aberta
#189 0 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

Avaliação

Dificuldade
3/5
Tempo estimado
1-2 dias
Facilidade para iniciantes
68/100
Tipo de issue
Bug
Clareza
Claramente especificada
Status de atividade
Ativa
Stack de tecnologia
ruby
Domínio
backend

Direção de pesquisa

Start by reading LogDevice#shift_log_file and the Windows-specific rename and inter-process locking paths described in the issue. Reproduce the failure with the supplied script on Windows, then check the logger tests for rotation behavior and add coverage for a failed rename while a rotated file is open. Done means failed rotation leaves the writer open so later writes are preserved and a subsequent write can retry rotation.

Escrita pelo modelo de indexação a partir do texto da issue.

Descrição

On Windows, LogDevice#shift_log_file closes @dev before it renames the active log to <log>.0. If that rename fails, the entry that triggered the rotation is lost. Every later write fails with closed stream until the log is reopened.

On Windows, a rename can't replace a destination file that is open, even when the handle that has it open uses File::SHARE_DELETE. With shift_age set to 2 or less, the active log is renamed over <log>.0 directly. So if another program still has <log>.0 open, the rename fails after @dev is closed. With shift_age set to 3 or more, rotation first moves <log>.0 to <log>.1, before it closes @dev. If that rename fails, the writer is still open. If it succeeds, <log>.0 is free for the active log.

Reproduction

The script sets shift_age to 2, so the second rotation renames the log over the app.log.0 that the first rotation created. Opening app.log.0 simulates a program that tails the log. For example, Fluentd's in_tail keeps the rotated file open for a few seconds (rotate_wait) to finish reading it.

require "logger"
require "tmpdir"

Dir.mktmpdir do |dir|
  path = File.join(dir, "app.log")
  logger = Logger.new(path, 2, 100)
  logger.formatter = proc { |_severity, _time, _progname, msg| "#{msg}\n" }

  logger.info("a" * 100)
  logger.info("rotated once")
  logger.info("b" * 100)

  # A program that tails the log still has the rotated file open.
  reader = File.open(path + ".0", File::RDONLY | File::BINARY | File::SHARE_DELETE)

  logger.info("rotate again")
  logger.info("next line")

  puts "logger #{Logger::VERSION}: dev closed? #{logger.instance_variable_get(:@logdev).dev.closed?}"
  puts "app.log: #{File.readlines(path).grep_v(/\A#/).map { |l| l.chomp[0, 12] }.inspect}"
  reader.close
  logger.close
end

Output on Windows 10 (ruby 3.4.13 x64-mingw-ucrt):

log rotation inter-process lock failed. Permission denied @ rb_file_s_rename - (.../app.log, .../app.log.0)
log writing failed. closed stream
log shifting failed. closed stream
log writing failed. closed stream
logger 1.7.0: dev closed? true
app.log: ["rotated once", "bbbbbbbbbbbb"]

The first two warnings come from logger.info("rotate again"). The first one reports that Windows denied the rename from app.log to app.log.0. It says "inter-process lock failed" because lock_shift_log rescues the error. The second one reports that the write found @dev closed. The last two warnings come from logger.info("next line"). Both the rotation check and the write hit the closed stream.

The same two entries are lost on Windows with logger 1.6.2 and 1.6.3. On 1.6.2, the first warning begins with log shifting failed instead. On Linux with logger 1.7.0, @dev stays open, and app.log has both entries.

Possible fix

Could shift_log_file close @dev only after the rename succeeds? Since logger 1.6.3, logger opens @dev with File::SHARE_DELETE on Windows. So the active log can be renamed while it is open. If the rename fails, the writer can still append to the current file and retry the rotation on the next write.

I tried this on Windows with logger 1.7.0. I prepended a version of shift_log_file that renames the active log first, then closes @dev and creates the new file. The script then printed dev closed? false. Both "rotate again" and "next line" were in app.log.

Related: #188 is another Windows problem in log rotation.

Linguagem predominante
Ruby
Estrelas
161
Forks
76
Merge médio
2d 5h
PRs com merge (30d)
3

Preparar o ambiente

Este projeto não oferece contêiner de desenvolvimento, Dockerfile nem guia de contribuição, então a configuração fica por sua conta: comece pelo README e veja nosso guia da primeira contribuição para os passos gerais.

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Mais de ruby/logger

Todas as issues de ruby/logger

Issues semelhantes

Mais issues de Ruby

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.