Merge "Fix descriptions on bonding templates"
[apex-tripleo-heat-templates.git] / docker / docker-puppet.py
1 #!/usr/bin/env python
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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
13 #    under the License.
14
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.
20
21 import glob
22 import json
23 import logging
24 import os
25 import sys
26 import subprocess
27 import sys
28 import tempfile
29 import multiprocessing
30
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)
37 log.addHandler(ch)
38
39 # this is to match what we do in deployed-server
40 def short_hostname():
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()
46
47
48 def pull_image(name):
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()
54     if cmd_stdout:
55         log.debug(cmd_stdout)
56     if cmd_stderr:
57         log.debug(cmd_stderr)
58
59
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', [])
64     config_volume=None
65     for v in volumes:
66         if v.startswith(prefix):
67             config_volume =  os.path.relpath(
68                 v.split(":")[0], prefix).split("/")[0]
69             break
70     return config_volume
71
72
73 def get_config_hash(prefix, config_volume):
74     hashfile = os.path.join(prefix, "%s.md5sum" % config_volume)
75     hash_data = None
76     if os.path.isfile(hashfile):
77         with open(hashfile) as f:
78             hash_data = f.read().rstrip()
79     return hash_data
80
81
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()
89         if cmd_stdout:
90             log.debug(cmd_stdout)
91         if cmd_stderr:
92             log.debug(cmd_stderr)
93
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()
99     if cmd_stdout:
100         log.debug(cmd_stdout)
101     if cmd_stderr and \
102            cmd_stderr != 'Error response from daemon: ' \
103            'No such container: {}\n'.format(name):
104         log.debug(cmd_stderr)
105
106 process_count = int(os.environ.get('PROCESS_COUNT',
107                                    multiprocessing.cpu_count()))
108
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)
114
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.
119 #
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.
124
125 configs = {}
126
127 for service in (json_data or []):
128     if service is None:
129         continue
130     if isinstance(service, dict):
131         service = [
132             service.get('config_volume'),
133             service.get('puppet_tags'),
134             service.get('step_config'),
135             service.get('config_image'),
136             service.get('volumes', []),
137         ]
138
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 []
144
145     if not manifest or not config_image:
146         continue
147
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")
157         if puppet_tags:
158             configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
159                                                    puppet_tags)
160         if manifest:
161             configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
162                                                     manifest)
163         if configs[config_volume][3] != config_image:
164             log.warn("Config containers do not match even though"
165                      " shared volumes are the same!")
166     else:
167         log.info("Adding new service")
168         configs[config_volume] = service
169
170 log.info('Service compilation completed.')
171
172 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
173
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'
180
181     with open(sh_script, 'w') as script_file:
182         os.chmod(script_file.name, 0755)
183         script_file.write("""#!/bin/bash
184         set -ex
185         mkdir -p /etc/puppet
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
189         TAGS=""
190         if [ -n "$PUPPET_TAGS" ]; then
191             TAGS="--tags \"$PUPPET_TAGS\""
192         fi
193
194         # workaround LP1696283
195         mkdir -p /etc/ssh
196         touch /etc/ssh/ssh_known_hosts
197
198         FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
199
200         # Disables archiving
201         if [ -z "$NO_ARCHIVE" ]; then
202             archivedirs=("/etc" "/root" "/var/lib/ironic/tftpboot" "/var/lib/ironic/httpboot" "/var/www")
203             rsync_srcs=""
204             for d in "${archivedirs[@]}"; do
205                 if [ -d "$d" ]; then
206                     rsync_srcs+=" $d"
207                 fi
208             done
209             rsync -a -R --delay-updates --delete-after $rsync_srcs /var/lib/config-data/${NAME}
210
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}
217
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
221         fi
222         """)
223
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)
228
229         rm_container('docker-puppet-%s' % config_volume)
230         pull_image(config_image)
231
232         dcmd = ['/usr/bin/docker', 'run',
233                 '--user', 'root',
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',
250                 # script injection
251                 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
252
253         for volume in volumes:
254             if volume:
255                 dcmd.extend(['--volume', volume])
256
257         dcmd.extend(['--entrypoint', sh_script])
258
259         env = {}
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)
264
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))
271
272         subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
273                                    stderr=subprocess.PIPE, env=env)
274         cmd_stdout, cmd_stderr = subproc.communicate()
275         if cmd_stdout:
276             log.debug(cmd_stdout)
277         if cmd_stderr:
278             log.debug(cmd_stderr)
279         if subproc.returncode != 0:
280             log.error('Failed running docker-puppet.py for %s' % config_volume)
281         else:
282             # only delete successful runs, for debugging
283             rm_container('docker-puppet-%s' % config_volume)
284         return subproc.returncode
285
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
289 # to consume.
290 process_map = []
291
292 for config_volume in configs:
293
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 []
299
300     if puppet_tags:
301         puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
302     else:
303         puppet_tags = "file,file_line,concat,augeas"
304
305     process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
306
307 for p in process_map:
308     log.debug('- %s' % p)
309
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]
315 success = True
316 for returncode, config_volume in zip(returncodes, config_volumes):
317     if returncode != 0:
318         log.error('ERROR configuring %s' % config_volume)
319         success = False
320
321
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)
331
332     for k, v in infile_data.iteritems():
333         config_volume = match_config_volume(config_volume_prefix, v)
334         if config_volume:
335             config_hash = get_config_hash(config_volume_prefix, config_volume)
336             if config_hash:
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
341
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)
345
346 if not success:
347     sys.exit(1)