Blame SOURCES/python-linux-procfs-Various-clean-ups.patch

b9c204
From ce8cacdd515bf7270daef62648d5f994f111cded Mon Sep 17 00:00:00 2001
b9c204
From: John Kacur <jkacur@redhat.com>
b9c204
Date: Thu, 2 Dec 2021 16:52:10 -0500
b9c204
Subject: [PATCH 1/2] python-linux-procfs: Various clean-ups
b9c204
b9c204
- Replace f=open with 'with' (context managers), except in try-except blocks
b9c204
- Reformat lines that are too long, especially in comments
b9c204
- Use min() instead of if construct
b9c204
- Use bool instead of complicated and True or False constructs
b9c204
- Reorder imports
b9c204
b9c204
Signed-off-by: John Kacur <jkacur@redhat.com>
b9c204
---
b9c204
 procfs/procfs.py | 292 +++++++++++++++++++++++------------------------
b9c204
 1 file changed, 142 insertions(+), 150 deletions(-)
b9c204
b9c204
diff --git a/procfs/procfs.py b/procfs/procfs.py
b9c204
index a0e9977214fe..a78bac5376e3 100755
b9c204
--- a/procfs/procfs.py
b9c204
+++ b/procfs/procfs.py
b9c204
@@ -19,10 +19,10 @@
b9c204
 #
b9c204
 
b9c204
 import os
b9c204
-import time
b9c204
-from functools import reduce
b9c204
 import platform
b9c204
 import re
b9c204
+import time
b9c204
+from functools import reduce
b9c204
 from six.moves import range
b9c204
 from procfs.utilist import bitmasklist
b9c204
 
b9c204
@@ -37,8 +37,9 @@ def is_s390():
b9c204
 
b9c204
 def process_cmdline(pid_info):
b9c204
     """
b9c204
-    Returns the process command line, if available in the given `process' class, if
b9c204
-    not available, falls back to using the comm (short process name) in its pidstat key.
b9c204
+    Returns the process command line, if available in the given `process' class,
b9c204
+    if not available, falls back to using the comm (short process name) in its
b9c204
+    pidstat key.
b9c204
     """
b9c204
     if pid_info["cmdline"]:
b9c204
         return reduce(lambda a, b: a + " %s" % b, pid_info["cmdline"]).strip()
b9c204
@@ -47,10 +48,12 @@ def process_cmdline(pid_info):
b9c204
 
b9c204
 
b9c204
 class pidstat:
b9c204
-    """Provides a dictionary to access the fields in the per process /proc/PID/stat
b9c204
-       files.
b9c204
+    """
b9c204
+    Provides a dictionary to access the fields in the
b9c204
+    per process /proc/PID/stat files.
b9c204
 
b9c204
-       One can obtain the available fields asking for the keys of the dictionary, e.g.:
b9c204
+    One can obtain the available fields by asking for the keys of the
b9c204
+    dictionary, e.g.:
b9c204
 
b9c204
         >>> p = procfs.pidstat(1)
b9c204
         >>> print p.keys()
b9c204
@@ -182,8 +185,7 @@ class pidstat:
b9c204
         Returns true if this process has a fixed smp affinity mask,
b9c204
                 not allowing it to be moved to a different set of CPUs.
b9c204
         """
b9c204
-        return self.fields["flags"] & self.PF_THREAD_BOUND and \
b9c204
-            True or False
b9c204
+        return bool(self.fields["flags"] & self.PF_THREAD_BOUND)
b9c204
 
b9c204
     def process_flags(self):
b9c204
         """
b9c204
@@ -193,33 +195,34 @@ class pidstat:
b9c204
 
b9c204
         As of v4.2-rc7 these include (from include/linux/sched.h comments):
b9c204
 
b9c204
-            PF_EXITING       Getting shut down
b9c204
-            PF_EXITPIDONE       Pi exit done on shut down
b9c204
+            PF_EXITING        Getting shut down
b9c204
+            PF_EXITPIDONE     Pi exit done on shut down
b9c204
             PF_VCPU           I'm a virtual CPU
b9c204
-            PF_WQ_WORKER       I'm a workqueue worker
b9c204
-            PF_FORKNOEXEC       Forked but didn't exec
b9c204
-            PF_MCE_PROCESS       Process policy on mce errors
b9c204
-            PF_SUPERPRIV       Used super-user privileges
b9c204
+            PF_WQ_WORKER      I'm a workqueue worker
b9c204
+            PF_FORKNOEXEC     Forked but didn't exec
b9c204
+            PF_MCE_PROCESS    Process policy on mce errors
b9c204
+            PF_SUPERPRIV      Used super-user privileges
b9c204
             PF_DUMPCORE       Dumped core
b9c204
             PF_SIGNALED       Killed by a signal
b9c204
             PF_MEMALLOC       Allocating memory
b9c204
-            PF_NPROC_EXCEEDED  Set_user noticed that RLIMIT_NPROC was exceeded
b9c204
-            PF_USED_MATH       If unset the fpu must be initialized before use
b9c204
-            PF_USED_ASYNC       Used async_schedule*(), used by module init
b9c204
+            PF_NPROC_EXCEEDED Set_user noticed that RLIMIT_NPROC was exceeded
b9c204
+            PF_USED_MATH      If unset the fpu must be initialized before use
b9c204
+            PF_USED_ASYNC     Used async_schedule*(), used by module init
b9c204
             PF_NOFREEZE       This thread should not be frozen
b9c204
-            PF_FROZEN       Frozen for system suspend
b9c204
-            PF_FSTRANS       Inside a filesystem transaction
b9c204
-            PF_KSWAPD       I am kswapd
b9c204
+            PF_FROZEN          Frozen for system suspend
b9c204
+            PF_FSTRANS         Inside a filesystem transaction
b9c204
+            PF_KSWAPD          I am kswapd
b9c204
             PF_MEMALLOC_NOIO   Allocating memory without IO involved
b9c204
             PF_LESS_THROTTLE   Throttle me less: I clean memory
b9c204
-            PF_KTHREAD       I am a kernel thread
b9c204
+            PF_KTHREAD         I am a kernel thread
b9c204
             PF_RANDOMIZE       Randomize virtual address space
b9c204
             PF_SWAPWRITE       Allowed to write to swap
b9c204
             PF_NO_SETAFFINITY  Userland is not allowed to meddle with cpus_allowed
b9c204
             PF_MCE_EARLY       Early kill for mce process policy
b9c204
-            PF_MUTEX_TESTER       Thread belongs to the rt mutex tester
b9c204
-            PF_FREEZER_SKIP       Freezer should not count it as freezable
b9c204
-            PF_SUSPEND_TASK       This thread called freeze_processes and should not be frozen
b9c204
+            PF_MUTEX_TESTER    Thread belongs to the rt mutex tester
b9c204
+            PF_FREEZER_SKIP    Freezer should not count it as freezable
b9c204
+            PF_SUSPEND_TASK    This thread called freeze_processes and
b9c204
+                               should not be frozen
b9c204
 
b9c204
         """
b9c204
         sflags = []
b9c204
@@ -236,8 +239,8 @@ class pidstat:
b9c204
 def cannot_set_affinity(self, pid):
b9c204
     PF_NO_SETAFFINITY = 0x04000000
b9c204
     try:
b9c204
-        return int(self.processes[pid]["stat"]["flags"]) & \
b9c204
-            PF_NO_SETAFFINITY and True or False
b9c204
+        return bool(int(self.processes[pid]["stat"]["flags"]) &
b9c204
+                    PF_NO_SETAFFINITY)
b9c204
     except:
b9c204
         return True
b9c204
 
b9c204
@@ -245,19 +248,21 @@ def cannot_set_affinity(self, pid):
b9c204
 def cannot_set_thread_affinity(self, pid, tid):
b9c204
     PF_NO_SETAFFINITY = 0x04000000
b9c204
     try:
b9c204
-        return int(self.processes[pid].threads[tid]["stat"]["flags"]) & \
b9c204
-            PF_NO_SETAFFINITY and True or False
b9c204
+        return bool(int(self.processes[pid].threads[tid]["stat"]["flags"]) &
b9c204
+                    PF_NO_SETAFFINITY)
b9c204
     except:
b9c204
         return True
b9c204
 
b9c204
 
b9c204
 class pidstatus:
b9c204
     """
b9c204
-    Provides a dictionary to access the fields in the per process /proc/PID/status
b9c204
-    files. This provides additional information about processes and threads to what
b9c204
-    can be obtained with the procfs.pidstat() class.
b9c204
+    Provides a dictionary to access the fields
b9c204
+    in the per process /proc/PID/status files.
b9c204
+    This provides additional information about processes and threads to
b9c204
+    what can be obtained with the procfs.pidstat() class.
b9c204
 
b9c204
-    One can obtain the available fields asking for the keys of the dictionary, e.g.:
b9c204
+    One can obtain the available fields by asking for the keys of the
b9c204
+    dictionary, e.g.:
b9c204
 
b9c204
         >>> import procfs
b9c204
         >>> p = procfs.pidstatus(1)
b9c204
@@ -312,19 +317,18 @@ class pidstatus:
b9c204
         return fieldname in self.fields
b9c204
 
b9c204
     def load(self, basedir="/proc"):
b9c204
-        f = open("%s/%d/status" % (basedir, self.pid))
b9c204
         self.fields = {}
b9c204
-        for line in f.readlines():
b9c204
-            fields = line.split(":")
b9c204
-            if len(fields) != 2:
b9c204
-                continue
b9c204
-            name = fields[0]
b9c204
-            value = fields[1].strip()
b9c204
-            try:
b9c204
-                self.fields[name] = int(value)
b9c204
-            except:
b9c204
-                self.fields[name] = value
b9c204
-        f.close()
b9c204
+        with open("%s/%d/status" % (basedir, self.pid)) as f:
b9c204
+            for line in f.readlines():
b9c204
+                fields = line.split(":")
b9c204
+                if len(fields) != 2:
b9c204
+                    continue
b9c204
+                name = fields[0]
b9c204
+                value = fields[1].strip()
b9c204
+                try:
b9c204
+                    self.fields[name] = int(value)
b9c204
+                except:
b9c204
+                    self.fields[name] = value
b9c204
 
b9c204
 
b9c204
 class process:
b9c204
@@ -380,14 +384,13 @@ class process:
b9c204
         del self.threads[self.pid]
b9c204
 
b9c204
     def load_cgroups(self):
b9c204
-        f = open("/proc/%d/cgroup" % self.pid)
b9c204
         self.cgroups = ""
b9c204
-        for line in reversed(f.readlines()):
b9c204
-            if len(self.cgroups) != 0:
b9c204
-                self.cgroups = self.cgroups + "," + line[:-1]
b9c204
-            else:
b9c204
-                self.cgroups = line[:-1]
b9c204
-        f.close()
b9c204
+        with open("/proc/%d/cgroup" % self.pid) as f:
b9c204
+            for line in reversed(f.readlines()):
b9c204
+                if len(self.cgroups) != 0:
b9c204
+                    self.cgroups = self.cgroups + "," + line[:-1]
b9c204
+                else:
b9c204
+                    self.cgroups = line[:-1]
b9c204
 
b9c204
     def load_environ(self):
b9c204
         """
b9c204
@@ -416,12 +419,11 @@ class process:
b9c204
         >>>
b9c204
         """
b9c204
         self.environ = {}
b9c204
-        f = open("/proc/%d/environ" % self.pid)
b9c204
-        for x in f.readline().split('\0'):
b9c204
-            if len(x) > 0:
b9c204
-                y = x.split('=')
b9c204
-                self.environ[y[0]] = y[1]
b9c204
-        f.close()
b9c204
+        with open("/proc/%d/environ" % self.pid) as f:
b9c204
+            for x in f.readline().split('\0'):
b9c204
+                if len(x) > 0:
b9c204
+                    y = x.split('=')
b9c204
+                    self.environ[y[0]] = y[1]
b9c204
 
b9c204
 
b9c204
 class pidstats:
b9c204
@@ -465,18 +467,18 @@ class pidstats:
b9c204
 
b9c204
     def reload(self):
b9c204
         """
b9c204
-        This operation will throw away the current dictionary contents, if any, and
b9c204
-        read all the pid files from /proc/, instantiating a 'process' instance for
b9c204
-        each of them.
b9c204
+        This operation will throw away the current dictionary contents,
b9c204
+        if any, and read all the pid files from /proc/, instantiating a
b9c204
+        'process' instance for each of them.
b9c204
 
b9c204
-        This is a high overhead operation, and should be avoided if the perf python
b9c204
-        binding can be used to detect when new threads appear and existing ones
b9c204
-        terminate.
b9c204
+        This is a high overhead operation, and should be avoided if the
b9c204
+        perf python binding can be used to detect when new threads appear
b9c204
+        and existing ones terminate.
b9c204
 
b9c204
         In RHEL it is found in the python-perf rpm package.
b9c204
 
b9c204
-        More information about the perf facilities can be found in the 'perf_event_open'
b9c204
-        man page.
b9c204
+        More information about the perf facilities can be found in the
b9c204
+        'perf_event_open' man page.
b9c204
         """
b9c204
         del self.processes
b9c204
         self.processes = {}
b9c204
@@ -643,24 +645,21 @@ class interrupts:
b9c204
     def reload(self):
b9c204
         del self.interrupts
b9c204
         self.interrupts = {}
b9c204
-        f = open("/proc/interrupts")
b9c204
-
b9c204
-        for line in f.readlines():
b9c204
-            line = line.strip()
b9c204
-            fields = line.split()
b9c204
-            if fields[0][:3] == "CPU":
b9c204
-                self.nr_cpus = len(fields)
b9c204
-                continue
b9c204
-            irq = fields[0].strip(":")
b9c204
-            self.interrupts[irq] = {}
b9c204
-            self.interrupts[irq] = self.parse_entry(fields[1:], line)
b9c204
-            try:
b9c204
-                nirq = int(irq)
b9c204
-            except:
b9c204
-                continue
b9c204
-            self.interrupts[irq]["affinity"] = self.parse_affinity(nirq)
b9c204
-
b9c204
-        f.close()
b9c204
+        with open("/proc/interrupts") as f:
b9c204
+            for line in f.readlines():
b9c204
+                line = line.strip()
b9c204
+                fields = line.split()
b9c204
+                if fields[0][:3] == "CPU":
b9c204
+                    self.nr_cpus = len(fields)
b9c204
+                    continue
b9c204
+                irq = fields[0].strip(":")
b9c204
+                self.interrupts[irq] = {}
b9c204
+                self.interrupts[irq] = self.parse_entry(fields[1:], line)
b9c204
+                try:
b9c204
+                    nirq = int(irq)
b9c204
+                except:
b9c204
+                    continue
b9c204
+                self.interrupts[irq]["affinity"] = self.parse_affinity(nirq)
b9c204
 
b9c204
     def parse_entry(self, fields, line):
b9c204
         dict = {}
b9c204
@@ -681,9 +680,8 @@ class interrupts:
b9c204
 
b9c204
     def parse_affinity(self, irq):
b9c204
         try:
b9c204
-            f = open("/proc/irq/%s/smp_affinity" % irq)
b9c204
-            line = f.readline()
b9c204
-            f.close()
b9c204
+            with open("/proc/irq/%s/smp_affinity" % irq) as f:
b9c204
+                line = f.readline()
b9c204
             return bitmasklist(line, self.nr_cpus)
b9c204
         except IOError:
b9c204
             return [0, ]
b9c204
@@ -741,11 +739,11 @@ class cmdline:
b9c204
     """
b9c204
     Parses the kernel command line (/proc/cmdline), turning it into a dictionary."
b9c204
 
b9c204
-    Useful to figure out if some kernel boolean knob has been turned on, as well
b9c204
-    as to find the value associated to other kernel knobs.
b9c204
+    Useful to figure out if some kernel boolean knob has been turned on,
b9c204
+    as well as to find the value associated to other kernel knobs.
b9c204
 
b9c204
-    It can also be used to find out about parameters passed to the init process,
b9c204
-    such as 'BOOT_IMAGE', etc.
b9c204
+    It can also be used to find out about parameters passed to the
b9c204
+    init process, such as 'BOOT_IMAGE', etc.
b9c204
 
b9c204
     E.g.:
b9c204
     >>> import procfs
b9c204
@@ -762,15 +760,13 @@ class cmdline:
b9c204
         self.parse()
b9c204
 
b9c204
     def parse(self):
b9c204
-        f = open("/proc/cmdline")
b9c204
-        for option in f.readline().strip().split():
b9c204
-            fields = option.split("=")
b9c204
-            if len(fields) == 1:
b9c204
-                self.options[fields[0]] = True
b9c204
-            else:
b9c204
-                self.options[fields[0]] = fields[1]
b9c204
-
b9c204
-        f.close()
b9c204
+        with open("/proc/cmdline") as f:
b9c204
+            for option in f.readline().strip().split():
b9c204
+                fields = option.split("=")
b9c204
+                if len(fields) == 1:
b9c204
+                    self.options[fields[0]] = True
b9c204
+                else:
b9c204
+                    self.options[fields[0]] = fields[1]
b9c204
 
b9c204
     def __getitem__(self, key):
b9c204
         return self.options[key]
b9c204
@@ -790,9 +786,9 @@ class cpuinfo:
b9c204
     Dictionary with information about CPUs in the system.
b9c204
 
b9c204
     Please refer to 'man procfs(5)' for further information about the
b9c204
-        '/proc/cpuinfo' file, that is the source of the information provided by this
b9c204
-        class. The 'man lscpu(1)' also has information about a program that uses
b9c204
-    the '/proc/cpuinfo' file.
b9c204
+    '/proc/cpuinfo' file, that is the source of the information provided
b9c204
+    by this class. The 'man lscpu(1)' also has information about a program that
b9c204
+    uses the '/proc/cpuinfo' file.
b9c204
 
b9c204
     Using this class one can obtain the number of CPUs in a system:
b9c204
 
b9c204
@@ -801,14 +797,14 @@ class cpuinfo:
b9c204
           4
b9c204
 
b9c204
     It is also possible to figure out aspects of the CPU topology, such as
b9c204
-    how many CPU physical sockets exists, i.e. groups of CPUs sharing components
b9c204
-    such as CPU memory caches:
b9c204
+    how many CPU physical sockets exists, i.e. groups of CPUs sharing
b9c204
+    components such as CPU memory caches:
b9c204
 
b9c204
       >>> print len(cpus.sockets)
b9c204
       1
b9c204
 
b9c204
-    Additionally dictionary with information common to all CPUs in the system is
b9c204
-    available:
b9c204
+    Additionally dictionary with information common to all CPUs in the system
b9c204
+    is available:
b9c204
 
b9c204
       >>> print cpus["model name"]
b9c204
           Intel(R) Core(TM) i7-3667U CPU @ 2.00GHz
b9c204
@@ -836,28 +832,26 @@ class cpuinfo:
b9c204
         return self.tags
b9c204
 
b9c204
     def parse(self, filename):
b9c204
-        f = open(filename)
b9c204
-        for line in f.readlines():
b9c204
-            line = line.strip()
b9c204
-            if not line:
b9c204
-                continue
b9c204
-            fields = line.split(":")
b9c204
-            tagname = fields[0].strip().lower()
b9c204
-            if tagname == "processor":
b9c204
-                self.nr_cpus += 1
b9c204
-                continue
b9c204
-            if is_s390() and tagname == "cpu number":
b9c204
-                self.nr_cpus += 1
b9c204
-                continue
b9c204
-            if tagname == "core id":
b9c204
-                continue
b9c204
-            self.tags[tagname] = fields[1].strip()
b9c204
-            if tagname == "physical id":
b9c204
-                socket_id = self.tags[tagname]
b9c204
-                if socket_id not in self.sockets:
b9c204
-                    self.sockets.append(socket_id)
b9c204
-
b9c204
-        f.close()
b9c204
+        with open(filename) as f:
b9c204
+            for line in f.readlines():
b9c204
+                line = line.strip()
b9c204
+                if not line:
b9c204
+                    continue
b9c204
+                fields = line.split(":")
b9c204
+                tagname = fields[0].strip().lower()
b9c204
+                if tagname == "processor":
b9c204
+                    self.nr_cpus += 1
b9c204
+                    continue
b9c204
+                if is_s390() and tagname == "cpu number":
b9c204
+                    self.nr_cpus += 1
b9c204
+                    continue
b9c204
+                if tagname == "core id":
b9c204
+                    continue
b9c204
+                self.tags[tagname] = fields[1].strip()
b9c204
+                if tagname == "physical id":
b9c204
+                    socket_id = self.tags[tagname]
b9c204
+                    if socket_id not in self.sockets:
b9c204
+                        self.sockets.append(socket_id)
b9c204
         self.nr_sockets = self.sockets and len(self.sockets) or \
b9c204
             (self.nr_cpus /
b9c204
              ("siblings" in self.tags and int(self.tags["siblings"]) or 1))
b9c204
@@ -870,7 +864,8 @@ class smaps_lib:
b9c204
     Representation of an mmap in place for a process. Can be used to figure
b9c204
     out which processes have an library mapped, etc.
b9c204
 
b9c204
-    The 'perm' member can be used to figure out executable mmaps, i.e. libraries.
b9c204
+    The 'perm' member can be used to figure out executable mmaps,
b9c204
+    i.e. libraries.
b9c204
 
b9c204
     The 'vm_start' and 'vm_end' in turn can be used when trying to resolve
b9c204
     processor instruction pointer addresses to a symbol name in a library.
b9c204
@@ -967,13 +962,12 @@ class smaps:
b9c204
         return self.entries[index]
b9c204
 
b9c204
     def reload(self):
b9c204
-        f = open("/proc/%d/smaps" % self.pid)
b9c204
         line = None
b9c204
-        while True:
b9c204
-            line = self.parse_entry(f, line)
b9c204
-            if not line:
b9c204
-                break
b9c204
-        f.close()
b9c204
+        with("/proc/%d/smaps" % self.pid) as f:
b9c204
+            while True:
b9c204
+                line = self.parse_entry(f, line)
b9c204
+                if not line:
b9c204
+                    break
b9c204
         self.nr_entries = len(self.entries)
b9c204
 
b9c204
     def find_by_name_fragment(self, fragment):
b9c204
@@ -1055,18 +1049,17 @@ class cpusstats:
b9c204
     def reload(self):
b9c204
         last_entries = self.entries
b9c204
         self.entries = {}
b9c204
-        f = open(self.filename)
b9c204
-        for line in f.readlines():
b9c204
-            fields = line.strip().split()
b9c204
-            if fields[0][:3].lower() != "cpu":
b9c204
-                continue
b9c204
-            c = cpustat(fields)
b9c204
-            if c.name == "cpu":
b9c204
-                idx = 0
b9c204
-            else:
b9c204
-                idx = int(c.name[3:]) + 1
b9c204
-            self.entries[idx] = c
b9c204
-        f.close()
b9c204
+        with open(self.filename) as f:
b9c204
+            for line in f.readlines():
b9c204
+                fields = line.strip().split()
b9c204
+                if fields[0][:3].lower() != "cpu":
b9c204
+                    continue
b9c204
+                c = cpustat(fields)
b9c204
+                if c.name == "cpu":
b9c204
+                    idx = 0
b9c204
+                else:
b9c204
+                    idx = int(c.name[3:]) + 1
b9c204
+                self.entries[idx] = c
b9c204
         last_time = self.time
b9c204
         self.time = time.time()
b9c204
         if last_entries:
b9c204
@@ -1082,8 +1075,7 @@ class cpusstats:
b9c204
                     (curr.nice - prev.nice) + \
b9c204
                     (curr.system - prev.system)
b9c204
                 curr.usage = (delta / interval_hz) * 100
b9c204
-                if curr.usage > 100:
b9c204
-                    curr.usage = 100
b9c204
+                curr.usage = min(curr.usage, 100)
b9c204
 
b9c204
 
b9c204
 if __name__ == '__main__':
b9c204
-- 
b9c204
2.31.1
b9c204