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 # Write a checksum of the config-data dir, this is used as a
212 # salt to trigger container restart when the config changes
213 tar cf - /var/lib/config-data/${NAME} | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
217 with tempfile.NamedTemporaryFile() as tmp_man:
218 with open(tmp_man.name, 'w') as man_file:
219 man_file.write('include ::tripleo::packages\n')
220 man_file.write(manifest)
222 rm_container('docker-puppet-%s' % config_volume)
223 pull_image(config_image)
225 dcmd = ['/usr/bin/docker', 'run',
227 '--name', 'docker-puppet-%s' % config_volume,
228 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
229 '--env', 'NAME=%s' % config_volume,
230 '--env', 'HOSTNAME=%s' % short_hostname(),
231 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
232 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
233 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
234 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
235 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
236 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
237 '--volume', 'tripleo_logs:/var/log/tripleo/',
238 # OpenSSL trusted CA injection
239 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
240 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
241 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
242 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
244 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
246 for volume in volumes:
248 dcmd.extend(['--volume', volume])
250 dcmd.extend(['--entrypoint', sh_script])
253 # NOTE(flaper87): Always copy the DOCKER_* environment variables as
254 # they contain the access data for the docker daemon.
255 for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
256 env[k] = os.environ.get(k)
258 if os.environ.get('NET_HOST', 'false') == 'true':
259 log.debug('NET_HOST enabled')
260 dcmd.extend(['--net', 'host', '--volume',
261 '/etc/hosts:/etc/hosts:ro'])
262 dcmd.append(config_image)
263 log.debug('Running docker command: %s' % ' '.join(dcmd))
265 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
266 stderr=subprocess.PIPE, env=env)
267 cmd_stdout, cmd_stderr = subproc.communicate()
269 log.debug(cmd_stdout)
271 log.debug(cmd_stderr)
272 if subproc.returncode != 0:
273 log.error('Failed running docker-puppet.py for %s' % config_volume)
275 # only delete successful runs, for debugging
276 rm_container('docker-puppet-%s' % config_volume)
277 return subproc.returncode
279 # Holds all the information for each process to consume.
280 # Instead of starting them all linearly we run them using a process
281 # pool. This creates a list of arguments for the above function
285 for config_volume in configs:
287 service = configs[config_volume]
288 puppet_tags = service[1] or ''
289 manifest = service[2] or ''
290 config_image = service[3] or ''
291 volumes = service[4] if len(service) > 4 else []
294 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
296 puppet_tags = "file,file_line,concat,augeas"
298 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
300 for p in process_map:
301 log.debug('- %s' % p)
303 # Fire off processes to perform each configuration. Defaults
304 # to the number of CPUs on the system.
305 p = multiprocessing.Pool(process_count)
306 returncodes = list(p.map(mp_puppet_config, process_map))
307 config_volumes = [pm[0] for pm in process_map]
309 for returncode, config_volume in zip(returncodes, config_volumes):
311 log.error('ERROR configuring %s' % config_volume)
315 # Update the startup configs with the config hash we generated above
316 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
317 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
318 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
319 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
320 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
321 for infile in infiles:
322 with open(infile) as f:
323 infile_data = json.load(f)
325 for k, v in infile_data.iteritems():
326 config_volume = match_config_volume(config_volume_prefix, v)
328 config_hash = get_config_hash(config_volume_prefix, config_volume)
330 env = v.get('environment', [])
331 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
332 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
333 infile_data[k]['environment'] = env
335 outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
336 with open(outfile, 'w') as out_f:
337 json.dump(infile_data, out_f)