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 # workaround LP1696283
200 touch /etc/ssh/ssh_known_hosts
202 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
205 if [ -z "$NO_ARCHIVE" ]; then
206 archivedirs=("/etc" "/root" "/opt" "/var/lib/ironic/tftpboot" "/var/lib/ironic/httpboot" "/var/www")
208 for d in "${archivedirs[@]}"; do
213 rsync -a -R --delay-updates --delete-after $rsync_srcs /var/lib/config-data/${NAME}
215 # Also make a copy of files modified during puppet run
216 # This is useful for debugging
217 mkdir -p /var/lib/config-data/puppet-generated/${NAME}
218 rsync -a -R -0 --delay-updates --delete-after \
219 --files-from=<(find $rsync_srcs -newer /etc/ssh/ssh_known_hosts -print0) \
220 / /var/lib/config-data/puppet-generated/${NAME}
222 # Write a checksum of the config-data dir, this is used as a
223 # salt to trigger container restart when the config changes
224 tar -c -f - /var/lib/config-data/${NAME} --mtime='1970-01-01' | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
228 with tempfile.NamedTemporaryFile() as tmp_man:
229 with open(tmp_man.name, 'w') as man_file:
230 man_file.write('include ::tripleo::packages\n')
231 man_file.write(manifest)
233 rm_container('docker-puppet-%s' % config_volume)
234 pull_image(config_image)
236 dcmd = ['/usr/bin/docker', 'run',
238 '--name', 'docker-puppet-%s' % config_volume,
239 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
240 '--env', 'NAME=%s' % config_volume,
241 '--env', 'HOSTNAME=%s' % short_hostname(),
242 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
243 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
244 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
245 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
246 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
247 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
248 '--volume', 'tripleo_logs:/var/log/tripleo/',
249 # OpenSSL trusted CA injection
250 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
251 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
252 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
253 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
255 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
257 for volume in volumes:
259 dcmd.extend(['--volume', volume])
261 dcmd.extend(['--entrypoint', sh_script])
264 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
265 # they contain the access data for the docker daemon.
266 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
267 env[k] = os.environ.get(k)
269 if os.environ.get('NET_HOST', 'false') == 'true':
270 log.debug('NET_HOST enabled')
271 dcmd.extend(['--net', 'host', '--volume',
272 '/etc/hosts:/etc/hosts:ro'])
273 dcmd.append(config_image)
274 log.debug('Running docker command: %s' % ' '.join(dcmd))
276 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
277 stderr=subprocess.PIPE, env=env)
278 cmd_stdout, cmd_stderr = subproc.communicate()
279 if subproc.returncode != 0:
280 log.error('Failed running docker-puppet.py for %s' % config_volume)
282 log.error(cmd_stdout)
284 log.error(cmd_stderr)
287 log.debug(cmd_stdout)
289 log.debug(cmd_stderr)
290 # only delete successful runs, for debugging
291 rm_container('docker-puppet-%s' % config_volume)
292 return subproc.returncode
294 # Holds all the information for each process to consume.
295 # Instead of starting them all linearly we run them using a process
296 # pool. This creates a list of arguments for the above function
300 for config_volume in configs:
302 service = configs[config_volume]
303 puppet_tags = service[1] or ''
304 manifest = service[2] or ''
305 config_image = service[3] or ''
306 volumes = service[4] if len(service) > 4 else []
309 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
311 puppet_tags = "file,file_line,concat,augeas"
313 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
315 for p in process_map:
316 log.debug('- %s' % p)
318 # Fire off processes to perform each configuration. Defaults
319 # to the number of CPUs on the system.
320 p = multiprocessing.Pool(process_count)
321 returncodes = list(p.map(mp_puppet_config, process_map))
322 config_volumes = [pm[0] for pm in process_map]
324 for returncode, config_volume in zip(returncodes, config_volumes):
326 log.error('ERROR configuring %s' % config_volume)
330 # Update the startup configs with the config hash we generated above
331 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
332 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
333 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
334 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
335 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
336 for infile in infiles:
337 with open(infile) as f:
338 infile_data = json.load(f)
340 for k, v in infile_data.iteritems():
341 config_volume = match_config_volume(config_volume_prefix, v)
343 config_hash = get_config_hash(config_volume_prefix, config_volume)
345 env = v.get('environment', [])
346 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
347 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
348 infile_data[k]['environment'] = env
350 outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
351 with open(outfile, 'w') as out_f:
352 json.dump(infile_data, out_f)