better patch for unverified context
[bootmanager.git] / source / RunlevelAgent.py
index e3047b3..0d514c3 100755 (executable)
@@ -7,6 +7,8 @@
 #   so that it is immediately visible at myplc (gui or api).
 # 
 
+from __future__ import print_function
+
 import xml, xmlrpclib
 import logging
 import time
@@ -14,35 +16,36 @@ import traceback
 import sys
 import os
 import string
+import ssl
 
-CONFIG_FILE="/tmp/source/configuration"
-SESSION_FILE="/etc/planetlab/session"
-RLA_PID_FILE="/var/run/rla.pid"
+CONFIG_FILE = "/tmp/source/configuration"
+SESSION_FILE = "/etc/planetlab/session"
+RLA_PID_FILE = "/var/run/rla.pid"
 
 def read_config_file(filename):
     ## NOTE: text copied from BootManager.py 
     # TODO: unify this code to make it common. i.e. use ConfigParser module
     vars = {}
-    vars_file= file(filename,'r')
+    vars_file = file(filename,'r')
     validConfFile = True
     for line in vars_file:
         # if its a comment or a whitespace line, ignore
         if line[:1] == "#" or string.strip(line) == "":
             continue
 
-        parts= string.split(line,"=")
+        parts = string.split(line, "=")
         if len(parts) != 2:
-            print "Invalid line in vars file: %s" % line
+            print("Invalid line in vars file: {}".format(line))
             validConfFile = False
             break
 
-        name= string.strip(parts[0])
-        value= string.strip(parts[1])
-        vars[name]= value
+        name = string.strip(parts[0])
+        value = string.strip(parts[1])
+        vars[name] = value
 
     vars_file.close()
     if not validConfFile:
-        print "Unable to read configuration vars."
+        print("Unable to read configuration vars.")
 
     return vars
 
@@ -51,7 +54,7 @@ try:
     import plc_config
     api_server_url = "https://" + plc_config.PLC_API_HOST + plc_config.PLC_API_PATH
 except:
-    filename=CONFIG_FILE
+    filename  = CONFIG_FILE
     vars = read_config_file(filename)
     api_server_url = vars['BOOT_API_SERVER']
 
@@ -59,20 +62,25 @@ except:
 class Auth:
     def __init__(self, username=None, password=None, **kwargs):
         if 'session' in kwargs:
-            self.auth= { 'AuthMethod' : 'session',
-                    'session' : kwargs['session'] }
+            self.auth = { 'AuthMethod' : 'session',
+                          'session' : kwargs['session'] }
         else:
-            if username==None and password==None:
+            if username is None and password is None:
                 self.auth = {'AuthMethod': "anonymous"}
             else:
                 self.auth = {'Username' : username,
-                            'AuthMethod' : 'password',
-                            'AuthString' : password}
+                             'AuthMethod' : 'password',
+                             'AuthString' : password}
 class PLC:
     def __init__(self, auth, url):
         self.auth = auth
         self.url = url
-        self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True)
+        # Using a self signed certificate
+        # https://www.python.org/dev/peps/pep-0476/
+        try:    turn_off_server_verify = { 'context' : ssl._create_unverified_context() } 
+        except: turn_off_server_verify = {}
+        self.api = xmlrpclib.Server(self.url, verbose=False, allow_none=True,
+                                    **turn_off_server_verify)
 
     def __getattr__(self, name):
         method = getattr(self.api, name)
@@ -85,12 +93,12 @@ class PLC:
         return self.api.__repr__()
 
 def extract_from(filename, pattern):
-    f = os.popen("grep -E %s %s" % (pattern, filename))
+    f = os.popen("grep -E {} {}".format(pattern, filename))
     val = f.read().strip()
     return val
 
 def check_running(commandname):
-    f = os.popen("ps ax | grep -E %s | grep -v grep" % (commandname))
+    f = os.popen("ps ax | grep -E {} | grep -v grep".format(commandname))
     val = f.read().strip()
     return val
 
@@ -100,10 +108,10 @@ def save_pid():
     try:
         pid = os.getpid()
         f = open(RLA_PID_FILE, 'w')
-        f.write("%s\n" % pid)
+        f.write("{}\n".format(pid))
         f.close()
     except:
-        print "Uuuhhh.... this should not occur."
+        print("Uuuhhh.... this should not occur.")
         sys.exit(1)
 
 def start_and_run():
@@ -114,16 +122,16 @@ def start_and_run():
     # session file, or DNS to succeed, until AuthCheck succeeds.
     while True:
         try:
-            f=open(SESSION_FILE,'r')
-            session_str=f.read().strip()
+            f = open(SESSION_FILE, 'r')
+            session_str = f.read().strip()
             api = PLC(Auth(session=session_str), api_server_url)
             # NOTE: What should we do if this call fails?
             # TODO: handle dns failure here.
             api.AuthCheck()
             break
         except:
-            print "Retry in 30 seconds: ", os.popen("uptime").read().strip()
-            traceback.print_exc()
+            print("Retry in 30 seconds: ", os.popen("uptime").read().strip())
+            traceback.print_exc(limit=5)
             time.sleep(30)
 
     try:
@@ -168,7 +176,7 @@ def start_and_run():
                 api.ReportRunlevel({'run_level' : 'failboot'})
                 
         except:
-            print "reporting error: ", os.popen("uptime").read().strip()
+            print("reporting error: ", os.popen("uptime").read().strip())
             traceback.print_exc()
 
         sys.stdout.flush()