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.
29 import multiprocessing
36 logger = logging.getLogger()
37 ch = logging.StreamHandler(sys.stdout)
38 if os.environ.get('DEBUG', False):
39 logger.setLevel(logging.DEBUG)
40 ch.setLevel(logging.DEBUG)
42 logger.setLevel(logging.INFO)
43 ch.setLevel(logging.INFO)
44 formatter = logging.Formatter('%(asctime)s %(levelname)s: '
45 '%(process)s -- %(message)s')
46 ch.setFormatter(formatter)
51 # this is to match what we do in deployed-server
53 subproc = subprocess.Popen(['hostname', '-s'],
54 stdout=subprocess.PIPE,
55 stderr=subprocess.PIPE)
56 cmd_stdout, cmd_stderr = subproc.communicate()
57 return cmd_stdout.rstrip()
61 log.info('Pulling image: %s' % name)
62 subproc = subprocess.Popen(['/usr/bin/docker', 'pull', name],
63 stdout=subprocess.PIPE,
64 stderr=subprocess.PIPE)
65 cmd_stdout, cmd_stderr = subproc.communicate()
72 def match_config_volume(prefix, config):
73 # Match the mounted config volume - we can't just use the
74 # key as e.g "novacomute" consumes config-data/nova
75 volumes = config.get('volumes', [])
78 if v.startswith(prefix):
79 config_volume = os.path.relpath(
80 v.split(":")[0], prefix).split("/")[0]
85 def get_config_hash(prefix, config_volume):
86 hashfile = os.path.join(prefix, "%s.md5sum" % config_volume)
88 if os.path.isfile(hashfile):
89 with open(hashfile) as f:
90 hash_data = f.read().rstrip()
94 def rm_container(name):
95 if os.environ.get('SHOW_DIFF', None):
96 log.info('Diffing container: %s' % name)
97 subproc = subprocess.Popen(['/usr/bin/docker', 'diff', name],
98 stdout=subprocess.PIPE,
99 stderr=subprocess.PIPE)
100 cmd_stdout, cmd_stderr = subproc.communicate()
102 log.debug(cmd_stdout)
104 log.debug(cmd_stderr)
106 log.info('Removing container: %s' % name)
107 subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
108 stdout=subprocess.PIPE,
109 stderr=subprocess.PIPE)
110 cmd_stdout, cmd_stderr = subproc.communicate()
112 log.debug(cmd_stdout)
114 cmd_stderr != 'Error response from daemon: ' \
115 'No such container: {}\n'.format(name):
116 log.debug(cmd_stderr)
118 process_count = int(os.environ.get('PROCESS_COUNT',
119 multiprocessing.cpu_count()))
121 log.info('Running docker-puppet')
122 config_file = os.environ.get('CONFIG', '/var/lib/docker-puppet/docker-puppet.json')
123 log.debug('CONFIG: %s' % config_file)
124 with open(config_file) as f:
125 json_data = json.load(f)
127 # To save time we support configuring 'shared' services at the same
128 # time. For example configuring all of the heat services
129 # in a single container pass makes sense and will save some time.
130 # To support this we merge shared settings together here.
132 # We key off of config_volume as this should be the same for a
133 # given group of services. We are also now specifying the container
134 # in which the services should be configured. This should match
135 # in all instances where the volume name is also the same.
139 for service in (json_data or []):
142 if isinstance(service, dict):
144 service.get('config_volume'),
145 service.get('puppet_tags'),
146 service.get('step_config'),
147 service.get('config_image'),
148 service.get('volumes', []),
151 config_volume = service[0] or ''
152 puppet_tags = service[1] or ''
153 manifest = service[2] or ''
154 config_image = service[3] or ''
155 volumes = service[4] if len(service) > 4 else []
157 if not manifest or not config_image:
160 log.info('config_volume %s' % config_volume)
161 log.info('puppet_tags %s' % puppet_tags)
162 log.info('manifest %s' % manifest)
163 log.info('config_image %s' % config_image)
164 log.info('volumes %s' % volumes)
165 # We key off of config volume for all configs.
166 if config_volume in configs:
167 # Append puppet tags and manifest.
168 log.info("Existing service, appending puppet tags and manifest")
170 configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
173 configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
175 if configs[config_volume][3] != config_image:
176 log.warn("Config containers do not match even though"
177 " shared volumes are the same!")
179 log.info("Adding new service")
180 configs[config_volume] = service
182 log.info('Service compilation completed.')
184 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
186 log.info('Started processing puppet configs')
187 log.debug('config_volume %s' % config_volume)
188 log.debug('puppet_tags %s' % puppet_tags)
189 log.debug('manifest %s' % manifest)
190 log.debug('config_image %s' % config_image)
191 log.debug('volumes %s' % volumes)
192 sh_script = '/var/lib/docker-puppet/docker-puppet.sh'
194 with open(sh_script, 'w') as script_file:
195 os.chmod(script_file.name, 0755)
196 script_file.write("""#!/bin/bash
199 cp -a /tmp/puppet-etc/* /etc/puppet
200 rm -Rf /etc/puppet/ssl # not in use and causes permission errors
201 echo "{\\"step\\": $STEP}" > /etc/puppet/hieradata/docker.json
203 if [ -n "$PUPPET_TAGS" ]; then
204 TAGS="--tags \"$PUPPET_TAGS\""
207 # Create a reference timestamp to easily find all files touched by
208 # puppet. The sync ensures we get all the files we want due to
209 # different timestamp.
210 touch /tmp/the_origin_of_time
213 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply \
214 --color=false --logdest syslog $TAGS /etc/config.pp
217 if [ -z "$NO_ARCHIVE" ]; then
218 archivedirs=("/etc" "/root" "/opt" "/var/lib/ironic/tftpboot" "/var/lib/ironic/httpboot" "/var/www")
220 for d in "${archivedirs[@]}"; do
225 rsync -a -R --delay-updates --delete-after $rsync_srcs /var/lib/config-data/${NAME}
227 # Also make a copy of files modified during puppet run
228 # This is useful for debugging
229 mkdir -p /var/lib/config-data/puppet-generated/${NAME}
230 rsync -a -R -0 --delay-updates --delete-after \
231 --files-from=<(find $rsync_srcs -newer /tmp/the_origin_of_time -not -path '/etc/puppet*' -print0) \
232 / /var/lib/config-data/puppet-generated/${NAME}
234 # Write a checksum of the config-data dir, this is used as a
235 # salt to trigger container restart when the config changes
236 tar -c -f - /var/lib/config-data/${NAME} --mtime='1970-01-01' | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
240 with tempfile.NamedTemporaryFile() as tmp_man:
241 with open(tmp_man.name, 'w') as man_file:
242 man_file.write('include ::tripleo::packages\n')
243 man_file.write(manifest)
245 rm_container('docker-puppet-%s' % config_volume)
246 pull_image(config_image)
248 dcmd = ['/usr/bin/docker', 'run',
250 '--name', 'docker-puppet-%s' % config_volume,
251 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
252 '--env', 'NAME=%s' % config_volume,
253 '--env', 'HOSTNAME=%s' % short_hostname(),
254 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
255 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
256 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
257 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
258 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
259 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
260 '--volume', 'tripleo_logs:/var/log/tripleo/',
261 # Syslog socket for puppet logs
262 '--volume', '/dev/log:/dev/log',
263 # OpenSSL trusted CA injection
264 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
265 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
266 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
267 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
269 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
271 for volume in volumes:
273 dcmd.extend(['--volume', volume])
275 dcmd.extend(['--entrypoint', sh_script])
278 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
279 # they contain the access data for the docker daemon.
280 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
281 env[k] = os.environ.get(k)
283 if os.environ.get('NET_HOST', 'false') == 'true':
284 log.debug('NET_HOST enabled')
285 dcmd.extend(['--net', 'host', '--volume',
286 '/etc/hosts:/etc/hosts:ro'])
287 dcmd.append(config_image)
288 log.debug('Running docker command: %s' % ' '.join(dcmd))
290 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
291 stderr=subprocess.PIPE, env=env)
292 cmd_stdout, cmd_stderr = subproc.communicate()
293 if subproc.returncode != 0:
294 log.error('Failed running docker-puppet.py for %s' % config_volume)
296 log.error(cmd_stdout)
298 log.error(cmd_stderr)
301 log.debug(cmd_stdout)
303 log.debug(cmd_stderr)
304 # only delete successful runs, for debugging
305 rm_container('docker-puppet-%s' % config_volume)
307 log.info('Finished processing puppet configs')
308 return subproc.returncode
310 # Holds all the information for each process to consume.
311 # Instead of starting them all linearly we run them using a process
312 # pool. This creates a list of arguments for the above function
316 for config_volume in configs:
318 service = configs[config_volume]
319 puppet_tags = service[1] or ''
320 manifest = service[2] or ''
321 config_image = service[3] or ''
322 volumes = service[4] if len(service) > 4 else []
325 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
327 puppet_tags = "file,file_line,concat,augeas"
329 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
331 for p in process_map:
332 log.debug('- %s' % p)
334 # Fire off processes to perform each configuration. Defaults
335 # to the number of CPUs on the system.
336 p = multiprocessing.Pool(process_count)
337 returncodes = list(p.map(mp_puppet_config, process_map))
338 config_volumes = [pm[0] for pm in process_map]
340 for returncode, config_volume in zip(returncodes, config_volumes):
342 log.error('ERROR configuring %s' % config_volume)
346 # Update the startup configs with the config hash we generated above
347 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
348 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
349 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
350 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
351 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
352 for infile in infiles:
353 with open(infile) as f:
354 infile_data = json.load(f)
356 for k, v in infile_data.iteritems():
357 config_volume = match_config_volume(config_volume_prefix, v)
359 config_hash = get_config_hash(config_volume_prefix, config_volume)
361 env = v.get('environment', [])
362 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
363 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
364 infile_data[k]['environment'] = env
366 outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
367 with open(outfile, 'w') as out_f:
368 json.dump(infile_data, out_f)