Class: QB::Util::STDIO::Service

Inherits:
Object
  • Object
show all
Includes:
SemanticLogger::Loggable
Defined in:
lib/qb/util/stdio.rb

Overview

STDIO as a service exposed on a UNIX socket so that modules can stream their output to it, which is in turn printed to the console qb is running in.

Direct Known Subclasses

InService, OutService

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ Service

Returns a new instance of Service.



73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/qb/util/stdio.rb', line 73

def initialize name
  @name = name
  @thread = nil
  @server = nil
  @socket = nil
  @env_key = "QB_STDIO_#{ name.upcase }"
  
  unless SOCKET_DIR.exist?
    FileUtils.mkdir SOCKET_DIR
  end
  
  @path = SOCKET_DIR.join "#{ name }.#{ SecureRandom.uuid }.sock"
  
  self.logger = SemanticLogger[
    [
      "#{ self.class.name } {",
      "  name: #{ name }",
      "  path: #{ @path.to_s }",
      "}"
    ].join( "\n" )
  ]
  
  logger.trace "Initialized"
end

Instance Method Details

#close!Object

open



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/qb/util/stdio.rb', line 134

def close!
  # clean up.
  # 
  # TODO not sure how correct this is...
  # 
  logger.trace "closing..."
  
  @socket.close unless @socket.nil?
  @socket = nil
  @server.close unless @server.nil?
  @server = nil
  FileUtils.rm(@path) if @path.exist?
  @thread.kill unless @thread.nil?
  
  logger.trace "closed."
end

#debug(*args) ⇒ Object



98
99
100
101
# File 'lib/qb/util/stdio.rb', line 98

def debug *args
  # logger.debug "#{ @debug_header }", args
  logger.debug *args
end

#open!Object



103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
# File 'lib/qb/util/stdio.rb', line 103

def open!
  logger.trace "opening..."
  
  # make sure env var is not already set (basically just prevents you from
  # accidentally opening two instances with the same name)
  if ENV.key? @env_key
    raise <<-END.squish
      env already contains key #{ @env_key } with value #{ ENV[@env_key] }
    END
  end
  
  @thread = Thread.new do
    Thread.current.name = @name
    logger.trace "thread started."
    
    @server = UNIXServer.new @path.to_s
    
    while true do
      @socket = @server.accept
      
      work_in_thread
    end
  end
  
  # set the env key so children can find the socket path
  ENV[@env_key] = @path.to_s
  logger.trace "set env var", @env_key => ENV[@env_key]
  
  logger.trace "service open."
end