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 log.setLevel(logging.DEBUG)
33 ch = logging.StreamHandler(sys.stdout)
34 ch.setLevel(logging.DEBUG)
35 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
36 ch.setFormatter(formatter)
39 # this is to match what we do in deployed-server
41 subproc = subprocess.Popen(['hostname', '-s'],
42 stdout=subprocess.PIPE,
43 stderr=subprocess.PIPE)
44 cmd_stdout, cmd_stderr = subproc.communicate()
45 return cmd_stdout.rstrip()
49 log.info('Pulling image: %s' % name)
50 subproc = subprocess.Popen(['/usr/bin/docker', 'pull', name],
51 stdout=subprocess.PIPE,
52 stderr=subprocess.PIPE)
53 cmd_stdout, cmd_stderr = subproc.communicate()
60 def match_config_volume(prefix, config):
61 # Match the mounted config volume - we can't just use the
62 # key as e.g "novacomute" consumes config-data/nova
63 volumes = config.get('volumes', [])
66 if v.startswith(prefix):
67 config_volume = os.path.relpath(
68 v.split(":")[0], prefix).split("/")[0]
73 def get_config_hash(prefix, config_volume):
74 hashfile = os.path.join(prefix, "%s.md5sum" % config_volume)
76 if os.path.isfile(hashfile):
77 with open(hashfile) as f:
78 hash_data = f.read().rstrip()
82 def rm_container(name):
83 if os.environ.get('SHOW_DIFF', None):
84 log.info('Diffing container: %s' % name)
85 subproc = subprocess.Popen(['/usr/bin/docker', 'diff', name],
86 stdout=subprocess.PIPE,
87 stderr=subprocess.PIPE)
88 cmd_stdout, cmd_stderr = subproc.communicate()
94 log.info('Removing container: %s' % name)
95 subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
96 stdout=subprocess.PIPE,
97 stderr=subprocess.PIPE)
98 cmd_stdout, cmd_stderr = subproc.communicate()
100 log.debug(cmd_stdout)
102 cmd_stderr != 'Error response from daemon: ' \
103 'No such container: {}\n'.format(name):
104 log.debug(cmd_stderr)
106 process_count = int(os.environ.get('PROCESS_COUNT',
107 multiprocessing.cpu_count()))
109 log.info('Running docker-puppet')
110 config_file = os.environ.get('CONFIG', '/var/lib/docker-puppet/docker-puppet.json')
111 log.debug('CONFIG: %s' % config_file)
112 with open(config_file) as f:
113 json_data = json.load(f)
115 # To save time we support configuring 'shared' services at the same
116 # time. For example configuring all of the heat services
117 # in a single container pass makes sense and will save some time.
118 # To support this we merge shared settings together here.
120 # We key off of config_volume as this should be the same for a
121 # given group of services. We are also now specifying the container
122 # in which the services should be configured. This should match
123 # in all instances where the volume name is also the same.
127 for service in (json_data or []):
130 if isinstance(service, dict):
132 service.get('config_volume'),
133 service.get('puppet_tags'),
134 service.get('step_config'),
135 service.get('config_image'),
136 service.get('volumes', []),
139 config_volume = service[0] or ''
140 puppet_tags = service[1] or ''
141 manifest = service[2] or ''
142 config_image = service[3] or ''
143 volumes = service[4] if len(service) > 4 else []
145 if not manifest or not config_image:
148 log.debug('config_volume %s' % config_volume)
149 log.debug('puppet_tags %s' % puppet_tags)
150 log.debug('manifest %s' % manifest)
151 log.debug('config_image %s' % config_image)
152 log.debug('volumes %s' % volumes)
153 # We key off of config volume for all configs.
154 if config_volume in configs:
155 # Append puppet tags and manifest.
156 log.info("Existing service, appending puppet tags and manifest")
158 configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
161 configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
163 if configs[config_volume][3] != config_image:
164 log.warn("Config containers do not match even though"
165 " shared volumes are the same!")
167 log.info("Adding new service")
168 configs[config_volume] = service
170 log.info('Service compilation completed.')
172 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
174 log.debug('config_volume %s' % config_volume)
175 log.debug('puppet_tags %s' % puppet_tags)
176 log.debug('manifest %s' % manifest)
177 log.debug('config_image %s' % config_image)
178 log.debug('volumes %s' % volumes)
179 sh_script = '/var/lib/docker-puppet/docker-puppet.sh'
181 with open(sh_script, 'w') as script_file:
182 os.chmod(script_file.name, 0755)
183 script_file.write("""#!/bin/bash
186 cp -a /tmp/puppet-etc/* /etc/puppet
187 rm -Rf /etc/puppet/ssl # not in use and causes permission errors
188 echo "{\\"step\\": $STEP}" > /etc/puppet/hieradata/docker.json
190 if [ -n "$PUPPET_TAGS" ]; then
191 TAGS="--tags \"$PUPPET_TAGS\""
194 # workaround LP1696283
196 touch /etc/ssh/ssh_known_hosts
198 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
201 if [ -z "$NO_ARCHIVE" ]; then
202 archivedirs=("/etc" "/root" "/var/lib/ironic/tftpboot" "/var/lib/ironic/httpboot" "/var/www")
204 for d in "${archivedirs[@]}"; do
209 rsync -a -R --delay-updates --delete-after $rsync_srcs /var/lib/config-data/${NAME}
211 # Also make a copy of files modified during puppet run
212 # This is useful for debugging
213 mkdir -p /var/lib/config-data/puppet-generated/${NAME}
214 rsync -a -R -0 --delay-updates --delete-after \
215 --files-from=<(find $rsync_srcs -newer /etc/ssh/ssh_known_hosts -print0) \
216 / /var/lib/config-data/puppet-generated/${NAME}
218 # Write a checksum of the config-data dir, this is used as a
219 # salt to trigger container restart when the config changes
220 tar cf - /var/lib/config-data/${NAME} | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
224 with tempfile.NamedTemporaryFile() as tmp_man:
225 with open(tmp_man.name, 'w') as man_file:
226 man_file.write('include ::tripleo::packages\n')
227 man_file.write(manifest)
229 rm_container('docker-puppet-%s' % config_volume)
230 pull_image(config_image)
232 dcmd = ['/usr/bin/docker', 'run',
234 '--name', 'docker-puppet-%s' % config_volume,
235 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
236 '--env', 'NAME=%s' % config_volume,
237 '--env', 'HOSTNAME=%s' % short_hostname(),
238 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
239 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
240 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
241 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
242 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
243 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
244 '--volume', 'tripleo_logs:/var/log/tripleo/',
245 # OpenSSL trusted CA injection
246 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
247 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
248 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
249 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
251 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
253 for volume in volumes:
255 dcmd.extend(['--volume', volume])
257 dcmd.extend(['--entrypoint', sh_script])
260 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
261 # they contain the access data for the docker daemon.
262 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
263 env[k] = os.environ.get(k)
265 if os.environ.get('NET_HOST', 'false') == 'true':
266 log.debug('NET_HOST enabled')
267 dcmd.extend(['--net', 'host', '--volume',
268 '/etc/hosts:/etc/hosts:ro'])
269 dcmd.append(config_image)
270 log.debug('Running docker command: %s' % ' '.join(dcmd))
272 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
273 stderr=subprocess.PIPE, env=env)
274 cmd_stdout, cmd_stderr = subproc.communicate()
276 log.debug(cmd_stdout)
278 log.debug(cmd_stderr)
279 if subproc.returncode != 0:
280 log.error('Failed running docker-puppet.py for %s' % config_volume)
282 # only delete successful runs, for debugging
283 rm_container('docker-puppet-%s' % config_volume)
284 return subproc.returncode
286 # Holds all the information for each process to consume.
287 # Instead of starting them all linearly we run them using a process
288 # pool. This creates a list of arguments for the above function
292 for config_volume in configs:
294 service = configs[config_volume]
295 puppet_tags = service[1] or ''
296 manifest = service[2] or ''
297 config_image = service[3] or ''
298 volumes = service[4] if len(service) > 4 else []
301 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
303 puppet_tags = "file,file_line,concat,augeas"
305 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
307 for p in process_map:
308 log.debug('- %s' % p)
310 # Fire off processes to perform each configuration. Defaults
311 # to the number of CPUs on the system.
312 p = multiprocessing.Pool(process_count)
313 returncodes = list(p.map(mp_puppet_config, process_map))
314 config_volumes = [pm[0] for pm in process_map]
316 for returncode, config_volume in zip(returncodes, config_volumes):
318 log.error('ERROR configuring %s' % config_volume)
322 # Update the startup configs with the config hash we generated above
323 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
324 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
325 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
326 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
327 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
328 for infile in infiles:
329 with open(infile) as f:
330 infile_data = json.load(f)
332 for k, v in infile_data.iteritems():
333 config_volume = match_config_volume(config_volume_prefix, v)
335 config_hash = get_config_hash(config_volume_prefix, config_volume)
337 env = v.get('environment', [])
338 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
339 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
340 infile_data[k]['environment'] = env
342 outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
343 with open(outfile, 'w') as out_f:
344 json.dump(infile_data, out_f)