OSDN Git Service

Debugged the daemon mode
[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 TOP_DIR = File.expand_path(File.dirname(__FILE__))
22 $:.unshift File.dirname(__FILE__)
23 require 'shogi_server'
24
25 #################################################
26 # MAIN
27 #
28
29 ShogiServer.reload
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   return 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         diff = floodgate.next_time - Time.now
199         if diff > 0
200           sleep(diff/2)
201           next
202         end
203         LEAGUE.reload
204         floodgate.match_game
205         floodgate.charge
206         next_time = floodgate.next_time
207         $mutex.synchronize do
208           log_message("Reloading source...")
209           ShogiServer.reload
210         end
211         floodgate = ShogiServer::League::Floodgate.new(LEAGUE, next_time)
212         log_message("Floodgate will start the next match at %s." % 
213                     [floodgate.next_time])
214       rescue Exception => ex 
215         # ignore errors
216         log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
217       end
218     end
219   end
220 end
221
222 def main
223   
224   $options = parse_command_line
225   if (ARGV.length != 2)
226     usage
227     exit 2
228   end
229   if $options["player-log-dir"]
230     $options["player-log-dir"] = File.expand_path($options["player-log-dir"])
231   end
232   if $options["player-log-dir"] && 
233      !File.directory?($options["player-log-dir"])
234     usage
235     exit 3
236   end
237   if $options["pid-file"] 
238     $options["pid-file"] = File.expand_path($options["pid-file"])
239   end
240
241   LEAGUE.event = ARGV.shift
242   port = ARGV.shift
243
244   dir = $options["daemon"]
245   dir = File.expand_path(dir) if dir
246   if dir && ! File.exist?(dir)
247     FileUtils.mkdir(dir)
248   end
249
250   log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
251   $logger = setup_logger(log_file)
252
253   LEAGUE.dir = dir || TOP_DIR
254
255   config = {}
256   config[:Port]       = port
257   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
258   config[:Logger]     = $logger
259
260   fg_thread = nil
261
262   config[:StartCallback] = Proc.new do
263     if $options["pid-file"]
264       write_pid_file($options["pid-file"])
265     end
266     setup_watchdog_for_giant_lock
267     LEAGUE.setup_players_database
268     fg_thread = setup_floodgate
269   end
270
271   config[:StopCallback] = Proc.new do
272     if $options["pid-file"]
273       FileUtils.rm($options["pid-file"], :force => true)
274     end
275   end
276
277   server = WEBrick::GenericServer.new(config)
278   ["INT", "TERM"].each do |signal| 
279     trap(signal) do
280       server.shutdown
281       fg_thread.kill if fg_thread
282     end
283   end
284   trap("HUP") do
285     Dependencies.clear
286   end
287   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
288   log_message("server started [Revision: #{ShogiServer::Revision}]")
289
290   server.start do |client|
291       # client.sync = true # this is already set in WEBrick 
292       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
293         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
294       player, login = login_loop(client) # loop
295       next unless player
296
297       log_message(sprintf("user %s login", player.name))
298       login.process
299       player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
300       player.run(login.csa_1st_str) # loop
301       $mutex.lock
302       begin
303         if (player.game)
304           player.game.kill(player)
305         end
306         player.finish # socket has been closed
307         LEAGUE.delete(player)
308         log_message(sprintf("user %s logout", player.name))
309       ensure
310         $mutex.unlock
311       end
312   end
313 end
314
315
316 if ($0 == __FILE__)
317   STDOUT.sync = true
318   STDERR.sync = true
319   TCPSocket.do_not_reverse_lookup = true
320   Thread.abort_on_exception = $DEBUG ? true : false
321
322   begin
323     LEAGUE = ShogiServer::League.new(TOP_DIR)
324     main
325   rescue Exception => ex
326     log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
327   end
328 end