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