source: trunk/athena/bin/athinfo/athinfo @ 24428

Revision 24428, 1.4 KB checked in by broder, 15 years ago (diff)
athinfo: Apply the timeout to the entire query, not just the connection. An athinfo query could run for an arbitrary amount of time, which is really just as bad as taking an arbitrary time trying to establish a connection. Instead of timing out on the connect() itself, set an alarm before we connect and exit if the alarm goes off.
  • Property svn:executable set to *
Line 
1#!/usr/bin/python
2
3import optparse
4import os
5import signal
6import socket
7import sys
8
9ATHINFO_FALLBACK_PORT = 49155
10
11def alarm(signum, frame):
12    print >>sys.stderr, 'athinfo: timed out'
13    sys.exit(1)
14
15def main():
16    parser = optparse.OptionParser(
17        usage='%prog [options] host query'
18        )
19    parser.add_option(
20        '-t', '--timeout',
21        type='int',
22        dest='timeout',
23        help='timeout after SECONDS',
24        metavar='SECONDS',
25        )
26
27    (options, args) = parser.parse_args()
28    if len(args) != 2:
29        parser.print_usage()
30        return 1
31    host = args[0]
32    query = args[1]
33
34    try:
35        port = socket.getservbyname('athinfo', 'tcp')
36    except socket.error:
37        port = ATHINFO_FALLBACK_PORT
38
39    try:
40        host_addr = socket.gethostbyname(host)
41    except socket.error:
42        print >>sys.stderr, 'athinfo: host %s not found' % host
43        return 1
44
45    try:
46        s = socket.socket()
47
48        if options.timeout:
49            signal.signal(signal.SIGALRM, alarm)
50            signal.alarm(options.timeout)
51
52        s.connect((host_addr, port))
53        s.sendall('%s\n' % query)
54        sys.stdout.write(s.makefile().read())
55    except socket.error, e:
56        print >>sys.stderr, 'athinfo: %s' % e.args[-1]
57        return 1
58    except KeyboardInterrupt:
59        return 1
60
61
62if __name__ == '__main__':
63    sys.exit(main())
Note: See TracBrowser for help on using the repository browser.