示例#1
0
def get_default_hub():
    """Select the default hub implementation based on what multiplexing
    libraries are installed.  The order that the hubs are tried is:
    
    * twistedr
    * epoll
    * poll
    * select
    
    It won't automatically select the pyevent hub, because it's not 
    python-thread-safe.
    
    .. include:: ../../doc/common.txt
    .. note :: |internal|
    """    
    
    # pyevent hub disabled for now because it is not thread-safe
    #try:
    #    import eventlet.hubs.pyevent
    #    return eventlet.hubs.pyevent
    #except:
    #    pass

    select = patcher.original('select')
    try:
        import eventlet.hubs.epolls
        return eventlet.hubs.epolls
    except ImportError:
        if hasattr(select, 'poll'):
            import eventlet.hubs.poll
            return eventlet.hubs.poll
        else:
            import eventlet.hubs.selects
            return eventlet.hubs.selects
示例#2
0
文件: manhole.py 项目: 2php/veles
def _get_original(qual_name):
    mod, name = qual_name.split('.')
    original = getattr(__import__(mod), name)

    try:
        from gevent.monkey import get_original
        original = get_original(mod, name)
    except (ImportError, SyntaxError):
        pass

    try:
        from eventlet.patcher import original
        original = getattr(original(mod), name)
    except (ImportError, SyntaxError):
        pass

    return original
示例#3
0
def _get_original(qual_name):
    mod, name = qual_name.split('.')
    original = getattr(__import__(mod), name)

    try:
        from gevent.monkey import get_original
        original = get_original(mod, name)
    except (ImportError, SyntaxError):
        pass

    try:
        from eventlet.patcher import original
        original = getattr(original(mod), name)
    except (ImportError, SyntaxError):
        pass

    return original
示例#4
0
文件: poller.py 项目: blp/ovs-reviews
def get_system_poll():
    """Returns the original select.poll() object. If select.poll is
    monkey patched by eventlet or gevent library, it gets the original
    select.poll and returns an object of it using the
    eventlet.patcher.original/gevent.monkey.get_original functions.

    As a last resort, if there is any exception it returns the
    SelectPoll() object.
    """
    try:
        if _using_eventlet_green_select():
            _system_poll = eventlet_patcher.original("select").poll
        elif gevent_monkey and gevent_monkey.is_object_patched(
                'select', 'poll'):
            _system_poll = gevent_monkey.get_original('select', 'poll')
        else:
            _system_poll = select.poll
    except:
        _system_poll = SelectPoll

    return _system_poll()
示例#5
0
def get_system_poll():
    """Returns the original select.poll() object. If select.poll is
    monkey patched by eventlet or gevent library, it gets the original
    select.poll and returns an object of it using the
    eventlet.patcher.original/gevent.monkey.get_original functions.

    As a last resort, if there is any exception it returns the
    SelectPoll() object.
    """
    try:
        if _using_eventlet_green_select():
            _system_poll = eventlet_patcher.original("select").poll
        elif gevent_monkey and gevent_monkey.is_object_patched(
                'select', 'poll'):
            _system_poll = gevent_monkey.get_original('select', 'poll')
        else:
            _system_poll = select.poll
    except:
        _system_poll = SelectPoll

    return _system_poll()
示例#6
0
import errno
from eventlet.support import get_errno
from eventlet import patcher
select = patcher.original("select")
if hasattr(select, 'epoll'):
    epoll = select.epoll
else:
    try:
        # http://pypi.python.org/pypi/select26/
        from select26 import epoll
    except ImportError:
        try:
            import epoll as _epoll_mod
        except ImportError:
            raise ImportError(
                "No epoll implementation found in select module or PYTHONPATH")
        else:
            if hasattr(_epoll_mod, 'poll'):
                epoll = _epoll_mod.poll
            else:
                raise ImportError(
                    "You have an old, buggy epoll module in PYTHONPATH."
                    " Install http://pypi.python.org/pypi/python-epoll/"
                    " NOT http://pypi.python.org/pypi/pyepoll/. "
                    " easy_install pyepoll installs the wrong version.")

from eventlet.hubs.hub import BaseHub
from eventlet.hubs import poll
from eventlet.hubs.poll import READ, WRITE

# NOTE: we rely on the fact that the epoll flag constants
示例#7
0
文件: epolls.py 项目: wdmchaft/hue
from eventlet import patcher
time = patcher.original('time')
select = patcher.original("select")
if hasattr(select, 'epoll'):
    epoll = select.epoll
else:
    try:
        # http://pypi.python.org/pypi/select26/
        from select26 import epoll
    except ImportError:
        try:
            import epoll as _epoll_mod
        except ImportError:
            raise ImportError(
                "No epoll implementation found in select module or PYTHONPATH")
        else:
            if hasattr(_epoll_mod, 'poll'):
                epoll = _epoll_mod.poll
            else:
                raise ImportError(
                    "You have an old, buggy epoll module in PYTHONPATH."
                    " Install http://pypi.python.org/pypi/python-epoll/"
                    " NOT http://pypi.python.org/pypi/pyepoll/. "
                    " easy_install pyepoll installs the wrong version.")

from eventlet.hubs.hub import BaseHub
from eventlet.hubs import poll
from eventlet.hubs.poll import READ, WRITE

# NOTE: we rely on the fact that the epoll flag constants
# are identical in value to the poll constants
示例#8
0
from os_win import _utils
from os_win import constants
from os_win import exceptions
from os_win.utils import win32utils
from os_win.utils.winapi import constants as w_const
from os_win.utils.winapi import libs as w_lib
from os_win.utils.winapi import wintypes

kernel32 = w_lib.get_shared_lib_handle(w_lib.KERNEL32)

LOG = logging.getLogger(__name__)

# Avoid using six.moves.queue as we need a non monkey patched class
if sys.version_info > (3, 0):
    Queue = patcher.original('queue')
else:
    Queue = patcher.original('Queue')

WAIT_PIPE_DEFAULT_TIMEOUT = 5  # seconds
WAIT_IO_COMPLETION_TIMEOUT = 2 * units.k
WAIT_INFINITE_TIMEOUT = 0xFFFFFFFF

IO_QUEUE_TIMEOUT = 2
IO_QUEUE_BURST_TIMEOUT = 0.05


class IOUtils(object):
    """Asyncronous IO helper class."""
    def __init__(self):
        self._win32_utils = win32utils.Win32Utils()
示例#9
0
文件: hub.py 项目: hardys/eventlet
    def alarm_itimer(seconds):
        signal.setitimer(signal.ITIMER_REAL, seconds)
    arm_alarm = alarm_itimer
else:
    try:
        import itimer
        arm_alarm = itimer.alarm
    except ImportError:
        def alarm_signal(seconds):
            signal.alarm(math.ceil(seconds))
        arm_alarm = alarm_signal

from eventlet import patcher
from eventlet.hubs import timer, IOClosed
from eventlet.support import greenlets as greenlet, clear_sys_exc_info
time = patcher.original('time')

g_prevent_multiple_readers = True

READ = "read"
WRITE = "write"


def closed_callback(fileno):
    """ Used to de-fang a callback that may be triggered by a loop in BaseHub.wait
    """
    # No-op.
    pass


class FdListener(object):
# An eventlet profiler, heavily influenced and parts borrowed from:
#   https://bitbucket.org/rtyler/eventlet/src/6fab81818ccd/eventlet/green/profile.py
# 

import nested_profile
profile_orig = nested_profile

for var in profile_orig.__all__:
    exec "%s = profile_orig.%s" % (var, var)

import functools

from eventlet import greenthread
from eventlet import patcher
thread = patcher.original('thread')  # non-monkeypatched module needed

class Profile(profile_orig.Profile):
    base = profile_orig.Profile
    def __init__(self, timer = None):
        self.current_tasklet = greenthread.getcurrent()
        self.base.__init__(self, timer)
        self.sleeping = {}

    def _setup(self):
        self.tasks = self._create_timing_store()
        self.call = self._create_timing_store()
        self.call_stack = [self.call]
        self.current_tasklet = greenthread.getcurrent()
        self.start_call = self.call
        self.start_time = self.timer()
示例#11
0
CONF = cfg.CONF

# it is a risk for using 'os_region_name', because it deprecated in DEFAULT
# group in Juno
compute_opts = [
    cfg.StrOpt('os_region_name',
               help='region of compute',
               deprecated_group='DEFAULT',
               deprecated_name='os_region_name')
]
CONF.register_opts(compute_opts)

LOG = logging.getLogger(__name__)

native_threading = patcher.original("threading")
native_Queue = patcher.original("Queue")

uvp_fault_channel = __import__('uvp_fault_chan')

# kernel panic
RTEV_FAULT_KERNEL_PANIC = 0
# watchdog timeout
RTEV_FAULT_WDT_TMOUT = 1
# watchdog pre timeout
RTEV_FAULT_WDT_PRE_TMOUT = 2
# nmi operation finished
RTEV_NMI_OPERATION_FINISHED = 6

SOFT_REBOOT_NMI = 1 << 8
HARD_REBOOT_NMI = 2 << 8
示例#12
0
import errno

from eventlet import patcher
from eventlet.hubs.v1_hub import BaseHub
from eventlet import support

select = patcher.original('select')
ev_sleep = patcher.original('time').sleep


def is_available():
    return hasattr(select, 'select')


try:
    BAD_SOCK = (errno.EBADF, errno.WSAENOTSOCK)
except AttributeError:
    BAD_SOCK = (errno.EBADF, )


class Hub(BaseHub):
    def _remove_bad_fds(self):
        """ Iterate through fds, removing the ones that are bad per the
        operating system.
        """
        for fd in list(self.listeners[self.READ]) + list(
                self.listeners[self.WRITE]):
            try:
                select.select([fd], [], [], 0)
            except select.error as e:
                if support.get_errno(e) in BAD_SOCK:
示例#13
0
文件: tpool.py 项目: Cue/eventlet
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import imp
import os
import sys

from eventlet import event
from eventlet import greenio
from eventlet import greenthread
from eventlet import patcher
from eventlet import timeout

threading = patcher.original("threading")
Queue_module = patcher.original("Queue")
Queue = Queue_module.Queue
Empty = Queue_module.Empty

__all__ = ["execute", "Proxy", "killall"]

QUIET = True

_rfile = _wfile = None

_bytetosend = " ".encode()


def _signal_t2e():
    _wfile.write(_bytetosend)
FIXME: No testcases for this module. 
"""

profile_orig = __import__("profile")
globals().update(dict([(var, getattr(profile_orig, var)) for var in dir(profile_orig) if not var.startswith("__")]))
__all__ = profile_orig.__all__

import new
import sys
import traceback
import functools

from eventlet import greenthread
from eventlet import patcher

thread = patcher.original("thread")  # non-monkeypatched module needed

# This class provides the start() and stop() functions
class Profile(profile_orig.Profile):
    base = profile_orig.Profile

    def __init__(self, timer=None, bias=None):
        self.current_tasklet = greenthread.getcurrent()
        self.thread_id = thread.get_ident()
        self.base.__init__(self, timer, bias)
        self.sleeping = {}

    def __call__(self, *args):
        "make callable, allowing an instance to be the profiler"
        r = self.dispatcher(*args)
示例#15
0
"""

profile_orig = __import__('profile')
__all__ = profile_orig.__all__

from eventlet.patcher import slurp_properties
slurp_properties(profile_orig, globals(), srckeys=dir(profile_orig))

import sys
import functools

from eventlet import greenthread
from eventlet import patcher
from eventlet.support import six

thread = patcher.original(six.moves._thread.__name__)  # non-monkeypatched module needed


# This class provides the start() and stop() functions
class Profile(profile_orig.Profile):
    base = profile_orig.Profile

    def __init__(self, timer=None, bias=None):
        self.current_tasklet = greenthread.getcurrent()
        self.thread_id = thread.get_ident()
        self.base.__init__(self, timer, bias)
        self.sleeping = {}

    def __call__(self, *args):
        """make callable, allowing an instance to be the profiler"""
        self.dispatcher(*args)
示例#16
0
"""Queued event dispatcher"""
import eventlet
from eventlet import patcher

from oslo_log import log as logging

native_threading = patcher.original("threading")
LOG = logging.getLogger(__name__)


class Dispatcher(object):
    """Adapter class to create native thread or eventlet green thread
    dispatcher"""
    def __init__(self, thread_type):
        self.t = None
        self.t_type = thread_type
        self.alive = False

    @classmethod
    def create(cls, thread_type, func, *args, **kwargs):
        """ Spawn a new dispatcher thread
        * @thread_type: 'nativethread' or 'greenthread'
        * @func: thread will start executing func
        * @args: args for func
        * @kwargs: kwargs for func
        """
        dispatcher = cls(thread_type)

        if thread_type == 'greenthread':
            dispatcher._green_thread_dispatcher(func, *args, **kwargs)
        else:
示例#17
0
 def event_cls(cls):
     from eventlet.patcher import original
     return original('threading').Event
CONF = cfg.CONF

# it is a risk for using 'os_region_name', because it deprecated in DEFAULT
# group in Juno
compute_opts = [
    cfg.StrOpt('os_region_name',
               help='region of compute',
               deprecated_group='DEFAULT',
               deprecated_name='os_region_name')
]
CONF.register_opts(compute_opts)

LOG = logging.getLogger(__name__)

native_threading = patcher.original("threading")
native_Queue = patcher.original("Queue")

uvp_fault_channel = __import__('uvp_fault_chan')

# kernel panic
RTEV_FAULT_KERNEL_PANIC = 0
# watchdog timeout
RTEV_FAULT_WDT_TMOUT = 1
# watchdog pre timeout
RTEV_FAULT_WDT_PRE_TMOUT = 2
# nmi operation finished
RTEV_NMI_OPERATION_FINISHED = 6

SOFT_REBOOT_NMI = 1 << 8
HARD_REBOOT_NMI = 2 << 8
示例#19
0
文件: kqueue.py 项目: Dostonbek1/NOL
import os
import sys
from eventlet import patcher, support
import six
select = patcher.original('select')
time = patcher.original('time')

from eventlet.hubs.hub import BaseHub, READ, WRITE, noop

if getattr(select, 'kqueue', None) is None:
    raise ImportError('No kqueue implementation found in select module')

FILTERS = {READ: select.KQ_FILTER_READ, WRITE: select.KQ_FILTER_WRITE}


class Hub(BaseHub):
    MAX_EVENTS = 100

    def __init__(self, clock=None):
        super(Hub, self).__init__(clock)
        self._events = {}
        self._init_kqueue()

    def _init_kqueue(self):
        self.kqueue = select.kqueue()
        self._pid = os.getpid()

    def _reinit_kqueue(self):
        self.kqueue.close()
        self._init_kqueue()
        kqueue = self.kqueue
示例#20
0
"""

profile_orig = __import__('profile')
__all__ = profile_orig.__all__

from eventlet.patcher import slurp_properties
slurp_properties(profile_orig, globals(), srckeys=dir(profile_orig))

import sys
import functools

from eventlet import greenthread
from eventlet import patcher
from eventlet.support import six

thread = patcher.original(six.moves._thread.__name__)  # non-monkeypatched module needed


# This class provides the start() and stop() functions
class Profile(profile_orig.Profile):
    base = profile_orig.Profile

    def __init__(self, timer=None, bias=None):
        self.current_tasklet = greenthread.getcurrent()
        self.thread_id = thread.get_ident()
        self.base.__init__(self, timer, bias)
        self.sleeping = {}

    def __call__(self, *args):
        """make callable, allowing an instance to be the profiler"""
        self.dispatcher(*args)
示例#21
0
import nova.conf
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova import rpc
from nova import utils
from nova.virt import event as virtevent
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import guest as libvirt_guest

libvirt = None

LOG = logging.getLogger(__name__)

native_socket = patcher.original('socket')
native_threading = patcher.original("threading")
native_Queue = patcher.original("Queue" if six.PY2 else "queue")

CONF = nova.conf.CONF

# This list is for libvirt hypervisor drivers that need special handling.
# This is *not* the complete list of supported hypervisor drivers.
HV_DRIVER_QEMU = "QEMU"
HV_DRIVER_XEN = "Xen"


class Host(object):
    def __init__(self,
                 uri,
                 read_only=False,
示例#22
0
import errno
from eventlet.support import get_errno
from eventlet import patcher
select = patcher.original('select')
if not hasattr(select, 'epoll'):
    # TODO: remove mention of python-epoll on 2019-01
    raise ImportError('No epoll implementation found in select module.'
                      ' python-epoll (or similar) package support was removed,'
                      ' please open issue on https://github.com/eventlet/eventlet/'
                      ' if you must use epoll outside stdlib.')
epoll = select.epoll

from eventlet.hubs.hub import BaseHub
from eventlet.hubs import poll
from eventlet.hubs.poll import READ, WRITE

# NOTE: we rely on the fact that the epoll flag constants
# are identical in value to the poll constants


class Hub(poll.Hub):
    def __init__(self, clock=None):
        BaseHub.__init__(self, clock)
        self.poll = epoll()

    def add(self, evtype, fileno, cb, tb, mac):
        oldlisteners = bool(self.listeners[READ].get(fileno) or
                            self.listeners[WRITE].get(fileno))
        listener = BaseHub.add(self, evtype, fileno, cb, tb, mac)
        try:
            if not oldlisteners:
示例#23
0
import struct
import sys

from eventlet import patcher
from nova.i18n import _
from oslo_log import log as logging
from oslo_utils import units

from hyperv.nova import constants
from hyperv.nova import vmutils

LOG = logging.getLogger(__name__)

# Avoid using six.moves.queue as we need a non monkey patched class
if sys.version_info > (3, 0):
    Queue = patcher.original('queue')
else:
    Queue = patcher.original('Queue')

if sys.platform == 'win32':
    from ctypes import wintypes

    kernel32 = ctypes.windll.kernel32

    class OVERLAPPED(ctypes.Structure):
        _fields_ = [
            ('Internal', wintypes.ULONG),
            ('InternalHigh', wintypes.ULONG),
            ('Offset', wintypes.DWORD),
            ('OffsetHigh', wintypes.DWORD),
            ('hEvent', wintypes.HANDLE)
示例#24
0
文件: kqueue.py 项目: jf89/eventlet
import os
import sys
from eventlet import patcher

select = patcher.original("select")
time = patcher.original("time")
sleep = time.sleep

from eventlet.support import get_errno, clear_sys_exc_info
from eventlet.hubs.hub import BaseHub, READ, WRITE, noop


if getattr(select, "kqueue", None) is None:
    raise ImportError("No kqueue implementation found in select module")


FILTERS = {READ: select.KQ_FILTER_READ, WRITE: select.KQ_FILTER_WRITE}


class Hub(BaseHub):
    MAX_EVENTS = 100

    def __init__(self, clock=time.time):
        super(Hub, self).__init__(clock)
        self._events = {}
        self._init_kqueue()

    def _init_kqueue(self):
        self.kqueue = select.kqueue()
        self._pid = os.getpid()
示例#25
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import imp
import os
import sys

from eventlet import event
from eventlet import greenio
from eventlet import greenthread
from eventlet import patcher
from eventlet import timeout
threading = patcher.original('threading')
Queue_module = patcher.original('Queue')
Queue = Queue_module.Queue
Empty = Queue_module.Empty

__all__ = ['execute', 'Proxy', 'killall']

QUIET=True

_rfile = _wfile = None

_bytetosend = ' '.encode()

def _signal_t2e():
    _wfile.write(_bytetosend)
    _wfile.flush()
示例#26
0
"""

profile_orig = __import__('profile')
globals().update(
    dict([(var, getattr(profile_orig, var)) for var in dir(profile_orig)
          if not var.startswith('__')]))
__all__ = profile_orig.__all__

import new
import sys
import traceback
import functools

from eventlet import greenthread
from eventlet import patcher
thread = patcher.original('thread')  # non-monkeypatched module needed


#This class provides the start() and stop() functions
class Profile(profile_orig.Profile):
    base = profile_orig.Profile

    def __init__(self, timer=None, bias=None):
        self.current_tasklet = greenthread.getcurrent()
        self.thread_id = thread.get_ident()
        self.base.__init__(self, timer, bias)
        self.sleeping = {}

    def __call__(self, *args):
        "make callable, allowing an instance to be the profiler"
        r = self.dispatcher(*args)
示例#27
0
from eventlet import greenio
from eventlet import patcher
from eventlet.green import select, threading, time
from eventlet.support import six


__patched__ = ["call", "check_call", "Popen"]
to_patch = [("select", select), ("threading", threading), ("time", time)]

if sys.version_info > (3, 4):
    from eventlet.green import selectors

    to_patch.append(("selectors", selectors))

patcher.inject("subprocess", globals(), *to_patch)
subprocess_orig = patcher.original("subprocess")
mswindows = sys.platform == "win32"


if getattr(subprocess_orig, "TimeoutExpired", None) is None:
    # Backported from Python 3.3.
    # https://bitbucket.org/eventlet/eventlet/issue/89
    class TimeoutExpired(Exception):
        """This exception is raised when the timeout expires while waiting for
        a child process.
        """

        def __init__(self, cmd, timeout, output=None):
            self.cmd = cmd
            self.timeout = timeout
            self.output = output
示例#28
0
__author__ = 'yokoi-h'

import time
import eventlet

eventlet.monkey_patch()

from eventlet import patcher
orig_time = patcher.original('time')


def greenthread1():
    print('spawn greenthread1')
    while True:
        print('before sleep Green Thread: 1')
        time.sleep(0.1)
        print('after sleep Green Thread: 1')


def greenthread2():
    print('spawn greenthread2')
    while True:
        print('-----------------------------before sleep Green Thread: 2')
        time.sleep(5)
        print('-----------------------------after sleep Green Thread: 2')


if __name__ == '__main__':
    t1 = eventlet.spawn(greenthread1)
    t2 = eventlet.spawn(greenthread2)
    print(t1)
示例#29
0
import eventlet
from eventlet import greenio
from eventlet import patcher
from eventlet.green import select, threading, time
from eventlet.support import six

__patched__ = ['call', 'check_call', 'Popen']
to_patch = [('select', select), ('threading', threading), ('time', time)]

if sys.version_info > (3, 4):
    from eventlet.green import selectors
    to_patch.append(('selectors', selectors))

patcher.inject('subprocess', globals(), *to_patch)
subprocess_orig = patcher.original("subprocess")
mswindows = sys.platform == "win32"

if getattr(subprocess_orig, 'TimeoutExpired', None) is None:
    # Backported from Python 3.3.
    # https://bitbucket.org/eventlet/eventlet/issue/89
    class TimeoutExpired(Exception):
        """This exception is raised when the timeout expires while waiting for
        a child process.
        """
        def __init__(self, cmd, timeout, output=None):
            self.cmd = cmd
            self.timeout = timeout
            self.output = output

        def __str__(self):
示例#30
0
import os
import sys
import traceback

from eventlet import event, greenio, greenthread, patcher, timeout
from eventlet.support import six

__all__ = ['execute', 'Proxy', 'killall', 'set_num_threads']


EXC_CLASSES = (Exception, timeout.Timeout)
SYS_EXCS = (GeneratorExit, KeyboardInterrupt, SystemExit)

QUIET = True

socket = patcher.original('socket')
threading = patcher.original('threading')
if six.PY2:
    Queue_module = patcher.original('Queue')
if six.PY3:
    Queue_module = patcher.original('queue')

Empty = Queue_module.Empty
Queue = Queue_module.Queue

_bytetosend = ' '.encode()
_coro = None
_nthreads = int(os.environ.get('EVENTLET_THREADPOOL_SIZE', 20))
_reqq = _rspq = None
_rsock = _wsock = None
_setup_already = False
示例#31
0
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import errno
import os

from eventlet import patcher
from oslo_log import log as logging

from os_win._i18n import _
from os_win import constants
from os_win import exceptions
from os_win.utils.io import ioutils

threading = patcher.original('threading')
time = patcher.original('time')

LOG = logging.getLogger(__name__)


class NamedPipeHandler(object):
    """Handles asyncronous I/O operations on a specified named pipe."""

    _MAX_LOG_ROTATE_RETRIES = 5

    def __init__(self,
                 pipe_name,
                 input_queue=None,
                 output_queue=None,
                 connect_event=None,
示例#32
0
import six
import struct
import sys

from eventlet import patcher
from oslo_log import log as logging
from oslo_utils import units

from os_win import _utils
from os_win import constants
from os_win import exceptions
from os_win.utils import win32utils

LOG = logging.getLogger(__name__)

native_threading = patcher.original('threading')

# Avoid using six.moves.queue as we need a non monkey patched class
if sys.version_info > (3, 0):
    Queue = patcher.original('queue')
else:
    Queue = patcher.original('Queue')

if sys.platform == 'win32':
    from ctypes import wintypes

    kernel32 = ctypes.windll.kernel32

    class OVERLAPPED(ctypes.Structure):
        _fields_ = [
            ('Internal', wintypes.ULONG),
示例#33
0
    try:
        import itimer

        arm_alarm = itimer.alarm
    except ImportError:

        def alarm_signal(seconds):
            signal.alarm(math.ceil(seconds))

        arm_alarm = alarm_signal

from eventlet.support import greenlets as greenlet, clear_sys_exc_info
from eventlet.hubs import timer
from eventlet import patcher

time = patcher.original("time")

g_prevent_multiple_readers = True

READ = "read"
WRITE = "write"


class FdListener(object):
    def __init__(self, evtype, fileno, cb):
        assert evtype is READ or evtype is WRITE
        self.evtype = evtype
        self.fileno = fileno
        self.cb = cb

    def __repr__(self):
示例#34
0
文件: host.py 项目: ddonwang/nova
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova import rpc
from nova import utils
from nova.virt import event as virtevent
from nova.virt.libvirt import compat
from nova.virt.libvirt import config as vconfig

libvirt = None

LOG = logging.getLogger(__name__)

native_socket = patcher.original('socket')
native_threading = patcher.original("threading")
native_Queue = patcher.original("Queue")

CONF = cfg.CONF
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')


class DomainJobInfo(object):
    """Information about libvirt background jobs

    This class encapsulates information about libvirt
    background jobs. It provides a mapping from either
    the old virDomainGetJobInfo API which returned a
    fixed list of fields, or the modern virDomainGetJobStats
示例#35
0
import os
import six
import struct
import sys

from eventlet import patcher
from oslo_log import log as logging
from oslo_utils import units

from os_win import constants
from os_win import exceptions
from os_win.utils import win32utils

LOG = logging.getLogger(__name__)

native_threading = patcher.original('threading')

# Avoid using six.moves.queue as we need a non monkey patched class
if sys.version_info > (3, 0):
    Queue = patcher.original('queue')
else:
    Queue = patcher.original('Queue')

if sys.platform == 'win32':
    from ctypes import wintypes

    kernel32 = ctypes.windll.kernel32

    class OVERLAPPED(ctypes.Structure):
        _fields_ = [('Internal', wintypes.ULONG),
                    ('InternalHigh', wintypes.ULONG),
示例#36
0
from nova import context as nova_context
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova import rpc
from nova import utils
from nova.virt import event as virtevent
from nova.virt.libvirt import config as vconfig

libvirt = None

LOG = logging.getLogger(__name__)

native_socket = patcher.original('socket')
native_threading = patcher.original("threading")
native_Queue = patcher.original("Queue")

CONF = cfg.CONF
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')


class DomainJobInfo(object):
    """Information about libvirt background jobs

    This class encapsulates information about libvirt
    background jobs. It provides a mapping from either
    the old virDomainGetJobInfo API which returned a
    fixed list of fields, or the modern virDomainGetJobStats
import socket

from eventlet import patcher

from nova import exception
from nova.i18n import _
from nova.virt.hyperv import constants

# Note(lpetrut): Eventlet greenpipes are not supported on Windows. The named
# pipe handlers implemented in os-win use Windows API calls which can block
# the whole thread. In order to avoid this, those workers run in separate
# 'native' threads.
#
# As this proxy communicates with those workers via queues, the serial console
# proxy workers have to run in 'native' threads as well.
threading = patcher.original('threading')


def handle_socket_errors(func):
    @functools.wraps(func)
    def wrapper(self, *args, **kwargs):
        try:
            return func(self, *args, **kwargs)
        except socket.error:
            self._client_connected.clear()
    return wrapper


class SerialProxy(threading.Thread):
    def __init__(self, instance_name, addr, port, input_queue,
                 output_queue, client_connected):
示例#38
0
文件: tpool.py 项目: c0ns0le/zenoss-4
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import imp
import os
import sys

from eventlet import event
from eventlet import greenio
from eventlet import greenthread
from eventlet import patcher
threading = patcher.original('threading')
Queue_module = patcher.original('Queue')
Queue = Queue_module.Queue
Empty = Queue_module.Empty

__all__ = ['execute', 'Proxy', 'killall']

QUIET = True

_rfile = _wfile = None

_bytetosend = ' '.encode()


def _signal_t2e():
    _wfile.write(_bytetosend)
示例#39
0
文件: host.py 项目: zouyapeng/nova
from nova import exception
from nova.i18n import _
from nova.i18n import _LE
from nova.i18n import _LI
from nova.i18n import _LW
from nova import rpc
from nova import utils
from nova.virt import event as virtevent
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import guest as libvirt_guest

libvirt = None

LOG = logging.getLogger(__name__)

native_socket = patcher.original('socket')
native_threading = patcher.original("threading")
native_Queue = patcher.original("queue" if six.PY3 else "Queue")

CONF = cfg.CONF
CONF.import_opt('host', 'nova.netconf')
CONF.import_opt('my_ip', 'nova.netconf')


# This list is for libvirt hypervisor drivers that need special handling.
# This is *not* the complete list of supported hypervisor drivers.
HV_DRIVER_QEMU = "QEMU"
HV_DRIVER_XEN = "Xen"


class DomainJobInfo(object):
示例#40
0
import errno
from eventlet import support
from eventlet import patcher

from eventlet.hubs.v1_hub import BaseHub
from eventlet.hubs import v1_poll

select = patcher.original('select')


def is_available():
    return hasattr(select, 'epoll')


class Hub(v1_poll.Hub):
    def __init__(self, clock=None):
        BaseHub.__init__(self, clock)
        self.poll = select.epoll()

    def add(self, *args):
        """ *args: evtype, fileno, cb, tb, mac """
        new = not self.has_listeners_fileno(args[1])
        listener = self.add_listener(*args)
        try:
            self.register(args[1], new=new)
        except IOError as ex:
            # ignore EEXIST, #80
            if support.get_errno(ex) != errno.EEXIST:
                raise
        return listener
示例#41
0
import sys
import errno
from eventlet import patcher
select = patcher.original('select')
time = patcher.original('time')

from eventlet.hubs.hub import BaseHub, READ, WRITE

try:
    BAD_SOCK = set((errno.EBADF, errno.WSAENOTSOCK))
except AttributeError:
    BAD_SOCK = set((errno.EBADF,))

class Hub(BaseHub):
    def _remove_bad_fds(self):
        """ Iterate through fds, removing the ones that are bad per the
        operating system.
        """
        for fd in self.listeners[READ].keys() + self.listeners[WRITE].keys():
            try:
                select.select([fd], [], [], 0)
            except select.error, e:
                if e.args[0] == errno.EBADF:
                    self.remove_descriptor(fd)

    def wait(self, seconds=None):
        readers = self.listeners[READ]
        writers = self.listeners[WRITE]
        if not readers and not writers:
            if seconds:
                time.sleep(seconds)
示例#42
0
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import errno
import os

from eventlet import patcher
from nova.i18n import _, _LE  # noqa
from oslo_log import log as logging

from hyperv.nova import constants
from hyperv.nova import ioutils
from hyperv.nova import vmutils

threading = patcher.original('threading')
time = patcher.original('time')

LOG = logging.getLogger(__name__)


class NamedPipeHandler(object):
    """Handles asyncronous I/O operations on a specified named pipe."""

    _MAX_LOG_ROTATE_RETRIES = 5

    def __init__(self, pipe_name, input_queue=None, output_queue=None,
                 connect_event=None, log_file=None):
        self._pipe_name = pipe_name
        self._input_queue = input_queue
        self._output_queue = output_queue
示例#43
0
文件: tpool.py 项目: rdw/Eventlet
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys

from Queue import Empty, Queue

from eventlet import event
from eventlet import greenio
from eventlet import greenthread
from eventlet import patcher

threading = patcher.original("threading")

__all__ = ["execute", "Proxy", "killall"]

QUIET = True

_rfile = _wfile = None

_bytetosend = " ".encode()


def _signal_t2e():
    _wfile.write(_bytetosend)
    _wfile.flush()

示例#44
0
import eventlet
eventlet.monkey_patch(os=False)

from eventlet import patcher
from eventlet import tpool
import libvirt
import six
import threading

from oslo_log import log as logging
from oslo_config import cfg


native_threading = patcher.original("threading")
native_queue = patcher.original("Queue" if six.PY2 else "queue")

CONF = cfg.CONF
LOG = logging.getLogger(__name__)


def init_logs(product="default_project"):
    logging.register_options(CONF)

    CONF.logging_exception_prefix = \
        "%(color)s%(asctime)s.%(msecs)03d " \
        "TRACE %(name)s %(instance)s"
    CONF.logging_debug_format_suffix = \
        "from " \
        "(pid=%(process)d) %(funcName)s %(pathname)s:%(lineno)d"
    CONF.logging_default_format_string = \
        "%(asctime)s.%(msecs)03d %(color)s%(levelname)s %(name)s " \