Exemplo n.º 1
0
 def get_async_run_status(self, async_content):
     """
     get the command's status
     """
     try:
         async_process = linux.Process(async_content.pid)
         res = async_process.get_process_status()
     except err.NoSuchProcess:
         res = "process is destructor"
     return res
Exemplo n.º 2
0
def test_get_fd():
    """test get fd"""
    # get_pid 第一个参数是启动程序的路径, 第二个是匹配参数, 比如mysqld
    arrow_pid = oper.get_pid('/home/maguannan/.jumbo/bin/', 'arrow_agent')
    print('pid {0}'.format(arrow_pid))
    process = linux.Process(arrow_pid)
    # 通过 get_open_files 函数获得打开文件数目
    print('opened fd {0}'.format(process.get_open_files()))
    # linux.Process(pid) 对象可以获取所有该进程的有效信息, 比如open fd, cpu时间


# vi:set tw=0 ts=4 sw=4 nowrap fdm=indent
Exemplo n.º 3
0
Arquivo: oper.py Projeto: lkunxyz/CUP
 def _target(argcontent):
     argcontent.__subpro = subprocess.Popen(argcontent.cmd,
                                            shell=True,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            preexec_fn=_signal_handle)
     from cup.res import linux
     parent = linux.Process(argcontent.__subpro.pid)
     children = parent.children(True)
     ret_dict = []
     for process in children:
         ret_dict.append(process)
     argcontent.child_list = ret_dict
Exemplo n.º 4
0
Arquivo: oper.py Projeto: wenhuiwu/CUP
    def get_async_run_status(cls, async_content):
        """
        get the process status of executing async cmd

        :return:
            None if the process has finished.
            Otherwise, return a object of linux.Process(async_pid)
        """
        try:
            async_process = linux.Process(async_content.pid)
            res = async_process.get_process_status()
        except err.NoSuchProcess:
            res = None
        return res
Exemplo n.º 5
0
 def _monitor(start_time, argcontent):
     while (int(time.mktime(datetime.datetime.now().timetuple())) -
            int(start_time) < int(argcontent.timeout)):
         time.sleep(1)
         if argcontent.subproc.poll() is not None:
             self._subpro_data = argcontent.subproc.communicate()
             argcontent.ret[
                 'returncode'] = argcontent.subproc.returncode
             argcontent.ret['stdout'] = self._subpro_data[0]
             argcontent.ret['stderr'] = self._subpro_data[1]
             return
     parent = linux.Process(argcontent.subproc.pid)
     children = parent.children(True)
     ret_dict = []
     for process in children:
         ret_dict.append(process)
     argcontent.child_list = ret_dict
     str_warn = ('Shell "{0}"execution timout:{1}. To kill it'.format(
         argcontent.cmd, argcontent.timeout))
     self.kill_all_process(argcontent)
     argcontent.ret['returncode'] = 999
     argcontent.ret['stderr'] = str_warn
     argcontent.subproc.terminate()
Exemplo n.º 6
0
    def run(self, cmd, timeout):
        """
        refer to the class description

        :param timeout:
            If the cmd is not returned after [timeout] seconds, the cmd process
            will be killed. If timeout is None, will block there until the cmd
            execution returns

        :return:
            {
                'stdout' : 'Success',
                'stderr' : None,
                'returncode' : 0
            }
            returncode == 0 means success, while 999 means timeout

        E.g.

        ::
            import cup
            shelltool = cup.shell.ShellExec()
            print shelltool.run('/bin/ls', timeout=1)
        """
        def _signal_handle():
            """
            signal setup
            """
            signal.signal(signal.SIGPIPE, signal.SIG_DFL)

        def _pipe_asshell(cmd):
            """
            run shell with subprocess.Popen
            """
            tempscript = tempfile.NamedTemporaryFile(dir=self._tmpdir,
                                                     prefix=self._tmpprefix,
                                                     delete=True)
            with open(tempscript.name, 'w+b') as fhandle:
                fhandle.write('cd {0};\n'.format(os.getcwd()))
                fhandle.write(cmd)
            shexe = self.which('sh')
            cmds = [shexe, tempscript.name]
            log.info('cup shell execute {0} with script {1}'.format(cmd, cmds))
            self._subpro = subprocess.Popen(cmds,
                                            stdout=subprocess.PIPE,
                                            stderr=subprocess.PIPE,
                                            preexec_fn=_signal_handle)
            self._subpro_data = self._subpro.communicate()

        ret = {'stdout': None, 'stderr': None, 'returncode': 0}
        cmdthd = threading.Thread(target=_pipe_asshell, args=(cmd, ))
        cmdthd.start()
        cmdthd.join(timeout)
        if cmdthd.isAlive():
            str_warn = ('Shell "%s"execution timout:%d. Killed it' %
                        (cmd, timeout))
            warnings.warn(str_warn, RuntimeWarning)
            parent = linux.Process(self._subpro.pid)
            for child in parent.children(True):
                os.kill(child, signal.SIGKILL)
            ret['returncode'] = 999
            ret['stderr'] = str_warn
            self._subpro.terminate()
        else:
            self._subpro.wait()
            times = 0
            while self._subpro.returncode is None and times < 10:
                time.sleep(1)
                times += 1
            ret['returncode'] = self._subpro.returncode
            assert type(self._subpro_data) == tuple, \
                'self._subpro_data should be a tuple'
            ret['stdout'] = self._subpro_data[0]
            ret['stderr'] = self._subpro_data[1]
        return ret