heartbeat.py
68 lines
| 2.3 KiB
| text/x-python
|
PythonLexer
Brian Granger
|
r2910 | """The client and server for a basic ping-pong style heartbeat. | ||
""" | ||||
#----------------------------------------------------------------------------- | ||||
Matthias BUSSONNIER
|
r5390 | # Copyright (C) 2008-2011 The IPython Development Team | ||
Brian Granger
|
r2910 | # | ||
# Distributed under the terms of the BSD License. The full license is in | ||||
# the file COPYING, distributed as part of this software. | ||||
#----------------------------------------------------------------------------- | ||||
#----------------------------------------------------------------------------- | ||||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
Pankaj Pandey
|
r12301 | import errno | ||
MinRK
|
r7321 | import os | ||
MinRK
|
r4500 | import socket | ||
Brian Granger
|
r2910 | from threading import Thread | ||
import zmq | ||||
MinRK
|
r12591 | from IPython.utils.localinterfaces import localhost | ||
MinRK
|
r3144 | |||
Brian Granger
|
r2910 | #----------------------------------------------------------------------------- | ||
# Code | ||||
#----------------------------------------------------------------------------- | ||||
class Heartbeat(Thread): | ||||
"A simple ping-pong style heartbeat that runs in a thread." | ||||
MinRK
|
r12591 | def __init__(self, context, addr=None): | ||
if addr is None: | ||||
addr = ('tcp', localhost(), 0) | ||||
Brian Granger
|
r2910 | Thread.__init__(self) | ||
self.context = context | ||||
MinRK
|
r7321 | self.transport, self.ip, self.port = addr | ||
MinRK
|
r4500 | if self.port == 0: | ||
MinRK
|
r7321 | if addr[0] == 'tcp': | ||
s = socket.socket() | ||||
# '*' means all interfaces to 0MQ, which is '' to socket.socket | ||||
s.bind(('' if self.ip == '*' else self.ip, 0)) | ||||
self.port = s.getsockname()[1] | ||||
s.close() | ||||
elif addr[0] == 'ipc': | ||||
MinRK
|
r9176 | self.port = 1 | ||
while os.path.exists("%s-%s" % (self.ip, self.port)): | ||||
MinRK
|
r7321 | self.port = self.port + 1 | ||
else: | ||||
raise ValueError("Unrecognized zmq transport: %s" % addr[0]) | ||||
MinRK
|
r5170 | self.addr = (self.ip, self.port) | ||
Brian Granger
|
r2910 | self.daemon = True | ||
def run(self): | ||||
self.socket = self.context.socket(zmq.REP) | ||||
MinRK
|
r16535 | self.socket.linger = 1000 | ||
MinRK
|
r7321 | c = ':' if self.transport == 'tcp' else '-' | ||
self.socket.bind('%s://%s' % (self.transport, self.ip) + c + str(self.port)) | ||||
Pankaj Pandey
|
r12301 | while True: | ||
try: | ||||
zmq.device(zmq.FORWARDER, self.socket, self.socket) | ||||
except zmq.ZMQError as e: | ||||
if e.errno == errno.EINTR: | ||||
continue | ||||
else: | ||||
raise | ||||
else: | ||||
break | ||||