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
31 log = logging.getLogger()
32 ch = logging.StreamHandler(sys.stdout)
33 if os.environ.get('DEBUG', False):
34 log.setLevel(logging.DEBUG)
35 ch.setLevel(logging.DEBUG)
37 log.setLevel(logging.INFO)
38 ch.setLevel(logging.INFO)
39 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
40 ch.setFormatter(formatter)
43 # this is to match what we do in deployed-server
45 subproc = subprocess.Popen(['hostname', '-s'],
46 stdout=subprocess.PIPE,
47 stderr=subprocess.PIPE)
48 cmd_stdout, cmd_stderr = subproc.communicate()
49 return cmd_stdout.rstrip()
53 log.info('Pulling image: %s' % name)
54 subproc = subprocess.Popen(['/usr/bin/docker', 'pull', name],
55 stdout=subprocess.PIPE,
56 stderr=subprocess.PIPE)
57 cmd_stdout, cmd_stderr = subproc.communicate()
64 def match_config_volume(prefix, config):
65 # Match the mounted config volume - we can't just use the
66 # key as e.g "novacomute" consumes config-data/nova
67 volumes = config.get('volumes', [])
70 if v.startswith(prefix):
71 config_volume = os.path.relpath(
72 v.split(":")[0], prefix).split("/")[0]
77 def get_config_hash(prefix, config_volume):
78 hashfile = os.path.join(prefix, "%s.md5sum" % config_volume)
80 if os.path.isfile(hashfile):
81 with open(hashfile) as f:
82 hash_data = f.read().rstrip()
86 def rm_container(name):
87 if os.environ.get('SHOW_DIFF', None):
88 log.info('Diffing container: %s' % name)
89 subproc = subprocess.Popen(['/usr/bin/docker', 'diff', name],
90 stdout=subprocess.PIPE,
91 stderr=subprocess.PIPE)
92 cmd_stdout, cmd_stderr = subproc.communicate()
98 log.info('Removing container: %s' % name)
99 subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
100 stdout=subprocess.PIPE,
101 stderr=subprocess.PIPE)
102 cmd_stdout, cmd_stderr = subproc.communicate()
104 log.debug(cmd_stdout)
106 cmd_stderr != 'Error response from daemon: ' \
107 'No such container: {}\n'.format(name):
108 log.debug(cmd_stderr)
110 process_count = int(os.environ.get('PROCESS_COUNT',
111 multiprocessing.cpu_count()))
113 log.info('Running docker-puppet')
114 config_file = os.environ.get('CONFIG', '/var/lib/docker-puppet/docker-puppet.json')
115 log.debug('CONFIG: %s' % config_file)
116 with open(config_file) as f:
117 json_data = json.load(f)
119 # To save time we support configuring 'shared' services at the same
120 # time. For example configuring all of the heat services
121 # in a single container pass makes sense and will save some time.
122 # To support this we merge shared settings together here.
124 # We key off of config_volume as this should be the same for a
125 # given group of services. We are also now specifying the container
126 # in which the services should be configured. This should match
127 # in all instances where the volume name is also the same.
131 for service in (json_data or []):
134 if isinstance(service, dict):
136 service.get('config_volume'),
137 service.get('puppet_tags'),
138 service.get('step_config'),
139 service.get('config_image'),
140 service.get('volumes', []),
143 config_volume = service[0] or ''
144 puppet_tags = service[1] or ''
145 manifest = service[2] or ''
146 config_image = service[3] or ''
147 volumes = service[4] if len(service) > 4 else []
149 if not manifest or not config_image:
152 log.info('config_volume %s' % config_volume)
153 log.info('puppet_tags %s' % puppet_tags)
154 log.info('manifest %s' % manifest)
155 log.info('config_image %s' % config_image)
156 log.info('volumes %s' % volumes)
157 # We key off of config volume for all configs.
158 if config_volume in configs:
159 # Append puppet tags and manifest.
160 log.info("Existing service, appending puppet tags and manifest")
162 configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
165 configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
167 if configs[config_volume][3] != config_image:
168 log.warn("Config containers do not match even though"
169 " shared volumes are the same!")
171 log.info("Adding new service")
172 configs[config_volume] = service
174 log.info('Service compilation completed.')
176 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
178 log.debug('config_volume %s' % config_volume)
179 log.debug('puppet_tags %s' % puppet_tags)
180 log.debug('manifest %s' % manifest)
181 log.debug('config_image %s' % config_image)
182 log.debug('volumes %s' % volumes)
183 sh_script = '/var/lib/docker-puppet/docker-puppet.sh'
185 with open(sh_script, 'w') as script_file:
186 os.chmod(script_file.name, 0755)
187 script_file.write("""#!/bin/bash
190 cp -a /tmp/puppet-etc/* /etc/puppet
191 rm -Rf /etc/puppet/ssl # not in use and causes permission errors
192 echo "{\\"step\\": $STEP}" > /etc/puppet/hieradata/docker.json
194 if [ -n "$PUPPET_TAGS" ]; then
195 TAGS="--tags \"$PUPPET_TAGS\""
198 # Create a reference timestamp to easily find all files touched by
199 # puppet. The sync ensures we get all the files we want due to
200 # different timestamp.
201 touch /tmp/the_origin_of_time
204 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
207 if [ -z "$NO_ARCHIVE" ]; then
208 archivedirs=("/etc" "/root" "/opt" "/var/lib/ironic/tftpboot" "/var/lib/ironic/httpboot" "/var/www" "/var/spool/cron")
210 for d in "${archivedirs[@]}"; do
215 rsync -a -R --delay-updates --delete-after $rsync_srcs /var/lib/config-data/${NAME}
217 # Also make a copy of files modified during puppet run
218 # This is useful for debugging
219 mkdir -p /var/lib/config-data/puppet-generated/${NAME}
220 rsync -a -R -0 --delay-updates --delete-after \
221 --files-from=<(find $rsync_srcs -newer /tmp/the_origin_of_time -not -path '/etc/puppet*' -print0) \
222 / /var/lib/config-data/puppet-generated/${NAME}
224 # Write a checksum of the config-data dir, this is used as a
225 # salt to trigger container restart when the config changes
226 tar -c -f - /var/lib/config-data/${NAME} --mtime='1970-01-01' | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
230 with tempfile.NamedTemporaryFile() as tmp_man:
231 with open(tmp_man.name, 'w') as man_file:
232 man_file.write('include ::tripleo::packages\n')
233 man_file.write(manifest)
235 rm_container('docker-puppet-%s' % config_volume)
236 pull_image(config_image)
238 dcmd = ['/usr/bin/docker', 'run',
240 '--name', 'docker-puppet-%s' % config_volume,
241 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
242 '--env', 'NAME=%s' % config_volume,
243 '--env', 'HOSTNAME=%s' % short_hostname(),
244 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
245 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
246 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
247 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
248 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
249 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
250 '--volume', 'tripleo_logs:/var/log/tripleo/',
251 # OpenSSL trusted CA injection
252 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
253 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
254 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
255 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
257 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
259 for volume in volumes:
261 dcmd.extend(['--volume', volume])
263 dcmd.extend(['--entrypoint', sh_script])
266 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
267 # they contain the access data for the docker daemon.
268 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
269 env[k] = os.environ.get(k)
271 if os.environ.get('NET_HOST', 'false') == 'true':
272 log.debug('NET_HOST enabled')
273 dcmd.extend(['--net', 'host', '--volume',
274 '/etc/hosts:/etc/hosts:ro'])
275 dcmd.append(config_image)
276 log.debug('Running docker command: %s' % ' '.join(dcmd))
278 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
279 stderr=subprocess.PIPE, env=env)
280 cmd_stdout, cmd_stderr = subproc.communicate()
281 if subproc.returncode != 0:
282 log.error('Failed running docker-puppet.py for %s' % config_volume)
284 log.error(cmd_stdout)
286 log.error(cmd_stderr)
289 log.debug(cmd_stdout)
291 log.debug(cmd_stderr)
292 # only delete successful runs, for debugging
293 rm_container('docker-puppet-%s' % config_volume)
294 return subproc.returncode
296 # Holds all the information for each process to consume.
297 # Instead of starting them all linearly we run them using a process
298 # pool. This creates a list of arguments for the above function
302 for config_volume in configs:
304 service = configs[config_volume]
305 puppet_tags = service[1] or ''
306 manifest = service[2] or ''
307 config_image = service[3] or ''
308 volumes = service[4] if len(service) > 4 else []
311 puppet_tags = "file,file_line,concat,augeas,cron,%s" % puppet_tags
313 puppet_tags = "file,file_line,concat,augeas,cron"
315 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
317 for p in process_map:
318 log.debug('- %s' % p)
320 # Fire off processes to perform each configuration. Defaults
321 # to the number of CPUs on the system.
322 p = multiprocessing.Pool(process_count)
323 returncodes = list(p.map(mp_puppet_config, process_map))
324 config_volumes = [pm[0] for pm in process_map]
326 for returncode, config_volume in zip(returncodes, config_volumes):
328 log.error('ERROR configuring %s' % config_volume)
332 # Update the startup configs with the config hash we generated above
333 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
334 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
335 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
336 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
337 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
338 for infile in infiles:
339 with open(infile) as f:
340 infile_data = json.load(f)
342 for k, v in infile_data.iteritems():
343 config_volume = match_config_volume(config_volume_prefix, v)
345 config_hash = get_config_hash(config_volume_prefix, config_volume)
347 env = v.get('environment', [])
348 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
349 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
350 infile_data[k]['environment'] = env
352 outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
353 with open(outfile, 'w') as out_f:
354 json.dump(infile_data, out_f)