运维咖啡吧

享受技术带来的乐趣,体验生活给予的感动

清理Harbor服务器磁盘空间

执行docker push时报错received unexpected HTTP status: 500 Internal Server Error

原因是Harbor服务器磁盘空间满了,清理Harbor磁盘空间需要以下四个步骤

清理Harbor磁盘空间

  1. 删除镜像,可以通过web管理删除,也可以通过API删除,API删除脚本如下
import requests
import json
import ssl

ssl._create_default_https_context = ssl._create_unverified_context
requests.packages.urllib3.disable_warnings()


class RequestClient(object):

    def __init__(self, login_url, username, password):
        self.username = username
        self.password = password
        self.login_url = login_url
        self.session = requests.Session()
        self.login()

    def login(self):
        self.session.post(self.login_url, params={"principal": self.username, "password": self.password}, verify=False)


class ClearHarbor(object):

    def __init__(self, domain, password, username="admin"):
        self.api_url = domain + "/api"
        self.client = RequestClient(domain + "/login", username, password)

    def fetch_pros_id(self):
        pro_res = self.client.session.get(self.api_url + "/projects", verify=False).json()
        pros_id = [i['project_id'] for i in pro_res]

        return pros_id

    def fetch_del_repos_name(self, pro_id, num=15):
        repos_res = self.client.session.get(self.api_url + "/repositories", params={"project_id": pro_id}, verify=False)
        del_repos_name = [repo['name'] for repo in repos_res.json() if repo["tags_count"] > num]

        return del_repos_name

    def fetch_del_repos(self, repo_name, num=15):
        tag_url = self.api_url + "/repositories/" + repo_name + "/tags"
        tags = self.client.session.get(tag_url, verify=False).json()
        tags_sort = sorted(tags, key=lambda a: a["created"])

        for tag in tags_sort[0:len(tags_sort) - num]:
            del_repo_tag_url = tag_url + "/" + tag['name']
            r = self.client.session.delete(del_repo_tag_url, verify=False)

            if r.status_code == 200:
                print('已删除镜像:' + del_repo_tag_url)

        return True


if __name__ == "__main__":

    domain = "https://harbor.ops-coffee.cn"
    password = "ops-coffee.cn"
    res = ClearHarbor(domain, password)
    for i in res.fetch_pros_id():
        repos = res.fetch_del_repos_name(i)
        if repos:
            for repo in repos:
                del_repos = res.fetch_del_repos(repo)

虽然删除了镜像但并不能释放磁盘空间,还需要如果进行垃圾回收操作才能释放存储空间清理,垃圾回收操作过程如下

  1. 关闭Harbor服务
cd /home/opt/tools/harbor && docker-compose stop
  1. 运行GC回收容器释放磁盘空间
docker run -it --name gc --rm --volumes-from registry vmware/registry:2.6.2-photon garbage-collect  /etc/registry/config.yml

运行以上命令会直接清除已删除的镜像,若想要先查看要清理的镜像,可以加上--dry-run参数

docker run -it --name gc --rm --volumes-from registry vmware/registry-photon:v2.6.2-v1.5.0 garbage-collect --dry-run /etc/registry/config.yml
  1. 启动Harbor服务
docker-compose up -d

找回Harbor管理员账号密码

忘记Harbor管理员密码,可以在harbor.cfg初始化文件中找回

# vi harbor.cfg
harbor_admin_password = ops-coffee.cn