Merge "docker/internal TLS: spawn extra container for swift's TLS proxy"
[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     sh_script = '/var/lib/docker-puppet/docker-puppet.sh'
156
157     with open(sh_script, 'w') as script_file:
158         os.chmod(script_file.name, 0755)
159         script_file.write("""#!/bin/bash
160         set -ex
161         mkdir -p /etc/puppet
162         cp -a /tmp/puppet-etc/* /etc/puppet
163         rm -Rf /etc/puppet/ssl # not in use and causes permission errors
164         echo "{\\"step\\": $STEP}" > /etc/puppet/hieradata/docker.json
165         TAGS=""
166         if [ -n "$PUPPET_TAGS" ]; then
167             TAGS="--tags \"$PUPPET_TAGS\""
168         fi
169         FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
170
171         # Disables archiving
172         if [ -z "$NO_ARCHIVE" ]; then
173             rm -Rf /var/lib/config-data/${NAME}
174
175             # copying etc should be enough for most services
176             mkdir -p /var/lib/config-data/${NAME}/etc
177             cp -a /etc/* /var/lib/config-data/${NAME}/etc/
178
179             if [ -d /root/ ]; then
180               cp -a /root/ /var/lib/config-data/${NAME}/root/
181             fi
182             if [ -d /var/lib/ironic/tftpboot/ ]; then
183               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
184               cp -a /var/lib/ironic/tftpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/tftpboot/
185             fi
186             if [ -d /var/lib/ironic/httpboot/ ]; then
187               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
188               cp -a /var/lib/ironic/httpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/httpboot/
189             fi
190
191             # apache services may files placed in /var/www/
192             if [ -d /var/www/ ]; then
193              mkdir -p /var/lib/config-data/${NAME}/var/www
194              cp -a /var/www/* /var/lib/config-data/${NAME}/var/www/
195             fi
196         fi
197         """)
198
199     with tempfile.NamedTemporaryFile() as tmp_man:
200         with open(tmp_man.name, 'w') as man_file:
201             man_file.write('include ::tripleo::packages\n')
202             man_file.write(manifest)
203
204         rm_container('docker-puppet-%s' % config_volume)
205         pull_image(config_image)
206
207         dcmd = ['/usr/bin/docker', 'run',
208                 '--user', 'root',
209                 '--name', 'docker-puppet-%s' % config_volume,
210                 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
211                 '--env', 'NAME=%s' % config_volume,
212                 '--env', 'HOSTNAME=%s' % short_hostname(),
213                 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
214                 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
215                 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
216                 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
217                 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
218                 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
219                 '--volume', 'tripleo_logs:/var/log/tripleo/',
220                 # OpenSSL trusted CA injection
221                 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
222                 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
223                 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
224                 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
225                 # script injection
226                 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
227
228         for volume in volumes:
229             if volume:
230                 dcmd.extend(['--volume', volume])
231
232         dcmd.extend(['--entrypoint', sh_script])
233
234         env = {}
235         # NOTE(flaper87): Always copy the DOCKER_* environment variables as
236         # they contain the access data for the docker daemon.
237         for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
238             env[k] = os.environ.get(k)
239
240         if os.environ.get('NET_HOST', 'false') == 'true':
241             log.debug('NET_HOST enabled')
242             dcmd.extend(['--net', 'host', '--volume',
243                          '/etc/hosts:/etc/hosts:ro'])
244         dcmd.append(config_image)
245         log.debug('Running docker command: %s' % ' '.join(dcmd))
246
247         subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
248                                    stderr=subprocess.PIPE, env=env)
249         cmd_stdout, cmd_stderr = subproc.communicate()
250         if cmd_stdout:
251             log.debug(cmd_stdout)
252         if cmd_stderr:
253             log.debug(cmd_stderr)
254         if subproc.returncode != 0:
255             log.error('Failed running docker-puppet.py for %s' % config_volume)
256         rm_container('docker-puppet-%s' % config_volume)
257         return subproc.returncode
258
259 # Holds all the information for each process to consume.
260 # Instead of starting them all linearly we run them using a process
261 # pool.  This creates a list of arguments for the above function
262 # to consume.
263 process_map = []
264
265 for config_volume in configs:
266
267     service = configs[config_volume]
268     puppet_tags = service[1] or ''
269     manifest = service[2] or ''
270     config_image = service[3] or ''
271     volumes = service[4] if len(service) > 4 else []
272
273     if puppet_tags:
274         puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
275     else:
276         puppet_tags = "file,file_line,concat,augeas"
277
278     process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
279
280 for p in process_map:
281     log.debug('- %s' % p)
282
283 # Fire off processes to perform each configuration.  Defaults
284 # to the number of CPUs on the system.
285 p = multiprocessing.Pool(process_count)
286 returncodes = list(p.map(mp_puppet_config, process_map))
287 config_volumes = [pm[0] for pm in process_map]
288 success = True
289 for returncode, config_volume in zip(returncodes, config_volumes):
290     if returncode != 0:
291         log.error('ERROR configuring %s' % config_volume)
292         success = False
293
294 if not success:
295     sys.exit(1)