renaming SliceAttribute into SliceTag and InterfaceSetting into InterfaceTag
[bootmanager.git] / source / steps / WriteNetworkConfig.py
index 4e8518a..cc6f7d6 100644 (file)
@@ -1,5 +1,6 @@
-#!/usr/bin/python2
-
+#!/usr/bin/python
+# $Id$
+#
 # Copyright (c) 2003 Intel Corporation
 # All rights reserved.
 #
@@ -8,24 +9,27 @@
 # expected /proc/partitions format
 
 import os, string
+import traceback
 
-from Exceptions import *
 import utils
+import urlparse
+import httplib
+
+from Exceptions import *
 import BootServerRequest
 import ModelOptions
-import urlparse
 import BootAPI
 
 def Run( vars, log ):
     """
     Write out the network configuration for this machine:
     /etc/hosts
-    /etc/sysconfig/network-scripts/ifcfg-eth0
+    /etc/sysconfig/network-scripts/ifcfg-<ifname>
     /etc/resolv.conf (if applicable)
     /etc/sysconfig/network
 
     The values to be used for the network settings are to be set in vars
-    in the variable 'NETWORK_SETTINGS', which is a dictionary
+    in the variable 'INTERFACE_SETTINGS', which is a dictionary
     with keys:
 
      Key               Used by this function
@@ -46,10 +50,9 @@ def Run( vars, log ):
 
     Expect the following variables from the store:
     SYSIMG_PATH             the path where the system image will be mounted
-                            (always starts with TEMP_PATH)
-    NETWORK_SETTINGS  A dictionary of the values from the network
-                                configuration file
-    NODE_NETWORKS           All the network associated with this node
+                                (always starts with TEMP_PATH)
+    INTERFACES              All the interfaces associated with this node
+    INTERFACE_SETTINGS      dictionary 
     Sets the following variables:
     None
     """
@@ -68,39 +71,31 @@ def Run( vars, log ):
 
 
     try:
-        network_settings= vars['NETWORK_SETTINGS']
+        INTERFACE_SETTINGS= vars['INTERFACE_SETTINGS']
     except KeyError, e:
-        raise BootManagerException, "No network settings found in vars."
+        raise BootManagerException, "No interface settings found in vars."
 
     try:
-        hostname= network_settings['hostname']
-        domainname= network_settings['domainname']
-        method= network_settings['method']
-        ip= network_settings['ip']
-        gateway= network_settings['gateway']
-        network= network_settings['network']
-        netmask= network_settings['netmask']
-        dns1= network_settings['dns1']
-        mac= network_settings['mac']
+        hostname= INTERFACE_SETTINGS['hostname']
+        domainname= INTERFACE_SETTINGS['domainname']
+        method= INTERFACE_SETTINGS['method']
+        ip= INTERFACE_SETTINGS['ip']
+        gateway= INTERFACE_SETTINGS['gateway']
+        network= INTERFACE_SETTINGS['network']
+        netmask= INTERFACE_SETTINGS['netmask']
+        dns1= INTERFACE_SETTINGS['dns1']
+        mac= INTERFACE_SETTINGS['mac']
     except KeyError, e:
-        raise BootManagerException, "Missing value %s in network settings." % str(e)
-
-    try:
-        dns2= ''
-        dns2= network_settings['dns2']
-    except KeyError, e:
-        pass
+        raise BootManagerException, "Missing value %s in interface settings." % str(e)
 
+    # dns2 is not required to be set
+    dns2 = INTERFACE_SETTINGS.get('dns2','')
 
     # Node Manager needs at least PLC_API_HOST and PLC_BOOT_HOST
     log.write("Writing /etc/planetlab/plc_config\n")
     utils.makedirs("%s/etc/planetlab" % SYSIMG_PATH)
     plc_config = file("%s/etc/planetlab/plc_config" % SYSIMG_PATH, "w")
 
-    bs= BootServerRequest.BootServerRequest()
-    if bs.BOOTSERVER_CERTS:
-        print >> plc_config, "PLC_BOOT_HOST='%s'" % bs.BOOTSERVER_CERTS.keys()[0]
-
     api_url = vars['BOOT_API_SERVER']
     (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(api_url)
     parts = netloc.split(':')
@@ -109,9 +104,23 @@ def Run( vars, log ):
         port = parts[1]
     else:
         port = '80'
-    print >> plc_config, "PLC_API_HOST='%s'" % host
-    print >> plc_config, "PLC_API_PORT='%s'" % port
-    print >> plc_config, "PLC_API_PATH='%s'" % path
+    try:
+        log.write("getting via https://%s/PlanetLabConf/get_plc_config.php " % host)
+        bootserver = httplib.HTTPSConnection(host, int(port))
+        bootserver.connect()
+        bootserver.request("GET","https://%s/PlanetLabConf/get_plc_config.php" % host)
+        plc_config.write("%s" % bootserver.getresponse().read())
+        bootserver.close()
+        log.write("Done\n")
+    except :
+        log.write(" .. Failed.  Using old method. -- stack trace follows\n")
+        traceback.print_exc(file=log.OutputFile)
+        bs= BootServerRequest.BootServerRequest()
+        if bs.BOOTSERVER_CERTS:
+            print >> plc_config, "PLC_BOOT_HOST='%s'" % bs.BOOTSERVER_CERTS.keys()[0]
+        print >> plc_config, "PLC_API_HOST='%s'" % host
+        print >> plc_config, "PLC_API_PORT='%s'" % port
+        print >> plc_config, "PLC_API_PATH='%s'" % path
 
     plc_config.close()
 
@@ -145,49 +154,89 @@ def Run( vars, log ):
     network_file.close()
     network_file= None
 
-    interface = 1
-    for network in vars['NODE_NETWORKS']:
+    interfaces = {}
+    interface_count = 1
+    for interface in vars['INTERFACES']:
         if method == "static" or method == "dhcp":
-            if network['is_primary'] == 1:
+            if interface['is_primary'] == 1:
                 ifnum = 0
             else:
-                ifnum = interface
-                interface += 1
-
-            path = "%s/etc/sysconfig/network-scripts/ifcfg-eth%d" % (
-                   SYSIMG_PATH, ifnum)
-            f = file(path, "w")
-            log.write("Writing %s\n" % path.replace(SYSIMG_PATH, ""))
-
-            f.write("DEVICE=eth%d\n" % ifnum)
-            f.write("HWADDR=%s\n" % network['mac'])
-            f.write("ONBOOT=yes\n")
-            f.write("USERCTL=no\n")
-
-            if network['method'] == "static":
-                f.write("BOOTPROTO=static\n")
-                f.write("IPADDR=%s\n" % network['ip'])
-                f.write("NETMASK=%s\n" % network['netmask'])
-
-            elif network['method'] == "dhcp":
-                f.write("BOOTPROTO=dhcp\n")
-                if network['hostname']:
-                    f.write("DHCP_HOSTNAME=%s\n" % network['hostname'])
+                ifnum = interface_count
+                interface_count += 1
+
+            inter = {}
+            if interface['mac']:
+                inter['HWADDR'] = interface['mac']
+
+            if interface['method'] == "static":
+                inter['BOOTPROTO'] = "static"
+                inter['IPADDR'] = interface['ip']
+                inter['NETMASK'] = interface['netmask']
+
+            elif interface['method'] == "dhcp":
+                inter['BOOTPROTO'] = "dhcp"
+                if interface['hostname']:
+                    inter['DHCP_HOSTNAME'] = interface['hostname']
+                else:
+                    inter['DHCP_HOSTNAME'] = hostname 
+                if not interface['is_primary']:
+                    inter['DHCLIENTARGS'] = "-R subnet-mask"
+
+            alias = ""
+            ifname=None
+            if len(interface['interface_tag_ids']) > 0:
+                tags =  BootAPI.call_api_function(vars, "GetInterfaceTags",
+                                                  ({'interface_tag_id': interface['interface_tag_ids']},))
+                for tag in tags:
+                    # to explicitly set interface name
+                    if   tag['tagname'].upper() == "IFNAME":
+                        ifname=tag['value']
+                    elif tag['tagname'].upper() == "DRIVER":
+                        # xxx not sure how to do that yet - probably add a line in modprobe.conf
+                        pass
+                    elif tag['tagname'].upper() == "ALIAS":
+                        alias = ":" + tag['value']
+
+                    # a hack for testing before a new setting is hardcoded here
+                    # use the backdoor tag and put as a value 'var=value'
+                    elif tag['tagname'].upper() == "BACKDOOR":
+                        [var,value]=tag['value'].split('=',1)
+                        inter[var]=value
+
+                    elif tag['tagname'].lower() in \
+                            [  "mode", "essid", "nw", "freq", "channel", "sens", "rate",
+                               "key", "key1", "key2", "key3", "key4", "securitymode", 
+                               "iwconfig", "iwpriv" ] :
+                        inter [tag['tagname'].upper()] = tag['value']
+                        inter ['TYPE']='Wireless'
+                    else:
+                        log.write("Warning - ignored tag named %s\n"%tag['tagname'])
+
+            if alias and 'HWADDR' in inter:
+                for (dev, i) in interfaces.iteritems():
+                    if i['HWADDR'] == inter['HWADDR']:
+                        break
+                del inter['HWADDR']
+                interfaces[dev + alias] =inter 
+                interface_count -= 1
+            else:
+                if not ifname:
+                    ifname="eth%d" % ifnum
                 else:
-                    f.write("DHCP_HOSTNAME=%s\n" % hostname)
-                if network['is_primary'] != 1:
-                    f.write("DHCLIENTARGS='-R subnet-mask'\n")
-
-            if len(network['nodenetwork_setting_ids']) > 0:
-                settings = BootAPI.call_api_function(vars, "GetNodeNetworkSettings",
-                    ({'nodenetwork_setting_id': network['nodenetwork_setting_ids']},))
-                for setting in settings:
-                    if setting['category'].upper() != "WLAN":
-                        continue
-                    if setting['name'].upper() == "SSID":
-                        f.write("ESSID=%s\n" % setting['value'])
-                    elif sett['name'].upper() == "IWCONFIG":
-                        f.write("IWCONFIG=%s\n" % setting['value'])
-
-            f.close()
+                    interface_count -= 1
+                interfaces[ifname] =inter 
+
+    for (dev, inter) in interfaces.iteritems():
+        path = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (
+               SYSIMG_PATH, dev)
+        f = file(path, "w")
+        log.write("Writing %s\n" % path.replace(SYSIMG_PATH, ""))
+
+        f.write("DEVICE=%s\n" % dev)
+        f.write("ONBOOT=yes\n")
+        f.write("USERCTL=no\n")
+        for (key, val) in inter.iteritems():
+            f.write('%s="%s"\n' % (key, val))
+
+        f.close()