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