forked from imain/container-check
-
Notifications
You must be signed in to change notification settings - Fork 0
/
container-check.py
executable file
·216 lines (172 loc) · 7.14 KB
/
container-check.py
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import argparse
import subprocess
import logging
import multiprocessing
import os
import sys
import yum
import yaml
log = logging.getLogger()
log.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
ch.setFormatter(formatter)
log.addHandler(ch)
def parse_opts(argv):
parser = argparse.ArgumentParser("Tool to let you know what packages need"
"updating in a list of containers")
parser.add_argument('-c', '--containers',
help="""YAML File containing a list of containers to inspect.""",
default='docker-centos-rdo.yaml')
parser.add_argument('-p', '--process-count',
help="""Number of processes to use in the pool when running docker containers.""",
default=multiprocessing.cpu_count())
parser.add_argument('-u', '--update',
action='store_true',
help="""Run yum update in any containers that need updating.""",
default=False)
opts = parser.parse_args(argv[1:])
return opts
def rm_container(name):
log.info('Removing container: %s' % name)
subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmd_stdout, cmd_stderr = subproc.communicate()
if cmd_stdout:
log.debug(cmd_stdout)
if cmd_stderr and \
cmd_stderr != 'Error response from daemon: ' \
'No such container: {}\n'.format(name):
log.debug(cmd_stderr)
def populate_container_rpms_list((container)):
dcmd = ['/usr/bin/docker', 'run',
'--user', 'root',
'--rm',
container]
dcmd.extend(['rpm', '-qa'])
log.info('Running docker command: %s' % ' '.join(dcmd))
subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmd_stdout, cmd_stderr = subproc.communicate()
if subproc.returncode != 0:
log.error('Failed running rpm -qa for %s' % container)
log.error(cmd_stderr)
rpms = cmd_stdout.split("\n")
return (subproc.returncode, container, rpms)
def yum_update_container((container, name)):
container_name = 'yum-update-%s' % name
rm_container(container_name)
dcmd = ['/usr/bin/docker', 'run',
'--user', 'root',
'--net', 'host',
'--volume', '/etc/yum.repos.d:/etc/yum.repos.d',
'--volume', '/patched_rpms:/patched_rpms',
'--name', container_name,
container]
dcmd.extend(['yum', '-y', 'update'])
log.info('Running docker command: %s' % ' '.join(dcmd))
subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmd_stdout, cmd_stderr = subproc.communicate()
if subproc.returncode != 0:
log.error('Failed running yum update for %s' % container)
log.error(cmd_stderr)
rm_container(container_name)
return (subproc.returncode, container)
dcmd = ['/usr/bin/docker', 'commit',
'-m', 'automatic yum update',
container_name,
container]
log.info('Running docker command: %s' % ' '.join(dcmd))
subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
cmd_stdout, cmd_stderr = subproc.communicate()
if subproc.returncode != 0:
log.error('Failed running docker commit in %s' % container)
log.error(cmd_stderr)
rm_container(container_name)
return (subproc.returncode, container)
def get_available_rpms():
available_rpms = {}
yb = yum.YumBase()
yb.setCacheDir()
pkglist = yb.doPackageLists(pkgnarrow='all')
for pkg in pkglist.available:
# This gives us a string the same as rpm -qa
available_rpms[pkg.name + '-' + pkg.vra] = 1
return available_rpms
def get_container_list(container_file):
with open(container_file) as cf:
data = yaml.safe_load(cf.read()).get('parameter_defaults')
if not data:
return None
container_list = []
for key in data:
container_list.append(data[key])
log.debug(container_list)
return container_list
if __name__ == '__main__':
opts = parse_opts(sys.argv)
# Get a list of all the docker containers we need to inspect.
docker_containers = get_container_list(opts.containers)
# Load up available rpms as a hash containing the latest versions of rpms.
available_rpms = get_available_rpms()
# Holds all the information for each process to consume.
# Instead of starting them all linearly we run them using a process
# pool.
process_map = []
for container in docker_containers:
process_map.append(container)
# This is what we're after here, a hash keyed by containers, each entry
# containing a list of rpms in that container.
container_rpms = {}
success = True
# Fire off processes to perform each rpm list.
p = multiprocessing.Pool(int(opts.process_count))
ret = list(p.map(populate_container_rpms_list, process_map))
for returncode, container, rpms in ret:
container_rpms[container] = rpms
if returncode != 0:
log.error('ERROR running rpm query in container: %s' % container)
success = False
if not success:
sys.exit(1)
container_update_list = {}
for container in container_rpms:
for rpm in container_rpms[container]:
if len(rpm) > 0 and not rpm in available_rpms:
if container not in container_update_list:
container_update_list[container] = []
container_update_list[container].append(rpm)
for container in container_update_list:
log.info("Container needs updating: %s" % container)
for rpm in container_update_list[container]:
log.info(" rpm: %s" % rpm)
# And finally update the containers if required
if opts.update:
process_map = []
name = 0
for container in container_update_list:
process_map.append([container, str(name)])
name += 1
ret = list(p.map(yum_update_container, process_map))
for returncode, container in ret:
if returncode != 0:
log.error('ERROR running yum update in container %s' % container)
success = False
if not success:
sys.exit(1)