1
2
3
4
5
6
7
8
9
10
11
12
13 import threading
14 import Queue
15 import logging
16 log = logging.getLogger("PingThread")
17
18 from Ping import Ping, PingJob
19
21 """
22 PingThread takes pingjobs off a Queue and pings them.
23 """
24
25 - def __init__(self, reportqueue,tries=2, timeout=2, chunkSize=10):
26 threading.Thread.__init__(self)
27 Ping.__init__(self, tries, timeout, chunkSize)
28 self.setDaemon(1)
29 self.setName("PingThread")
30 self.sendqueue = Queue.Queue()
31 self.reportqueue = reportqueue
32
33
35 """Send any packets that are in our queue up to numbtosend.
36 """
37 try:
38 numbtosend = self.chunkSize - len(self.jobqueue)
39 for i in range(numbtosend):
40 pingJob = self.sendqueue.get(False)
41 self.devcount += 1
42 self.sendPacket(pingJob)
43 except Queue.Empty: pass
44
45
47 """Called from main thread to add new pingjob to send queue.
48 """
49 self.incount += 1
50 self.sendqueue.put(pj)
51
52
53
55 """Pass pingJobs back to our master thread when done.
56 """
57 self.outcount += 1
58 self.reportqueue.put(pj)
59
60
62 """Start this thread. Exit by setting self.morepkts.
63 """
64 log.info("starting")
65 self.eventLoop(self.sendqueue)
66 log.info("stopped")
67
68
70 log.info("stopping...")
71 self.morepkts = False
72 self.join(5)
73
74
75 if __name__ == "__main__":
76 import sys
77 import Queue
78 logging.basicConfig()
79 log = logging.getLogger()
80 log.setLevel(10)
81 sendqueue = Queue.Queue()
82 reportqueue = Queue.Queue()
83 pt = PingThread(sendqueue, reportqueue)
84 if len(sys.argv) > 1: targets = sys.argv[1:]
85 else: targets = ("127.0.0.1",)
86 for ip in targets:
87 pj = PingJob(ip)
88 sendqueue.put(pj)
89 pt.start()
90 sent = len(targets)
91 received = 0
92 while received < sent:
93 try:
94 pj = reportqueue.get(False)
95 received += 1
96 except Queue.Empty: pass
97 pt.morepkts = False
98 pt.join(2)
99