脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|shell|

服务器之家 - 脚本之家 - Python - Python实现Harbor私有镜像仓库垃圾自动化清理详情

Python实现Harbor私有镜像仓库垃圾自动化清理详情

2023-02-16 11:50键客李大白 Python

这篇文章主要介绍了Python实现Harbor私有镜像仓库垃圾自动化清理详情,文章围绕主题分享相关详细代码,需要的小伙伴可以参考一下

一、编写Python脚本

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
[root@lidabai ~]# vim harbor_clearimage.py
# -*- coding:utf-8 -*-
import requests
from requests.auth import HTTPBasicAuth
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry
import os
import time
import logging
from logging.handlers import RotatingFileHandler
 
class Harbor(object):
def __init__(self, api_url, api_user, api_passwd, tag_num, proj_exclude):
self.api_url = api_url
self.api_user = api_user
self.api_passwd = api_passwd
self.api_auth = HTTPBasicAuth(self.api_user, self.api_passwd)
self.tag_num = int(tag_num)
self.proj_exclude = proj_exclude
self.proj_url = self.api_url + "/projects"
self.repos_url = self.api_url + "/repositories"
self.header_dict = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36',
'Content-Type': 'application/x-www-form-urlencoded'
}
self.deldata = []
self.session = requests.Session()
self.session.auth = self.api_auth
retry = Retry(connect=3, backoff_factor=1)
adapter = HTTPAdapter(max_retries=retry)
self.session.mount('http://', adapter)
self.session.keep_alive = False
 
def soft_del_repos(self):
try:
projresp = self.session.get(self.proj_url, headers=self.header_dict)
if projresp.status_code == 200:
projdata = projresp.json()
for proj in projdata:
if proj['name'] not in self.proj_exclude # and proj['name'] == "gxjxhwebtest-28003" :
try:
reporesp = self.session.get(self.repos_url, params={"project_id": proj['project_id']} , headers=self.header_dict)
if reporesp.status_code == 200:
repodata = reporesp.json()
for repo in repodata:
if repo["tags_count"] > self.tag_num:
tag_url = self.repos_url + "/" + repo['name'] + "/tags"
tags = self.session.get(tag_url).json()
tagdata = sorted(tags, key=lambda a: a["created"])
del_tags = tagdata[0:len(tagdata) - self.tag_num]
for tag in del_tags:
del_repo_tag_url = tag_url + "/" + tag['name']
cmd = 'curl -v -X DELETE -u "' + self.api_user + ":" + self.api_passwd + '" -H "accept: application/json" ' + del_repo_tag_url
try:
#del_resp = self.session.delete(del_repo_tag_url,headers=self.header_dict)
ok = os.system(cmd)
if ok == 0 :
logging.info("httpdel:" + del_repo_tag_url )
_deldata = {"project_id":proj['project_id'],"project_name":proj['name'],"repo_name":repo['name'],"tag_name":tag['name']}
self.deldata.append(_deldata)
logging.info("httpdel project_id=" + str(proj['project_id']) + ",project_name=" + proj['name'] + ",repo_name=" + repo['name'] + ",tag_name=" + tag['name'])
else:
logging.error("exec_cmd fail:" + cmd )
except:
logging.error("exec_cmd fail:" + cmd )
except:
logging.error("httpget fail:" + self.repos_url)
else:
logging.error("httpget fail:" + self.proj_url )
except:
logging.error("apilogin fail:" + self.api_url )
return self.deldata
 
def hard_del_repo(self):
pwd_cmd = "cd /dcos/app/harbor/ " #进入到Harbor安装目录
stop_cmd = "docker-compose stop" #停止Harbor服务
del_cmd = "docker run -it --name gc --rm --volumes-from registry goharbor/registry-photon:v2.7.1-patch-2819-v1.8.6 garbage-collect /etc/registryctl/config.yml"
start_cmd = "docker-compose start" #启动Harbor服务
os.system(pwd_cmd)
ok1 = os.system(stop_cmd)
if ok1 == 0 :
time.sleep(10)
ok2 = os.system(del_cmd)
ok3 = os.system(start_cmd)
if ok3 == 0 :
logging.info("hard_del_repo ok:")
else:
logging.error("hard_del_repo fail:")
 
if __name__ == "__main__":
Rthandler = RotatingFileHandler('harbor_repo_clear.log', maxBytes=10*1024*1024,backupCount=5)
logging.basicConfig(level=logging.INFO)
formatter = logging.Formatter('%(levelname)s %(asctime)s %(process)d %(thread)d %(pathname)s %(filename)s %(funcName)s[line:%(lineno)d] %(message)s')
Rthandler.setFormatter(formatter)
logging.getLogger('').addHandler(Rthandler)
 
api_url = "http://192.168,2,66:443/api" #Harbor服务的API URL
api_user = "admin" #超级管理员
api_passwd = "Harbor12345" #超级管理员的用户密码
tag_num = 20 #保留的tag数量
proj_exclude = ["library"]
harborClient = Harbor(api_url,api_user,api_passwd,tag_num,proj_exclude)
data = harborClient.soft_del_repos()
if len(data) > 0 :
#harborClient.hard_del_repos()
logging.info("hard_del_repo:")

二、执行Python脚本

?
1
[root@lidabai ~]# python harbor_clearimage.py

到此这篇关于Python实现Harbor私有镜像仓库垃圾自动化清理详情的文章就介绍到这了,更多相关 Harbor垃圾清理内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.51cto.com/lidabai/5320660

延伸 · 阅读

精彩推荐
  • Pythonpython中Switch/Case实现的示例代码

    python中Switch/Case实现的示例代码

    本篇文章主要介绍了python中Switch/Case实现的示例代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    gerrydeng9322020-12-16
  • Python学会用Python实现滑雪小游戏,再也不用去北海道啦

    学会用Python实现滑雪小游戏,再也不用去北海道啦

    Python除了极少的事情不能做之外,其他基本上可以说全能.,图形处理、文本处理、数据库编程、网络编程、web编程、黑客编程、爬虫编写、机器学习、人工智...

    程序猿中的BUG8462021-11-08
  • PythonPython异步爬虫实现原理与知识总结

    Python异步爬虫实现原理与知识总结

    之前有很多小伙伴想看Python异步爬虫的有关知识总结,这次它来了,文中有非常详细的代码示例与注释,即使对刚开始学python的小伙伴也很友好,,需要的朋友可...

    amcomputer6502021-10-29
  • Pythontensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用

    tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用

    今天小编就为大家分享一篇tensorflow入门:tfrecord 和tf.data.TFRecordDataset的使用,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧 ...

    yeqiustu5032020-04-09
  • Pythonpython爬虫之异常捕获及标签过滤详解

    python爬虫之异常捕获及标签过滤详解

    今天带大家了解python异常捕获及标签过滤,文中有非常详细的代码示例,对正在学习python爬虫的小伙伴们很有帮助,需要的朋友可以参考下...

    一名小测试7482021-11-03
  • PythonPython连接PostgreSQL数据库的方法

    Python连接PostgreSQL数据库的方法

    大家应该都有所了解,python可以操作多种数据库,诸如SQLite、MySql、PostgreSQL等,这里不对所有的数据库操作方法进行赘述,只针对目前项目中用到的Postgr...

    标点符9092020-09-13
  • Pythonpython入门课程第一讲之安装与优缺点介绍

    python入门课程第一讲之安装与优缺点介绍

    这篇文章主要介绍了python入门课程第一讲之安装与优缺点,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参...

    码农飞哥7052021-12-31
  • Pythonpython安装numpy scipy的教程

    python安装numpy scipy的教程

    下面小编就为大家带来一篇python安装numpy&安装matplotlib& scipy的教程。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    ucsb4282020-12-15