OSDN Git Service

* Changed the stley of the comment lines to RDoc's one.
[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 TOP_DIR = File.expand_path(File.dirname(__FILE__))
29 $:.unshift File.dirname(__FILE__)
30 require 'shogi_server'
31
32 #################################################
33 # MAIN
34 #
35
36 ShogiServer.reload
37
38 def gets_safe(socket, timeout=nil)
39   if r = select([socket], nil, nil, timeout)
40     return r[0].first.gets
41   else
42     return :timeout
43   end
44 rescue Exception => ex
45   log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
46   return :exception
47 end
48
49 def usage
50     print <<EOM
51 NAME
52         shogi-server - server for CSA server protocol
53
54 SYNOPSIS
55         shogi-server [OPTIONS] event_name port_number
56
57 DESCRIPTION
58         server for CSA server protocol
59
60 OPTIONS
61         --pid-file file
62                 specify filename for logging process ID
63         --daemon dir
64                 run as a daemon. Log files will be put in dir.
65         --player-log-dir dir
66                 log network messages for each player. Log files
67                 will be put in the dir.
68         --floodgate-history
69                 file name to record Floodgate game history
70                 default: './floodgate_history.yaml'
71
72 LICENSE
73         GPL versoin 2 or later
74
75 SEE ALSO
76
77 RELEASE
78         #{ShogiServer::Release}
79
80 REVISION
81         #{ShogiServer::Revision}
82 EOM
83 end
84
85
86 def log_debug(str)
87   $logger.debug(str)
88 end
89
90 def log_message(str)
91   $logger.info(str)
92 end
93 def log_info(str)
94   log_message(str)
95 end
96
97 def log_warning(str)
98   $logger.warn(str)
99 end
100
101 def log_error(str)
102   $logger.error(str)
103 end
104
105
106 def parse_command_line
107   options = Hash::new
108   parser = GetoptLong.new(
109     ["--daemon",            GetoptLong::REQUIRED_ARGUMENT],
110     ["--pid-file",          GetoptLong::REQUIRED_ARGUMENT],
111     ["--player-log-dir",    GetoptLong::REQUIRED_ARGUMENT],
112     ["--floodgate-history", GetoptLong::REQUIRED_ARGUMENT])
113   parser.quiet = true
114   begin
115     parser.each_option do |name, arg|
116       name.sub!(/^--/, '')
117       options[name] = arg.dup
118     end
119   rescue
120     usage
121     raise parser.error_message
122   end
123   return options
124 end
125
126 def write_pid_file(file)
127   open(file, "w") do |fh|
128     fh.puts "#{$$}"
129   end
130 end
131
132 def mutex_watchdog(mutex, sec)
133   sec = 1 if sec < 1
134   queue = []
135   while true
136     if mutex.try_lock
137       queue.clear
138       mutex.unlock
139     else
140       queue.push(Object.new)
141       if queue.size > sec
142         # timeout
143         log_error("mutex watchdog timeout: %d sec" % [sec])
144         queue.clear
145       end
146     end
147     sleep(1)
148   end
149 end
150
151 def login_loop(client)
152   player = login = nil
153  
154   while r = select([client], nil, nil, ShogiServer::Login_Time) do
155     break unless str = r[0].first.gets
156     $mutex.lock # guards LEAGUE
157     begin
158       str =~ /([\r\n]*)$/
159       eol = $1
160       if (ShogiServer::Login::good_login?(str))
161         player = ShogiServer::Player::new(str, client, eol)
162         login  = ShogiServer::Login::factory(str, player)
163         if (current_player = LEAGUE.find(player.name))
164           if (current_player.password == player.password &&
165               current_player.status != "game")
166             log_message(sprintf("user %s login forcely", player.name))
167             current_player.kill
168           else
169             login.incorrect_duplicated_player(str)
170             player = nil
171             break
172           end
173         end
174         LEAGUE.add(player)
175         break
176       else
177         client.write("LOGIN:incorrect" + eol)
178         client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
179       end
180     ensure
181       $mutex.unlock
182     end
183   end                       # login loop
184   return [player, login]
185 end
186
187 def setup_logger(log_file)
188   logger = Logger.new(log_file, 'daily')
189   logger.formatter = ShogiServer::Formatter.new
190   logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO  
191   logger.datetime_format = "%Y-%m-%d %H:%M:%S"
192   return logger
193 end
194
195 def setup_watchdog_for_giant_lock
196   $mutex = Mutex::new
197   Thread::start do
198     Thread.pass
199     mutex_watchdog($mutex, 10)
200   end
201 end
202
203 def setup_floodgate
204   return Thread.start do 
205     Thread.pass
206     floodgate = ShogiServer::League::Floodgate.new(LEAGUE)
207     log_message("Flooddgate reloaded. The next match will start at %s." % 
208                 [floodgate.next_time])
209
210     while (true)
211       begin
212         diff = floodgate.next_time - Time.now
213         if diff > 0
214           sleep(diff/2)
215           next
216         end
217         LEAGUE.reload
218         floodgate.match_game
219         floodgate.charge
220         next_time = floodgate.next_time
221         $mutex.synchronize do
222           log_message("Reloading source...")
223           ShogiServer.reload
224         end
225         floodgate = ShogiServer::League::Floodgate.new(LEAGUE, next_time)
226         log_message("Floodgate: The next match will start at %s." % 
227                     [floodgate.next_time])
228       rescue Exception => ex 
229         # ignore errors
230         log_error("[in Floodgate's thread] #{ex} #{ex.backtrace}")
231       end
232     end
233   end
234 end
235
236 def main
237   
238   $options = parse_command_line
239   if (ARGV.length != 2)
240     usage
241     exit 2
242   end
243   if $options["player-log-dir"]
244     $options["player-log-dir"] = File.expand_path($options["player-log-dir"])
245   end
246   if $options["player-log-dir"] && 
247      !File.directory?($options["player-log-dir"])
248     usage
249     exit 3
250   end
251   if $options["pid-file"] 
252     $options["pid-file"] = File.expand_path($options["pid-file"])
253   end
254   $options["floodgate-history"] ||= File.join(File.dirname(__FILE__), "floodgate_history.yaml")
255   $options["floodgate-history"] = File.expand_path($options["floodgate-history"])
256
257   LEAGUE.event = ARGV.shift
258   port = ARGV.shift
259
260   dir = $options["daemon"]
261   dir = File.expand_path(dir) if dir
262   if dir && ! File.exist?(dir)
263     FileUtils.mkdir(dir)
264   end
265
266   log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
267   $logger = setup_logger(log_file)
268
269   LEAGUE.dir = dir || TOP_DIR
270
271   config = {}
272   config[:Port]       = port
273   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
274   config[:Logger]     = $logger
275
276   fg_thread = nil
277
278   config[:StartCallback] = Proc.new do
279     srand
280     if $options["pid-file"]
281       write_pid_file($options["pid-file"])
282     end
283     setup_watchdog_for_giant_lock
284     LEAGUE.setup_players_database
285     fg_thread = setup_floodgate
286   end
287
288   config[:StopCallback] = Proc.new do
289     if $options["pid-file"]
290       FileUtils.rm($options["pid-file"], :force => true)
291     end
292   end
293
294   srand
295   server = WEBrick::GenericServer.new(config)
296   ["INT", "TERM"].each do |signal| 
297     trap(signal) do
298       server.shutdown
299       fg_thread.kill if fg_thread
300     end
301   end
302   trap("HUP") do
303     Dependencies.clear
304   end
305   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
306   log_message("server started [Revision: #{ShogiServer::Revision}]")
307
308   server.start do |client|
309       # client.sync = true # this is already set in WEBrick 
310       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
311         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
312       player, login = login_loop(client) # loop
313       next unless player
314
315       log_message(sprintf("user %s login", player.name))
316       login.process
317       player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
318       player.run(login.csa_1st_str) # loop
319       $mutex.lock
320       begin
321         if (player.game)
322           player.game.kill(player)
323         end
324         player.finish # socket has been closed
325         LEAGUE.delete(player)
326         log_message(sprintf("user %s logout", player.name))
327       ensure
328         $mutex.unlock
329       end
330   end
331 end
332
333
334 if ($0 == __FILE__)
335   STDOUT.sync = true
336   STDERR.sync = true
337   TCPSocket.do_not_reverse_lookup = true
338   Thread.abort_on_exception = $DEBUG ? true : false
339
340   begin
341     LEAGUE = ShogiServer::League.new(TOP_DIR)
342     main
343   rescue Exception => ex
344     if $logger
345       log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
346     else
347       $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
348     end
349   end
350 end