Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def accept_close_early(listener):
# verify that the makefile and the socket are truly independent
# by closing the socket prior to using the made file
try:
conn, addr = listener.accept()
fd = conn.makefile()
conn.close()
fd.write('hello\n')
fd.close()
r = fd.write('a')
assert r is None, r
self.assertRaises(socket.error, conn.send, 'b')
finally:
listener.close()
def test_failover(self):
from iris.coordinator.kazoo import Coordinator
# If we can't connect to zk, skip
try:
sock = socket.socket()
sock.connect(zk_address)
sock.close()
except socket.error:
pytest.skip('Skipping this test as ZK server is not running/reachable.')
# Create an initial instance which should become master
self.instances['c1'] = Coordinator(zk_url, 'testinstance', '1001', True)
spawn(self.instances['c1'].update_forever)
sleep(3)
assert self.instances['c1'].am_i_master()
# Make another instance which should become slave
self.instances['c2'] = Coordinator(zk_url, 'testinstance', '1002', True)
spawn(self.instances['c2'].update_forever)
sleep(3)
assert self.instances['c2'].am_i_master() is False
def _run(self):
selectable = self.selectable
method = self.method
wait = {'doRead':socket.wait_read,'doWrite':socket.wait_write}[method]
try:
fileno = selectable.fileno()
except AttributeError:
why = _NO_FILENO
else:
if fileno == -1:
why = _NO_FILEDESC
else:
why = None
if why is None:
wake = self.wake.wait
try:
while wake():
wait(fileno)
why = getattr(selectable,method)()
if why:
def create_connection(self):
"""Create connection to remote host."""
sock = socket.create_connection((self.host, self.port),
timeout=self.connect_timeout)
sock.settimeout(self.read_timeout)
return self.factory(sock)
def get_ip_version(ip):
# CR: http://stackoverflow.com/questions/11827961/checking-for-ip-addresses
try:
socket.inet_aton(ip)
return 4
except socket.error:
pass
try:
socket.inet_pton(socket.AF_INET6, ip)
return 6
except socket.error:
pass
raise ValueError(ip)
def patch_socket(dns=True, aggressive=True):
"""Replace the standard socket object with gevent's cooperative sockets.
If *dns* is true, also patch dns functions in :mod:`socket`.
"""
from gevent import socket
# Note: although it seems like it's not strictly necessary to monkey patch 'create_connection',
# it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module
# was, create_connection would still use "green" getaddrinfo and "green" socket.
# However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes
# _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail.
if dns:
items = socket.__implements__
else:
items = set(socket.__implements__) - set(socket.__dns__)
patch_module('socket', items=items)
if aggressive:
if 'ssl' not in socket.__implements__:
remove_item(socket, 'ssl')
def done_writing(self):
self._sock.shutdown(socket.SHUT_WR)
def _make_socket(address, backlog=50, reuse_addr=None, family=socket.AF_INET):
sock = socket.socket(family=family)
if reuse_addr is not None:
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, reuse_addr)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
try:
sock.bind(address)
except socket.error as e:
strerror = getattr(e, 'strerror', None)
if strerror is not None:
e.strerror = strerror + ': ' + repr(address)
raise
sock.listen(backlog)
sock.setblocking(0)
return sock
def killsock(sock):
"""Attempts to cleanly shutdown a socket. Regardless of cleanliness,
ensures that upon return, the socket is fully closed, catching any
exceptions along the way. A safe and prompt way to dispose of the
socket, freeing system resources.
"""
if hasattr(sock, '_sock'):
ml.ld("Killing socket {0}/FD {1}", id(sock), sock._sock.fileno())
else:
ml.ld("Killing socket {0}", id(sock))
try:
# TODO: better ideas for how to get SHUT_RDWR constant?
sock.shutdown(gevent.socket.SHUT_RDWR)
except gevent.socket.error:
pass # just being nice to the server, don't care if it fails
except Exception as e:
log_rec = context.get_context().log.info("SOCKET", "SHUTDOWN")
log_rec.failure('error ({exc}) shutting down socket: {socket}',
socket=sock, exc=e)
try:
sock.close()
except gevent.socket.error:
pass # just being nice to the server, don't care if it fails
except Exception as e:
log_rec = context.get_context().log.info("SOCKET", "CLOSE")
log_rec.failure('error ({exc}) closing socket: {socket}',
socket=sock, exc=e)
Replace the standard socket object with gevent's cooperative
sockets.
:keyword bool dns: When true (the default), also patch address
resolution functions in :mod:`socket`. See :doc:`dns` for details.
"""
from gevent import socket
# Note: although it seems like it's not strictly necessary to monkey patch 'create_connection',
# it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module
# was, create_connection would still use "green" getaddrinfo and "green" socket.
# However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes
# _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail.
if dns:
items = socket.__implements__ # pylint:disable=no-member
else:
items = set(socket.__implements__) - set(socket.__dns__) # pylint:disable=no-member
_patch_module('socket', items=items)
if aggressive:
if 'ssl' not in socket.__implements__: # pylint:disable=no-member
remove_item(socket, 'ssl')