Class: RuboCop::Service::Server

Inherits:
Object
  • Object
show all
Defined in:
lib/rubocop/service/server.rb

Constant Summary collapse

DEFAULT_SERVER_CONFIG =
{
  pid: -1,
  port: -1,
  host: -1,
  version: "0.0.0"
}.freeze
SERVICE_NAME =
"rubocop_service"

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeServer

Returns a new instance of Server.



26
27
28
29
30
31
32
# File 'lib/rubocop/service/server.rb', line 26

def initialize
  host = ENV.fetch("RUBOCOP_SERVICE_SERVER_HOST", "127.0.0.1")
  port = ENV.fetch("RUBOCOP_SERVICE_SERVER_PORT", 0)
  @server = TCPServer.open(host, port)
  @threads = []
  @processes = []
end

Class Method Details

.assert_runningObject



206
207
208
209
210
211
# File 'lib/rubocop/service/server.rb', line 206

def assert_running
  return if running?

  warn "Service is not running! Please run `rubocop-service start` with administrator privileges."
  exit 1
end

.connect {|connection| ... } ⇒ Object

Yields:

  • (connection)


168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/rubocop/service/server.rb', line 168

def connect
  assert_running
  connection =
    TCPSocket.open(server_config[:host], server_config[:port])
  exitcode = nil
  connection_thread =
    Thread.new do
      catch :exit do
        while (messages = connection.gets)
          messages
            .split("\n")
            .each do |message|
              next if message.strip.empty?
              data = JSON.parse(message, symbolize_names: true)
              case data[:type]
              when "stdout"
                $stdout.write(data[:message])
              when "stderr"
                $stderr.write(data[:message])
              when "exitcode"
                exitcode = data[:message]
                throw :exit
              end
            rescue JSON::ParserError
              warn "Invalid message received: #{message}"
            end
        end
      end
    rescue IOError
      # ignore
    end
  return connection unless block_given?
  yield connection
  connection_thread.join
  connection.close
  exitcode
end

.registerObject



275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/rubocop/service/server.rb', line 275

def register
  Win32::Service.create(
    service_name: SERVICE_NAME,
    service_type: Win32::Service::WIN32_OWN_PROCESS,
    description:
      "RuboCop Server for windows, provided by rubocop-service gem",
    start_type: Win32::Service::AUTO_START,
    error_control: Win32::Service::ERROR_NORMAL,
    binary_path_name: "#{RbConfig.ruby} #{File.expand_path(__FILE__)}",
    load_order_group: "Network",
    dependencies: %w[W32Time Schedule]
  )
end

.running?Boolean

Returns:

  • (Boolean)


253
254
255
256
257
258
259
260
261
# File 'lib/rubocop/service/server.rb', line 253

def running?
  return false if server_config[:pid] == -1
  begin
    Process.kill(0, server_config[:pid])
    true
  rescue Errno::ESRCH
    false
  end
end

.server_configObject



267
268
269
270
271
272
273
# File 'lib/rubocop/service/server.rb', line 267

def server_config
  if File.exist?(server_config_path)
    JSON.load_file(server_config_path, symbolize_names: true)
  else
    DEFAULT_SERVER_CONFIG.dup
  end
end

.server_config_pathObject



263
264
265
# File 'lib/rubocop/service/server.rb', line 263

def server_config_path
  File.expand_path("~/.rubocop-service")
end

.startObject



213
214
215
216
217
218
219
220
221
222
223
# File 'lib/rubocop/service/server.rb', line 213

def start
  begin
    register unless Win32::Service.exists?(SERVICE_NAME)
    Win32::Service.start SERVICE_NAME
  rescue Errno::EIO
    puts "Could not start service! Missing administrator privileges?"
    exit 1
  end

  puts "Service started successfully!"
end

.statusObject



245
246
247
248
249
250
251
# File 'lib/rubocop/service/server.rb', line 245

def status
  if running?
    puts "Service is running."
  else
    puts "Service is not running."
  end
end

.stopObject



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
# File 'lib/rubocop/service/server.rb', line 225

def stop
  unless Win32::Service.exists?(SERVICE_NAME)
    puts "Service not found."
    exit 1
  end

  if running?
    begin
      Win32::Service.stop SERVICE_NAME
    rescue Errno::EIO
      puts "Could not stop service! Missing administrator privileges?"
      exit 1
    end
    puts "Service stopped."
  else
    puts "Service is not running."
    exit 1
  end
end

Instance Method Details

#hostObject



159
160
161
# File 'lib/rubocop/service/server.rb', line 159

def host
  @server.addr[3]
end

#portObject



163
164
165
# File 'lib/rubocop/service/server.rb', line 163

def port
  @server.addr[1]
end

#process(connection) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# File 'lib/rubocop/service/server.rb', line 63

def process(connection)
  r = connection.gets
  message = JSON.parse(r, symbolize_names: true)
  case message[:type]
  when "spawn"
    spawn_server(connection, message[:directory])
  else
    connection.puts(
      JSON.generate(
        {
          type: "stderr",
          message:
            "Unknown message type: #{message[:type]}. This is bug, please report it to https://github.com/sevenc-nanashi/rubocop-service/issues"
        }
      )
    )
    connection.puts(JSON.generate({ type: "exitcode", message: 1 }))
  end
end

#server_configObject



150
151
152
153
154
155
156
157
# File 'lib/rubocop/service/server.rb', line 150

def server_config
  {
    pid: Process.pid,
    port: port,
    host: host,
    version: RuboCop::Service::VERSION
  }
end

#spawn_server(connection, directory) ⇒ Object



83
84
85
86
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
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/rubocop/service/server.rb', line 83

def spawn_server(connection, directory)
  nonce = SecureRandom.hex(8)
  puts "#{Thread.current.inspect}: Starting server..."
  Open3.popen3(
    {
      "RUBOCOP_SERVICE_SERVER_PROCESS" => "true",
      "RUBOCOP_SERVICE_STARTING_NONCE" => nonce
    },
    "rubocop --start-server",
    chdir: directory
  ) do |i, o, e, t|
    i.close
    queue = Queue.new
    started = false
    @processes << t
    Thread.start do
      while (od = o.readpartial(4096))
        $stdout.write od
        $stdout.flush
        if od.include?("rubocop-service-nonce:#{nonce}")
          queue << -1
          od.gsub!("rubocop-service-nonce:#{nonce}", "")
        end
        unless started
          connection.puts("#{{ type: "stdout", message: od }.to_json}\n")
        end
      end
    rescue IOError
      # ignore
    end
    Thread.start do
      while (ed = e.readpartial(4096))
        $stderr.write ed
        $stderr.flush
        unless started
          connection.puts("#{{ type: "stderr", message: ed }.to_json}\n")
        end
      end
    rescue IOError
      # ignore
    end
    Thread.start { queue << t.value }
    exit_status = queue.pop

    connection.puts(
      JSON.generate(
        { type: "exitcode", message: exit_status == -1 ? 0 : exit_status }
      )
    )
    case exit_status
    when -1
      puts "#{Thread.current.inspect}: Server started."
    else
      puts "#{Thread.current.inspect}: Server failed to start."
    end
    started = true
    t.join
    exit_status = queue.pop
    case exit_status
    when 0
      puts "#{Thread.current.inspect}: Server exited normally."
    else
      puts "#{Thread.current.inspect}: Server exited with error, exit status: #{exit_status}"
    end
  end
end

#startObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/rubocop/service/server.rb', line 34

def start
  File.write(Server.server_config_path, server_config.to_json)
  puts "Server ready! pid: #{Process.pid}, port: #{port}, host: #{host}"

  @main_thread =
    Thread.new do
      loop do
        # process(@server.accept)
        # client.close
        @threads << Thread.start(@server.accept) do |client|
          puts "#{Thread.current.inspect}: Connected #{client.inspect}"
          process(client)
          puts "#{Thread.current.inspect}: Processed #{client.inspect}"
          client.close
        end
      end
    end
  @main_thread.join
rescue Interrupt
  puts "Terminating..."
  stop
end

#stopObject



57
58
59
60
61
# File 'lib/rubocop/service/server.rb', line 57

def stop
  @processes.each(&:kill)
  @threads.each(&:kill)
  @main_thread.kill
end