Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
except IndexError:
# Not actually something on the queue, this can occur if
# something happens to cancel the request such that we
# don't clear the socket below after sending
try:
# Clear possible inconsistence (no request in the queue
# but have data in the read socket), which causes cpu to spin.
self._read_sock.recv(1)
except OSError:
pass
return
# Special case for testing, if this is a _SessionExpire object
# then throw a SessionExpiration error as if we were dropped
if request is _SESSION_EXPIRED:
raise SessionExpiredError("Session expired: Testing")
if request is _CONNECTION_DROP:
raise ConnectionDropped("Connection dropped: Testing")
# Special case for auth packets
if request.type == Auth.type:
xid = AUTH_XID
else:
self._xid = (self._xid % 2147483647) + 1
xid = self._xid
self._submit(request, connect_timeout, xid)
client._queue.popleft()
self._read_sock.recv(1)
client._pending.append((request, async_object, xid))
except IndexError:
# Not actually something on the queue, this can occur if
# something happens to cancel the request such that we
# don't clear the pipe below after sending
try:
# Clear possible inconsistence (no request in the queue
# but have data in the read pipe), which causes cpu to spin.
os.read(self._read_pipe, 1)
except OSError:
pass
return
# Special case for testing, if this is a _SessionExpire object
# then throw a SessionExpiration error as if we were dropped
if request is _SESSION_EXPIRED:
raise SessionExpiredError("Session expired: Testing")
if request is _CONNECTION_DROP:
raise ConnectionDropped("Connection dropped: Testing")
# Special case for auth packets
if request.type == Auth.type:
xid = AUTH_XID
else:
self._xid += 1
xid = self._xid
self._submit(request, connect_timeout, xid)
client._queue.popleft()
os.read(self._read_pipe, 1)
client._pending.append((request, async_object, xid))
except IndexError:
# Not actually something on the queue, this can occur if
# something happens to cancel the request such that we
# don't clear the pipe below after sending
try:
# Clear possible inconsistence (no request in the queue
# but have data in the read pipe), which causes cpu to spin.
os.read(self._read_pipe, 1)
except OSError:
pass
return
# Special case for testing, if this is a _SessionExpire object
# then throw a SessionExpiration error as if we were dropped
if request is _SESSION_EXPIRED:
raise SessionExpiredError("Session expired: Testing")
if request is _CONNECTION_DROP:
raise ConnectionDropped("Connection dropped: Testing")
# Special case for auth packets
if request.type == Auth.type:
xid = AUTH_XID
else:
self._xid += 1
xid = self._xid
self._submit(request, connect_timeout, xid)
client._queue.popleft()
os.read(self._read_pipe, 1)
client._pending.append((request, async_object, xid))
in the locking recipe.
timeout:
Time in seconds to wait for the lock to be acquired.
If this time elapses before the lock is acquired, a
`kazoo.exceptions.LockTimeout` exception is raised.
Raises:
kazoo.exceptions.LockTimeout:
If the `timeout` is exceeded without the lock being acquired.
"""
lock = zk.Lock(lock_path, contender_id)
try:
log.info("Acquiring ZooKeeper lock.")
lock.acquire(blocking=True, timeout=timeout)
except (ConnectionLoss, SessionExpiredError) as e:
msg_fmt = "Failed to acquire lock: {}"
msg = msg_fmt.format(e.__class__.__name__)
log.exception(msg)
raise e
except LockTimeout as e:
msg_fmt = "Failed to acquire lock in `{}` seconds"
msg = msg_fmt.format(timeout)
log.exception(msg)
raise e
else:
log.info("ZooKeeper lock acquired.")
yield
log.info("Releasing ZooKeeper lock")
lock.release()
log.info("ZooKeeper lock released.")
def verify(self):
if not self._connected:
raise k_exceptions.ConnectionClosedError("Connection has been"
" closed")
if self.expired:
raise k_exceptions.SessionExpiredError("Expired")
bgp_table = BGPTable()
for ip in self.get_conf().srv_non_auth_ips:
if str(ip) not in children:
bgp_table.add_route(prefix=ip, metric=200)
else:
bgp_table.del_route(prefix=ip)
ip = self.get_conf().srv_auth_ip
if str(ip) not in children:
bgp_table.del_route(prefix=ip)
else:
bgp_table.add_route(prefix=ip, metric=100)
self.set_bgp_table(bgp_table)
except SessionExpiredError as e:
pass
import kazoo.security as ksec
import kazoo.exceptions as ke
# TODO(wickman) Put this in twitter.common somewhere?
def partition(items, predicate=bool):
a, b = itertools.tee((predicate(item), item) for item in items)
return ([item for pred, item in a if not pred], [item for pred, item in b if pred])
class KazooGroup(GroupBase, GroupInterface):
"""
An implementation of GroupInterface against Kazoo.
"""
DISCONNECT_EXCEPTIONS = (ke.ConnectionLoss, ke.OperationTimeoutError, ke.SessionExpiredError)
@classmethod
def translate_acl(cls, acl):
if not isinstance(acl, dict) or any(key not in acl for key in ('perms', 'scheme', 'id')):
raise TypeError('Expected acl to be Acl-like, got %s' % type(acl))
return ksec.ACL(acl['perms'], ksec.Id(acl['scheme'], acl['id']))
@classmethod
def translate_acl_list(cls, acls):
if acls is None:
return acls
try:
acls = list(acls)
except (ValueError, TypeError):
raise TypeError('ACLs should be a list, got %s' % type(acls))
if all(isinstance(acl, ksec.ACL) for acl in acls):
hexlify(client._session_passwd))
with self._socket_error_handling():
self._socket = self.handler.create_connection(
(host, port), client._session_timeout / 1000.0)
self._socket.setblocking(0)
connect = Connect(0, client.last_zxid, client._session_timeout,
client._session_id or 0, client._session_passwd,
client.read_only)
connect_result, zxid = self._invoke(client._session_timeout, connect)
if connect_result.time_out <= 0:
raise SessionExpiredError("Session has expired")
if zxid:
client.last_zxid = zxid
# Load return values
client._session_id = connect_result.session_id
client._protocol_version = connect_result.protocol_version
negotiated_session_timeout = connect_result.time_out
connect_timeout = negotiated_session_timeout / len(client.hosts)
read_timeout = negotiated_session_timeout * 2.0 / 3.0
client._session_passwd = connect_result.passwd
self.logger.log(BLATHER,
'Session created, session_id: %r session_passwd: %s\n'
' negotiated session timeout: %s\n'
' connect timeout: %s\n'
Returns False if the call short circuits due to AUTH_FAILED,
CLOSED, EXPIRED_SESSION or CONNECTING state.
"""
if self._state == KeeperState.AUTH_FAILED:
async_object.set_exception(AuthFailedError())
return False
elif self._state == KeeperState.CLOSED:
async_object.set_exception(ConnectionClosedError(
"Connection has been closed"))
return False
elif self._state in (KeeperState.EXPIRED_SESSION,
KeeperState.CONNECTING):
async_object.set_exception(SessionExpiredError())
return False
self._queue.append((request, async_object))
# wake the connection, guarding against a race with close()
write_sock = self._connection._write_sock
if write_sock is None:
async_object.set_exception(ConnectionClosedError(
"Connection has been closed"))
try:
write_sock.send(b'\0')
except: # NOQA
async_object.set_exception(ConnectionClosedError(
"Connection has been closed"))