Change HorizonSecureCookies default to False
[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             # workaround LP1696283
180             mkdir -p /var/lib/config-data/${NAME}/etc/ssh
181             touch /var/lib/config-data/${NAME}/etc/ssh/ssh_known_hosts
182
183             if [ -d /root/ ]; then
184               cp -a /root/ /var/lib/config-data/${NAME}/root/
185             fi
186             if [ -d /var/lib/ironic/tftpboot/ ]; then
187               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
188               cp -a /var/lib/ironic/tftpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/tftpboot/
189             fi
190             if [ -d /var/lib/ironic/httpboot/ ]; then
191               mkdir -p /var/lib/config-data/${NAME}/var/lib/ironic/
192               cp -a /var/lib/ironic/httpboot/ /var/lib/config-data/${NAME}/var/lib/ironic/httpboot/
193             fi
194
195             # apache services may files placed in /var/www/
196             if [ -d /var/www/ ]; then
197              mkdir -p /var/lib/config-data/${NAME}/var/www
198              cp -a /var/www/* /var/lib/config-data/${NAME}/var/www/
199             fi
200         fi
201         """)
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                 '--env', 'PUPPET_TAGS=%s' % puppet_tags,
215                 '--env', 'NAME=%s' % config_volume,
216                 '--env', 'HOSTNAME=%s' % short_hostname(),
217                 '--env', 'NO_ARCHIVE=%s' % os.environ.get('NO_ARCHIVE', ''),
218                 '--env', 'STEP=%s' % os.environ.get('STEP', '6'),
219                 '--volume', '%s:/etc/config.pp:ro' % tmp_man.name,
220                 '--volume', '/etc/puppet/:/tmp/puppet-etc/:ro',
221                 '--volume', '/usr/share/openstack-puppet/modules/:/usr/share/openstack-puppet/modules/:ro',
222                 '--volume', '/var/lib/config-data/:/var/lib/config-data/:rw',
223                 '--volume', 'tripleo_logs:/var/log/tripleo/',
224                 # OpenSSL trusted CA injection
225                 '--volume', '/etc/pki/ca-trust/extracted:/etc/pki/ca-trust/extracted:ro',
226                 '--volume', '/etc/pki/tls/certs/ca-bundle.crt:/etc/pki/tls/certs/ca-bundle.crt:ro',
227                 '--volume', '/etc/pki/tls/certs/ca-bundle.trust.crt:/etc/pki/tls/certs/ca-bundle.trust.crt:ro',
228                 '--volume', '/etc/pki/tls/cert.pem:/etc/pki/tls/cert.pem:ro',
229                 # script injection
230                 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
231
232         for volume in volumes:
233             if volume:
234                 dcmd.extend(['--volume', volume])
235
236         dcmd.extend(['--entrypoint', sh_script])
237
238         env = {}
239         # NOTE(flaper87): Always copy the DOCKER_* environment variables as
240         # they contain the access data for the docker daemon.
241         for k in filter(lambda k: k.startswith('DOCKER'), os.environ.keys()):
242             env[k] = os.environ.get(k)
243
244         if os.environ.get('NET_HOST', 'false') == 'true':
245             log.debug('NET_HOST enabled')
246             dcmd.extend(['--net', 'host', '--volume',
247                          '/etc/hosts:/etc/hosts:ro'])
248         dcmd.append(config_image)
249         log.debug('Running docker command: %s' % ' '.join(dcmd))
250
251         subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
252                                    stderr=subprocess.PIPE, env=env)
253         cmd_stdout, cmd_stderr = subproc.communicate()
254         if cmd_stdout:
255             log.debug(cmd_stdout)
256         if cmd_stderr:
257             log.debug(cmd_stderr)
258         if subproc.returncode != 0:
259             log.error('Failed running docker-puppet.py for %s' % config_volume)
260         else:
261             # only delete successful runs, for debugging
262             rm_container('docker-puppet-%s' % config_volume)
263         return subproc.returncode
264
265 # Holds all the information for each process to consume.
266 # Instead of starting them all linearly we run them using a process
267 # pool.  This creates a list of arguments for the above function
268 # to consume.
269 process_map = []
270
271 for config_volume in configs:
272
273     service = configs[config_volume]
274     puppet_tags = service[1] or ''
275     manifest = service[2] or ''
276     config_image = service[3] or ''
277     volumes = service[4] if len(service) > 4 else []
278
279     if puppet_tags:
280         puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
281     else:
282         puppet_tags = "file,file_line,concat,augeas"
283
284     process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
285
286 for p in process_map:
287     log.debug('- %s' % p)
288
289 # Fire off processes to perform each configuration.  Defaults
290 # to the number of CPUs on the system.
291 p = multiprocessing.Pool(process_count)
292 returncodes = list(p.map(mp_puppet_config, process_map))
293 config_volumes = [pm[0] for pm in process_map]
294 success = True
295 for returncode, config_volume in zip(returncodes, config_volumes):
296     if returncode != 0:
297         log.error('ERROR configuring %s' % config_volume)
298         success = False
299
300 if not success:
301     sys.exit(1)