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