-
Notifications
You must be signed in to change notification settings - Fork 0
/
docker_cleaner
executable file
·87 lines (69 loc) · 2.08 KB
/
docker_cleaner
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
#!/usr/bin/env python3
import subprocess as sb
f = open('docker_cleaner.log', 'w')
f.write('Beginning state: \n')
res = []
def log(data):
f.write(data)
def subprocess_run(command):
rs = sb.Popen(command, shell=True, stdout=sb.PIPE, stderr=sb.PIPE).communicate()
if rs[1].decode('utf-8'):
return rs[1].decode('utf-8')
return rs[0].decode('utf-8')
def check_container_status(containter_id): # If container is UP
rs = subprocess_run('docker ps').split('\n')[1::]
for containter in rs:
print(containter.split(' ')[0])
if containter != '' and containter.split(' ')[0] == containter_id:
return True
return False
def remove_data(img_id):
rs = subprocess_run(f'docker rmi {img_id}')
if 'Deleted' not in rs:
containter = rs.split(' ')[-1][:-1:]
print(f'Image {img_id} is connected with {containter}.', end=' ')
if check_container_status(containter):
print(f'{containter} is working, image wont be deleted.')
else:
print(f'Deleting {containter} due to inactivity.')
res.append('Deleted connected containter: ' + subprocess_run(f'docker rm {containter}'))
remove_data(img_id)
else:
res.append(rs)
def docker_img_check(repo, tag, img_id):
if repo == '<none>' and tag == '<none>':
remove_data(img_id)
return 1
return 0
def volumes_cleaning():
cntr = 0
volumes = subprocess_run('docker volume ls -f dangling=true').split('\n')[1::]
for volume_line in volumes:
if volume_line:
vol = volume_line.split(' ')[-1]
rs = subprocess_run(f'docker volume rm {vol}')
res.append(f'Removed volume: {vol}')
cntr += 1
return cntr
images = subprocess_run('docker images')
counter = 0
log(images)
for image in images.split('\n')[1::]:
if len(image) > 1:
data = list(filter(('').__ne__, image.split(' ')))
if len(data) > 0:
counter += docker_img_check(data[0], data[1], data[2])
if counter:
print(f'successfully cleaned {counter} images')
log('\n')
else:
print('no images to clean')
vol_res = volumes_cleaning()
if vol_res:
print(f'cleaned {vol_res} volume(s)')
for i in res:
log(i)
images = subprocess_run('docker images')
log('\nFinal state: \n')
log(images)
f.close()