cull_idle_servers.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:zero-to-jupyterhub-k8s 作者: jupyterhub 项目源码 文件源码
def cull_idle(url, api_token, timeout, cull_users=False):
    """Shutdown idle single-user servers

    If cull_users, inactive *users* will be deleted as well.
    """
    auth_header = {
            'Authorization': 'token %s' % api_token
        }
    req = HTTPRequest(url=url + '/users',
        headers=auth_header,
    )
    now = datetime.datetime.utcnow()
    cull_limit = now - datetime.timedelta(seconds=timeout)
    client = AsyncHTTPClient()
    resp = yield client.fetch(req)
    users = json.loads(resp.body.decode('utf8', 'replace'))
    futures = []

    @coroutine
    def cull_one(user, last_activity):
        """cull one user"""

        # shutdown server first. Hub doesn't allow deleting users with running servers.
        if user['server']:
            app_log.info("Culling server for %s (inactive since %s)", user['name'], last_activity)
            req = HTTPRequest(url=url + '/users/%s/server' % user['name'],
                method='DELETE',
                headers=auth_header,
            )
            yield client.fetch(req)
        if cull_users:
            app_log.info("Culling user %s (inactive since %s)", user['name'], last_activity)
            req = HTTPRequest(url=url + '/users/%s' % user['name'],
                method='DELETE',
                headers=auth_header,
            )
            yield client.fetch(req)

    for user in users:
        if not user['server'] and not cull_users:
            # server not running and not culling users, nothing to do
            continue
        last_activity = parse_date(user['last_activity'])
        if last_activity < cull_limit:
            futures.append((user['name'], cull_one(user, last_activity)))
        else:
            app_log.debug("Not culling %s (active since %s)", user['name'], last_activity)

    for (name, f) in futures:
        yield f
        app_log.debug("Finished culling %s", name)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号