예제 #1
0
 def __init__(self, tagName='trader_msg', size=1024 * 1024):
     self.fm = mmap.mmap(-1,
                         size,
                         access=mmap.ACCESS_WRITE,
                         tagname=tagName)
     self.eventAu = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0,
                                         "aauto_trigger")
     self.eventPy = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0,
                                         "python_trigger")
     self.timeOut = 0xFFFFFFFF  #无穷等待
     win32event.ResetEvent(self.eventAu)
     win32event.ResetEvent(self.eventPy)
예제 #2
0
    def stop(self, kill=False):  # pylint: disable=too-many-branches
        """Terminate the process."""
        if sys.platform == "win32":

            # Attempt to cleanly shutdown mongod.
            if not kill and self.args and self.args[0].find("mongod") != -1:
                mongo_signal_handle = None
                try:
                    mongo_signal_handle = win32event.OpenEvent(
                        win32event.EVENT_MODIFY_STATE, False,
                        "Global\\Mongo_" + str(self._process.pid))

                    if not mongo_signal_handle:
                        # The process has already died.
                        return
                    win32event.SetEvent(mongo_signal_handle)
                    # Wait 60 seconds for the program to exit.
                    status = win32event.WaitForSingleObject(
                        self._process._handle, 60 * 1000)
                    if status == win32event.WAIT_OBJECT_0:
                        return
                except win32process.error as err:
                    # ERROR_FILE_NOT_FOUND (winerror=2)
                    # ERROR_ACCESS_DENIED (winerror=5)
                    # ERROR_INVALID_HANDLE (winerror=6)
                    # One of the above errors is received if the process has
                    # already died.
                    if err.winerror not in (2, 5, 6):
                        raise
                finally:
                    win32api.CloseHandle(mongo_signal_handle)

                print("Failed to cleanly exit the program, calling TerminateProcess() on PID: " +\
                    str(self._process.pid))

            # Adapted from implementation of Popen.terminate() in subprocess.py of Python 2.7
            # because earlier versions do not catch exceptions.
            try:
                # Have the process exit with code 0 if it is terminated by us to simplify the
                # success-checking logic later on.
                win32process.TerminateProcess(self._process._handle, 0)
            except win32process.error as err:
                # ERROR_ACCESS_DENIED (winerror=5) is received when the process
                # has already died.
                if err.winerror != winerror.ERROR_ACCESS_DENIED:
                    raise
                return_code = win32process.GetExitCodeProcess(
                    self._process._handle)
                if return_code == win32con.STILL_ACTIVE:
                    raise
        else:
            try:
                if kill:
                    self._process.kill()
                else:
                    self._process.terminate()
            except OSError as err:
                # ESRCH (errno=3) is received when the process has already died.
                if err.errno != 3:
                    raise
예제 #3
0
def signal_event_object(logger, pid):
    """Signal the Windows event object"""

    # Use unique event_name created.
    event_name = "Global\\Mongo_Python_" + str(pid)

    try:
        desired_access = win32event.EVENT_MODIFY_STATE
        inherit_handle = False
        task_timeout_handle = win32event.OpenEvent(desired_access,
                                                   inherit_handle,
                                                   event_name)
    except win32event.error as err:
        logger.info("Exception from win32event.OpenEvent with error: %s" % err)
        return

    try:
        win32event.SetEvent(task_timeout_handle)
    except win32event.error as err:
        logger.info("Exception from win32event.SetEvent with error: %s" % err)
    finally:
        win32api.CloseHandle(task_timeout_handle)

    logger.info("Waiting for process to report")
    time.sleep(5)
예제 #4
0
def run():
    r = RunTestLib()
    r.run_test(name='memstats',
               command="%s -memstats testdata/memstats.abc" % r.avm,
               expectedout=[
                   'gross stats', 'managed overhead', 'gross stats end',
                   'sweep\\([0-9]+\\) reclaimed [0-9]+ whole pages'
               ])
    if os.name != 'nt':
        print "pyspy     requires windows named pipes, does not work with cygwin python or non-windows operating systems"
    else:
        failed = False
        try:
            import win32event
            import win32pipe
            import win32file
        except:
            failed = True
            print "pyspy failed to load python win32 extension  FAILED"
        if failed == False:
            os.putenv('MMGC_PROFILE', '1')
            proc = r.run_command_async(command="%s testdata/memstats.abc" %
                                       r.avm,
                                       sleep=2)
            # pyspy source
            e = "MMgc::MemoryProfiler::DumpFatties"
            h = None
            try:
                h = win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, False,
                                         e)
            except Exception:
                print "Error: No registered event: %s FAILED!" % e
                sys.exit(1)

            win32event.SetEvent(h)

            pipe = "\\\\.\\pipe\MMgc_Spy"
            readHandle = None
            while True:
                try:
                    readHandle = win32file.CreateFile(pipe,
                                                      win32file.GENERIC_READ,
                                                      0, None,
                                                      win32file.OPEN_EXISTING,
                                                      0, None)
                    win32pipe.WaitNamedPipe(pipe, 100)
                except Exception:
                    pass
                if readHandle:
                    break

                while True:
                    try:
                        data = win32file.ReadFile(readHandle, 128)
                        sys.stdout.write(data[1])
                    except:
                        break
예제 #5
0
    def stop(self, pid):
        # call the method that any subclasses out there may implement:
        self.onStop()

        winver = sys.getwindowsversion()
        # This is unfortunately needed because runzope.exe is a setuptools
        # generated .exe that spawns off a sub process, so pid would give us
        # the wrong event name.
        child_pid = int(
            open(self.getReg('pid_filename', keyname='PythonClass')).read())

        # Stop the child process by sending signals to the special named event.
        # We give it 90 seconds to shutdown normally. If that doesn't stop
        # things, we give it 30 seconds to do a "fast" shutdown.
        for sig, timeout in (
            (signal.SIGINT, 30),
            (signal.SIGTERM, 10)):
            # See the Signals.WinSignalHandler module for
            # the source of this event name
            event_name = "Zope-%d-%d" % (child_pid, sig)
            if winver[0] >= 5 and winver[3] == 2:
                event_name = "Global\\" + event_name
            try:
                he = win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, 0,
                                          event_name)
            except win32event.error:
                # no other expected error - report it.
                self.warning("Failed to open child shutdown event %s"
                             % (event_name, ))
                continue

            win32event.SetEvent(he)
            # It should be shutting down now - wait for termination, reporting
            # progress as we go.
            for i in range(timeout):
                # wait for one second
                rc = win32event.WaitForSingleObject(self.hZope, 1000)
                if rc == win32event.WAIT_OBJECT_0:
                    break
            # Process terminated - no need to try harder.
            if rc == win32event.WAIT_OBJECT_0:
                break

        if win32process.GetExitCodeProcess(self.hZope)==win32con.STILL_ACTIVE:
            # None of the signals worked, so kill the process
            self.warning(
                "Terminating process as it could not be gracefully ended")
            win32api.TerminateProcess(self.hZope, 3)

        output = self.getCapturedOutput()
        if output:
            self.info("Process terminated with output:\n"+output)
예제 #6
0
def socket_send_msg(socket_fn, msg):
    """
    非bsd系统的进程间通信,发送消息,使用windows全局共享内存实现,函数名称保持与bsd的接口名称一致
    :param socket_fn: : 共享内存名称
    :param msg: 字符串类型需要传递的数据,不需要encode,内部进行encode
    """
    global_fn = 'Global\\{}'.format(socket_fn)
    event = w32e.OpenEvent(w32e.EVENT_ALL_ACCESS, 0, global_fn)
    event_mmap = mmf.mmapfile(None, socket_fn, 1024)
    w32e.SetEvent(event)
    event_mmap.write(msg)
    event_mmap.close()
    win_api.CloseHandle(event)
예제 #7
0
def OpenNameEventSet(name, loop=1):
    # print("open event = [" + name + "]")
    event = None
    for i in range(0, loop):
        # 打开
        event = win32event.OpenEvent(0x1F0003, False, name)
        if event is not None:
            break
        # 打不开就sleep 然后再打开
        Sleep(500)
    if event is None:
        return False
    win32event.SetEvent(event)
    CloseHandle(event)
    return True
예제 #8
0
def test_Security_from_object_HANDLE():
    _event = win32event.CreateEvent(None, 0, 0, GUID)
    hEvent = win32event.OpenEvent(
        win32event.EVENT_ALL_ACCESS | win32con.ACCESS_SYSTEM_SECURITY, 0, GUID)
    try:
        s = security.Security.from_object(
            hEvent, security.SE_OBJECT_TYPE.KERNEL_OBJECT, options=OPTIONS)
        assert equal(
            win32security.GetSecurityInfo(hEvent,
                                          win32security.SE_KERNEL_OBJECT,
                                          OPTIONS), s)
        assert s.inherit_handle is True
        assert s._originating_object == hEvent
        assert s._originating_object_type == win32security.SE_KERNEL_OBJECT
    finally:
        hEvent.Close()
예제 #9
0
파일: service.py 프로젝트: bendavis78/zope
    def SvcDoRun(self):
        # indicate to Zope that the process is daemon managed (restartable)
        os.environ['ZMANAGED'] = '1'

        # XXX the restart behavior is different here than it is for
        # zdaemon.zdrun.  we should probably do the same thing in both
        # places.

        # daemon behavior:  we want to to restart the process if it
        # dies, but if it dies too many times, we need to give up.

        # we use a simple backoff algorithm to determine whether
        # we should try to restart a dead process:  for each
        # time the process dies unexpectedly, we wait some number of
        # seconds to restart it, as determined by the backoff interval,
        # which doubles each time the process dies.  if we exceed
        # BACKOFF_MAX seconds in cumulative backoff time, we give up.
        # at any time if we successfully run the process for more thab
        # BACKOFF_CLEAR_TIME seconds, the backoff stats are reset.

        # the initial number of seconds between process start attempts
        self.backoff_interval = BACKOFF_INITIAL_INTERVAL
        # the cumulative backoff seconds counter
        self.backoff_cumulative = 0

        self.logmsg(servicemanager.PYS_SERVICE_STARTED)

        while 1:
            # We pass *this* file and the handle as the first 2 params, then
            # the 'normal' startup args.
            # See the bottom of this script for how that is handled.
            cmd = '"%s" %s' % (self.process_runner, self.process_args)
            info = self.createProcess(cmd)
            # info is (hProcess, hThread, pid, tid)
            self.hZope = info[0]  # process handle
            # XXX why the test before the log message?
            if self.backoff_interval > BACKOFF_INITIAL_INTERVAL:
                self.info("created process")
            if not (self.run() and self.checkRestart()):
                break

        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # Stop the child process by opening the special named event.
        # We give it 90 seconds to shutdown normally.  If that doesn't
        # stop things, we give it 30 seconds to do a "fast" shutdown.
        # After that, we just knock it on the head.
        winver = sys.getwindowsversion()
        for sig, timeout in ((signal.SIGINT, 30), (signal.SIGTERM, 10)):
            event_name = "Zope-%d-%d" % (info[2], sig)
            # sys.getwindowsversion() -> major, minor, build, platform_id, ver_string
            # for platform_id, 2==VER_PLATFORM_WIN32_NT
            if winver[0] >= 5 and winver[3] == 2:
                event_name = "Global\\" + event_name
            try:
                he = win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, 0,
                                          event_name)
            except win32event.error, details:
                if details[0] == winerror.ERROR_FILE_NOT_FOUND:
                    # process already dead!
                    break
                # no other expected error - report it.
                self.warning("Failed to open child shutdown event %s" %
                             (event_name, ))
                continue

            win32event.SetEvent(he)
            # It should be shutting down now - wait for termination, reporting
            # progress as we go.
            for i in range(timeout):
                self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
                rc = win32event.WaitForSingleObject(self.hZope, 3000)
                if rc == win32event.WAIT_OBJECT_0:
                    break
            # Process terminated - no need to try harder.
            if rc == win32event.WAIT_OBJECT_0:
                break
예제 #10
0
# from processing import passport_cropper as pc

import multiprocessing.shared_memory
import win32event
# import json

MEM_NAME = 'pppmem'
PASSPORT_EVENT_NAME = 'ppppassport'
RECOGNITION_EVENT_NAME = 'ppprecognition'
RESULT_TAKEN_EVENT_NAME = 'pppresulttaken'
KILL_EVENT_NAME = 'pppkill'

try:
    MEM = multiprocessing.shared_memory.SharedMemory(MEM_NAME, False)
    MEM_BUF = MEM.buf
    PASSPORT_EVENT = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, False,
                                          PASSPORT_EVENT_NAME)
    RECOGNITION_EVENT = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS,
                                             False, RECOGNITION_EVENT_NAME)
    RESULT_TAKEN_EVENT = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS,
                                              False, RESULT_TAKEN_EVENT_NAME)
    KILL_EVENT = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, False,
                                      KILL_EVENT_NAME)
except Exception as e:
    print('Exception', e)
    if 'MEM' in globals():
        MEM.close()
    if 'PASSPORT_EVENT' in globals():
        PASSPORT_EVENT.close()
    if 'RECOGNITION_EVENT' in globals():
        RECOGNITION_EVENT.close()
    if 'RESULT_TAKEN_EVENT' in globals():
예제 #11
0
 def init(self):
     try:
         self.event = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0,
                                           EVENT_NAME)
     except Exception, r:
         print r[2]
    def StopMonitoringPower(self):
        assert self._ippet_handle, (
            'Called StopMonitoringPower() before StartMonitoringPower().')
        try:
            # Stop IPPET.
            with contextlib.closing(
                    win32event.OpenEvent(win32event.EVENT_MODIFY_STATE, False,
                                         QUIT_EVENT)) as quit_event:
                win32event.SetEvent(quit_event)

            # Wait for IPPET process to exit.
            wait_code = win32event.WaitForSingleObject(self._ippet_handle,
                                                       20000)
            if wait_code != win32event.WAIT_OBJECT_0:
                if wait_code == win32event.WAIT_TIMEOUT:
                    raise IppetError('Timed out waiting for IPPET to close.')
                else:
                    raise IppetError(
                        'Error code %d while waiting for IPPET to close.' %
                        wait_code)

        finally:  # If we need to, forcefully kill IPPET.
            try:
                exit_code = win32process.GetExitCodeProcess(self._ippet_handle)
                if exit_code == win32con.STILL_ACTIVE:
                    win32process.TerminateProcess(self._ippet_handle, 0)
                    raise IppetError(
                        'IPPET is still running but should have stopped.')
                elif exit_code != 0:
                    raise IppetError('IPPET closed with exit code %d.' %
                                     exit_code)
            finally:
                self._ippet_handle.Close()
                self._ippet_handle = None

        # Read IPPET's log file.
        log_file = os.path.join(self._output_dir, 'ippet_log_processes.xls')
        try:
            with open(log_file, 'r') as f:
                reader = csv.DictReader(f, dialect='excel-tab')
                data = list(reader)[
                    1:]  # The first iteration only reports temperature.
        except IOError:
            logging.error('Output directory %s contains: %s', self._output_dir,
                          os.listdir(self._output_dir))
            raise
        shutil.rmtree(self._output_dir)
        self._output_dir = None

        def get(*args, **kwargs):
            """Pull all iterations of a field from the IPPET data as a list.

      Args:
        args: A list representing the field name.
        mult: A cosntant to multiply the field's value by, for unit conversions.
        default: The default value if the field is not found in the iteration.

      Returns:
        A list containing the field's value across all iterations.
      """
            key = '\\\\.\\' + '\\'.join(args)

            def value(line):
                if key in line:
                    return line[key]
                elif 'default' in kwargs:
                    return kwargs['default']
                else:
                    raise KeyError('Key "%s" not found in data and '
                                   'no default was given.' % key)

            return [
                float(value(line)) * kwargs.get('mult', 1) for line in data
            ]

        result = {
            'identifier':
            'ippet',
            'power_samples_mw':
            get('Power(_Total)', 'Package W', mult=1000),
            'energy_consumption_mwh':
            sum(
                map(operator.mul, get('Power(_Total)', 'Package W', mult=1000),
                    get('sys', 'Interval(secs)', mult=1. / 3600.))),
            'component_utilization': {
                'whole_package': {
                    'average_temperature_c':
                    statistics.ArithmeticMean(
                        get('Temperature(Package)', 'Current C')),
                },
                'cpu': {
                    'power_samples_mw':
                    get('Power(_Total)', 'CPU W', mult=1000),
                    'energy_consumption_mwh':
                    sum(
                        map(operator.mul,
                            get('Power(_Total)', 'CPU W', mult=1000),
                            get('sys', 'Interval(secs)', mult=1. / 3600.))),
                },
                'disk': {
                    'power_samples_mw':
                    get('Power(_Total)', 'Disk W', mult=1000),
                    'energy_consumption_mwh':
                    sum(
                        map(operator.mul,
                            get('Power(_Total)', 'Disk W', mult=1000),
                            get('sys', 'Interval(secs)', mult=1. / 3600.))),
                },
                'gpu': {
                    'power_samples_mw':
                    get('Power(_Total)', 'GPU W', mult=1000),
                    'energy_consumption_mwh':
                    sum(
                        map(operator.mul,
                            get('Power(_Total)', 'GPU W', mult=1000),
                            get('sys', 'Interval(secs)', mult=1. / 3600.))),
                },
            },
        }

        # Find Chrome processes in data. Note that this won't work if there are
        # extra Chrome processes lying around.
        chrome_keys = set()
        for iteration in data:
            for key in iteration.iterkeys():
                parts = key.split('\\')
                if (len(parts) >= 4 and re.match(
                        r'Process\(Google Chrome [0-9]+\)', parts[3])):
                    chrome_keys.add(parts[3])
        # Add Chrome process power usage to result.
        # Note that this is only an estimate of Chrome's CPU power usage.
        if chrome_keys:
            per_process_power_usage = [
                get(key, 'CPU Power W', default=0, mult=1000)
                for key in chrome_keys
            ]
            result['application_energy_consumption_mwh'] = (sum(
                map(operator.mul, map(sum, zip(*per_process_power_usage)),
                    get('sys', 'Interval(secs)', mult=1. / 3600.))))

        return result
예제 #13
0
import win32api, win32con,win32event,pywintypes;

try:
    a = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0, "KSPRODUCT_EVENT_NAME")
    print(a)
    print("begin waited event")
    b = win32event.WaitForSingleObject(a, 9999)
    print(b)
    if b == 0:
        print("waited, input any thing to exit")
    else:
        print("failed, input any thing to exit")
    a = raw_input()
except pywintypes.error as identifier:
    print "exception:"
    print("error:%d,%s" % (identifier[0],identifier[2]))
    pass
예제 #14
0
파일: api.py 프로젝트: openxzx/fms
def signal_restart_collect():
    hEvent = win32event.OpenEvent(win32event.EVENT_ALL_ACCESS, 0, "Global\\CollectEvent")
    if hEvent != None:
        win32event.SetEvent(hEvent)