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