Merge "Make upgrade steps unconditional to fix broken dependencies"
[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 json
22 import logging
23 import os
24 import subprocess
25 import sys
26 import tempfile
27 import multiprocessing
28
29 log = logging.getLogger()
30 log.setLevel(logging.DEBUG)
31 ch = logging.StreamHandler(sys.stdout)
32 ch.setLevel(logging.DEBUG)
33 formatter = logging.Formatter('%(asctime)s %(levelname)s: %(message)s')
34 ch.setFormatter(formatter)
35 log.addHandler(ch)
36
37 # this is to match what we do in deployed-server
38 def short_hostname():
39     subproc = subprocess.Popen(['hostname', '-s'],
40                                stdout=subprocess.PIPE,
41                                stderr=subprocess.PIPE)
42     cmd_stdout, cmd_stderr = subproc.communicate()
43     return cmd_stdout.rstrip()
44
45
46 def pull_image(name):
47     log.info('Pulling image: %s' % name)
48     subproc = subprocess.Popen(['/usr/bin/docker', 'pull', name],
49                                stdout=subprocess.PIPE,
50                                stderr=subprocess.PIPE)
51     cmd_stdout, cmd_stderr = subproc.communicate()
52     if cmd_stdout:
53         log.debug(cmd_stdout)
54     if cmd_stderr:
55         log.debug(cmd_stderr)
56
57
58 def rm_container(name):
59     if os.environ.get('SHOW_DIFF', None):
60         log.info('Diffing container: %s' % name)
61         subproc = subprocess.Popen(['/usr/bin/docker', 'diff', name],
62                                    stdout=subprocess.PIPE,
63                                    stderr=subprocess.PIPE)
64         cmd_stdout, cmd_stderr = subproc.communicate()
65         if cmd_stdout:
66             log.debug(cmd_stdout)
67         if cmd_stderr:
68             log.debug(cmd_stderr)
69
70     log.info('Removing container: %s' % name)
71     subproc = subprocess.Popen(['/usr/bin/docker', 'rm', name],
72                                stdout=subprocess.PIPE,
73                                stderr=subprocess.PIPE)
74     cmd_stdout, cmd_stderr = subproc.communicate()
75     if cmd_stdout:
76         log.debug(cmd_stdout)
77     if cmd_stderr and \
78            cmd_stderr != 'Error response from daemon: ' \
79            'No such container: {}\n'.format(name):
80         log.debug(cmd_stderr)
81
82 process_count = int(os.environ.get('PROCESS_COUNT',
83                                    multiprocessing.cpu_count()))
84
85 log.info('Running docker-puppet')
86 config_file = os.environ.get('CONFIG', '/var/lib/docker-puppet/docker-puppet.json')
87 log.debug('CONFIG: %s' % config_file)
88 with open(config_file) as f:
89     json_data = json.load(f)
90
91 # To save time we support configuring 'shared' services at the same
92 # time. For example configuring all of the heat services
93 # in a single container pass makes sense and will save some time.
94 # To support this we merge shared settings together here.
95 #
96 # We key off of config_volume as this should be the same for a
97 # given group of services.  We are also now specifying the container
98 # in which the services should be configured.  This should match
99 # in all instances where the volume name is also the same.
100
101 configs = {}
102
103 for service in (json_data or []):
104     if service is None:
105         continue
106     if isinstance(service, dict):
107         service = [
108             service.get('config_volume'),
109             service.get('puppet_tags'),
110             service.get('step_config'),
111             service.get('config_image'),
112             service.get('volumes', []),
113         ]
114
115     config_volume = service[0] or ''
116     puppet_tags = service[1] or ''
117     manifest = service[2] or ''
118     config_image = service[3] or ''
119     volumes = service[4] if len(service) > 4 else []
120
121     if not manifest or not config_image:
122         continue
123
124     log.debug('config_volume %s' % config_volume)
125     log.debug('puppet_tags %s' % puppet_tags)
126     log.debug('manifest %s' % manifest)
127     log.debug('config_image %s' % config_image)
128     log.debug('volumes %s' % volumes)
129     # We key off of config volume for all configs.
130     if config_volume in configs:
131         # Append puppet tags and manifest.
132         log.info("Existing service, appending puppet tags and manifest")
133         if puppet_tags:
134             configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
135                                                    puppet_tags)
136         if manifest:
137             configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
138                                                     manifest)
139         if configs[config_volume][3] != config_image:
140             log.warn("Config containers do not match even though"
141                      " shared volumes are the same!")
142     else:
143         log.info("Adding new service")
144         configs[config_volume] = service
145
146 log.info('Service compilation completed.')
147
148 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
149
150     log.debug('config_volume %s' % config_volume)
151     log.debug('puppet_tags %s' % puppet_tags)
152     log.debug('manifest %s' % manifest)
153     log.debug('config_image %s' % config_image)
154     log.debug('volumes %s' % volumes)
155     hostname = short_hostname()
156     sh_script = '/var/lib/docker-puppet/docker-puppet-%s.sh' % config_volume
157
158     with open(sh_script, 'w') as script_file:
159         os.chmod(script_file.name, 0755)
160         script_file.write("""#!/bin/bash
161         set -ex
162         mkdir -p /etc/puppet
163         cp -a /tmp/puppet-etc/* /etc/puppet
164         rm -Rf /etc/puppet/ssl # not in use and causes permission errors
165         echo '{"step": %(step)s}' > /etc/puppet/hieradata/docker.json
166         TAGS=""
167         if [ -n "%(puppet_tags)s" ]; then
168             TAGS='--tags "%(puppet_tags)s"'
169         fi
170         FACTER_hostname=%(hostname)s FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
171
172         # Disables archiving
173         if [ -z "%(no_archive)s" ]; then
174             rm -Rf /var/lib/config-data/%(name)s
175
176             # copying etc should be enough for most services
177             mkdir -p /var/lib/config-data/%(name)s/etc
178             cp -a /etc/* /var/lib/config-data/%(name)s/etc/
179
180             if [ -d /root/ ]; then
181               cp -a /root/ /var/lib/config-data/%(name)s/root/
182             fi
183             if [ -d /var/lib/ironic/tftpboot/ ]; then
184               mkdir -p /var/lib/config-data/%(name)s/var/lib/ironic/
185               cp -a /var/lib/ironic/tftpboot/ /var/lib/config-data/%(name)s/var/lib/ironic/tftpboot/
186             fi
187             if [ -d /var/lib/ironic/httpboot/ ]; then
188               mkdir -p /var/lib/config-data/%(name)s/var/lib/ironic/
189               cp -a /var/lib/ironic/httpboot/ /var/lib/config-data/%(name)s/var/lib/ironic/httpboot/
190             fi
191
192             # apache services may files placed in /var/www/
193             if [ -d /var/www/ ]; then
194              mkdir -p /var/lib/config-data/%(name)s/var/www
195              cp -a /var/www/* /var/lib/config-data/%(name)s/var/www/
196             fi
197         fi
198         """ % {'puppet_tags': puppet_tags, 'name': config_volume,
199                'hostname': hostname,
200                'no_archive': os.environ.get('NO_ARCHIVE', ''),
201                'step': os.environ.get('STEP', '6')})
202
203     with tempfile.NamedTemporaryFile() as tmp_man:
204         with open(tmp_man.name, 'w') as man_file:
205             man_file.write('include ::tripleo::packages\n')
206             man_file.write(manifest)
207
208         rm_container('docker-puppet-%s' % config_volume)
209         pull_image(config_image)
210
211         dcmd = ['/usr/bin/docker', 'run',
212                 '--user', 'root',
213                 '--name', 'docker-puppet-%s' % config_volume,
214                 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
215                 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
216                 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
217                 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
218                 '--volume', 'tripleo_logs:/var/log/tripleo/',
219                 # OpenSSL trusted CA injection
220                 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
221                 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
222                 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
223                 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
224                 # script injection
225                 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
226
227         for volume in volumes:
228             if volume:
229                 dcmd.extend(['--volume', volume])
230
231         dcmd.extend(['--entrypoint', sh_script])
232
233         env = {}
234         # NOTE(flaper87): Always copy the DOCKER_* environment variables as
235         # they contain the access data for the docker daemon.
236         for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
237             env[k] = os.environ.get(k)
238
239         if os.environ.get('NET_HOST', 'false') == 'true':
240             log.debug('NET_HOST enabled')
241             dcmd.extend(['--net', 'host', '--volume',
242                          '/etc/hosts:/etc/hosts:ro'])
243         dcmd.append(config_image)
244         log.debug('Running docker command: %s' % ' '.join(dcmd))
245
246         subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
247                                    stderr=subprocess.PIPE, env=env)
248         cmd_stdout, cmd_stderr = subproc.communicate()
249         if cmd_stdout:
250             log.debug(cmd_stdout)
251         if cmd_stderr:
252             log.debug(cmd_stderr)
253         if subproc.returncode != 0:
254             log.error('Failed running docker-puppet.py for %s' % config_volume)
255         rm_container('docker-puppet-%s' % config_volume)
256         return subproc.returncode
257
258 # Holds all the information for each process to consume.
259 # Instead of starting them all linearly we run them using a process
260 # pool.  This creates a list of arguments for the above function
261 # to consume.
262 process_map = []
263
264 for config_volume in configs:
265
266     service = configs[config_volume]
267     puppet_tags = service[1] or ''
268     manifest = service[2] or ''
269     config_image = service[3] or ''
270     volumes = service[4] if len(service) > 4 else []
271
272     if puppet_tags:
273         puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
274     else:
275         puppet_tags = "file,file_line,concat,augeas"
276
277     process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
278
279 for p in process_map:
280     log.debug('- %s' % p)
281
282 # Fire off processes to perform each configuration.  Defaults
283 # to the number of CPUs on the system.
284 p = multiprocessing.Pool(process_count)
285 returncodes = list(p.map(mp_puppet_config, process_map))
286 config_volumes = [pm[0] for pm in process_map]
287 success = True
288 for returncode, config_volume in zip(returncodes, config_volumes):
289     if returncode != 0:
290         log.error('ERROR configuring %s' % config_volume)
291         success = False
292
293 if not success:
294     sys.exit(1)