better patch for unverified context
[bootmanager.git] / source / RunlevelAgent.py
1 #!/usr/bin/python
2 #
3 # RunlevelAgent - acts as a heartbeat back to myplc reporting that the node is
4 #     online and whether it is in boot or pre-boot run-level.
5 #   This is useful to identify nodes that are behind a firewall, as well as to
6 #   have the machine report run-time status both in safeboot and boot modes,
7 #   so that it is immediately visible at myplc (gui or api).
8
9
10 from __future__ import print_function
11
12 import xml, xmlrpclib
13 import logging
14 import time
15 import traceback
16 import sys
17 import os
18 import string
19 import ssl
20
21 CONFIG_FILE = "/tmp/source/configuration"
22 SESSION_FILE = "/etc/planetlab/session"
23 RLA_PID_FILE = "/var/run/rla.pid"
24
25 def read_config_file(filename):
26     ## NOTE: text copied from BootManager.py 
27     # TODO: unify this code to make it common. i.e. use ConfigParser module
28     vars = {}
29     vars_file = file(filename,'r')
30     validConfFile = True
31     for line in vars_file:
32         # if its a comment or a whitespace line, ignore
33         if line[:1] == "#" or string.strip(line) == "":
34             continue
35
36         parts = string.split(line, "=")
37         if len(parts) != 2:
38             print("Invalid line in vars file: {}".format(line))
39             validConfFile = False
40             break
41
42         name = string.strip(parts[0])
43         value = string.strip(parts[1])
44         vars[name] = value
45
46     vars_file.close()
47     if not validConfFile:
48         print("Unable to read configuration vars.")
49
50     return vars
51
52 try:
53     sys.path = ['/etc/planetlab'] + sys.path
54     import plc_config
55     api_server_url = "https://" + plc_config.PLC_API_HOST + plc_config.PLC_API_PATH
56 except:
57     filename  = CONFIG_FILE
58     vars = read_config_file(filename)
59     api_server_url = vars['BOOT_API_SERVER']
60
61
62 class Auth:
63     def __init__(self, username=None, password=None, **kwargs):
64         if 'session' in kwargs:
65             self.auth = { 'AuthMethod' : 'session',
66                           'session' : kwargs['session'] }
67         else:
68             if username is None and password is None:
69                 self.auth = {'AuthMethod': "anonymous"}
70             else:
71                 self.auth = {'Username' : username,
72                              'AuthMethod' : 'password',
73                              'AuthString' : password}
74 class PLC:
75     def __init__(self, auth, url):
76         self.auth = auth
77         self.url = url
78         # Using a self signed certificate
79         # https://www.python.org/dev/peps/pep-0476/
80         try:    turn_off_server_verify = { 'context' : ssl._create_unverified_context() } 
81         except: turn_off_server_verify = {}
82         self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
83                                     **turn_off_server_verify)
84
85     def __getattr__(self, name):
86         method = getattr(self.api, name)
87         if method is None:
88             raise AssertionError("method does not exist")
89
90         return lambda *params : method(self.auth.auth, *params)
91
92     def __repr__(self):
93         return self.api.__repr__()
94
95 def extract_from(filename, pattern):
96     f = os.popen("grep -E {} {}".format(pattern, filename))
97     val = f.read().strip()
98     return val
99
100 def check_running(commandname):
101     f = os.popen("ps ax | grep -E {} | grep -v grep".format(commandname))
102     val = f.read().strip()
103     return val
104
105
106 def save_pid():
107     # save PID
108     try:
109         pid = os.getpid()
110         f = open(RLA_PID_FILE, 'w')
111         f.write("{}\n".format(pid))
112         f.close()
113     except:
114         print("Uuuhhh.... this should not occur.")
115         sys.exit(1)
116
117 def start_and_run():
118
119     save_pid()
120
121     # Keep trying to authenticate session, waiting for NM to re-write the
122     # session file, or DNS to succeed, until AuthCheck succeeds.
123     while True:
124         try:
125             f = open(SESSION_FILE, 'r')
126             session_str = f.read().strip()
127             api = PLC(Auth(session=session_str), api_server_url)
128             # NOTE: What should we do if this call fails?
129             # TODO: handle dns failure here.
130             api.AuthCheck()
131             break
132         except:
133             print("Retry in 30 seconds: ", os.popen("uptime").read().strip())
134             traceback.print_exc(limit=5)
135             time.sleep(30)
136
137     try:
138         env = 'production'
139         if len(sys.argv) > 2:
140             env = sys.argv[2]
141     except:
142         traceback.print_exc()
143
144     while True:
145         try:
146             # NOTE: here we are inferring the runlevel by environmental
147             #         observations.  We know how this process was started by the
148             #         given command line argument.  Then in bootmanager
149             #         runlevel, the bm.log gives information about the current
150             #         activity.
151             # other options:
152             #   call plc for current boot state?
153             #   how long have we been running?
154             if env == "bootmanager":
155                 bs_val = extract_from('/tmp/bm.log', "'Current boot state:'")
156                 if len(bs_val) > 0: bs_val = bs_val.split()[-1]
157                 ex_val = extract_from('/tmp/bm.log', 'Exception')
158                 fs_val = extract_from('/tmp/bm.log', 'mke2fs')
159                 bm_val = check_running("BootManager.py")
160
161                 if bs_val in ['diag', 'diagnose', 'safeboot', 'disabled', 'disable']:
162                     api.ReportRunlevel({'run_level' : 'safeboot'})
163
164                 elif len(ex_val) > len("Exception"):
165                     api.ReportRunlevel({'run_level' : 'failboot'})
166
167                 elif len(fs_val) > 0 and len(bm_val) > 0:
168                     api.ReportRunlevel({'run_level' : 'reinstall'})
169
170                 else:
171                     api.ReportRunlevel({'run_level' : 'failboot'})
172
173             elif env == "production":
174                 api.ReportRunlevel({'run_level' : 'boot'})
175             else:
176                 api.ReportRunlevel({'run_level' : 'failboot'})
177                 
178         except:
179             print("reporting error: ", os.popen("uptime").read().strip())
180             traceback.print_exc()
181
182         sys.stdout.flush()
183         # TODO: change to a configurable value
184         time.sleep(60*15)
185
186 def agent_running():
187     try:
188         os.stat(RLA_PID_FILE)
189         f = os.popen("ps ax | grep RunlevelAgent | grep -Ev 'grep|vim' | awk '{print $1}' | wc -l")
190         l = f.read().strip()
191         if int(l) >= 2:
192             return True
193         else:
194             try:
195                 os.unlink(RLA_PID_FILE)
196             except:
197                 pass
198             return False
199     except:
200         return False
201         
202
203 def shutdown():
204     import signal
205
206     pid = open(RLA_PID_FILE, 'r').read().strip()
207
208     # Try three different ways to kill the process.  Just to be sure.
209     os.kill(int(pid), signal.SIGKILL)
210     os.system("pkill RunlevelAgent.py")
211     os.system("ps ax | grep RunlevelAgent | grep -v grep | awk '{print $1}' | xargs kill -9 ")
212
213 if __name__ == "__main__":
214     if "start" in sys.argv and not agent_running():
215         start_and_run()
216
217     if "stop" in sys.argv and agent_running():
218         shutdown()