4 # Author:: NABEYA Kenichi, Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
8 # Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
9 # Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
11 # This program is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # This program is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with this program; if not, write to the Free Software
23 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
32 $:.unshift File.dirname(__FILE__)
33 require 'shogi_server'
34 require 'shogi_server/config'
35 require 'shogi_server/util'
38 #################################################
44 def gets_safe(socket, timeout=nil)
45 if r = select([socket], nil, nil, timeout)
46 return r[0].first.gets
50 rescue Exception => ex
51 log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
58 shogi-server - server for CSA server protocol
61 shogi-server [OPTIONS] event_name port_number
64 server for CSA server protocol
68 specify filename for logging process ID
70 run as a daemon. Log files will be put in dir.
72 log network messages for each player. Log files
73 will be put in the dir.
76 GPL versoin 2 or later
81 #{ShogiServer::Release}
84 #{ShogiServer::Revision}
110 # Parse command line options. Return a hash containing the option strings
111 # where a key is the option name without the first two slashes. For example,
112 # {"pid-file" => "foo.pid"}.
114 def parse_command_line
116 parser = GetoptLong.new(
117 ["--daemon", GetoptLong::REQUIRED_ARGUMENT],
118 ["--pid-file", GetoptLong::REQUIRED_ARGUMENT],
119 ["--player-log-dir", GetoptLong::REQUIRED_ARGUMENT])
122 parser.each_option do |name, arg|
124 options[name] = arg.dup
128 raise parser.error_message
133 # Check command line options.
134 # If any of them is invalid, exit the process.
136 def check_command_line
137 if (ARGV.length != 2)
142 if $options["daemon"]
143 $options["daemon"] = File.expand_path($options["daemon"], File.dirname(__FILE__))
144 unless is_writable_dir? $options["daemon"]
146 $stderr.puts "Can not create a file in the daemon directory: %s" % [$options["daemon"]]
151 $topdir = $options["daemon"] || File.expand_path(File.dirname(__FILE__))
153 if $options["player-log-dir"]
154 $options["player-log-dir"] = File.expand_path($options["player-log-dir"], $topdir)
155 unless is_writable_dir?($options["player-log-dir"])
157 $stderr.puts "Can not write a file in the player log dir: %s" % [$options["player-log-dir"]]
162 if $options["pid-file"]
163 $options["pid-file"] = File.expand_path($options["pid-file"], $topdir)
164 unless ShogiServer::is_writable_file? $options["pid-file"]
166 $stderr.puts "Can not create the pid file: %s" % [$options["pid-file"]]
171 if $options["floodgate-history"]
172 $stderr.puts "WARNING: --floodgate-history has been deprecated."
173 $options["floodgate-history"] = nil
177 # See if a file can be created in the directory.
178 # Return true if a file is writable in the directory, otherwise false.
180 def is_writable_dir?(dir)
181 unless File.directory? dir
188 temp_file = Tempfile.new("dummy-shogi-server", dir)
197 def write_pid_file(file)
198 open(file, "w") do |fh|
203 def mutex_watchdog(mutex, sec)
211 queue.push(Object.new)
214 log_error("mutex watchdog timeout: %d sec" % [sec])
222 def login_loop(client)
225 while r = select([client], nil, nil, ShogiServer::Login_Time) do
228 break unless str = r[0].first.gets
229 rescue Exception => ex
230 # It is posssible that the socket causes an error (ex. Errno::ECONNRESET)
231 log_error("login_loop: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
234 $mutex.lock # guards $league
238 if (ShogiServer::Login::good_login?(str))
239 player = ShogiServer::Player::new(str, client, eol)
240 login = ShogiServer::Login::factory(str, player)
241 if (current_player = $league.find(player.name))
242 if (current_player.password == player.password &&
243 current_player.status != "game")
244 log_message(sprintf("user %s login forcely", player.name))
247 login.incorrect_duplicated_player(str)
255 client.write("LOGIN:incorrect" + eol)
256 client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
262 return [player, login]
265 def setup_logger(log_file)
266 logger = ShogiServer::Logger.new(log_file, 'daily')
267 logger.formatter = ShogiServer::Formatter.new
268 logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO
269 logger.datetime_format = "%Y-%m-%d %H:%M:%S"
273 def setup_watchdog_for_giant_lock
277 mutex_watchdog($mutex, 10)
281 def floodgate_reload_log(leagues)
282 floodgate = leagues.min {|a,b| a.next_time <=> b.next_time}
283 diff = floodgate.next_time - Time.now
284 log_message("Floodgate reloaded. The next match will start at %s in %d seconds" %
285 [floodgate.next_time, diff])
288 def setup_floodgate(game_names)
289 return Thread.start(game_names) do |game_names|
291 leagues = game_names.collect do |game_name|
292 ShogiServer::League::Floodgate.new($league,
293 {:game_name => game_name})
295 leagues.delete_if do |floodgate|
297 unless floodgate.next_time
298 log_error("Unsupported game name: %s" % floodgate.game_name)
304 log_error("No valid Floodgate game names found")
305 return # exit from this thread
307 floodgate_reload_log(leagues)
311 floodgate = leagues.min {|a,b| a.next_time <=> b.next_time}
312 diff = floodgate.next_time - Time.now
314 floodgate_reload_log(leagues) if $DEBUG
318 next_array = leagues.collect do |floodgate|
319 if (floodgate.next_time - Time.now) > 0
320 [floodgate.game_name, floodgate.next_time]
322 log_message("Starting Floodgate games...: %s" % [floodgate.game_name])
326 [floodgate.game_name, floodgate.next_time] # next_time has been updated
329 $mutex.synchronize do
330 log_message("Reloading source...")
333 # Regenerate floodgate instances after ShogiServer.realod
334 leagues = next_array.collect do |game_name, next_time|
335 floodgate = ShogiServer::League::Floodgate.new($league,
336 {:game_name => game_name,
337 :next_time => next_time})
339 floodgate_reload_log(leagues)
340 rescue Exception => ex
342 log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
350 $options = parse_command_line
352 $config = ShogiServer::Config.new $options
354 $league = ShogiServer::League.new($topdir)
356 $league.event = ARGV.shift
359 log_file = $options["daemon"] ? File.join($options["daemon"], "shogi-server.log") : STDOUT
360 $logger = setup_logger(log_file)
362 $league.dir = $topdir
366 config[:ServerType] = WEBrick::Daemon if $options["daemon"]
367 config[:Logger] = $logger
371 config[:StartCallback] = Proc.new do
373 if $options["pid-file"]
374 write_pid_file($options["pid-file"])
376 setup_watchdog_for_giant_lock
377 $league.setup_players_database
378 fg_thread = setup_floodgate(["floodgate-900-0", "floodgate-3600-0"])
381 config[:StopCallback] = Proc.new do
382 if $options["pid-file"]
383 FileUtils.rm($options["pid-file"], :force => true)
388 server = WEBrick::GenericServer.new(config)
389 ["INT", "TERM"].each do |signal|
392 fg_thread.kill if fg_thread
395 unless (RUBY_PLATFORM.downcase =~ /mswin|mingw|cygwin|bccwin/)
400 $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"]
401 log_message("server started [Revision: #{ShogiServer::Revision}]")
403 server.start do |client|
404 # client.sync = true # this is already set in WEBrick
405 client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
406 # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
407 player, login = login_loop(client) # loop
410 log_message(sprintf("user %s login", player.name))
412 player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
413 player.run(login.csa_1st_str) # loop
417 player.game.kill(player)
419 player.finish # socket has been closed
420 $league.delete(player)
421 log_message(sprintf("user %s logout", player.name))
432 TCPSocket.do_not_reverse_lookup = true
433 Thread.abort_on_exception = $DEBUG ? true : false
437 rescue Exception => ex
439 log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
441 $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"