Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def _do_stop(self,stop_cmd):
"Stop a process."
pid = ''
# Read the pid from the file.
pid_file_path='/tmp/arch3_'+self.service_name+'.pid'
if os.path.isfile(pid_file_path):
with open(pid_file_path,'r') as pidfile:
pid = pidfile.readline()
stop_cmd += pid
self.log.debug (stop_cmd)
self.log.debug('pid: '+pid)
if psutil.pid_exists(int(pid)):
returncode = subprocess.call(stop_cmd.split(' '))
if returncode == 0:
self.log.info ('The '+self.service_name+' process has been stopped.')
os.remove(pid_file_path)
else:
self.log.info('The '+self.service_name+' process with PID '+pid+' does not appear to be running.')
else:
self.log.info('The '+self.service_name+' process does not appear to be running.')
rootdir = config['Default']['rootdir']
# In debug mode, do not interfere with the regular data files
if args.debug:
rootdir = rootdir + ".debug"
if not os.path.exists(rootdir):
os.makedirs(rootdir)
# Check if another instance is already running
lock = os.path.join(rootdir, "ArloDownload.pid")
if os.path.isfile(lock):
pid = int(open(lock, 'r').read())
if pid == 0:
print(lock + " file exists but connot be read. Assuming an instance is already running. Exiting.")
sys.exit
if psutil.pid_exists(pid):
# if the lock file is more than a few hours old, we got ourselves something hung...
if ((time.time() - os.path.getmtime(lock)) < 60*60*6):
print("An instance is already running. Exiting.")
sys.exit()
print("Process " + str(pid) + " appears stuck. Killing it.")
os.kill(pid, signal.SIGTERM);
sleep(1)
if psutil.pid_exists(pid):
print("ERROR: Unable to kill hung process. Exiting.")
sys.exit()
# We can proceed and claim this run as our own...
# I guess something crashed. Let's go ahead and claim this run!
open(lock, 'w').write(str(os.getpid()))
return True if the lock file exists on disk and has a valid process
"""
if not os.path.isfile(self.path):
return False
with open(self.path, "r") as stream:
data = stream.read()
# return False if the data in the file
# cannot be converted to a number
if not data.isdigit():
return False
data = int(data)
if not psutil.pid_exists(data):
self.remove()
return False
return True
def _kill_process(self, box_config):
""" method is called to kill a running process """
try:
self.logger.info(f'kill: {box_config.process_name} {{')
self.logger.info(f'target process pid={box_config.pid}')
if box_config.pid and psutil.pid_exists(box_config.pid):
p = psutil.Process(box_config.pid)
p.kill()
p.wait()
box_config.pid = None
self.bc_dao.update(box_config)
remove_pid_file(box_config.process_name)
except Exception:
self.logger.error(f'Exception on killing: {box_config.process_name}', exc_info=True)
finally:
self.logger.info('}')
elif self.__methods.lower() == 'peach':
flag=False
# TODO: Same Binary run in parallel
statusFile = os.path.join(self.__input, 'status.txt')
if os.path.exists(statusFile):
f = open(statusFile, 'r')
lines = f.readlines()
f.close()
for line in lines:
if 'command line:' in line.lower():
Commandline = ":".join(line.split(":")[1:]).strip()
break
pids=psutil.pids()
for pid in pids:
if psutil.pid_exists(pid) == True:
try:
p=psutil.Process(pid)
if p.name()=="Peach.exe" or p.name()=="peach":
if Commandline == p.cmdline()[-1]:
flag=True
break
except Exception as err:
print(err)
continue
if flag:
sp=psutil.Process(pid)
status=p.status()
if ' process no longer exists' not in status:
Pid = pid
else:
Pid =None
def check_running_builds(self):
builds = self.env['runbot.build'].search([('state', '=', 'running')])
for b in builds:
if not psutil.pid_exists(b.pid) or not b.pid:
b.kill()
def _should_run(pid):
if not _check_ts():
return False
if pid is None:
return True
else:
if PS_UTIL:
return psutil.pid_exists(pid)
else:
return os.path.exists("/proc/%s" % pid)
def apply(openvpn):
pid = 0
pidfile = '/var/run/openvpn/{}.pid'.format(openvpn['intf'])
if os.path.isfile(pidfile):
pid = 0
with open(pidfile, 'r') as f:
pid = int(f.read())
# Always stop OpenVPN service. We can not send a SIGUSR1 for restart of the
# service as the configuration is not re-read. Stop daemon only if it's
# running - it could have died or killed by someone evil
if pid_exists(pid):
cmd = 'start-stop-daemon --stop --quiet'
cmd += ' --pidfile ' + pidfile
subprocess_cmd(cmd)
# cleanup old PID file
if os.path.isfile(pidfile):
os.remove(pidfile)
# Do some cleanup when OpenVPN is disabled/deleted
if openvpn['deleted'] or openvpn['disable']:
# cleanup old configuration file
if os.path.isfile(get_config_name(openvpn['intf'])):
os.remove(get_config_name(openvpn['intf']))
# cleanup client config dir
directory = os.path.dirname(get_config_name(openvpn['intf']))
def get_process(pid=None):
pid = os.getpid() if pid is None \
else os.getppid() if pid == 0 \
else pid
return psutil.Process(pid) if psutil.pid_exists(pid) else None
def killcelery():
"""
Kills the celery server for local development
"""
def anyfn(fn, iterable):
for e in iterable:
if fn(e): return True
return False
import psutil
celeryd_pss = [p for p in psutil.process_iter() if p.name == 'python' and anyfn(lambda arg: 'celery.bin.celeryd' in arg, p.cmdline)]
counter = 0
for ps in celeryd_pss:
if psutil.pid_exists(ps.pid):
counter += 1
ps.terminate()
print "%i processes terminated" % counter