How to use the eventlet.Timeout function in eventlet

To help you get started, we’ve selected a few eventlet examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github openstack / swift / test / unit / container / test_server.py View on Github external
def accept(return_code, expected_timestamp):
            try:
                with Timeout(3):
                    sock, addr = bindsock.accept()
                    inc = sock.makefile('rb')
                    out = sock.makefile('wb')
                    out.write('HTTP/1.1 %d OK\r\nContent-Length: 0\r\n\r\n' %
                              return_code)
                    out.flush()
                    self.assertEqual(inc.readline(),
                                     'PUT /sda1/123/a/c HTTP/1.1\r\n')
                    headers = {}
                    line = inc.readline()
                    while line and line != '\r\n':
                        headers[line.split(':')[0].lower()] = \
                            line.split(':')[1].strip()
                        line = inc.readline()
                    self.assertEqual(headers['x-delete-timestamp'],
                                     expected_timestamp)
github openstack / swift / test / unit / __init__.py View on Github external
def getresponse(self):
            exc = kwargs.get('raise_exc')
            if exc:
                if isinstance(exc, (Exception, eventlet.Timeout)):
                    raise exc
                raise Exception('test')
            if kwargs.get('raise_timeout_exc'):
                raise eventlet.Timeout()
            self.status = self._status.get_response_status()
            return self
github temoto / heroshi / heroshi / worker / tests.py View on Github external
def test_crawl_001(self):
        """Must call `api.get_crawl_queue()`."""

        smock.mock('api.get_crawl_queue', returns=[])
        with eventlet.Timeout(DEFAULT_TIMEOUT, False):
            self.client.crawl()
        self.assertTrue(smock.is_called('api.get_crawl_queue'))
github gluster / gluster-swift / test / unit / proxy / controllers / test_obj.py View on Github external
def test_PUT_commit_timeout(self):
        req = swift.common.swob.Request.blank('/v1/a/c/o', method='PUT',
                                              body='')
        codes = [201] * (self.replicas() - 1)
        codes.append((100, Timeout(), Exception('not used')))
        expect_headers = {
            'X-Obj-Metadata-Footer': 'yes',
            'X-Obj-Multiphase-Commit': 'yes'
        }
        with set_http_connect(*codes, expect_headers=expect_headers):
            resp = req.get_response(self.app)
        self.assertEquals(resp.status_int, 201)
github openstack / swift / swift / common / memcached.py View on Github external
:param key: key
        :param delta: amount to add to the value of key (or set as the value
                      if the key is not found) will be cast to an int
        :param time: the time to live
        :returns: result of incrementing
        :raises MemcacheConnectionError:
        """
        key = md5hash(key)
        command = b'incr'
        if delta < 0:
            command = b'decr'
        delta = str(abs(int(delta))).encode('ascii')
        timeout = sanitize_timeout(time)
        for (server, fp, sock) in self._get_conns(key):
            try:
                with Timeout(self._io_timeout):
                    sock.sendall(b' '.join([
                        command, key, delta]) + b'\r\n')
                    line = fp.readline().strip().split()
                    if not line:
                        raise MemcacheConnectionError('incomplete read')
                    if line[0].upper() == b'NOT_FOUND':
                        add_val = delta
                        if command == b'decr':
                            add_val = b'0'
                        sock.sendall(b' '.join([
                            b'add', key, b'0', str(timeout).encode('ascii'),
                            str(len(add_val)).encode('ascii')
                        ]) + b'\r\n' + add_val + b'\r\n')
                        line = fp.readline().strip().split()
                        if line[0].upper() == b'NOT_STORED':
                            sock.sendall(b' '.join([
github openstack / swift / swift / common / memcached.py View on Github external
def get(self, key):
        """
        Gets the object specified by key.  It will also unserialize the object
        before returning if it is serialized in memcache with JSON, or if it
        is pickled and unpickling is allowed.

        :param key: key
        :returns: value of the key in memcache
        """
        key = md5hash(key)
        value = None
        for (server, fp, sock) in self._get_conns(key):
            try:
                with Timeout(self._io_timeout):
                    sock.sendall(b'get ' + key + b'\r\n')
                    line = fp.readline().strip().split()
                    while True:
                        if not line:
                            raise MemcacheConnectionError('incomplete read')
                        if line[0].upper() == b'END':
                            break
                        if line[0].upper() == b'VALUE' and line[1] == key:
                            size = int(line[3])
                            value = fp.read(size)
                            if int(line[2]) & PICKLE_FLAG:
                                if self._allow_unpickle:
                                    value = pickle.loads(value)
                                else:
                                    value = None
                            elif int(line[2]) & JSON_FLAG:
github MichaelStott / CRLF-Injection-Scanner / scanner.py View on Github external
def scan(self, url):
        """ Scan target URL for CRLF injection
        """
        result = False
        session = requests.Session()
        with eventlet.Timeout(self.TIMEOUT):
            try:
                session.get(url)
            except KeyboardInterrupt:
                raise
            except:
                pass
            if 'param' in session.cookies.get_dict() and\
                'crlf' in session.cookies.get_dict().values():
                result = True
        return result
github openstack / swift / swift / common / direct_client.py View on Github external
:param conn_timeout: timeout in seconds for establishing the connection
    :param response_timeout: timeout in seconds for getting the response
    :param resp_chunk_size: if defined, chunk size of data to read.
    :param headers: dict to be passed into HTTPConnection headers
    :returns: a tuple of (response headers, the object's contents) The response
              headers will be a HeaderKeyDict.
    :raises ClientException: HTTP GET request failed
    """
    if headers is None:
        headers = {}

    path = '/%s/%s/%s' % (account, container, obj)
    with Timeout(conn_timeout):
        conn = http_connect(node['ip'], node['port'], node['device'], part,
                            'GET', path, headers=gen_headers(headers))
    with Timeout(response_timeout):
        resp = conn.getresponse()
    if not is_success(resp.status):
        resp.read()
        raise DirectClientException('Object', 'GET', node, part, path, resp)

    if resp_chunk_size:

        def _object_body():
            buf = resp.read(resp_chunk_size)
            while buf:
                yield buf
                buf = resp.read(resp_chunk_size)
        object_body = _object_body()
    else:
        object_body = resp.read()
    resp_headers = HeaderKeyDict()
github openstack / swift / swift / container / sharder.py View on Github external
def _put_container(self, node, part, account, container, headers, body):
        try:
            direct_put_container(node, part, account, container,
                                 conn_timeout=self.conn_timeout,
                                 response_timeout=self.node_timeout,
                                 headers=headers, contents=body)
        except DirectClientException as err:
            self.logger.warning(
                'Failed to put shard ranges to %s:%s/%s: %s',
                node['ip'], node['port'], node['device'], err.http_status)
        except (Exception, Timeout) as err:
            self.logger.exception(
                'Failed to put shard ranges to %s:%s/%s: %s',
                node['ip'], node['port'], node['device'], err)
        else:
            return True
        return False
github openstack / tricircle / compute / compute_keystoneclient.py View on Github external
def delete_stack_user(self, user_id):

        user = self.client_v2.users.get(user_id)

        # FIXME (shardy) : need to test, do we still need this retry logic?
        # Copied from user.py, but seems like something we really shouldn't
        # need to do, no bug reference in the original comment (below)...
        # tempory hack to work around an openstack bug.
        # seems you can't delete a user first time - you have to try
        # a couple of times - go figure!
        tmo = eventlet.Timeout(10)
        status = 'WAITING'
        reason = 'Timed out trying to delete user'
        try:
            while status == 'WAITING':
                try:
                    user.delete()
                    status = 'DELETED'
                except Exception as ce:
                    reason = str(ce)
                    logger.warning("Problem deleting user %s: %s" %
                                   (user_id, reason))
                    eventlet.sleep(1)
        except eventlet.Timeout as t:
            if t is not tmo:
                # not my timeout
                raise