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