當前位置: 首頁>>代碼示例>>Python>>正文


Python exceptions.NodeExistsError方法代碼示例

本文整理匯總了Python中kazoo.exceptions.NodeExistsError方法的典型用法代碼示例。如果您正苦於以下問題:Python exceptions.NodeExistsError方法的具體用法?Python exceptions.NodeExistsError怎麽用?Python exceptions.NodeExistsError使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在kazoo.exceptions的用法示例。


在下文中一共展示了exceptions.NodeExistsError方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _create

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def _create(self):

        logger.debug('to creaet: {s}'.format(s=str(self)))

        try:
            self.zkclient.create(self.lock_path,
                                 utfjson.dump(self.identifier),
                                 ephemeral=self.ephemeral,
                                 acl=self.zkconf.kazoo_digest_acl())

        except NodeExistsError as e:

            # NOTE Success create on server side might also results in failure
            # on client side due to network issue.
            # 'get' after 'create' to check if existent node belongs to this
            # client.

            logger.debug(repr(e) + ' while create lock: {s}'.format(s=str(self)))
            self.lock_holder = None
            return

        logger.info('CREATE OK: {s}'.format(s=str(self))) 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:24,代碼來源:zklock.py

示例2: set_or_create

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def set_or_create(self, key, value, version=-1):

        value = self._dump(value)
        while True:
            try:
                self.zkclient.set(self.get_path(key), value, version=version)
                return
            except NoNodeError:
                if version == -1:
                    try:
                        self.zkclient.create(self.get_path(key), value, acl=self._get_acl())
                        return
                    except NodeExistsError:
                        continue
                else:
                    raise 
開發者ID:bsc-s2,項目名稱:pykit,代碼行數:18,代碼來源:zkaccessor.py

示例3: update_task

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def update_task(self, task_id: str, **kwargs):
        retry = True
        while retry:
            retry = False
            existing_task, stat = self._get_task(task_id)

            zk_path = self._zk_path_from_task_id(task_id)
            if existing_task:
                merged_params = existing_task.merge(**kwargs)
                try:
                    self.zk_client.set(
                        zk_path, merged_params.serialize(), version=stat.version
                    )
                except BadVersionError:
                    retry = True
            else:
                merged_params = MesosTaskParameters(**kwargs)
                try:
                    self.zk_client.create(zk_path, merged_params.serialize())
                except NodeExistsError:
                    retry = True

        return merged_params 
開發者ID:Yelp,項目名稱:paasta,代碼行數:25,代碼來源:task_store.py

示例4: reallocate_partitions

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def reallocate_partitions(self, partitions_data: list) -> bool:
        j = {
            "version": "1",
            "partitions": [
                {
                    "topic": topic,
                    "partition": int(partition),
                    "replicas": [int(p) for p in replicas]
                } for (topic, partition, replicas) in partitions_data]
        }
        try:
            data = json.dumps(j)
            self.exhibitor.create("/admin/reassign_partitions", data.encode('utf-8'))
            _LOG.info("Reallocating {}".format(data))
            return True
        except NodeExistsError:
            _LOG.info("Waiting for free reallocation slot, still in progress...")
        return False 
開發者ID:zalando-nakadi,項目名稱:bubuku,代碼行數:20,代碼來源:__init__.py

示例5: test_add_service_instance_with_concurrency_request_error

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def test_add_service_instance_with_concurrency_request_error(
        test_application_name, add_service, mocker):
    key = '169.254.1.2_5000'
    value = '{"ip": "169.254.1.2", "port":{"main": 5000},"state":"up"}'
    mocker.patch.object(
        service_client.raw_client, 'create', side_effect=NodeExistsError)

    _, r = add_service(key, value)
    assert r.status_code == 409
    assert r.json['status'] == 'Conflict'
    assert r.json['message'] == 'resource is modified by another request'

    mocker.patch.object(service_client.raw_client, 'create', return_value=None)
    mocker.patch.object(service_client.raw_client, 'exists', return_value=None)

    _, r = add_service(key, value)
    assert r.status_code == 409
    assert r.json['status'] == 'Conflict'
    assert r.json['message'] == 'resource is modified by another request' 
開發者ID:huskar-org,項目名稱:huskar,代碼行數:21,代碼來源:test_service.py

示例6: _exc_wrapper

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def _exc_wrapper(self):
        """Exception context-manager which wraps kazoo exceptions.

        This is used to capture and wrap any kazoo specific exceptions and
        then group them into corresponding taskflow exceptions (not doing
        that would expose the underlying kazoo exception model).
        """
        try:
            yield
        except self._client.handler.timeout_exception:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Storage backend timeout")
        except k_exc.SessionExpiredError:
            exc.raise_with_cause(exc.StorageFailure,
                                 "Storage backend session has expired")
        except k_exc.NoNodeError:
            exc.raise_with_cause(exc.NotFound,
                                 "Storage backend node not found")
        except k_exc.NodeExistsError:
            exc.raise_with_cause(exc.Duplicate,
                                 "Storage backend duplicate node")
        except (k_exc.KazooException, k_exc.ZookeeperError):
            exc.raise_with_cause(exc.StorageFailure,
                                 "Storage backend internal error") 
開發者ID:openstack,項目名稱:taskflow,代碼行數:26,代碼來源:impl_zookeeper.py

示例7: start_deployd

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def start_deployd(context):
    try:
        os.makedirs("/nail/etc/services")
    except OSError as e:
        if e.errno == errno.EEXIST:
            pass
    with ZookeeperPool() as zk:
        try:
            zk.create("/autoscaling")
        except NodeExistsError:
            pass
    context.zk_hosts = "%s/mesos-testcluster" % get_service_connection_string(
        "zookeeper"
    )
    context.soa_dir = "/nail/etc/services"
    if not hasattr(context, "daemon"):
        context.daemon = Popen("paasta-deployd", stderr=PIPE)
    output = context.daemon.stderr.readline().decode("utf-8")
    start = time.time()
    timeout = start + 60
    while "Startup finished!" not in output:
        output = context.daemon.stderr.readline().decode("utf-8")
        if not output:
            raise Exception("deployd exited prematurely")
        print(output.rstrip("\n"))
        if time.time() > timeout:
            raise Exception("deployd never ran")

    context.num_workers_crashed = 0

    def dont_let_stderr_buffer():
        while True:
            line = context.daemon.stderr.readline()
            if not line:
                return
            if DEAD_DEPLOYD_WORKER_MESSAGE.encode("utf-8") in line:
                context.num_workers_crashed += 1
            print(f"deployd stderr: {line}")

    threading.Thread(target=dont_let_stderr_buffer).start()
    time.sleep(5) 
開發者ID:Yelp,項目名稱:paasta,代碼行數:43,代碼來源:paasta_deployd_steps.py

示例8: _lock_and_get_entry

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def _lock_and_get_entry(self, entry_node: str) -> Optional[Tuple[bytes, ZnodeStat]]:
        try:
            lock_path = f"{self.locks_path}/{entry_node}"
            self.locked_entry_nodes.add(entry_node)
            self.client.create(lock_path, value=self.id, ephemeral=True)
        except NodeExistsError:
            self.locked_entry_nodes.add(entry_node)
            return None

        try:
            return self.client.get(f"{self.entries_path}/{entry_node}")
        except NoNodeError:
            self.client.delete(lock_path)
            return None 
開發者ID:Yelp,項目名稱:paasta,代碼行數:16,代碼來源:queue.py

示例9: update_disk_stats

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def update_disk_stats(self, broker_id: str, data: dict):
        data_bytes = json.dumps(data, separators=(',', ':')).encode('utf-8')
        path = '/bubuku/size_stats/{}'.format(broker_id)
        try:
            self.exhibitor.create(path, data_bytes, ephemeral=True, makepath=True)
        except NodeExistsError:
            self.exhibitor.set(path, data_bytes) 
開發者ID:zalando-nakadi,項目名稱:bubuku,代碼行數:9,代碼來源:__init__.py

示例10: register_action

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def register_action(self, data: dict, broker_id: str = 'global'):
        registered = False
        while not registered:
            name = '/bubuku/actions/{}/{}'.format(broker_id, uuid.uuid4())
            try:
                self.exhibitor.create(name, json.dumps(data).encode('utf-8'), makepath=True)
                _LOG.info('Action {} registered with name {}'.format(data, name))
                registered = True
            except NodeExistsError:
                pass 
開發者ID:zalando-nakadi,項目名稱:bubuku,代碼行數:12,代碼來源:__init__.py

示例11: test_reallocate_partition

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def test_reallocate_partition():
    call_idx = [0]

    def _create(path, value=None, **kwargs):
        if path in ('/bubuku/changes', '/bubuku/actions/global'):
            pass
        elif path == '/admin/reassign_partitions':
            if call_idx[0] >= 5:
                raise NodeExistsError()
            call_idx[0] += 1
            j = json.loads(value.decode('utf-8'))
            assert j['version'] == '1'
            assert len(j['partitions']) == 1
            p = j['partitions'][0]
            assert p['topic'] == 't01'
            assert p['partition'] == 0
            assert p['replicas'] == [1, 2, 3]
        else:
            raise NotImplementedError('Not implemented for path {}'.format(path))

    exhibitor_mock = MagicMock()
    exhibitor_mock.create = _create

    buku = BukuExhibitor(exhibitor_mock)

    assert buku.reallocate_partition('t01', 0, ['1', '2', '3'])
    assert buku.reallocate_partition('t01', 0, ['1', '2', 3])
    assert buku.reallocate_partition('t01', 0, [1, 2, 3])
    assert buku.reallocate_partition('t01', 0, [1, 2, 3])
    assert buku.reallocate_partition('t01', 0, [1, 2, 3])
    # Node exists
    assert not buku.reallocate_partition('t01', 0, [1, 2, 3]) 
開發者ID:zalando-nakadi,項目名稱:bubuku,代碼行數:34,代碼來源:test_zookeeper.py

示例12: create_if_not_exist

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def create_if_not_exist(self, application, cluster=None, strict=False):
        path = self.get_path(application, cluster)
        try:
            self.raw_client.create(path, b'', makepath=True)
            zk_payload(payload_data=b'', payload_type='create')
        except NodeExistsError:
            if strict:
                target = 'application' if cluster is None else 'cluster'
                raise DataExistsError('%s exists already' % target) 
開發者ID:huskar-org,項目名稱:huskar,代碼行數:11,代碼來源:client.py

示例13: save

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def save(self, version=None):
        """Saves the data in this instance to ZooKeeper.

        It is concurrency-safe if you never break the :attr:`ZnodeModel.stat`.

        :param version: Optional. The alternative version instead of
                        :attr:`ZnodeModel.stat`.
        :raises OutOfSyncError: The local data is outdated.
        :raises marshmallow.ValidationError: :attr:`ZnodeModel.data` is invalid
        """
        data, _ = self.MARSHMALLOW_SCHEMA.dumps(self.data)
        self.MARSHMALLOW_SCHEMA.loads(data)  # raise ValidationError if need
        if self.stat is None:
            try:
                self.client.create(self.path, data, makepath=True)
                zk_payload(payload_data=data, payload_type='create')
            except NodeExistsError as e:
                raise OutOfSyncError(e)
            self.load()
        else:
            if version is None:
                version = self.stat.version
            try:
                self.stat = self.client.set(self.path, data, version=version)
                zk_payload(payload_data=data, payload_type='set')
            except (NoNodeError, BadVersionError) as e:
                raise OutOfSyncError(e) 
開發者ID:huskar-org,項目名稱:huskar,代碼行數:29,代碼來源:znode.py

示例14: test_znode_model_create_oos

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def test_znode_model_create_oos(zk, faker, mocker, schema, model_class):
    name = faker.uuid4()
    model = model_class(zk, application_name=name)
    model.data = '{}'

    zk.create('/huskar/service/%s/overall' % name, b'1s', makepath=True)
    with raises(OutOfSyncError) as error:
        model.save()
    assert isinstance(error.value.args[0], NodeExistsError)
    assert model.stat is None
    assert model.data == '{}' 
開發者ID:huskar-org,項目名稱:huskar,代碼行數:13,代碼來源:test_znode.py

示例15: create_offsets

# 需要導入模塊: from kazoo import exceptions [as 別名]
# 或者: from kazoo.exceptions import NodeExistsError [as 別名]
def create_offsets(zk, consumer_group, offsets):
    """Create path with offset value for each topic-partition of given consumer
    group.

    :param zk: Zookeeper client
    :param consumer_group: Consumer group id for given offsets
    :type consumer_group: int
    :param offsets: Offsets of all topic-partitions
    :type offsets: dict(topic, dict(partition, offset))
    """
    # Create new offsets
    for topic, partition_offsets in six.iteritems(offsets):
        for partition, offset in six.iteritems(partition_offsets):
            new_path = "/consumers/{groupid}/offsets/{topic}/{partition}".format(
                groupid=consumer_group,
                topic=topic,
                partition=partition,
            )
            try:
                zk.create(new_path, value=offset, makepath=True)
            except NodeExistsError:
                print(
                    "Error: Path {path} already exists. Please re-run the "
                    "command.".format(path=new_path),
                    file=sys.stderr,
                )
                raise 
開發者ID:Yelp,項目名稱:kafka-utils,代碼行數:29,代碼來源:util.py


注:本文中的kazoo.exceptions.NodeExistsError方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。