a pass on some explicit encode calls that are obviously wrong in python3; some may...
[plcapi.git] / PLC / Methods / GetBootMedium.py
index 368ae1e..d9fc671 100644 (file)
@@ -1,3 +1,5 @@
+# pylint: disable=c0111, c0103
+
 import random
 import base64
 import os
@@ -14,9 +16,9 @@ from PLC.Interfaces import Interface, Interfaces
 from PLC.InterfaceTags import InterfaceTag, InterfaceTags
 from PLC.NodeTags import NodeTag, NodeTags
 
-from PLC.Debug import log
+from PLC.Logger import logger
 
-from PLC.Accessors.Accessors_standard import *                  # import node accessors
+from PLC.Accessors.Accessors_standard import *              # node accessors
 
 # could not define this in the class..
 # create a dict with the allowed actions for each type of node
@@ -40,12 +42,11 @@ allowed_actions = {
 # compute a new key
 def compute_key():
     # Generate 32 random bytes
-    bytes = random.sample(xrange(0, 256), 32)
+    int8s = random.sample(range(0, 256), 32)
     # Base64 encode their string representation
-    key = base64.b64encode("".join(map(chr, bytes)))
+    key = base64.b64encode(bytes(int8s))
     # Boot Manager cannot handle = in the key
-    # XXX this sounds wrong, as it might prevent proper decoding
-    key = key.replace("=", "")
+    key = key.replace(b"=", b"")
     return key
 
 class GetBootMedium(Method):
@@ -287,7 +288,8 @@ class GetBootMedium(Method):
 
     def bootcd_version (self):
         try:
-            return file(self.BOOTCDDIR + "/build/version.txt").readline().strip()
+            with open(self.BOOTCDDIR + "/build/version.txt") as feed:
+                return feed.readline().strip()
         except:
             raise Exception("Unknown boot cd version - probably wrong bootcd dir : {}"\
                             .format(self.BOOTCDDIR))
@@ -295,7 +297,7 @@ class GetBootMedium(Method):
     def cleantrash (self):
         for file in self.trash:
             if self.DEBUG:
-                print >> log, 'DEBUG -- preserving',file
+                logger.debug('DEBUG -- preserving trash file {}'.format(file))
             else:
                 os.unlink(file)
 
@@ -344,7 +346,7 @@ class GetBootMedium(Method):
             if filedir:
                 if not os.path.exists(filedir):
                     try:
-                        os.makedirs (filedir,0777)
+                        os.makedirs (filedir,0o777)
                     except:
                         raise PLCPermissionDenied("Could not create dir {}".format(filedir))
 
@@ -362,9 +364,9 @@ class GetBootMedium(Method):
         # regular node, make build's arguments
         # and build the full command line to be called
         if node_type not in [ 'regular', 'reservable' ]:
-            print >> log, "GetBootMedium.build_command: unexpected node_type {}".format(node_type)
+            logger.error("GetBootMedium.build_command: unexpected node_type {}".format(node_type))
             return command, None
-        
+
         build_sh_options=""
         if "cramfs" in build_sh_spec:
             type += "_cramfs"
@@ -389,8 +391,8 @@ class GetBootMedium(Method):
                           type,
                           build_sh_options,
                           log_file)
-        
-        print >> log, "The build command line is {}".format(command)
+
+        logger.info("The build command line is {}".format(command))
 
         return command, log_file
 
@@ -415,8 +417,8 @@ class GetBootMedium(Method):
             raise PLCInvalidArgument("No such node {}".format(node_id_or_hostname))
         node = nodes[0]
 
-        print >> log, "GetBootMedium: {} requested on node {}. Node type is: {}"\
-            .format(action, node['node_id'], node['node_type'])
+        logger.info("GetBootMedium: {} requested on node {}. Node type is: {}"\
+            .format(action, node['node_id'], node['node_type']))
 
         # check the required action against the node type
         node_type = node['node_type']
@@ -481,7 +483,7 @@ class GetBootMedium(Method):
         else:
             node = None
             # compute a 8 bytes random number
-            tempbytes = random.sample (xrange(0,256), 8);
+            tempbytes = random.sample (range(0,256), 8);
             def hexa2 (c): return chr((c>>4)+65) + chr ((c&16)+65)
             nodename = "".join(map(hexa2,tempbytes))
 
@@ -520,7 +522,8 @@ class GetBootMedium(Method):
                                               .format(generic_path, filename))
             else:
                 ### return the generic medium content as-is, just base64 encoded
-                return base64.b64encode(file(generic_path).read())
+                with open(generic_path) as feed:
+                    return base64.b64encode(feed.read())
 
         ### config file preview or regenerated
         if action == 'node-preview' or action == 'node-floppy':
@@ -528,7 +531,8 @@ class GetBootMedium(Method):
             floppy = self.floppy_contents (node,renew_key)
             if filename:
                 try:
-                    file(filename,'w').write(floppy)
+                    with open(filename, 'w') as writer:
+                        writer.write(floppy)
                 except:
                     raise PLCPermissionDenied("Could not write into {}".format(filename))
                 return filename
@@ -553,8 +557,8 @@ class GetBootMedium(Method):
             # create the workdir if needed
             if not os.path.isdir(self.WORKDIR):
                 try:
-                    os.makedirs(self.WORKDIR,0777)
-                    os.chmod(self.WORKDIR,0777)
+                    os.makedirs(self.WORKDIR,0o777)
+                    os.chmod(self.WORKDIR,0o777)
                 except:
                     raise PLCPermissionDenied("Could not create dir {}".format(self.WORKDIR))
 
@@ -564,7 +568,8 @@ class GetBootMedium(Method):
                 # store it
                 floppy_file = "{}/{}.txt".format(self.WORKDIR, nodename)
                 try:
-                    file(floppy_file,"w").write(floppy_text)
+                    with open(floppy_file, "w") as writer:
+                        writer.write(floppy_text)
                 except:
                     raise PLCPermissionDenied("Could not write into {}".format(floppy_file))
 
@@ -583,7 +588,7 @@ class GetBootMedium(Method):
                     raise PLCAPIError("{} failed Command line was: {} See logs in {}"\
                                       .format(self.BOOTCDBUILD, command, log_file))
 
-                if not os.path.isfile (node_image):
+                if not os.path.isfile(node_image):
                     raise PLCAPIError("Unexpected location of build.sh output - {}".format(node_image))
 
                 # handle result
@@ -597,13 +602,14 @@ class GetBootMedium(Method):
                     self.cleantrash()
                     return filename
                 else:
-                    result = file(node_image).read()
+                    with open(node_image) as feed:
+                        result = feed.read()
                     self.trash.append(node_image)
                     self.cleantrash()
-                    print >> log, "GetBootMedium - done with build.sh"
+                    logger.info("GetBootMedium - done with build.sh")
                     encoded_result = base64.b64encode(result)
-                    print >> log, "GetBootMedium - done with base64 encoding - lengths: raw={} - b64={}"\
-                        .format(len(result), len(encoded_result))
+                    logger.info("GetBootMedium - done with base64 encoding - lengths: raw={} - b64={}"
+                                .format(len(result), len(encoded_result)))
                     return encoded_result
             except:
                 self.cleantrash()