3 # Licensed under the Apache License, Version 2.0 (the "License"); you may
4 # not use this file except in compliance with the License. You may obtain
5 # a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 # License for the specific language governing permissions and limitations
15 # Shell script tool to run puppet inside of the given docker container image.
16 # Uses the config file at /var/lib/docker-puppet/docker-puppet.json as a source for a JSON
17 # array of [config_volume, puppet_tags, manifest, config_image, [volumes]] settings
18 # that can be used to generate config files or run ad-hoc puppet modules
19 # inside of a container.
27 import multiprocessing
29 log = logging.getLogger()
30 log.setLevel(logging.DEBUG)
31 ch = logging.StreamHandler(sys.stdout)
32 ch.setLevel(logging.DEBUG)
33 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
34 ch.setFormatter(formatter)
37 # this is to match what we do in deployed-server
39 subproc = subprocess.Popen(['hostname', '-s'],
40 stdout=subprocess.PIPE,
41 stderr=subprocess.PIPE)
42 cmd_stdout, cmd_stderr = subproc.communicate()
43 return cmd_stdout.rstrip()
47 log.info('Pulling image: %s' % name)
48 subproc = subprocess.Popen(['/usr/bin/docker', 'pull', name],
49 stdout=subprocess.PIPE,
50 stderr=subprocess.PIPE)
51 cmd_stdout, cmd_stderr = subproc.communicate()
58 def rm_container(name):
59 if os.environ.get('SHOW_DIFF', None):
60 log.info('Diffing container: %s' % name)
61 subproc = subprocess.Popen(['/usr/bin/docker', 'diff', name],
62 stdout=subprocess.PIPE,
63 stderr=subprocess.PIPE)
64 cmd_stdout, cmd_stderr = subproc.communicate()
70 log.info('Removing container: %s' % name)
71 subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
72 stdout=subprocess.PIPE,
73 stderr=subprocess.PIPE)
74 cmd_stdout, cmd_stderr = subproc.communicate()
78 cmd_stderr != 'Error response from daemon: ' \
79 'No such container: {}\n'.format(name):
82 process_count = int(os.environ.get('PROCESS_COUNT',
83 multiprocessing.cpu_count()))
85 log.info('Running docker-puppet')
86 config_file = os.environ.get('CONFIG', '/var/lib/docker-puppet/docker-puppet.json')
87 log.debug('CONFIG: %s' % config_file)
88 with open(config_file) as f:
89 json_data = json.load(f)
91 # To save time we support configuring 'shared' services at the same
92 # time. For example configuring all of the heat services
93 # in a single container pass makes sense and will save some time.
94 # To support this we merge shared settings together here.
96 # We key off of config_volume as this should be the same for a
97 # given group of services. We are also now specifying the container
98 # in which the services should be configured. This should match
99 # in all instances where the volume name is also the same.
103 for service in (json_data or []):
106 if isinstance(service, dict):
108 service.get('config_volume'),
109 service.get('puppet_tags'),
110 service.get('step_config'),
111 service.get('config_image'),
112 service.get('volumes', []),
115 config_volume = service[0] or ''
116 puppet_tags = service[1] or ''
117 manifest = service[2] or ''
118 config_image = service[3] or ''
119 volumes = service[4] if len(service) > 4 else []
121 if not manifest or not config_image:
124 log.debug('config_volume %s' % config_volume)
125 log.debug('puppet_tags %s' % puppet_tags)
126 log.debug('manifest %s' % manifest)
127 log.debug('config_image %s' % config_image)
128 log.debug('volumes %s' % volumes)
129 # We key off of config volume for all configs.
130 if config_volume in configs:
131 # Append puppet tags and manifest.
132 log.info("Existing service, appending puppet tags and manifest")
134 configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
137 configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
139 if configs[config_volume][3] != config_image:
140 log.warn("Config containers do not match even though"
141 " shared volumes are the same!")
143 log.info("Adding new service")
144 configs[config_volume] = service
146 log.info('Service compilation completed.')
148 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
150 log.debug('config_volume %s' % config_volume)
151 log.debug('puppet_tags %s' % puppet_tags)
152 log.debug('manifest %s' % manifest)
153 log.debug('config_image %s' % config_image)
154 log.debug('volumes %s' % volumes)
155 sh_script = '/var/lib/docker-puppet/docker-puppet.sh'
157 with open(sh_script, 'w') as script_file:
158 os.chmod(script_file.name, 0755)
159 script_file.write("""#!/bin/bash
162 cp -a /tmp/puppet-etc/* /etc/puppet
163 rm -Rf /etc/puppet/ssl # not in use and causes permission errors
164 echo "{\\"step\\": $STEP}" > /etc/puppet/hieradata/docker.json
166 if [ -n "$PUPPET_TAGS" ]; then
167 TAGS="--tags \"$PUPPET_TAGS\""
169 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
172 if [ -z "$NO_ARCHIVE" ]; then
173 rm -Rf /var/lib/config-data/${NAME}
175 # copying etc should be enough for most services
176 mkdir -p /var/lib/config-data/${NAME}/etc
177 cp -a /etc/* /var/lib/config-data/${NAME}/etc/
179 # workaround LP1696283
180 mkdir -p /var/lib/config-data/${NAME}/etc/ssh
181 touch /var/lib/config-data/${NAME}/etc/ssh/ssh_known_hosts
183 if [ -d /root/ ]; then
184 cp -a /root/ /var/lib/config-data/${NAME}/root/
186 if [ -d /var/lib/ironic/tftpboot/ ]; then
187 mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
188 cp -a /var/lib/ironic/tftpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/tftpboot/
190 if [ -d /var/lib/ironic/httpboot/ ]; then
191 mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
192 cp -a /var/lib/ironic/httpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/httpboot/
195 # apache services may files placed in /var/www/
196 if [ -d /var/www/ ]; then
197 mkdir -p /var/lib/config-data/${NAME}/var/www
198 cp -a /var/www/* /var/lib/config-data/${NAME}/var/www/
203 with tempfile.NamedTemporaryFile() as tmp_man:
204 with open(tmp_man.name, 'w') as man_file:
205 man_file.write('include ::tripleo::packages\n')
206 man_file.write(manifest)
208 rm_container('docker-puppet-%s' % config_volume)
209 pull_image(config_image)
211 dcmd = ['/usr/bin/docker', 'run',
213 '--name', 'docker-puppet-%s' % config_volume,
214 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
215 '--env', 'NAME=%s' % config_volume,
216 '--env', 'HOSTNAME=%s' % short_hostname(),
217 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
218 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
219 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
220 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
221 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
222 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
223 '--volume', 'tripleo_logs:/var/log/tripleo/',
224 # OpenSSL trusted CA injection
225 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
226 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
227 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
228 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
230 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
232 for volume in volumes:
234 dcmd.extend(['--volume', volume])
236 dcmd.extend(['--entrypoint', sh_script])
239 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
240 # they contain the access data for the docker daemon.
241 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
242 env[k] = os.environ.get(k)
244 if os.environ.get('NET_HOST', 'false') == 'true':
245 log.debug('NET_HOST enabled')
246 dcmd.extend(['--net', 'host', '--volume',
247 '/etc/hosts:/etc/hosts:ro'])
248 dcmd.append(config_image)
249 log.debug('Running docker command: %s' % ' '.join(dcmd))
251 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
252 stderr=subprocess.PIPE, env=env)
253 cmd_stdout, cmd_stderr = subproc.communicate()
255 log.debug(cmd_stdout)
257 log.debug(cmd_stderr)
258 if subproc.returncode != 0:
259 log.error('Failed running docker-puppet.py for %s' % config_volume)
261 # only delete successful runs, for debugging
262 rm_container('docker-puppet-%s' % config_volume)
263 return subproc.returncode
265 # Holds all the information for each process to consume.
266 # Instead of starting them all linearly we run them using a process
267 # pool. This creates a list of arguments for the above function
271 for config_volume in configs:
273 service = configs[config_volume]
274 puppet_tags = service[1] or ''
275 manifest = service[2] or ''
276 config_image = service[3] or ''
277 volumes = service[4] if len(service) > 4 else []
280 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
282 puppet_tags = "file,file_line,concat,augeas"
284 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
286 for p in process_map:
287 log.debug('- %s' % p)
289 # Fire off processes to perform each configuration. Defaults
290 # to the number of CPUs on the system.
291 p = multiprocessing.Pool(process_count)
292 returncodes = list(p.map(mp_puppet_config, process_map))
293 config_volumes = [pm[0] for pm in process_map]
295 for returncode, config_volume in zip(returncodes, config_volumes):
297 log.error('ERROR configuring %s' % config_volume)