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
7 # http://www.apache.org/licenses/LICENSE-2.0
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
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.
27 import multiprocessing
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)
37 # this is to match what we do in deployed-server
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()
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()
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()
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()
78 cmd_stderr != 'Error response from daemon: ' \
79 'No such container: {}\n'.format(name):
82 process_count = int(os.environ.get('PROCESS_COUNT',
83 multiprocessing.cpu_count()))
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)
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.
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.
103 for service in (json_data or []):
106 if isinstance(service, dict):
108 service.get('config_volume'),
109 service.get('puppet_tags'),
110 service.get('step_config'),
111 service.get('config_image'),
112 service.get('volumes', []),
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 []
121 if not manifest or not config_image:
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")
134 configs[config_volume][1] = '%s,%s' % (configs[config_volume][1],
137 configs[config_volume][2] = '%s\n%s' % (configs[config_volume][2],
139 if configs[config_volume][3] != config_image:
140 log.warn("Config containers do not match even though"
141 " shared volumes are the same!")
143 log.info("Adding new service")
144 configs[config_volume] = service
146 log.info('Service compilation completed.')
148 def mp_puppet_config((config_volume, puppet_tags, manifest, config_image, volumes)):
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'
157 with open(sh_script, 'w') as script_file:
158 os.chmod(script_file.name, 0755)
159 script_file.write("""#!/bin/bash
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
166 if [ -n "$PUPPET_TAGS" ]; then
167 TAGS="--tags \"$PUPPET_TAGS\""
169 FACTER_hostname=$HOSTNAME FACTER_uuid=docker /usr/bin/puppet apply --verbose $TAGS /etc/config.pp
172 if [ -z "$NO_ARCHIVE" ]; then
173 rm -Rf /var/lib/config-data/${NAME}
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/
179 if [ -d /root/ ]; then
180 cp -a /root/ /var/lib/config-data/${NAME}/root/
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/
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/
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/
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)
204 rm_container('docker-puppet-%s' % config_volume)
205 pull_image(config_image)
207 dcmd = ['/usr/bin/docker', 'run',
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',
226 '--volume', '%s:%s:rw' % (sh_script, sh_script) ]
228 for volume in volumes:
230 dcmd.extend(['--volume', volume])
232 dcmd.extend(['--entrypoint', sh_script])
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)
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))
247 subproc = subprocess.Popen(dcmd, stdout=subprocess.PIPE,
248 stderr=subprocess.PIPE, env=env)
249 cmd_stdout, cmd_stderr = subproc.communicate()
251 log.debug(cmd_stdout)
253 log.debug(cmd_stderr)
254 if subproc.returncode != 0:
255 log.error('Failed running docker-puppet.py for %s' % config_volume)
257 # only delete successful runs, for debugging
258 rm_container('docker-puppet-%s' % config_volume)
259 return subproc.returncode
261 # Holds all the information for each process to consume.
262 # Instead of starting them all linearly we run them using a process
263 # pool. This creates a list of arguments for the above function
267 for config_volume in configs:
269 service = configs[config_volume]
270 puppet_tags = service[1] or ''
271 manifest = service[2] or ''
272 config_image = service[3] or ''
273 volumes = service[4] if len(service) > 4 else []
276 puppet_tags = "file,file_line,concat,augeas,%s" % puppet_tags
278 puppet_tags = "file,file_line,concat,augeas"
280 process_map.append([config_volume, puppet_tags, manifest, config_image, volumes])
282 for p in process_map:
283 log.debug('- %s' % p)
285 # Fire off processes to perform each configuration. Defaults
286 # to the number of CPUs on the system.
287 p = multiprocessing.Pool(process_count)
288 returncodes = list(p.map(mp_puppet_config, process_map))
289 config_volumes = [pm[0] for pm in process_map]
291 for returncode, config_volume in zip(returncodes, config_volumes):
293 log.error('ERROR configuring %s' % config_volume)