OSDN Git Service

d3b4f5b7a946c44d0bd1f52645bd8c597b228db9
[shogi-server/shogi-server.git] / shogi-server
1 #! /usr/bin/env ruby
2 # $Id$
3 #
4 # Author:: NABEYA Kenichi, Daigo Moriwaki
5 # Homepage:: http://sourceforge.jp/projects/shogi-server/
6 #
7 #--
8 # Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
9 # Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
10 #
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.
15 #
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.
20 #
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
24 #++
25 #
26 #
27
28 $topdir = nil
29 $league = nil
30 $logger = nil
31 $config = nil
32 $:.unshift File.dirname(__FILE__)
33 require 'shogi_server'
34 require 'shogi_server/config'
35 require 'shogi_server/util'
36 require 'tempfile'
37
38 #################################################
39 # MAIN
40 #
41
42 ShogiServer.reload
43
44 def gets_safe(socket, timeout=nil)
45   if r = select([socket], nil, nil, timeout)
46     return r[0].first.gets
47   else
48     return :timeout
49   end
50 rescue Exception => ex
51   log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
52   return :exception
53 end
54
55 def usage
56     print <<EOM
57 NAME
58         shogi-server - server for CSA server protocol
59
60 SYNOPSIS
61         shogi-server [OPTIONS] event_name port_number
62
63 DESCRIPTION
64         server for CSA server protocol
65
66 OPTIONS
67         --pid-file file
68                 specify filename for logging process ID
69         --daemon dir
70                 run as a daemon. Log files will be put in dir.
71         --player-log-dir dir
72                 log network messages for each player. Log files
73                 will be put in the dir.
74
75 LICENSE
76         GPL versoin 2 or later
77
78 SEE ALSO
79
80 RELEASE
81         #{ShogiServer::Release}
82
83 REVISION
84         #{ShogiServer::Revision}
85
86 EOM
87 end
88
89
90 def log_debug(str)
91   $logger.debug(str)
92 end
93
94 def log_message(str)
95   $logger.info(str)
96 end
97 def log_info(str)
98   log_message(str)
99 end
100
101 def log_warning(str)
102   $logger.warn(str)
103 end
104
105 def log_error(str)
106   $logger.error(str)
107 end
108
109
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"}.
113 #
114 def parse_command_line
115   options = Hash::new
116   parser = GetoptLong.new(
117     ["--daemon",            GetoptLong::REQUIRED_ARGUMENT],
118     ["--pid-file",          GetoptLong::REQUIRED_ARGUMENT],
119     ["--player-log-dir",    GetoptLong::REQUIRED_ARGUMENT])
120   parser.quiet = true
121   begin
122     parser.each_option do |name, arg|
123       name.sub!(/^--/, '')
124       options[name] = arg.dup
125     end
126   rescue
127     usage
128     raise parser.error_message
129   end
130   return options
131 end
132
133 # Check command line options.
134 # If any of them is invalid, exit the process.
135 #
136 def check_command_line
137   if (ARGV.length != 2)
138     usage
139     exit 2
140   end
141
142   if $options["daemon"]
143     $options["daemon"] = File.expand_path($options["daemon"], File.dirname(__FILE__))
144     unless is_writable_dir? $options["daemon"]
145       usage
146       $stderr.puts "Can not create a file in the daemon directory: %s" % [$options["daemon"]]
147       exit 5
148     end
149   end
150
151   $topdir = $options["daemon"] || File.expand_path(File.dirname(__FILE__))
152
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"])
156       usage
157       $stderr.puts "Can not write a file in the player log dir: %s" % [$options["player-log-dir"]]
158       exit 3
159     end 
160   end
161
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"]
165       usage
166       $stderr.puts "Can not create the pid file: %s" % [$options["pid-file"]]
167       exit 4
168     end
169   end
170
171   if $options["floodgate-history"]
172     $stderr.puts "WARNING: --floodgate-history has been deprecated."
173     $options["floodgate-history"] = nil
174   end
175 end
176
177 # See if a file can be created in the directory.
178 # Return true if a file is writable in the directory, otherwise false.
179 #
180 def is_writable_dir?(dir)
181   unless File.directory? dir
182     return false
183   end
184
185   result = true
186
187   begin
188     temp_file = Tempfile.new("dummy-shogi-server", dir)
189     temp_file.close true
190   rescue
191     result = false
192   end
193
194   return result
195 end
196
197 def write_pid_file(file)
198   open(file, "w") do |fh|
199     fh.puts "#{$$}"
200   end
201 end
202
203 def mutex_watchdog(mutex, sec)
204   sec = 1 if sec < 1
205   queue = []
206   while true
207     if mutex.try_lock
208       queue.clear
209       mutex.unlock
210     else
211       queue.push(Object.new)
212       if queue.size > sec
213         # timeout
214         log_error("mutex watchdog timeout: %d sec" % [sec])
215         queue.clear
216       end
217     end
218     sleep(1)
219   end
220 end
221
222 def login_loop(client)
223   player = login = nil
224  
225   while r = select([client], nil, nil, ShogiServer::Login_Time) do
226     str = nil
227     begin
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]}")
232       break
233     end
234     $mutex.lock # guards $league
235     begin
236       str =~ /([\r\n]*)$/
237       eol = $1
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))
245             current_player.kill
246           else
247             login.incorrect_duplicated_player(str)
248             player = nil
249             break
250           end
251         end
252         $league.add(player)
253         break
254       else
255         client.write("LOGIN:incorrect" + eol)
256         client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
257       end
258     ensure
259       $mutex.unlock
260     end
261   end                       # login loop
262   return [player, login]
263 end
264
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"
270   return logger
271 end
272
273 def setup_watchdog_for_giant_lock
274   $mutex = Mutex::new
275   Thread::start do
276     Thread.pass
277     mutex_watchdog($mutex, 10)
278   end
279 end
280
281 def setup_floodgate(game_names)
282   return Thread.start(game_names) do |game_names|
283     Thread.pass
284     while (true)
285       begin
286         leagues = game_names.collect do |game_name|
287           floodgate = ShogiServer::League::Floodgate.new($league, 
288                                                          {:game_name => game_name})
289           log_message("Floodgate reloaded. The next match will start at %s." % 
290                       [floodgate.next_time])
291           floodgate
292         end
293         leagues.delete_if do |floodgate|
294           ret = false
295           unless floodgate.next_time 
296             log_error("Unsupported game name: %s" % floodgate.game_name)
297             ret = true
298           end
299           ret
300         end
301         if leagues.empty?
302           log_error("No valid Floodgate game names found")
303           return # exit from this thread
304         end
305
306         floodgate = leagues.min {|a,b| a.next_time <=> b.next_time}
307         diff = floodgate.next_time - Time.now
308         if diff > 0
309           sleep(diff/2)
310           next
311         end
312         log_message("Starting Floodgate games...: %s" % [floodgate.game_name])
313         $league.reload
314         floodgate.match_game
315         floodgate.charge
316         next_time = floodgate.next_time
317         $mutex.synchronize do
318           log_message("Reloading source...")
319           ShogiServer.reload
320         end
321         floodgate = ShogiServer::League::Floodgate.new($league, 
322                                                        {:game_name => game_name,
323                                                         :next_time => next_time})
324         log_message("Floodgate: The next match of %s will start at %s." % 
325                     [floodgate.game_name, floodgate.next_time])
326       rescue Exception => ex 
327         # ignore errors
328         log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
329       end
330     end
331   end
332 end
333
334 def main
335   
336   $options = parse_command_line
337   check_command_line
338   $config = ShogiServer::Config.new $options
339
340   $league = ShogiServer::League.new($topdir)
341
342   $league.event = ARGV.shift
343   port = ARGV.shift
344
345   log_file = $options["daemon"] ? File.join($options["daemon"], "shogi-server.log") : STDOUT
346   $logger = setup_logger(log_file)
347
348   $league.dir = $topdir
349
350   config = {}
351   config[:Port]       = port
352   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
353   config[:Logger]     = $logger
354
355   fg_thread = nil
356
357   config[:StartCallback] = Proc.new do
358     srand
359     if $options["pid-file"]
360       write_pid_file($options["pid-file"])
361     end
362     setup_watchdog_for_giant_lock
363     $league.setup_players_database
364     fg_thread = setup_floodgate(["floodgate-900-0", "floodgate-3600-0"])
365   end
366
367   config[:StopCallback] = Proc.new do
368     if $options["pid-file"]
369       FileUtils.rm($options["pid-file"], :force => true)
370     end
371   end
372
373   srand
374   server = WEBrick::GenericServer.new(config)
375   ["INT", "TERM"].each do |signal| 
376     trap(signal) do
377       server.shutdown
378       fg_thread.kill if fg_thread
379     end
380   end
381   unless (RUBY_PLATFORM.downcase =~ /mswin|mingw|cygwin|bccwin/)
382     trap("HUP") do
383       Dependencies.clear
384     end
385   end
386   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
387   log_message("server started [Revision: #{ShogiServer::Revision}]")
388
389   server.start do |client|
390       # client.sync = true # this is already set in WEBrick 
391       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
392         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
393       player, login = login_loop(client) # loop
394       next unless player
395
396       log_message(sprintf("user %s login", player.name))
397       login.process
398       player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
399       player.run(login.csa_1st_str) # loop
400       $mutex.lock
401       begin
402         if (player.game)
403           player.game.kill(player)
404         end
405         player.finish # socket has been closed
406         $league.delete(player)
407         log_message(sprintf("user %s logout", player.name))
408       ensure
409         $mutex.unlock
410       end
411   end
412 end
413
414
415 if ($0 == __FILE__)
416   STDOUT.sync = true
417   STDERR.sync = true
418   TCPSocket.do_not_reverse_lookup = true
419   Thread.abort_on_exception = $DEBUG ? true : false
420
421   begin
422     main
423   rescue Exception => ex
424     if $logger
425       log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
426     else
427       $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
428     end
429   end
430 end