OSDN Git Service

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