class Exhibitor: def __init__(self, exhibitor, chroot): self.chroot = chroot self.exhibitor = ExhibitorEnsembleProvider(exhibitor['hosts'], exhibitor['port'], poll_interval=30) self.client = KazooClient(hosts=self.exhibitor.zookeeper_hosts + self.chroot, command_retry={ 'deadline': 10, 'max_delay': 1, 'max_tries': -1}, connection_retry={'max_delay': 1, 'max_tries': -1}) self.client.add_listener(self.session_listener) self.client.start() def session_listener(self, state): pass def _poll_exhibitor(self): if self.exhibitor.poll(): self.client.set_hosts(self.exhibitor.zookeeper_hosts + self.chroot) def get(self, *params): self._poll_exhibitor() return self.client.retry(self.client.get, *params) def get_children(self, *params): self._poll_exhibitor() try: return self.client.retry(self.client.get_children, *params) except NoNodeError: return []
def test_update_host_list(self): from kazoo.client import KazooClient from kazoo.protocol.states import KeeperState hosts = self.cluster[0].address # create a client with only one server in its list client = KazooClient(hosts=hosts) client.start() # try to change the chroot, not currently allowed self.assertRaises(ConfigurationError, client.set_hosts, hosts + '/new_chroot') # grow the cluster to 3 client.set_hosts(self.servers) # shut down the first host try: self.cluster[0].stop() time.sleep(5) eq_(client.client_state, KeeperState.CONNECTED) finally: self.cluster[0].run()
def test_update_host_list(self): from kazoo.client import KazooClient from kazoo.protocol.states import KeeperState hosts = self.cluster[0].address # create a client with only one server in its list client = KazooClient(hosts=hosts) client.start() # try to change the chroot, not currently allowed self.assertRaises(ConfigurationError, client.set_hosts, hosts + '/new_chroot') # grow the cluster to 3 client.set_hosts(self.servers) # shut down the first host try: self.cluster[0].stop() time.sleep(5) eq_(client.client_state, KeeperState.CONNECTED) finally: self.cluster[0].run()
class ZooKeeper(object): ''' Class implementing the ZooKeeper interface. This class uses the facade design pattern to keep common interaction with the ZooKeeper API simple and consistent for the caller, and limits coupling between objects. It allows for more complex interactions by providing direct access to the client connection when needed (though that is discouraged). It also provides for a convenient entry point for testing only ZooKeeper interactions. ''' log = logging.getLogger("zuul.zk.ZooKeeper") REQUEST_ROOT = '/nodepool/requests' NODE_ROOT = '/nodepool/nodes' # Log zookeeper retry every 10 seconds retry_log_rate = 10 def __init__(self): ''' Initialize the ZooKeeper object. ''' self.client = None self._became_lost = False self._last_retry_log = 0 def _dictToStr(self, data): return json.dumps(data).encode('utf8') def _strToDict(self, data): return json.loads(data.decode('utf8')) def _connection_listener(self, state): ''' Listener method for Kazoo connection state changes. .. warning:: This method must not block. ''' if state == KazooState.LOST: self.log.debug("ZooKeeper connection: LOST") self._became_lost = True elif state == KazooState.SUSPENDED: self.log.debug("ZooKeeper connection: SUSPENDED") else: self.log.debug("ZooKeeper connection: CONNECTED") @property def connected(self): return self.client.state == KazooState.CONNECTED @property def suspended(self): return self.client.state == KazooState.SUSPENDED @property def lost(self): return self.client.state == KazooState.LOST @property def didLoseConnection(self): return self._became_lost def resetLostFlag(self): self._became_lost = False def logConnectionRetryEvent(self): now = time.monotonic() if now - self._last_retry_log >= self.retry_log_rate: self.log.warning("Retrying zookeeper connection") self._last_retry_log = now def connect(self, hosts, read_only=False, timeout=10.0): ''' Establish a connection with ZooKeeper cluster. Convenience method if a pre-existing ZooKeeper connection is not supplied to the ZooKeeper object at instantiation time. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). :param bool read_only: If True, establishes a read-only connection. :param float timeout: The ZooKeeper session timeout, in seconds (default: 10.0). ''' if self.client is None: self.client = KazooClient(hosts=hosts, read_only=read_only, timeout=timeout) self.client.add_listener(self._connection_listener) # Manually retry initial connection attempt while True: try: self.client.start(1) break except KazooTimeoutError: self.logConnectionRetryEvent() def disconnect(self): ''' Close the ZooKeeper cluster connection. You should call this method if you used connect() to establish a cluster connection. ''' if self.client is not None and self.client.connected: self.client.stop() self.client.close() self.client = None def resetHosts(self, hosts): ''' Reset the ZooKeeper cluster connection host list. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). ''' if self.client is not None: self.client.set_hosts(hosts=hosts) def submitNodeRequest(self, node_request, watcher): ''' Submit a request for nodes to Nodepool. :param NodeRequest node_request: A NodeRequest with the contents of the request. :param callable watcher: A callable object that will be invoked each time the request is updated. It is called with two arguments: (node_request, deleted) where node_request is the same argument passed to this method, and deleted is a boolean which is True if the node no longer exists (notably, this will happen on disconnection from ZooKeeper). The watcher should return False when further updates are no longer necessary. ''' data = node_request.toDict() data['created_time'] = time.time() path = '%s/%s-' % (self.REQUEST_ROOT, node_request.priority) path = self.client.create(path, self._dictToStr(data), makepath=True, sequence=True, ephemeral=True) reqid = path.split("/")[-1] node_request.id = reqid def callback(data, stat): if data: data = self._strToDict(data) request_nodes = list(node_request.nodeset.getNodes()) for i, nodeid in enumerate(data.get('nodes', [])): node_path = '%s/%s' % (self.NODE_ROOT, nodeid) node_data, node_stat = self.client.get(node_path) node_data = self._strToDict(node_data) request_nodes[i].id = nodeid request_nodes[i].updateFromDict(node_data) node_request.updateFromDict(data) deleted = (data is None) # data *are* none return watcher(node_request, deleted) self.client.DataWatch(path, callback) def deleteNodeRequest(self, node_request): ''' Delete a request for nodes. :param NodeRequest node_request: A NodeRequest with the contents of the request. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) try: self.client.delete(path) except kze.NoNodeError: pass def nodeRequestExists(self, node_request): ''' See if a NodeRequest exists in ZooKeeper. :param NodeRequest node_request: A NodeRequest to verify. :returns: True if the request exists, False otherwise. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) if self.client.exists(path): return True return False def storeNode(self, node): '''Store the node. The node is expected to already exist and is updated in its entirety. :param Node node: The node to update. ''' path = '%s/%s' % (self.NODE_ROOT, node.id) self.client.set(path, self._dictToStr(node.toDict())) def lockNode(self, node, blocking=True, timeout=None): ''' Lock a node. This should be called as soon as a request is fulfilled and the lock held for as long as the node is in-use. It can be used by nodepool to detect if Zuul has gone offline and the node should be reclaimed. :param Node node: The node which should be locked. ''' lock_path = '%s/%s/lock' % (self.NODE_ROOT, node.id) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException("Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % lock_path) node.lock = lock def unlockNode(self, node): ''' Unlock a node. The node must already have been locked. :param Node node: The node which should be unlocked. ''' if node.lock is None: raise LockException("Node %s does not hold a lock" % (node, )) node.lock.release() node.lock = None def heldNodeCount(self, autohold_key): ''' Count the number of nodes being held for the given tenant/project/job. :param set autohold_key: A set with the tenant/project/job names. ''' identifier = " ".join(autohold_key) try: nodes = self.client.get_children(self.NODE_ROOT) except kze.NoNodeError: return 0 count = 0 for nodeid in nodes: node_path = '%s/%s' % (self.NODE_ROOT, nodeid) node_data, node_stat = self.client.get(node_path) if not node_data: self.log.warning("Node ID %s has no data", nodeid) continue node_data = self._strToDict(node_data) if (node_data['state'] == zuul.model.STATE_HOLD and node_data.get('hold_job') == identifier): count += 1 return count
class ZooKeeper(AbstractDCS): def __init__(self, name, config): super(ZooKeeper, self).__init__(name, config) hosts = config.get('hosts', []) if isinstance(hosts, list): hosts = ','.join(hosts) self.exhibitor = None if 'exhibitor' in config: exhibitor = config['exhibitor'] interval = exhibitor.get('poll_interval', 300) self.exhibitor = ExhibitorEnsembleProvider(exhibitor['hosts'], exhibitor['port'], poll_interval=interval) hosts = self.exhibitor.zookeeper_hosts self._client = KazooClient(hosts=hosts, timeout=(config.get('session_timeout') or 30), command_retry={'deadline': (config.get('reconnect_timeout') or 10), 'max_delay': 1, 'max_tries': -1}, connection_retry={'max_delay': 1, 'max_tries': -1}) self._client.add_listener(self.session_listener) self._my_member_data = None self._fetch_cluster = True self._last_leader_operation = 0 self._client.start() def session_listener(self, state): if state in [KazooState.SUSPENDED, KazooState.LOST]: self.cluster_watcher(None) def cluster_watcher(self, event): self._fetch_cluster = True self.event.set() def get_node(self, key, watch=None): try: ret = self._client.get(key, watch) return (ret[0].decode('utf-8'), ret[1]) except NoNodeError: return None @staticmethod def member(name, value, znode): return Member.from_node(znode.version, name, znode.ephemeralOwner, value) def get_children(self, key, watch=None): try: return self._client.get_children(key, watch) except NoNodeError: return [] def load_members(self): members = [] for member in self.get_children(self.members_path, self.cluster_watcher): data = self.get_node(self.members_path + member) if data is not None: members.append(self.member(member, *data)) return members def _inner_load_cluster(self): self._fetch_cluster = False self.event.clear() nodes = set(self.get_children(self.client_path(''), self.cluster_watcher)) if not nodes: self._fetch_cluster = True # get initialize flag initialize = (self.get_node(self.initialize_path) or [None])[0] if self._INITIALIZE in nodes else None # get list of members members = self.load_members() if self._MEMBERS[:-1] in nodes else [] # get leader leader = self.get_node(self.leader_path) if self._LEADER in nodes else None if leader: client_id = self._client.client_id if leader[0] == self._name and client_id is not None and client_id[0] != leader[1].ephemeralOwner: logger.info('I am leader but not owner of the session. Removing leader node') self._client.delete(self.leader_path) leader = None if leader: member = Member(-1, leader[0], None, {}) member = ([m for m in members if m.name == leader[0]] or [member])[0] leader = Leader(leader[1].version, leader[1].ephemeralOwner, member) self._fetch_cluster = member.index == -1 # failover key failover = self.get_node(self.failover_path, watch=self.cluster_watcher) if self._FAILOVER in nodes else None if failover: failover = Failover.from_node(failover[1].version, failover[0]) # get last leader operation optime = self.get_node(self.leader_optime_path) if self._OPTIME in nodes and self._fetch_cluster else None self._last_leader_operation = 0 if optime is None else int(optime[0]) self._cluster = Cluster(initialize, leader, self._last_leader_operation, members, failover) def _load_cluster(self): if self.exhibitor and self.exhibitor.poll(): self._client.set_hosts(self.exhibitor.zookeeper_hosts) if self._fetch_cluster or self._cluster is None: try: self._client.retry(self._inner_load_cluster) except: logger.exception('get_cluster') self.session_listener(KazooState.LOST) raise ZooKeeperError('ZooKeeper in not responding properly') def _create(self, path, value, **kwargs): try: self._client.retry(self._client.create, path, value.encode('utf-8'), **kwargs) return True except: return False def attempt_to_acquire_leader(self): ret = self._create(self.leader_path, self._name, makepath=True, ephemeral=True) if not ret: logger.info('Could not take out TTL lock') return ret def set_failover_value(self, value, index=None): try: self._client.retry(self._client.set, self.failover_path, value.encode('utf-8'), version=index or -1) return True except NoNodeError: return value == '' or (not index and self._create(self.failover_path, value)) except: logging.exception('set_failover_value') return False def initialize(self, create_new=True, sysid=""): return self._create(self.initialize_path, sysid, makepath=True) if create_new \ else self._client.retry(self._client.set, self.initialize_path, sysid.encode("utf-8")) def touch_member(self, data, ttl=None): cluster = self.cluster member = cluster and ([m for m in cluster.members if m.name == self._name] or [None])[0] path = self.member_path data = data.encode('utf-8') if member and self._client.client_id is not None and member.session != self._client.client_id[0]: try: self._client.retry(self._client.delete, path) except NoNodeError: pass except: return False member = None if member and data == self._my_member_data: return True try: if member: self._client.retry(self._client.set, path, data) else: self._client.retry(self._client.create, path, data, makepath=True, ephemeral=True) self._my_member_data = data return True except NodeExistsError: try: self._client.retry(self._client.set, path, data) self._my_member_data = data return True except: logger.exception('touch_member') except: logger.exception('touch_member') return False def take_leader(self): return self.attempt_to_acquire_leader() def write_leader_optime(self, last_operation): last_operation = last_operation.encode('utf-8') if last_operation != self._last_leader_operation: self._last_leader_operation = last_operation path = self.leader_optime_path try: self._client.retry(self._client.set, path, last_operation) except NoNodeError: try: self._client.retry(self._client.create, path, last_operation, makepath=True) except: logger.exception('Failed to create %s', path) except: logger.exception('Failed to update %s', path) def update_leader(self): return True def delete_leader(self): self._client.restart() self._my_member_data = None return True def _cancel_initialization(self): node = self.get_node(self.initialize_path) if node: self._client.delete(self.initialize_path, version=node[1].version) def cancel_initialization(self): try: self._client.retry(self._cancel_initialization) except: logger.exception("Unable to delete initialize key") def delete_cluster(self): try: return self._client.retry(self._client.delete, self.client_path(''), recursive=True) except NoNodeError: return True def watch(self, timeout): if super(ZooKeeper, self).watch(timeout): self._fetch_cluster = True return self._fetch_cluster
class ZooKeeper(object): ''' Class implementing the ZooKeeper interface. This class uses the facade design pattern to keep common interaction with the ZooKeeper API simple and consistent for the caller, and limits coupling between objects. It allows for more complex interactions by providing direct access to the client connection when needed (though that is discouraged). It also provides for a convenient entry point for testing only ZooKeeper interactions. Most API calls reference an image name only, as the path for the znode for that image is calculated automatically. And image names are assumed to be unique. ''' log = logging.getLogger("nodepool.zk.ZooKeeper") IMAGE_ROOT = "/nodepool/images" def __init__(self): ''' Initialize the ZooKeeper object. ''' self.client = None self._became_lost = False #======================================================================== # Private Methods #======================================================================== def _imagePath(self, image): return "%s/%s" % (self.IMAGE_ROOT, image) def _imageBuildRequestPath(self, image): return "%s/request-build" % self._imagePath(image) def _imageBuildsPath(self, image): return "%s/builds" % self._imagePath(image) def _imageBuildLockPath(self, image): return "%s/lock" % self._imageBuildsPath(image) def _imageBuildNumberLockPath(self, image, build_number): return "%s/%s/lock" % (self._imageBuildsPath(image), build_number) def _imageProviderPath(self, image, build_number): return "%s/%s/providers" % (self._imageBuildsPath(image), build_number) def _imageUploadPath(self, image, build_number, provider): return "%s/%s/providers/%s/images" % (self._imageBuildsPath(image), build_number, provider) def _imageUploadLockPath(self, image, build_number, provider): return "%s/lock" % self._imageUploadPath(image, build_number, provider) def _dictToStr(self, data): return json.dumps(data) def _strToDict(self, data): return json.loads(data) def _getImageBuildLock(self, image, blocking=True, timeout=None): lock_path = self._imageBuildLockPath(image) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise npe.TimeoutException( "Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise npe.ZKLockException("Did not get lock on %s" % lock_path) return lock def _getImageBuildNumberLock(self, image, build_number, blocking=True, timeout=None): lock_path = self._imageBuildNumberLockPath(image, build_number) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise npe.TimeoutException( "Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise npe.ZKLockException("Did not get lock on %s" % lock_path) return lock def _getImageUploadLock(self, image, build_number, provider, blocking=True, timeout=None): lock_path = self._imageUploadLockPath(image, build_number, provider) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise npe.TimeoutException( "Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise npe.ZKLockException("Did not get lock on %s" % lock_path) return lock def _connection_listener(self, state): ''' Listener method for Kazoo connection state changes. .. warning:: This method must not block. ''' if state == KazooState.LOST: self.log.debug("ZooKeeper connection: LOST") self._became_lost = True elif state == KazooState.SUSPENDED: self.log.debug("ZooKeeper connection: SUSPENDED") else: self.log.debug("ZooKeeper connection: CONNECTED") #======================================================================== # Public Methods and Properties #======================================================================== @property def connected(self): return self.client.state == KazooState.CONNECTED @property def suspended(self): return self.client.state == KazooState.SUSPENDED @property def lost(self): return self.client.state == KazooState.LOST @property def didLoseConnection(self): return self._became_lost def resetLostFlag(self): self._became_lost = False def connect(self, host_list, read_only=False): ''' Establish a connection with ZooKeeper cluster. Convenience method if a pre-existing ZooKeeper connection is not supplied to the ZooKeeper object at instantiation time. :param list host_list: A list of :py:class:`~nodepool.zk.ZooKeeperConnectionConfig` objects (one per server) defining the ZooKeeper cluster servers. :param bool read_only: If True, establishes a read-only connection. ''' if self.client is None: hosts = buildZooKeeperHosts(host_list) self.client = KazooClient(hosts=hosts, read_only=read_only) self.client.add_listener(self._connection_listener) self.client.start() def disconnect(self): ''' Close the ZooKeeper cluster connection. You should call this method if you used connect() to establish a cluster connection. ''' if self.client is not None and self.client.connected: self.client.stop() self.client.close() self.client = None def resetHosts(self, host_list): ''' Reset the ZooKeeper cluster connection host list. :param list host_list: A list of :py:class:`~nodepool.zk.ZooKeeperConnectionConfig` objects (one per server) defining the ZooKeeper cluster servers. ''' if self.client is not None: hosts = buildZooKeeperHosts(host_list) self.client.set_hosts(hosts=hosts) @contextmanager def imageBuildLock(self, image, blocking=True, timeout=None): ''' Context manager to use for locking image builds. Obtains a write lock for the specified image. :param str image: Name of the image to lock :param bool blocking: Whether or not to block on trying to acquire the lock :param int timeout: When blocking, how long to wait for the lock to get acquired. None, the default, waits forever. :raises: TimeoutException if we failed to acquire the lock when blocking with a timeout. ZKLockException if we are not blocking and could not get the lock, or a lock is already held. ''' lock = None try: lock = self._getImageBuildLock(image, blocking, timeout) yield finally: if lock: lock.release() @contextmanager def imageBuildNumberLock(self, image, build_number, blocking=True, timeout=None): ''' Context manager to use for locking _specific_ image builds. Obtains a write lock for the specified image build number. This is used for locking a build number during the cleanup phase of the builder. :param str image: Name of the image :param str build_number: The image build number to lock. :param bool blocking: Whether or not to block on trying to acquire the lock :param int timeout: When blocking, how long to wait for the lock to get acquired. None, the default, waits forever. :raises: TimeoutException if we failed to acquire the lock when blocking with a timeout. ZKLockException if we are not blocking and could not get the lock, or a lock is already held. ''' lock = None try: lock = self._getImageBuildNumberLock(image, build_number, blocking, timeout) yield finally: if lock: lock.release() @contextmanager def imageUploadLock(self, image, build_number, provider, blocking=True, timeout=None): ''' Context manager to use for locking image builds. Obtains a write lock for the specified image upload. :param str image: Name of the image. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param bool blocking: Whether or not to block on trying to acquire the lock :param int timeout: When blocking, how long to wait for the lock to get acquired. None, the default, waits forever. :raises: TimeoutException if we failed to acquire the lock when blocking with a timeout. ZKLockException if we are not blocking and could not get the lock, or a lock is already held. ''' lock = None try: lock = self._getImageUploadLock(image, build_number, provider, blocking, timeout) yield finally: if lock: lock.release() def getImageNames(self): ''' Retrieve the image names in Zookeeper. :returns: A list of image names or the empty list. ''' path = self.IMAGE_ROOT try: images = self.client.get_children(path) except kze.NoNodeError: return [] return sorted(images) def getBuildNumbers(self, image): ''' Retrieve the builds available for an image. :param str image: The image name. :returns: A list of image build numbers or the empty list. ''' path = self._imageBuildsPath(image) try: builds = self.client.get_children(path) except kze.NoNodeError: return [] builds = [x for x in builds if x != 'lock'] return builds def getBuildProviders(self, image, build_number): ''' Retrieve the providers which have uploads for an image build. :param str image: The image name. :param str build_number: The image build number. :returns: A list of provider names or the empty list. ''' path = self._imageProviderPath(image, build_number) try: providers = self.client.get_children(path) except kze.NoNodeError: return [] return sorted(providers) def getImageUploadNumbers(self, image, build_number, provider): ''' Retrieve upload numbers for a provider and image build. :param str image: The image name. :param str build_number: The image build number. :param str provider: The provider name owning the image. :returns: A list of upload numbers or the empty list. ''' path = self._imageUploadPath(image, build_number, provider) try: uploads = self.client.get_children(path) except kze.NoNodeError: return [] uploads = [x for x in uploads if x != 'lock'] return uploads def getBuild(self, image, build_number): ''' Retrieve the image build data. :param str image: The image name. :param str build_number: The image build number. :returns: An ImageBuild object, or None if not found. ''' path = self._imageBuildsPath(image) + "/%s" % build_number try: data, stat = self.client.get(path) except kze.NoNodeError: return None d = ImageBuild.fromDict(self._strToDict(data), build_number) d.stat = stat return d def getBuilds(self, image, states=None): ''' Retrieve all image build data matching any given states. :param str image: The image name. :param list states: A list of build state values to match against. A value of None will disable state matching and just return all builds. :returns: A list of ImageBuild objects. ''' path = self._imageBuildsPath(image) try: builds = self.client.get_children(path) except kze.NoNodeError: return [] matches = [] for build in builds: if build == 'lock': # skip the build lock node continue data = self.getBuild(image, build) if states is None: matches.append(data) elif data and data.state in states: matches.append(data) return matches def getMostRecentBuilds(self, count, image, state=None): ''' Retrieve the most recent image build data with the given state. :param int count: A count of the most recent builds to return. Use None for all builds. :param str image: The image name. :param str state: The build state to match on. Use None to ignore state :returns: A list of the most recent ImageBuild objects matching the given state, or an empty list if there were no builds matching the state. You may get less than 'count' entries if there were not enough matching builds. ''' states = None if state: states = [state] builds = self.getBuilds(image, states) if not builds: return [] builds.sort(key=lambda x: x.state_time, reverse=True) return builds[:count] def storeBuild(self, image, build_data, build_number=None): ''' Store the image build data. The build data is either created if it does not exist, or it is updated in its entirety if it does not. There is no partial updating. The build data is expected to be represented as a dict. This dict may contain any data, as appropriate. If a build number is not supplied, then a new build node/number is created. The new build number is available in the return value. .. important: You should have the image locked before calling this method. :param str image: The image name for which we have data. :param ImageBuild build_data: The build data. :param str build_number: The image build number. :returns: A string for the build number that was updated. ''' # Append trailing / so the sequence node is created as a child node. build_path = self._imageBuildsPath(image) + "/" if build_number is None: path = self.client.create( build_path, value=self._dictToStr(build_data.toDict()), sequence=True, makepath=True) build_number = path.split("/")[-1] else: path = build_path + build_number self.client.set(path, self._dictToStr(build_data.toDict())) return build_number def getImageUpload(self, image, build_number, provider, upload_number): ''' Retrieve the image upload data. :param str image: The image name. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param str upload_number: The image upload number. :returns: An ImageUpload object, or None if not found. :raises: ZKException if the image upload path is not found. ''' path = self._imageUploadPath(image, build_number, provider) path = path + "/%s" % upload_number try: data, stat = self.client.get(path) except kze.NoNodeError: return None d = ImageUpload.fromDict( self._strToDict(data), build_number, provider, image, upload_number ) d.stat = stat return d def getUploads(self, image, build_number, provider, states=None): ''' Retrieve all image upload data matching any given states. :param str image: The image name. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param list states: A list of upload state values to match against. A value of None will disable state matching and just return all uploads. :returns: A list of ImageUpload objects. ''' path = self._imageUploadPath(image, build_number, provider) try: uploads = self.client.get_children(path) except kze.NoNodeError: return [] matches = [] for upload in uploads: if upload == 'lock': continue data = self.getImageUpload(image, build_number, provider, upload) if states is None: matches.append(data) elif data and data.state in states: matches.append(data) return matches def getMostRecentBuildImageUploads(self, count, image, build_number, provider, state=None): ''' Retrieve the most recent image upload data with the given state. :param int count: A count of the most recent uploads to return. Use None for all uploads. :param str image: The image name. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param str state: The image upload state to match on. Use None to ignore state. :returns: A tuple with the most recent upload number and dictionary of upload data matching the given state, or None if there was no upload matching the state. ''' states = None if state: states = [state] uploads = self.getUploads(image, build_number, provider, states) if not uploads: return [] uploads.sort(key=lambda x: x.state_time, reverse=True) return uploads[:count] def getMostRecentImageUpload(self, image, provider, state="ready"): ''' Retrieve the most recent image upload data with the given state. :param str image: The image name. :param str provider: The provider name owning the image. :param str state: The image upload state to match on. :returns: An ImageUpload object matching the given state, or None if there is no recent upload. ''' recent_data = None for build_number in self.getBuildNumbers(image): path = self._imageUploadPath(image, build_number, provider) try: uploads = self.client.get_children(path) except kze.NoNodeError: uploads = [] for upload in uploads: if upload == 'lock': # skip the upload lock node continue data = self.getImageUpload(image, build_number, provider, upload) if not data or data.state != state: continue elif (recent_data is None or recent_data.state_time < data.state_time): recent_data = data return recent_data def storeImageUpload(self, image, build_number, provider, image_data, upload_number=None): ''' Store the built image's upload data for the given provider. The image upload data is either created if it does not exist, or it is updated in its entirety if it does not. There is no partial updating. The image data is expected to be represented as a dict. This dict may contain any data, as appropriate. If an image upload number is not supplied, then a new image upload node/number is created. The new upload number is available in the return value. :param str image: The image name for which we have data. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param ImageUpload image_data: The image data we want to store. :param str upload_number: The image upload number to update. :returns: A string for the upload number that was updated. :raises: ZKException for an invalid image build. ''' # We expect the image builds path to already exist. build_path = self._imageBuildsPath(image) if not self.client.exists(build_path): raise npe.ZKException( "Cannot find build %s of image %s" % (build_number, image) ) # Generate a path for the upload. This doesn't have to exist yet # since we'll create new provider/upload ID znodes automatically. # Append trailing / so the sequence node is created as a child node. upload_path = self._imageUploadPath(image, build_number, provider) + "/" if upload_number is None: path = self.client.create( upload_path, value=self._dictToStr(image_data.toDict()), sequence=True, makepath=True) upload_number = path.split("/")[-1] else: path = upload_path + upload_number self.client.set(path, self._dictToStr(image_data.toDict())) return upload_number def hasBuildRequest(self, image): ''' Check if an image has a pending build request. :param str image: The image name to check. :returns: True if request is pending, False otherwise ''' path = self._imageBuildRequestPath(image) if self.client.exists(path) is not None: return True return False def submitBuildRequest(self, image): ''' Submit a request for a new image build. :param str image: The image name. ''' path = self._imageBuildRequestPath(image) self.client.ensure_path(path) def removeBuildRequest(self, image): ''' Remove an image build request. :param str image: The image name to check. ''' path = self._imageBuildRequestPath(image) try: self.client.delete(path) except kze.NoNodeError: pass def deleteBuild(self, image, build_number): ''' Delete an image build from ZooKeeper. Any provider uploads for this build must be deleted before the build node can be deleted. :param str image: The image name. :param str build_number: The image build number to delete. :returns: True if the build is successfully deleted or did not exist, False if the provider uploads still exist. ''' path = self._imageBuildsPath(image) path = path + "/%s" % build_number # Verify that no upload znodes exist. for prov in self.getBuildProviders(image, build_number): if self.getImageUploadNumbers(image, build_number, prov): return False try: # NOTE: Need to do recursively to remove lock znodes self.client.delete(path, recursive=True) except kze.NoNodeError: pass return True def deleteUpload(self, image, build_number, provider, upload_number): ''' Delete an image upload from ZooKeeper. :param str image: The image name. :param str build_number: The image build number. :param str provider: The provider name owning the image. :param str upload_number: The image upload number to delete. ''' path = self._imageUploadPath(image, build_number, provider) path = path + "/%s" % upload_number try: self.client.delete(path) except kze.NoNodeError: pass
class _ZookeeperProxy(object): def __init__(self, address_provider: AddressListProvider, prefix: str): self.address_provider = address_provider self.async_counter = WaitingCounter(limit=100) self.conn_str = None self.client = None self.prefix = prefix self.hosts_cache = SlowlyUpdatedCache( self.address_provider.get_latest_address, self._update_hosts, 30, # Refresh every 30 seconds 3 * 60) # Update only after 180 seconds of stability def _update_hosts(self, value): hosts, port = value if hosts: self.conn_str = ','.join(['{}:{}'.format(h, port) for h in hosts]) + self.prefix if self.client is None: self.client = KazooClient(hosts=self.conn_str, command_retry={ 'deadline': 120, 'max_delay': 1, 'max_tries': -1 }, connection_retry={ 'max_delay': 1, 'max_tries': -1 }) self.client.add_listener(self.session_listener) else: self.client.stop() self.client.set_hosts(self.conn_str) self.client.start() def terminate(self): if self.client: self.client.stop() def session_listener(self, state): pass def get_conn_str(self): return self.conn_str def get(self, *params): self.hosts_cache.touch() return self.client.retry(self.client.get, *params) def get_async(self, *params): # Exhibitor is not polled here and it's totally fine! self.async_counter.increment() try: i_async = self.client.get_async(*params) i_async.rawlink(self._decrement) return i_async except Exception as e: self._decrement() raise e def _decrement(self, *args, **kwargs): self.async_counter.decrement() def set(self, *args, **kwargs): self.hosts_cache.touch() return self.client.retry(self.client.set, *args, **kwargs) def create(self, *args, **kwargs): self.hosts_cache.touch() return self.client.retry(self.client.create, *args, **kwargs) def delete(self, *args, **kwargs): self.hosts_cache.touch() try: return self.client.retry(self.client.delete, *args, **kwargs) except NoNodeError: pass def get_children(self, *params): self.hosts_cache.touch() try: return self.client.retry(self.client.get_children, *params) except NoNodeError: return [] def take_lock(self, *args, **kwargs): while True: try: self.hosts_cache.touch() return self.client.Lock(*args, **kwargs) except Exception as e: _LOG.error('Failed to obtain lock for exhibitor, retrying', exc_info=e)
class ZooKeeper(AbstractDCS): def __init__(self, name, config): super(ZooKeeper, self).__init__(name, config) hosts = config.get('hosts', []) if isinstance(hosts, list): hosts = ','.join(hosts) self.exhibitor = None if 'exhibitor' in config: exhibitor = config['exhibitor'] interval = exhibitor.get('poll_interval', 300) self.exhibitor = ExhibitorEnsembleProvider(exhibitor['hosts'], exhibitor['port'], poll_interval=interval) hosts = self.exhibitor.zookeeper_hosts self.client = KazooClient(hosts=hosts, timeout=(config.get('session_timeout', None) or 30), command_retry={ 'deadline': (config.get('reconnect_timeout', None) or 10), 'max_delay': 1, 'max_tries': -1}, connection_retry={'max_delay': 1, 'max_tries': -1}) self.client.add_listener(self.session_listener) self.cluster_event = self.client.handler.event_object() self.cluster = None self.fetch_cluster = True self.last_leader_operation = 0 self.client.start(None) def session_listener(self, state): if state in [KazooState.SUSPENDED, KazooState.LOST]: self.cluster_watcher(None) def cluster_watcher(self, event): self.fetch_cluster = True self.cluster_event.set() def get_node(self, key, watch=None): try: ret = self.client.get(key, watch) return (ret[0].decode('utf-8'), ret[1]) except NoNodeError: return None @staticmethod def member(name, value, znode): conn_url, api_url = parse_connection_string(value) return Member(znode.version, name, conn_url, api_url, None, None) def get_children(self, key, watch=None): try: return self.client.get_children(key, watch) except NoNodeError: return [] def load_members(self): members = [] for member in self.get_children(self.members_path, self.cluster_watcher): data = self.get_node(self.members_path + member) if data is not None: members.append(self.member(member, *data)) return members def _inner_load_cluster(self): self.cluster_event.clear() nodes = set(self.get_children(self.client_path(''))) # get initialize flag initialize = self._INITIALIZE in nodes # get list of members members = self.load_members() if self._MEMBERS[:-1] in nodes else [] # get leader leader = self.get_node(self.leader_path, self.cluster_watcher) if self._LEADER in nodes else None if leader: client_id = self.client.client_id if leader[0] == self._name and client_id is not None and client_id[0] != leader[1].ephemeralOwner: logger.info('I am leader but not owner of the session. Removing leader node') self.client.delete(self.leader_path) leader = None if leader: member = Member(-1, leader[0], None, None, None, None) member = ([m for m in members if m.name == leader[0]] or [member])[0] leader = Leader(leader[1].version, None, None, member) self.fetch_cluster = member.index == -1 # get last leader operation self.last_leader_operation = self.get_node(self.leader_optime_path) if self.fetch_cluster else None self.last_leader_operation = 0 if self.last_leader_operation is None else int(self.last_leader_operation[0]) self.cluster = Cluster(initialize, leader, self.last_leader_operation, members) def get_cluster(self): if self.exhibitor and self.exhibitor.poll(): self.client.set_hosts(self.exhibitor.zookeeper_hosts) if self.fetch_cluster: try: self.client.retry(self._inner_load_cluster) except: logger.exception('get_cluster') self.session_listener(KazooState.LOST) raise ZooKeeperError('ZooKeeper in not responding properly') return self.cluster def _create(self, path, value, **kwargs): try: self.client.retry(self.client.create, path, value.encode('utf-8'), **kwargs) return True except: return False def attempt_to_acquire_leader(self): ret = self._create(self.leader_path, self._name, makepath=True, ephemeral=True) ret or logger.info('Could not take out TTL lock') return ret def initialize(self): return self._create(self.initialize_path, self._name, makepath=True) def touch_member(self, connection_string, ttl=None): if self.cluster and any(m.name == self._name for m in self.cluster.members): return True path = self.member_path connection_string = connection_string.encode('utf-8') try: self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except NodeExistsError: try: self.client.retry(self.client.delete, path) self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except: logger.exception('touch_member') return False def take_leader(self): return self.attempt_to_acquire_leader() def update_leader(self, state_handler): last_operation = state_handler.last_operation().encode('utf-8') if last_operation != self.last_leader_operation: self.last_leader_operation = last_operation path = self.leader_optime_path try: self.client.retry(self.client.set, path, last_operation) except NoNodeError: try: self.client.retry(self.client.create, path, last_operation, makepath=True) except: logger.exception('Failed to create %s', path) except: logger.exception('Failed to update %s', path) return True def delete_leader(self): if isinstance(self.cluster, Cluster) and self.cluster.leader.name == self._name: self.client.delete(self.leader_path, version=self.cluster.leader.index) def _cancel_initialization(self): node = self.get_node(self.initialize_path) if node and node[0] == self._name: self.client.delete(self.initialize_path, version=node[1].version) def cancel_initialization(self): try: self.client.retry(self._cancel_initialization) except: logger.exception("Unable to delete initialize key") def watch(self, timeout): self.cluster_event.wait(timeout) if self.cluster_event.isSet(): self.fetch_cluster = True
class ZooKeeper(object): ''' Class implementing the ZooKeeper interface. This class uses the facade design pattern to keep common interaction with the ZooKeeper API simple and consistent for the caller, and limits coupling between objects. It allows for more complex interactions by providing direct access to the client connection when needed (though that is discouraged). It also provides for a convenient entry point for testing only ZooKeeper interactions. ''' log = logging.getLogger("zuul.zk.ZooKeeper") REQUEST_ROOT = '/nodepool/requests' REQUEST_LOCK_ROOT = "/nodepool/requests-lock" NODE_ROOT = '/nodepool/nodes' HOLD_REQUEST_ROOT = '/zuul/hold-requests' # Log zookeeper retry every 10 seconds retry_log_rate = 10 def __init__(self, enable_cache=True): ''' Initialize the ZooKeeper object. :param bool enable_cache: When True, enables caching of ZooKeeper objects (e.g., HoldRequests). ''' self.client = None self._became_lost = False self._last_retry_log = 0 self.enable_cache = enable_cache # The caching model we use is designed around handing out model # data as objects. To do this, we use two caches: one is a TreeCache # which contains raw znode data (among other details), and one for # storing that data serialized as objects. This allows us to return # objects from the APIs, and avoids calling the methods to serialize # the data into objects more than once. self._hold_request_tree = None self._cached_hold_requests = {} def _dictToStr(self, data): return json.dumps(data).encode('utf8') def _strToDict(self, data): return json.loads(data.decode('utf8')) def _connection_listener(self, state): ''' Listener method for Kazoo connection state changes. .. warning:: This method must not block. ''' if state == KazooState.LOST: self.log.debug("ZooKeeper connection: LOST") self._became_lost = True elif state == KazooState.SUSPENDED: self.log.debug("ZooKeeper connection: SUSPENDED") else: self.log.debug("ZooKeeper connection: CONNECTED") @property def connected(self): return self.client.state == KazooState.CONNECTED @property def suspended(self): return self.client.state == KazooState.SUSPENDED @property def lost(self): return self.client.state == KazooState.LOST @property def didLoseConnection(self): return self._became_lost def resetLostFlag(self): self._became_lost = False def logConnectionRetryEvent(self): now = time.monotonic() if now - self._last_retry_log >= self.retry_log_rate: self.log.warning("Retrying zookeeper connection") self._last_retry_log = now def connect(self, hosts, read_only=False, timeout=10.0): ''' Establish a connection with ZooKeeper cluster. Convenience method if a pre-existing ZooKeeper connection is not supplied to the ZooKeeper object at instantiation time. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). :param bool read_only: If True, establishes a read-only connection. :param float timeout: The ZooKeeper session timeout, in seconds (default: 10.0). ''' if self.client is None: self.client = KazooClient(hosts=hosts, read_only=read_only, timeout=timeout) self.client.add_listener(self._connection_listener) # Manually retry initial connection attempt while True: try: self.client.start(1) break except KazooTimeoutError: self.logConnectionRetryEvent() if self.enable_cache: self._hold_request_tree = TreeCache(self.client, self.HOLD_REQUEST_ROOT) self._hold_request_tree.listen_fault(self.cacheFaultListener) self._hold_request_tree.listen(self.holdRequestCacheListener) self._hold_request_tree.start() def cacheFaultListener(self, e): self.log.exception(e) def holdRequestCacheListener(self, event): ''' Keep the hold request object cache in sync with the TreeCache. ''' try: self._holdRequestCacheListener(event) except Exception: self.log.exception( "Exception in hold request cache update for event: %s", event) def _holdRequestCacheListener(self, event): if hasattr(event.event_data, 'path'): # Ignore root node path = event.event_data.path if path == self.HOLD_REQUEST_ROOT: return if event.event_type not in (TreeEvent.NODE_ADDED, TreeEvent.NODE_UPDATED, TreeEvent.NODE_REMOVED): return path = event.event_data.path request_id = path.rsplit('/', 1)[1] if event.event_type in (TreeEvent.NODE_ADDED, TreeEvent.NODE_UPDATED): # Requests with no data are invalid if not event.event_data.data: return # Perform an in-place update of the already cached request d = self._bytesToDict(event.event_data.data) old_request = self._cached_hold_requests.get(request_id) if old_request: if event.event_data.stat.version <= old_request.stat.version: # Don't update to older data return old_request.updateFromDict(d) old_request.stat = event.event_data.stat else: request = zuul.model.HoldRequest.fromDict(d) request.id = request_id request.stat = event.event_data.stat self._cached_hold_requests[request_id] = request elif event.event_type == TreeEvent.NODE_REMOVED: try: del self._cached_hold_requests[request_id] except KeyError: pass def disconnect(self): ''' Close the ZooKeeper cluster connection. You should call this method if you used connect() to establish a cluster connection. ''' if self._hold_request_tree is not None: self._hold_request_tree.close() self._hold_request_tree = None if self.client is not None and self.client.connected: self.client.stop() self.client.close() self.client = None def resetHosts(self, hosts): ''' Reset the ZooKeeper cluster connection host list. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). ''' if self.client is not None: self.client.set_hosts(hosts=hosts) def submitNodeRequest(self, node_request, watcher): ''' Submit a request for nodes to Nodepool. :param NodeRequest node_request: A NodeRequest with the contents of the request. :param callable watcher: A callable object that will be invoked each time the request is updated. It is called with two arguments: (node_request, deleted) where node_request is the same argument passed to this method, and deleted is a boolean which is True if the node no longer exists (notably, this will happen on disconnection from ZooKeeper). The watcher should return False when further updates are no longer necessary. ''' node_request.created_time = time.time() data = node_request.toDict() path = '{}/{:0>3}-'.format(self.REQUEST_ROOT, node_request.priority) path = self.client.create(path, self._dictToStr(data), makepath=True, sequence=True, ephemeral=True) reqid = path.split("/")[-1] node_request.id = reqid def callback(data, stat): if data: self.updateNodeRequest(node_request, data) deleted = (data is None) # data *are* none return watcher(node_request, deleted) self.client.DataWatch(path, callback) def deleteNodeRequest(self, node_request): ''' Delete a request for nodes. :param NodeRequest node_request: A NodeRequest with the contents of the request. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) try: self.client.delete(path) except kze.NoNodeError: pass def nodeRequestExists(self, node_request): ''' See if a NodeRequest exists in ZooKeeper. :param NodeRequest node_request: A NodeRequest to verify. :returns: True if the request exists, False otherwise. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) if self.client.exists(path): return True return False def storeNodeRequest(self, node_request): '''Store the node request. The request is expected to already exist and is updated in its entirety. :param NodeRequest node_request: The request to update. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) self.client.set(path, self._dictToStr(node_request.toDict())) def updateNodeRequest(self, node_request, data=None): '''Refresh an existing node request. :param NodeRequest node_request: The request to update. :param dict data: The data to use; query ZK if absent. ''' if data is None: path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) data, stat = self.client.get(path) data = self._strToDict(data) request_nodes = list(node_request.nodeset.getNodes()) for i, nodeid in enumerate(data.get('nodes', [])): request_nodes[i].id = nodeid self.updateNode(request_nodes[i]) node_request.updateFromDict(data) def storeNode(self, node): '''Store the node. The node is expected to already exist and is updated in its entirety. :param Node node: The node to update. ''' path = '%s/%s' % (self.NODE_ROOT, node.id) self.client.set(path, self._dictToStr(node.toDict())) def updateNode(self, node): '''Refresh an existing node. :param Node node: The node to update. ''' node_path = '%s/%s' % (self.NODE_ROOT, node.id) node_data, node_stat = self.client.get(node_path) node_data = self._strToDict(node_data) node.updateFromDict(node_data) def lockNode(self, node, blocking=True, timeout=None): ''' Lock a node. This should be called as soon as a request is fulfilled and the lock held for as long as the node is in-use. It can be used by nodepool to detect if Zuul has gone offline and the node should be reclaimed. :param Node node: The node which should be locked. ''' lock_path = '%s/%s/lock' % (self.NODE_ROOT, node.id) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException("Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % lock_path) node.lock = lock def unlockNode(self, node): ''' Unlock a node. The node must already have been locked. :param Node node: The node which should be unlocked. ''' if node.lock is None: raise LockException("Node %s does not hold a lock" % (node, )) node.lock.release() node.lock = None def lockNodeRequest(self, request, blocking=True, timeout=None): ''' Lock a node request. This will set the `lock` attribute of the request object when the lock is successfully acquired. :param NodeRequest request: The request to lock. :param bool blocking: Whether or not to block on trying to acquire the lock :param int timeout: When blocking, how long to wait for the lock to get acquired. None, the default, waits forever. :raises: TimeoutException if we failed to acquire the lock when blocking with a timeout. ZKLockException if we are not blocking and could not get the lock, or a lock is already held. ''' path = "%s/%s" % (self.REQUEST_LOCK_ROOT, request.id) try: lock = Lock(self.client, path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException("Timeout trying to acquire lock %s" % path) except kze.NoNodeError: have_lock = False self.log.error("Request not found for locking: %s", request) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % path) request.lock = lock self.updateNodeRequest(request) def unlockNodeRequest(self, request): ''' Unlock a node request. The request must already have been locked. :param NodeRequest request: The request to unlock. :raises: ZKLockException if the request is not currently locked. ''' if request.lock is None: raise LockException("Request %s does not hold a lock" % request) request.lock.release() request.lock = None def heldNodeCount(self, autohold_key): ''' Count the number of nodes being held for the given tenant/project/job. :param set autohold_key: A set with the tenant/project/job names. ''' identifier = " ".join(autohold_key) try: nodes = self.client.get_children(self.NODE_ROOT) except kze.NoNodeError: return 0 count = 0 for nodeid in nodes: node_path = '%s/%s' % (self.NODE_ROOT, nodeid) try: node_data, node_stat = self.client.get(node_path) except kze.NoNodeError: # Node got removed on us. Just ignore. continue if not node_data: self.log.warning("Node ID %s has no data", nodeid) continue node_data = self._strToDict(node_data) if (node_data['state'] == zuul.model.STATE_HOLD and node_data.get('hold_job') == identifier): count += 1 return count # Copy of nodepool/zk.py begins here NODE_ROOT = "/nodepool/nodes" LAUNCHER_ROOT = "/nodepool/launchers" def _bytesToDict(self, data): return json.loads(data.decode('utf8')) def _launcherPath(self, launcher): return "%s/%s" % (self.LAUNCHER_ROOT, launcher) def _nodePath(self, node): return "%s/%s" % (self.NODE_ROOT, node) def getRegisteredLaunchers(self): ''' Get a list of all launchers that have registered with ZooKeeper. :returns: A list of Launcher objects, or empty list if none are found. ''' try: launcher_ids = self.client.get_children(self.LAUNCHER_ROOT) except kze.NoNodeError: return [] objs = [] for launcher in launcher_ids: path = self._launcherPath(launcher) try: data, _ = self.client.get(path) except kze.NoNodeError: # launcher disappeared continue objs.append(Launcher.fromDict(self._bytesToDict(data))) return objs def getNodes(self): ''' Get the current list of all nodes. :returns: A list of nodes. ''' try: return self.client.get_children(self.NODE_ROOT) except kze.NoNodeError: return [] def getNode(self, node): ''' Get the data for a specific node. :param str node: The node ID. :returns: The node data, or None if the node was not found. ''' path = self._nodePath(node) try: data, stat = self.client.get(path) except kze.NoNodeError: return None if not data: return None d = self._bytesToDict(data) d['id'] = node return d def nodeIterator(self): ''' Utility generator method for iterating through all nodes. ''' for node_id in self.getNodes(): node = self.getNode(node_id) if node: yield node def getHoldRequests(self): ''' Get the current list of all hold requests. ''' try: return sorted(self.client.get_children(self.HOLD_REQUEST_ROOT)) except kze.NoNodeError: return [] def getHoldRequest(self, hold_request_id): path = self.HOLD_REQUEST_ROOT + "/" + hold_request_id try: data, stat = self.client.get(path) except kze.NoNodeError: return None if not data: return None obj = zuul.model.HoldRequest.fromDict(self._strToDict(data)) obj.id = hold_request_id obj.stat = stat return obj def storeHoldRequest(self, hold_request): ''' Create or update a hold request. If this is a new request with no value for the `id` attribute of the passed in request, then `id` will be set with the unique request identifier after successful creation. :param HoldRequest hold_request: Object representing the hold request. ''' if hold_request.id is None: path = self.client.create(self.HOLD_REQUEST_ROOT + "/", value=hold_request.serialize(), sequence=True, makepath=True) hold_request.id = path.split('/')[-1] else: path = self.HOLD_REQUEST_ROOT + "/" + hold_request.id self.client.set(path, hold_request.serialize()) def _markHeldNodesAsUsed(self, hold_request): ''' Changes the state for each held node for the hold request to 'used'. :returns: True if all nodes marked USED, False otherwise. ''' def getHeldNodeIDs(request): node_ids = [] for data in request.nodes: # TODO(Shrews): Remove type check at some point. # When autoholds were initially changed to be stored in ZK, # the node IDs were originally stored as a list of strings. # A later change embedded them within a dict. Handle both # cases here to deal with the upgrade. if isinstance(data, dict): node_ids += data['nodes'] else: node_ids.append(data) return node_ids failure = False for node_id in getHeldNodeIDs(hold_request): node = self.getNode(node_id) if not node or node['state'] == zuul.model.STATE_USED: continue node['state'] = zuul.model.STATE_USED name = None label = None if 'name' in node: name = node['name'] if 'label' in node: label = node['label'] node_obj = zuul.model.Node(name, label) node_obj.updateFromDict(node) try: self.lockNode(node_obj, blocking=False) self.storeNode(node_obj) except Exception: self.log.exception( "Cannot change HELD node state to USED " "for node %s in request %s", node_obj.id, hold_request.id) failure = True finally: try: if node_obj.lock: self.unlockNode(node_obj) except Exception: self.log.exception( "Failed to unlock HELD node %s for request %s", node_obj.id, hold_request.id) return not failure def deleteHoldRequest(self, hold_request): ''' Delete a hold request. :param HoldRequest hold_request: Object representing the hold request. ''' if not self._markHeldNodesAsUsed(hold_request): self.log.info( "Unable to delete hold request %s because " "not all nodes marked as USED.", hold_request.id) return path = self.HOLD_REQUEST_ROOT + "/" + hold_request.id try: self.client.delete(path, recursive=True) except kze.NoNodeError: pass def lockHoldRequest(self, request, blocking=True, timeout=None): ''' Lock a node request. This will set the `lock` attribute of the request object when the lock is successfully acquired. :param HoldRequest request: The hold request to lock. ''' if not request.id: raise LockException( "Hold request without an ID cannot be locked: %s" % request) path = "%s/%s/lock" % (self.HOLD_REQUEST_ROOT, request.id) try: lock = Lock(self.client, path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException("Timeout trying to acquire lock %s" % path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % path) request.lock = lock def unlockHoldRequest(self, request): ''' Unlock a hold request. The request must already have been locked. :param HoldRequest request: The request to unlock. :raises: ZKLockException if the request is not currently locked. ''' if request.lock is None: raise LockException("Request %s does not hold a lock" % request) request.lock.release() request.lock = None
class ZooKeeper(AbstractDCS): def __init__(self, name, config): super(ZooKeeper, self).__init__(name, config) hosts = config.get('hosts', []) if isinstance(hosts, list): hosts = ','.join(hosts) self.exhibitor = None if 'exhibitor' in config: exhibitor = config['exhibitor'] interval = exhibitor.get('poll_interval', 300) self.exhibitor = ExhibitorEnsembleProvider(exhibitor['hosts'], exhibitor['port'], poll_interval=interval) hosts = self.exhibitor.zookeeper_hosts self.client = KazooClient(hosts=hosts, timeout=(config.get('session_timeout', None) or 30), command_retry={ 'deadline': (config.get('reconnect_timeout', None) or 10), 'max_delay': 1, 'max_tries': -1 }, connection_retry={ 'max_delay': 1, 'max_tries': -1 }) self.client.add_listener(self.session_listener) self.cluster_event = self.client.handler.event_object() self.fetch_cluster = True self.members = [] self.leader = None self.last_leader_operation = 0 self.client.start(None) def session_listener(self, state): if state in [KazooState.SUSPENDED, KazooState.LOST]: self.cluster_watcher(None) def cluster_watcher(self, event): self.fetch_cluster = True self.cluster_event.set() def get_node(self, name, watch=None): try: return self.client.get(self.client_path(name), watch) except NoNodeError: pass except: logger.exception('get_node') return None @staticmethod def member(name, value, znode): conn_url, api_url = parse_connection_string(value) return Member(znode.mzxid, name, conn_url, api_url, None, None) def load_members(self): members = [] for member in self.client.get_children(self.client_path('/members'), self.cluster_watcher): data = self.get_node('/members/' + member) if data is not None: members.append(self.member(member, *data)) return members def _inner_load_cluster(self): self.cluster_event.clear() leader = self.get_node('/leader', self.cluster_watcher) self.members = self.load_members() if leader: if leader[0] == self._name: client_id = self.client.client_id if client_id is not None and client_id[0] != leader[ 1].ephemeralOwner: logger.info( 'I am leader but not owner of the session. Removing leader node' ) self.client.delete(self.client_path('/leader')) leader = None if leader: for member in self.members: if member.name == leader[0]: leader = member self.fetch_cluster = False break if not isinstance(leader, Member): leader = Member(-1, leader, None, None, None, None) self.leader = leader if self.fetch_cluster: last_leader_operation = self.get_node('/optime/leader') if last_leader_operation: self.last_leader_operation = int(last_leader_operation[0]) def get_cluster(self): if self.exhibitor and self.exhibitor.poll(): self.client.set_hosts(self.exhibitor.zookeeper_hosts) if self.fetch_cluster: try: self.client.retry(self._inner_load_cluster) except: logger.exception('get_cluster') self.session_listener(KazooState.LOST) raise ZooKeeperError('ZooKeeper in not responding properly') return Cluster(True, self.leader, self.last_leader_operation, self.members) def _create(self, path, value, **kwargs): try: self.client.retry(self.client.create, self.client_path(path), value, **kwargs) return True except: return False def attempt_to_acquire_leader(self): ret = self._create('/leader', self._name, makepath=True, ephemeral=True) ret or logger.info('Could not take out TTL lock') return ret def race(self, path): return self._create(path, self._name, makepath=True) def touch_member(self, connection_string, ttl=None): for m in self.members: if m.name == self._name: return True path = self.client_path('/members/' + self._name) try: self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except NodeExistsError: try: self.client.retry(self.client.delete, path) self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except: logger.exception('touch_member') return False def take_leader(self): return self.attempt_to_acquire_leader() def update_leader(self, state_handler): last_operation = state_handler.last_operation() if last_operation != self.last_leader_operation: self.last_leader_operation = last_operation path = self.client_path('/optime/leader') try: self.client.retry(self.client.set, path, last_operation) except NoNodeError: try: self.client.retry(self.client.create, path, last_operation, makepath=True) except: logger.exception('Failed to create %s', path) except: logger.exception('Failed to update %s', path) return True def delete_leader(self): if isinstance(self.leader, Member) and self.leader.name == self._name: self.client.delete(self.client_path('/leader')) def sleep(self, timeout): self.cluster_event.wait(timeout) if self.cluster_event.isSet(): self.fetch_cluster = True
class ZooKeeper(AbstractDCS): def __init__(self, name, config): super(ZooKeeper, self).__init__(name, config) hosts = config.get('hosts', []) if isinstance(hosts, list): hosts = ','.join(hosts) self.exhibitor = None if 'exhibitor' in config: exhibitor = config['exhibitor'] interval = exhibitor.get('poll_interval', 300) self.exhibitor = ExhibitorEnsembleProvider(exhibitor['hosts'], exhibitor['port'], poll_interval=interval) hosts = self.exhibitor.zookeeper_hosts self.client = KazooClient(hosts=hosts, timeout=(config.get('session_timeout', None) or 30), command_retry={ 'deadline': (config.get('reconnect_timeout', None) or 10), 'max_delay': 1, 'max_tries': -1}, connection_retry={'max_delay': 1, 'max_tries': -1}) self.client.add_listener(self.session_listener) self.cluster_event = self.client.handler.event_object() self.fetch_cluster = True self.members = [] self.leader = None self.last_leader_operation = 0 self.client.start(None) def session_listener(self, state): if state in [KazooState.SUSPENDED, KazooState.LOST]: self.cluster_watcher(None) def cluster_watcher(self, event): self.fetch_cluster = True self.cluster_event.set() def get_node(self, name, watch=None): try: return self.client.get(self.client_path(name), watch) except NoNodeError: pass except: logger.exception('get_node') return None @staticmethod def member(name, value, znode): conn_url, api_url = parse_connection_string(value) return Member(znode.mzxid, name, conn_url, api_url, None, None) def load_members(self): members = [] for member in self.client.get_children(self.client_path('/members'), self.cluster_watcher): data = self.get_node('/members/' + member) if data is not None: members.append(self.member(member, *data)) return members def _inner_load_cluster(self): self.cluster_event.clear() leader = self.get_node('/leader', self.cluster_watcher) self.members = self.load_members() if leader: if leader[0] == self._name: client_id = self.client.client_id if client_id is not None and client_id[0] != leader[1].ephemeralOwner: logger.info('I am leader but not owner of the session. Removing leader node') self.client.delete(self.client_path('/leader')) leader = None if leader: for member in self.members: if member.name == leader[0]: leader = member self.fetch_cluster = False break if not isinstance(leader, Member): leader = Member(-1, leader, None, None, None, None) self.leader = leader if self.fetch_cluster: last_leader_operation = self.get_node('/optime/leader') if last_leader_operation: self.last_leader_operation = int(last_leader_operation[0]) def get_cluster(self): if self.exhibitor and self.exhibitor.poll(): self.client.set_hosts(self.exhibitor.zookeeper_hosts) if self.fetch_cluster: try: self.client.retry(self._inner_load_cluster) except: logger.exception('get_cluster') self.session_listener(KazooState.LOST) raise ZooKeeperError('ZooKeeper in not responding properly') return Cluster(True, self.leader, self.last_leader_operation, self.members) def _create(self, path, value, **kwargs): try: self.client.retry(self.client.create, self.client_path(path), value, **kwargs) return True except: return False def attempt_to_acquire_leader(self): ret = self._create('/leader', self._name, makepath=True, ephemeral=True) ret or logger.info('Could not take out TTL lock') return ret def race(self, path): return self._create(path, self._name, makepath=True) def touch_member(self, connection_string, ttl=None): for m in self.members: if m.name == self._name: return True path = self.client_path('/members/' + self._name) try: self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except NodeExistsError: try: self.client.retry(self.client.delete, path) self.client.retry(self.client.create, path, connection_string, makepath=True, ephemeral=True) return True except: logger.exception('touch_member') return False def take_leader(self): return self.attempt_to_acquire_leader() def update_leader(self, state_handler): last_operation = state_handler.last_operation() if last_operation != self.last_leader_operation: self.last_leader_operation = last_operation path = self.client_path('/optime/leader') try: self.client.retry(self.client.set, path, last_operation) except NoNodeError: try: self.client.retry(self.client.create, path, last_operation, makepath=True) except: logger.exception('Failed to create %s', path) except: logger.exception('Failed to update %s', path) return True def delete_leader(self): if isinstance(self.leader, Member) and self.leader.name == self._name: self.client.delete(self.client_path('/leader')) def sleep(self, timeout): self.cluster_event.wait(timeout) if self.cluster_event.isSet(): self.fetch_cluster = True
class _ZookeeperProxy(object): def __init__(self, address_provider: AddressListProvider, prefix: str): self.address_provider = address_provider self.async_counter = WaitingCounter(limit=100) self.conn_str = None self.client = None self.prefix = prefix self.hosts_cache = SlowlyUpdatedCache( self.address_provider.get_latest_address, self._update_hosts, 30, # Refresh every 30 seconds 3 * 60) # Update only after 180 seconds of stability def _update_hosts(self, value): hosts, port = value if hosts: self.conn_str = ','.join(['{}:{}'.format(h, port) for h in hosts]) + self.prefix if self.client is None: self.client = KazooClient(hosts=self.conn_str, command_retry={'deadline': 120, 'max_delay': 1, 'max_tries': -1}, connection_retry={'max_delay': 1, 'max_tries': -1}) self.client.add_listener(self.session_listener) else: self.client.stop() self.client.set_hosts(self.conn_str) self.client.start() def terminate(self): if self.client: self.client.stop() def session_listener(self, state): pass def get_conn_str(self): return self.conn_str def get(self, *params): self.hosts_cache.touch() return self.client.retry(self.client.get, *params) def get_async(self, *params): # Exhibitor is not polled here and it's totally fine! self.async_counter.increment() try: i_async = self.client.get_async(*params) i_async.rawlink(self._decrement) return i_async except Exception as e: self._decrement() raise e def _decrement(self, *args, **kwargs): self.async_counter.decrement() def set(self, *args, **kwargs): self.hosts_cache.touch() return self.client.retry(self.client.set, *args, **kwargs) def create(self, *args, **kwargs): self.hosts_cache.touch() return self.client.retry(self.client.create, *args, **kwargs) def delete(self, *args, **kwargs): self.hosts_cache.touch() try: return self.client.retry(self.client.delete, *args, **kwargs) except NoNodeError: pass def get_children(self, *args, **kwargs): self.hosts_cache.touch() try: return self.client.retry(self.client.get_children, *args, **kwargs) except NoNodeError: return [] def take_lock(self, *args, **kwargs): while True: try: self.hosts_cache.touch() return self.client.Lock(*args, **kwargs) except Exception as e: _LOG.error('Failed to obtain lock for exhibitor, retrying', exc_info=e)
class ZooKeeper(object): ''' Class implementing the ZooKeeper interface. This class uses the facade design pattern to keep common interaction with the ZooKeeper API simple and consistent for the caller, and limits coupling between objects. It allows for more complex interactions by providing direct access to the client connection when needed (though that is discouraged). It also provides for a convenient entry point for testing only ZooKeeper interactions. ''' log = logging.getLogger("zuul.zk.ZooKeeper") REQUEST_ROOT = '/nodepool/requests' REQUEST_LOCK_ROOT = "/nodepool/requests-lock" NODE_ROOT = '/nodepool/nodes' # Log zookeeper retry every 10 seconds retry_log_rate = 10 def __init__(self): ''' Initialize the ZooKeeper object. ''' self.client = None self._became_lost = False self._last_retry_log = 0 def _dictToStr(self, data): return json.dumps(data).encode('utf8') def _strToDict(self, data): return json.loads(data.decode('utf8')) def _connection_listener(self, state): ''' Listener method for Kazoo connection state changes. .. warning:: This method must not block. ''' if state == KazooState.LOST: self.log.debug("ZooKeeper connection: LOST") self._became_lost = True elif state == KazooState.SUSPENDED: self.log.debug("ZooKeeper connection: SUSPENDED") else: self.log.debug("ZooKeeper connection: CONNECTED") @property def connected(self): return self.client.state == KazooState.CONNECTED @property def suspended(self): return self.client.state == KazooState.SUSPENDED @property def lost(self): return self.client.state == KazooState.LOST @property def didLoseConnection(self): return self._became_lost def resetLostFlag(self): self._became_lost = False def logConnectionRetryEvent(self): now = time.monotonic() if now - self._last_retry_log >= self.retry_log_rate: self.log.warning("Retrying zookeeper connection") self._last_retry_log = now def connect(self, hosts, read_only=False, timeout=10.0): ''' Establish a connection with ZooKeeper cluster. Convenience method if a pre-existing ZooKeeper connection is not supplied to the ZooKeeper object at instantiation time. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). :param bool read_only: If True, establishes a read-only connection. :param float timeout: The ZooKeeper session timeout, in seconds (default: 10.0). ''' if self.client is None: self.client = KazooClient(hosts=hosts, read_only=read_only, timeout=timeout) self.client.add_listener(self._connection_listener) # Manually retry initial connection attempt while True: try: self.client.start(1) break except KazooTimeoutError: self.logConnectionRetryEvent() def disconnect(self): ''' Close the ZooKeeper cluster connection. You should call this method if you used connect() to establish a cluster connection. ''' if self.client is not None and self.client.connected: self.client.stop() self.client.close() self.client = None def resetHosts(self, hosts): ''' Reset the ZooKeeper cluster connection host list. :param str hosts: Comma-separated list of hosts to connect to (e.g. 127.0.0.1:2181,127.0.0.1:2182,[::1]:2183). ''' if self.client is not None: self.client.set_hosts(hosts=hosts) def submitNodeRequest(self, node_request, watcher): ''' Submit a request for nodes to Nodepool. :param NodeRequest node_request: A NodeRequest with the contents of the request. :param callable watcher: A callable object that will be invoked each time the request is updated. It is called with two arguments: (node_request, deleted) where node_request is the same argument passed to this method, and deleted is a boolean which is True if the node no longer exists (notably, this will happen on disconnection from ZooKeeper). The watcher should return False when further updates are no longer necessary. ''' node_request.created_time = time.time() data = node_request.toDict() path = '{}/{:0>3}-'.format(self.REQUEST_ROOT, node_request.priority) path = self.client.create(path, self._dictToStr(data), makepath=True, sequence=True, ephemeral=True) reqid = path.split("/")[-1] node_request.id = reqid def callback(data, stat): if data: self.updateNodeRequest(node_request, data) deleted = (data is None) # data *are* none return watcher(node_request, deleted) self.client.DataWatch(path, callback) def deleteNodeRequest(self, node_request): ''' Delete a request for nodes. :param NodeRequest node_request: A NodeRequest with the contents of the request. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) try: self.client.delete(path) except kze.NoNodeError: pass def nodeRequestExists(self, node_request): ''' See if a NodeRequest exists in ZooKeeper. :param NodeRequest node_request: A NodeRequest to verify. :returns: True if the request exists, False otherwise. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) if self.client.exists(path): return True return False def storeNodeRequest(self, node_request): '''Store the node request. The request is expected to already exist and is updated in its entirety. :param NodeRequest node_request: The request to update. ''' path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) self.client.set(path, self._dictToStr(node_request.toDict())) def updateNodeRequest(self, node_request, data=None): '''Refresh an existing node request. :param NodeRequest node_request: The request to update. :param dict data: The data to use; query ZK if absent. ''' if data is None: path = '%s/%s' % (self.REQUEST_ROOT, node_request.id) data, stat = self.client.get(path) data = self._strToDict(data) request_nodes = list(node_request.nodeset.getNodes()) for i, nodeid in enumerate(data.get('nodes', [])): request_nodes[i].id = nodeid self.updateNode(request_nodes[i]) node_request.updateFromDict(data) def storeNode(self, node): '''Store the node. The node is expected to already exist and is updated in its entirety. :param Node node: The node to update. ''' path = '%s/%s' % (self.NODE_ROOT, node.id) self.client.set(path, self._dictToStr(node.toDict())) def updateNode(self, node): '''Refresh an existing node. :param Node node: The node to update. ''' node_path = '%s/%s' % (self.NODE_ROOT, node.id) node_data, node_stat = self.client.get(node_path) node_data = self._strToDict(node_data) node.updateFromDict(node_data) def lockNode(self, node, blocking=True, timeout=None): ''' Lock a node. This should be called as soon as a request is fulfilled and the lock held for as long as the node is in-use. It can be used by nodepool to detect if Zuul has gone offline and the node should be reclaimed. :param Node node: The node which should be locked. ''' lock_path = '%s/%s/lock' % (self.NODE_ROOT, node.id) try: lock = Lock(self.client, lock_path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException( "Timeout trying to acquire lock %s" % lock_path) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % lock_path) node.lock = lock def unlockNode(self, node): ''' Unlock a node. The node must already have been locked. :param Node node: The node which should be unlocked. ''' if node.lock is None: raise LockException("Node %s does not hold a lock" % (node,)) node.lock.release() node.lock = None def lockNodeRequest(self, request, blocking=True, timeout=None): ''' Lock a node request. This will set the `lock` attribute of the request object when the lock is successfully acquired. :param NodeRequest request: The request to lock. :param bool blocking: Whether or not to block on trying to acquire the lock :param int timeout: When blocking, how long to wait for the lock to get acquired. None, the default, waits forever. :raises: TimeoutException if we failed to acquire the lock when blocking with a timeout. ZKLockException if we are not blocking and could not get the lock, or a lock is already held. ''' path = "%s/%s" % (self.REQUEST_LOCK_ROOT, request.id) try: lock = Lock(self.client, path) have_lock = lock.acquire(blocking, timeout) except kze.LockTimeout: raise LockException( "Timeout trying to acquire lock %s" % path) except kze.NoNodeError: have_lock = False self.log.error("Request not found for locking: %s", request) # If we aren't blocking, it's possible we didn't get the lock # because someone else has it. if not have_lock: raise LockException("Did not get lock on %s" % path) request.lock = lock self.updateNodeRequest(request) def unlockNodeRequest(self, request): ''' Unlock a node request. The request must already have been locked. :param NodeRequest request: The request to unlock. :raises: ZKLockException if the request is not currently locked. ''' if request.lock is None: raise LockException( "Request %s does not hold a lock" % request) request.lock.release() request.lock = None def heldNodeCount(self, autohold_key): ''' Count the number of nodes being held for the given tenant/project/job. :param set autohold_key: A set with the tenant/project/job names. ''' identifier = " ".join(autohold_key) try: nodes = self.client.get_children(self.NODE_ROOT) except kze.NoNodeError: return 0 count = 0 for nodeid in nodes: node_path = '%s/%s' % (self.NODE_ROOT, nodeid) try: node_data, node_stat = self.client.get(node_path) except kze.NoNodeError: # Node got removed on us. Just ignore. continue if not node_data: self.log.warning("Node ID %s has no data", nodeid) continue node_data = self._strToDict(node_data) if (node_data['state'] == zuul.model.STATE_HOLD and node_data.get('hold_job') == identifier): count += 1 return count # Copy of nodepool/zk.py begins here NODE_ROOT = "/nodepool/nodes" LAUNCHER_ROOT = "/nodepool/launchers" def _bytesToDict(self, data): return json.loads(data.decode('utf8')) def _launcherPath(self, launcher): return "%s/%s" % (self.LAUNCHER_ROOT, launcher) def _nodePath(self, node): return "%s/%s" % (self.NODE_ROOT, node) def getRegisteredLaunchers(self): ''' Get a list of all launchers that have registered with ZooKeeper. :returns: A list of Launcher objects, or empty list if none are found. ''' try: launcher_ids = self.client.get_children(self.LAUNCHER_ROOT) except kze.NoNodeError: return [] objs = [] for launcher in launcher_ids: path = self._launcherPath(launcher) try: data, _ = self.client.get(path) except kze.NoNodeError: # launcher disappeared continue objs.append(Launcher.fromDict(self._bytesToDict(data))) return objs def getNodes(self): ''' Get the current list of all nodes. :returns: A list of nodes. ''' try: return self.client.get_children(self.NODE_ROOT) except kze.NoNodeError: return [] def getNode(self, node): ''' Get the data for a specific node. :param str node: The node ID. :returns: The node data, or None if the node was not found. ''' path = self._nodePath(node) try: data, stat = self.client.get(path) except kze.NoNodeError: return None if not data: return None d = self._bytesToDict(data) d['id'] = node return d def nodeIterator(self): ''' Utility generator method for iterating through all nodes. ''' for node_id in self.getNodes(): node = self.getNode(node_id) if node: yield node
class MainWindow(QMainWindow, ui_MainWindow.Ui_MainWindow): mainWriteGui = pyqtSignal(str) @catchExept def __init__(self): super().__init__() self.setupUi(self) self.zk = KazooClient() self.zkTimer = QTimer(self) self.zkTimer.setInterval(100) self.zkTimer.timeout.connect(self.zkTimeout) self.zkStartThread = threading.Thread(target=self.zkConnect) self.msgBox = QMessageBox(QMessageBox.NoIcon, "Connection", "Connecting...", QMessageBox.Cancel, self) self.treeWidget.itemClicked.connect(self.itemClicked) self.treeWidget.itemDoubleClicked.connect(self.itemOpen) self.tabWidget.tabCloseRequested.connect(self.closeTab) self.actionConnect.triggered.connect(self.msgBox.show) self.actionConnect.triggered.connect(self.zkStartThread.start) self.actionConnect.triggered.connect(self.zkTimer.start) self.actionDisconnect.triggered.connect(self.zkDisconnect) self.actionACLVersion.triggered.connect(self.aclVersion) self.actionCreated.triggered.connect(self.created) self.actionChildrenCount.triggered.connect(self.childrenCount) self.actionDataLength.triggered.connect(self.dataLength) self.actionLastModified.triggered.connect(self.lastModified) self.actionLastModifiedTransactionId.triggered.connect( self.lastModifiedTransactionId) self.actionOwnerSessionId.triggered.connect(self.ownerSessionId) self.actionVersion.triggered.connect(self.version) self.actionCreationTransactionId.triggered.connect( self.creationTransactionId) self.actionChangeServerAddress.triggered.connect( self.changeServerAddress) self.msgBox.rejected.connect(self.zkTimer.stop) self.msgBox.rejected.connect(self.msgBox.hide) self.msgBox.rejected.connect(self.zkDisconnect) self.mainWriteGui.connect(self.slotMainWriteGui) self.log.setCenterOnScroll(True) self.dialog = SelectorDialog(self) class PlainTextWidgetHandler: def __init__(self, logToWriteGui): self.logToWriteGui = logToWriteGui def write(self, text): self.logToWriteGui(text) def flush(self): pass logging.basicConfig(format='%(asctime)s.%(msecs)d: %(message)s', datefmt='%H:%M:%S', level=logging.DEBUG, handlers=[ logging.StreamHandler( PlainTextWidgetHandler( self.logToWriteGui)), logging.StreamHandler(sys.stderr) ]) self.treeWidget.setColumnCount(1) self.treeWidget.sortByColumn(0, Qt.AscendingOrder) l = self.msgBox.layout() progress = QProgressBar() progress.setMaximum(0) progress.setMinimum(0) l.addWidget(progress, l.rowCount() - 2, 1, 1, l.columnCount()) self.actionConnect.setEnabled(False) if os.path.exists("config.txt"): with open("config.txt", "r") as f: prelines = [string.strip() for string in f.readlines()] lines = [prelines[0]] for i in range(1, len(prelines)): if prelines[i - 1] != prelines[i] and prelines[i] not in lines: lines.append(prelines[i]) lines = list(filter(None, lines)) self.dialog.comboBox.addItems(lines) self.actionConnect.setEnabled(True) @pyqtSlot(str) def slotMainWriteGui(self, text): self.log.ensureCursorVisible() self.log.textCursor().insertText(text) def logToWriteGui(self, text): self.mainWriteGui.emit(text) @catchExept def getCurrentStat(self): _, stat = self.zk.get(self.treeWidget.currentItem().text(1)) return stat @catchExept @pyqtSlot() def aclVersion(self): self.print("ACL version: %s" % self.getCurrentStat().acl_version) @catchExept @pyqtSlot() def created(self): self.print("Created: %s" % self.getCurrentStat().created) @catchExept @pyqtSlot() def childrenCount(self): self.print("Children count: %s" % self.getCurrentStat().children_count) @catchExept @pyqtSlot() def dataLength(self): self.print("Data length: %s" % self.getCurrentStat().data_length) @catchExept @pyqtSlot() def lastModified(self): self.print("Last modified: %s" % self.getCurrentStat().last_modified) @catchExept @pyqtSlot() def lastModifiedTransactionId(self): self.print("Last modified transactionId: %s" % self.getCurrentStat().last_modified_transaction_id) @catchExept @pyqtSlot() def ownerSessionId(self): self.print("Owner sessionId: %s" % self.getCurrentStat().owner_session_id) @catchExept @pyqtSlot() def version(self): self.print("Version: %s" % self.getCurrentStat().version) @catchExept @pyqtSlot() def creationTransactionId(self): self.print("Creation transactionId: %s" % self.getCurrentStat().creation_transaction_id) @catchExept @pyqtSlot() def changeServerAddress(self): code = self.dialog.exec_() if code == QDialog.Accepted: text = self.currentHost() with open("config.txt", "w") as f: hosts = [ self.dialog.comboBox.itemText(s) for s in range(self.dialog.comboBox.count()) if text != self.dialog.comboBox.itemText(s) ] self.dialog.comboBox.clear() self.dialog.comboBox.addItems(hosts) hosts.insert(0, text) f.write('\n'.join(hosts)) if text != "": if text != self.dialog.comboBox.itemText(0): self.dialog.comboBox.insertItem(0, text) self.dialog.comboBox.setCurrentText(text) self.print("Current host changed to %s" % self.currentHost()) self.actionConnect.setEnabled(True) @catchExept @pyqtSlot() def zkDisconnect(self): self.tabWidget.clear() self.treeWidget.clear() self.zk.stop() self.zk.close() self.actionDisconnect.setEnabled(False) self.menuFileInfo.setEnabled(False) self.actionConnect.setEnabled(True) self.actionChangeServerAddress.setEnabled(True) self.zkStartThread = threading.Thread(target=self.zkConnect) self.actionConnect.triggered.connect(self.zkStartThread.start) @catchExept @pyqtSlot() def zkTimeout(self): if self.zk.connected: self.zkConnected() self.zkTimer.stop() @catchExept def zkConnected(self): self.msgBox.hide() self.init() self.menuFileInfo.setEnabled(True) self.actionDisconnect.setEnabled(True) self.actionConnect.setEnabled(False) self.actionChangeServerAddress.setEnabled(False) @catchExept def zkConnect(self): self.zk.set_hosts(self.currentHost()) self.zk.add_listener(self.my_listener) try: self.zk.start_async() except Exception as e: logging.exception("error: {0}".format(e)) def currentHost(self): return self.dialog.comboBox.currentText() @catchExept def init(self): for child in self.zk.get_children("/"): self.treeWidget.addTopLevelItem( QTreeWidgetItem([child, "/" + child, child])) @catchExept def my_listener(self, state): if state == KazooState.LOST: # Register somewhere that the session was lost self.print("state is LOST!") elif state == KazooState.SUSPENDED: # Handle being disconnected from Zookeeper self.print("state is SUSPENDED!") else: # Handle being connected/reconnected to Zookeeper self.print("state is CONNECTED!") @catchExept def print(self, text): logging.debug(text) @catchExept def printAllChildren(self, curPath, children, layer): spaces = " " * layer for child in children: newPath = curPath + "/" + child data, stat = self.zk.get(newPath) self.print("%s: %s" % (spaces + child, data)) self.printAllChildren(newPath, self.zk.get_children(newPath), layer + 1) @catchExept @pyqtSlot(int) def closeTab(self, idx): self.tabWidget.removeTab(idx) @catchExept @pyqtSlot(QTreeWidgetItem, int) def itemOpen(self, item, column): if not self.zk.exists(item.text(1)): return tabName = item.text(2) for i in range(self.tabWidget.count()): if tabName == self.tabWidget.tabText(i): self.tabWidget.setCurrentIndex(i) return innerText = QPlainTextEdit() innerText.setReadOnly(True) data, stat = self.zk.get(item.text(1)) innerText.setPlainText(data.decode("utf8")) pos = self.tabWidget.addTab(innerText, tabName) self.tabWidget.setCurrentIndex(pos) @catchExept def drawAllTree(self): if self.zk.exists("/"): root = self.zk.get_children("/") self.printAllChildren("/", root, 0) else: self.print("Really?.. How?.. Why?..") @catchExept @pyqtSlot(QTreeWidgetItem, int) def itemClicked(self, item, column): item.setText( 0, item.text(2) + " (%s)" % self.getCurrentStat().children_count) children = item.takeChildren() newChildren = [] if self.zk.exists(item.text(1)): for child in self.zk.get_children(item.text(1)): for oldChild in children: if oldChild.text(2) == child: newChildren.append(oldChild) break else: newChildren.append( QTreeWidgetItem( [child, item.text(1) + "/" + child, child])) item.addChildren(newChildren)