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