PageRenderTime 38ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/god/socket.rb

https://github.com/anselmo/god
Ruby | 96 lines | 54 code | 14 blank | 28 comment | 0 complexity | 5b03f567d85215fea9735210c5e711c1 MD5 | raw file
  1. require 'drb'
  2. module God
  3. # The God::Server oversees the DRb server which dishes out info on this God daemon.
  4. class Socket
  5. attr_reader :port
  6. # The location of the socket for a given port
  7. # +port+ is the port number
  8. #
  9. # Returns String (file location)
  10. def self.socket_file(port)
  11. "/tmp/god.#{port}.sock"
  12. end
  13. # The address of the socket for a given port
  14. # +port+ is the port number
  15. #
  16. # Returns String (drb address)
  17. def self.socket(port)
  18. "drbunix://#{self.socket_file(port)}"
  19. end
  20. # The location of the socket for this Server
  21. #
  22. # Returns String (file location)
  23. def socket_file
  24. self.class.socket_file(@port)
  25. end
  26. # The address of the socket for this Server
  27. #
  28. # Returns String (drb address)
  29. def socket
  30. self.class.socket(@port)
  31. end
  32. # Create a new Server and star the DRb server
  33. # +port+ is the port on which to start the DRb service (default nil)
  34. def initialize(port = nil)
  35. @port = port
  36. start
  37. end
  38. # Returns true
  39. def ping
  40. true
  41. end
  42. # Forward API calls to God
  43. #
  44. # Returns whatever the forwarded call returns
  45. def method_missing(*args, &block)
  46. God.send(*args, &block)
  47. end
  48. # Stop the DRb server and delete the socket file
  49. #
  50. # Returns nothing
  51. def stop
  52. DRb.stop_service
  53. FileUtils.rm_f(self.socket_file)
  54. end
  55. private
  56. # Start the DRb server. Abort if there is already a running god instance
  57. # on the socket.
  58. #
  59. # Returns nothing
  60. def start
  61. begin
  62. @drb ||= DRb.start_service(self.socket, self)
  63. applog(nil, :info, "Started on #{DRb.uri}")
  64. rescue Errno::EADDRINUSE
  65. applog(nil, :info, "Socket already in use")
  66. DRb.start_service
  67. server = DRbObject.new(nil, self.socket)
  68. begin
  69. Timeout.timeout(5) do
  70. server.ping
  71. end
  72. abort "Socket #{self.socket} already in use by another instance of god"
  73. rescue StandardError, Timeout::Error
  74. applog(nil, :info, "Socket is stale, reopening")
  75. File.delete(self.socket_file) rescue nil
  76. @drb ||= DRb.start_service(self.socket, self)
  77. applog(nil, :info, "Started on #{DRb.uri}")
  78. end
  79. end
  80. end
  81. end
  82. end