12 # TODO: maybe when there's more time; for better readability.
13 #class History(Structure):
14 # _fields_ = [ ("version", c_int),
16 # ("history", c_float * HISTORY_LENGTH), ]
18 # allocate fixed space on disk to save persistent state.
19 # what to store in this file?
20 # slice_history : x,x,x,x,x,...
21 # root_history : y,y,y,y,y,y...
23 HISTORY_LENGTH = 24*30 # 30 days, if checked once an hour
24 HISTORY_fmt = ('ii', 'f'*HISTORY_LENGTH )
28 def get_network_bytes(interface):
29 for line in open('/proc/net/dev', 'r'):
31 data = line.split('%s:' % interface)[1].split()
32 rx_bytes, tx_bytes = (data[0], data[8])
33 return (float(rx_bytes), float(tx_bytes))
37 for line in open('/proc/uptime', 'r'):
38 data = line.split()[0]
42 def read_safe_history(filename):
44 This function guarantees that space is preserved.
45 If one of the file operations fail, it will throw an exception.
47 if os.path.exists(filename):
49 fd = os.open(filename, os.O_RDONLY)
50 a = os.read(fd, os.path.getsize(filename))
52 (version, i) = struct.unpack_from(HISTORY_fmt[0], a, 0)
53 assert version == HISTORY_version
54 history = struct.unpack_from(HISTORY_fmt[1], a, struct.calcsize(HISTORY_fmt[0]))
55 history = [ h for h in history ]
57 # TODO: in the future a more clever version migration might be nice.
58 os.remove(filename) # just nuke the old version
59 # create for the first time, with empty data
60 (i, history) = (0, [0]*HISTORY_LENGTH)
61 write_safe_history(filename, (i, history), False)
66 # create for the first time, with empty data
67 (i, history) = (0, [0]*HISTORY_LENGTH)
68 write_safe_history(filename, (i, history), False)
72 def write_safe_history(filename, (i, history), check_for_file=True):
73 # length should match, and the file should already exist
74 assert len(history) == HISTORY_LENGTH
76 assert os.path.exists(filename)
78 # open without TRUNC nor APPEND, then seek to beginning to preserve space on disk
79 fd = os.open(filename, os.O_WRONLY|os.O_CREAT)
81 ret = os.write(fd, struct.pack(HISTORY_fmt[0], HISTORY_version, i ))
82 ret += os.write(fd, struct.pack(HISTORY_fmt[1], *history))
86 def add_to_history((i, history), data):
91 i = i % HISTORY_LENGTH
93 # do not record data if data <= 0
97 def record_data(filename, data):
98 rh = read_safe_history(filename)
99 return write_safe_history(filename, add_to_history(rh, data))
101 def get_avg_uptime(filename):
102 (idx, history) = read_safe_history(filename)
103 summary = history[idx:] + history[:idx]
104 measured = filter(lambda x: x != 0, summary)
105 if len(measured) == 0:
107 return float(sum(measured))/float(len(measured))
111 def timeit(*args, **kw):
113 result = method(*args, **kw)
116 #print '%r (%r, %r) %2.2f sec' % \
117 # (method.__name__, args, kw, te-ts)
118 return (result, te-ts)
123 def check_dns(ip, protocol='udp'):
126 ro = DNS.Request(name="www.yahoo.com", qtype="A", server=ip)
127 r = ro.req(protocol=protocol)
129 except DNS.Base.DNSError, e:
133 def get_nameserver_ips(filename):
134 ip_re = re.compile("\d+\.\d+\.\d+\.\d+")
136 if not os.path.exists(filename):
139 f = open(filename, 'r')
141 if 'resolv' in filename:
143 for field in l.strip().split():
144 if ip_re.match(field) and field not in ret:
147 if 'ifcfg' in filename:
151 for field in l.strip().split('='):
152 field = field.replace('"', '')
153 field = field.replace("'", '')
154 if ip_re.match(field) and field not in ret:
162 # massive fail. cannot continue.
165 record_data("uptime_history.dat", ut)
167 print get_avg_uptime("uptime_history.dat"),
172 if __name__ == "__main__":
177 #url = """http://comon.cs.princeton.edu/status/tabulator.cgi?table=table_nodeviewshort&select='dns1udp>80 && dns2udp>80&&name=="%s"'&format=formatcsv&dumpcols='dns1udp,dns1tcp,dns2udp,dns2tcp'""" % os.popen("hostname").read().strip()