Class: Zold::Farmers::Spawn

Inherits:
Object
  • Object
show all
Defined in:
lib/zold/node/farmers.rb

Overview

In a child process

Instance Method Summary collapse

Constructor Details

#initialize(log: Log::NULL) ⇒ Spawn

Returns a new instance of Spawn.



83
84
85
# File 'lib/zold/node/farmers.rb', line 83

def initialize(log: Log::NULL)
  @log = log
end

Instance Method Details

#up(score) ⇒ Object



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
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
133
134
135
136
137
# File 'lib/zold/node/farmers.rb', line 87

def up(score)
  start = Time.now
  bin = File.expand_path(File.join(File.dirname(__FILE__), '../../../bin/zold'))
  raise "Zold binary not found at #{bin}" unless File.exist?(bin)
  cmd = [
    'ruby',
    Shellwords.escape(bin),
    '--skip-upgrades',
    "--info-tid=#{Thread.current.thread_variable_get(:tid)}",
    "--info-thread=#{Shellwords.escape(Thread.current.name)}",
    "--info-start=#{Time.now.utc.iso8601}",
    '--low-priority',
    'next',
    Shellwords.escape(score)
  ].join(' ')
  Open3.popen2e(cmd) do |stdin, stdout, thr|
    Thread.current.thread_variable_set(:pid, thr.pid.to_s)
    at_exit { Farmers.kill(@log, thr.pid, start) }
    @log.debug("Scoring started in proc ##{thr.pid} \
for #{score.value}/#{score.strength} at #{score.host}:#{score.port}")
    begin
      stdin.close
      buffer = +''
      loop do
        begin
          buffer << stdout.read_nonblock(16 * 1024)
          # rubocop:disable Lint/HandleExceptions
        rescue IO::WaitReadable => _
          # rubocop:enable Lint/HandleExceptions
          # nothing to do here
        rescue StandardError => e
          @log.error(buffer)
          raise e
        end
        break if buffer.end_with?("\n") && thr.value.to_i.zero?
        if stdout.closed?
          raise "Failed to calculate the score (##{thr.value}): #{buffer}" unless thr.value.to_i.zero?
          break
        end
        sleep(1)
        Thread.current.thread_variable_set(:buffer, buffer.length.to_s)
      end
      after = Score.parse(buffer.strip)
      @log.debug("Next score #{after.value}/#{after.strength} found in proc ##{thr.pid} \
for #{after.host}:#{after.port} in #{Age.new(start)}: #{after.suffixes}")
      after
    ensure
      Farmers.kill(@log, thr.pid, start)
    end
  end
end