Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_name_always_available(self):
# On Windows name() is never supposed to raise AccessDenied,
# see https://github.com/giampaolo/psutil/issues/627
for p in psutil.process_iter():
try:
p.name()
except psutil.NoSuchProcess:
pass
def _cleanup_worker_processes(self):
# cleanup children
to_remove = []
for pid, child in self._processes.items():
try:
name, status = child.name(), child.status()
except psutil.NoSuchProcess: # May be untimely deceased
name, status = "unknown", "unknown"
logger.debug(" child: name=%s pid=%d status=%s" % (name, child.pid, status))
if status in (psutil.STATUS_ZOMBIE, "unknown"):
logger.debug(" process {} is zombie, will cleanup".format(child.pid))
# join process to clean it up
child.wait()
# set the process to be removed from self._processes
to_remove.append(pid)
# cleanup our internal state (self._processes)
for pid in to_remove:
del self._processes[pid]
def process_scan():
processes = []
for proc in psutil.process_iter():
try:
proc_info = proc.as_dict(attrs=['pid', 'name', 'cmdline', 'username'])
cpuset = Path('/proc/{}/cpuset'.format(proc_info['pid']))
if cpuset.exists():
with cpuset.open() as cpuset_file:
if cpuset_file.read().startswith('/docker/'):
proc_info['container'] = 'docker'
processes.append(proc_info)
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return processes
def resume_task(self, task_id):
pid = self._tasks[task_id].find(task_id)[-1]
if pid == -1:
raise psutil.NoSuchProcess("task: {} was not running".format(task_id))
else:
psutil.Process(pid).resume()
return True
def get_current_services_status():
services_status = _get_default_services_status()
for pid in pidlist():
try:
p = psutil.Process(pid)
pinfo = p.as_dict(attrs=['name', 'exe', 'username', 'status', 'cmdline'])
detected_service_name = executionenvironment.is_montag_process(pinfo, names)
if detected_service_name is not None:
services_status[detected_service_name] = {'status': pinfo['status'], 'pid': pid, 'process': p}
except (psutil.AccessDenied, psutil.NoSuchProcess):
pass
return services_status
def _get_process_id(self):
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'cmdline'])
if re.search(self.pname, str(pinfo.get('cmdline'))):
self.pid = pinfo.get('pid')
return self.pid
except psutil.NoSuchProcess:
LOG.info("NoSuchProcess:%(pname)s", {"pname": self.pname})
LOG.info("NoSuchProcess:%(pname)s", {"pname": self.pname})
return self.pid
def get_pids(self):
if self.proc is None:
return []
try:
ppid = self.proc.pid
psproc = psutil.Process(ppid)
child_procs = psproc.children(recursive=True)
pids = [c.pid for c in child_procs]
return [ppid] + pids
except psutil.NoSuchProcess:
return []
def memory_usage(self):
try:
memory_size = psutil.virtual_memory().total
except (psutil.NoSuchProcess, AttributeError):
return 0
return int(memory_size * self.percentage_memory_usage() / 100)
# Publish the sum of CPU and memory usage for all processes whose calls
# contain the trigger string.
cpu_count = psutil.cpu_count()
while not rospy.is_shutdown():
cpu_usage = 0.0
memory_usage = 0.0
for process in psutil.process_iter():
try:
with process.oneshot():
for chunk in process.cmdline():
if trigger_string in chunk:
cpu_usage += process.cpu_percent()
memory_usage += process.memory_percent()
break
except psutil.NoSuchProcess:
rospy.logwarn("Attempted to analyze non-existent process.")
pass
cpu_usage_publisher.publish(cpu_usage / cpu_count)
memory_usage_publisher.publish(memory_usage)
# Publish battery information as well.
battery_remaining = psutil.sensors_battery()
if battery_remaining is not None:
battery_remaining_publisher.publish(battery_remaining.percent)
# Don't do this too fast, lest you waste precious CPU cycles.
rospy.sleep(1)
except rospy.ROSInterruptException:
pass
def wait_for_all(exe, timeout=30):
"""Wait for the given process to exit"""
import psutil
processes = []
for proc in psutil.process_iter():
try:
pinfo = proc.as_dict(attrs=['pid', 'name', 'exe'])
except psutil.NoSuchProcess:
pass
else:
if 'exe' in pinfo and pinfo['exe'] is not None and\
os.path.basename(pinfo['exe']) == exe:
processes.append(proc)
if len(processes):
logging.debug("Waiting up to %d seconds for %s to exit", timeout, exe)
psutil.wait_procs(processes, timeout=timeout)