#! /usr/bin/env python3
# -*- coding:utf-8 -*-
# 基于时间排序后删除 保留最新n个tag
import requests
requests.packages.urllib3.disable_warnings()
class CleanHarbor:
# haror地址 用户 密码 保留tag数量
def __init__(self, base_url, user, password,counts):
self.user = user
self.password = password
self.base_url = base_url
self.counts = counts
#harbor 1.8的登录url加了个c
self.login_url = self.base_url + '/c/login'
self.project_url = self.base_url + '/api/projects'
self.repo_url = self.base_url + '/api/repositories'
self.gc_url = self.base_url + '/api/system/gc/schedule'
self.session = requests.Session()
self.session.verify = False
self.session.post(self.login_url, params={"principal": self.user, "password": self.password})
def get_project(self):
project_info = []
harbor_info = self.session.get(self.project_url).json()
for project in harbor_info:
info = {}
info['project_id'] = project['project_id']
info['project_name'] = project['name']
project_info.append(info)
return project_info
def get_delete_repo(self):
project_info = self.get_project()
delete_reponame = []
for project_id in project_info:
repo_info = self.session.get(self.repo_url, params={"project_id": project_id['project_id']}).json()
for repo in repo_info:
#如果该repo的tag数量不大于期望值则略过
if repo['tags_count'] > self.counts:
delete_reponame.append(repo['name'])
return delete_reponame
def delete_repo_tag(self):
delete_reponame = self.get_delete_repo()
for repo_name in delete_reponame:
tag_url = self.repo_url + "/" + repo_name + "/tags"
tags = self.session.get(tag_url).json()
tags_sort = sorted(tags, key=lambda tags: tags["created"])
del_tags = tags_sort[0:len(tags_sort) - self.counts]
for tag in del_tags:
#print(tag)
del_repo_tag_url = tag_url + "/" + tag['name']
print(del_repo_tag_url)
result = self.session.delete(del_repo_tag_url)
if result.status_code == 200:
print('{}:{} tag删除成功..'.format(repo_name, tag['name']))
print("所有tag删除完成...")
self.gc()
def gc(self):
result = self.session.post(self.gc_url, params={"schedule":{"type":"Manual"}})
if result.status_code == 201:
print("gc成功")
if __name__ == "__main__":
Harobr = CleanHarbor('https://hub.my.com','admin', 'Harbor12345',5)
Harobr.delete_repo_tag()