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