OSDN Git Service

* [shogi-server]
[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 $:.unshift File.dirname(__FILE__)
32 require 'shogi_server'
33 require 'tempfile'
34
35 #################################################
36 # MAIN
37 #
38
39 ShogiServer.reload
40
41 def gets_safe(socket, timeout=nil)
42   if r = select([socket], nil, nil, timeout)
43     return r[0].first.gets
44   else
45     return :timeout
46   end
47 rescue Exception => ex
48   log_error("gets_safe: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
49   return :exception
50 end
51
52 def usage
53     print <<EOM
54 NAME
55         shogi-server - server for CSA server protocol
56
57 SYNOPSIS
58         shogi-server [OPTIONS] event_name port_number
59
60 DESCRIPTION
61         server for CSA server protocol
62
63 OPTIONS
64         --pid-file file
65                 specify filename for logging process ID
66         --daemon dir
67                 run as a daemon. Log files will be put in dir.
68         --player-log-dir dir
69                 log network messages for each player. Log files
70                 will be put in the dir.
71         --floodgate-history
72                 file name to record Floodgate game history
73                 default: './floodgate_history.yaml'
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     ["--floodgate-history", GetoptLong::REQUIRED_ARGUMENT])
121   parser.quiet = true
122   begin
123     parser.each_option do |name, arg|
124       name.sub!(/^--/, '')
125       options[name] = arg.dup
126     end
127   rescue
128     usage
129     raise parser.error_message
130   end
131   return options
132 end
133
134 # Check command line options.
135 # If any of them is invalid, exit the process.
136 #
137 def check_command_line
138   if (ARGV.length != 2)
139     usage
140     exit 2
141   end
142
143   if $options["daemon"]
144     $options["daemon"] = File.expand_path($options["daemon"], File.dirname(__FILE__))
145     unless is_writable_dir? $options["daemon"]
146       usage
147       $stderr.puts "Can not create a file in the daemon directory: %s" % [$options["daemon"]]
148       exit 5
149     end
150   end
151
152   $topdir = $options["daemon"] || File.expand_path(File.dirname(__FILE__))
153
154   if $options["player-log-dir"]
155     $options["player-log-dir"] = File.expand_path($options["player-log-dir"], $topdir)
156     unless is_writable_dir?($options["player-log-dir"])
157       usage
158       $stderr.puts "Can not write a file in the player log dir: %s" % [$options["player-log-dir"]]
159       exit 3
160     end 
161   end
162
163   if $options["pid-file"] 
164     $options["pid-file"] = File.expand_path($options["pid-file"], $topdir)
165     unless is_writable_file? $options["pid-file"]
166       usage
167       $stderr.puts "Can not create the pid file: %s" % [$options["pid-file"]]
168       exit 4
169     end
170   end
171
172   $options["floodgate-history"] ||= File.join($topdir, "floodgate_history.yaml")
173   $options["floodgate-history"] = File.expand_path($options["floodgate-history"], $topdir)
174   unless is_writable_file? $options["floodgate-history"]
175     usage
176     $stderr.puts "Can not create the floodgate history file: %s" % [$options["floodgate-history"]]
177     exit 6
178   end
179 end
180
181 # See if the file is writable. The file will be created if it does not exist
182 # yet.
183 # Return true if the file is writable, otherwise false.
184 #
185 def is_writable_file?(file)
186   if File.exist?(file)
187     if FileTest.file?(file)
188       return FileTest.writable_real?(file)
189     else
190       return false
191     end
192   end
193   
194   begin
195     open(file, "w") {|fh| } 
196     FileUtils.rm file
197   rescue
198     return false
199   end
200
201   return true
202 end
203
204 # See if a file can be created in the directory.
205 # Return true if a file is writable in the directory, otherwise false.
206 #
207 def is_writable_dir?(dir)
208   unless File.directory? dir
209     return false
210   end
211
212   result = true
213
214   begin
215     temp_file = Tempfile.new("dummy-shogi-server", dir)
216     temp_file.close true
217   rescue
218     result = false
219   end
220
221   return result
222 end
223
224 def write_pid_file(file)
225   open(file, "w") do |fh|
226     fh.puts "#{$$}"
227   end
228 end
229
230 def mutex_watchdog(mutex, sec)
231   sec = 1 if sec < 1
232   queue = []
233   while true
234     if mutex.try_lock
235       queue.clear
236       mutex.unlock
237     else
238       queue.push(Object.new)
239       if queue.size > sec
240         # timeout
241         log_error("mutex watchdog timeout: %d sec" % [sec])
242         queue.clear
243       end
244     end
245     sleep(1)
246   end
247 end
248
249 def login_loop(client)
250   player = login = nil
251  
252   while r = select([client], nil, nil, ShogiServer::Login_Time) do
253     break unless str = r[0].first.gets
254     $mutex.lock # guards $league
255     begin
256       str =~ /([\r\n]*)$/
257       eol = $1
258       if (ShogiServer::Login::good_login?(str))
259         player = ShogiServer::Player::new(str, client, eol)
260         login  = ShogiServer::Login::factory(str, player)
261         if (current_player = $league.find(player.name))
262           if (current_player.password == player.password &&
263               current_player.status != "game")
264             log_message(sprintf("user %s login forcely", player.name))
265             current_player.kill
266           else
267             login.incorrect_duplicated_player(str)
268             player = nil
269             break
270           end
271         end
272         $league.add(player)
273         break
274       else
275         client.write("LOGIN:incorrect" + eol)
276         client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
277       end
278     ensure
279       $mutex.unlock
280     end
281   end                       # login loop
282   return [player, login]
283 end
284
285 def setup_logger(log_file)
286   logger = ShogiServer::Logger.new(log_file, 'daily')
287   logger.formatter = ShogiServer::Formatter.new
288   logger.level = $DEBUG ? Logger::DEBUG : Logger::INFO  
289   logger.datetime_format = "%Y-%m-%d %H:%M:%S"
290   return logger
291 end
292
293 def setup_watchdog_for_giant_lock
294   $mutex = Mutex::new
295   Thread::start do
296     Thread.pass
297     mutex_watchdog($mutex, 10)
298   end
299 end
300
301 def setup_floodgate
302   return Thread.start do 
303     Thread.pass
304     floodgate = ShogiServer::League::Floodgate.new($league)
305     log_message("Flooddgate reloaded. The next match will start at %s." % 
306                 [floodgate.next_time])
307
308     while (true)
309       begin
310         diff = floodgate.next_time - Time.now
311         if diff > 0
312           sleep(diff/2)
313           next
314         end
315         $league.reload
316         floodgate.match_game
317         floodgate.charge
318         next_time = floodgate.next_time
319         $mutex.synchronize do
320           log_message("Reloading source...")
321           ShogiServer.reload
322         end
323         floodgate = ShogiServer::League::Floodgate.new($league, next_time)
324         log_message("Floodgate: The next match will start at %s." % 
325                     [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
339   $league = ShogiServer::League.new($topdir)
340
341   $league.event = ARGV.shift
342   port = ARGV.shift
343
344   log_file = $options["daemon"] ? File.join($options["daemon"], "shogi-server.log") : STDOUT
345   $logger = setup_logger(log_file)
346
347   $league.dir = $topdir
348
349   config = {}
350   config[:Port]       = port
351   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
352   config[:Logger]     = $logger
353
354   fg_thread = nil
355
356   config[:StartCallback] = Proc.new do
357     srand
358     if $options["pid-file"]
359       write_pid_file($options["pid-file"])
360     end
361     setup_watchdog_for_giant_lock
362     $league.setup_players_database
363     fg_thread = setup_floodgate
364   end
365
366   config[:StopCallback] = Proc.new do
367     if $options["pid-file"]
368       FileUtils.rm($options["pid-file"], :force => true)
369     end
370   end
371
372   srand
373   server = WEBrick::GenericServer.new(config)
374   ["INT", "TERM"].each do |signal| 
375     trap(signal) do
376       server.shutdown
377       fg_thread.kill if fg_thread
378     end
379   end
380   trap("HUP") do
381     Dependencies.clear
382   end
383   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
384   log_message("server started [Revision: #{ShogiServer::Revision}]")
385
386   server.start do |client|
387       # client.sync = true # this is already set in WEBrick 
388       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
389         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
390       player, login = login_loop(client) # loop
391       next unless player
392
393       log_message(sprintf("user %s login", player.name))
394       login.process
395       player.setup_logger($options["player-log-dir"]) if $options["player-log-dir"]
396       player.run(login.csa_1st_str) # loop
397       $mutex.lock
398       begin
399         if (player.game)
400           player.game.kill(player)
401         end
402         player.finish # socket has been closed
403         $league.delete(player)
404         log_message(sprintf("user %s logout", player.name))
405       ensure
406         $mutex.unlock
407       end
408   end
409 end
410
411
412 if ($0 == __FILE__)
413   STDOUT.sync = true
414   STDERR.sync = true
415   TCPSocket.do_not_reverse_lookup = true
416   Thread.abort_on_exception = $DEBUG ? true : false
417
418   begin
419     main
420   rescue Exception => ex
421     if $logger
422       log_error("main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
423     else
424       $stderr.puts "main: #{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"
425     end
426   end
427 end