Support config dir for env generator input files
[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         FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
194
195         # Disables archiving
196         if [ -z "$NO_ARCHIVE" ]; then
197             rm -Rf /var/lib/config-data/${NAME}
198
199             # copying etc should be enough for most services
200             mkdir -p /var/lib/config-data/${NAME}/etc
201             cp -a /etc/* /var/lib/config-data/${NAME}/etc/
202
203             # workaround LP1696283
204             mkdir -p /var/lib/config-data/${NAME}/etc/ssh
205             touch /var/lib/config-data/${NAME}/etc/ssh/ssh_known_hosts
206
207             if [ -d /root/ ]; then
208               cp -a /root/ /var/lib/config-data/${NAME}/root/
209             fi
210             if [ -d /var/lib/ironic/tftpboot/ ]; then
211               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
212               cp -a /var/lib/ironic/tftpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/tftpboot/
213             fi
214             if [ -d /var/lib/ironic/httpboot/ ]; then
215               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
216               cp -a /var/lib/ironic/httpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/httpboot/
217             fi
218
219             # apache services may files placed in /var/www/
220             if [ -d /var/www/ ]; then
221              mkdir -p /var/lib/config-data/${NAME}/var/www
222              cp -a /var/www/* /var/lib/config-data/${NAME}/var/www/
223             fi
224
225             # Write a checksum of the config-data dir, this is used as a
226             # salt to trigger container restart when the config changes
227             tar cf - /var/lib/config-data/${NAME} | md5sum | awk '{print $1}' > /var/lib/config-data/${NAME}.md5sum
228         fi
229         """)
230
231     with tempfile.NamedTemporaryFile() as tmp_man:
232         with open(tmp_man.name, 'w') as man_file:
233             man_file.write('include ::tripleo::packages\n')
234             man_file.write(manifest)
235
236         rm_container('docker-puppet-%s' % config_volume)
237         pull_image(config_image)
238
239         dcmd = ['/usr/bin/docker', 'run',
240                 '--user', 'root',
241                 '--name', 'docker-puppet-%s' % config_volume,
242                 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
243                 '--env', 'NAME=%s' % config_volume,
244                 '--env', 'HOSTNAME=%s' % short_hostname(),
245                 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
246                 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
247                 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
248                 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
249                 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
250                 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
251                 '--volume', 'tripleo_logs:/var/log/tripleo/',
252                 # OpenSSL trusted CA injection
253                 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
254                 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
255                 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
256                 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
257                 # script injection
258                 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
259
260         for volume in volumes:
261             if volume:
262                 dcmd.extend(['--volume', volume])
263
264         dcmd.extend(['--entrypoint', sh_script])
265
266         env = {}
267         # NOTE(flaper87): Always copy the DOCKER_* environment variables as
268         # they contain the access data for the docker daemon.
269         for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
270             env[k] = os.environ.get(k)
271
272         if os.environ.get('NET_HOST', 'false') == 'true':
273             log.debug('NET_HOST enabled')
274             dcmd.extend(['--net', 'host', '--volume',
275                          '/etc/hosts:/etc/hosts:ro'])
276         dcmd.append(config_image)
277         log.debug('Running docker command: %s' % ' '.join(dcmd))
278
279         subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
280                                    stderr=subprocess.PIPE, env=env)
281         cmd_stdout, cmd_stderr = subproc.communicate()
282         if cmd_stdout:
283             log.debug(cmd_stdout)
284         if cmd_stderr:
285             log.debug(cmd_stderr)
286         if subproc.returncode != 0:
287             log.error('Failed running docker-puppet.py for %s' % config_volume)
288         else:
289             # only delete successful runs, for debugging
290             rm_container('docker-puppet-%s' % config_volume)
291         return subproc.returncode
292
293 # Holds all the information for each process to consume.
294 # Instead of starting them all linearly we run them using a process
295 # pool.  This creates a list of arguments for the above function
296 # to consume.
297 process_map = []
298
299 for config_volume in configs:
300
301     service = configs[config_volume]
302     puppet_tags = service[1] or ''
303     manifest = service[2] or ''
304     config_image = service[3] or ''
305     volumes = service[4] if len(service) > 4 else []
306
307     if puppet_tags:
308         puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
309     else:
310         puppet_tags = "file,file_line,concat,augeas"
311
312     process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
313
314 for p in process_map:
315     log.debug('- %s' % p)
316
317 # Fire off processes to perform each configuration.  Defaults
318 # to the number of CPUs on the system.
319 p = multiprocessing.Pool(process_count)
320 returncodes = list(p.map(mp_puppet_config, process_map))
321 config_volumes = [pm[0] for pm in process_map]
322 success = True
323 for returncode, config_volume in zip(returncodes, config_volumes):
324     if returncode != 0:
325         log.error('ERROR configuring %s' % config_volume)
326         success = False
327
328
329 # Update the startup configs with the config hash we generated above
330 config_volume_prefix = os.environ.get('CONFIG_VOLUME_PREFIX', '/var/lib/config-data')
331 log.debug('CONFIG_VOLUME_PREFIX: %s' % config_volume_prefix)
332 startup_configs = os.environ.get('STARTUP_CONFIG_PATTERN', '/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
333 log.debug('STARTUP_CONFIG_PATTERN: %s' % startup_configs)
334 infiles = glob.glob('/var/lib/tripleo-config/docker-container-startup-config-step_*.json')
335 for infile in infiles:
336     with open(infile) as f:
337         infile_data = json.load(f)
338
339     for k, v in infile_data.iteritems():
340         config_volume = match_config_volume(config_volume_prefix, v)
341         if config_volume:
342             config_hash = get_config_hash(config_volume_prefix, config_volume)
343             if config_hash:
344                 env = v.get('environment', [])
345                 env.append("TRIPLEO_CONFIG_HASH=%s" % config_hash)
346                 log.debug("Updating config hash for %s, config_volume=%s hash=%s" % (k, config_volume, config_hash))
347                 infile_data[k]['environment'] = env
348
349     outfile = os.path.join(os.path.dirname(infile), "hashed-" + os.path.basename(infile))
350     with open(outfile, 'w') as out_f:
351         json.dump(infile_data, out_f)
352
353 if not success:
354     sys.exit(1)