...
[bootmanager.git] / source / steps / WriteNetworkConfig.py
1 #!/usr/bin/python2
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
22 def Run( vars, log ):
23     """
24     Write out the network configuration for this machine:
25     /etc/hosts
26     /etc/sysconfig/network-scripts/ifcfg-<ifname>
27     /etc/resolv.conf (if applicable)
28     /etc/sysconfig/network
29
30     The values to be used for the network settings are to be set in vars
31     in the variable 'INTERFACE_SETTINGS', which is a dictionary
32     with keys:
33
34      Key               Used by this function
35      -----------------------------------------------
36      node_id
37      node_key
38      method            x
39      ip                x
40      mac               x (optional)
41      gateway           x
42      network           x
43      broadcast         x
44      netmask           x
45      dns1              x
46      dns2              x (optional)
47      hostname          x
48      domainname        x
49
50     Expect the following variables from the store:
51     SYSIMG_PATH             the path where the system image will be mounted
52                                 (always starts with TEMP_PATH)
53     INTERFACES              All the interfaces associated with this node
54     INTERFACE_SETTINGS      dictionary 
55     Sets the following variables:
56     None
57     """
58
59     log.write( "\n\nStep: Install: Writing Network Configuration files.\n" )
60
61     try:
62         SYSIMG_PATH= vars["SYSIMG_PATH"]
63         if SYSIMG_PATH == "":
64             raise ValueError, "SYSIMG_PATH"
65
66     except KeyError, var:
67         raise BootManagerException, "Missing variable in vars: %s\n" % var
68     except ValueError, var:
69         raise BootManagerException, "Variable in vars, shouldn't be: %s\n" % var
70
71
72     try:
73         interface_settings= vars['INTERFACE_SETTINGS']
74     except KeyError, e:
75         raise BootManagerException, "No interface settings found in vars."
76
77     try:
78         hostname= interface_settings['hostname']
79         domainname= interface_settings['domainname']
80         method= interface_settings['method']
81         ip= interface_settings['ip']
82         gateway= interface_settings['gateway']
83         network= interface_settings['network']
84         netmask= interface_settings['netmask']
85         dns1= interface_settings['dns1']
86         mac= interface_settings['mac']
87     except KeyError, e:
88         raise BootManagerException, "Missing value %s in interface settings." % str(e)
89
90     try:
91         dns2= ''
92         dns2= interface_settings['dns2']
93     except KeyError, e:
94         pass
95
96
97     # Node Manager needs at least PLC_API_HOST and PLC_BOOT_HOST
98     log.write("Writing /etc/planetlab/plc_config\n")
99     utils.makedirs("%s/etc/planetlab" % SYSIMG_PATH)
100     plc_config = file("%s/etc/planetlab/plc_config" % SYSIMG_PATH, "w")
101
102     api_url = vars['BOOT_API_SERVER']
103     (scheme, netloc, path, params, query, fragment) = urlparse.urlparse(api_url)
104     parts = netloc.split(':')
105     host = parts[0]
106     if len(parts) > 1:
107         port = parts[1]
108     else:
109         port = '80'
110     try:
111         log.write("getting via https://%s/PlanetLabConf/get_plc_config.php " % host)
112         bootserver = httplib.HTTPSConnection(host, port)
113         bootserver.connect()
114         bootserver.request("GET","https://%s/PlanetLabConf/get_plc_config.php" % host)
115         plc_config.write("%s" % bootserver.getresponse().read())
116         bootserver.close()
117         log.write("Done\n")
118     except :
119         log.write(" .. Failed.  Using old method. -- stack trace follows\n")
120         traceback.print_exc(file=log.OutputFile)
121         bs= BootServerRequest.BootServerRequest()
122         if bs.BOOTSERVER_CERTS:
123             print >> plc_config, "PLC_BOOT_HOST='%s'" % bs.BOOTSERVER_CERTS.keys()[0]
124         print >> plc_config, "PLC_API_HOST='%s'" % host
125         print >> plc_config, "PLC_API_PORT='%s'" % port
126         print >> plc_config, "PLC_API_PATH='%s'" % path
127
128     plc_config.close()
129
130
131     log.write( "Writing /etc/hosts\n" )
132     hosts_file= file("%s/etc/hosts" % SYSIMG_PATH, "w" )    
133     hosts_file.write( "127.0.0.1       localhost\n" )
134     if method == "static":
135         hosts_file.write( "%s %s.%s\n" % (ip, hostname, domainname) )
136     hosts_file.close()
137     hosts_file= None
138     
139
140     if method == "static":
141         log.write( "Writing /etc/resolv.conf\n" )
142         resolv_file= file("%s/etc/resolv.conf" % SYSIMG_PATH, "w" )
143         if dns1 != "":
144             resolv_file.write( "nameserver %s\n" % dns1 )
145         if dns2 != "":
146             resolv_file.write( "nameserver %s\n" % dns2 )
147         resolv_file.write( "search %s\n" % domainname )
148         resolv_file.close()
149         resolv_file= None
150
151     log.write( "Writing /etc/sysconfig/network\n" )
152     network_file= file("%s/etc/sysconfig/network" % SYSIMG_PATH, "w" )
153     network_file.write( "NETWORKING=yes\n" )
154     network_file.write( "HOSTNAME=%s.%s\n" % (hostname, domainname) )
155     if method == "static":
156         network_file.write( "GATEWAY=%s\n" % gateway )
157     network_file.close()
158     network_file= None
159
160     interfaces = {}
161     interface = 1
162     for interface in vars['INTERFACES']:
163         if method == "static" or method == "dhcp":
164             if interface['is_primary'] == 1:
165                 ifnum = 0
166             else:
167                 ifnum = interface
168                 interface += 1
169
170             int = {}
171             if interface['mac']:
172                 int['HWADDR'] = interface['mac']
173
174             if interface['method'] == "static":
175                 int['BOOTPROTO'] = "static"
176                 int['IPADDR'] = interface['ip']
177                 int['NETMASK'] = interface['netmask']
178
179             elif interface['method'] == "dhcp":
180                 int['BOOTPROTO'] = "dhcp"
181                 if interface['hostname']:
182                     int['DHCP_HOSTNAME'] = interface['hostname']
183                 else:
184                     int['DHCP_HOSTNAME'] = hostname
185                 if not interface['is_primary']:
186                     int['DHCLIENTARGS'] = "-R subnet-mask"
187
188             alias = ""
189             ifname=None
190             if len(interface['interface_setting_ids']) > 0:
191                 settings = \
192                     BootAPI.call_api_function(vars, "GetInterfaceSettings",
193                                               ({'interface_setting_id': 
194                                                 interface['interface_setting_ids']},))
195                 for setting in settings:
196                     # to explicitly set interface name
197                     if   setting['name'].upper() == "IFNAME":
198                         ifname=setting['value']
199                     elif setting['name'].upper() == "DRIVER":
200                         # xxx not sure how to do that yet - probably add a line in modprobe.conf
201                         pass
202                     elif setting['name'].upper() == "ALIAS":
203                         alias = ":" + setting['value']
204
205                     # a hack for testing before a new setting is hardcoded here
206                     # use the backdoor setting and put as a value 'var=value'
207                     elif setting['name'].upper() == "BACKDOOR":
208                         [var,value]=setting['value'].split('=',1)
209                         int[var]=value
210
211                     elif setting['name'].lower() in \
212                             [  "mode", "essid", "nw", "freq", "channel", "sens", "rate",
213                                "key", "key1", "key2", "key3", "key4", "securitymode", 
214                                "iwconfig", "iwpriv" ] :
215                         int [setting['name'].upper()] = setting['value']
216                         int ['TYPE']='Wireless'
217                     else:
218                         log.write("Warning - ignored setting named %s\n"%setting['name'])
219
220             if alias and 'HWADDR' in int:
221                 for (dev, i) in interfaces.iteritems():
222                     if i['HWADDR'] == int['HWADDR']:
223                         break
224                 del int['HWADDR']
225                 interfaces[dev + alias] = int
226                 interface -= 1
227             else:
228                 if not ifname:
229                     ifname="eth%d" % ifnum
230                 else:
231                     interface -= 1
232                 interfaces[ifname] = int
233
234     for (dev, int) in interfaces.iteritems():
235         path = "%s/etc/sysconfig/network-scripts/ifcfg-%s" % (
236                SYSIMG_PATH, dev)
237         f = file(path, "w")
238         log.write("Writing %s\n" % path.replace(SYSIMG_PATH, ""))
239
240         f.write("DEVICE=%s\n" % dev)
241         f.write("ONBOOT=yes\n")
242         f.write("USERCTL=no\n")
243         for (key, val) in int.iteritems():
244             f.write('%s="%s"\n' % (key, val))
245
246         f.close()
247