OSDN Git Service

Under debugging
[shogi-server/shogi-server.git] / shogi-server
1 #! /usr/bin/env ruby
2 ## $Id$
3
4 ## Copyright (C) 2004 NABEYA Kenichi (aka nanami@2ch)
5 ## Copyright (C) 2007-2008 Daigo Moriwaki (daigo at debian dot org)
6 ##
7 ## This program is free software; you can redistribute it and/or modify
8 ## it under the terms of the GNU General Public License as published by
9 ## the Free Software Foundation; either version 2 of the License, or
10 ## (at your option) any later version.
11 ##
12 ## This program is distributed in the hope that it will be useful,
13 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
14 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 ## GNU General Public License for more details.
16 ##
17 ## You should have received a copy of the GNU General Public License
18 ## along with this program; if not, write to the Free Software
19 ## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20
21 $:.unshift File.dirname(__FILE__)
22 require 'shogi_server'
23 require 'shogi_server/board' # not autoloaded
24 require 'shogi_server/player'
25 require 'shogi_server/game'
26
27 #################################################
28 # MAIN
29 #
30
31 def gets_safe(socket, timeout=nil)
32   if r = select([socket], nil, nil, timeout)
33     return r[0].first.gets
34   else
35     return :timeout
36   end
37 rescue Exception => ex
38   log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
39   return :exception
40 end
41
42 def usage
43     print <<EOM
44 NAME
45         shogi-server - server for CSA server protocol
46
47 SYNOPSIS
48         shogi-server [OPTIONS] event_name port_number
49
50 DESCRIPTION
51         server for CSA server protocol
52
53 OPTIONS
54         --pid-file file
55                 specify filename for logging process ID
56         --daemon dir
57                 run as a daemon. Log files will be put in dir.
58         --player-log-dir dir
59                 log network messages for each player. Log files
60                 will be put in the dir.
61
62 LICENSE
63         GPL versoin 2 or later
64
65 SEE ALSO
66
67 RELEASE
68         #{ShogiServer::Release}
69
70 REVISION
71         #{ShogiServer::Revision}
72 EOM
73 end
74
75
76 def log_debug(str)
77   $logger.debug(str)
78 end
79
80 def log_message(str)
81   $logger.info(str)
82 end
83
84 def log_warning(str)
85   $logger.warn(str)
86 end
87
88 def log_error(str)
89   $logger.error(str)
90 end
91
92
93 def parse_command_line
94   options = Hash::new
95   parser = GetoptLong.new(
96     ["--daemon",   GetoptLong::REQUIRED_ARGUMENT],
97     ["--pid-file", GetoptLong::REQUIRED_ARGUMENT],
98     ["--player-log-dir", GetoptLong::REQUIRED_ARGUMENT])
99   parser.quiet = true
100   begin
101     parser.each_option do |name, arg|
102       name.sub!(/^--/, '')
103       options[name] = arg.dup
104     end
105   rescue
106     usage
107     raise parser.error_message
108   end
109   return options
110 end
111
112 def write_pid_file(file)
113   open(file, "w") do |fh|
114     fh.puts "#{$$}"
115   end
116 end
117
118 def mutex_watchdog(mutex, sec)
119   sec = 1 if sec < 1
120   queue = []
121   while true
122     if mutex.try_lock
123       queue.clear
124       mutex.unlock
125     else
126       queue.push(Object.new)
127       if queue.size > sec
128         # timeout
129         log_error("mutex watchdog timeout: %d sec" % [sec])
130         queue.clear
131       end
132     end
133     sleep(1)
134   end
135 end
136
137 def login_loop(client)
138   player = login = nil
139  
140   while r = select([client], nil, nil, ShogiServer::Login_Time) do
141     break unless str = r[0].first.gets
142     $mutex.lock # guards LEAGUE
143     begin
144       str =~ /([\r\n]*)$/
145       eol = $1
146       if (ShogiServer::Login::good_login?(str))
147         player = ShogiServer::Player::new(str, client, eol)
148         login  = ShogiServer::Login::factory(str, player)
149         if (current_player = LEAGUE.find(player.name))
150           if (current_player.password == player.password &&
151               current_player.status != "game")
152             log_message(sprintf("user %s login forcely", player.name))
153             current_player.kill
154           else
155             login.incorrect_duplicated_player(str)
156             player = nil
157             break
158           end
159         end
160         LEAGUE.add(player)
161         break
162       else
163         client.write("LOGIN:incorrect" + eol)
164         client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
165       end
166     ensure
167       $mutex.unlock
168     end
169   end                       # login loop
170   return [player, login]
171 end
172
173 def setup_logger(log_file)
174   logger = Logger.new(log_file, 'daily')
175   logger.formatter = ShogiServer::Formatter.new
176   logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO  
177   logger.datetime_format = "%Y-%m-%d %H:%M:%S"
178   return logger
179 end
180
181 def setup_watchdog_for_giant_lock
182   $mutex = Mutex::new
183   Thread::start do
184     Thread.pass
185     mutex_watchdog($mutex, 10)
186   end
187 end
188
189 def setup_floodgate
190   Thread.start do 
191     Thread.pass
192     floodgate = ShogiServer::League::Floodgate.new(LEAGUE)
193     log_message("Flooddgate reloaded. The next match will start at %s." % 
194                 [floodgate.next_time])
195
196     while (true)
197       begin
198         sleep(10)
199         next if Time.now < floodgate.next_time
200         LEAGUE.reload
201         floodgate.match_game
202         floodgate.charge
203         next_time = floodgate.next_time
204         $mutex.synchronize do
205           Dependencies.clear
206         end
207         floodgate = ShogiServer::League::Floodgate.new(LEAGUE, next_time)
208         log_message("Flooddgate reloaded. The next match will start at %s." % 
209                 [floodgate.next_time])
210       rescue Exception => ex 
211         # ignore errors
212         log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
213       end
214     end
215   end
216 end
217
218 def main
219   
220   [ShogiServer::League::Floodgate, ShogiServer::Pairing].each do |klass|
221     Dependencies.unloadable klass
222   end
223
224   setup_watchdog_for_giant_lock
225
226   $options = parse_command_line
227   if (ARGV.length != 2)
228     usage
229     exit 2
230   end
231   if $options["player-log-dir"]
232     $options["player-log-dir"] = File.expand_path($options["player-log-dir"])
233   end
234   if $options["player-log-dir"] && 
235      !File.directory?($options["player-log-dir"])
236     usage
237     exit 3
238   end
239
240   LEAGUE.event = ARGV.shift
241   port = ARGV.shift
242
243   dir = $options["daemon"]
244   dir = File.expand_path(dir) if dir
245   if dir && ! File.exist?(dir)
246     FileUtils.mkdir(dir)
247   end
248
249   log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
250   $logger = setup_logger(log_file)
251
252   LEAGUE.dir = dir || File.dirname(__FILE__)
253   LEAGUE.setup_players_database
254
255   config = {}
256   config[:Port]       = port
257   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
258   config[:Logger]     = $logger
259
260   config[:StartCallback] = Proc.new do
261     if $options["pid-file"]
262       write_pid_file($options["pid-file"])
263     end
264     setup_floodgate
265   end
266
267   config[:StopCallback] = Proc.new do
268     if $options["pid-file"]
269       FileUtils.rm(pid_file, :force => true)
270     end
271   end
272
273   server = WEBrick::GenericServer.new(config)
274   ["INT", "TERM"].each do |signal| 
275     trap(signal) do
276       LEAGUE.shutdown
277       server.shutdown
278       # TODO Shutdown Floodgate's thread
279     end
280   end
281   trap("HUP") do
282     LEAGUE.shutdown
283     Dependencies.clear
284     # TODO Restart Floodgate's thread
285   end
286   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
287   log_message("server started [Revision: #{ShogiServer::Revision}]")
288
289   server.start do |client|
290       # client.sync = true # this is already set in WEBrick 
291       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
292         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
293       player, login = login_loop(client) # loop
294       next unless player
295
296       log_message(sprintf("user %s login", player.name))
297       login.process
298       player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
299       player.run(login.csa_1st_str) # loop
300       $mutex.lock
301       begin
302         if (player.game)
303           player.game.kill(player)
304         end
305         player.finish # socket has been closed
306         LEAGUE.delete(player)
307         log_message(sprintf("user %s logout", player.name))
308       ensure
309         $mutex.unlock
310       end
311   end
312 end
313
314
315 if ($0 == __FILE__)
316   STDOUT.sync = true
317   STDERR.sync = true
318   TCPSocket.do_not_reverse_lookup = true
319   Thread.abort_on_exception = $DEBUG ? true : false
320
321   begin
322   LEAGUE = ShogiServer::League::new
323     main
324   rescue Exception => ex
325     log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
326   end
327 end