Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
state_fut, states.States.LOST)
fut.cancel()
await self.delete_unique_znode(znode_label)
class Lock:
async def __aenter__(self):
return self
async def __aexit__(self, exc_type, exc, tb):
await on_exit()
return Lock()
class LockLostError(exc.ZKError):
pass
async def start(self):
base, _leaf = self.base_path.rsplit("/", 1)
if base:
await self.client.ensure_path(base)
try:
await self.client.create(self.base_path, str(self._default))
self.value = self._default
self._version = 0
except exc.NodeExists:
await self._fetch()
acl = acl or self.default_acl
paths_to_make = []
for segment in path[1:].split("/"):
if not paths_to_make:
paths_to_make.append("/" + segment)
continue
paths_to_make.append("/".join([paths_to_make[-1], segment]))
while paths_to_make:
path = paths_to_make[0]
if self.features.create_with_stat:
request = protocol.Create2Request(path=path, acl=acl)
else:
request = protocol.CreateRequest(path=path, acl=acl)
request.set_flags(
ephemeral=False, sequential=False, container=self.features.containers
)
try:
await self.send(request)
except exc.NodeExists:
pass
paths_to_make.pop(0)
async def commit(self):
if not self.request.requests:
raise ValueError("No operations to commit.")
response = await self.client.send(self.request)
pairs = zip(self.request.requests, response.responses)
result = Result()
for request, reply in pairs:
if isinstance(reply, protocol.CheckVersionResponse):
result.checked.add(self.client.denormalize_path(request.path))
elif isinstance(reply, protocol.CreateResponse):
result.created.add(self.client.denormalize_path(request.path))
elif isinstance(reply, protocol.SetDataResponse):
result.updated.add(self.client.denormalize_path(request.path))
elif isinstance(reply, protocol.DeleteResponse):
result.deleted.add(self.client.denormalize_path(request.path))
return result
async def wait(self, timeout=None):
barrier_lifted = self.client.wait_for_events(
[WatchEvent.DELETED], self.path
)
exists = await self.client.exists(path=self.path, watch=True)
if not exists:
return
try:
if timeout:
await asyncio.wait_for(barrier_lifted, timeout)
else:
await barrier_lifted
except asyncio.TimeoutError:
raise exc.TimeoutError
async def on_exit():
state["acquired"] = False
if not fut.done():
if not state_fut.done():
self.client.session.state.remove_waiting(
state_fut, states.States.LOST)
fut.cancel()
await self.delete_unique_znode(znode_label)
import asyncio
from aiozk import exc, WatchEvent
from .recipe import Recipe
class Barrier(Recipe):
def __init__(self, path):
super().__init__()
self.path = path
async def create(self):
await self.ensure_path()
await self.create_znode(self.path)
async def lift(self):
try:
await self.client.delete(self.path)
except exc.NoNode:
pass
async def wait(self, timeout=None):
import asyncio
import logging
import re
import uuid
from aiozk import exc, WatchEvent, RetryPolicy, states
from .recipe import Recipe
log = logging.getLogger(__name__)
sequential_re = re.compile(r'.*[0-9]{10}$')
class SequentialRecipe(Recipe):
def __init__(self, base_path):
super().__init__(base_path)
self.guid = uuid.uuid4().hex
self.owned_paths = {}
def sequence_number(self, sibling):
return int(sibling[-10:])
def determine_znode_label(self, sibling):
return sibling.rsplit("-", 2)[0]
def sibling_path(self, path):
return "/".join([self.base_path, path])
with suppress(asyncio.CancelledError):
await self.read_loop_task
if self.pending or (self.pending_specials and self.pending_specials != {None: []}):
log.warning('Pendings: {}; specials: {}'.format(self.pending, self.pending_specials))
try:
# await list(pending_with_timeouts)
self.abort(exception=exc.TimeoutError)
# wlist = list(self.drain_all_pending())
# log.warning('Wait for list: {} {}'.format(wlist, self.pending))
# if len(wlist) > 0:
# await asyncio.wait(wlist, timeout=timeout)
except asyncio.TimeoutError:
log.warning('ABORT Timeout')
await self.abort(exception=exc.TimeoutError)
except Exception as e:
log.exception('in close: {}'.format(e))
raise e
finally:
log.debug('Closing writer')
self.writer.close()
log.debug('Writer closed')
async def close(self, timeout):
if self.closing:
return
self.closing = True
if self.read_loop_task:
self.read_loop_task.cancel()
with suppress(asyncio.CancelledError):
await self.read_loop_task
if self.pending or (self.pending_specials and self.pending_specials != {None: []}):
log.warning('Pendings: {}; specials: {}'.format(self.pending, self.pending_specials))
try:
# await list(pending_with_timeouts)
self.abort(exception=exc.TimeoutError)
# wlist = list(self.drain_all_pending())
# log.warning('Wait for list: {} {}'.format(wlist, self.pending))
# if len(wlist) > 0:
# await asyncio.wait(wlist, timeout=timeout)
except asyncio.TimeoutError:
log.warning('ABORT Timeout')
await self.abort(exception=exc.TimeoutError)
except Exception as e:
log.exception('in close: {}'.format(e))
raise e
finally:
log.debug('Closing writer')
self.writer.close()
log.debug('Writer closed')