Memory leak when thread is terminated after using logger.with_level

未關閉
#135 0 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

  • #185 來自 @wtn —— 已關閉,未合併

評估

難度
5/5
預估耗時
一週以上
新手友好度
30/100
Issue 類型
缺陷
描述清晰度
需要釐清
活躍度
停滯
技術堆疊
ruby
領域
tooling

研究方向

首先執行回報的 MemoryProfiler 重現,並檢查 Logger#with_level、level_override 雜湊及其 Fiber.current 索引鍵。判斷已終止的執行緒或 fiber 是否可以釋放;如果有必要修改 Logger,則新增回歸測試;當執行緒終止後保留的記憶體不再成長時,即表示完成。

由索引模型根據 Issue 內容生成。

描述

Hello. We were debugging a memory leak that appeared in our rails app after we started using with_level method to adjust visibility of some logs. How to reproduce:

require "logger"
require "memory_profiler"

logger = Logger.new $stdout
MemoryProfiler.report do
  100.times { Thread.new { Thread.current[:data] = Array.new(200); logger.with_level(Logger::ERROR) { logger.debug("test") } }.join }
  GC.start
end.pretty_print
# Total allocated: 336800 bytes (400 objects)
# Total retained:  336800 bytes (400 objects)
# ...
# retained memory by class
-----------------------------------
    164000  Array
    114400  Fiber
     50400  Thread
      8000  Proc

All memory is freed if logger.with_level is removed. My guess is that it happens because Logger uses Fiber.current as key in level_override hash to track log level for current fiber. This reference to Fiber.current is never cleared so GC cannot free connected terminated threads.

For more context this is why it happened in our rails application - we are deployed in kubernetes and have small plugin in puma to process liveness and readiness probes (simple http requests to specific endpoints). One of these requests checks connection to database via simple query. We hide these queries from logs via logger.with_level(Logger::Error) .... Problem was that our puma plugin options had min_threads: 0, max_threads: 1 so puma terminated (and later created again) its thread from time to time, which lead to level_override filling up with old Fiber.current for terminated threads.

When we eventually figured this out the fix was to just keep min_threads same as max_threads in puma.

I am not sure what would be the best way to prevent it (Fiber local variable instead of hash?) or if even something should be changed in Logger, because I realize that our problem was most likely quite unusual. If you think that this should be fixed I would be happy to prepare the change if you point me to the right direction. If not then this could at least help someone who is searching for similar problem.

主要語言
Ruby
星號
161
分支
76
平均合併
2 天 5 小時
30 天內合併 PR
3

環境準備

這個專案沒有提供開發容器、Dockerfile 或貢獻指南,環境需要你自己搭建:先看它的 README,通用步驟見我們的新手貢獻指南。

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

ruby/logger 的其他 Issue

查看 ruby/logger 的全部 Issue

相似的 Issue

更多 Ruby Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。