OSDN Git Service

* [shogi-server]
[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
24 #################################################
25 # MAIN
26 #
27
28 def gets_safe(socket, timeout=nil)
29   if r = select([socket], nil, nil, timeout)
30     return r[0].first.gets
31   else
32     return :timeout
33   end
34 rescue Exception => ex
35   log_error("#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}")
36   return :exception
37 end
38
39 def usage
40     print <<EOM
41 NAME
42         shogi-server - server for CSA server protocol
43
44 SYNOPSIS
45         shogi-server [OPTIONS] event_name port_number
46
47 DESCRIPTION
48         server for CSA server protocol
49
50 OPTIONS
51         --pid-file file
52                 specify filename for logging process ID
53         --daemon dir
54                 run as a daemon. Log files will be put in dir.
55
56 LICENSE
57         GPL versoin 2 or later
58
59 SEE ALSO
60
61 RELEASE
62         #{ShogiServer::Release}
63
64 REVISION
65         #{ShogiServer::Revision}
66 EOM
67 end
68
69
70 def log_debug(str)
71   $logger.debug(str)
72 end
73
74 def log_message(str)
75   $logger.info(str)
76 end
77
78 def log_warning(str)
79   $logger.warn(str)
80 end
81
82 def log_error(str)
83   $logger.error(str)
84 end
85
86
87 def parse_command_line
88   options = Hash::new
89   parser = GetoptLong.new(
90     ["--daemon",   GetoptLong::REQUIRED_ARGUMENT],
91     ["--pid-file", GetoptLong::REQUIRED_ARGUMENT])
92   parser.quiet = true
93   begin
94     parser.each_option do |name, arg|
95       name.sub!(/^--/, '')
96       options[name] = arg.dup
97     end
98   rescue
99     usage
100     raise parser.error_message
101   end
102   return options
103 end
104
105 def write_pid_file(file)
106   open(file, "w") do |fh|
107     fh.puts "#{$$}"
108   end
109 end
110
111 def mutex_watchdog(mutex, sec)
112   while true
113     begin
114       timeout(sec) do
115         begin
116           mutex.lock
117         ensure
118           mutex.unlock
119         end
120       end
121       sleep(sec)
122     rescue TimeoutError
123       log_error("mutex watchdog timeout")
124       exit(1)
125     end
126   end
127 end
128
129 def login_loop(client)
130   player = login = nil
131  
132   while r = select([client], nil, nil, ShogiServer::Login_Time) do
133     break unless str = r[0].first.gets
134     $mutex.lock # guards LEAGUE
135     begin
136       str =~ /([\r\n]*)$/
137       eol = $1
138       if (ShogiServer::Login::good_login?(str))
139         player = ShogiServer::Player::new(str, client, eol)
140         login  = ShogiServer::Login::factory(str, player)
141         if (current_player = LEAGUE.find(player.name))
142           if (current_player.password == player.password &&
143               current_player.status != "game")
144             log_message(sprintf("user %s login forcely", player.name))
145             current_player.kill
146           else
147             login.incorrect_duplicated_player(str)
148             player = nil
149             break
150           end
151         end
152         LEAGUE.add(player)
153         break
154       else
155         client.write("LOGIN:incorrect" + eol)
156         client.write("type 'LOGIN name password' or 'LOGIN name password x1'" + eol) if (str.split.length >= 4)
157       end
158     ensure
159       $mutex.unlock
160     end
161   end                       # login loop
162   return [player, login]
163 end
164
165 def setup_logger(log_file)
166   logger = Logger.new(log_file, 'daily')
167   logger.formatter = ShogiServer::Formatter.new
168   logger.level = Logger::INFO  
169   logger.datetime_format = "%Y-%m-%d %H:%M:%S"
170   return logger
171 end
172
173 def setup_watchdog_for_giant_lock
174   $mutex = Mutex::new
175   Thread::start do
176     Thread.pass
177     mutex_watchdog($mutex, 10)
178   end
179 end
180
181 def main
182
183   setup_watchdog_for_giant_lock
184
185   $options = parse_command_line
186   if (ARGV.length != 2)
187     usage
188     exit 2
189   end
190
191   LEAGUE.event = ARGV.shift
192   port = ARGV.shift
193
194   dir = $options["daemon"]
195   dir = File.expand_path(dir) if dir
196   if dir && ! File.exist?(dir)
197     FileUtils.mkdir(dir)
198   end
199
200   log_file = dir ? File.join(dir, "shogi-server.log") : STDOUT
201   $logger = setup_logger(log_file)
202
203   LEAGUE.dir = dir || File.dirname(__FILE__)
204   LEAGUE.setup_players_database
205
206   config = {}
207   config[:Port]       = port
208   config[:ServerType] = WEBrick::Daemon if $options["daemon"]
209   config[:Logger]     = $logger
210   if $options["pid-file"]
211     pid_file = File.expand_path($options["pid-file"])
212     config[:StartCallback] = Proc.new do
213       write_pid_file(pid_file)
214     end
215     config[:StopCallback] = Proc.new do
216       FileUtils.rm(pid_file, :force => true)
217     end
218   end
219
220   server = WEBrick::GenericServer.new(config)
221   ["INT", "TERM"].each do |signal| 
222     trap(signal) do
223       LEAGUE.shutdown
224       server.shutdown
225     end
226   end
227   trap("HUP") do
228     LEAGUE.shutdown
229     Dependencies.clear
230     LEAGUE.restart
231   end
232   $stderr.puts("server started as a deamon [Revision: #{ShogiServer::Revision}]") if $options["daemon"] 
233   log_message("server started [Revision: #{ShogiServer::Revision}]")
234
235   server.start do |client|
236       # client.sync = true # this is already set in WEBrick 
237       client.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
238         # Keepalive time can be set by /proc/sys/net/ipv4/tcp_keepalive_time
239       player, login = login_loop(client) # loop
240       next unless player
241
242       log_message(sprintf("user %s login", player.name))
243       login.process
244       player.run(login.csa_1st_str) # loop
245       $mutex.lock
246       begin
247         if (player.game)
248           player.game.kill(player)
249         end
250         player.finish # socket has been closed
251         LEAGUE.delete(player)
252         log_message(sprintf("user %s logout", player.name))
253       ensure
254         $mutex.unlock
255       end
256   end
257 end
258
259
260 if ($0 == __FILE__)
261   STDOUT.sync = true
262   STDERR.sync = true
263   TCPSocket.do_not_reverse_lookup = true
264   Thread.abort_on_exception = $DEBUG ? true : false
265
266   LEAGUE = ShogiServer::League::new
267   main
268 end