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