def main(argv): global ps ps = procfs.pidstats() if (len(argv) > 1): pids = reduce(lambda i, j: i + j, map(thread_mapper, argv[1].split(","))) else: pids = ps.processes.keys() pids.sort() len_comms = map(lambda pid: len(ps[pid]["stat"]["comm"]), pids) max_comm_len = max(len_comms) del (len_comms) for pid in pids: flags = ps[pid].stat.process_flags() # Remove flags that were superseeded if "PF_THREAD_BOUND" in flags and "PF_NO_SETAFFINITY" in flags: flags.remove("PF_THREAD_BOUND") if "PF_FLUSHER" in flags and "PF_NPROC_EXCEEDED" in flags: flags.remove("PF_FLUSHER") if "PF_SWAPOFF" in flags and "PF_MEMALLOC_NOIO" in flags: flags.remove("PF_SWAPOFF") if "PF_FREEZER_NOSIG" in flags and "PF_SUSPEND_TASK" in flags: flags.remove("PF_FREEZER_NOSIG") comm = ps[pid].stat["comm"] flags.sort() sflags = reduce(lambda i, j: "%s|%s" % (i, j), map(lambda a: a[3:], flags)) print "%6d %*s %s" % (pid, max_comm_len, comm, sflags)
def perf_process_events(self, source, condition): had_events = True while had_events: had_events = False for cpu in self.cpu_map: event = self.evlist.read_on_cpu(cpu) if event: had_events = True if event.type == perf.RECORD_FORK: if event.pid == event.tid: try: self.ps.processes[event.pid] = procfs.process(event.pid) except: # short lived thread pass else: try: self.ps.processes[event.pid].threads.processes[event.tid] = procfs.process(event.tid) except AttributeError: self.ps.processes[event.pid].threads = procfs.pidstats("/proc/%d/task/" % event.pid) elif event.type == perf.RECORD_EXIT: del self.ps[int(event.tid)] elif event.type == perf.RECORD_SAMPLE: tid = event.sample_tid if self.perf_counter.has_key(tid): self.perf_counter[tid] += event.sample_period else: self.perf_counter[tid] = event.sample_period self.show() return True
def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads, affect_children, show_sockets, cgroups): ps = procfs.pidstats() if affect_children: ps.reload_threads() sock_inodes = None sock_inode_re = None if show_sockets: sock_inodes = load_sockets() sock_inode_re = re.compile(r"socket:\[(\d+)\]") has_ctxt_switch_info = ps[1]["status"].has_key("voluntary_ctxt_switches") try: ps_show_header(has_ctxt_switch_info, cgroups) ps_show( ps, affect_children, thread_list, cpu_list, irq_list, show_uthreads, show_kthreads, has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups, ) except IOError: # 'tuna -P | head' for instance pass
def _set_ps_affinity(self, affinity, intersect = False): _affinity = affinity affinity_hex = self._cmd.cpulist2hex(_affinity) ps = procfs.pidstats() ps.reload_threads() psl = [v for v in list(ps.values()) if re.search(self._ps_whitelist, self._get_stat_comm(v)) is not None] if self._ps_blacklist != "": psl = [v for v in psl if re.search(self._ps_blacklist, self._get_stat_comm(v)) is None] psd = dict([(v.pid, v) for v in psl]) self._set_all_obj_affinity(psd, affinity, False, intersect) # process IRQs irqs = procfs.interrupts() for irq in list(irqs.keys()): try: prev_affinity = irqs[irq]["affinity"] except KeyError: continue if intersect: _affinity = self._get_intersect_affinity(prev_affinity, affinity, affinity) affinity_hex = self._cmd.cpulist2hex(_affinity) self._cmd.write_to_file("/proc/irq/%s/smp_affinity" % irq, affinity_hex, no_error = True) # default affinity prev_affinity_hex = self._cmd.read_file("/proc/irq/default_smp_affinity") prev_affinity = self._cmd.hex2cpulist(prev_affinity_hex) if intersect: _affinity = self._get_intersect_affinity(prev_affinity, affinity, affinity) affinity_hex = self._cmd.cpulist2hex(_affinity) self._cmd.write_to_file("/proc/irq/default_smp_affinity", affinity_hex)
def get_kthread_sched_tunings(proc = None): if not proc: proc = procfs.pidstats() kthreads = {} for pid in proc.keys(): name = proc[pid]["stat"]["comm"] # Trying to set the priority of the migration threads will # fail, at least on 3.6.0-rc1 and doesn't make sense anyway # and this function is only used to save those priorities # to reset them using tools like rtctl, skip those to # avoid sched_setscheduler/chrt to fail if iskthread(pid) and not name.startswith("migration/"): rtprio = int(proc[pid]["stat"]["rt_priority"]) try: policy = schedutils.get_scheduler(pid) affinity = schedutils.get_affinity(pid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e percpu = iskthread(pid) and \ proc.is_bound_to_cpu(pid) kthreads[name] = sched_tunings(name, pid, policy, rtprio, affinity, percpu) return kthreads
def process_recommend_file(self, fname): matching_profile = None try: if not os.path.isfile(fname): return None config = ConfigObj(fname, list_values = False, interpolation = False) for section in list(config.keys()): match = True for option in list(config[section].keys()): value = config[section][option] if value == "": value = r"^$" if option == "virt": if not re.match(value, self.execute("virt-what")[1], re.S): match = False elif option == "system": if not re.match(value, self.read_file(consts.SYSTEM_RELEASE_FILE), re.S): match = False elif option[0] == "/": if not os.path.exists(option) or not re.match(value, self.read_file(option), re.S): match = False elif option[0:7] == "process": ps = procfs.pidstats() ps.reload_threads() if len(ps.find_by_regex(re.compile(value))) == 0: match = False if match: # remove the ",.*" suffix r = re.compile(r",[^,]*$") matching_profile = r.sub("", section) break except (IOError, OSError, ConfigObjError) as e: log.error("error processing '%s', %s" % (fname, e)) return matching_profile
def perf_process_events(self, source, condition): had_events = True while had_events: had_events = False for cpu in self.cpu_map: event = self.evlist.read_on_cpu(cpu) if event: had_events = True if event.type == perf.RECORD_FORK: if event.pid == event.tid: try: self.ps.processes[event.pid] = procfs.process( event.pid) except: # short lived thread pass else: try: self.ps.processes[event.pid].threads.processes[ event.tid] = procfs.process(event.tid) except AttributeError: self.ps.processes[ event.pid].threads = procfs.pidstats( "/proc/%d/task/" % event.pid) elif event.type == perf.RECORD_EXIT: del self.ps[int(event.tid)] elif event.type == perf.RECORD_SAMPLE: tid = event.sample_tid if self.perf_counter.has_key(tid): self.perf_counter[tid] += event.sample_period else: self.perf_counter[tid] = event.sample_period self.show() return True
def _set_ps_affinity(self, affinity): try: ps = procfs.pidstats() ps.reload_threads() self._set_all_obj_affinity(ps.values(), affinity, False) except (OSError, IOError) as e: log.error("error applying tuning, cannot get information about running processes: %s" % e)
def process_recommend_file(self, fname): matching_profile = None try: if not os.path.isfile(fname): return None config = ConfigObj(fname, list_values = False, interpolation = False) for section in list(config.keys()): match = True for option in list(config[section].keys()): value = config[section][option] if value == "": value = r"^$" if option == "virt": if not re.match(value, self.execute("virt-what")[1], re.S): match = False elif option == "system": if not re.match(value, self.read_file(consts.SYSTEM_RELEASE_FILE), re.S): match = False elif option[0] == "/": if not os.path.exists(option) or not re.match(value, self.read_file(option), re.S): match = False elif option[0:7] == "process": ps = procfs.pidstats() ps.reload_threads() if len(ps.find_by_regex(re.compile(value))) == 0: match = False elif option == "chassis_type": for chassis in dmidecode.chassis().values(): chassis_type = chassis["data"]["Type"] if re.match(value, chassis_type, re.IGNORECASE): break else: match = False elif option == "syspurpose_role": if have_syspurpose: s = syspurpose.files.SyspurposeStore( syspurpose.files.USER_SYSPURPOSE, raise_on_error = True) role = "" try: s.read_file() role = s.contents["role"] except (IOError, OSError, KeyError) as e: if hasattr(e, "errno") and e.errno != errno.ENOENT: log.error("Failed to load the syspurpose file: %s" % e) if re.match(value, role, re.IGNORECASE) is None: match = False else: log.error("Failed to process 'syspurpose_role' in '%s', the syspurpose module is not available" % fname) if match: # remove the ",.*" suffix r = re.compile(r",[^,]*$") matching_profile = r.sub("", section) break except (IOError, OSError, ConfigObjError) as e: log.error("error processing '%s', %s" % (fname, e)) return matching_profile
def thread_help(self, tid): if not self.ps: self.ps = procfs.pidstats() if not ps.has_key(tid): print "tuna: " + _("thread %d doesn't exists!") % tid return pinfo = ps[tid] cmdline = procfs.process_cmdline(pinfo) help, title = tuna.kthread_help_plain_text(tid, cmdline) print "%s\n\n%s" % (title, _(help))
def thread_mapper(s): global ps try: return [int(s)] except: pass if not ps: ps = procfs.pidstats() try: return ps.find_by_regex(re.compile(fnmatch.translate(s))) except: return ps.find_by_name(s)
def thread_help(tid): global ps if not ps: ps = procfs.pidstats() if not ps.has_key(tid): print "tuna: " + _("thread %d doesn't exists!") % tid return pinfo = ps[tid] cmdline = procfs.process_cmdline(pinfo) help, title = tuna.kthread_help_plain_text(tid, cmdline) print "%s\n\n%s" % (title, _(help))
def thread_mapper(s): global ps try: return [ int(s), ] except: pass if not ps: ps = procfs.pidstats() try: return ps.find_by_regex(re.compile(fnmatch.translate(s))) except: return ps.find_by_name(s)
def thread_mapper(self, s): try: return [ int(s), ] except: pass if not self.ps: self.ps = procfs.pidstats() try: return self.ps.find_by_regex(re.compile(fnmatch.translate(s))) except: return self.ps.find_by_name(s)
def move_irqs_to_cpu(cpus, irq_list, spread = False): changed = 0 unprocessed = [] cpu_idx = 0 nr_cpus = len(cpus) new_affinity = cpus last_cpu = max(cpus) + 1 irqs = None ps = procfs.pidstats() for i in irq_list: try: irq = int(i) except: if not irqs: irqs = procfs.interrupts() irq = irqs.find_by_user(i) if not irq: unprocessed.append(i) continue try: irq = int(irq) except: unprocessed.append(i) continue if spread: new_affinity = [cpus[cpu_idx]] cpu_idx += 1 if cpu_idx == nr_cpus: cpu_idx = 0 bitmasklist = procfs.hexbitmask(new_affinity, last_cpu) set_irq_affinity(irq, bitmasklist) changed += 1 pid = ps.find_by_name("IRQ-%d" % irq) if pid: pid = int(pid[0]) try: schedutils.set_affinity(pid, new_affinity) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: unprocessed.append(i) changed -= 1 continue raise e return (changed, unprocessed)
def recommend_profile(self, hardcoded=False): profile = consts.DEFAULT_PROFILE if hardcoded: return profile r = re.compile(r",[^,]*$") for f in consts.LOAD_DIRECTORIES: try: fname = os.path.join(f, consts.AUTODETECT_FILE) config = ConfigObj(fname, list_values=False, interpolation=False) for section in reversed(config.keys()): match = True for option in config[section].keys(): value = config[section][option] if value == "": value = r"^$" if option == "virt": if not re.match(value, self.execute("virt-what")[1], re.S): match = False elif option == "system": if not re.match( value, self.read_file(consts.SYSTEM_RELEASE_FILE), re.S): match = False elif option[0] == "/": if not os.path.exists(option) or not re.match( value, self.read_file(option), re.S): match = False elif option[0:7] == "process": ps = procfs.pidstats() ps.reload_threads() if len(ps.find_by_regex(re.compile(value))) == 0: match = False if match: # remove the ",.*" suffix profile = r.sub("", section) except (IOError, OSError, ConfigObjError) as e: log.error("error parsing '%s', %s" % (fname, e)) return profile
def get_processes(self): ps = procfs.pidstats() ps.reload_threads() processes = {} for proc in ps.values(): try: cmd = self._get_cmdline(proc) pid = proc["pid"] processes[pid] = cmd if "threads" in proc: for pid in proc["threads"].keys(): cmd = self._get_cmdline(proc) processes[pid] = cmd except (OSError, IOError) as e: if e.errno == errno.ENOENT \ or e.errno == errno.ESRCH: continue else: raise return processes
def do_ps(thread_list, cpu_list, irq_list, show_uthreads, show_kthreads, affect_children, show_sockets, cgroups): ps = procfs.pidstats() if affect_children: ps.reload_threads() sock_inodes = None sock_inode_re = None if show_sockets: sock_inodes = load_sockets() sock_inode_re = re.compile(r"socket:\[(\d+)\]") has_ctxt_switch_info = ps[1]["status"].has_key("voluntary_ctxt_switches") try: ps_show_header(has_ctxt_switch_info, cgroups) ps_show(ps, affect_children, thread_list, cpu_list, irq_list, show_uthreads, show_kthreads, has_ctxt_switch_info, sock_inodes, sock_inode_re, cgroups) except IOError: # 'tuna -P | head' for instance pass
except: irq_affinity = "" events = reduce(lambda a, b: a + b, info["cpu"]) users = info["users"] for u in users: if u in nics: users[users.index(u)] = "%s(%s)" % (u, ethtool.get_module(u)) print "%5d: %5d %5d %11d %8s %8s %s" % (irq, pid, rtprio, events, thread_affinity, irq_affinity, ",".join(users)) if __name__ == '__main__': irqs = procfs.interrupts() ps = procfs.pidstats() show_header() show(irqs, ps) try: interval = int(sys.argv[1]) while True: time.sleep(interval) irqs.reload() ps.reload() show_header() show(irqs, ps) except: for direction in [ "rx", "tx" ]:
def main(): ps = procfs.pidstats() ps.reload_threads() ps_objs = ps.values() get_affinity(ps_objs)
def isolate_cpus(cpus, nr_cpus): ps = procfs.pidstats() ps.reload_threads() previous_pid_affinities = {} for pid in ps.keys(): if cannot_set_affinity(ps, pid): continue try: affinity = schedutils.get_affinity(pid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(affinity).intersection(set(cpus)): previous_pid_affinities[pid] = copy.copy(affinity) affinity = affinity_remove_cpus(affinity, cpus, nr_cpus) try: schedutils.set_affinity(pid, affinity) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if not ps[pid].has_key("threads"): continue threads = ps[pid]["threads"] for tid in threads.keys(): if cannot_set_thread_affinity(ps, pid, tid): continue try: affinity = schedutils.get_affinity(tid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(affinity).intersection(set(cpus)): previous_pid_affinities[tid] = copy.copy(affinity) affinity = affinity_remove_cpus(affinity, cpus, nr_cpus) try: schedutils.set_affinity(tid, affinity) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e del ps # Now isolate it from IRQs too irqs = procfs.interrupts() previous_irq_affinities = {} for irq in irqs.keys(): # LOC, NMI, TLB, etc if not irqs[irq].has_key("affinity"): continue affinity = irqs[irq]["affinity"] if set(affinity).intersection(set(cpus)): previous_irq_affinities[irq] = copy.copy(affinity) affinity = affinity_remove_cpus(affinity, cpus, nr_cpus) set_irq_affinity(int(irq), procfs.hexbitmask(affinity, nr_cpus)) affinity = parse_irq_affinity_filename("default_smp_affinity", nr_cpus) affinity = affinity_remove_cpus(affinity, cpus, nr_cpus) set_irq_affinity_filename("default_smp_affinity", procfs.hexbitmask(affinity, nr_cpus)) return (previous_pid_affinities, previous_irq_affinities)
def process_config(self, fname, has_root=True): matching_profile = None try: if not os.path.isfile(fname): return None config = ConfigParser(delimiters=('='), inline_comment_prefixes=('#')) config.optionxform = str with open(fname) as f: config.read_file(f, fname) for section in config.sections(): match = True for option in config.options(section): value = config.get(section, option, raw=True) if value == "": value = r"^$" if option == "virt": if not has_root: match = False break if not re.match(value, self._commands.execute(["virt-what"])[1], re.S): match = False elif option == "system": if not re.match(value, self._commands.read_file( consts.SYSTEM_RELEASE_FILE, no_error = True), re.S): match = False elif option[0] == "/": if not os.path.exists(option) or not re.match(value, self._commands.read_file(option), re.S): match = False elif option[0:7] == "process": ps = procfs.pidstats() ps.reload_threads() if len(ps.find_by_regex(re.compile(value))) == 0: match = False elif option == "chassis_type": chassis_type = self._get_chassis_type() if not re.match(value, chassis_type, re.IGNORECASE): match = False elif option == "syspurpose_role": if have_syspurpose: s = syspurpose.files.SyspurposeStore( syspurpose.files.USER_SYSPURPOSE, raise_on_error = True) role = "" try: s.read_file() role = s.contents["role"] except (IOError, OSError, KeyError) as e: if hasattr(e, "errno") and e.errno != errno.ENOENT: log.error("Failed to load the syspurpose\ file: %s" % e) if re.match(value, role, re.IGNORECASE) is None: match = False else: log.error("Failed to process 'syspurpose_role' in '%s'\ , the syspurpose module is not available" % fname) if match: # remove the ",.*" suffix r = re.compile(r",[^,]*$") matching_profile = r.sub("", section) break except (IOError, OSError, Error) as e: log.error("error processing '%s', %s" % (fname, e)) return matching_profile
cpu_list = do_list_op(op, cpu_list, op_list) elif o in ("-K", "--no_kthreads"): kthreads = False elif o in ("-q", "--irqs"): (op, a) = pick_op(a) op_list = reduce(lambda i, j: i + j, map(irq_mapper, list(set(a.split(","))))) irq_list = do_list_op(op, irq_list, op_list) # See comment above about thread_list_str if not op_list and type(a) == type(''): irq_list_str = do_list_op(op, irq_list_str, a.split(",")) if not op: thread_list = [] if not ps: ps = procfs.pidstats() if tuna.has_threaded_irqs(ps): for irq in irq_list: irq_re = tuna.threaded_irq_re(irq) irq_threads = ps.find_by_regex(irq_re) if irq_threads: # Change the affinity of the thread too # as we can't rely on changing the irq # affinity changing the affinity of the # thread or vice versa. We need to change # both. thread_list += irq_threads elif o in ("-U", "--no_uthreads"): uthreads = False elif o in ("-v", "--version"):
def include_cpus(cpus, nr_cpus): ps = procfs.pidstats() ps.reload_threads() previous_pid_affinities = {} for pid in ps.keys(): if iskthread(pid): continue try: affinity = schedutils.get_affinity(pid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(affinity).intersection(set(cpus)) != set(cpus): previous_pid_affinities[pid] = copy.copy(affinity) affinity = list(set(affinity + cpus)) try: schedutils.set_affinity(pid, affinity) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if not ps[pid].has_key("threads"): continue threads = ps[pid]["threads"] for tid in threads.keys(): if iskthread(tid): continue try: affinity = schedutils.get_affinity(tid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(affinity).intersection(set(cpus)) != set(cpus): previous_pid_affinities[tid] = copy.copy(affinity) affinity = list(set(affinity + cpus)) try: schedutils.set_affinity(tid, affinity) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e del ps # Now include it in IRQs too irqs = procfs.interrupts() previous_irq_affinities = {} for irq in irqs.keys(): # LOC, NMI, TLB, etc if not irqs[irq].has_key("affinity"): continue affinity = irqs[irq]["affinity"] if set(affinity).intersection(set(cpus)) != set(cpus): previous_irq_affinities[irq] = copy.copy(affinity) affinity = list(set(affinity + cpus)) set_irq_affinity(int(irq), procfs.hexbitmask(affinity, nr_cpus)) return (previous_pid_affinities, previous_irq_affinities)
def print_sockets(states, families, socktype, show_options = False, show_mem = False, show_protocol_info = False, show_details = False, show_users = False): if show_users: ps = procfs.pidstats() inode_re = re.compile(r"socket:\[(\d+)\]") inodes = {} for pid in ps.keys(): dirname = "/proc/%d/fd" % pid try: filenames = os.listdir(dirname) except: # Process died continue for fd in filenames: pathname = os.path.join(dirname, fd) try: linkto = os.readlink(pathname) except: break inode_match = inode_re.match(linkto) if not inode_match: continue inode = int(inode_match.group(1)) sock = socket_link(pid, int(fd)) if inodes.has_key(inode): inodes[inode].append(sock) else: inodes[inode] = [ sock, ] extensions = 0 if show_mem: extensions |= inet_diag.EXT_MEMORY; if show_protocol_info: extensions |= inet_diag.EXT_PROTOCOL | inet_diag.EXT_CONGESTION; idiag = inet_diag.create(states = states, extensions = extensions, socktype = socktype); print "%-*s %-6s %-6s %*s:%-*s %*s:%-*s" % \ (state_width, "State", "Recv-Q", "Send-Q", addr_width, "Local Address", serv_width, "Port", addr_width, "Peer Address", serv_width, "Port") while True: try: s = idiag.get() except: break if not (families & (1 << s.family())): continue print "%-*s %-6d %-6d %*s:%-*d %*s:%-*d " % \ (state_width, s.state(), s.receive_queue(), s.write_queue(), addr_width, s.saddr(), serv_width, s.sport(), addr_width, s.daddr(), serv_width, s.dport()), if show_options: timer = s.timer() if timer != "off": print "timer:(%s,%s,%d)" % (timer, print_ms_timer(s), s.retransmissions()), if show_users: inode = s.inode() if inodes.has_key(inode): print "users:(" + \ ",".join(map(lambda sock: '("%s",%d,%d)' % (ps[sock.pid]["stat"]["comm"], sock.pid, sock.fd), inodes[inode])) + ")", if show_details: uid = s.uid() if uid: print "uid:%d" % uid, print "ino:%d sk:%x" % (s.inode(), s.sock()), if show_mem: try: print "\n\t mem:(r%u,w%u,f%u,t%u)" % \ (s.receive_queue_memory(), s.write_queue_used_memory(), s.write_queue_memory(), s.forward_alloc()), except: pass if show_protocol_info: try: options = s.protocol_options() if options & inet_diag.PROTO_OPT_TIMESTAMPS: print "ts", if options & inet_diag.PROTO_OPT_SACK: print "sack", if options & inet_diag.PROTO_OPT_ECN: print "ecn", print s.congestion_algorithm(), if options & inet_diag.PROTO_OPT_WSCALE: print "wscale:%d,%d" % (s.receive_window_scale_shift(), s.send_window_scale_shift()), except: pass try: print "rto:%g" % s.rto(), except: pass try: print "rtt:%g/%g ato:%g cwnd:%d" % \ (s.rtt() / 1000.0, s.rttvar() / 1000.0, s.ato() / 1000.0, s.cwnd()), except: pass try: ssthresh = s.ssthresh() if ssthresh < 0xffff: print "ssthresh:%d" % ssthresh, except: pass print
def move_threads_to_cpu(cpus, pid_list, set_affinity_warning = None, spread = False): changed = False ps = procfs.pidstats() cpu_idx = 0 nr_cpus = len(cpus) new_affinity = cpus last_cpu = max(cpus) + 1 for pid in pid_list: if spread: new_affinity = [cpus[cpu_idx]] cpu_idx += 1 if cpu_idx == nr_cpus: cpu_idx = 0 try: try: curr_affinity = schedutils.get_affinity(pid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: # 'No such process' continue curr_affinity = None raise e if set(curr_affinity) != set(new_affinity): try: schedutils.set_affinity(pid, new_affinity) curr_affinity = schedutils.get_affinity(pid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: # 'No such process' continue curr_affinity == None raise e if set(curr_affinity) == set(new_affinity): changed = True if is_hardirq_handler(ps, pid): try: irq = int(ps[pid]["stat"]["comm"][4:]) bitmasklist = procfs.hexbitmask(new_affinity, last_cpu) set_irq_affinity(irq, bitmasklist) except: pass elif set_affinity_warning: set_affinity_warning(pid, new_affinity) else: print "move_threads_to_cpu: %s " % \ (_("could not change %(pid)d affinity to %(new_affinity)s") % \ {'pid':pid, 'new_affinity':new_affinity}) # See if this is the thread group leader if not ps.has_key(pid): continue threads = procfs.pidstats("/proc/%d/task" % pid) for tid in threads.keys(): try: curr_affinity = schedutils.get_affinity(tid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(curr_affinity) != set(new_affinity): try: schedutils.set_affinity(tid, new_affinity) curr_affinity = schedutils.get_affinity(tid) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: continue raise e if set(curr_affinity) == set(new_affinity): changed = True elif set_affinity_warning: set_affinity_warning(tid, new_affinity) else: print "move_threads_to_cpu: %s " % \ (_("could not change %(pid)d affinity to %(new_affinity)s") % \ {'pid':pid, 'new_affinity':new_affinity}) except (SystemError, OSError) as e: # (3, 'No such process') old python-schedutils incorrectly raised SystemError if e[0] == 3: # process died continue raise e return changed
def __init__(self, show_kthreads = True, show_uthreads = True, cpus_filtered = []): global tuna_glade (app, localedir) = ('tuna', '/usr/share/locale') gtk.glade.bindtextdomain(app, localedir) gtk.glade.textdomain(app) if self.check_root(): sys.exit(1) for dir in tuna_glade_dirs: tuna_glade = "%s/tuna_gui.glade" % dir if os.access(tuna_glade, os.F_OK): break self.wtree = gtk.glade.XML(tuna_glade, "mainbig_window", "tuna") self.ps = procfs.pidstats() self.irqs = procfs.interrupts() self.window = self.wtree.get_widget("mainbig_window") self.procview = procview(self.wtree.get_widget("processlist"), self.ps, show_kthreads, show_uthreads, cpus_filtered, tuna_glade) self.irqview = irqview(self.wtree.get_widget("irqlist"), self.irqs, self.ps, cpus_filtered, tuna_glade) self.cpuview = cpuview(self.wtree.get_widget("vpaned1"), self.wtree.get_widget("hpaned2"), self.wtree.get_widget("cpuview"), self.procview, self.irqview, cpus_filtered) self.config = Config() self.check_env() self.commonview = commonview() self.commonview.contentTable = self.wtree.get_widget("commonTbl") self.commonview.configFileCombo = self.wtree.get_widget("profileSelector") self.profileview = profileview() self.profileview.config = self.config self.commonview.config = self.config self.profileview.commonview = self.commonview self.commonview.profileview = self.profileview self.profileview.setWtree(self.wtree) self.profileview.init_default_file() event_handlers = { "on_mainbig_window_delete_event" : self.on_mainbig_window_delete_event, "on_processlist_button_press_event" : self.procview.on_processlist_button_press_event, "on_irqlist_button_press_event" : self.irqview.on_irqlist_button_press_event, "on_loadProfileButton_clicked" : self.profileview.on_loadProfileButton_clicked, "on_SaveButton_clicked" : self.profileview.on_SaveButton_clicked, "on_UpdateButton_clicked" : self.profileview.on_UpdateButton_clicked, "on_applyChanges_clicked" : self.commonview.on_applyChanges_clicked, "on_undoChanges_clicked" : self.commonview.on_undoChanges_clicked, "on_saveSnapshot_clicked" : self.commonview.on_saveSnapshot_clicked, "on_saveTunedChanges_clicked" : self.commonview.on_saveTunedChanges_clicked, "on_profileSelector_changed" : self.commonview.on_profileSelector_changed, "on_profileTree_button_press_event" : self.profileview.on_profileTree_button_press_event } self.wtree.signal_autoconnect(event_handlers) self.ps.reload_threads() self.show() self.timer = gobject.timeout_add(2500, self.refresh) try: self.icon = gtk.status_icon_new_from_stock(gtk.STOCK_PREFERENCES) self.icon.connect("activate", self.on_status_icon_activate) self.icon.connect("popup-menu", self.on_status_icon_popup_menu) except AttributeError: # Old pygtk2 pass pixbuf = self.window.render_icon(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_SMALL_TOOLBAR) self.window.set_icon(pixbuf)
def __init__(self, show_kthreads=True, show_uthreads=True, cpus_filtered=[]): global tuna_glade (app, localedir) = ('tuna', '/usr/share/locale') gtk.glade.bindtextdomain(app, localedir) gtk.glade.textdomain(app) if self.check_root(): sys.exit(1) for dir in tuna_glade_dirs: tuna_glade = "%s/tuna_gui.glade" % dir if os.access(tuna_glade, os.F_OK): break self.wtree = gtk.glade.XML(tuna_glade, "mainbig_window", "tuna") self.ps = procfs.pidstats() self.irqs = procfs.interrupts() self.window = self.wtree.get_widget("mainbig_window") self.procview = procview(self.wtree.get_widget("processlist"), self.ps, show_kthreads, show_uthreads, cpus_filtered, tuna_glade) self.irqview = irqview(self.wtree.get_widget("irqlist"), self.irqs, self.ps, cpus_filtered, tuna_glade) self.cpuview = cpuview(self.wtree.get_widget("vpaned1"), self.wtree.get_widget("hpaned2"), self.wtree.get_widget("cpuview"), self.procview, self.irqview, cpus_filtered) self.config = Config() self.check_env() self.commonview = commonview() self.commonview.contentTable = self.wtree.get_widget("commonTbl") self.commonview.configFileCombo = self.wtree.get_widget( "profileSelector") self.profileview = profileview() self.profileview.config = self.config self.commonview.config = self.config self.profileview.commonview = self.commonview self.commonview.profileview = self.profileview self.profileview.setWtree(self.wtree) self.profileview.init_default_file() event_handlers = { "on_mainbig_window_delete_event": self.on_mainbig_window_delete_event, "on_processlist_button_press_event": self.procview.on_processlist_button_press_event, "on_irqlist_button_press_event": self.irqview.on_irqlist_button_press_event, "on_loadProfileButton_clicked": self.profileview.on_loadProfileButton_clicked, "on_SaveButton_clicked": self.profileview.on_SaveButton_clicked, "on_UpdateButton_clicked": self.profileview.on_UpdateButton_clicked, "on_applyChanges_clicked": self.commonview.on_applyChanges_clicked, "on_undoChanges_clicked": self.commonview.on_undoChanges_clicked, "on_saveSnapshot_clicked": self.commonview.on_saveSnapshot_clicked, "on_saveTunedChanges_clicked": self.commonview.on_saveTunedChanges_clicked, "on_profileSelector_changed": self.commonview.on_profileSelector_changed, "on_profileTree_button_press_event": self.profileview.on_profileTree_button_press_event } self.wtree.signal_autoconnect(event_handlers) self.ps.reload_threads() self.show() self.timer = gobject.timeout_add(2500, self.refresh) try: self.icon = gtk.status_icon_new_from_stock(gtk.STOCK_PREFERENCES) self.icon.connect("activate", self.on_status_icon_activate) self.icon.connect("popup-menu", self.on_status_icon_popup_menu) except AttributeError: # Old pygtk2 pass pixbuf = self.window.render_icon(gtk.STOCK_PREFERENCES, gtk.ICON_SIZE_SMALL_TOOLBAR) self.window.set_icon(pixbuf)