← Back to team overview

cloud-init-dev team mailing list archive

[Merge] ~prometheanfire/cloud-init:fix-gentoo-networking into cloud-init:master

 

Matthew Thode has proposed merging ~prometheanfire/cloud-init:fix-gentoo-networking into cloud-init:master.

Requested reviews:
  cloud init development team (cloud-init-dev)

For more details, see:
https://code.launchpad.net/~prometheanfire/cloud-init/+git/cloud-init/+merge/303577
-- 
Your team cloud init development team is requested to review the proposed merge of ~prometheanfire/cloud-init:fix-gentoo-networking into cloud-init:master.
diff --git a/cloudinit/distros/gentoo.py b/cloudinit/distros/gentoo.py
index 6267dd6..704a29a 100644
--- a/cloudinit/distros/gentoo.py
+++ b/cloudinit/distros/gentoo.py
@@ -1,8 +1,10 @@
 # vi: ts=4 expandtab
 #
 #    Copyright (C) 2014 Rackspace, US Inc.
+#    Copyright (C) 2016 Matthew Thode.
 #
 #    Author: Nate House <nathan.house@xxxxxxxxxxxxx>
+#    Author: Matthew Thode <prometheanfire@xxxxxxxxxx>
 #
 #    This program is free software: you can redistribute it and/or modify
 #    it under the terms of the GNU General Public License version 3, as
@@ -21,6 +23,7 @@ from cloudinit import helpers
 from cloudinit import log as logging
 from cloudinit import util
 
+from cloudinit.distros import net_util
 from cloudinit.distros.parsers.hostname import HostnameConf
 
 from cloudinit.settings import PER_INSTANCE
@@ -29,9 +32,11 @@ LOG = logging.getLogger(__name__)
 
 
 class Distro(distros.Distro):
-    locale_conf_fn = "/etc/locale.gen"
-    network_conf_fn = "/etc/conf.d/net"
-    init_cmd = ['']  # init scripts
+    locale_conf_fn = '/etc/locale.gen'
+    network_conf_fn = '/etc/conf.d/net'
+    resolve_conf_fn = '/etc/resolv.conf'
+    hostname_conf_fn = '/etc/conf.d/hostname'
+    init_cmd = ['service']  # init scripts
 
     def __init__(self, name, cfg, paths):
         distros.Distro.__init__(self, name, cfg, paths)
@@ -50,7 +55,7 @@ class Distro(distros.Distro):
         # "" provides trailing newline during join
         lines = [
             util.make_header(),
-            'LANG="%s"' % (locale),
+            'LANG="%s"' % locale,
             "",
         ]
         util.write_file(out_fn, "\n".join(lines))
@@ -60,8 +65,67 @@ class Distro(distros.Distro):
         self.package_command('', pkgs=pkglist)
 
     def _write_network(self, settings):
-        util.write_file(self.network_conf_fn, settings)
-        return ['all']
+        entries = net_util.translate_network(settings)
+        LOG.debug("Translated ubuntu style network settings %s into %s",
+                  settings, entries)
+        dev_names = entries.keys()
+        nameservers = []
+
+        for (dev, info) in entries.items():
+            if 'dns-nameservers' in info:
+                nameservers.extend(info['dns-nameservers'])
+            if dev == 'lo':
+                continue
+            net_fn = self.network_conf_fn + '.' + dev
+            dns_nameservers = info.get('dns-nameservers')
+            if isinstance(dns_nameservers, (list, tuple)):
+                dns_nameservers = str(tuple(dns_nameservers)).replace(',', '')
+            # eth0, {'auto': True, 'ipv6': {}, 'bootproto': 'dhcp'}
+            # lo, {'dns-nameservers': ['10.0.1.3'], 'ipv6': {}, 'auto': True}
+            results = ''
+            if info.get('bootproto') == 'dhcp':
+                results += """config_{name}="dhcp\"""".format(name=dev)
+            else:
+                results += """config_{name}="{ip_address} netmask {netmask}"
+mac_{name}="{hwaddr}"\n""".format(
+                    name=dev,
+                    ip_address=info.get('address'),
+                    netmask=info.get('netmask'),
+                    hwaddr=info.get('hwaddress')
+                )
+                results += """routes_{name}="default via {gateway}"\n""".format(
+                    name=dev,
+                    gateway=info.get('gateway')
+                )
+            if info.get('dns-nameservers'):
+                results += """dns_servers_{name}="{dnsservers}"\n""".format(
+                    name=dev,
+                    dnsservers=dns_nameservers)
+            util.write_file(net_fn, results)
+            self._create_network_symlink(dev)
+            if info.get('auto'):
+                cmd = ['rc-update', 'add', 'net.{name}'.format(name=dev),
+                       'default']
+                try:
+                    (_out, err) = util.subp(cmd)
+                    if len(err):
+                        LOG.warn("Running %s resulted in stderr output: %s",
+                                 cmd, err)
+                except util.ProcessExecutionError:
+                    util.logexc(LOG, "Running interface command %s failed",
+                                cmd)
+
+        if nameservers:
+            util.write_file(self.resolve_conf_fn,
+                            convert_resolv_conf(nameservers))
+
+        return dev_names
+
+    @staticmethod
+    def _create_network_symlink(interface_name):
+        file_path = '/etc/init.d/net.{name}'.format(name=interface_name)
+        if not util.is_link(file_path):
+            util.sym_link('/etc/init.d/net.lo', file_path)
 
     def _bring_up_interface(self, device_name):
         cmd = ['/etc/init.d/net.%s' % device_name, 'restart']
@@ -108,13 +172,16 @@ class Distro(distros.Distro):
         if not conf:
             conf = HostnameConf('')
         conf.set_hostname(your_hostname)
-        util.write_file(out_fn, conf, 0o644)
+        gentoo_hostname_config = 'hostname="%s"' % conf
+        gentoo_hostname_config = gentoo_hostname_config.replace('\n', '')
+        util.write_file(out_fn, gentoo_hostname_config, 0o644)
 
     def _read_system_hostname(self):
         sys_hostname = self._read_hostname(self.hostname_conf_fn)
-        return (self.hostname_conf_fn, sys_hostname)
+        return self.hostname_conf_fn, sys_hostname
 
-    def _read_hostname_conf(self, filename):
+    @staticmethod
+    def _read_hostname_conf(filename):
         conf = HostnameConf(util.load_file(filename))
         conf.parse()
         return conf
@@ -137,7 +204,7 @@ class Distro(distros.Distro):
         if pkgs is None:
             pkgs = []
 
-        cmd = ['emerge']
+        cmd = list('emerge')
         # Redirect output
         cmd.append("--quiet")
 
@@ -158,3 +225,12 @@ class Distro(distros.Distro):
     def update_package_sources(self):
         self._runner.run("update-sources", self.package_command,
                          ["-u", "world"], freq=PER_INSTANCE)
+
+
+def convert_resolv_conf(settings):
+    """Returns a settings string formatted for resolv.conf."""
+    result = ''
+    if isinstance(settings, list):
+        for ns in settings:
+            result += 'nameserver %s\n' % ns
+    return result
diff --git a/cloudinit/util.py b/cloudinit/util.py
index db80ca9..9c89de6 100644
--- a/cloudinit/util.py
+++ b/cloudinit/util.py
@@ -1639,6 +1639,11 @@ def get_builtin_cfg():
     return obj_copy.deepcopy(CFG_BUILTIN)
 
 
+def is_link(path):
+    LOG.debug("Testing if a link exists for %s", path)
+    return os.path.islink(path)
+
+
 def sym_link(source, link, force=False):
     LOG.debug("Creating symbolic link from %r => %r", link, source)
     if force and os.path.exists(link):
diff --git a/sysvinit/gentoo/cloud-config b/sysvinit/gentoo/cloud-config
index b0fa786..5618472 100644
--- a/sysvinit/gentoo/cloud-config
+++ b/sysvinit/gentoo/cloud-config
@@ -1,4 +1,4 @@
-#!/sbin/runscript
+#!/sbin/openrc-run
 
 depend() {
   after cloud-init-local
diff --git a/sysvinit/gentoo/cloud-final b/sysvinit/gentoo/cloud-final
index b457a35..a9bf01f 100644
--- a/sysvinit/gentoo/cloud-final
+++ b/sysvinit/gentoo/cloud-final
@@ -1,4 +1,4 @@
-#!/sbin/runscript
+#!/sbin/openrc-run
 
 depend() {
   after cloud-config
diff --git a/sysvinit/gentoo/cloud-init b/sysvinit/gentoo/cloud-init
index 9ab64ad..5afc0f2 100644
--- a/sysvinit/gentoo/cloud-init
+++ b/sysvinit/gentoo/cloud-init
@@ -1,4 +1,4 @@
-#!/sbin/runscript
+#!/sbin/openrc-run
 # add depends for network, dns, fs etc
 depend() {
   after cloud-init-local
diff --git a/sysvinit/gentoo/cloud-init-local b/sysvinit/gentoo/cloud-init-local
index 9d47263..9bd0b56 100644
--- a/sysvinit/gentoo/cloud-init-local
+++ b/sysvinit/gentoo/cloud-init-local
@@ -1,4 +1,4 @@
-#!/sbin/runscript
+#!/sbin/openrc-run
 
 depend() {
   after localmount

Follow ups