mirror of https://github.com/dnomd343/ProxyC
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
209 lines
9.5 KiB
209 lines
9.5 KiB
2 years ago
|
#!/usr/bin/env python3
|
||
|
# -*- coding: utf-8 -*-
|
||
|
|
||
|
import os
|
||
|
import copy
|
||
|
import time
|
||
|
import ctypes
|
||
|
import signal
|
||
2 years ago
|
from Utils.Logger import logger
|
||
|
from Utils.Common import genFlag
|
||
|
from Utils.Exception import processException
|
||
2 years ago
|
from subprocess import Popen, STDOUT, DEVNULL
|
||
|
|
||
2 years ago
|
libcSysPaths = [
|
||
2 years ago
|
'/usr/lib/libc.so.6', # CentOS
|
||
|
'/usr/lib64/libc.so.6',
|
||
|
'/lib/libc.musl-i386.so.1', # Alpine
|
||
|
'/lib/libc.musl-x86_64.so.1',
|
||
|
'/lib/libc.musl-aarch64.so.1',
|
||
|
'/lib/i386-linux-gnu/libc.so.6', # Debian / Ubuntu
|
||
|
'/lib/x86_64-linux-gnu/libc.so.6',
|
||
|
'/lib/aarch64-linux-gnu/libc.so.6',
|
||
|
]
|
||
|
|
||
|
libcPath = None
|
||
2 years ago
|
for path in libcSysPaths:
|
||
|
if os.path.exists(path): # try to locate libc.so
|
||
|
libcPath = path
|
||
2 years ago
|
break
|
||
|
if libcPath is None: # lost libc.so -> unable to utilize prctl
|
||
2 years ago
|
logger.warning('libc.so not found')
|
||
2 years ago
|
else:
|
||
2 years ago
|
logger.info('libc.so -> %s' % libcPath)
|
||
2 years ago
|
|
||
|
|
||
|
class Process(object):
|
||
2 years ago
|
""" Manage a sub process and it's configure file.
|
||
2 years ago
|
|
||
|
Arguments:
|
||
|
cmd: Command list, which use to start the program.
|
||
|
|
||
|
env: Environment variables for sub process.
|
||
|
|
||
|
file: dict or list or None, include path and content option.
|
||
|
|
||
|
workDir: A directory for storing log files and configuration files.
|
||
|
|
||
2 years ago
|
taskId: Task ID, defaults to 12 random characters length.
|
||
|
|
||
|
isStart: Start the process after class init complete.
|
||
2 years ago
|
|
||
|
Attributes:
|
||
2 years ago
|
id, cmd, env, file, workDir, output
|
||
2 years ago
|
"""
|
||
|
output = None # sub process output if capture is True
|
||
|
__capture = None # capture the sub process output or not
|
||
|
__logfile = None # the log file which sub process output into STDOUT and STDERR
|
||
|
__process = None # CompletedProcess object of subprocess module
|
||
|
|
||
|
@staticmethod
|
||
|
def __preExec() -> None:
|
||
|
ctypes.CDLL(libcPath).prctl(1, signal.SIGTERM) # sub process killed when father process exit
|
||
|
os.setpgrp() # new process group
|
||
|
|
||
|
def __checkWorkDir(self) -> None: # check if the working directory is normal
|
||
|
if os.path.isdir(self.workDir):
|
||
|
return
|
||
2 years ago
|
logger.warning('[%s] Work directory %s not exist' % (self.id, self.workDir))
|
||
2 years ago
|
try:
|
||
|
os.makedirs(self.workDir) # just like `mkdir -p ...`
|
||
2 years ago
|
logger.info('[%s] New directory -> %s' % (self.id, self.workDir))
|
||
2 years ago
|
except:
|
||
|
if os.path.exists(self.workDir):
|
||
2 years ago
|
logger.error('[%s] %s already exist but not folder' % (self.id, self.workDir))
|
||
2 years ago
|
else:
|
||
2 years ago
|
logger.error('[%s] Unable to create new folder -> %s' % (self.id, self.workDir))
|
||
2 years ago
|
raise processException('Working directory error') # fatal error
|
||
2 years ago
|
|
||
|
def __killProcess(self, killSignal: int) -> None:
|
||
|
try:
|
||
|
pgid = os.getpgid(self.__process.pid) # progress group id
|
||
|
os.killpg(pgid, killSignal) # kill sub process group
|
||
2 years ago
|
logger.debug('[%s] Send signal %i to PGID %i' % (self.id, killSignal, pgid))
|
||
2 years ago
|
except:
|
||
2 years ago
|
logger.warning('[%s] Failed to get PGID of sub process (PID = %i)' % (self.id, self.__process.pid))
|
||
2 years ago
|
|
||
|
def __deleteFile(self, filePath: str) -> None:
|
||
|
if not os.path.isfile(filePath): # file not found (or not a file)
|
||
2 years ago
|
logger.warning('[%s] File %s not found' % (self.id, filePath))
|
||
2 years ago
|
return
|
||
|
try:
|
||
|
os.remove(filePath) # remove config file
|
||
2 years ago
|
logger.debug('[%s] File %s deleted successfully' % (self.id, filePath))
|
||
2 years ago
|
except:
|
||
2 years ago
|
logger.error('[%s] Unable to delete file %s' % (self.id, filePath))
|
||
2 years ago
|
|
||
|
def __init__(self, workDir: str, taskId: str = '', isStart: bool = True,
|
||
|
cmd: str or list or None = None, env: dict or None = None, file: dict or list or None = None) -> None:
|
||
|
self.id = genFlag(length = 12) if taskId == '' else taskId
|
||
|
self.workDir = workDir
|
||
2 years ago
|
self.env = copy.copy(env) # depth = 1
|
||
|
self.cmd = copy.copy([cmd] if type(cmd) == str else cmd) # depth = 1
|
||
|
self.file = copy.deepcopy([file] if type(file) == dict else file) # depth = 2
|
||
2 years ago
|
self.__checkWorkDir() # ensure the working direction is normal
|
||
2 years ago
|
logger.debug('[%s] Process command -> %s (%s)' % (self.id, self.cmd, self.env))
|
||
2 years ago
|
if self.file is not None:
|
||
|
if len(self.file) > 1:
|
||
2 years ago
|
logger.debug('[%s] Manage %i files' % (self.id, len(self.file)))
|
||
2 years ago
|
for file in self.file: # traverse all files
|
||
2 years ago
|
if not isStart: # don't print log twice
|
||
2 years ago
|
logger.debug('[%s] File %s -> %s' % (self.id, file['path'], file['content']))
|
||
2 years ago
|
if isStart:
|
||
|
self.start()
|
||
|
|
||
|
def setCmd(self, cmd: str or list) -> None:
|
||
2 years ago
|
self.cmd = copy.copy([cmd] if type(cmd) == str else cmd)
|
||
2 years ago
|
logger.info('[%s] Process setting command -> %s' % (self.id, self.cmd))
|
||
2 years ago
|
|
||
|
def setEnv(self, env: dict or None) -> None:
|
||
2 years ago
|
self.env = copy.copy(env)
|
||
2 years ago
|
logger.info('[%s] Process setting environ -> %s' % (self.id, self.env))
|
||
2 years ago
|
|
||
|
def setFile(self, file: dict or list or None) -> None:
|
||
2 years ago
|
self.file = copy.deepcopy([file] if type(file) == dict else file)
|
||
|
if self.file is None:
|
||
2 years ago
|
logger.info('[%s] Process setting file -> None' % self.id)
|
||
2 years ago
|
return
|
||
2 years ago
|
for file in self.file: # traverse all files
|
||
2 years ago
|
logger.info('[%s] Process setting file %s -> %s' % (self.id, file['path'], file['content']))
|
||
2 years ago
|
|
||
|
def start(self, isCapture: bool = True) -> None:
|
||
|
self.__capture = isCapture
|
||
2 years ago
|
logger.debug('[%s] Process ready to start (%s output capture)' % (
|
||
|
self.id, 'with' if self.__capture else 'without'
|
||
2 years ago
|
))
|
||
2 years ago
|
if self.cmd is None: # ERROR CASE
|
||
2 years ago
|
logger.error('[%s] Process miss start command' % self.id)
|
||
2 years ago
|
raise processException('Miss start command')
|
||
2 years ago
|
if self.__process is not None and self.__process.poll() is None: # ERROR CASE
|
||
2 years ago
|
logger.error('[%s] Process try to start but it is running' % self.id)
|
||
2 years ago
|
raise processException('Process is still running')
|
||
2 years ago
|
if self.env is not None and 'PATH' not in self.env and '/' not in self.cmd[0]: # WARNING CASE
|
||
2 years ago
|
logger.warning('[%s] Executable file in relative path but miss PATH in environ' % self.id)
|
||
2 years ago
|
if self.file is not None: # create and write file contents
|
||
|
for file in self.file:
|
||
2 years ago
|
with open(file['path'], 'w', encoding = 'utf-8') as fileObject: # save file content
|
||
|
fileObject.write(file['content'])
|
||
2 years ago
|
logger.debug('[%s] File %s -> %s' % (self.id, file['path'], file['content']))
|
||
2 years ago
|
if self.__capture: # with output capture
|
||
2 years ago
|
self.__logfile = os.path.join(self.workDir, '%s.log' % self.id)
|
||
|
logger.debug('[%s] Process output capture -> %s' % (self.id, self.__logfile))
|
||
2 years ago
|
stdout = open(self.__logfile, 'w', encoding = 'utf-8')
|
||
|
stderr = STDOUT # combine the stderr with stdout
|
||
|
else: # discard all the output of sub process
|
||
|
stdout = DEVNULL
|
||
|
stderr = DEVNULL
|
||
2 years ago
|
try:
|
||
|
self.__process = Popen(
|
||
|
self.cmd, env = self.env,
|
||
|
stdout = stdout, stderr = stderr,
|
||
|
preexec_fn = None if libcPath is None else Process.__preExec
|
||
|
)
|
||
|
except Exception as exp:
|
||
2 years ago
|
logger.error('[%s] Process unable to start -> %s' % (self.id, exp))
|
||
2 years ago
|
raise processException('Unable to start process')
|
||
2 years ago
|
logger.info('[%s] Process running -> PID = %i' % (self.id, self.__process.pid))
|
||
2 years ago
|
|
||
|
def signal(self, signalNum: int) -> None: # send specified signal to sub process
|
||
|
try:
|
||
|
signalName = signal.Signals(signalNum).name
|
||
|
except:
|
||
|
signalName = 'unknown'
|
||
2 years ago
|
logger.info('[%s] Send signal -> %i (%s)' % (self.id, signalNum, signalName))
|
||
2 years ago
|
self.__process.send_signal(signalNum)
|
||
|
|
||
|
def status(self) -> bool: # check if the sub process is still running
|
||
|
status = self.__process.poll() is None
|
||
2 years ago
|
logger.debug('[%s] Process check status -> %s' % (self.id, 'running' if status else 'exit'))
|
||
2 years ago
|
return status
|
||
|
|
||
|
def wait(self, timeout: int or None = None) -> None: # blocking wait sub process
|
||
2 years ago
|
logger.info('[%s] Process wait -> timeout = %s' % (self.id, str(timeout)))
|
||
2 years ago
|
try:
|
||
|
self.__process.wait(timeout = timeout)
|
||
2 years ago
|
logger.info('[%s] Process wait timeout -> exit' % self.id)
|
||
2 years ago
|
except:
|
||
2 years ago
|
logger.info('[%s] Process wait timeout -> running' % self.id)
|
||
2 years ago
|
|
||
|
def quit(self, isForce: bool = False, waitTime: int = 50) -> None: # wait 50ms in default
|
||
|
killSignal = signal.SIGKILL if isForce else signal.SIGTERM # 9 -> force kill / 15 -> terminate signal
|
||
2 years ago
|
logger.debug('[%s] Kill signal -> %i (%s)' % (self.id, killSignal, signal.Signals(killSignal).name))
|
||
2 years ago
|
self.__killProcess(killSignal)
|
||
|
time.sleep(waitTime / 1000) # sleep (ms -> s)
|
||
|
while self.__process.poll() is None: # confirm sub process exit
|
||
|
self.__killProcess(killSignal)
|
||
|
time.sleep(waitTime / 1000)
|
||
2 years ago
|
logger.info('[%s] Process terminated -> PID = %i' % (self.id, self.__process.pid))
|
||
2 years ago
|
if self.__capture:
|
||
|
try:
|
||
|
with open(self.__logfile, 'r', encoding = 'utf-8') as fileObject: # read sub process output
|
||
|
self.output = fileObject.read()
|
||
2 years ago
|
logger.debug('[%s] Process output capture -> length = %s' % (self.id, len(self.output)))
|
||
2 years ago
|
self.__deleteFile(self.__logfile)
|
||
|
except:
|
||
2 years ago
|
logger.error('[%s] Failed to read capture file -> %s' % (self.id, self.__logfile))
|
||
2 years ago
|
if self.file is not None: # with config file
|
||
|
for file in self.file:
|
||
2 years ago
|
self.__deleteFile(file['path'])
|