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