comparison server/utils.py @ 328:46070aaf29ea

A bit of work on the server python
author Matt Johnston <matt@ucc.asn.au>
date Sat, 26 May 2012 10:17:27 +0800
parents
children b5925cb4f264
comparison
equal deleted inserted replaced
327:5639c74f2cbb 328:46070aaf29ea
1 import os
2 import sys
3 import ctypes
4 import time
5 import select
6
7 DEFAULT_TRIES = 3
8
9 __all__ = ('monotonic_time', 'retry')
10
11 clock_gettime = None
12 no_clock_gettime = False
13 def monotonic_time():
14 global clock_gettime
15 global no_clock_gettime
16 if no_clock_gettime:
17 return time.time()
18
19 class timespec(ctypes.Structure):
20 _fields_ = [
21 ('tv_sec', ctypes.c_long),
22 ('tv_nsec', ctypes.c_long)
23 ]
24 if not clock_gettime:
25 try:
26 librt = ctypes.CDLL('librt.so.0', use_errno=True)
27 clock_gettime = librt.clock_gettime
28 clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
29 except:
30 print>>sys.stderr, "No clock_gettime(), using fake fallback."
31 no_clock_gettime = True
32 return time.time()
33
34 t = timespec()
35 CLOCK_MONOTONIC = 1 # see <linux/time.h>
36
37 if clock_gettime(CLOCK_MONOTONIC, ctypes.pointer(t)) != 0:
38 errno_ = ctypes.get_errno()
39 raise OSError(errno_, os.strerror(errno_))
40 return t.tv_sec + t.tv_nsec * 1e-9
41
42 # decorator, tries a number of times, returns None on failure, sleeps between
43 # Must be used as "@retry()" if arguments are defaulted
44 def retry(retries=DEFAULT_TRIES, try_time = 1):
45 def inner(func):
46 print "inner"
47 def new_f(*args, **kwargs):
48 print "newf"
49 for i in range(retries):
50 print "retry %d" % i
51 d = func(*args, **kwargs)
52 if d:
53 return d
54 time.sleep(try_time)
55 new_f.func_name = func.func_name
56 return new_f
57 return inner
58
59 def readline(sock):
60 timeout = READLINE_SELECT_TIMEOUT
61 buf = ''
62 while true:
63 (rlist, wlist, xlist) = select.select([sock], [], [], timeout)
64 if sock not in rlist:
65 # hit timeout
66 return None
67
68 c = sock.recv(1)
69 if c == '\r':
70 continue
71
72 buf.append(c)
73 if c == '\n':
74 return buf
75