简体   繁体   中英

How do I get the Puma worker index within a Rails request?

When a Rails server starts, it lists the Puma workers by their index and PID.

[17042] - Worker 0 (PID: 17069) booted in 0.01s, phase: 0
[17042] - Worker 1 (PID: 17070) booted in 0.01s, phase: 0

I can get the PID of the worker from within the request with Process.pid .

> Process.pid
=> 17069

Is there a way to get the index of the Puma worker ( 0 , 1 , etc.) from within the request processing?

I see that the Puma::Cluster::Worker class has an index method that should get me that value, but I can't figure out how to get the instance of that class making the current request.

I believe I can get it through ObjectSpace , but I have to imagine I'm missing a better way.

> ObjectSpace.each_object(Puma::Cluster::Worker) { |x| p x.index }
0
=> 1

I don't think the API supports it, but the following workaround can work

The index is passed to some callbacks, eg

https://github.com/puma/puma/blob/34c706be2cd8d48d1e3fa80b2b0b33bcc2b8d8eb/lib/puma/cluster/worker.rb#L55

You can then do something with it (save it somewhere you can reference later, eg)

https://github.com/puma/puma/blob/15b079439222e489915380021b9dca7b9fa5ff65/test/config/state_file_testing_config.rb#L3

On a side note, I find it a bit confusing that defining on_worker_boot in the DSL will actually call before_worker_boot hook

https://github.com/puma/puma/blob/e9f09ba1fe6b168bed7fff59d0bdbfd65351cf9d/lib/puma/dsl.rb#L567

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM