思路

  • 主要思路就是先拿到数据,通过执行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()