1. 程式人生 > >python docker registry 歷史映象批量刪除

python docker registry 歷史映象批量刪除

思路

  • 主要思路就是先拿到資料,通過執行docker images 寫入到一個檔案中
  • 從檔案中拿出資料,進行排序【這部分需要根據自己的需求來自定義編寫,可以留言交流】
  • 刪除需要刪除的映象。

指令碼內容

#coding:utf-8

def get_date_time(date_list,date_range,version_date_range):
    '''
    獲取列表中最大的時間
    date_list: 時間列表,[20181109-11,20181110-1,20181110-2,20181111-4,20181111-5]
    date_range: 每個專案保留的天數,如上保留兩天,[20181109-11,20181110-1,20181110-2]
    version_date_range: 每個專案保留的天數,其中每天保留幾個版本,如上保留兩天每天保留一個版本:[20181109-11,20181110-1]
    '''
    new_num_dict = {}
    for i in date_list:
        try:
            date_time = int(i.split('-')[0])
            version_num = int(i.split('-')[1])
            if date_time not in new_num_dict.keys():
                new_num_dict[date_time] = [version_num]
            else:
                new_num_dict[date_time].append(version_num)
        except Exception:
            pass

    new_date_time_list = []
    for i in new_num_dict.keys():
        new_date_time_list.append(i)
    new_date_time_list=sorted(new_date_time_list,reverse=True)

    if len(new_date_time_list) > date_range:
        keep_date_time_list = new_date_time_list[0:date_range]
        delete_date_time_list = new_date_time_list[-(len(new_date_time_list)-date_range):]

    else:
        keep_date_time_list = new_date_time_list
        delete_date_time_list = []

    #print "天數保留的結果: %s" % keep_date_time_list
    #print "天數刪除的結果: %s" % delete_date_time_list

    keep_version_num_list = []
    delete_version_num_list = []

    result = {}
    for i in keep_date_time_list:
        # 降序
        sort_version_num_list = sorted(new_num_dict[i],reverse=True)
        print (i,sort_version_num_list)
        if len(sort_version_num_list) > version_date_range:
            for n in range(version_date_range):
                keep_version_num_list.append("{}-{}".format(i,sort_version_num_list[n]))
            for n in range(1,(len(sort_version_num_list)-version_date_range)):
                delete_version_num_list.append("{}-{}".format(i, sort_version_num_list[-n]))

        else:
            for n in range(len(sort_version_num_list)):
                keep_version_num_list.append("{}-{}".format(i,sort_version_num_list[n]))
    for i in delete_date_time_list:
        sort_version_num_list = sorted(new_num_dict[i], reverse=True)
        for n in sort_version_num_list:
            delete_version_num_list.append("{}-{}".format(i,n))
    result['keep'] = keep_version_num_list
    result['delete'] = delete_version_num_list

    #print '保留:',keep_version_num_list
    #print '刪除:',delete_version_num_list
    return result

def get_docker_images_info(filename,date_range,version_date_range):
'''
filename: 通過在registry伺服器上執行會生成一個文字檔案
date_range: 每個專案保留的天數,如上保留兩天,[20181109-11,20181110-1,20181110-2]
 version_date_range: 每個專案保留的天數,其中每天保留幾個版本,如上保留兩天每天保留一個版本:[20181109-11,20181110-1]
'''
    readlines_list=[]
    with open(filename,'rb+') as f:
            data = f.readlines()
            for line in data:
                if line:
                    readlines_list.append(line)
    f.close()
    readlines_dict={}
    for i in readlines_list:
        readline_list = i.split()
     #print (readline_list)
        if readline_list[0] not in readlines_dict.keys():
            readlines_dict[readline_list[0]] = [readline_list[1]]
        else:
            readlines_dict[readline_list[0]].append(readline_list[1])

    result = {}
    for k,v in readlines_dict.items():
        # print "%s------------%s" % (k,v)
        delete_date_list = get_date_time(v,date_range,version_date_range)
        result[k] = delete_date_list
    return result

if __name__ == "__main__":
    import os
    import datetime
    home_path = '.'
        #生成的檔案
    os.system("docker images > 1.txt")
    ret=get_docker_images_info("1.txt",5,2)
        #生成一個日誌記錄
    with open("%s/logs/delete.%s.log" % (home_path,datetime.datetime.now().strftime('%Y-%m-%d')),'w+') as f:
        for k,v in ret.items():
            if len(v['delete']) > 0:
                f.write("[%s] [%s] docker delete images:%s\n" % ((datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')),k,v['delete']))
                for i in v['delete']:
                    delete_docker_image_tag = ("{}:{}".format(k,i))
                    print ('刪除: %s' % delete_docker_image_tag)
                    os.system("docker rmi %s " % delete_docker_image_tag)
            if len(v['keep']) > 0:
                f.write('[%s] [%s] docker keep images: %s\n' % ((datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')), k, v['keep']))
                for i in v['keep']:
                    keep_docker_image_tag = ("{}:{}".format(k,i))
                    print ('保留: %s ' % keep_docker_image_tag)
        f.close()