bfc29b41a770e8ce715b10aff17eded8d7b5f49e
[bootmanager.git] / source / steps / WriteNetworkConfig.py
1 #!/usr/bin/python
2 #
3 # Copyright (c) 2003 Intel Corporation
4 # All rights reserved.
5 #
6 # Copyright (c) 2004-2006 The Trustees of Princeton University
7 # All rights reserved.
8 # expected /proc/partitions format
9
10 import os, string
11 import traceback
12
13 import utils
14 import urlparse
15 import httplib
16
17 from Exceptions import *
18 import BootServerRequest
19 import ModelOptions
20 import BootAPI
21 import plnet
22
23 class BootAPIWrap:
24     def __init__(self, vars):
25         self.vars = vars
26     def call(self, func, *args):
27         return BootAPI.call_api_function(self.vars, func, args)
28     def __getattr__(self, func):
29         return lambda *args: self.call(func, *args)
30
31 class logger:
32     def __init__(self, log):
33         self._log = log
34     def log(self, msg, level=3):
35         self._log.write(msg + "\n")
36     def verbose(self, msg):
37         self.log(msg, 0)
38
39 def Run( vars, log ):
40     """
41     Write out the network configuration for this machine:
42     /etc/hosts
43     /etc/sysconfig/network-scripts/ifcfg-<ifname>
44     /etc/resolv.conf (if applicable)
45     /etc/sysconfig/network
46
47     The values to be used for the network settings are to be set in vars
48     in the variable 'INTERFACE_SETTINGS', which is a dictionary
49     with keys:
50
51      Key               Used by this function
52      -----------------------------------------------
53      node_id
54      node_key
55      method            x
56      ip                x
57      mac               x (optional)
58      gateway           x
59      network           x
60      broadcast         x
61      netmask           x
62      dns1              x
63      dns2              x (optional)
64      hostname          x
65      domainname        x
66
67     Expect the following variables from the store:
68     SYSIMG_PATH             the path where the system image will be mounted
69                                 (always starts with TEMP_PATH)
70     INTERFACES              All the interfaces associated with this node
71     INTERFACE_SETTINGS      dictionary 
72     Sets the following variables:
73     None
74     """
75
76     log.write( "\n\nStep: Install: Writing Network Configuration files.\n" )
77
78     try:
79         SYSIMG_PATH= vars["SYSIMG_PATH"]
80         if SYSIMG_PATH == "":
81             raise ValueError, "SYSIMG_PATH"
82
83     except KeyError, var:
84         raise BootManagerException, "Missing variable in vars: %s\n" % var
85     except ValueError, var:
86         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
87
88
89     try:
90         INTERFACE_SETTINGS= vars['INTERFACE_SETTINGS']
91     except KeyError, e:
92         raise BootManagerException, "No interface settings found in vars."
93
94     try:
95         hostname= INTERFACE_SETTINGS['hostname']
96         domainname= INTERFACE_SETTINGS['domainname']
97         method= INTERFACE_SETTINGS['method']
98         ip= INTERFACE_SETTINGS['ip']
99         gateway= INTERFACE_SETTINGS['gateway']
100         network= INTERFACE_SETTINGS['network']
101         netmask= INTERFACE_SETTINGS['netmask']
102         dns1= INTERFACE_SETTINGS['dns1']
103         mac= INTERFACE_SETTINGS['mac']
104     except KeyError, e:
105         raise BootManagerException, "Missing value %s in interface settings." % str(e)
106
107     # dns2 is not required to be set
108     dns2 = INTERFACE_SETTINGS.get('dns2','')
109
110     # Node Manager needs at least PLC_API_HOST and PLC_BOOT_HOST
111     log.write("Writing /etc/planetlab/plc_config\n")
112     utils.makedirs("%s/etc/planetlab" % SYSIMG_PATH)
113     plc_config = file("%s/etc/planetlab/plc_config" % SYSIMG_PATH, "w")
114
115     api_url = vars['BOOT_API_SERVER']
116     (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(api_url)
117     parts = netloc.split(':')
118     host = parts[0]
119     if len(parts) > 1:
120         port = parts[1]
121     else:
122         port = '80'
123     try:
124         log.write("getting via https://%s/PlanetLabConf/get_plc_config.php " % host)
125         bootserver = httplib.HTTPSConnection(host, int(port))
126         bootserver.connect()
127         bootserver.request("GET","https://%s/PlanetLabConf/get_plc_config.php" % host)
128         plc_config.write("%s" % bootserver.getresponse().read())
129         bootserver.close()
130         log.write("Done\n")
131     except :
132         log.write(" .. Failed.  Using old method. -- stack trace follows\n")
133         traceback.print_exc(file=log.OutputFile)
134         bs= BootServerRequest.BootServerRequest(vars)
135         if bs.BOOTSERVER_CERTS:
136             print >> plc_config, "PLC_BOOT_HOST='%s'" % bs.BOOTSERVER_CERTS.keys()[0]
137         print >> plc_config, "PLC_API_HOST='%s'" % host
138         print >> plc_config, "PLC_API_PORT='%s'" % port
139         print >> plc_config, "PLC_API_PATH='%s'" % path
140
141     plc_config.close()
142
143
144     log.write( "Writing /etc/hosts\n" )
145     hosts_file= file("%s/etc/hosts" % SYSIMG_PATH, "w" )    
146     hosts_file.write( "127.0.0.1       localhost\n" )
147     if method == "static":
148         hosts_file.write( "%s %s.%s\n" % (ip, hostname, domainname) )
149     hosts_file.close()
150     hosts_file= None
151     
152     data =  {'hostname': '%s.%s' % (hostname, domainname),
153              'networks': vars['INTERFACES']}
154     plnet.InitInterfaces(logger(log), BootAPIWrap(vars), data, SYSIMG_PATH,
155                          True, "BootManager")
156