|
17 | 17 |
|
18 | 18 | ''' |
19 | 19 |
|
| 20 | +from scompose.templates import get_template |
20 | 21 | from scompose.logger import bot |
21 | | -from scompose.utils import read_yaml |
| 22 | +from scompose.utils import ( |
| 23 | + read_yaml, |
| 24 | + read_file, |
| 25 | + write_file |
| 26 | +) |
22 | 27 | from spython.main import get_client |
23 | 28 | from .instance import Instance |
24 | 29 | import json |
@@ -158,6 +163,50 @@ def parse(self): |
158 | 163 | for _, instance in self.instances.items(): |
159 | 164 | instance.set_volumes_from(self.instances) |
160 | 165 |
|
| 166 | +# Networking |
| 167 | + |
| 168 | + |
| 169 | + def create_hosts(self, name, depends_on): |
| 170 | + '''create a hosts file to bind to all containers, where we define the |
| 171 | + correct hostnames to correspond with the ip addresses created. |
| 172 | +
|
| 173 | + Note: This function is terrible. Singularity should easily expose |
| 174 | + these addresses. |
| 175 | + ''' |
| 176 | + template = read_file(get_template('hosts')) |
| 177 | + hosts_file = os.path.join(self.working_dir, 'etc.hosts.%s' % name) |
| 178 | + hosts_basename = os.path.basename(hosts_file) |
| 179 | + |
| 180 | + for _, instance in self.instances.items(): |
| 181 | + if instance.name in depends_on: |
| 182 | + if self.sudo: |
| 183 | + if instance.exists(): |
| 184 | + result = self.client.execute(image=instance.instance.get_uri(), |
| 185 | + command=['hostname', '-I'], |
| 186 | + return_result=True, |
| 187 | + sudo=self.sudo) |
| 188 | + |
| 189 | + # Busybox won't have hostname -I |
| 190 | + if result['return_code'] != 0: |
| 191 | + cmd = "ip -4 --oneline address show up eth0" |
| 192 | + result = self.client.execute(image=instance.instance.get_uri(), |
| 193 | + command=cmd, |
| 194 | + return_result=True, |
| 195 | + sudo=self.sudo) |
| 196 | + |
| 197 | + ip_address = result['message'].strip('\n').strip() |
| 198 | + |
| 199 | + # Clean up busybox output |
| 200 | + if "inet" in ip_address: |
| 201 | + ip_address = re.match('.+ inet (?P<address>.+)/', ip_address).groups()[0] |
| 202 | + else: |
| 203 | + ip_address = '127.0.1.1' |
| 204 | + |
| 205 | + template = ['%s\t%s\n' % (ip_address, instance.name)] + template |
| 206 | + instance.volumes.append('%s:/etc/hosts' % hosts_basename) |
| 207 | + write_file(hosts_file, template) |
| 208 | + |
| 209 | + |
161 | 210 | # Commands |
162 | 211 |
|
163 | 212 | def shell(self, name): |
@@ -235,6 +284,9 @@ def _create(self, names, command="create", writable_tmpfs=False): |
235 | 284 | count += 1 |
236 | 285 | continue |
237 | 286 |
|
| 287 | + # Create a hosts file for the instance based on depends |
| 288 | + self.create_hosts(instance.name, created) |
| 289 | + |
238 | 290 | # If we get here, execute command and add to list |
239 | 291 | getattr(instance, command)(self.working_dir, writable_tmpfs) |
240 | 292 | created.append(instance.name) |
|
0 commit comments