#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'hhh' '''本脚本适用于清理释放harbor镜像仓库空间; 此脚本基于harbor 1.9.0版本编写; harbor 1.7.0 以后版本可通过页面垃圾回收; 如不同版本api不同需自行更改各个函数中url部分。''' import json import heapq import requests from requests.auth import HTTPBasicAuth from requests.adapters import HTTPAdapter from requests.packages.urllib3.util.retry import Retry from tqdm import tqdm from time import sleep, time import traceback class Harbor(object): def __init__(self, api_url, user, num, exclude): """ 初始化一些基本参数 :param auth: login password authority management :param head: change user-agent :param url: harbor server api url :param project_exclude: Exclude project team :param num_limit: Limit the number of retained versions :param project_special: project dict id and repo total :param project_state: project dict name and id :param repo_state: repo dict name and tag total :param repo_dispose: Count the number of tag processing :param tag_state: tag dict repo_name and tag """ self.auth = user self.head = {"user_agent": "Mozilla/5.0"} self.url = api_url self.project_exclude = exclude self.num_limit = int(num) self.project_special = {} self.project_state = {} self.repo_state = {} self.repo_dispose_count = 0 self.tag_state = {} def setting(self): self.session = requests.Session() self.session.auth = self.auth retry = Retry(connect=3, backoff_factor=1) adapter = HTTPAdapter(max_retries=retry) self.session.mount('https://', adapter) self.session.keep_alive = False def list_project(self): try: r_project = self.session.get("{}/projects".format(self.url), headers=self.head) r_project.raise_for_status() # 将得到的文本转换格式 project_data = json.loads(r_project.text) for i in project_data: # 项目组名称 project_name = i.get('name') # 项目组id project_id = i.get('project_id') # 项目组仓库 project_repo = i.get('repo_count') # 利用一个字典将项目名称与id对应起来 self.project_state[project_name] = project_id # 由于请求限制,另外用一个字典,对应id于repo总数 self.project_special[project_id] = project_repo print("