Guest User

Untitled

a guest
Jan 23rd, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.01 KB | None | 0 0
  1. # we're using the TmpIO class
  2. # -*- encoding: binary -*-
  3. # :stopdoc:
  4. require 'tmpdir'
  5. # some versions of Ruby had a broken Tempfile which didn't work
  6. # well with unlinked files. This one is much shorter, easier
  7. # to understand, and slightly faster.
  8. class TmpIO < File
  9.  
  10. # creates and returns a new File object. The File is unlinked
  11. # immediately, switched to binary mode, and userspace output
  12. # buffering is disabled
  13. def self.new
  14. fp = begin
  15. super("#{Dir::tmpdir}/#{rand}", RDWR|CREAT|EXCL, 0600)
  16. rescue Errno::EEXIST
  17. retry
  18. end
  19. unlink(fp.path)
  20. fp.binmode
  21. fp.sync = true
  22. fp
  23. end
  24.  
  25. # for easier env["rack.input"] compatibility with Rack <= 1.1
  26. def size
  27. stat.size
  28. end unless File.method_defined?(:size)
  29. end
  30. # end
  31.  
  32. #
  33. # EXAMPLE
  34. #
  35. # usage : worker = Worker.new(worker_nr, Unicorn::TmpIO.new)
  36. # p TmpIO.new
  37. # p TmpIO.new
  38.  
  39. #
  40. # Worker class
  41. #
  42. class Worker < Struct.new(:nr, :tmp, :switched)
  43. # worker objects may be compared to just plain Integers
  44. def ==(other_nr) # :nodoc:
  45. nr == other_nr
  46. end
  47. end
  48.  
  49. #
  50. # EXAMPLE
  51. #
  52. # we create some workers
  53. w1 = Worker.new 1, TmpIO.new
  54. w2 = Worker.new 2, TmpIO.new
  55.  
  56. # The chmod will use either ‘1’ or ‘0’ each time this gets executed.
  57. # (Assign ‘0’ to the local variable ‘m’, compare it to ‘0’. If it matches (m == 0), m = 1, otherwise m = 0.
  58. # A one line toggle.)
  59.  
  60. # this one should be stale
  61. p w1.tmp.chmod(m = 0 == m ? 1 : 0)
  62. sleep 5
  63. # this one should be ok
  64. p w2.tmp.chmod(m = 0 == m ? 1 : 0)
  65.  
  66. WORKERS = []
  67. WORKERS << w1
  68. WORKERS << w2
  69.  
  70. # Here’s what the master does to check the worker’s status
  71. # Even though the file is unlinked it still has metadata associated with it.
  72. # Using the file’s #ctime we can check when the file was last mode changed,
  73. # and thus when the worker was last alive.
  74. timeout = 3
  75. WORKERS.each do |worker|
  76. stat = worker.tmp.stat
  77. unless (diff = (Time.now - stat.ctime)) <= timeout
  78. p "Worker #{worker.nr} has gone stale and needs to be respawned"
  79. else
  80. p "Worker #{worker.nr} is not stale"
  81. end
  82. end
Add Comment
Please, Sign In to add comment