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