Class: Spring::Client::Run

Inherits:
Command
  • Object
show all
Defined in:
lib/spring/client/run.rb

Constant Summary collapse

FORWARDED_SIGNALS =
%w(INT QUIT USR1 USR2 INFO WINCH) & Signal.list.keys
ServerReadTimeout =
Class.new(StandardError)

Instance Attribute Summary collapse

Attributes inherited from Command

#args, #env

Instance Method Summary collapse

Methods inherited from Command

call

Constructor Details

#initialize(args) ⇒ Run

Returns a new instance of Run.



13
14
15
16
17
18
# File 'lib/spring/client/run.rb', line 13

def initialize(args)
  super

  @signal_queue  = []
  @server_booted = false
end

Instance Attribute Details

#serverObject (readonly)

Returns the value of attribute server.



11
12
13
# File 'lib/spring/client/run.rb', line 11

def server
  @server
end

Instance Method Details

#boot_serverObject



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/spring/client/run.rb', line 72

def boot_server
  env.socket_path.unlink if env.socket_path.exist?

  pid     = Process.spawn(server_process_env, env.server_command, out: File::NULL)
  timeout = Time.now + Spring.boot_timeout

  @server_booted = true

  until env.socket_path.exist?
    _, status = Process.waitpid2(pid, Process::WNOHANG)

    if status
      exit status.exitstatus
    elsif Time.now > timeout
      $stderr.puts "Starting Spring server with `#{env.server_command}` " \
                   "timed out after #{Spring.boot_timeout} seconds"
      exit 1
    end

    sleep 0.1
  end
end

#callObject



28
29
30
31
32
33
34
35
36
37
38
# File 'lib/spring/client/run.rb', line 28

def call
  begin
    connect
  rescue Errno::ENOENT, Errno::ECONNRESET, Errno::ECONNREFUSED
    cold_run
  else
    warm_run
  end
ensure
  server.close if server
end

#cold_runObject



54
55
56
57
58
# File 'lib/spring/client/run.rb', line 54

def cold_run
  boot_server
  connect
  run
end

#connectObject



24
25
26
# File 'lib/spring/client/run.rb', line 24

def connect
  @server = UNIXSocket.open(env.socket_name)
end

#connect_to_application(client) ⇒ Object



182
183
184
185
186
187
188
189
190
191
# File 'lib/spring/client/run.rb', line 182

def connect_to_application(client)
  server.send_io client
  send_json server, "args" => args, "default_rails_env" => default_rails_env, "spawn_env" => spawn_env, "reset_env" => reset_env

  if IO.select([server], [], [], Spring.connect_timeout)
    server.gets or raise CommandNotFound
  else
    raise "Error connecting to Spring server"
  end
end

#default_rails_envObject



286
287
288
# File 'lib/spring/client/run.rb', line 286

def default_rails_env
  ENV['RAILS_ENV'] || ENV['RACK_ENV'] || 'development'
end

#forward_signal(sig, application) ⇒ Object



265
266
267
268
269
270
271
272
# File 'lib/spring/client/run.rb', line 265

def forward_signal(sig, application)
  if kill(sig, application) != 0
    # If the application process is gone, then don't block the
    # signal on this process.
    trap(sig, 'DEFAULT')
    Process.kill(sig, Process.pid)
  end
end

#forward_signals(application) ⇒ Object



257
258
259
260
261
262
263
# File 'lib/spring/client/run.rb', line 257

def forward_signals(application)
  @signal_queue.each { |sig| kill sig, application }

  FORWARDED_SIGNALS.each do |sig|
    trap(sig) { forward_signal sig, application }
  end
end

#gem_envObject



99
100
101
102
103
104
105
106
107
# File 'lib/spring/client/run.rb', line 99

def gem_env
  bundle = Bundler.bundle_path.to_s
  paths  = Gem.path + ENV["GEM_PATH"].to_s.split(File::PATH_SEPARATOR)

  {
    "GEM_PATH" => [bundle, *paths].uniq.join(File::PATH_SEPARATOR),
    "GEM_HOME" => bundle
  }
end

#kill(sig, application) ⇒ Object



274
275
276
277
# File 'lib/spring/client/run.rb', line 274

def kill(sig, application)
  application.puts(sig)
  application.gets.to_i
end

#log(message) ⇒ Object



20
21
22
# File 'lib/spring/client/run.rb', line 20

def log(message)
  env.log "[client] #{message}"
end

#queue_signalsObject



239
240
241
242
243
# File 'lib/spring/client/run.rb', line 239

def queue_signals
  FORWARDED_SIGNALS.each do |sig|
    trap(sig) { @signal_queue << sig }
  end
end

#read_server_line(timeout = Spring.connect_timeout) ⇒ Object

Raises:



163
164
165
166
167
# File 'lib/spring/client/run.rb', line 163

def read_server_line(timeout = Spring.connect_timeout)
  raise ServerReadTimeout if IO.select([server], [], [], timeout).nil?

  server.gets
end

#reboot_or_raise_connection_errorObject



173
174
175
176
177
178
179
180
# File 'lib/spring/client/run.rb', line 173

def reboot_or_raise_connection_error
  if server_booted?
    raise "Error connecting to Spring server"
  else
    stop_server
    cold_run
  end
end

#reset_envObject



109
110
111
# File 'lib/spring/client/run.rb', line 109

def reset_env
  ENV.slice(*Spring.reset_on_env)
end

#runObject



60
61
62
63
64
65
66
67
68
69
70
# File 'lib/spring/client/run.rb', line 60

def run
  verify_server_version

  application, client = UNIXSocket.pair

  queue_signals
  connect_to_application(client)
  run_command(client, application)
rescue Errno::ECONNRESET
  exit 1
end

#run_command(client, application) ⇒ Object



193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/spring/client/run.rb', line 193

def run_command(client, application)
  application.send_io STDOUT
  application.send_io STDERR
  application.send_io STDIN

  log "waiting for the application to be preloaded"
  preload_status = application.gets
  preload_status = preload_status.chomp if preload_status
  log "app preload status: #{preload_status}"
  exit 1 if preload_status == "1"

  log "sending command"
  send_json application, "args" => args, "env" => ENV.to_hash

  pid = server.gets
  pid = pid.chomp if pid

  # We must not close the client socket until we are sure that the application has
  # received the FD. Otherwise the FD can end up getting closed while it's in the server
  # socket buffer on OS X. This doesn't happen on Linux.
  client.close

  if pid && !pid.empty?
    log "got pid: #{pid}"

    suspend_resume_on_tstp_cont(pid)

    forward_signals(application)
    status = application.read
    log "got exit status #{status.inspect}"

    # Status should always be an integer. If it is empty, something unexpected must have happened to the server.
    if status.to_s.strip.empty?
      log "unexpected empty exit status, app crashed?"
      exit 1
    end

    exit status.to_i
  else
    log "got no pid"
    exit 1
  end
ensure
  application.close
end

#send_json(socket, data) ⇒ Object



279
280
281
282
283
284
# File 'lib/spring/client/run.rb', line 279

def send_json(socket, data)
  data = JSON.dump(data)

  socket.puts  data.bytesize
  socket.write data
end

#server_booted?Boolean

Returns:

  • (Boolean)


95
96
97
# File 'lib/spring/client/run.rb', line 95

def server_booted?
  @server_booted
end

#server_process_envObject



113
114
115
# File 'lib/spring/client/run.rb', line 113

def server_process_env
  reset_env.merge(gem_env)
end

#spawn_envObject



290
291
292
293
294
# File 'lib/spring/client/run.rb', line 290

def spawn_env
  Spring.spawn_on_env.to_h do |key|
    [key, ENV[key]]
  end
end

#stop_serverObject



117
118
119
120
121
# File 'lib/spring/client/run.rb', line 117

def stop_server
  server.close
  @server = nil
  env.stop
end

#suspend_resume_on_tstp_cont(pid) ⇒ Object



245
246
247
248
249
250
251
252
253
254
255
# File 'lib/spring/client/run.rb', line 245

def suspend_resume_on_tstp_cont(pid)
  trap("TSTP") {
    log "suspended"
    Process.kill("STOP", pid.to_i)
    Process.kill("STOP", Process.pid)
  }
  trap("CONT") {
    log "resumed"
    Process.kill("CONT", pid.to_i)
  }
end

#verify_server_versionObject



123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/spring/client/run.rb', line 123

def verify_server_version
  begin
    line = read_server_line
  rescue ServerReadTimeout
    if waiting_for_server_boot?
      begin
        # Try again, but with same timeout as booting, as server might still be booting
        #   from another client starting it.
        line = read_server_line(Spring.boot_timeout)
      rescue ServerReadTimeout
        reboot_or_raise_connection_error
        return
      end
    else
      reboot_or_raise_connection_error
      return
    end
  end

  if line.nil?
    reboot_or_raise_connection_error
    return
  end

  server_version = line.chomp
  if server_version != env.version
    $stderr.puts "There is a version mismatch between the Spring client " \
                   "(#{env.version}) and the server (#{server_version})."

    if server_booted?
      $stderr.puts "We already tried to reboot the server, but the mismatch is still present."
      exit 1
    else
      $stderr.puts "Restarting to resolve."
      stop_server
      cold_run
    end
  end
end

#waiting_for_server_boot?Boolean

Returns:

  • (Boolean)


169
170
171
# File 'lib/spring/client/run.rb', line 169

def waiting_for_server_boot?
  !server_booted? && env.server_running?
end

#warm_runObject



40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/spring/client/run.rb', line 40

def warm_run
  run
rescue CommandNotFound
  require "spring/commands"

  if Spring.command?(args.first)
    # Command installed since Spring started
    stop_server
    cold_run
  else
    raise
  end
end