Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/AUTHORS +62 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/INSTALLER +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/LICENSE +25 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/METADATA +349 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/NOTICE +94 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/RECORD +558 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/WHEEL +6 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/entry_points.txt +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/top_level.txt +1 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/__init__.py +27 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/callback.py +57 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/loop.py +789 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/watcher.py +644 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/core.py +20 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/event.py +427 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/events.py +516 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/exceptions.py +136 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/fileobject.py +85 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/greenlet.py +1186 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/hub.py +909 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/__init__.py +7 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/_corecffi_build.py +126 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/corecffi.py +470 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/watcher.py +287 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/__init__.py +7 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/_corecffi_build.py +345 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/loop.py +690 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/watcher.py +762 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/local.py +610 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/lock.py +372 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__init__.py +704 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__main__.py +2 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_errors.py +26 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_main.py +117 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_common.py +311 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_gte313.py +91 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_lt313.py +78 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_state.py +70 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_util.py +105 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/api.py +199 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/os.py +543 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pool.py +677 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pywsgi.py +1727 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/queue.py +772 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/__init__.py +285 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_addresses.py +163 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_hostsfile.py +145 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/ares.py +355 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/blocking.py +45 -0
- miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/dnspython.py +511 -0
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/AUTHORS
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Gevent is written and maintained by
|
| 2 |
+
|
| 3 |
+
Denis Bilenko
|
| 4 |
+
Matt Iversen
|
| 5 |
+
Steffen Prince
|
| 6 |
+
Jason Madden
|
| 7 |
+
|
| 8 |
+
and the contributors (ordered by the date of first contribution):
|
| 9 |
+
|
| 10 |
+
Jason Toffaletti
|
| 11 |
+
Mike Barton
|
| 12 |
+
Ludvig Ericson
|
| 13 |
+
Marcus Cavanaugh
|
| 14 |
+
Matt Goodall
|
| 15 |
+
Ralf Schmitt
|
| 16 |
+
Daniele Varrazzo
|
| 17 |
+
Nicholas Piël
|
| 18 |
+
Örjan Persson
|
| 19 |
+
Uriel Katz
|
| 20 |
+
Ted Suzman
|
| 21 |
+
Randall Leeds
|
| 22 |
+
Erik Näslund
|
| 23 |
+
Alexey Borzenkov
|
| 24 |
+
David Hain
|
| 25 |
+
Dmitry Chechik
|
| 26 |
+
Ned Rockson
|
| 27 |
+
Tommie Gannert
|
| 28 |
+
Shaun Lindsay
|
| 29 |
+
Andreas Blixt
|
| 30 |
+
Nick Barkas
|
| 31 |
+
Galfy Pundee
|
| 32 |
+
Alexander Boudkar
|
| 33 |
+
Damien Churchill
|
| 34 |
+
Tom Lynn
|
| 35 |
+
Shaun Cutts
|
| 36 |
+
David LaBissoniere
|
| 37 |
+
Alexandre Kandalintsev
|
| 38 |
+
Geert Jansen
|
| 39 |
+
Vitaly Kruglikov
|
| 40 |
+
Saúl Ibarra Corretgé
|
| 41 |
+
Oliver Beattie
|
| 42 |
+
Bobby Powers
|
| 43 |
+
Anton Patrushev
|
| 44 |
+
Jan-Philip Gehrcke
|
| 45 |
+
Alex Gaynor
|
| 46 |
+
陈小玉
|
| 47 |
+
Philip Conrad
|
| 48 |
+
Heungsub Lee
|
| 49 |
+
Ron Rothman
|
| 50 |
+
|
| 51 |
+
See https://github.com/gevent/gevent/graphs/contributors for more info.
|
| 52 |
+
|
| 53 |
+
Gevent is inspired by and uses some code from eventlet which was written by
|
| 54 |
+
|
| 55 |
+
Bob Ipollito
|
| 56 |
+
Donovan Preston
|
| 57 |
+
|
| 58 |
+
The win32util module is taken from Twisted. The tblib module is taken from python-tblib by Ionel Cristian Mărieș.
|
| 59 |
+
|
| 60 |
+
Some modules (local, ssl) contain code from the Python standard library.
|
| 61 |
+
|
| 62 |
+
If your code is used in gevent and you are not mentioned above, please contact the maintainer.
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Except when otherwise stated (look at the beginning of each file) the software
|
| 4 |
+
and the documentation in this project are copyrighted by:
|
| 5 |
+
|
| 6 |
+
Denis Bilenko and the contributors, http://www.gevent.org
|
| 7 |
+
|
| 8 |
+
Permission is hereby granted, free of charge, to any person obtaining
|
| 9 |
+
a copy of this software and associated documentation files (the
|
| 10 |
+
"Software"), to deal in the Software without restriction, including
|
| 11 |
+
without limitation the rights to use, copy, modify, merge, publish,
|
| 12 |
+
distribute, sublicense, and/or sell copies of the Software, and to
|
| 13 |
+
permit persons to whom the Software is furnished to do so, subject to
|
| 14 |
+
the following conditions:
|
| 15 |
+
|
| 16 |
+
The above copyright notice and this permission notice shall be
|
| 17 |
+
included in all copies or substantial portions of the Software.
|
| 18 |
+
|
| 19 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
| 20 |
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 21 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
| 22 |
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
| 23 |
+
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
| 24 |
+
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
| 25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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: gevent
|
| 3 |
+
Version: 24.11.1
|
| 4 |
+
Summary: Coroutine-based network library
|
| 5 |
+
Home-page: http://www.gevent.org/
|
| 6 |
+
Author: Denis Bilenko
|
| 7 |
+
Author-email: denis.bilenko@gmail.com
|
| 8 |
+
Maintainer: Jason Madden
|
| 9 |
+
Maintainer-email: jason@nextthought.com
|
| 10 |
+
License: MIT
|
| 11 |
+
Project-URL: Bug Tracker, https://github.com/gevent/gevent/issues
|
| 12 |
+
Project-URL: Source Code, https://github.com/gevent/gevent/
|
| 13 |
+
Project-URL: Documentation, http://www.gevent.org
|
| 14 |
+
Project-URL: Changes, https://www.gevent.org/changelog.html
|
| 15 |
+
Keywords: greenlet coroutine cooperative multitasking light threads monkey
|
| 16 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 17 |
+
Classifier: Programming Language :: Python :: 3 :: Only
|
| 18 |
+
Classifier: Programming Language :: Python :: 3.9
|
| 19 |
+
Classifier: Programming Language :: Python :: 3.10
|
| 20 |
+
Classifier: Programming Language :: Python :: 3.11
|
| 21 |
+
Classifier: Programming Language :: Python :: 3.12
|
| 22 |
+
Classifier: Programming Language :: Python :: 3.13
|
| 23 |
+
Classifier: Programming Language :: Python :: Implementation :: CPython
|
| 24 |
+
Classifier: Programming Language :: Python :: Implementation :: PyPy
|
| 25 |
+
Classifier: Operating System :: MacOS :: MacOS X
|
| 26 |
+
Classifier: Operating System :: POSIX
|
| 27 |
+
Classifier: Operating System :: Microsoft :: Windows
|
| 28 |
+
Classifier: Topic :: Internet
|
| 29 |
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
| 30 |
+
Classifier: Intended Audience :: Developers
|
| 31 |
+
Classifier: Development Status :: 4 - Beta
|
| 32 |
+
Requires-Python: >=3.9
|
| 33 |
+
Description-Content-Type: text/x-rst
|
| 34 |
+
License-File: LICENSE
|
| 35 |
+
License-File: NOTICE
|
| 36 |
+
License-File: AUTHORS
|
| 37 |
+
Requires-Dist: zope.event
|
| 38 |
+
Requires-Dist: zope.interface
|
| 39 |
+
Requires-Dist: greenlet>=3.1.1; platform_python_implementation == "CPython"
|
| 40 |
+
Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and sys_platform == "win32"
|
| 41 |
+
Provides-Extra: dnspython
|
| 42 |
+
Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "dnspython"
|
| 43 |
+
Requires-Dist: idna; python_version < "3.10" and extra == "dnspython"
|
| 44 |
+
Provides-Extra: docs
|
| 45 |
+
Requires-Dist: sphinx; extra == "docs"
|
| 46 |
+
Requires-Dist: furo; extra == "docs"
|
| 47 |
+
Requires-Dist: repoze.sphinx.autointerface; extra == "docs"
|
| 48 |
+
Requires-Dist: sphinxcontrib-programoutput; extra == "docs"
|
| 49 |
+
Requires-Dist: zope.schema; extra == "docs"
|
| 50 |
+
Provides-Extra: events
|
| 51 |
+
Provides-Extra: monitor
|
| 52 |
+
Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "monitor"
|
| 53 |
+
Provides-Extra: recommended
|
| 54 |
+
Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and extra == "recommended"
|
| 55 |
+
Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "recommended"
|
| 56 |
+
Requires-Dist: idna; python_version < "3.10" and extra == "recommended"
|
| 57 |
+
Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "recommended"
|
| 58 |
+
Provides-Extra: test
|
| 59 |
+
Requires-Dist: requests; extra == "test"
|
| 60 |
+
Requires-Dist: objgraph; extra == "test"
|
| 61 |
+
Requires-Dist: cffi>=1.17.1; platform_python_implementation == "CPython" and extra == "test"
|
| 62 |
+
Requires-Dist: dnspython<2.0,>=1.16.0; python_version < "3.10" and extra == "test"
|
| 63 |
+
Requires-Dist: idna; python_version < "3.10" and extra == "test"
|
| 64 |
+
Requires-Dist: coverage>=5.0; sys_platform != "win32" and extra == "test"
|
| 65 |
+
Requires-Dist: psutil>=5.7.0; (sys_platform != "win32" or platform_python_implementation == "CPython") and extra == "test"
|
| 66 |
+
|
| 67 |
+
========
|
| 68 |
+
gevent
|
| 69 |
+
========
|
| 70 |
+
|
| 71 |
+
.. image:: https://github.com/gevent/gevent/workflows/gevent%20testing/badge.svg
|
| 72 |
+
:target: https://github.com/gevent/gevent/actions
|
| 73 |
+
|
| 74 |
+
.. image:: https://ci.appveyor.com/api/projects/status/bqxl88yhpho223jg?svg=true
|
| 75 |
+
:target: https://ci.appveyor.com/project/denik/gevent
|
| 76 |
+
|
| 77 |
+
.. image:: https://coveralls.io/repos/gevent/gevent/badge.svg?branch=master&service=github
|
| 78 |
+
:target: https://coveralls.io/github/gevent/gevent?branch=master
|
| 79 |
+
|
| 80 |
+
..
|
| 81 |
+
This file is included in README.rst from the top-level
|
| 82 |
+
so it is limited to pure ReST markup, not Sphinx.
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
gevent is a coroutine_ -based Python_ networking library that uses
|
| 87 |
+
`greenlet <https://greenlet.readthedocs.io>`_ to provide a high-level synchronous API on top of the `libev`_
|
| 88 |
+
or `libuv`_ event loop.
|
| 89 |
+
|
| 90 |
+
Features include:
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
* Fast event loop based on `libev`_ or `libuv`_.
|
| 94 |
+
* Lightweight execution units based on greenlets.
|
| 95 |
+
* API that re-uses concepts from the Python standard library (for
|
| 96 |
+
examples there are `events`_ and
|
| 97 |
+
`queues`_).
|
| 98 |
+
* `Cooperative sockets with SSL support <http://www.gevent.org/api/index.html#networking>`_
|
| 99 |
+
* `Cooperative DNS queries <http://www.gevent.org/dns.html>`_ performed through a threadpool,
|
| 100 |
+
dnspython, or c-ares.
|
| 101 |
+
* `Monkey patching utility <http://www.gevent.org/intro.html#monkey-patching>`_ to get 3rd party modules to become cooperative
|
| 102 |
+
* TCP/UDP/HTTP servers
|
| 103 |
+
* Subprocess support (through `gevent.subprocess`_)
|
| 104 |
+
* Thread pools
|
| 105 |
+
|
| 106 |
+
gevent is `inspired by eventlet`_ but features a more consistent API,
|
| 107 |
+
simpler implementation and better performance. Read why others `use
|
| 108 |
+
gevent`_ and check out the list of the `open source projects based on
|
| 109 |
+
gevent`_.
|
| 110 |
+
|
| 111 |
+
gevent was written by `Denis Bilenko <http://denisbilenko.com/>`_.
|
| 112 |
+
|
| 113 |
+
Since version 1.1, gevent is maintained by Jason Madden for
|
| 114 |
+
`NextThought <https://nextthought.com>`_ (through gevent 21) and
|
| 115 |
+
`Institutional Shareholder Services <https://www.issgovernance.com>`_
|
| 116 |
+
with help from the `contributors
|
| 117 |
+
<https://github.com/gevent/gevent/graphs/contributors>`_ and is
|
| 118 |
+
licensed under the MIT license.
|
| 119 |
+
|
| 120 |
+
See `what's new`_ in the latest major release.
|
| 121 |
+
|
| 122 |
+
Check out the detailed changelog_ for this version.
|
| 123 |
+
|
| 124 |
+
.. _events: http://www.gevent.org/api/gevent.event.html#gevent.event.Event
|
| 125 |
+
.. _queues: http://www.gevent.org/api/gevent.queue.html#gevent.queue.Queue
|
| 126 |
+
.. _gevent.subprocess: http://www.gevent.org/api/gevent.subprocess.html#module-gevent.subprocess
|
| 127 |
+
|
| 128 |
+
.. _coroutine: https://en.wikipedia.org/wiki/Coroutine
|
| 129 |
+
.. _Python: http://python.org
|
| 130 |
+
.. _libev: http://software.schmorp.de/pkg/libev.html
|
| 131 |
+
.. _libuv: http://libuv.org
|
| 132 |
+
.. _inspired by eventlet: http://blog.gevent.org/2010/02/27/why-gevent/
|
| 133 |
+
.. _use gevent: http://groups.google.com/group/gevent/browse_thread/thread/4de9703e5dca8271
|
| 134 |
+
.. _open source projects based on gevent: https://github.com/gevent/gevent/wiki/Projects
|
| 135 |
+
.. _what's new: http://www.gevent.org/whatsnew_1_5.html
|
| 136 |
+
.. _changelog: http://www.gevent.org/changelog.html
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
Read the documentation online at http://www.gevent.org.
|
| 140 |
+
|
| 141 |
+
Post issues on the `bug tracker`_, discuss and ask open ended
|
| 142 |
+
questions on the `mailing list`_, and find announcements and
|
| 143 |
+
information on the blog_ and `twitter (@gevent)`_.
|
| 144 |
+
|
| 145 |
+
===============================
|
| 146 |
+
Installation and Requirements
|
| 147 |
+
===============================
|
| 148 |
+
|
| 149 |
+
.. _installation:
|
| 150 |
+
|
| 151 |
+
..
|
| 152 |
+
This file is included in README.rst so it is limited to plain
|
| 153 |
+
ReST markup, not Sphinx.
|
| 154 |
+
|
| 155 |
+
.. note::
|
| 156 |
+
|
| 157 |
+
If you are reading this document on the `Python Package Index`_
|
| 158 |
+
(PyPI, https://pypi.org/), it is specific to the version of gevent that
|
| 159 |
+
you are viewing. If you are viewing this document on gevent.org, it
|
| 160 |
+
refers to the current state of gevent in source control (git
|
| 161 |
+
master).
|
| 162 |
+
|
| 163 |
+
Supported Platforms
|
| 164 |
+
===================
|
| 165 |
+
|
| 166 |
+
This version of gevent runs on Python 3.8 and up, (for exact details
|
| 167 |
+
of tested versions, see the classifiers on the PyPI page or in
|
| 168 |
+
``setup.py``). gevent requires the `greenlet
|
| 169 |
+
<https://greenlet.readthedocs.io>`_ library and will install the
|
| 170 |
+
`cffi`_ library by default on Windows. The cffi library will become
|
| 171 |
+
the default on all platforms in a future release of gevent.
|
| 172 |
+
|
| 173 |
+
This version of gevent is also tested on on PyPy 3.10 (7.3.12); it
|
| 174 |
+
should run on PyPy 3.9 and above. On PyPy, there are no external
|
| 175 |
+
dependencies.
|
| 176 |
+
|
| 177 |
+
gevent is tested on Windows, macOS, and Linux, and should run on most
|
| 178 |
+
other Unix-like operating systems (e.g., FreeBSD, Solaris, etc.)
|
| 179 |
+
|
| 180 |
+
.. note::
|
| 181 |
+
|
| 182 |
+
Windows is supported as a tier 2, "best effort," platform. It is
|
| 183 |
+
suitable for development, but not recommended for production. In
|
| 184 |
+
particular, PyPy3 on Windows may have issues, especially with
|
| 185 |
+
subprocesses.
|
| 186 |
+
|
| 187 |
+
On Windows using the deprecated libev backend, gevent is
|
| 188 |
+
limited to a maximum of 1024 open sockets due to
|
| 189 |
+
`limitations in libev`_. This limitation should not exist
|
| 190 |
+
with the default libuv backend.
|
| 191 |
+
|
| 192 |
+
Older Versions of Python
|
| 193 |
+
------------------------
|
| 194 |
+
|
| 195 |
+
Users of older versions of Python 2 or Python 3 may install an older
|
| 196 |
+
version of gevent. Note that these versions are generally not
|
| 197 |
+
supported.
|
| 198 |
+
|
| 199 |
+
+-------+-------+
|
| 200 |
+
|Python |Gevent |
|
| 201 |
+
|Version|Version|
|
| 202 |
+
+=======+=======+
|
| 203 |
+
|2.5 |1.0.x |
|
| 204 |
+
| | |
|
| 205 |
+
+-------+-------+
|
| 206 |
+
|2.6 |1.1.x |
|
| 207 |
+
+-------+-------+
|
| 208 |
+
|<= |1.2.x |
|
| 209 |
+
|2.7.8 | |
|
| 210 |
+
+-------+-------+
|
| 211 |
+
|3.3 |1.2.x |
|
| 212 |
+
+-------+-------+
|
| 213 |
+
|3.4.0 -| 1.3.x |
|
| 214 |
+
|3.4.2 | |
|
| 215 |
+
| | |
|
| 216 |
+
+-------+-------+
|
| 217 |
+
|3.4.3 | 1.4.x |
|
| 218 |
+
| | |
|
| 219 |
+
| | |
|
| 220 |
+
+-------+-------+
|
| 221 |
+
|3.5.x | 20.9.0|
|
| 222 |
+
| | |
|
| 223 |
+
| | |
|
| 224 |
+
+-------+-------+
|
| 225 |
+
|2.7.9 -| |
|
| 226 |
+
|2.7.18,| 22.10 |
|
| 227 |
+
|3.6, | |
|
| 228 |
+
|3.7 | |
|
| 229 |
+
| | |
|
| 230 |
+
+-------+-------+
|
| 231 |
+
|
| 232 |
+
Installation
|
| 233 |
+
============
|
| 234 |
+
|
| 235 |
+
.. note::
|
| 236 |
+
|
| 237 |
+
This section is about installing released versions of gevent as
|
| 238 |
+
distributed on the `Python Package Index`_. For building gevent
|
| 239 |
+
from source, including customizing the build and embedded
|
| 240 |
+
libraries, see `Installing From Source`_.
|
| 241 |
+
|
| 242 |
+
.. _Python Package Index: http://pypi.org/project/gevent
|
| 243 |
+
|
| 244 |
+
gevent and greenlet can both be installed with `pip`_, e.g., ``pip
|
| 245 |
+
install gevent``. Installation using `buildout
|
| 246 |
+
<http://docs.buildout.org/en/latest/>`_ is also supported.
|
| 247 |
+
|
| 248 |
+
On Windows, macOS, and Linux, both gevent and greenlet are
|
| 249 |
+
distributed as binary `wheels`_.
|
| 250 |
+
|
| 251 |
+
.. tip::
|
| 252 |
+
|
| 253 |
+
You need Pip 8.0 or later, or buildout 2.10.0 to install the binary
|
| 254 |
+
wheels on Windows or macOS. On Linux, you'll need `pip 19
|
| 255 |
+
<https://github.com/pypa/pip/pull/5008>`_ to install the
|
| 256 |
+
manylinux2010 wheels.
|
| 257 |
+
|
| 258 |
+
.. tip::
|
| 259 |
+
|
| 260 |
+
While the x86-64 binaries are considered production quality, they
|
| 261 |
+
are built with relatively low optimization levels and no hardware
|
| 262 |
+
specific optimizations. Serious production users are encouraged to
|
| 263 |
+
install from source with appropriate compiler flags.
|
| 264 |
+
|
| 265 |
+
.. tip::
|
| 266 |
+
|
| 267 |
+
Beginning with gevent 20.12.0, 64-bit ARM binaries are distributed
|
| 268 |
+
on PyPI for aarch64 manylinux2014 compatible systems. Installing these
|
| 269 |
+
needs a very recent version of ``pip``. These wheels *do not*
|
| 270 |
+
contain the c-ares resolver, are not tested, and are built with
|
| 271 |
+
very low levels of optimizations. Serious production users of
|
| 272 |
+
gevent on 64-bit ARM systems are encouraged to build their own
|
| 273 |
+
binary wheels.
|
| 274 |
+
|
| 275 |
+
Beginning with gevent 22.10.0, ppc64le binaries are distributed on
|
| 276 |
+
PyPI. The same caveats apply as for 64-bit ARM binaries. Using them
|
| 277 |
+
for anything other than local development is discouraged.
|
| 278 |
+
|
| 279 |
+
Beginning with gevent 23, muslinux aarch64 and S390X binaries
|
| 280 |
+
are distributed on PyPI. The same caveats apply as for 64-bit ARM
|
| 281 |
+
binaries. Using them for anything other than local development is
|
| 282 |
+
discouraged.
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
Installing From Source
|
| 286 |
+
----------------------
|
| 287 |
+
|
| 288 |
+
If you are unable to use the binary wheels (for platforms where no
|
| 289 |
+
pre-built wheels are available or if wheel installation is disabled),
|
| 290 |
+
you can build gevent from source. A normal ``pip install`` will
|
| 291 |
+
fall back to doing this if no binary wheel is available. See
|
| 292 |
+
`Installing From Source`_ for more, including common installation issues.
|
| 293 |
+
|
| 294 |
+
Extra Dependencies
|
| 295 |
+
==================
|
| 296 |
+
|
| 297 |
+
There are a number
|
| 298 |
+
of additional libraries that extend gevent's functionality and will be
|
| 299 |
+
used if they are available. All of these may be installed using
|
| 300 |
+
`setuptools extras
|
| 301 |
+
<https://setuptools.readthedocs.io/en/latest/setuptools.html#declaring-extras-optional-features-with-their-own-dependencies>`_,
|
| 302 |
+
as named below, e.g., ``pip install gevent[events]``.
|
| 303 |
+
|
| 304 |
+
events
|
| 305 |
+
In versions of gevent up to and including 20.5.0, this provided configurable
|
| 306 |
+
event support using `zope.event
|
| 307 |
+
<https://pypi.org/project/zope.event>`_ and was highly
|
| 308 |
+
recommended.
|
| 309 |
+
|
| 310 |
+
In versions after that, this extra is empty and does nothing. It
|
| 311 |
+
will be removed in gevent 21.0.
|
| 312 |
+
|
| 313 |
+
dnspython
|
| 314 |
+
Enables a pure-Python resolver, backed by `dnspython
|
| 315 |
+
<https://pypi.org/project/dnspython>`_. On Python 2, this also
|
| 316 |
+
includes `idna <https://pypi.org/project/idna>`_. They can be
|
| 317 |
+
installed with the ``dnspython`` extra.
|
| 318 |
+
|
| 319 |
+
.. note:: This is not compatible with Python 3.10+ or dnspython 2.
|
| 320 |
+
|
| 321 |
+
monitor
|
| 322 |
+
Enhancements to gevent's self-monitoring capabilities. This
|
| 323 |
+
includes the `psutil <https://pypi.org/project/psutil>`_ library
|
| 324 |
+
which is needed to monitor memory usage. (Note that this may not
|
| 325 |
+
build on all platforms.)
|
| 326 |
+
|
| 327 |
+
recommended
|
| 328 |
+
A shortcut for installing suggested extras together. This includes
|
| 329 |
+
the non-test extras defined here, plus additions that improve
|
| 330 |
+
gevent's operation on certain platforms (for example, in the past,
|
| 331 |
+
it has included backports of newer APIs).
|
| 332 |
+
|
| 333 |
+
test
|
| 334 |
+
Everything needed to run the complete gevent test suite.
|
| 335 |
+
|
| 336 |
+
|
| 337 |
+
.. _`pip`: https://pip.pypa.io/en/stable/installing/
|
| 338 |
+
.. _`wheels`: http://pythonwheels.com
|
| 339 |
+
.. _`gevent 1.5`: whatsnew_1_5.html
|
| 340 |
+
.. _`Installing From Source`: https://www.gevent.org/development/installing_from_source.html
|
| 341 |
+
|
| 342 |
+
.. _`cffi`: https://cffi.readthedocs.io
|
| 343 |
+
.. _`limitations in libev`: http://pod.tst.eu/http://cvs.schmorp.de/libev/ev.pod#WIN32_PLATFORM_LIMITATIONS_AND_WORKA
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
.. _bug tracker: https://github.com/gevent/gevent/issues
|
| 347 |
+
.. _mailing list: http://groups.google.com/group/gevent
|
| 348 |
+
.. _blog: https://dev.nextthought.com/blog/categories/gevent.html
|
| 349 |
+
.. _twitter (@gevent): http://twitter.com/gevent
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/NOTICE
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gevent is licensed under the MIT license. See the LICENSE file for the
|
| 2 |
+
complete license.
|
| 3 |
+
|
| 4 |
+
Portions of this software may have other licenses.
|
| 5 |
+
|
| 6 |
+
=============================================
|
| 7 |
+
|
| 8 |
+
greentest/2.7
|
| 9 |
+
greentest/2.7.8
|
| 10 |
+
greentest/2.7pypy
|
| 11 |
+
greentest/3.3
|
| 12 |
+
greentest/3.4
|
| 13 |
+
greentest/3.5
|
| 14 |
+
-----------------
|
| 15 |
+
|
| 16 |
+
Copyright (c) 2001-2016 Python Software Foundation; All Rights Reserved
|
| 17 |
+
|
| 18 |
+
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
|
| 19 |
+
--------------------------------------------
|
| 20 |
+
|
| 21 |
+
1. This LICENSE AGREEMENT is between the Python Software Foundation
|
| 22 |
+
("PSF"), and the Individual or Organization ("Licensee") accessing and
|
| 23 |
+
otherwise using this software ("Python") in source or binary form and
|
| 24 |
+
its associated documentation.
|
| 25 |
+
|
| 26 |
+
2. Subject to the terms and conditions of this License Agreement, PSF hereby
|
| 27 |
+
grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
|
| 28 |
+
analyze, test, perform and/or display publicly, prepare derivative works,
|
| 29 |
+
distribute, and otherwise use Python alone or in any derivative version,
|
| 30 |
+
provided, however, that PSF's License Agreement and PSF's notice of copyright,
|
| 31 |
+
i.e., "Copyright (c) 2001-2016 Python Software Foundation; All Rights
|
| 32 |
+
Reserved" are retained in Python alone or in any derivative version prepared
|
| 33 |
+
by Licensee.
|
| 34 |
+
|
| 35 |
+
3. In the event Licensee prepares a derivative work that is based on
|
| 36 |
+
or incorporates Python or any part thereof, and wants to make
|
| 37 |
+
the derivative work available to others as provided herein, then
|
| 38 |
+
Licensee hereby agrees to include in any such work a brief summary of
|
| 39 |
+
the changes made to Python.
|
| 40 |
+
|
| 41 |
+
4. PSF is making Python available to Licensee on an "AS IS"
|
| 42 |
+
basis. PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR
|
| 43 |
+
IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND
|
| 44 |
+
DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS
|
| 45 |
+
FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF PYTHON WILL NOT
|
| 46 |
+
INFRINGE ANY THIRD PARTY RIGHTS.
|
| 47 |
+
|
| 48 |
+
5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
|
| 49 |
+
FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS
|
| 50 |
+
A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON,
|
| 51 |
+
OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.
|
| 52 |
+
|
| 53 |
+
6. This License Agreement will automatically terminate upon a material
|
| 54 |
+
breach of its terms and conditions.
|
| 55 |
+
|
| 56 |
+
7. Nothing in this License Agreement shall be deemed to create any
|
| 57 |
+
relationship of agency, partnership, or joint venture between PSF and
|
| 58 |
+
Licensee. This License Agreement does not grant permission to use PSF
|
| 59 |
+
trademarks or trade name in a trademark sense to endorse or promote
|
| 60 |
+
products or services of Licensee, or any third party.
|
| 61 |
+
|
| 62 |
+
8. By copying, installing or otherwise using Python, Licensee
|
| 63 |
+
agrees to be bound by the terms and conditions of this License
|
| 64 |
+
Agreement.
|
| 65 |
+
|
| 66 |
+
============================================
|
| 67 |
+
|
| 68 |
+
gevent/libuv/_corecffi_source.c
|
| 69 |
+
gevent/libuv/_corecffi_cdef.c
|
| 70 |
+
|
| 71 |
+
Originally based on code from https://github.com/veegee/guv
|
| 72 |
+
|
| 73 |
+
Copyright (c) 2014 V G
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 77 |
+
of this software and associated documentation files (the "Software"), to
|
| 78 |
+
deal in the Software without restriction, including without limitation the
|
| 79 |
+
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
| 80 |
+
sell copies of the Software, and to permit persons to whom the Software is
|
| 81 |
+
furnished to do so, subject to the following conditions:
|
| 82 |
+
|
| 83 |
+
The above copyright notice and this permission notice shall be included in
|
| 84 |
+
all copies or substantial portions of the Software.
|
| 85 |
+
|
| 86 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 87 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 88 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 89 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 90 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
| 91 |
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
| 92 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gevent-24.11.1.dist-info/AUTHORS,sha256=IS4ttuioANx5ucZqOXHiezC9ys2nkpxl1M_8f77Rleo,1303
|
| 2 |
+
gevent-24.11.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 3 |
+
gevent-24.11.1.dist-info/LICENSE,sha256=TUa8EdGeOFPVQyWXO44sUwkPVjinvyf6H18SMseJAfc,1235
|
| 4 |
+
gevent-24.11.1.dist-info/METADATA,sha256=WaZtQb7KccFebD8a5N-GXq2gXBzY6CzkOSA33IqGveA,13477
|
| 5 |
+
gevent-24.11.1.dist-info/NOTICE,sha256=ZJOCR8qaV_7kwRZWQEuTwxMCkYfhPaeHySe2xkpoBYM,4004
|
| 6 |
+
gevent-24.11.1.dist-info/RECORD,,
|
| 7 |
+
gevent-24.11.1.dist-info/WHEEL,sha256=-ffw4ErOrld3H5FyGb0-yfKd91A4S1balHz5KyTz-4c,151
|
| 8 |
+
gevent-24.11.1.dist-info/entry_points.txt,sha256=g2MTL3KfdJVJ6CEp0d4f9x6HjLAp-MklXYlxlZQ9_u4,95
|
| 9 |
+
gevent-24.11.1.dist-info/top_level.txt,sha256=fpElGiTe2fdw27vmNxdV5MQpyndjzWZMk5TB_NMYPSI,7
|
| 10 |
+
gevent/__init__.py,sha256=CGttQxS3SceN70fIhe-oRee6AmT9RjtXKc02Aol6TNw,3407
|
| 11 |
+
gevent/__pycache__/__init__.cpython-310.pyc,,
|
| 12 |
+
gevent/__pycache__/_abstract_linkable.cpython-310.pyc,,
|
| 13 |
+
gevent/__pycache__/_compat.cpython-310.pyc,,
|
| 14 |
+
gevent/__pycache__/_config.cpython-310.pyc,,
|
| 15 |
+
gevent/__pycache__/_fileobjectcommon.cpython-310.pyc,,
|
| 16 |
+
gevent/__pycache__/_fileobjectposix.cpython-310.pyc,,
|
| 17 |
+
gevent/__pycache__/_greenlet_primitives.cpython-310.pyc,,
|
| 18 |
+
gevent/__pycache__/_hub_local.cpython-310.pyc,,
|
| 19 |
+
gevent/__pycache__/_hub_primitives.cpython-310.pyc,,
|
| 20 |
+
gevent/__pycache__/_ident.cpython-310.pyc,,
|
| 21 |
+
gevent/__pycache__/_imap.cpython-310.pyc,,
|
| 22 |
+
gevent/__pycache__/_interfaces.cpython-310.pyc,,
|
| 23 |
+
gevent/__pycache__/_monitor.cpython-310.pyc,,
|
| 24 |
+
gevent/__pycache__/_patcher.cpython-310.pyc,,
|
| 25 |
+
gevent/__pycache__/_semaphore.cpython-310.pyc,,
|
| 26 |
+
gevent/__pycache__/_socket3.cpython-310.pyc,,
|
| 27 |
+
gevent/__pycache__/_socketcommon.cpython-310.pyc,,
|
| 28 |
+
gevent/__pycache__/_tblib.cpython-310.pyc,,
|
| 29 |
+
gevent/__pycache__/_threading.cpython-310.pyc,,
|
| 30 |
+
gevent/__pycache__/_tracer.cpython-310.pyc,,
|
| 31 |
+
gevent/__pycache__/_util.cpython-310.pyc,,
|
| 32 |
+
gevent/__pycache__/_waiter.cpython-310.pyc,,
|
| 33 |
+
gevent/__pycache__/ares.cpython-310.pyc,,
|
| 34 |
+
gevent/__pycache__/backdoor.cpython-310.pyc,,
|
| 35 |
+
gevent/__pycache__/baseserver.cpython-310.pyc,,
|
| 36 |
+
gevent/__pycache__/builtins.cpython-310.pyc,,
|
| 37 |
+
gevent/__pycache__/contextvars.cpython-310.pyc,,
|
| 38 |
+
gevent/__pycache__/core.cpython-310.pyc,,
|
| 39 |
+
gevent/__pycache__/event.cpython-310.pyc,,
|
| 40 |
+
gevent/__pycache__/events.cpython-310.pyc,,
|
| 41 |
+
gevent/__pycache__/exceptions.cpython-310.pyc,,
|
| 42 |
+
gevent/__pycache__/fileobject.cpython-310.pyc,,
|
| 43 |
+
gevent/__pycache__/greenlet.cpython-310.pyc,,
|
| 44 |
+
gevent/__pycache__/hub.cpython-310.pyc,,
|
| 45 |
+
gevent/__pycache__/local.cpython-310.pyc,,
|
| 46 |
+
gevent/__pycache__/lock.cpython-310.pyc,,
|
| 47 |
+
gevent/__pycache__/os.cpython-310.pyc,,
|
| 48 |
+
gevent/__pycache__/pool.cpython-310.pyc,,
|
| 49 |
+
gevent/__pycache__/pywsgi.cpython-310.pyc,,
|
| 50 |
+
gevent/__pycache__/queue.cpython-310.pyc,,
|
| 51 |
+
gevent/__pycache__/resolver_ares.cpython-310.pyc,,
|
| 52 |
+
gevent/__pycache__/resolver_thread.cpython-310.pyc,,
|
| 53 |
+
gevent/__pycache__/select.cpython-310.pyc,,
|
| 54 |
+
gevent/__pycache__/selectors.cpython-310.pyc,,
|
| 55 |
+
gevent/__pycache__/server.cpython-310.pyc,,
|
| 56 |
+
gevent/__pycache__/signal.cpython-310.pyc,,
|
| 57 |
+
gevent/__pycache__/socket.cpython-310.pyc,,
|
| 58 |
+
gevent/__pycache__/ssl.cpython-310.pyc,,
|
| 59 |
+
gevent/__pycache__/subprocess.cpython-310.pyc,,
|
| 60 |
+
gevent/__pycache__/thread.cpython-310.pyc,,
|
| 61 |
+
gevent/__pycache__/threading.cpython-310.pyc,,
|
| 62 |
+
gevent/__pycache__/threadpool.cpython-310.pyc,,
|
| 63 |
+
gevent/__pycache__/time.cpython-310.pyc,,
|
| 64 |
+
gevent/__pycache__/timeout.cpython-310.pyc,,
|
| 65 |
+
gevent/__pycache__/util.cpython-310.pyc,,
|
| 66 |
+
gevent/__pycache__/win32util.cpython-310.pyc,,
|
| 67 |
+
gevent/_abstract_linkable.py,sha256=vpHRKQF0qw4FMKYQMCCY70jzuWGUpL-VFeBshchG364,22722
|
| 68 |
+
gevent/_compat.py,sha256=5J80cwYac8ns8sOWc719Lkw7O-pCSH7r3Y7Na4OsDYM,2806
|
| 69 |
+
gevent/_config.py,sha256=Lx1isVwHjFutWHL2Oth1Y6lc9ynENucjhcZFOVFrxnc,21428
|
| 70 |
+
gevent/_ffi/__init__.py,sha256=BTBgjjvO4ecQBPbReBhem-0zvy1Mq6jXf5dMrykGIhs,493
|
| 71 |
+
gevent/_ffi/__pycache__/__init__.cpython-310.pyc,,
|
| 72 |
+
gevent/_ffi/__pycache__/callback.cpython-310.pyc,,
|
| 73 |
+
gevent/_ffi/__pycache__/loop.cpython-310.pyc,,
|
| 74 |
+
gevent/_ffi/__pycache__/watcher.cpython-310.pyc,,
|
| 75 |
+
gevent/_ffi/callback.py,sha256=JL2mvMVD7vVaatIdUxo9UfvUJvIwiHhZ7qLGgiBc8YA,1564
|
| 76 |
+
gevent/_ffi/loop.py,sha256=gq5kGvEyhMknFEM58vXnN0QC5tbmN9sOOWOsHHR7NcY,31802
|
| 77 |
+
gevent/_ffi/watcher.py,sha256=qUFXAHM56_GVyCrvv6VkA735ZvtvLB8Zv26I8iMKIgs,20954
|
| 78 |
+
gevent/_fileobjectcommon.py,sha256=S-69DeitiPnvjbGfexTuD2yzPeI0-eDv_1DBIlV0sTg,24359
|
| 79 |
+
gevent/_fileobjectposix.py,sha256=n4ziPoRoq3741XEHN-UTKdXihoq8TUyik6k9HD-UFI8,12840
|
| 80 |
+
gevent/_gevent_c_abstract_linkable.cpython-310-x86_64-linux-gnu.so,sha256=biDM6csd8yxuD1ggOl_n69rZroxKaawS4qzExEPBLWo,1021000
|
| 81 |
+
gevent/_gevent_c_greenlet_primitives.cpython-310-x86_64-linux-gnu.so,sha256=QkNhIn0oKA4PHk1XTCssDgz3CpjbTY3_y_EQwbupfd8,498944
|
| 82 |
+
gevent/_gevent_c_hub_local.cpython-310-x86_64-linux-gnu.so,sha256=Gf2NVwg68xmwNzj04QQsXXCJlouk28J9_ilBC0BPZx0,398712
|
| 83 |
+
gevent/_gevent_c_hub_primitives.cpython-310-x86_64-linux-gnu.so,sha256=8CR_u8d-3MO0YQKOZCT0xY7Zt-u4nkM6vJK2wVv0c-0,1086104
|
| 84 |
+
gevent/_gevent_c_ident.cpython-310-x86_64-linux-gnu.so,sha256=3Lz-x4XoynIkpg8XwIvU3zk5dCMwjeHArldLReiUOwk,346704
|
| 85 |
+
gevent/_gevent_c_imap.cpython-310-x86_64-linux-gnu.so,sha256=dyXcy00koo5ACsyQHdFNzF-dTeFHBOX2hV-R2BRheSY,623536
|
| 86 |
+
gevent/_gevent_c_semaphore.cpython-310-x86_64-linux-gnu.so,sha256=Y3o7jHFE9r4bJwRmPSuXn-TH1lwgJO65Xl54Jl4IeD4,1062208
|
| 87 |
+
gevent/_gevent_c_tracer.cpython-310-x86_64-linux-gnu.so,sha256=gnwW0AS7s4QFfWlCUAb7wFBMoQ5_Z3KUcoAaDgtXDeg,731368
|
| 88 |
+
gevent/_gevent_c_waiter.cpython-310-x86_64-linux-gnu.so,sha256=8_ttuHOOOEcckQpbhtqUO9eECjHstd8K4wOh9T9bXAo,521608
|
| 89 |
+
gevent/_gevent_cevent.cpython-310-x86_64-linux-gnu.so,sha256=spDqQyo89edL6qPh2TMk5YliCxnbMSiKhpsMhhloddA,776328
|
| 90 |
+
gevent/_gevent_cgreenlet.cpython-310-x86_64-linux-gnu.so,sha256=ai4EL81Zy8Sq47-zwEjYSrvrT-wYd8qFD0vWtH6_pnE,2119856
|
| 91 |
+
gevent/_gevent_clocal.cpython-310-x86_64-linux-gnu.so,sha256=9zjpFK2y2q99o-FyiY7mHkDfcPb18pi7crb4SmzkpSA,1009128
|
| 92 |
+
gevent/_gevent_cqueue.cpython-310-x86_64-linux-gnu.so,sha256=hfPVeCsWlxgSv254bEWRmEFDUb8OhIEvc3CipIc3DuU,1923064
|
| 93 |
+
gevent/_greenlet_primitives.py,sha256=i2b0bj5oYr5qzhRRQPhzbCMEg9zMRAx_zhiSOCHtTeY,4647
|
| 94 |
+
gevent/_hub_local.py,sha256=OJPT7QZufzgEgV3SJvOVUWIqhYAKVgfn2mGx9ismIFo,4763
|
| 95 |
+
gevent/_hub_primitives.py,sha256=aTCXhH1gJNdb1JONz7X0fBnNCu9Lv1U55sVF2dXpnUk,14026
|
| 96 |
+
gevent/_ident.py,sha256=w7kjbyaNR4MVzRTjB0_3ZUZ-JYS6eukY55l-r_MdjM4,2249
|
| 97 |
+
gevent/_imap.py,sha256=RtrIfyUPPMFxNX4gSVuJQLjn6oxIdI2t9ERVErIgtwg,7672
|
| 98 |
+
gevent/_interfaces.py,sha256=D-ZJuGse_gtj8XOTRQyXgsj9FNLCr9Xtn_9U5Txk-Cc,9731
|
| 99 |
+
gevent/_monitor.py,sha256=t-zK6iL6rxtGMuBcnNq0kpRIdNDmESWnTRf1y4j64vc,12006
|
| 100 |
+
gevent/_patcher.py,sha256=e4dfPB9MhmnipVpwwEPcChMbiC2F0Rp_MdkwZ02ZF_c,9020
|
| 101 |
+
gevent/_semaphore.py,sha256=BBjdqHfz8NFVD_XbKbiGxgMUvxYfGeBXA1qh26tgqb8,20887
|
| 102 |
+
gevent/_socket3.py,sha256=w8mFOeD3gFyI2_zWOj1u0adxIKBeNc2Jumhy-CjmNUs,23013
|
| 103 |
+
gevent/_socketcommon.py,sha256=tbdbfwoVh6lSBEYYKogVCRTH-uyUpKBvIbCc4TFkGwY,26066
|
| 104 |
+
gevent/_tblib.py,sha256=szKF1dyK4ELE2_44vxyBPZatAtZe57w0Mseki4ld_IA,12219
|
| 105 |
+
gevent/_threading.py,sha256=mYFPLhSlSWXTGDixNLm0JFfnh3jH1e51fyl5iSXaczM,8342
|
| 106 |
+
gevent/_tracer.py,sha256=FX1B-6s7GWWKLvcdYKRZYCbHABy9i3c5p66cy95ijKM,6455
|
| 107 |
+
gevent/_util.py,sha256=go3VuMYv1k9zpvNkGp0MbxZT4gn3xfutA9HjoY9G6nk,10964
|
| 108 |
+
gevent/_waiter.py,sha256=fCVW5AxbqvIYROgHbC22kljXr6wHIr54fPePtTVMoW4,7387
|
| 109 |
+
gevent/ares.py,sha256=2LLRXoWkyS5YwSpJ0b7R_e3M8ikwpsA53eUWizys8eM,383
|
| 110 |
+
gevent/backdoor.py,sha256=Hn7dZXAzywWypJm2MENTWZLS4oUrSpriy_Apz2X-7f4,8642
|
| 111 |
+
gevent/baseserver.py,sha256=x4zWdbE5JtOYCuvGQozCUgfpArhN0mPMXdLdPDRiYnI,16614
|
| 112 |
+
gevent/builtins.py,sha256=0K7haEs0DhfIEhArBaxaRRx_i3Dws2ZqFWey6HOYjHo,4108
|
| 113 |
+
gevent/contextvars.py,sha256=a0f8GxwQESkQM-zUNO-gdmDcW-2-kV321auE6KbSHGw,9838
|
| 114 |
+
gevent/core.py,sha256=XgaVreHocvO9JCVby3JCo8ixbllJL08V9OrA7ETDaHs,479
|
| 115 |
+
gevent/event.py,sha256=vOR3t77RyCzLH240f-DrypxLNgwsP4YkOaaeqZfYa64,15079
|
| 116 |
+
gevent/events.py,sha256=olRj_SbHNW-I8Ifs6vNYWaRKV0bWtgEFnOYt6Uhihuk,17182
|
| 117 |
+
gevent/exceptions.py,sha256=6JvoCgb4Recrl_kngtBe8Zx36uwc5qTakLJSJBQVr8I,3932
|
| 118 |
+
gevent/fileobject.py,sha256=GNeYmbGSLWq8t311pVbgYsyDpzMmtQ8m2fHI15a0EpI,3020
|
| 119 |
+
gevent/greenlet.py,sha256=gWxllLzY6SQanwBKO_nXxm7IEY7k02cv4Bq0V4gIm0Y,45203
|
| 120 |
+
gevent/hub.py,sha256=_ZodHnESbnnj2qg8p-4aGhY4HH4u-7T7wJHI00JYJAM,34590
|
| 121 |
+
gevent/libev/__init__.py,sha256=I6hpYFJCnbBBDrousKzZ7Ql--mnfAFwfM2q1BuxcMfI,169
|
| 122 |
+
gevent/libev/__pycache__/__init__.cpython-310.pyc,,
|
| 123 |
+
gevent/libev/__pycache__/_corecffi_build.cpython-310.pyc,,
|
| 124 |
+
gevent/libev/__pycache__/corecffi.cpython-310.pyc,,
|
| 125 |
+
gevent/libev/__pycache__/watcher.cpython-310.pyc,,
|
| 126 |
+
gevent/libev/_corecffi.abi3.so,sha256=iivm2mzecVM_515ub_hbspW7nT1nRFlS4NC8TUWlumw,473480
|
| 127 |
+
gevent/libev/_corecffi_build.py,sha256=ARUO9jiMqdfk80aSs4_CkBIIwcpUaF9enyj-AJVXVP8,4059
|
| 128 |
+
gevent/libev/corecext.cpython-310-x86_64-linux-gnu.so,sha256=dVkXbVISohLQNrKUqHonyhh1BDzudif32NSryKk0aGU,2563472
|
| 129 |
+
gevent/libev/corecffi.py,sha256=yxz0x6YzcQSFPSuba3JJpPJkkdU7KBwFPa299cGOGSw,13720
|
| 130 |
+
gevent/libev/watcher.py,sha256=DGBi_JFksqLv4ifO5o-eIT8POn-om3EdiJhQDVx4pLs,7999
|
| 131 |
+
gevent/libuv/__init__.py,sha256=I6hpYFJCnbBBDrousKzZ7Ql--mnfAFwfM2q1BuxcMfI,169
|
| 132 |
+
gevent/libuv/__pycache__/__init__.cpython-310.pyc,,
|
| 133 |
+
gevent/libuv/__pycache__/_corecffi_build.cpython-310.pyc,,
|
| 134 |
+
gevent/libuv/__pycache__/loop.cpython-310.pyc,,
|
| 135 |
+
gevent/libuv/__pycache__/watcher.cpython-310.pyc,,
|
| 136 |
+
gevent/libuv/_corecffi.abi3.so,sha256=LsSrcAHjxBA-GEbOP7U-E3OuVX9T4yp4ZX_sncATvrQ,1307296
|
| 137 |
+
gevent/libuv/_corecffi_build.py,sha256=uzAzrWhtl6yfjvBSR-1WkdPtsPSPo-oS_kqii1WAMnc,12349
|
| 138 |
+
gevent/libuv/loop.py,sha256=q7es7RTne1wl2EEJ9AVHw5-mBvu92cmxQ5qh_QeKtlM,27626
|
| 139 |
+
gevent/libuv/watcher.py,sha256=kuT3uqGc5XnAw1T_vgnseH2KpqAUqE5xjk65VXVoFxk,27664
|
| 140 |
+
gevent/local.py,sha256=I12OWg8nWR5q7p3UZhJjSMfbyHuShVqYqQTkmPdF-8k,21457
|
| 141 |
+
gevent/lock.py,sha256=Wsfkdv2By0C-7plcGmK5OWEX9EmVhvY1UpEdYkHUNYA,11398
|
| 142 |
+
gevent/monkey/__init__.py,sha256=blTV4wtxZGjRAJLXA80cCSduobcUJE9KUdLvkibq2Xk,24869
|
| 143 |
+
gevent/monkey/__main__.py,sha256=JPNIwI-Qb_VQERows-n4R2XzcY8rGCt5FR8kUiKD1J4,31
|
| 144 |
+
gevent/monkey/__pycache__/__init__.cpython-310.pyc,,
|
| 145 |
+
gevent/monkey/__pycache__/__main__.cpython-310.pyc,,
|
| 146 |
+
gevent/monkey/__pycache__/_errors.cpython-310.pyc,,
|
| 147 |
+
gevent/monkey/__pycache__/_main.cpython-310.pyc,,
|
| 148 |
+
gevent/monkey/__pycache__/_patch_thread_common.cpython-310.pyc,,
|
| 149 |
+
gevent/monkey/__pycache__/_patch_thread_gte313.cpython-310.pyc,,
|
| 150 |
+
gevent/monkey/__pycache__/_patch_thread_lt313.cpython-310.pyc,,
|
| 151 |
+
gevent/monkey/__pycache__/_state.cpython-310.pyc,,
|
| 152 |
+
gevent/monkey/__pycache__/_util.cpython-310.pyc,,
|
| 153 |
+
gevent/monkey/__pycache__/api.cpython-310.pyc,,
|
| 154 |
+
gevent/monkey/_errors.py,sha256=cBctoXo4sAME97eaCdWGY1q1zEOtG8krDFyv-O5WOiQ,547
|
| 155 |
+
gevent/monkey/_main.py,sha256=8zzhBLrRSBV0D_GbgwcY_iwsIR3ayrG9xX8TvyGAvH8,4411
|
| 156 |
+
gevent/monkey/_patch_thread_common.py,sha256=n018JoqZ2zMZnKWzhDNOOkEOWJxskOOWjth-q_30b3A,13119
|
| 157 |
+
gevent/monkey/_patch_thread_gte313.py,sha256=83Mix-vpJA2xGmmsxD4Glc4c-c8kyjrMMngxuB1zlPo,3490
|
| 158 |
+
gevent/monkey/_patch_thread_lt313.py,sha256=3qLEpTt2L6CRJy2H1SFyVqtrfT8ItnHpUpOD45Mxdzc,3054
|
| 159 |
+
gevent/monkey/_state.py,sha256=FGJFTDXFUwio1b-IwtlOmXCysVrqheM9j9JjRxOzrqI,1897
|
| 160 |
+
gevent/monkey/_util.py,sha256=U-KBkLB9v5J7RedNHOfK7qaaonaKo5Z7oQ-5gwrYnAo,3689
|
| 161 |
+
gevent/monkey/api.py,sha256=ZoRUk0e-wVXE6CnTI8BULQaDAIVqyEmTCwXhVzUrh5s,6760
|
| 162 |
+
gevent/os.py,sha256=1sJXacYJZUDwgUii44K_D1AB6EwFTTHtYQEX7D6Vaho,20858
|
| 163 |
+
gevent/pool.py,sha256=JSt0I106SQr3wYjc9z919ebcX3MUyM33gaAbohSXNCo,25634
|
| 164 |
+
gevent/pywsgi.py,sha256=ZWZMKmn21k3K5NS6JLJ4UrPLTA3z2bn-jPjHRjm7fKc,69033
|
| 165 |
+
gevent/queue.py,sha256=Vkq4L7xSTcYYOmw_EynWMas6OkWoXdSV47YOivlMnI0,25708
|
| 166 |
+
gevent/resolver/__init__.py,sha256=lx0L8Up3DXkp61RQxceQbmj5AVFt9WGMhHi12-iy7GI,10760
|
| 167 |
+
gevent/resolver/__pycache__/__init__.cpython-310.pyc,,
|
| 168 |
+
gevent/resolver/__pycache__/_addresses.cpython-310.pyc,,
|
| 169 |
+
gevent/resolver/__pycache__/_hostsfile.cpython-310.pyc,,
|
| 170 |
+
gevent/resolver/__pycache__/ares.cpython-310.pyc,,
|
| 171 |
+
gevent/resolver/__pycache__/blocking.cpython-310.pyc,,
|
| 172 |
+
gevent/resolver/__pycache__/dnspython.cpython-310.pyc,,
|
| 173 |
+
gevent/resolver/__pycache__/thread.cpython-310.pyc,,
|
| 174 |
+
gevent/resolver/_addresses.py,sha256=BvLXxwN1QTQ4Pajgk5UwvHRP6J8TDQ8n-_75AfIaOVo,4795
|
| 175 |
+
gevent/resolver/_hostsfile.py,sha256=KY6q-aY5F1f3MV4SZioAcstBRvxm4647-JKlCtY47E0,4629
|
| 176 |
+
gevent/resolver/ares.py,sha256=6Oed67PUah45MwMQz3KFIWNAnm7XkoRJXx9vz7voJEc,12965
|
| 177 |
+
gevent/resolver/blocking.py,sha256=5ubBMewB7X-JouMKIlf_s2JNw4KJ_EqmNVUg4PrrSaA,1216
|
| 178 |
+
gevent/resolver/cares.cpython-310-x86_64-linux-gnu.so,sha256=MRiOjNPMCvdmF0vwePyW9kFRz0mDbURipVbx1vXWCsM,2882264
|
| 179 |
+
gevent/resolver/dnspython.py,sha256=cZ0mQyWluVz_h2YsyS_sSg0n7NEpuFPsZhp63WMyFeg,20706
|
| 180 |
+
gevent/resolver/thread.py,sha256=DTSwSwBRsSJKjPjyAHS0qT07oDxmFOhR4wYLfSSaJCU,2487
|
| 181 |
+
gevent/resolver_ares.py,sha256=s5Jo9Z0b-zKxSWcIvW5onaFE2OrfqLuNnTPlOoxFxEQ,486
|
| 182 |
+
gevent/resolver_thread.py,sha256=jcKcEVCXwyRqcsDUZmryQ9hc-83yztgaM4kuTKHOvaw,504
|
| 183 |
+
gevent/select.py,sha256=7-LNetKIlhpB3YifQ5momSLQXnt5q92g8EDJaC4qGEE,13257
|
| 184 |
+
gevent/selectors.py,sha256=ffV2jG6m2etjqNIppHNCBY7JSDr4q0_zbf-tkA06gVI,11725
|
| 185 |
+
gevent/server.py,sha256=7rrN3Ieujlo0vKddDyYIqgocslsW-3VNG-faOfOk7vE,10852
|
| 186 |
+
gevent/signal.py,sha256=-Rx0_Ta7Zel8UWXmrrtzDWVnjUQZuGWINWhrNwHB9ic,5217
|
| 187 |
+
gevent/socket.py,sha256=CUC-jiNIjbXghj_muCXyn9Ij7GUDa44kKxBb3F1-PMM,6503
|
| 188 |
+
gevent/ssl.py,sha256=Q_etOyl2s9PcZRvOaf1_7joEIeo8d8u4N7XWhRxnFTs,34772
|
| 189 |
+
gevent/subprocess.py,sha256=Q1mRVgRyAVigzjlLd0aXvhTb5IKk3TOhbLNcK6mVJX0,83510
|
| 190 |
+
gevent/testing/__init__.py,sha256=my2P6ikG7OUO9hGXN54zZawh4LYtu825K9epAGUnoDc,5583
|
| 191 |
+
gevent/testing/__pycache__/__init__.cpython-310.pyc,,
|
| 192 |
+
gevent/testing/__pycache__/errorhandler.cpython-310.pyc,,
|
| 193 |
+
gevent/testing/__pycache__/exception.cpython-310.pyc,,
|
| 194 |
+
gevent/testing/__pycache__/flaky.cpython-310.pyc,,
|
| 195 |
+
gevent/testing/__pycache__/hub.cpython-310.pyc,,
|
| 196 |
+
gevent/testing/__pycache__/leakcheck.cpython-310.pyc,,
|
| 197 |
+
gevent/testing/__pycache__/modules.cpython-310.pyc,,
|
| 198 |
+
gevent/testing/__pycache__/monkey_test.cpython-310.pyc,,
|
| 199 |
+
gevent/testing/__pycache__/openfiles.cpython-310.pyc,,
|
| 200 |
+
gevent/testing/__pycache__/params.cpython-310.pyc,,
|
| 201 |
+
gevent/testing/__pycache__/patched_tests_setup.cpython-310.pyc,,
|
| 202 |
+
gevent/testing/__pycache__/resources.cpython-310.pyc,,
|
| 203 |
+
gevent/testing/__pycache__/six.cpython-310.pyc,,
|
| 204 |
+
gevent/testing/__pycache__/skipping.cpython-310.pyc,,
|
| 205 |
+
gevent/testing/__pycache__/sockets.cpython-310.pyc,,
|
| 206 |
+
gevent/testing/__pycache__/support.cpython-310.pyc,,
|
| 207 |
+
gevent/testing/__pycache__/switching.cpython-310.pyc,,
|
| 208 |
+
gevent/testing/__pycache__/sysinfo.cpython-310.pyc,,
|
| 209 |
+
gevent/testing/__pycache__/testcase.cpython-310.pyc,,
|
| 210 |
+
gevent/testing/__pycache__/testrunner.cpython-310.pyc,,
|
| 211 |
+
gevent/testing/__pycache__/timing.cpython-310.pyc,,
|
| 212 |
+
gevent/testing/__pycache__/travis.cpython-310.pyc,,
|
| 213 |
+
gevent/testing/__pycache__/util.cpython-310.pyc,,
|
| 214 |
+
gevent/testing/coveragesite/__pycache__/sitecustomize.cpython-310.pyc,,
|
| 215 |
+
gevent/testing/coveragesite/sitecustomize.py,sha256=GSOkHhxLE_pjOHuUn4InKmmuLyIGSIumySFVVSmc4Vo,558
|
| 216 |
+
gevent/testing/errorhandler.py,sha256=NzoItIrdz8t0YOFEAa6fn9WyFnubs_egnpV8yD7AcDQ,2329
|
| 217 |
+
gevent/testing/exception.py,sha256=yQHF9Ebom2JAKUq70mLsdFk9p4eorpK36O-3iH1LL1Q,1265
|
| 218 |
+
gevent/testing/flaky.py,sha256=x-IujIZGK_m2FYRyi4RxKMZhLfxq25p47En4DAlYhCs,4104
|
| 219 |
+
gevent/testing/hub.py,sha256=Qmo7bcZPLIEOF7mncgV3vR-KrbHLUT_pORNQejrltig,3115
|
| 220 |
+
gevent/testing/leakcheck.py,sha256=mHU-MoeEtHV319aTbDeMx-F0OwDWmf3rJI-sYJl9lmI,8227
|
| 221 |
+
gevent/testing/modules.py,sha256=qGfvohEps4mo6_hqcRZHlEuxBx1wDNqRY_DZmJDM61o,4987
|
| 222 |
+
gevent/testing/monkey_test.py,sha256=Y2WYnBEb5FQIuOnFpv42ETuvdKRbBhAtqywDDDoPowE,5730
|
| 223 |
+
gevent/testing/openfiles.py,sha256=daybcm27dkOGOiloGj0GocHzPRX2q6NvW861WylWxFA,8739
|
| 224 |
+
gevent/testing/params.py,sha256=B-5PoctZfrtii3rcjA68kmI0wvwg7_sHJ4pWFzRAcbw,2674
|
| 225 |
+
gevent/testing/patched_tests_setup.py,sha256=ztdpf2o4DlhjaLSIMy1Ie5VJY78l843b7QpAFA_pwZ8,66439
|
| 226 |
+
gevent/testing/resources.py,sha256=C3cxaDi56orLzs50vTCnGElxk-ChJBjFV3JX2f610_A,7481
|
| 227 |
+
gevent/testing/six.py,sha256=4Gi0PTjZ9rKHn-DGy9WdRSxuYFmeoTonD_LL_TvyrcU,1035
|
| 228 |
+
gevent/testing/skipping.py,sha256=z9S_gzsCaDeuAbw3E80gysE7CoVGrvc6a1OYXyDtTkY,6719
|
| 229 |
+
gevent/testing/sockets.py,sha256=CvtRiCVxCXcv_Vv3OFQiEYEH-Mok32sY18JiATEbeI4,2285
|
| 230 |
+
gevent/testing/support.py,sha256=hn2IghJcKYUcS7hcii9RdWBLy0gGOu2nRTlEEvaq06U,4631
|
| 231 |
+
gevent/testing/switching.py,sha256=6idIaCiHKFZF8aibeHjxIdZi38cxXCKuhQRHUT1YWoo,2708
|
| 232 |
+
gevent/testing/sysinfo.py,sha256=LP97FlKGdJXc-S1ejAkO-k8VHGX2ybIpk_Ozy_WNNIw,8211
|
| 233 |
+
gevent/testing/testcase.py,sha256=-Xo56A1ZIX_PW7RMqn_YkPKauzUI5yxJXAjpd_dKjXI,18602
|
| 234 |
+
gevent/testing/testrunner.py,sha256=ld43CGn3CbDjzOGW4lOlyOnubr2mWyd2ve-J8Pt58F4,36487
|
| 235 |
+
gevent/testing/timing.py,sha256=Yy9dQ3KvJ9uEV6BwpgM3ZEnVYP1ic6jgVGqZF1uWLLc,4982
|
| 236 |
+
gevent/testing/travis.py,sha256=yYJlIY2L4vMzSxaODPVhANFaB_svNmwhrw4CRotQXlc,877
|
| 237 |
+
gevent/testing/util.py,sha256=Kky0x628NVhr9g_-yYjkeuhSQViBSRZ9YWt02WfWbG4,19302
|
| 238 |
+
gevent/tests/2_7_keycert.pem,sha256=PuSO2qCmga4an7pkSs7ep1Fo16yrQKd9i84DnrqSYcI,5081
|
| 239 |
+
gevent/tests/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 240 |
+
gevent/tests/__main__.py,sha256=EMw-OppCjl-heu15mLg-cf400NS1Ikuy96OisvLoKLM,179
|
| 241 |
+
gevent/tests/__pycache__/__init__.cpython-310.pyc,,
|
| 242 |
+
gevent/tests/__pycache__/__main__.cpython-310.pyc,,
|
| 243 |
+
gevent/tests/__pycache__/_blocks_at_top_level.cpython-310.pyc,,
|
| 244 |
+
gevent/tests/__pycache__/_import_import_patch.cpython-310.pyc,,
|
| 245 |
+
gevent/tests/__pycache__/_import_patch.cpython-310.pyc,,
|
| 246 |
+
gevent/tests/__pycache__/_import_wait.cpython-310.pyc,,
|
| 247 |
+
gevent/tests/__pycache__/_imports_at_top_level.cpython-310.pyc,,
|
| 248 |
+
gevent/tests/__pycache__/_imports_imports_at_top_level.cpython-310.pyc,,
|
| 249 |
+
gevent/tests/__pycache__/getaddrinfo_module.cpython-310.pyc,,
|
| 250 |
+
gevent/tests/__pycache__/known_failures.cpython-310.pyc,,
|
| 251 |
+
gevent/tests/__pycache__/lock_tests.cpython-310.pyc,,
|
| 252 |
+
gevent/tests/__pycache__/test__GreenletExit.cpython-310.pyc,,
|
| 253 |
+
gevent/tests/__pycache__/test___config.cpython-310.pyc,,
|
| 254 |
+
gevent/tests/__pycache__/test___ident.cpython-310.pyc,,
|
| 255 |
+
gevent/tests/__pycache__/test___monitor.cpython-310.pyc,,
|
| 256 |
+
gevent/tests/__pycache__/test___monkey_patching.cpython-310.pyc,,
|
| 257 |
+
gevent/tests/__pycache__/test__all__.cpython-310.pyc,,
|
| 258 |
+
gevent/tests/__pycache__/test__api.cpython-310.pyc,,
|
| 259 |
+
gevent/tests/__pycache__/test__api_timeout.cpython-310.pyc,,
|
| 260 |
+
gevent/tests/__pycache__/test__ares_host_result.cpython-310.pyc,,
|
| 261 |
+
gevent/tests/__pycache__/test__ares_timeout.cpython-310.pyc,,
|
| 262 |
+
gevent/tests/__pycache__/test__backdoor.cpython-310.pyc,,
|
| 263 |
+
gevent/tests/__pycache__/test__close_backend_fd.cpython-310.pyc,,
|
| 264 |
+
gevent/tests/__pycache__/test__compat.cpython-310.pyc,,
|
| 265 |
+
gevent/tests/__pycache__/test__contextvars.cpython-310.pyc,,
|
| 266 |
+
gevent/tests/__pycache__/test__core.cpython-310.pyc,,
|
| 267 |
+
gevent/tests/__pycache__/test__core_async.cpython-310.pyc,,
|
| 268 |
+
gevent/tests/__pycache__/test__core_callback.cpython-310.pyc,,
|
| 269 |
+
gevent/tests/__pycache__/test__core_fork.cpython-310.pyc,,
|
| 270 |
+
gevent/tests/__pycache__/test__core_loop_run.cpython-310.pyc,,
|
| 271 |
+
gevent/tests/__pycache__/test__core_stat.cpython-310.pyc,,
|
| 272 |
+
gevent/tests/__pycache__/test__core_timer.cpython-310.pyc,,
|
| 273 |
+
gevent/tests/__pycache__/test__core_watcher.cpython-310.pyc,,
|
| 274 |
+
gevent/tests/__pycache__/test__destroy.cpython-310.pyc,,
|
| 275 |
+
gevent/tests/__pycache__/test__destroy_default_loop.cpython-310.pyc,,
|
| 276 |
+
gevent/tests/__pycache__/test__doctests.cpython-310.pyc,,
|
| 277 |
+
gevent/tests/__pycache__/test__environ.cpython-310.pyc,,
|
| 278 |
+
gevent/tests/__pycache__/test__event.cpython-310.pyc,,
|
| 279 |
+
gevent/tests/__pycache__/test__events.cpython-310.pyc,,
|
| 280 |
+
gevent/tests/__pycache__/test__example_echoserver.cpython-310.pyc,,
|
| 281 |
+
gevent/tests/__pycache__/test__example_portforwarder.cpython-310.pyc,,
|
| 282 |
+
gevent/tests/__pycache__/test__example_udp_client.cpython-310.pyc,,
|
| 283 |
+
gevent/tests/__pycache__/test__example_udp_server.cpython-310.pyc,,
|
| 284 |
+
gevent/tests/__pycache__/test__example_webproxy.cpython-310.pyc,,
|
| 285 |
+
gevent/tests/__pycache__/test__example_wsgiserver.cpython-310.pyc,,
|
| 286 |
+
gevent/tests/__pycache__/test__example_wsgiserver_ssl.cpython-310.pyc,,
|
| 287 |
+
gevent/tests/__pycache__/test__examples.cpython-310.pyc,,
|
| 288 |
+
gevent/tests/__pycache__/test__exc_info.cpython-310.pyc,,
|
| 289 |
+
gevent/tests/__pycache__/test__execmodules.cpython-310.pyc,,
|
| 290 |
+
gevent/tests/__pycache__/test__fileobject.cpython-310.pyc,,
|
| 291 |
+
gevent/tests/__pycache__/test__getaddrinfo_import.cpython-310.pyc,,
|
| 292 |
+
gevent/tests/__pycache__/test__greenio.cpython-310.pyc,,
|
| 293 |
+
gevent/tests/__pycache__/test__greenlet.cpython-310.pyc,,
|
| 294 |
+
gevent/tests/__pycache__/test__greenletset.cpython-310.pyc,,
|
| 295 |
+
gevent/tests/__pycache__/test__greenness.cpython-310.pyc,,
|
| 296 |
+
gevent/tests/__pycache__/test__hub.cpython-310.pyc,,
|
| 297 |
+
gevent/tests/__pycache__/test__hub_join.cpython-310.pyc,,
|
| 298 |
+
gevent/tests/__pycache__/test__hub_join_timeout.cpython-310.pyc,,
|
| 299 |
+
gevent/tests/__pycache__/test__import_blocking_in_greenlet.cpython-310.pyc,,
|
| 300 |
+
gevent/tests/__pycache__/test__import_wait.cpython-310.pyc,,
|
| 301 |
+
gevent/tests/__pycache__/test__issue112.cpython-310.pyc,,
|
| 302 |
+
gevent/tests/__pycache__/test__issue1686.cpython-310.pyc,,
|
| 303 |
+
gevent/tests/__pycache__/test__issue1864.cpython-310.pyc,,
|
| 304 |
+
gevent/tests/__pycache__/test__issue230.cpython-310.pyc,,
|
| 305 |
+
gevent/tests/__pycache__/test__issue330.cpython-310.pyc,,
|
| 306 |
+
gevent/tests/__pycache__/test__issue467.cpython-310.pyc,,
|
| 307 |
+
gevent/tests/__pycache__/test__issue6.cpython-310.pyc,,
|
| 308 |
+
gevent/tests/__pycache__/test__issue600.cpython-310.pyc,,
|
| 309 |
+
gevent/tests/__pycache__/test__issue607.cpython-310.pyc,,
|
| 310 |
+
gevent/tests/__pycache__/test__issue639.cpython-310.pyc,,
|
| 311 |
+
gevent/tests/__pycache__/test__issue_728.cpython-310.pyc,,
|
| 312 |
+
gevent/tests/__pycache__/test__issues461_471.cpython-310.pyc,,
|
| 313 |
+
gevent/tests/__pycache__/test__iwait.cpython-310.pyc,,
|
| 314 |
+
gevent/tests/__pycache__/test__joinall.cpython-310.pyc,,
|
| 315 |
+
gevent/tests/__pycache__/test__local.cpython-310.pyc,,
|
| 316 |
+
gevent/tests/__pycache__/test__lock.cpython-310.pyc,,
|
| 317 |
+
gevent/tests/__pycache__/test__loop_callback.cpython-310.pyc,,
|
| 318 |
+
gevent/tests/__pycache__/test__makefile_ref.cpython-310.pyc,,
|
| 319 |
+
gevent/tests/__pycache__/test__memleak.cpython-310.pyc,,
|
| 320 |
+
gevent/tests/__pycache__/test__monkey.cpython-310.pyc,,
|
| 321 |
+
gevent/tests/__pycache__/test__monkey_builtins_future.cpython-310.pyc,,
|
| 322 |
+
gevent/tests/__pycache__/test__monkey_hub_in_thread.cpython-310.pyc,,
|
| 323 |
+
gevent/tests/__pycache__/test__monkey_logging.cpython-310.pyc,,
|
| 324 |
+
gevent/tests/__pycache__/test__monkey_module_run.cpython-310.pyc,,
|
| 325 |
+
gevent/tests/__pycache__/test__monkey_multiple_imports.cpython-310.pyc,,
|
| 326 |
+
gevent/tests/__pycache__/test__monkey_queue.cpython-310.pyc,,
|
| 327 |
+
gevent/tests/__pycache__/test__monkey_select.cpython-310.pyc,,
|
| 328 |
+
gevent/tests/__pycache__/test__monkey_selectors.cpython-310.pyc,,
|
| 329 |
+
gevent/tests/__pycache__/test__monkey_sigchld.cpython-310.pyc,,
|
| 330 |
+
gevent/tests/__pycache__/test__monkey_sigchld_2.cpython-310.pyc,,
|
| 331 |
+
gevent/tests/__pycache__/test__monkey_sigchld_3.cpython-310.pyc,,
|
| 332 |
+
gevent/tests/__pycache__/test__monkey_ssl_warning.cpython-310.pyc,,
|
| 333 |
+
gevent/tests/__pycache__/test__monkey_ssl_warning2.cpython-310.pyc,,
|
| 334 |
+
gevent/tests/__pycache__/test__monkey_ssl_warning3.cpython-310.pyc,,
|
| 335 |
+
gevent/tests/__pycache__/test__nondefaultloop.cpython-310.pyc,,
|
| 336 |
+
gevent/tests/__pycache__/test__order.cpython-310.pyc,,
|
| 337 |
+
gevent/tests/__pycache__/test__os.cpython-310.pyc,,
|
| 338 |
+
gevent/tests/__pycache__/test__pool.cpython-310.pyc,,
|
| 339 |
+
gevent/tests/__pycache__/test__pywsgi.cpython-310.pyc,,
|
| 340 |
+
gevent/tests/__pycache__/test__queue.cpython-310.pyc,,
|
| 341 |
+
gevent/tests/__pycache__/test__real_greenlet.cpython-310.pyc,,
|
| 342 |
+
gevent/tests/__pycache__/test__refcount.cpython-310.pyc,,
|
| 343 |
+
gevent/tests/__pycache__/test__refcount_core.cpython-310.pyc,,
|
| 344 |
+
gevent/tests/__pycache__/test__resolver_dnspython.cpython-310.pyc,,
|
| 345 |
+
gevent/tests/__pycache__/test__select.cpython-310.pyc,,
|
| 346 |
+
gevent/tests/__pycache__/test__selectors.cpython-310.pyc,,
|
| 347 |
+
gevent/tests/__pycache__/test__semaphore.cpython-310.pyc,,
|
| 348 |
+
gevent/tests/__pycache__/test__server.cpython-310.pyc,,
|
| 349 |
+
gevent/tests/__pycache__/test__server_pywsgi.cpython-310.pyc,,
|
| 350 |
+
gevent/tests/__pycache__/test__signal.cpython-310.pyc,,
|
| 351 |
+
gevent/tests/__pycache__/test__sleep0.cpython-310.pyc,,
|
| 352 |
+
gevent/tests/__pycache__/test__socket.cpython-310.pyc,,
|
| 353 |
+
gevent/tests/__pycache__/test__socket_close.cpython-310.pyc,,
|
| 354 |
+
gevent/tests/__pycache__/test__socket_dns.cpython-310.pyc,,
|
| 355 |
+
gevent/tests/__pycache__/test__socket_dns6.cpython-310.pyc,,
|
| 356 |
+
gevent/tests/__pycache__/test__socket_errors.cpython-310.pyc,,
|
| 357 |
+
gevent/tests/__pycache__/test__socket_ex.cpython-310.pyc,,
|
| 358 |
+
gevent/tests/__pycache__/test__socket_send_memoryview.cpython-310.pyc,,
|
| 359 |
+
gevent/tests/__pycache__/test__socket_ssl.cpython-310.pyc,,
|
| 360 |
+
gevent/tests/__pycache__/test__socket_timeout.cpython-310.pyc,,
|
| 361 |
+
gevent/tests/__pycache__/test__socketpair.cpython-310.pyc,,
|
| 362 |
+
gevent/tests/__pycache__/test__ssl.cpython-310.pyc,,
|
| 363 |
+
gevent/tests/__pycache__/test__subprocess.cpython-310.pyc,,
|
| 364 |
+
gevent/tests/__pycache__/test__subprocess_interrupted.cpython-310.pyc,,
|
| 365 |
+
gevent/tests/__pycache__/test__subprocess_poll.cpython-310.pyc,,
|
| 366 |
+
gevent/tests/__pycache__/test__systemerror.cpython-310.pyc,,
|
| 367 |
+
gevent/tests/__pycache__/test__thread.cpython-310.pyc,,
|
| 368 |
+
gevent/tests/__pycache__/test__threading.cpython-310.pyc,,
|
| 369 |
+
gevent/tests/__pycache__/test__threading_2.cpython-310.pyc,,
|
| 370 |
+
gevent/tests/__pycache__/test__threading_before_monkey.cpython-310.pyc,,
|
| 371 |
+
gevent/tests/__pycache__/test__threading_fork_from_dummy.cpython-310.pyc,,
|
| 372 |
+
gevent/tests/__pycache__/test__threading_holding_lock_while_monkey.cpython-310.pyc,,
|
| 373 |
+
gevent/tests/__pycache__/test__threading_monkey_in_thread.cpython-310.pyc,,
|
| 374 |
+
gevent/tests/__pycache__/test__threading_native_before_monkey.cpython-310.pyc,,
|
| 375 |
+
gevent/tests/__pycache__/test__threading_no_monkey.cpython-310.pyc,,
|
| 376 |
+
gevent/tests/__pycache__/test__threading_patched_local.cpython-310.pyc,,
|
| 377 |
+
gevent/tests/__pycache__/test__threading_vs_settrace.cpython-310.pyc,,
|
| 378 |
+
gevent/tests/__pycache__/test__threadpool.cpython-310.pyc,,
|
| 379 |
+
gevent/tests/__pycache__/test__threadpool_executor_patched.cpython-310.pyc,,
|
| 380 |
+
gevent/tests/__pycache__/test__timeout.cpython-310.pyc,,
|
| 381 |
+
gevent/tests/__pycache__/test__util.cpython-310.pyc,,
|
| 382 |
+
gevent/tests/_blocks_at_top_level.py,sha256=Hp36RFiC0djMSfvUHZsu8pVttpc7Hbmv_7VGq6xW630,48
|
| 383 |
+
gevent/tests/_import_import_patch.py,sha256=IbgraY7KaPggcX1JNVkUQTTBSboegF_VWSDFJp38buI,28
|
| 384 |
+
gevent/tests/_import_patch.py,sha256=_PWRiLjpsFyhT2CxTDIE9ZVS9gcCFqzQGFKel00zc2s,47
|
| 385 |
+
gevent/tests/_import_wait.py,sha256=8353o30STWbRg53op9CWmTXfElU6VV4klLdqiq7Jmjg,570
|
| 386 |
+
gevent/tests/_imports_at_top_level.py,sha256=9SCo81uRMT8xWbDFUBhbc_EwAoii9oygwOBSSNWfWWI,55
|
| 387 |
+
gevent/tests/_imports_imports_at_top_level.py,sha256=VcIaDELcdgeEMqO_Cndy0XMjx05h5eG4_F_12giOSDs,345
|
| 388 |
+
gevent/tests/badcert.pem,sha256=JioQeRZkHH8hGsWJjAF3U1zQvcWqhyzG6IOEJpTY9SE,1928
|
| 389 |
+
gevent/tests/badkey.pem,sha256=gaBK9px_gG7DmrLKxfD6f6i-toAmARBTVfs-YGFRQF0,2162
|
| 390 |
+
gevent/tests/getaddrinfo_module.py,sha256=oFyeNRywc3QO5HlpuV5DVcpUbml8hFn86pbWm_mGQX8,116
|
| 391 |
+
gevent/tests/hosts_file.txt,sha256=07jEX3FicSKuiUJbQ_14H0MP8v7r35h_usGUmScPnSM,290909
|
| 392 |
+
gevent/tests/https_svn_python_org_root.pem,sha256=wOB3Onnc62Iu9kEFd8GcHhd_suucYjpJNA3jyfHeJWA,2569
|
| 393 |
+
gevent/tests/keycert.pem,sha256=r0KE1WH9eV6X4mUykpCY5Dm8_robBSi4zwMcGBPtMi4,1872
|
| 394 |
+
gevent/tests/known_failures.py,sha256=y7BTq9dlR-At455-Q5YCJ5pnDaXOnmo5Ms317fcbbDo,17473
|
| 395 |
+
gevent/tests/lock_tests.py,sha256=Oxi0uoEPVzA1NKP6t69fuezuHCZE0xQZbHBuMQtTwUs,21858
|
| 396 |
+
gevent/tests/monkey_package/__init__.py,sha256=bvY5MXWih-w0IshrJmEKnPTI25R0eC_ma0Xa2bT3XCI,329
|
| 397 |
+
gevent/tests/monkey_package/__main__.py,sha256=mJx6YRmYplQEY8Lb3hQOPrbIj2Z3mwrZY3wLL7p2zcM,363
|
| 398 |
+
gevent/tests/monkey_package/__pycache__/__init__.cpython-310.pyc,,
|
| 399 |
+
gevent/tests/monkey_package/__pycache__/__main__.cpython-310.pyc,,
|
| 400 |
+
gevent/tests/monkey_package/__pycache__/issue1526_no_monkey.cpython-310.pyc,,
|
| 401 |
+
gevent/tests/monkey_package/__pycache__/issue1526_with_monkey.cpython-310.pyc,,
|
| 402 |
+
gevent/tests/monkey_package/__pycache__/issue302monkey.cpython-310.pyc,,
|
| 403 |
+
gevent/tests/monkey_package/__pycache__/script.cpython-310.pyc,,
|
| 404 |
+
gevent/tests/monkey_package/__pycache__/threadpool_monkey_patches.cpython-310.pyc,,
|
| 405 |
+
gevent/tests/monkey_package/__pycache__/threadpool_no_monkey.cpython-310.pyc,,
|
| 406 |
+
gevent/tests/monkey_package/issue1526_no_monkey.py,sha256=mDdY5_Y4IDBd8b-gjYNQKh8U4jb8Nn7eSEC_DM7lSxk,573
|
| 407 |
+
gevent/tests/monkey_package/issue1526_with_monkey.py,sha256=5mbVockojXOZQZwQFaPrMVcg50T_vD1WRj07F6pOj_Y,666
|
| 408 |
+
gevent/tests/monkey_package/issue302monkey.py,sha256=aitTDyrxJZI4EE_n6gg0o4AfHEQsFPfzQtVVmWMr6JQ,935
|
| 409 |
+
gevent/tests/monkey_package/script.py,sha256=4q695hn_S3YA2aQh4TRyjVJ7QA9xlfqNTrezlUZkjVQ,427
|
| 410 |
+
gevent/tests/monkey_package/threadpool_monkey_patches.py,sha256=0Glu2IugiK6rT6fYZbgqmGgciUjUX-6eannkqekzTi4,869
|
| 411 |
+
gevent/tests/monkey_package/threadpool_no_monkey.py,sha256=c-bdOwTHjhBzlmcJMFyixL3Wjp-wXO4T1VZIGC3clGE,787
|
| 412 |
+
gevent/tests/nullcert.pem,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 413 |
+
gevent/tests/server.crt,sha256=LOyJ1muRGaDZapZQ9x3BRNGIrC4jKiiIyNZJvMM5eQI,1809
|
| 414 |
+
gevent/tests/server.key,sha256=CXI8bo8kvTo3I_o0kVPabuQ0oHBsoNbgFVT1bWNTwOI,3272
|
| 415 |
+
gevent/tests/sha256.pem,sha256=trYsA7FY0hyVoV1AoGNwZ_s6T89eiiOIFexoNRv029s,2065
|
| 416 |
+
gevent/tests/test__GreenletExit.py,sha256=qHtC7KnjCG039F_VGDXnsrhyWaQXvfcmgnVB2Rfa_Vk,127
|
| 417 |
+
gevent/tests/test___config.py,sha256=mCJfAOG9DEAU5RtUg_UgHwsB6f0x-KWTjHX9aTaS7d8,4889
|
| 418 |
+
gevent/tests/test___ident.py,sha256=15ucVXe5y4hE9F--Y8fhxN9-WcGhXt2ehHMLTzDuDKs,2109
|
| 419 |
+
gevent/tests/test___monitor.py,sha256=-hp7xNRmS3dnqgdfea9228hOUQ_IuG26WXTk2gsVZgE,12624
|
| 420 |
+
gevent/tests/test___monkey_patching.py,sha256=2W6ZF3gTCSh9SgUjJUuX2OP1ZZCq9Vjsv20UPqgrXnY,3502
|
| 421 |
+
gevent/tests/test__all__.py,sha256=j_TqCJ3_iILFT3tDlH0RBGjYv70dqzncJ536ove_ZOs,11547
|
| 422 |
+
gevent/tests/test__api.py,sha256=zJF6cfQKnPscZio9ErpkY2Mn2NNPOzNnzX4J8ujx4ww,4550
|
| 423 |
+
gevent/tests/test__api_timeout.py,sha256=is-HOBSQiMKPc67r41FqamL3KOF5BnfmtV8kW01JId4,6323
|
| 424 |
+
gevent/tests/test__ares_host_result.py,sha256=f-ZJubI1wyzJExMifQnRFNpNcxkZ0Ykyp2W75jLjrqY,908
|
| 425 |
+
gevent/tests/test__ares_timeout.py,sha256=65MC4NdPYJzbLO90FRjwtPuz3E_Y0JJm2Ld5aDcYLcU,1015
|
| 426 |
+
gevent/tests/test__backdoor.py,sha256=y6xN2JGBlo4EziEWp5C4Xh550RMe60EHyrgGm73VE4I,5580
|
| 427 |
+
gevent/tests/test__close_backend_fd.py,sha256=6yssqISBW-rhKZx25iCDbE6gaLYAEBCTzPlchwzsB7Y,3865
|
| 428 |
+
gevent/tests/test__compat.py,sha256=YBE4IJwtRozcCRqeZXY9dkxqjZ6m2xS0Pk1ceApjvnE,1439
|
| 429 |
+
gevent/tests/test__contextvars.py,sha256=JUPQ3TzpSLTQkdRNr7g2OgEzmFIK5vd8ml2bF7BNTYc,31717
|
| 430 |
+
gevent/tests/test__core.py,sha256=VDxOazcjEyhp4o094xQcKSupm-Qf0aDNN0o3Ja_UF7s,5618
|
| 431 |
+
gevent/tests/test__core_async.py,sha256=X4CNU4Kroea9fyjlfd_l8HmMLKfvec-eE4qzqTPZNow,761
|
| 432 |
+
gevent/tests/test__core_callback.py,sha256=occ-buOrq8DrbJ0GUzHeMVF-Qcuu5e4qnUPnrmqvq80,618
|
| 433 |
+
gevent/tests/test__core_fork.py,sha256=i4WdiNIL_LWINMg38rnNakfCfVZiMkFgVo9wUsiXxH4,2738
|
| 434 |
+
gevent/tests/test__core_loop_run.py,sha256=N6ZHGuVfrclHoKrL1R8T7BeObT9P28Ey2wfvyo_jGJs,494
|
| 435 |
+
gevent/tests/test__core_stat.py,sha256=YvqLSe-9j5tIFC6MoPQhD5_0MdBtxrbVagp4o0jzpw8,3754
|
| 436 |
+
gevent/tests/test__core_timer.py,sha256=e6VG-IHLiQ3OkrTOYGiLMX4VdU6RLG3UoA69uao2xG8,4330
|
| 437 |
+
gevent/tests/test__core_watcher.py,sha256=ULftUAJqrMLYgzItmSzEosgeagKbI72m0oheKn14vYo,3573
|
| 438 |
+
gevent/tests/test__destroy.py,sha256=fy9Gh1WH6URkLCTjVv2RzxljX6DDRZXmaCuUEHVCYf8,1765
|
| 439 |
+
gevent/tests/test__destroy_default_loop.py,sha256=9KsDb5i7Nn4uFrNrfT_vMYLOG7VV6-hp46HGlFg06nc,2199
|
| 440 |
+
gevent/tests/test__doctests.py,sha256=aZqNLQDOpyvFYkhmqgXyDRhtV3CnN50H4OnZkp0vC0E,3613
|
| 441 |
+
gevent/tests/test__environ.py,sha256=i7sqbSsRVyM5ypN9obyVIMWKyATOs5FC3BrMNf_i5Sk,608
|
| 442 |
+
gevent/tests/test__event.py,sha256=UVT1jc5lgWoTJnWSEThOhrV3kaXCk7oA6ai8d-JiYYQ,14176
|
| 443 |
+
gevent/tests/test__events.py,sha256=wa8mZSnMCsZ_qX2ak0Lwy3RE0MqXfdaSevLv0PEzXFM,1465
|
| 444 |
+
gevent/tests/test__example_echoserver.py,sha256=oHLko-fDrrhS-3YrSr86B599W1ww1-MlTomarszLuZM,1198
|
| 445 |
+
gevent/tests/test__example_portforwarder.py,sha256=hIVFPP8CBapzR918PBlrZM_Zibt8OyzDdKD9V1vfgbw,2025
|
| 446 |
+
gevent/tests/test__example_udp_client.py,sha256=VGDHP_cYMlxnDkqW1E1fs-WteLH_6O7euW3SYvA1Mvk,884
|
| 447 |
+
gevent/tests/test__example_udp_server.py,sha256=ApnWzkhqlHXmELMwgviFr8jf2QU4obHYefWCq1t2zlY,513
|
| 448 |
+
gevent/tests/test__example_webproxy.py,sha256=Tg4dVbS725yOQVoslPz3FpA6SFAoYKIPAhddwUvEvEs,807
|
| 449 |
+
gevent/tests/test__example_wsgiserver.py,sha256=bavlc9OfdFdkyibxxGhBuhEFXOYcfyc_Jqg0P8gfQEo,3202
|
| 450 |
+
gevent/tests/test__example_wsgiserver_ssl.py,sha256=Ztn83XeMTLENcZduhdE2hiGYitSvi0hEQLJaD1tLpdA,649
|
| 451 |
+
gevent/tests/test__examples.py,sha256=F2tAzDtGDYz3mo9Y5u0UfgnXGUTSz6TbtxK_LzEJyFQ,3336
|
| 452 |
+
gevent/tests/test__exc_info.py,sha256=qp4J_TJrPk3JakATBvyOBO_7UbEhpoXmqVShNRK3yvY,1377
|
| 453 |
+
gevent/tests/test__execmodules.py,sha256=oUgXwnV9wD3PZSJD6RVzWj9DxDpnmzPE5pm0z8YgG_4,1628
|
| 454 |
+
gevent/tests/test__fileobject.py,sha256=38RddEZk-TdK0adkLpZmrKQUkJwXifAFrcT2fvkViAI,18345
|
| 455 |
+
gevent/tests/test__getaddrinfo_import.py,sha256=eGmX5zaq-x9Or3UGtIZL8yqNN97yVBQx9zlehM3ogE4,463
|
| 456 |
+
gevent/tests/test__greenio.py,sha256=vYzw_tSAAZxD0TjbKt_9wy_2KM3727YjUEdmcJ6GNvc,5523
|
| 457 |
+
gevent/tests/test__greenlet.py,sha256=_bm2-nbngzCtR1mjC7LuugvWX-BhHANrnwUpeEOaYDw,32010
|
| 458 |
+
gevent/tests/test__greenletset.py,sha256=NaIikUvwC7FcHjZQ24P3blp3iW4VaLImJfqH_E6mVuo,5032
|
| 459 |
+
gevent/tests/test__greenness.py,sha256=YztEj8cMW3XkbTtoRJPv8K5yKugRwhlWy6szMKRwk2o,2790
|
| 460 |
+
gevent/tests/test__hub.py,sha256=kT1T7tzDAZ1zmU3EsYGhGBqyYRv7acMVgTA3_BE1Ok0,13728
|
| 461 |
+
gevent/tests/test__hub_join.py,sha256=-V1LjhFtZOAvCTWJsqxsLKFGicoDbp3NpojlS1EOZKc,3217
|
| 462 |
+
gevent/tests/test__hub_join_timeout.py,sha256=E6Ul1xhZ1Ro7_IMx9QZBpf1zzWl1yrYWS11K25JyLho,2913
|
| 463 |
+
gevent/tests/test__import_blocking_in_greenlet.py,sha256=BEEB6WrcXqFscxQxEIdMzlLVQ-KFvDlQ52yNlQWxIKs,1134
|
| 464 |
+
gevent/tests/test__import_wait.py,sha256=-m2mg2urO-nNDTj3Ov0QNXuDmgr7rOCa7MKD-LT5cyA,252
|
| 465 |
+
gevent/tests/test__issue112.py,sha256=OxamNgJF1QlKuirw_jJNYzpE84PgjYP2z1x27n61JQc,338
|
| 466 |
+
gevent/tests/test__issue1686.py,sha256=5CIooK1MteQPtSWaWPpvyzMil_OLcvIYeHjIcZHlpxE,2878
|
| 467 |
+
gevent/tests/test__issue1864.py,sha256=Xb3CcArxYDox-lCDpHOpwTkE5XXM3jK5zqUk3zyKGzk,1291
|
| 468 |
+
gevent/tests/test__issue230.py,sha256=3zEzP5fLwLaHUeX0xNntV29AhhtHr_9t0cG1SPSa24c,500
|
| 469 |
+
gevent/tests/test__issue330.py,sha256=qDbqSKfvZ4IdR_r7PwDAuCfTQuZEjLELSK1IvTowoaI,2333
|
| 470 |
+
gevent/tests/test__issue467.py,sha256=PrqSlERQf8XttyiNB5NRZqEo8D0cmNTiO8qIdamRgPg,1205
|
| 471 |
+
gevent/tests/test__issue6.py,sha256=OOBbWEwmA4zKxpF8jZ_5fm4E7uHKbqxP63FiE0ktU9w,1530
|
| 472 |
+
gevent/tests/test__issue600.py,sha256=dKW-RzdzaJhVl8dClpBzLzgRjMn7BlqeTIiIB97R9cw,1386
|
| 473 |
+
gevent/tests/test__issue607.py,sha256=-lQuJxVfIPDhrrf1G-2BpIbQqwDMygDeuRMh7vANGPM,1354
|
| 474 |
+
gevent/tests/test__issue639.py,sha256=ExWDeXqUDqGTXF1rx6t1SQjac4GWKqZ2opusTpxgi1g,214
|
| 475 |
+
gevent/tests/test__issue_728.py,sha256=1u6WSToRxMYe70aLU5vMhrWSZ_OHtwN9oP6L4UXXywg,212
|
| 476 |
+
gevent/tests/test__issues461_471.py,sha256=_Xwj-ImGgYuTcWGxITACba3FGnRHmlXZxTDkkChriVg,3889
|
| 477 |
+
gevent/tests/test__iwait.py,sha256=uzef1gKSo8dDbciyjZobklIXNDdc-B0ehEKb3iIn2Bg,1205
|
| 478 |
+
gevent/tests/test__joinall.py,sha256=UAV56-NMPLhs8TBYJ-qcNAC8gT_ZoUAcOq22_qYEQZM,296
|
| 479 |
+
gevent/tests/test__local.py,sha256=1iThKxhRmbTG5aH91kVNOEdU84CnsT3YMqjX3zY5WXU,11741
|
| 480 |
+
gevent/tests/test__lock.py,sha256=9QBouc6_S4xVwbxraJNpTPN12S7R9c4yj_4mwF28KuA,1100
|
| 481 |
+
gevent/tests/test__loop_callback.py,sha256=SUKmuaQh4sSC1fTyGv3zaTG1NkJN7T4EaJt-ezd_wT4,356
|
| 482 |
+
gevent/tests/test__makefile_ref.py,sha256=OVdy8i-zQDzL_wnF9_M_WL_3cT1S_k-VAAKQQ8Rh-MA,19150
|
| 483 |
+
gevent/tests/test__memleak.py,sha256=Yq3tfWmbpgI5hYopozWEHSbP8Xs4lDqBBQ76in2mFxc,1466
|
| 484 |
+
gevent/tests/test__monkey.py,sha256=DNAhYP27e9l3t_wFATd99SHlPKhbSzzYPF6mKh3WGdM,6722
|
| 485 |
+
gevent/tests/test__monkey_builtins_future.py,sha256=ZUJj7wWz9jEa9vDPSdEPrjqewiUwBspmtgh7RN8LymA,521
|
| 486 |
+
gevent/tests/test__monkey_hub_in_thread.py,sha256=iMWv4a8Agy_llZypYxXo62kSB7LLTdNG5u9N_eHKIg8,520
|
| 487 |
+
gevent/tests/test__monkey_logging.py,sha256=ZBbUvAqOam0Twekv_Mint1dWiWBt_ce9Y7L3JRCrqGU,1564
|
| 488 |
+
gevent/tests/test__monkey_module_run.py,sha256=G-bHCowrKt4dDUgotEeB5rX8yVlDrfppIRGKYJIOdA8,4368
|
| 489 |
+
gevent/tests/test__monkey_multiple_imports.py,sha256=QwmJJ4r3RXOQhti_5vj3Let0zllXzq4GwDY8NqzJUuQ,296
|
| 490 |
+
gevent/tests/test__monkey_queue.py,sha256=d9m4mfBPMFa5bhuyNOOEMHEoBLc7bvlCz7Q3jbODULk,12337
|
| 491 |
+
gevent/tests/test__monkey_select.py,sha256=U77pqLIX-2wCtdY7CxigfT0wgSTBqHs3e53eajJV45A,741
|
| 492 |
+
gevent/tests/test__monkey_selectors.py,sha256=gootPuj6Hp_ZuT_ChQmjkR75TY9xNmTXNq0nTbRxEMU,2580
|
| 493 |
+
gevent/tests/test__monkey_sigchld.py,sha256=U4L8AciJ-1-ivwMZlfIMkgpmoWFVxxlZri0bsJ_1vvo,2939
|
| 494 |
+
gevent/tests/test__monkey_sigchld_2.py,sha256=zV1WsDX8dTQiW6XBOs0GQejZsq2obE2LA9Dil1eo_9Y,1774
|
| 495 |
+
gevent/tests/test__monkey_sigchld_3.py,sha256=dlaDG9t4kPRfhT6anZRRCkltvQSKWNeKPOBd7doAgGo,1755
|
| 496 |
+
gevent/tests/test__monkey_ssl_warning.py,sha256=vvfhrq-1zurv3ERAaeiIotk1LARVAGeUy4UDdrde7Zk,1250
|
| 497 |
+
gevent/tests/test__monkey_ssl_warning2.py,sha256=NRlZ8-s-doOC6xNkQbaiVPIaqOtFBfEmQzyrKsUukww,1255
|
| 498 |
+
gevent/tests/test__monkey_ssl_warning3.py,sha256=WZEOHQoewYAuYJu0f8UMjpmRzaR0B-sf0wBhvaRKTEQ,1330
|
| 499 |
+
gevent/tests/test__nondefaultloop.py,sha256=Y3IrgT8SF3SmO3A1IlvC0nF4GCqxzvKES0KqvO72crE,204
|
| 500 |
+
gevent/tests/test__order.py,sha256=iI8wh316sNia20IkHx7wSnE_LKdCsse6Q89xVkQev1U,1125
|
| 501 |
+
gevent/tests/test__os.py,sha256=FywENBJyzocpTd2dK_3VfqVWFBK2lPNhPm-8qkMZDog,5963
|
| 502 |
+
gevent/tests/test__pool.py,sha256=oOf38RQcEVd8AQQuynwebNWLnQ2CRoXHV9hJWskmhrc,18351
|
| 503 |
+
gevent/tests/test__pywsgi.py,sha256=qOp0J-IbtKy9EXZBXBG-EBE6j2a6Zp8E8Av11j_wSTQ,73786
|
| 504 |
+
gevent/tests/test__queue.py,sha256=GZTa2XcuseEqJKNOa04Clk4ipPGPCgsARGo09nDjwxk,13107
|
| 505 |
+
gevent/tests/test__real_greenlet.py,sha256=SoZQ8cY1wQFJnVmTFxuYvXo08KVyb99ZUqGDBUbo1C4,693
|
| 506 |
+
gevent/tests/test__refcount.py,sha256=rqdMK4QiCLWTIblXbxvGJ2AWQimV91KDFmawHV-X5ik,5866
|
| 507 |
+
gevent/tests/test__refcount_core.py,sha256=XiTmU2kYH-JkVINch2jpA1vGVKOc6ufdPW28DMNpo9c,600
|
| 508 |
+
gevent/tests/test__resolver_dnspython.py,sha256=aA7rtaB273IaTG9whMwvtGwG8c42xTPtb4iH9gTR4DE,1117
|
| 509 |
+
gevent/tests/test__select.py,sha256=q7wFNosgYq2T6BBekZ-DKZifNQVnbzXr-nfv4eewpVM,4069
|
| 510 |
+
gevent/tests/test__selectors.py,sha256=SB2A581GN0ZDl_qk5LdQIeGI2q6Kbiwv7NGas238M6c,3789
|
| 511 |
+
gevent/tests/test__semaphore.py,sha256=m-CHrKE_S5yyKd6O78b6j8AvmTFpgTVJtGT-b91nDvA,13756
|
| 512 |
+
gevent/tests/test__server.py,sha256=VmpoHCkPW6baDlfzhfg9Jg8LIKefsOkXaP0KEUYKtU4,19882
|
| 513 |
+
gevent/tests/test__server_pywsgi.py,sha256=0Fquqy69Xylu3UXATvd__Y9wTBXnohP9fdvEoUhGysI,3074
|
| 514 |
+
gevent/tests/test__signal.py,sha256=3vN7T6bNTQchXHs6THkRm9QNROisO_40lGk1jgiO41I,3813
|
| 515 |
+
gevent/tests/test__sleep0.py,sha256=uoruOPjsaPk1m0thN_4UppH4kW4k9fHQXDuLXnc3u5k,139
|
| 516 |
+
gevent/tests/test__socket.py,sha256=GbN3AZC6eup3G8w_bpnBf7jcAWL2oCTYG9Zzd-KC8FU,23490
|
| 517 |
+
gevent/tests/test__socket_close.py,sha256=_lidh6C8SSup3avpXKUdv0Kkok1GiLbaC_5Dn6hkiRQ,1862
|
| 518 |
+
gevent/tests/test__socket_dns.py,sha256=n_KUI-C2x15cfoj_3N7XlOevQAsMI721zdWm4ToyZJo,36681
|
| 519 |
+
gevent/tests/test__socket_dns6.py,sha256=zCqRfupQLxCNNQFaHVat5pzO_UMWiBORnmxWeax_K9U,3716
|
| 520 |
+
gevent/tests/test__socket_errors.py,sha256=L6ZZymYkkYGq6V_S7lzdC2D1J-0jQkKF9_xytAldQN8,1869
|
| 521 |
+
gevent/tests/test__socket_ex.py,sha256=RYT56ubUxD-e13wL1rG5NS9afx0gaqYfKcqzL0uS0T0,1110
|
| 522 |
+
gevent/tests/test__socket_send_memoryview.py,sha256=xhNyL7y_TriGrMbJvKmbwEReUBMR_M6LKL0l0IarBbE,960
|
| 523 |
+
gevent/tests/test__socket_ssl.py,sha256=X7iDcOwBbtX7e0B_JBXoSFI_dRzpQzVMGYpMQTswtf4,865
|
| 524 |
+
gevent/tests/test__socket_timeout.py,sha256=_TqCsWOPrKNMJ8OFvKGjLIbiToDm7X1Y1wJxR39rJME,1351
|
| 525 |
+
gevent/tests/test__socketpair.py,sha256=VKi94yATBBTzKsN7S7D1rpx-GropJf0qXRpw9GT43c0,951
|
| 526 |
+
gevent/tests/test__ssl.py,sha256=mTvZ6r9hJxh_9siwPgQDwaG7c4WTjDDIPr4JsfY7JpA,5597
|
| 527 |
+
gevent/tests/test__subprocess.py,sha256=7hByz0Yh4_BG93BwDhnGyZPvMnPlW11RLSmp6Hy3daQ,20208
|
| 528 |
+
gevent/tests/test__subprocess_interrupted.py,sha256=qNr4GCwg-xhLrZLGHnprQILnj0g08-GozvYClSR_uE0,1922
|
| 529 |
+
gevent/tests/test__subprocess_poll.py,sha256=AFlQJZcNCfDKP5zwefoGmSFvPe_1cT5HpUu_VDbp4Lk,346
|
| 530 |
+
gevent/tests/test__systemerror.py,sha256=lgUg-grJQ6VTNXjOTkQQGds6m7PmtoPgddG-tYURYsU,3295
|
| 531 |
+
gevent/tests/test__thread.py,sha256=xhyh6Z_HQzh2kqSjdoPoEdUURzj8A2B2l1dbXpuv1yc,780
|
| 532 |
+
gevent/tests/test__threading.py,sha256=R6eAMnNIMQE757HL6JdwKaCFQq21HD4uPCen5iRCghc,2586
|
| 533 |
+
gevent/tests/test__threading_2.py,sha256=Z23N_WRNT6h2wDGuK-qQY6UWi7NKxB5Vy6dW8og-4EM,23535
|
| 534 |
+
gevent/tests/test__threading_before_monkey.py,sha256=DhdEFVUY6LTb-74I3KgiFExW-aFvSn_B8jTvMS_NjWo,714
|
| 535 |
+
gevent/tests/test__threading_fork_from_dummy.py,sha256=Ds0y3KgYqLzQnjUuAeu2WmpBtabpMF9qA4n6weoirwQ,2181
|
| 536 |
+
gevent/tests/test__threading_holding_lock_while_monkey.py,sha256=5IWkIjTs1eRlphtDF0cCINz16M6tUi9hZMB-R_eVMIw,411
|
| 537 |
+
gevent/tests/test__threading_monkey_in_thread.py,sha256=rnxzlmcUahqg4pWEIdh-5bmIMdGn5ed-V7hjt-WxXDo,2366
|
| 538 |
+
gevent/tests/test__threading_native_before_monkey.py,sha256=KvQaAWQe78cGVYT-T2MAh6T4s7YUZdza8-vqxS4YJp0,2157
|
| 539 |
+
gevent/tests/test__threading_no_monkey.py,sha256=FkY93eRfkpZjsbEzLbJLvtI9-POMbAGYd3IpJE8peHw,806
|
| 540 |
+
gevent/tests/test__threading_patched_local.py,sha256=0EaAtlORHJjfxkUZzGKL1lOh-OY9hZa1R6MoUE0eSHo,675
|
| 541 |
+
gevent/tests/test__threading_vs_settrace.py,sha256=vsRpAqYimfePGGqyTj-8M-SpGmwVN01JQ6yROkKBjl8,5023
|
| 542 |
+
gevent/tests/test__threadpool.py,sha256=FhfeW0JZ5U_e84B8Q3JIb6KBxXKFkGSD6RsYVNHMMoM,24825
|
| 543 |
+
gevent/tests/test__threadpool_executor_patched.py,sha256=KihwMAZ_hQfZBhnxv_CCx8HJnvdQaKxxaMuuJkV9IiM,386
|
| 544 |
+
gevent/tests/test__timeout.py,sha256=uRjOchrp6NVrjkxrCW9UMd6r5iheRe8EjzpW5XDD7Bg,5243
|
| 545 |
+
gevent/tests/test__util.py,sha256=8T3EPIPWlOQtAylapMTLjz32ZQyCudhRlchXx-EGSGQ,10705
|
| 546 |
+
gevent/tests/test_server.crt,sha256=QIKfCQ-jpwWvzwJLO-eOSqT2TTSEVE-HLcC1wzs-YNw,1809
|
| 547 |
+
gevent/tests/test_server.key,sha256=5yU4QY75gVWwTt4TE5EKkiOhENEwO0eP9oG3WTB0dtk,3268
|
| 548 |
+
gevent/tests/tests_that_dont_do_leakchecks.txt,sha256=dzRXEFB_7uZlFI5ANA1VCfYCd9HTINqDTi1BcIkzxOY,223
|
| 549 |
+
gevent/tests/tests_that_dont_monkeypatch.txt,sha256=PH8kQY8hpSlwzXJkJQpTsczkNZ13uUxkWM-Hl4Cz-wQ,647
|
| 550 |
+
gevent/tests/tests_that_dont_use_resolver.txt,sha256=nhsAcj2CwFEsEtmfROY3NFiIe7Xqpb3AK1I-nQK6f2A,3184
|
| 551 |
+
gevent/tests/wrongcert.pem,sha256=6n4u7wcalNKCtnMsq7J3Y7uOiez901ZLiH38oE0jGUM,1880
|
| 552 |
+
gevent/thread.py,sha256=H6weO4bwie9U0DciiDjC1rDLMvkGgSKDO1xDT2pXaKE,10586
|
| 553 |
+
gevent/threading.py,sha256=yIo2tlqfrlgutwKM9Bw1uIsbYQquMdGICBnXbsZHE6Q,16808
|
| 554 |
+
gevent/threadpool.py,sha256=iQ90WLeFsm1XUM_cI_WehtKGLh9BJ-r-fgubPvsyTEo,30975
|
| 555 |
+
gevent/time.py,sha256=C0eRlHq0rBxy9tC_SsIywkYaBNlwO1bc04qFi2OceB4,491
|
| 556 |
+
gevent/timeout.py,sha256=TWuPBaYcXZMzX4vUEKtGVBCsLj3QClL6TWTCZq5Zcng,13678
|
| 557 |
+
gevent/util.py,sha256=lZoYCZDZdkBQYd8wSCbbwdkVW0VTVx_cikkX1lxMDmg,22571
|
| 558 |
+
gevent/win32util.py,sha256=WBk_YNf_kk3QF3PMUdScqgM_PreF4OBhfXq2W5264n0,3637
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.3.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_17_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux2014_x86_64
|
| 6 |
+
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/entry_points.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[gevent.plugins.monkey.will_patch_all]
|
| 2 |
+
signal_os_incompat = gevent.monkey:_subscribe_signal_os
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent-24.11.1.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
gevent
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/__init__.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Internal helpers for FFI implementations.
|
| 3 |
+
"""
|
| 4 |
+
from __future__ import print_function, absolute_import
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
|
| 9 |
+
def _dbg(*args, **kwargs):
|
| 10 |
+
# pylint:disable=unused-argument
|
| 11 |
+
pass
|
| 12 |
+
|
| 13 |
+
#_dbg = print
|
| 14 |
+
|
| 15 |
+
def _pid_dbg(*args, **kwargs):
|
| 16 |
+
kwargs['file'] = sys.stderr
|
| 17 |
+
print(os.getpid(), *args, **kwargs)
|
| 18 |
+
|
| 19 |
+
CRITICAL = 1
|
| 20 |
+
ERROR = 3
|
| 21 |
+
DEBUG = 5
|
| 22 |
+
TRACE = 9
|
| 23 |
+
|
| 24 |
+
GEVENT_DEBUG_LEVEL = vars()[os.getenv("GEVENT_DEBUG", 'CRITICAL').upper()]
|
| 25 |
+
|
| 26 |
+
if GEVENT_DEBUG_LEVEL >= TRACE:
|
| 27 |
+
_dbg = _pid_dbg
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/callback.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
from __future__ import print_function
|
| 3 |
+
|
| 4 |
+
from zope.interface import implementer
|
| 5 |
+
|
| 6 |
+
from gevent._interfaces import ICallback
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
'callback',
|
| 10 |
+
]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@implementer(ICallback)
|
| 14 |
+
class callback(object):
|
| 15 |
+
|
| 16 |
+
__slots__ = ('callback', 'args')
|
| 17 |
+
|
| 18 |
+
def __init__(self, cb, args):
|
| 19 |
+
self.callback = cb
|
| 20 |
+
self.args = args
|
| 21 |
+
|
| 22 |
+
def stop(self):
|
| 23 |
+
self.callback = None
|
| 24 |
+
self.args = None
|
| 25 |
+
|
| 26 |
+
close = stop
|
| 27 |
+
|
| 28 |
+
# Note that __nonzero__ and pending are different
|
| 29 |
+
# bool() is used in contexts where we need to know whether to schedule another callback,
|
| 30 |
+
# so it's true if it's pending or currently running
|
| 31 |
+
# 'pending' has the same meaning as libev watchers: it is cleared before actually
|
| 32 |
+
# running the callback
|
| 33 |
+
|
| 34 |
+
def __bool__(self):
|
| 35 |
+
# it's nonzero if it's pending or currently executing
|
| 36 |
+
# NOTE: This depends on loop._run_callbacks setting the args property
|
| 37 |
+
# to None.
|
| 38 |
+
return self.args is not None
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def pending(self):
|
| 42 |
+
return self.callback is not None
|
| 43 |
+
|
| 44 |
+
def _format(self):
|
| 45 |
+
return ''
|
| 46 |
+
|
| 47 |
+
def __repr__(self):
|
| 48 |
+
result = "<%s at 0x%x" % (self.__class__.__name__, id(self))
|
| 49 |
+
if self.pending:
|
| 50 |
+
result += " pending"
|
| 51 |
+
if self.callback is not None:
|
| 52 |
+
result += " callback=%r" % (self.callback, )
|
| 53 |
+
if self.args is not None:
|
| 54 |
+
result += " args=%r" % (self.args, )
|
| 55 |
+
if self.callback is None and self.args is None:
|
| 56 |
+
result += " stopped"
|
| 57 |
+
return result + ">"
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/loop.py
ADDED
|
@@ -0,0 +1,789 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Basic loop implementation for ffi-based cores.
|
| 3 |
+
"""
|
| 4 |
+
# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
|
| 5 |
+
from __future__ import absolute_import, print_function
|
| 6 |
+
|
| 7 |
+
from collections import deque
|
| 8 |
+
import sys
|
| 9 |
+
import os
|
| 10 |
+
import traceback
|
| 11 |
+
|
| 12 |
+
from gevent._ffi import _dbg
|
| 13 |
+
from gevent._ffi import GEVENT_DEBUG_LEVEL
|
| 14 |
+
from gevent._ffi import TRACE
|
| 15 |
+
from gevent._ffi.callback import callback
|
| 16 |
+
from gevent._compat import PYPY
|
| 17 |
+
from gevent.exceptions import HubDestroyed
|
| 18 |
+
|
| 19 |
+
from gevent import getswitchinterval
|
| 20 |
+
|
| 21 |
+
__all__ = [
|
| 22 |
+
'AbstractLoop',
|
| 23 |
+
'assign_standard_callbacks',
|
| 24 |
+
]
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
class _EVENTSType(object):
|
| 28 |
+
def __repr__(self):
|
| 29 |
+
return 'gevent.core.EVENTS'
|
| 30 |
+
|
| 31 |
+
EVENTS = GEVENT_CORE_EVENTS = _EVENTSType()
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class _DiscardedSet(frozenset):
|
| 35 |
+
__slots__ = ()
|
| 36 |
+
|
| 37 |
+
def discard(self, o):
|
| 38 |
+
"Does nothing."
|
| 39 |
+
|
| 40 |
+
#####
|
| 41 |
+
## Note on CFFI objects, callbacks and the lifecycle of watcher objects
|
| 42 |
+
#
|
| 43 |
+
# Each subclass of `watcher` allocates a C structure of the
|
| 44 |
+
# appropriate type e.g., struct gevent_ev_io and holds this pointer in
|
| 45 |
+
# its `_gwatcher` attribute. When that watcher instance is garbage
|
| 46 |
+
# collected, then the C structure is also freed. The C structure is
|
| 47 |
+
# passed to libev from the watcher's start() method and then to the
|
| 48 |
+
# appropriate C callback function, e.g., _gevent_ev_io_callback, which
|
| 49 |
+
# passes it back to python's _python_callback where we need the
|
| 50 |
+
# watcher instance. Therefore, as long as that callback is active (the
|
| 51 |
+
# watcher is started), the watcher instance must not be allowed to get
|
| 52 |
+
# GC'd---any access at the C level or even the FFI level to the freed
|
| 53 |
+
# memory could crash the process.
|
| 54 |
+
#
|
| 55 |
+
# However, the typical idiom calls for writing something like this:
|
| 56 |
+
# loop.io(fd, python_cb).start()
|
| 57 |
+
# thus forgetting the newly created watcher subclass and allowing it to be immediately
|
| 58 |
+
# GC'd. To combat this, when the watcher is started, it places itself into the loop's
|
| 59 |
+
# `_keepaliveset`, and it only removes itself when the watcher's `stop()` method is called.
|
| 60 |
+
# Often, this is the *only* reference keeping the watcher object, and hence its C structure,
|
| 61 |
+
# alive.
|
| 62 |
+
#
|
| 63 |
+
# This is slightly complicated by the fact that the python-level
|
| 64 |
+
# callback, called from the C callback, could choose to manually stop
|
| 65 |
+
# the watcher. When we return to the C level callback, we now have an
|
| 66 |
+
# invalid pointer, and attempting to pass it back to Python (e.g., to
|
| 67 |
+
# handle an error) could crash. Hence, _python_callback,
|
| 68 |
+
# _gevent_io_callback, and _python_handle_error cooperate to make sure
|
| 69 |
+
# that the watcher instance stays in the loops `_keepaliveset` while
|
| 70 |
+
# the C code could be running---and if it gets removed, to not call back
|
| 71 |
+
# to Python again.
|
| 72 |
+
# See also https://github.com/gevent/gevent/issues/676
|
| 73 |
+
####
|
| 74 |
+
class AbstractCallbacks(object):
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def __init__(self, ffi):
|
| 78 |
+
self.ffi = ffi
|
| 79 |
+
self.callbacks = []
|
| 80 |
+
if GEVENT_DEBUG_LEVEL < TRACE:
|
| 81 |
+
self.from_handle = ffi.from_handle
|
| 82 |
+
|
| 83 |
+
def from_handle(self, handle): # pylint:disable=method-hidden
|
| 84 |
+
x = self.ffi.from_handle(handle)
|
| 85 |
+
return x
|
| 86 |
+
|
| 87 |
+
def python_callback(self, handle, revents):
|
| 88 |
+
"""
|
| 89 |
+
Returns an integer having one of three values:
|
| 90 |
+
|
| 91 |
+
- -1
|
| 92 |
+
An exception occurred during the callback and you must call
|
| 93 |
+
:func:`_python_handle_error` to deal with it. The Python watcher
|
| 94 |
+
object will have the exception tuple saved in ``_exc_info``.
|
| 95 |
+
- 1
|
| 96 |
+
Everything went according to plan. You should check to see if the native
|
| 97 |
+
watcher is still active, and call :func:`python_stop` if it is not. This will
|
| 98 |
+
clean up the memory. Finding the watcher still active at the event loop level,
|
| 99 |
+
but not having stopped itself at the gevent level is a buggy scenario and
|
| 100 |
+
shouldn't happen.
|
| 101 |
+
- 2
|
| 102 |
+
Everything went according to plan, but the watcher has already
|
| 103 |
+
been stopped. Its memory may no longer be valid.
|
| 104 |
+
|
| 105 |
+
This function should never return 0, as that's the default value that
|
| 106 |
+
Python exceptions will produce.
|
| 107 |
+
"""
|
| 108 |
+
#_dbg("Running callback", handle)
|
| 109 |
+
orig_ffi_watcher = None
|
| 110 |
+
orig_loop = None
|
| 111 |
+
try:
|
| 112 |
+
# Even dereferencing the handle needs to be inside the try/except;
|
| 113 |
+
# if we don't return normally (e.g., a signal) then we wind up going
|
| 114 |
+
# to the 'onerror' handler (unhandled_onerror), which
|
| 115 |
+
# is not what we want; that can permanently wedge the loop depending
|
| 116 |
+
# on which callback was executing.
|
| 117 |
+
# XXX: See comments in that function. We may be able to restart and do better?
|
| 118 |
+
if not handle:
|
| 119 |
+
# Hmm, a NULL handle. That's not supposed to happen.
|
| 120 |
+
# We can easily get into a loop if we deref it and allow that
|
| 121 |
+
# to raise.
|
| 122 |
+
_dbg("python_callback got null handle")
|
| 123 |
+
return 1
|
| 124 |
+
the_watcher = self.from_handle(handle)
|
| 125 |
+
orig_ffi_watcher = the_watcher._watcher
|
| 126 |
+
orig_loop = the_watcher.loop
|
| 127 |
+
args = the_watcher.args
|
| 128 |
+
if args is None:
|
| 129 |
+
# Legacy behaviour from corecext: convert None into ()
|
| 130 |
+
# See test__core_watcher.py
|
| 131 |
+
args = _NOARGS
|
| 132 |
+
if args and args[0] == GEVENT_CORE_EVENTS:
|
| 133 |
+
args = (revents, ) + args[1:]
|
| 134 |
+
the_watcher.callback(*args) # None here means we weren't started
|
| 135 |
+
except: # pylint:disable=bare-except
|
| 136 |
+
# It's possible for ``the_watcher`` to be undefined (UnboundLocalError)
|
| 137 |
+
# if we threw an exception (signal) on the line that created that variable.
|
| 138 |
+
# This is typically the case with a signal under libuv
|
| 139 |
+
try:
|
| 140 |
+
the_watcher
|
| 141 |
+
except UnboundLocalError:
|
| 142 |
+
the_watcher = self.from_handle(handle)
|
| 143 |
+
|
| 144 |
+
# It may not be safe to do anything with `handle` or `orig_ffi_watcher`
|
| 145 |
+
# anymore. If the watcher closed or stopped itself *before* throwing the exception,
|
| 146 |
+
# then the `handle` and `orig_ffi_watcher` may no longer be valid. Attempting to
|
| 147 |
+
# e.g., dereference the handle is likely to crash the process.
|
| 148 |
+
the_watcher._exc_info = sys.exc_info()
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# If it hasn't been stopped, we need to make sure its
|
| 152 |
+
# memory stays valid so we can stop it at the native level if needed.
|
| 153 |
+
# If its loop is gone, it has already been stopped,
|
| 154 |
+
# see https://github.com/gevent/gevent/issues/1295 for a case where
|
| 155 |
+
# that happened, as well as issue #1482
|
| 156 |
+
if (
|
| 157 |
+
# The last thing it does. Full successful close.
|
| 158 |
+
the_watcher.loop is None
|
| 159 |
+
# Only a partial close. We could leak memory and even crash later.
|
| 160 |
+
or the_watcher._handle is None
|
| 161 |
+
):
|
| 162 |
+
# Prevent unhandled_onerror from using the invalid handle
|
| 163 |
+
handle = None
|
| 164 |
+
exc_info = the_watcher._exc_info
|
| 165 |
+
del the_watcher._exc_info
|
| 166 |
+
try:
|
| 167 |
+
if orig_loop is not None:
|
| 168 |
+
orig_loop.handle_error(the_watcher, *exc_info)
|
| 169 |
+
else:
|
| 170 |
+
self.unhandled_onerror(*exc_info)
|
| 171 |
+
except:
|
| 172 |
+
print("WARNING: gevent: Error when handling error",
|
| 173 |
+
file=sys.stderr)
|
| 174 |
+
traceback.print_exc()
|
| 175 |
+
# Signal that we're closed, no need to do more.
|
| 176 |
+
return 2
|
| 177 |
+
|
| 178 |
+
# Keep it around so we can close it later.
|
| 179 |
+
the_watcher.loop._keepaliveset.add(the_watcher)
|
| 180 |
+
return -1
|
| 181 |
+
|
| 182 |
+
if (the_watcher.loop is not None
|
| 183 |
+
and the_watcher in the_watcher.loop._keepaliveset
|
| 184 |
+
and the_watcher._watcher is orig_ffi_watcher):
|
| 185 |
+
# It didn't stop itself, *and* it didn't stop itself, reset
|
| 186 |
+
# its watcher, and start itself again. libuv's io watchers
|
| 187 |
+
# multiplex and may do this.
|
| 188 |
+
|
| 189 |
+
# The normal, expected scenario when we find the watcher still
|
| 190 |
+
# in the keepaliveset is that it is still active at the event loop
|
| 191 |
+
# level, so we don't expect that python_stop gets called.
|
| 192 |
+
#_dbg("The watcher has not stopped itself, possibly still active", the_watcher)
|
| 193 |
+
return 1
|
| 194 |
+
return 2 # it stopped itself
|
| 195 |
+
|
| 196 |
+
def python_handle_error(self, handle, _revents):
|
| 197 |
+
_dbg("Handling error for handle", handle)
|
| 198 |
+
if not handle:
|
| 199 |
+
return
|
| 200 |
+
try:
|
| 201 |
+
watcher = self.from_handle(handle)
|
| 202 |
+
exc_info = watcher._exc_info
|
| 203 |
+
del watcher._exc_info
|
| 204 |
+
# In the past, we passed the ``watcher`` itself as the context,
|
| 205 |
+
# which typically meant that the Hub would just print
|
| 206 |
+
# the exception. This is a problem because sometimes we can't
|
| 207 |
+
# detect signals until late in ``python_callback``; specifically,
|
| 208 |
+
# test_selectors.py:DefaultSelectorTest.test_select_interrupt_exc
|
| 209 |
+
# installs a SIGALRM handler that raises an exception. That exception can happen
|
| 210 |
+
# before we enter ``python_callback`` or at any point within it because of the way
|
| 211 |
+
# libuv swallows signals. By passing None, we get the exception prapagated into
|
| 212 |
+
# the main greenlet (which is probably *also* not what we always want, but
|
| 213 |
+
# I see no way to distinguish the cases).
|
| 214 |
+
watcher.loop.handle_error(None, *exc_info)
|
| 215 |
+
finally:
|
| 216 |
+
# XXX Since we're here on an error condition, and we
|
| 217 |
+
# made sure that the watcher object was put in loop._keepaliveset,
|
| 218 |
+
# what about not stopping the watcher? Looks like a possible
|
| 219 |
+
# memory leak?
|
| 220 |
+
# XXX: This used to do "if revents & (libev.EV_READ | libev.EV_WRITE)"
|
| 221 |
+
# before stopping. Why?
|
| 222 |
+
try:
|
| 223 |
+
watcher.stop()
|
| 224 |
+
except: # pylint:disable=bare-except
|
| 225 |
+
watcher.loop.handle_error(watcher, *sys.exc_info())
|
| 226 |
+
return # pylint:disable=lost-exception,return-in-finally
|
| 227 |
+
|
| 228 |
+
def unhandled_onerror(self, t, v, tb):
|
| 229 |
+
# This is supposed to be called for signals, etc.
|
| 230 |
+
# This is the onerror= value for CFFI.
|
| 231 |
+
# If we return None, C will get a value of 0/NULL;
|
| 232 |
+
# if we raise, CFFI will print the exception and then
|
| 233 |
+
# return 0/NULL; (unless error= was configured)
|
| 234 |
+
# If things go as planned, we return the value that asks
|
| 235 |
+
# C to call back and check on if the watcher needs to be closed or
|
| 236 |
+
# not.
|
| 237 |
+
|
| 238 |
+
# XXX: TODO: Could this cause events to be lost? Maybe we need to return
|
| 239 |
+
# a value that causes the C loop to try the callback again?
|
| 240 |
+
# at least for signals under libuv, which are delivered at very odd times.
|
| 241 |
+
# Hopefully the event still shows up when we poll the next time.
|
| 242 |
+
watcher = None
|
| 243 |
+
handle = tb.tb_frame.f_locals.get('handle') if tb is not None else None
|
| 244 |
+
if handle: # handle could be NULL
|
| 245 |
+
watcher = self.from_handle(handle)
|
| 246 |
+
if watcher is not None:
|
| 247 |
+
watcher.loop.handle_error(None, t, v, tb)
|
| 248 |
+
return 1
|
| 249 |
+
|
| 250 |
+
# Raising it causes a lot of noise from CFFI
|
| 251 |
+
print("WARNING: gevent: Unhandled error with no watcher",
|
| 252 |
+
file=sys.stderr)
|
| 253 |
+
traceback.print_exception(t, v, tb)
|
| 254 |
+
|
| 255 |
+
def python_stop(self, handle):
|
| 256 |
+
if not handle: # pragma: no cover
|
| 257 |
+
print(
|
| 258 |
+
"WARNING: gevent: Unable to dereference handle; not stopping watcher. "
|
| 259 |
+
"Native resources may leak. This is most likely a bug in gevent.",
|
| 260 |
+
file=sys.stderr)
|
| 261 |
+
# The alternative is to crash with no helpful information
|
| 262 |
+
# NOTE: Raising exceptions here does nothing, they're swallowed by CFFI.
|
| 263 |
+
# Since the C level passed in a null pointer, even dereferencing the handle
|
| 264 |
+
# will just produce some exceptions.
|
| 265 |
+
return
|
| 266 |
+
watcher = self.from_handle(handle)
|
| 267 |
+
watcher.stop()
|
| 268 |
+
|
| 269 |
+
if not PYPY:
|
| 270 |
+
def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument
|
| 271 |
+
# If we have the onerror callback, this is a no-op; all the real
|
| 272 |
+
# work to rethrow the exception is done by the onerror callback
|
| 273 |
+
|
| 274 |
+
# NOTE: Unlike the rest of the functions, this is called with a pointer
|
| 275 |
+
# to the C level structure, *not* a pointer to the void* that represents a
|
| 276 |
+
# <cdata> for the Python Watcher object.
|
| 277 |
+
pass
|
| 278 |
+
else: # PyPy
|
| 279 |
+
# On PyPy, we need the function to have some sort of body, otherwise
|
| 280 |
+
# the signal exceptions don't always get caught, *especially* with
|
| 281 |
+
# libuv (however, there's no reason to expect this to only be a libuv
|
| 282 |
+
# issue; it's just that we don't depend on the periodic signal timer
|
| 283 |
+
# under libev, so the issue is much more pronounced under libuv)
|
| 284 |
+
# test_socket's test_sendall_interrupted can hang.
|
| 285 |
+
# See https://github.com/gevent/gevent/issues/1112
|
| 286 |
+
|
| 287 |
+
def python_check_callback(self, watcher_ptr): # pylint:disable=unused-argument
|
| 288 |
+
# Things we've tried that *don't* work:
|
| 289 |
+
# greenlet.getcurrent()
|
| 290 |
+
# 1 + 1
|
| 291 |
+
try:
|
| 292 |
+
raise MemoryError()
|
| 293 |
+
except MemoryError:
|
| 294 |
+
pass
|
| 295 |
+
|
| 296 |
+
def python_prepare_callback(self, watcher_ptr):
|
| 297 |
+
loop = self._find_loop_from_c_watcher(watcher_ptr)
|
| 298 |
+
if loop is None: # pragma: no cover
|
| 299 |
+
print("WARNING: gevent: running prepare callbacks from a destroyed handle: ",
|
| 300 |
+
watcher_ptr)
|
| 301 |
+
return
|
| 302 |
+
loop._run_callbacks()
|
| 303 |
+
|
| 304 |
+
def check_callback_onerror(self, t, v, tb):
|
| 305 |
+
loop = None
|
| 306 |
+
watcher_ptr = self._find_watcher_ptr_in_traceback(tb)
|
| 307 |
+
if watcher_ptr:
|
| 308 |
+
loop = self._find_loop_from_c_watcher(watcher_ptr)
|
| 309 |
+
if loop is not None:
|
| 310 |
+
# None as the context argument causes the exception to be raised
|
| 311 |
+
# in the main greenlet.
|
| 312 |
+
loop.handle_error(None, t, v, tb)
|
| 313 |
+
return None
|
| 314 |
+
raise v # Let CFFI print
|
| 315 |
+
|
| 316 |
+
def _find_loop_from_c_watcher(self, watcher_ptr):
|
| 317 |
+
raise NotImplementedError()
|
| 318 |
+
|
| 319 |
+
def _find_watcher_ptr_in_traceback(self, tb):
|
| 320 |
+
return tb.tb_frame.f_locals['watcher_ptr'] if tb is not None else None
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def assign_standard_callbacks(ffi, lib, callbacks_class, extras=()): # pylint:disable=unused-argument
|
| 324 |
+
"""
|
| 325 |
+
Given the typical *ffi* and *lib* arguments, and a subclass of :class:`AbstractCallbacks`
|
| 326 |
+
in *callbacks_class*, set up the ``def_extern`` Python callbacks from C
|
| 327 |
+
into an instance of *callbacks_class*.
|
| 328 |
+
|
| 329 |
+
:param tuple extras: If given, this is a sequence of ``(name, error_function)``
|
| 330 |
+
additional callbacks to register. Each *name* is an attribute of
|
| 331 |
+
the *callbacks_class* instance. (Each element cas also be just a *name*.)
|
| 332 |
+
:return: The *callbacks_class* instance. This object must be kept alive,
|
| 333 |
+
typically at module scope.
|
| 334 |
+
"""
|
| 335 |
+
# callbacks keeps these cdata objects alive at the python level
|
| 336 |
+
callbacks = callbacks_class(ffi)
|
| 337 |
+
extras = [extra if len(extra) == 2 else (extra, None) for extra in extras]
|
| 338 |
+
extras = tuple((getattr(callbacks, name), error) for name, error in extras)
|
| 339 |
+
for (func, error_func) in (
|
| 340 |
+
(callbacks.python_callback, None),
|
| 341 |
+
(callbacks.python_handle_error, None),
|
| 342 |
+
(callbacks.python_stop, None),
|
| 343 |
+
(callbacks.python_check_callback, callbacks.check_callback_onerror),
|
| 344 |
+
(callbacks.python_prepare_callback, callbacks.check_callback_onerror)
|
| 345 |
+
) + extras:
|
| 346 |
+
# The name of the callback function matches the 'extern Python' declaration.
|
| 347 |
+
error_func = error_func or callbacks.unhandled_onerror
|
| 348 |
+
callback = ffi.def_extern(onerror=error_func)(func)
|
| 349 |
+
# keep alive the cdata
|
| 350 |
+
# (def_extern returns the original function, and it requests that
|
| 351 |
+
# the function be "global", so maybe it keeps a hard reference to it somewhere now
|
| 352 |
+
# unlike ffi.callback(), and we don't need to do this?)
|
| 353 |
+
callbacks.callbacks.append(callback)
|
| 354 |
+
|
| 355 |
+
# At this point, the library C variable (static function, actually)
|
| 356 |
+
# is filled in.
|
| 357 |
+
|
| 358 |
+
return callbacks
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
basestring = (bytes, str)
|
| 363 |
+
integer_types = (int,)
|
| 364 |
+
|
| 365 |
+
|
| 366 |
+
_NOARGS = ()
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
class AbstractLoop(object):
|
| 370 |
+
# pylint:disable=too-many-public-methods,too-many-instance-attributes
|
| 371 |
+
|
| 372 |
+
# How many callbacks we should run between checking against the
|
| 373 |
+
# switch interval.
|
| 374 |
+
CALLBACK_CHECK_COUNT = 50
|
| 375 |
+
|
| 376 |
+
error_handler = None
|
| 377 |
+
|
| 378 |
+
_CHECK_POINTER = None
|
| 379 |
+
|
| 380 |
+
_TIMER_POINTER = None
|
| 381 |
+
_TIMER_CALLBACK_SIG = None
|
| 382 |
+
|
| 383 |
+
_PREPARE_POINTER = None
|
| 384 |
+
|
| 385 |
+
starting_timer_may_update_loop_time = False
|
| 386 |
+
|
| 387 |
+
# Subclasses should set this in __init__ to reflect
|
| 388 |
+
# whether they were the default loop.
|
| 389 |
+
_default = None
|
| 390 |
+
|
| 391 |
+
_keepaliveset = _DiscardedSet()
|
| 392 |
+
_threadsafe_async = None
|
| 393 |
+
|
| 394 |
+
def __init__(self, ffi, lib, watchers, flags=None, default=None):
|
| 395 |
+
self._ffi = ffi
|
| 396 |
+
self._lib = lib
|
| 397 |
+
self._ptr = None
|
| 398 |
+
self._handle_to_self = self._ffi.new_handle(self) # XXX: Reference cycle?
|
| 399 |
+
self._watchers = watchers
|
| 400 |
+
self._in_callback = False
|
| 401 |
+
self._callbacks = deque()
|
| 402 |
+
# Stores python watcher objects while they are started
|
| 403 |
+
self._keepaliveset = set()
|
| 404 |
+
self._init_loop_and_aux_watchers(flags, default)
|
| 405 |
+
|
| 406 |
+
def _init_loop_and_aux_watchers(self, flags=None, default=None):
|
| 407 |
+
self._ptr = self._init_loop(flags, default)
|
| 408 |
+
|
| 409 |
+
# self._check is a watcher that runs in each iteration of the
|
| 410 |
+
# mainloop, just after the blocking call. It's point is to handle
|
| 411 |
+
# signals. It doesn't run watchers or callbacks, it just exists to give
|
| 412 |
+
# CFFI a chance to raise signal exceptions so we can handle them.
|
| 413 |
+
self._check = self._ffi.new(self._CHECK_POINTER)
|
| 414 |
+
self._check.data = self._handle_to_self
|
| 415 |
+
self._init_and_start_check()
|
| 416 |
+
|
| 417 |
+
# self._prepare is a watcher that runs in each iteration of the mainloop,
|
| 418 |
+
# just before the blocking call. It's where we run deferred callbacks
|
| 419 |
+
# from self.run_callback. This cooperates with _setup_for_run_callback()
|
| 420 |
+
# to schedule self._timer0 if needed.
|
| 421 |
+
self._prepare = self._ffi.new(self._PREPARE_POINTER)
|
| 422 |
+
self._prepare.data = self._handle_to_self
|
| 423 |
+
self._init_and_start_prepare()
|
| 424 |
+
|
| 425 |
+
# A timer we start and stop on demand. If we have callbacks,
|
| 426 |
+
# too many to run in one iteration of _run_callbacks, we turn this
|
| 427 |
+
# on so as to have the next iteration of the run loop return to us
|
| 428 |
+
# as quickly as possible.
|
| 429 |
+
# TODO: There may be a more efficient way to do this using ev_timer_again;
|
| 430 |
+
# see the "ev_timer" section of the ev manpage (http://linux.die.net/man/3/ev)
|
| 431 |
+
# Alternatively, setting the ev maximum block time may also work.
|
| 432 |
+
self._timer0 = self._ffi.new(self._TIMER_POINTER)
|
| 433 |
+
self._timer0.data = self._handle_to_self
|
| 434 |
+
self._init_callback_timer()
|
| 435 |
+
|
| 436 |
+
self._threadsafe_async = self.async_(ref=False)
|
| 437 |
+
# No need to do anything with this on ``fork()``, both libev and libuv
|
| 438 |
+
# take care of creating a new pipe in their respective ``loop_fork()`` methods.
|
| 439 |
+
self._threadsafe_async.start(lambda: None)
|
| 440 |
+
# TODO: We may be able to do something nicer and use the existing python_callback
|
| 441 |
+
# combined with onerror and the class check/timer/prepare to simplify things
|
| 442 |
+
# and unify our handling
|
| 443 |
+
|
| 444 |
+
def _init_loop(self, flags, default):
|
| 445 |
+
"""
|
| 446 |
+
Called by __init__ to create or find the loop. The return value
|
| 447 |
+
is assigned to self._ptr.
|
| 448 |
+
"""
|
| 449 |
+
raise NotImplementedError()
|
| 450 |
+
|
| 451 |
+
def _init_and_start_check(self):
|
| 452 |
+
raise NotImplementedError()
|
| 453 |
+
|
| 454 |
+
def _init_and_start_prepare(self):
|
| 455 |
+
raise NotImplementedError()
|
| 456 |
+
|
| 457 |
+
def _init_callback_timer(self):
|
| 458 |
+
raise NotImplementedError()
|
| 459 |
+
|
| 460 |
+
def _stop_callback_timer(self):
|
| 461 |
+
raise NotImplementedError()
|
| 462 |
+
|
| 463 |
+
def _start_callback_timer(self):
|
| 464 |
+
raise NotImplementedError()
|
| 465 |
+
|
| 466 |
+
def _check_callback_handle_error(self, t, v, tb):
|
| 467 |
+
self.handle_error(None, t, v, tb)
|
| 468 |
+
|
| 469 |
+
def _run_callbacks(self): # pylint:disable=too-many-branches
|
| 470 |
+
# When we're running callbacks, its safe for timers to
|
| 471 |
+
# update the notion of the current time (because if we're here,
|
| 472 |
+
# we're not running in a timer callback that may let other timers
|
| 473 |
+
# run; this is mostly an issue for libuv).
|
| 474 |
+
|
| 475 |
+
# That's actually a bit of a lie: on libev, self._timer0 really is
|
| 476 |
+
# a timer, and so sometimes this is running in a timer callback, not
|
| 477 |
+
# a prepare callback. But that's OK, libev doesn't suffer from cascading
|
| 478 |
+
# timer expiration and its safe to update the loop time at any
|
| 479 |
+
# moment there.
|
| 480 |
+
self.starting_timer_may_update_loop_time = True
|
| 481 |
+
try:
|
| 482 |
+
count = self.CALLBACK_CHECK_COUNT
|
| 483 |
+
now = self.now()
|
| 484 |
+
expiration = now + getswitchinterval()
|
| 485 |
+
self._stop_callback_timer()
|
| 486 |
+
while self._callbacks:
|
| 487 |
+
cb = self._callbacks.popleft() # pylint:disable=assignment-from-no-return
|
| 488 |
+
count -= 1
|
| 489 |
+
self.unref() # XXX: libuv doesn't have a global ref count!
|
| 490 |
+
callback = cb.callback
|
| 491 |
+
cb.callback = None
|
| 492 |
+
args = cb.args
|
| 493 |
+
if callback is None or args is None:
|
| 494 |
+
# it's been stopped
|
| 495 |
+
continue
|
| 496 |
+
|
| 497 |
+
try:
|
| 498 |
+
callback(*args)
|
| 499 |
+
except: # pylint:disable=bare-except
|
| 500 |
+
# If we allow an exception to escape this method (while we are running the ev callback),
|
| 501 |
+
# then CFFI will print the error and libev will continue executing.
|
| 502 |
+
# There are two problems with this. The first is that the code after
|
| 503 |
+
# the loop won't run. The second is that any remaining callbacks scheduled
|
| 504 |
+
# for this loop iteration will be silently dropped; they won't run, but they'll
|
| 505 |
+
# also not be *stopped* (which is not a huge deal unless you're looking for
|
| 506 |
+
# consistency or checking the boolean/pending status; the loop doesn't keep
|
| 507 |
+
# a reference to them like it does to watchers...*UNLESS* the callback itself had
|
| 508 |
+
# a reference to a watcher; then I don't know what would happen, it depends on
|
| 509 |
+
# the state of the watcher---a leak or crash is not totally inconceivable).
|
| 510 |
+
# The Cython implementation in core.ppyx uses gevent_call from callbacks.c
|
| 511 |
+
# to run the callback, which uses gevent_handle_error to handle any errors the
|
| 512 |
+
# Python callback raises...it unconditionally simply prints any error raised
|
| 513 |
+
# by loop.handle_error and clears it, so callback handling continues.
|
| 514 |
+
# We take a similar approach (but are extra careful about printing)
|
| 515 |
+
try:
|
| 516 |
+
self.handle_error(cb, *sys.exc_info())
|
| 517 |
+
except: # pylint:disable=bare-except
|
| 518 |
+
try:
|
| 519 |
+
print("Exception while handling another error", file=sys.stderr)
|
| 520 |
+
traceback.print_exc()
|
| 521 |
+
except: # pylint:disable=bare-except
|
| 522 |
+
pass # Nothing we can do here
|
| 523 |
+
finally:
|
| 524 |
+
# NOTE: this must be reset here, because cb.args is used as a flag in
|
| 525 |
+
# the callback class so that bool(cb) of a callback that has been run
|
| 526 |
+
# becomes False
|
| 527 |
+
cb.args = None
|
| 528 |
+
|
| 529 |
+
# We've finished running one group of callbacks
|
| 530 |
+
# but we may have more, so before looping check our
|
| 531 |
+
# switch interval.
|
| 532 |
+
if count == 0 and self._callbacks:
|
| 533 |
+
count = self.CALLBACK_CHECK_COUNT
|
| 534 |
+
self.update_now()
|
| 535 |
+
if self.now() >= expiration:
|
| 536 |
+
now = 0
|
| 537 |
+
break
|
| 538 |
+
|
| 539 |
+
# Update the time before we start going again, if we didn't
|
| 540 |
+
# just do so.
|
| 541 |
+
if now != 0:
|
| 542 |
+
self.update_now()
|
| 543 |
+
|
| 544 |
+
if self._callbacks:
|
| 545 |
+
self._start_callback_timer()
|
| 546 |
+
finally:
|
| 547 |
+
self.starting_timer_may_update_loop_time = False
|
| 548 |
+
|
| 549 |
+
def _stop_aux_watchers(self):
|
| 550 |
+
if self._threadsafe_async is not None:
|
| 551 |
+
self._threadsafe_async.close()
|
| 552 |
+
self._threadsafe_async = None
|
| 553 |
+
|
| 554 |
+
def destroy(self):
|
| 555 |
+
ptr = self.ptr
|
| 556 |
+
if ptr:
|
| 557 |
+
try:
|
| 558 |
+
if not self._can_destroy_loop(ptr):
|
| 559 |
+
return False
|
| 560 |
+
self._stop_aux_watchers()
|
| 561 |
+
self._destroy_loop(ptr)
|
| 562 |
+
finally:
|
| 563 |
+
# not ffi.NULL, we don't want something that can be
|
| 564 |
+
# passed to C and crash later. This will create nice friendly
|
| 565 |
+
# TypeError from CFFI.
|
| 566 |
+
self._ptr = None
|
| 567 |
+
del self._handle_to_self
|
| 568 |
+
del self._callbacks
|
| 569 |
+
del self._keepaliveset
|
| 570 |
+
|
| 571 |
+
return True
|
| 572 |
+
|
| 573 |
+
def _can_destroy_loop(self, ptr):
|
| 574 |
+
raise NotImplementedError()
|
| 575 |
+
|
| 576 |
+
def _destroy_loop(self, ptr):
|
| 577 |
+
raise NotImplementedError()
|
| 578 |
+
|
| 579 |
+
@property
|
| 580 |
+
def ptr(self):
|
| 581 |
+
# Use this when you need to be sure the pointer is valid.
|
| 582 |
+
return self._ptr
|
| 583 |
+
|
| 584 |
+
@property
|
| 585 |
+
def WatcherType(self):
|
| 586 |
+
return self._watchers.watcher
|
| 587 |
+
|
| 588 |
+
@property
|
| 589 |
+
def MAXPRI(self):
|
| 590 |
+
return 1
|
| 591 |
+
|
| 592 |
+
@property
|
| 593 |
+
def MINPRI(self):
|
| 594 |
+
return 1
|
| 595 |
+
|
| 596 |
+
def _handle_syserr(self, message, errno):
|
| 597 |
+
try:
|
| 598 |
+
errno = os.strerror(errno)
|
| 599 |
+
except: # pylint:disable=bare-except
|
| 600 |
+
traceback.print_exc()
|
| 601 |
+
try:
|
| 602 |
+
message = '%s: %s' % (message, errno)
|
| 603 |
+
except: # pylint:disable=bare-except
|
| 604 |
+
traceback.print_exc()
|
| 605 |
+
self.handle_error(None, SystemError, SystemError(message), None)
|
| 606 |
+
|
| 607 |
+
def handle_error(self, context, type, value, tb):
|
| 608 |
+
if type is HubDestroyed:
|
| 609 |
+
self._callbacks.clear()
|
| 610 |
+
self.break_()
|
| 611 |
+
return
|
| 612 |
+
|
| 613 |
+
handle_error = None
|
| 614 |
+
error_handler = self.error_handler
|
| 615 |
+
if error_handler is not None:
|
| 616 |
+
# we do want to do getattr every time so that setting Hub.handle_error property just works
|
| 617 |
+
handle_error = getattr(error_handler, 'handle_error', error_handler)
|
| 618 |
+
handle_error(context, type, value, tb)
|
| 619 |
+
else:
|
| 620 |
+
self._default_handle_error(context, type, value, tb)
|
| 621 |
+
|
| 622 |
+
def _default_handle_error(self, context, type, value, tb): # pylint:disable=unused-argument
|
| 623 |
+
# note: Hub sets its own error handler so this is not used by gevent
|
| 624 |
+
# this is here to make core.loop usable without the rest of gevent
|
| 625 |
+
# Should cause the loop to stop running.
|
| 626 |
+
traceback.print_exception(type, value, tb)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def run(self, nowait=False, once=False):
|
| 630 |
+
raise NotImplementedError()
|
| 631 |
+
|
| 632 |
+
def reinit(self):
|
| 633 |
+
raise NotImplementedError()
|
| 634 |
+
|
| 635 |
+
def ref(self):
|
| 636 |
+
# XXX: libuv doesn't do it this way
|
| 637 |
+
raise NotImplementedError()
|
| 638 |
+
|
| 639 |
+
def unref(self):
|
| 640 |
+
raise NotImplementedError()
|
| 641 |
+
|
| 642 |
+
def break_(self, how=None):
|
| 643 |
+
raise NotImplementedError()
|
| 644 |
+
|
| 645 |
+
def verify(self):
|
| 646 |
+
pass
|
| 647 |
+
|
| 648 |
+
def now(self):
|
| 649 |
+
raise NotImplementedError()
|
| 650 |
+
|
| 651 |
+
def update_now(self):
|
| 652 |
+
raise NotImplementedError()
|
| 653 |
+
|
| 654 |
+
def update(self):
|
| 655 |
+
import warnings
|
| 656 |
+
warnings.warn("'update' is deprecated; use 'update_now'",
|
| 657 |
+
DeprecationWarning,
|
| 658 |
+
stacklevel=2)
|
| 659 |
+
self.update_now()
|
| 660 |
+
|
| 661 |
+
def __repr__(self):
|
| 662 |
+
return '<%s.%s at 0x%x %s>' % (
|
| 663 |
+
self.__class__.__module__,
|
| 664 |
+
self.__class__.__name__,
|
| 665 |
+
id(self),
|
| 666 |
+
self._format()
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
@property
|
| 670 |
+
def default(self):
|
| 671 |
+
return self._default if self.ptr else False
|
| 672 |
+
|
| 673 |
+
@property
|
| 674 |
+
def iteration(self):
|
| 675 |
+
return -1
|
| 676 |
+
|
| 677 |
+
@property
|
| 678 |
+
def depth(self):
|
| 679 |
+
return -1
|
| 680 |
+
|
| 681 |
+
@property
|
| 682 |
+
def backend_int(self):
|
| 683 |
+
return 0
|
| 684 |
+
|
| 685 |
+
@property
|
| 686 |
+
def backend(self):
|
| 687 |
+
return "default"
|
| 688 |
+
|
| 689 |
+
@property
|
| 690 |
+
def pendingcnt(self):
|
| 691 |
+
return 0
|
| 692 |
+
|
| 693 |
+
def io(self, fd, events, ref=True, priority=None):
|
| 694 |
+
return self._watchers.io(self, fd, events, ref, priority)
|
| 695 |
+
|
| 696 |
+
def closing_fd(self, fd): # pylint:disable=unused-argument
|
| 697 |
+
return False
|
| 698 |
+
|
| 699 |
+
def timer(self, after, repeat=0.0, ref=True, priority=None):
|
| 700 |
+
return self._watchers.timer(self, after, repeat, ref, priority)
|
| 701 |
+
|
| 702 |
+
def signal(self, signum, ref=True, priority=None):
|
| 703 |
+
return self._watchers.signal(self, signum, ref, priority)
|
| 704 |
+
|
| 705 |
+
def idle(self, ref=True, priority=None):
|
| 706 |
+
return self._watchers.idle(self, ref, priority)
|
| 707 |
+
|
| 708 |
+
def prepare(self, ref=True, priority=None):
|
| 709 |
+
return self._watchers.prepare(self, ref, priority)
|
| 710 |
+
|
| 711 |
+
def check(self, ref=True, priority=None):
|
| 712 |
+
return self._watchers.check(self, ref, priority)
|
| 713 |
+
|
| 714 |
+
def fork(self, ref=True, priority=None):
|
| 715 |
+
return self._watchers.fork(self, ref, priority)
|
| 716 |
+
|
| 717 |
+
def async_(self, ref=True, priority=None):
|
| 718 |
+
return self._watchers.async_(self, ref, priority)
|
| 719 |
+
|
| 720 |
+
# Provide BWC for those that can use 'async' as is
|
| 721 |
+
locals()['async'] = async_
|
| 722 |
+
|
| 723 |
+
if sys.platform != "win32":
|
| 724 |
+
|
| 725 |
+
def child(self, pid, trace=0, ref=True):
|
| 726 |
+
return self._watchers.child(self, pid, trace, ref)
|
| 727 |
+
|
| 728 |
+
def install_sigchld(self):
|
| 729 |
+
pass
|
| 730 |
+
|
| 731 |
+
def stat(self, path, interval=0.0, ref=True, priority=None):
|
| 732 |
+
return self._watchers.stat(self, path, interval, ref, priority)
|
| 733 |
+
|
| 734 |
+
def callback(self, priority=None):
|
| 735 |
+
return callback(self, priority)
|
| 736 |
+
|
| 737 |
+
def _setup_for_run_callback(self):
|
| 738 |
+
raise NotImplementedError()
|
| 739 |
+
|
| 740 |
+
def run_callback(self, func, *args):
|
| 741 |
+
# If we happen to already be running callbacks (inside
|
| 742 |
+
# _run_callbacks), this could happen almost immediately,
|
| 743 |
+
# without the loop cycling.
|
| 744 |
+
cb = callback(func, args)
|
| 745 |
+
self._callbacks.append(cb) # Relying on the GIL for this to be threadsafe
|
| 746 |
+
self._setup_for_run_callback() # XXX: This may not be threadsafe.
|
| 747 |
+
return cb
|
| 748 |
+
|
| 749 |
+
def run_callback_threadsafe(self, func, *args):
|
| 750 |
+
cb = self.run_callback(func, *args)
|
| 751 |
+
self._threadsafe_async.send()
|
| 752 |
+
return cb
|
| 753 |
+
|
| 754 |
+
def _format(self):
|
| 755 |
+
ptr = self.ptr
|
| 756 |
+
if not ptr:
|
| 757 |
+
return 'destroyed'
|
| 758 |
+
msg = "backend=" + self.backend
|
| 759 |
+
msg += ' ptr=' + str(ptr)
|
| 760 |
+
if self.default:
|
| 761 |
+
msg += ' default'
|
| 762 |
+
msg += ' pending=%s' % self.pendingcnt
|
| 763 |
+
msg += self._format_details()
|
| 764 |
+
return msg
|
| 765 |
+
|
| 766 |
+
def _format_details(self):
|
| 767 |
+
msg = ''
|
| 768 |
+
fileno = self.fileno() # pylint:disable=assignment-from-none
|
| 769 |
+
try:
|
| 770 |
+
activecnt = self.activecnt
|
| 771 |
+
except AttributeError:
|
| 772 |
+
activecnt = None
|
| 773 |
+
if activecnt is not None:
|
| 774 |
+
msg += ' ref=' + repr(activecnt)
|
| 775 |
+
if fileno is not None:
|
| 776 |
+
msg += ' fileno=' + repr(fileno)
|
| 777 |
+
#if sigfd is not None and sigfd != -1:
|
| 778 |
+
# msg += ' sigfd=' + repr(sigfd)
|
| 779 |
+
msg += ' callbacks=' + str(len(self._callbacks))
|
| 780 |
+
return msg
|
| 781 |
+
|
| 782 |
+
def fileno(self):
|
| 783 |
+
return None
|
| 784 |
+
|
| 785 |
+
@property
|
| 786 |
+
def activecnt(self):
|
| 787 |
+
if not self.ptr:
|
| 788 |
+
raise ValueError('operation on destroyed loop')
|
| 789 |
+
return 0
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/_ffi/watcher.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Useful base classes for watchers. The available
|
| 3 |
+
watchers will depend on the specific event loop.
|
| 4 |
+
"""
|
| 5 |
+
# pylint:disable=not-callable
|
| 6 |
+
from __future__ import absolute_import, print_function
|
| 7 |
+
|
| 8 |
+
import signal as signalmodule
|
| 9 |
+
import functools
|
| 10 |
+
import warnings
|
| 11 |
+
|
| 12 |
+
from gevent._config import config
|
| 13 |
+
from gevent._util import LazyOnClass
|
| 14 |
+
|
| 15 |
+
try:
|
| 16 |
+
from tracemalloc import get_object_traceback
|
| 17 |
+
|
| 18 |
+
def tracemalloc(init):
|
| 19 |
+
# PYTHONTRACEMALLOC env var controls this on Python 3.
|
| 20 |
+
return init
|
| 21 |
+
except ImportError: # Python < 3.4
|
| 22 |
+
|
| 23 |
+
if config.trace_malloc:
|
| 24 |
+
# Use the same env var to turn this on for Python 2
|
| 25 |
+
import traceback
|
| 26 |
+
|
| 27 |
+
class _TB(object):
|
| 28 |
+
__slots__ = ('lines',)
|
| 29 |
+
|
| 30 |
+
def __init__(self, lines):
|
| 31 |
+
# These end in newlines, which we don't want for consistency
|
| 32 |
+
self.lines = [x.rstrip() for x in lines]
|
| 33 |
+
|
| 34 |
+
def format(self):
|
| 35 |
+
return self.lines
|
| 36 |
+
|
| 37 |
+
def tracemalloc(init):
|
| 38 |
+
@functools.wraps(init)
|
| 39 |
+
def traces(self, *args, **kwargs):
|
| 40 |
+
init(self, *args, **kwargs)
|
| 41 |
+
self._captured_malloc = _TB(traceback.format_stack())
|
| 42 |
+
return traces
|
| 43 |
+
|
| 44 |
+
def get_object_traceback(obj):
|
| 45 |
+
return obj._captured_malloc
|
| 46 |
+
|
| 47 |
+
else:
|
| 48 |
+
def get_object_traceback(_obj):
|
| 49 |
+
return None
|
| 50 |
+
|
| 51 |
+
def tracemalloc(init):
|
| 52 |
+
return init
|
| 53 |
+
|
| 54 |
+
from gevent._compat import fsencode
|
| 55 |
+
|
| 56 |
+
from gevent._ffi import _dbg # pylint:disable=unused-import
|
| 57 |
+
from gevent._ffi import GEVENT_DEBUG_LEVEL
|
| 58 |
+
from gevent._ffi import DEBUG
|
| 59 |
+
from gevent._ffi.loop import GEVENT_CORE_EVENTS
|
| 60 |
+
from gevent._ffi.loop import _NOARGS
|
| 61 |
+
|
| 62 |
+
ALLOW_WATCHER_DEL = GEVENT_DEBUG_LEVEL >= DEBUG
|
| 63 |
+
|
| 64 |
+
__all__ = [
|
| 65 |
+
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
try:
|
| 69 |
+
ResourceWarning # pylint:disable=used-before-assignment
|
| 70 |
+
except NameError:
|
| 71 |
+
class ResourceWarning(Warning):
|
| 72 |
+
"Python 2 fallback"
|
| 73 |
+
|
| 74 |
+
class _NoWatcherResult(int):
|
| 75 |
+
|
| 76 |
+
def __repr__(self):
|
| 77 |
+
return "<NoWatcher>"
|
| 78 |
+
|
| 79 |
+
_NoWatcherResult = _NoWatcherResult(0)
|
| 80 |
+
|
| 81 |
+
def events_to_str(event_field, all_events):
|
| 82 |
+
result = []
|
| 83 |
+
for (flag, string) in all_events:
|
| 84 |
+
c_flag = flag
|
| 85 |
+
if event_field & c_flag:
|
| 86 |
+
result.append(string)
|
| 87 |
+
event_field &= (~c_flag)
|
| 88 |
+
if not event_field:
|
| 89 |
+
break
|
| 90 |
+
if event_field:
|
| 91 |
+
result.append(hex(event_field))
|
| 92 |
+
return '|'.join(result)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def not_while_active(func):
|
| 96 |
+
@functools.wraps(func)
|
| 97 |
+
def nw(self, *args, **kwargs):
|
| 98 |
+
if self.active:
|
| 99 |
+
raise ValueError("not while active")
|
| 100 |
+
func(self, *args, **kwargs)
|
| 101 |
+
return nw
|
| 102 |
+
|
| 103 |
+
def only_if_watcher(func):
|
| 104 |
+
@functools.wraps(func)
|
| 105 |
+
def if_w(self):
|
| 106 |
+
if self._watcher:
|
| 107 |
+
return func(self)
|
| 108 |
+
return _NoWatcherResult
|
| 109 |
+
return if_w
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
class AbstractWatcherType(type):
|
| 113 |
+
"""
|
| 114 |
+
Base metaclass for watchers.
|
| 115 |
+
|
| 116 |
+
To use, you will:
|
| 117 |
+
|
| 118 |
+
- subclass the watcher class defined from this type.
|
| 119 |
+
- optionally subclass this type
|
| 120 |
+
"""
|
| 121 |
+
# pylint:disable=bad-mcs-classmethod-argument
|
| 122 |
+
|
| 123 |
+
_FFI = None
|
| 124 |
+
_LIB = None
|
| 125 |
+
|
| 126 |
+
def __new__(cls, name, bases, cls_dict):
|
| 127 |
+
if name != 'watcher' and not cls_dict.get('_watcher_skip_ffi'):
|
| 128 |
+
cls._fill_watcher(name, bases, cls_dict)
|
| 129 |
+
if '__del__' in cls_dict and not ALLOW_WATCHER_DEL: # pragma: no cover
|
| 130 |
+
raise TypeError("CFFI watchers are not allowed to have __del__")
|
| 131 |
+
return type.__new__(cls, name, bases, cls_dict)
|
| 132 |
+
|
| 133 |
+
@classmethod
|
| 134 |
+
def _fill_watcher(cls, name, bases, cls_dict):
|
| 135 |
+
# TODO: refactor smaller
|
| 136 |
+
# pylint:disable=too-many-locals
|
| 137 |
+
if name.endswith('_'):
|
| 138 |
+
# Strip trailing _ added to avoid keyword duplications
|
| 139 |
+
# e.g., async_
|
| 140 |
+
name = name[:-1]
|
| 141 |
+
|
| 142 |
+
def _mro_get(attr, bases, error=True):
|
| 143 |
+
for b in bases:
|
| 144 |
+
try:
|
| 145 |
+
return getattr(b, attr)
|
| 146 |
+
except AttributeError:
|
| 147 |
+
continue
|
| 148 |
+
if error: # pragma: no cover
|
| 149 |
+
raise AttributeError(attr)
|
| 150 |
+
_watcher_prefix = cls_dict.get('_watcher_prefix') or _mro_get('_watcher_prefix', bases)
|
| 151 |
+
|
| 152 |
+
if '_watcher_type' not in cls_dict:
|
| 153 |
+
watcher_type = _watcher_prefix + '_' + name
|
| 154 |
+
cls_dict['_watcher_type'] = watcher_type
|
| 155 |
+
elif not cls_dict['_watcher_type'].startswith(_watcher_prefix):
|
| 156 |
+
watcher_type = _watcher_prefix + '_' + cls_dict['_watcher_type']
|
| 157 |
+
cls_dict['_watcher_type'] = watcher_type
|
| 158 |
+
|
| 159 |
+
active_name = _watcher_prefix + '_is_active'
|
| 160 |
+
|
| 161 |
+
def _watcher_is_active(self):
|
| 162 |
+
return getattr(self._LIB, active_name)
|
| 163 |
+
|
| 164 |
+
LazyOnClass.lazy(cls_dict, _watcher_is_active)
|
| 165 |
+
|
| 166 |
+
watcher_struct_name = cls_dict.get('_watcher_struct_name')
|
| 167 |
+
if not watcher_struct_name:
|
| 168 |
+
watcher_struct_pattern = (cls_dict.get('_watcher_struct_pattern')
|
| 169 |
+
or _mro_get('_watcher_struct_pattern', bases, False)
|
| 170 |
+
or 'struct %s')
|
| 171 |
+
watcher_struct_name = watcher_struct_pattern % (watcher_type,)
|
| 172 |
+
|
| 173 |
+
def _watcher_struct_pointer_type(self):
|
| 174 |
+
return self._FFI.typeof(watcher_struct_name + ' *')
|
| 175 |
+
|
| 176 |
+
LazyOnClass.lazy(cls_dict, _watcher_struct_pointer_type)
|
| 177 |
+
|
| 178 |
+
callback_name = (cls_dict.get('_watcher_callback_name')
|
| 179 |
+
or _mro_get('_watcher_callback_name', bases, False)
|
| 180 |
+
or '_gevent_generic_callback')
|
| 181 |
+
|
| 182 |
+
def _watcher_callback(self):
|
| 183 |
+
return self._FFI.addressof(self._LIB, callback_name)
|
| 184 |
+
|
| 185 |
+
LazyOnClass.lazy(cls_dict, _watcher_callback)
|
| 186 |
+
|
| 187 |
+
def _make_meth(name, watcher_name):
|
| 188 |
+
def meth(self):
|
| 189 |
+
lib_name = self._watcher_type + '_' + name
|
| 190 |
+
return getattr(self._LIB, lib_name)
|
| 191 |
+
meth.__name__ = watcher_name
|
| 192 |
+
return meth
|
| 193 |
+
|
| 194 |
+
for meth_name in 'start', 'stop', 'init':
|
| 195 |
+
watcher_name = '_watcher' + '_' + meth_name
|
| 196 |
+
if watcher_name not in cls_dict:
|
| 197 |
+
LazyOnClass.lazy(cls_dict, _make_meth(meth_name, watcher_name))
|
| 198 |
+
|
| 199 |
+
def new_handle(cls, obj):
|
| 200 |
+
return cls._FFI.new_handle(obj)
|
| 201 |
+
|
| 202 |
+
def new(cls, kind):
|
| 203 |
+
return cls._FFI.new(kind)
|
| 204 |
+
|
| 205 |
+
class watcher(object):
|
| 206 |
+
|
| 207 |
+
_callback = None
|
| 208 |
+
_args = None
|
| 209 |
+
_watcher = None
|
| 210 |
+
# self._handle has a reference to self, keeping it alive.
|
| 211 |
+
# We must keep self._handle alive for ffi.from_handle() to be
|
| 212 |
+
# able to work. We only fill this in when we are started,
|
| 213 |
+
# and when we are stopped we destroy it.
|
| 214 |
+
# NOTE: This is a GC cycle, so we keep it around for as short
|
| 215 |
+
# as possible.
|
| 216 |
+
_handle = None
|
| 217 |
+
|
| 218 |
+
@tracemalloc
|
| 219 |
+
def __init__(self, _loop, ref=True, priority=None, args=_NOARGS):
|
| 220 |
+
self.loop = _loop
|
| 221 |
+
self.__init_priority = priority
|
| 222 |
+
self.__init_args = args
|
| 223 |
+
self.__init_ref = ref
|
| 224 |
+
self._watcher_full_init()
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def _watcher_full_init(self):
|
| 228 |
+
priority = self.__init_priority
|
| 229 |
+
ref = self.__init_ref
|
| 230 |
+
args = self.__init_args
|
| 231 |
+
|
| 232 |
+
self._watcher_create(ref)
|
| 233 |
+
|
| 234 |
+
if priority is not None:
|
| 235 |
+
self._watcher_ffi_set_priority(priority)
|
| 236 |
+
|
| 237 |
+
try:
|
| 238 |
+
self._watcher_ffi_init(args)
|
| 239 |
+
except:
|
| 240 |
+
# Let these be GC'd immediately.
|
| 241 |
+
# If we keep them around to when *we* are gc'd,
|
| 242 |
+
# they're probably invalid, meaning any native calls
|
| 243 |
+
# we do then to close() them are likely to fail
|
| 244 |
+
self._watcher = None
|
| 245 |
+
raise
|
| 246 |
+
self._watcher_ffi_set_init_ref(ref)
|
| 247 |
+
|
| 248 |
+
@classmethod
|
| 249 |
+
def _watcher_ffi_close(cls, ffi_watcher):
|
| 250 |
+
pass
|
| 251 |
+
|
| 252 |
+
def _watcher_create(self, ref): # pylint:disable=unused-argument
|
| 253 |
+
self._watcher = self._watcher_new()
|
| 254 |
+
|
| 255 |
+
def _watcher_new(self):
|
| 256 |
+
return type(self).new(self._watcher_struct_pointer_type) # pylint:disable=no-member
|
| 257 |
+
|
| 258 |
+
def _watcher_ffi_set_init_ref(self, ref):
|
| 259 |
+
pass
|
| 260 |
+
|
| 261 |
+
def _watcher_ffi_set_priority(self, priority):
|
| 262 |
+
pass
|
| 263 |
+
|
| 264 |
+
def _watcher_ffi_init(self, args):
|
| 265 |
+
raise NotImplementedError()
|
| 266 |
+
|
| 267 |
+
def _watcher_ffi_start(self):
|
| 268 |
+
raise NotImplementedError()
|
| 269 |
+
|
| 270 |
+
def _watcher_ffi_stop(self):
|
| 271 |
+
self._watcher_stop(self.loop.ptr, self._watcher)
|
| 272 |
+
|
| 273 |
+
def _watcher_ffi_ref(self):
|
| 274 |
+
raise NotImplementedError()
|
| 275 |
+
|
| 276 |
+
def _watcher_ffi_unref(self):
|
| 277 |
+
raise NotImplementedError()
|
| 278 |
+
|
| 279 |
+
def _watcher_ffi_start_unref(self):
|
| 280 |
+
# While a watcher is active, we don't keep it
|
| 281 |
+
# referenced. This allows a timer, for example, to be started,
|
| 282 |
+
# and still allow the loop to end if there is nothing
|
| 283 |
+
# else to do. see test__order.TestSleep0 for one example.
|
| 284 |
+
self._watcher_ffi_unref()
|
| 285 |
+
|
| 286 |
+
def _watcher_ffi_stop_ref(self):
|
| 287 |
+
self._watcher_ffi_ref()
|
| 288 |
+
|
| 289 |
+
# A string identifying the type of libev object we watch, e.g., 'ev_io'
|
| 290 |
+
# This should be a class attribute.
|
| 291 |
+
_watcher_type = None
|
| 292 |
+
# A class attribute that is the callback on the libev object that init's the C struct,
|
| 293 |
+
# e.g., libev.ev_io_init. If None, will be set by _init_subclasses.
|
| 294 |
+
_watcher_init = None
|
| 295 |
+
# A class attribute that is the callback on the libev object that starts the C watcher,
|
| 296 |
+
# e.g., libev.ev_io_start. If None, will be set by _init_subclasses.
|
| 297 |
+
_watcher_start = None
|
| 298 |
+
# A class attribute that is the callback on the libev object that stops the C watcher,
|
| 299 |
+
# e.g., libev.ev_io_stop. If None, will be set by _init_subclasses.
|
| 300 |
+
_watcher_stop = None
|
| 301 |
+
# A cffi ctype object identifying the struct pointer we create.
|
| 302 |
+
# This is a class attribute set based on the _watcher_type
|
| 303 |
+
_watcher_struct_pointer_type = None
|
| 304 |
+
# The attribute of the libev object identifying the custom
|
| 305 |
+
# callback function for this type of watcher. This is a class
|
| 306 |
+
# attribute set based on the _watcher_type in _init_subclasses.
|
| 307 |
+
_watcher_callback = None
|
| 308 |
+
_watcher_is_active = None
|
| 309 |
+
|
| 310 |
+
def close(self):
|
| 311 |
+
if self._watcher is None:
|
| 312 |
+
return
|
| 313 |
+
|
| 314 |
+
self.stop()
|
| 315 |
+
_watcher = self._watcher
|
| 316 |
+
self._watcher = None
|
| 317 |
+
self._watcher_set_data(_watcher, self._FFI.NULL) # pylint: disable=no-member
|
| 318 |
+
self._watcher_ffi_close(_watcher)
|
| 319 |
+
self.loop = None
|
| 320 |
+
|
| 321 |
+
def _watcher_set_data(self, the_watcher, data):
|
| 322 |
+
# This abstraction exists for the sole benefit of
|
| 323 |
+
# libuv.watcher.stat, which "subclasses" uv_handle_t.
|
| 324 |
+
# Can we do something to avoid this extra function call?
|
| 325 |
+
the_watcher.data = data
|
| 326 |
+
return data
|
| 327 |
+
|
| 328 |
+
def __enter__(self):
|
| 329 |
+
return self
|
| 330 |
+
|
| 331 |
+
def __exit__(self, t, v, tb):
|
| 332 |
+
self.close()
|
| 333 |
+
|
| 334 |
+
if ALLOW_WATCHER_DEL:
|
| 335 |
+
def __del__(self):
|
| 336 |
+
if self._watcher:
|
| 337 |
+
tb = get_object_traceback(self)
|
| 338 |
+
tb_msg = ''
|
| 339 |
+
if tb is not None:
|
| 340 |
+
tb_msg = '\n'.join(tb.format())
|
| 341 |
+
tb_msg = '\nTraceback:\n' + tb_msg
|
| 342 |
+
warnings.warn("Failed to close watcher %r%s" % (self, tb_msg),
|
| 343 |
+
ResourceWarning)
|
| 344 |
+
|
| 345 |
+
# may fail if __init__ did; will be harmlessly printed
|
| 346 |
+
self.close()
|
| 347 |
+
|
| 348 |
+
__in_repr = False
|
| 349 |
+
|
| 350 |
+
def __repr__(self):
|
| 351 |
+
basic = "<%s at 0x%x" % (self.__class__.__name__, id(self))
|
| 352 |
+
if self.__in_repr:
|
| 353 |
+
return basic + '>'
|
| 354 |
+
# Running child watchers have been seen to have a
|
| 355 |
+
# recursive repr in ``self.args``, thanks to ``gevent.os.fork_and_watch``
|
| 356 |
+
# passing the watcher as an argument to its callback.
|
| 357 |
+
self.__in_repr = True
|
| 358 |
+
try:
|
| 359 |
+
result = '%s%s' % (basic, self._format())
|
| 360 |
+
if self.pending:
|
| 361 |
+
result += " pending"
|
| 362 |
+
if self.callback is not None:
|
| 363 |
+
fself = getattr(self.callback, '__self__', None)
|
| 364 |
+
if fself is self:
|
| 365 |
+
result += " callback=<bound method %s of self>" % (self.callback.__name__)
|
| 366 |
+
else:
|
| 367 |
+
result += " callback=%r" % (self.callback, )
|
| 368 |
+
if self.args is not None:
|
| 369 |
+
result += " args=%r" % (self.args, )
|
| 370 |
+
if self.callback is None and self.args is None:
|
| 371 |
+
result += " stopped"
|
| 372 |
+
result += " watcher=%s" % (self._watcher)
|
| 373 |
+
result += " handle=%s" % (self._watcher_handle)
|
| 374 |
+
result += " ref=%s" % (self.ref)
|
| 375 |
+
return result + ">"
|
| 376 |
+
finally:
|
| 377 |
+
self.__in_repr = False
|
| 378 |
+
|
| 379 |
+
@property
|
| 380 |
+
def _watcher_handle(self):
|
| 381 |
+
if self._watcher:
|
| 382 |
+
return self._watcher.data
|
| 383 |
+
|
| 384 |
+
def _format(self):
|
| 385 |
+
return ''
|
| 386 |
+
|
| 387 |
+
@property
|
| 388 |
+
def ref(self):
|
| 389 |
+
raise NotImplementedError()
|
| 390 |
+
|
| 391 |
+
def _get_callback(self):
|
| 392 |
+
return self._callback if '_callback' in self.__dict__ else None
|
| 393 |
+
|
| 394 |
+
def _set_callback(self, cb):
|
| 395 |
+
if not callable(cb) and cb is not None:
|
| 396 |
+
raise TypeError("Expected callable, not %r" % (cb, ))
|
| 397 |
+
if cb is None:
|
| 398 |
+
if '_callback' in self.__dict__:
|
| 399 |
+
del self._callback
|
| 400 |
+
else:
|
| 401 |
+
self._callback = cb
|
| 402 |
+
callback = property(_get_callback, _set_callback)
|
| 403 |
+
|
| 404 |
+
def _get_args(self):
|
| 405 |
+
return self._args
|
| 406 |
+
|
| 407 |
+
def _set_args(self, args):
|
| 408 |
+
if not isinstance(args, tuple) and args is not None:
|
| 409 |
+
raise TypeError("args must be a tuple or None")
|
| 410 |
+
if args is None:
|
| 411 |
+
if '_args' in self.__dict__:
|
| 412 |
+
del self._args
|
| 413 |
+
else:
|
| 414 |
+
self._args = args
|
| 415 |
+
|
| 416 |
+
args = property(_get_args, _set_args)
|
| 417 |
+
|
| 418 |
+
def start(self, callback, *args):
|
| 419 |
+
if callback is None:
|
| 420 |
+
raise TypeError('callback must be callable, not None')
|
| 421 |
+
self.callback = callback
|
| 422 |
+
self.args = args or _NOARGS
|
| 423 |
+
self.loop._keepaliveset.add(self)
|
| 424 |
+
self._handle = self._watcher_set_data(self._watcher, type(self).new_handle(self)) # pylint:disable=no-member
|
| 425 |
+
self._watcher_ffi_start()
|
| 426 |
+
self._watcher_ffi_start_unref()
|
| 427 |
+
|
| 428 |
+
def stop(self):
|
| 429 |
+
if self.callback is None:
|
| 430 |
+
assert self.loop is None or self not in self.loop._keepaliveset
|
| 431 |
+
return
|
| 432 |
+
self.callback = None
|
| 433 |
+
# Only after setting the signal to make this idempotent do
|
| 434 |
+
# we move ahead.
|
| 435 |
+
self._watcher_ffi_stop_ref()
|
| 436 |
+
self._watcher_ffi_stop()
|
| 437 |
+
self.loop._keepaliveset.discard(self)
|
| 438 |
+
self._handle = None
|
| 439 |
+
self._watcher_set_data(self._watcher, self._FFI.NULL) # pylint:disable=no-member
|
| 440 |
+
|
| 441 |
+
self.args = None
|
| 442 |
+
|
| 443 |
+
def _get_priority(self):
|
| 444 |
+
return None
|
| 445 |
+
|
| 446 |
+
@not_while_active
|
| 447 |
+
def _set_priority(self, priority):
|
| 448 |
+
pass
|
| 449 |
+
|
| 450 |
+
priority = property(_get_priority, _set_priority)
|
| 451 |
+
|
| 452 |
+
|
| 453 |
+
@property
|
| 454 |
+
def active(self):
|
| 455 |
+
if self._watcher is not None and self._watcher_is_active(self._watcher):
|
| 456 |
+
return True
|
| 457 |
+
return False
|
| 458 |
+
|
| 459 |
+
@property
|
| 460 |
+
def pending(self):
|
| 461 |
+
return False
|
| 462 |
+
|
| 463 |
+
watcher = AbstractWatcherType('watcher', (object,), dict(watcher.__dict__))
|
| 464 |
+
|
| 465 |
+
class IoMixin(object):
|
| 466 |
+
|
| 467 |
+
EVENT_MASK = 0
|
| 468 |
+
|
| 469 |
+
def __init__(self, loop, fd, events, ref=True, priority=None, _args=None):
|
| 470 |
+
# Win32 only works with sockets, and only when we use libuv, because
|
| 471 |
+
# we don't use _open_osfhandle. See libuv/watchers.py:io for a description.
|
| 472 |
+
if fd < 0:
|
| 473 |
+
raise ValueError('fd must be non-negative: %r' % fd)
|
| 474 |
+
if events & ~self.EVENT_MASK:
|
| 475 |
+
raise ValueError('illegal event mask: %r' % events)
|
| 476 |
+
self._fd = fd
|
| 477 |
+
super(IoMixin, self).__init__(loop, ref=ref, priority=priority,
|
| 478 |
+
args=_args or (fd, events))
|
| 479 |
+
|
| 480 |
+
def start(self, callback, *args, **kwargs):
|
| 481 |
+
args = args or _NOARGS
|
| 482 |
+
if kwargs.get('pass_events'):
|
| 483 |
+
args = (GEVENT_CORE_EVENTS, ) + args
|
| 484 |
+
super(IoMixin, self).start(callback, *args)
|
| 485 |
+
|
| 486 |
+
def _format(self):
|
| 487 |
+
return ' fd=%d' % self._fd
|
| 488 |
+
|
| 489 |
+
class TimerMixin(object):
|
| 490 |
+
_watcher_type = 'timer'
|
| 491 |
+
|
| 492 |
+
def __init__(self, loop, after=0.0, repeat=0.0, ref=True, priority=None):
|
| 493 |
+
if repeat < 0.0:
|
| 494 |
+
raise ValueError("repeat must be positive or zero: %r" % repeat)
|
| 495 |
+
self._after = after
|
| 496 |
+
self._repeat = repeat
|
| 497 |
+
super(TimerMixin, self).__init__(loop, ref=ref, priority=priority, args=(after, repeat))
|
| 498 |
+
|
| 499 |
+
def start(self, callback, *args, **kw):
|
| 500 |
+
update = kw.get("update", self.loop.starting_timer_may_update_loop_time)
|
| 501 |
+
if update:
|
| 502 |
+
# Quoth the libev doc: "This is a costly operation and is
|
| 503 |
+
# usually done automatically within ev_run(). This
|
| 504 |
+
# function is rarely useful, but when some event callback
|
| 505 |
+
# runs for a very long time without entering the event
|
| 506 |
+
# loop, updating libev's idea of the current time is a
|
| 507 |
+
# good idea."
|
| 508 |
+
|
| 509 |
+
# 1.3 changed the default for this to False *unless* the loop is
|
| 510 |
+
# running a callback; see libuv for details. Note that
|
| 511 |
+
# starting Timeout objects still sets this to true.
|
| 512 |
+
|
| 513 |
+
self.loop.update_now()
|
| 514 |
+
super(TimerMixin, self).start(callback, *args)
|
| 515 |
+
|
| 516 |
+
def again(self, callback, *args, **kw):
|
| 517 |
+
raise NotImplementedError()
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
class SignalMixin(object):
|
| 521 |
+
_watcher_type = 'signal'
|
| 522 |
+
|
| 523 |
+
def __init__(self, loop, signalnum, ref=True, priority=None):
|
| 524 |
+
if signalnum < 1 or signalnum >= signalmodule.NSIG:
|
| 525 |
+
raise ValueError('illegal signal number: %r' % signalnum)
|
| 526 |
+
# still possible to crash on one of libev's asserts:
|
| 527 |
+
# 1) "libev: ev_signal_start called with illegal signal number"
|
| 528 |
+
# EV_NSIG might be different from signal.NSIG on some platforms
|
| 529 |
+
# 2) "libev: a signal must not be attached to two different loops"
|
| 530 |
+
# we probably could check that in LIBEV_EMBED mode, but not in general
|
| 531 |
+
self._signalnum = signalnum
|
| 532 |
+
super(SignalMixin, self).__init__(loop, ref=ref, priority=priority, args=(signalnum, ))
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class IdleMixin(object):
|
| 536 |
+
_watcher_type = 'idle'
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
class PrepareMixin(object):
|
| 540 |
+
_watcher_type = 'prepare'
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class CheckMixin(object):
|
| 544 |
+
_watcher_type = 'check'
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
class ForkMixin(object):
|
| 548 |
+
_watcher_type = 'fork'
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
class AsyncMixin(object):
|
| 552 |
+
_watcher_type = 'async'
|
| 553 |
+
|
| 554 |
+
def send(self):
|
| 555 |
+
raise NotImplementedError()
|
| 556 |
+
|
| 557 |
+
def send_ignoring_arg(self, _ignored):
|
| 558 |
+
"""
|
| 559 |
+
Calling compatibility with ``greenlet.switch(arg)``
|
| 560 |
+
as used by waiters that have ``rawlink``.
|
| 561 |
+
|
| 562 |
+
This is an advanced method, not usually needed.
|
| 563 |
+
"""
|
| 564 |
+
return self.send()
|
| 565 |
+
|
| 566 |
+
@property
|
| 567 |
+
def pending(self):
|
| 568 |
+
raise NotImplementedError()
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
class ChildMixin(object):
|
| 572 |
+
|
| 573 |
+
# hack for libuv which doesn't extend watcher
|
| 574 |
+
_CALL_SUPER_INIT = True
|
| 575 |
+
|
| 576 |
+
def __init__(self, loop, pid, trace=0, ref=True):
|
| 577 |
+
if not loop.default:
|
| 578 |
+
raise TypeError('child watchers are only available on the default loop')
|
| 579 |
+
loop.install_sigchld()
|
| 580 |
+
self._pid = pid
|
| 581 |
+
if self._CALL_SUPER_INIT:
|
| 582 |
+
super(ChildMixin, self).__init__(loop, ref=ref, args=(pid, trace))
|
| 583 |
+
|
| 584 |
+
def _format(self):
|
| 585 |
+
return ' pid=%r rstatus=%r' % (self.pid, self.rstatus)
|
| 586 |
+
|
| 587 |
+
@property
|
| 588 |
+
def pid(self):
|
| 589 |
+
return self._pid
|
| 590 |
+
|
| 591 |
+
@property
|
| 592 |
+
def rpid(self):
|
| 593 |
+
# The received pid, the result of the waitpid() call.
|
| 594 |
+
return self._rpid
|
| 595 |
+
|
| 596 |
+
_rpid = None
|
| 597 |
+
_rstatus = 0
|
| 598 |
+
|
| 599 |
+
@property
|
| 600 |
+
def rstatus(self):
|
| 601 |
+
return self._rstatus
|
| 602 |
+
|
| 603 |
+
class StatMixin(object):
|
| 604 |
+
|
| 605 |
+
@staticmethod
|
| 606 |
+
def _encode_path(path):
|
| 607 |
+
return fsencode(path)
|
| 608 |
+
|
| 609 |
+
def __init__(self, _loop, path, interval=0.0, ref=True, priority=None):
|
| 610 |
+
# Store the encoded path in the same attribute that corecext does
|
| 611 |
+
self._paths = self._encode_path(path)
|
| 612 |
+
|
| 613 |
+
# Keep the original path to avoid re-encoding, especially on Python 3
|
| 614 |
+
self._path = path
|
| 615 |
+
|
| 616 |
+
# Although CFFI would automatically convert a bytes object into a char* when
|
| 617 |
+
# calling ev_stat_init(..., char*, ...), on PyPy the char* pointer is not
|
| 618 |
+
# guaranteed to live past the function call. On CPython, only with a constant/interned
|
| 619 |
+
# bytes object is the pointer guaranteed to last path the function call. (And since
|
| 620 |
+
# Python 3 is pretty much guaranteed to produce a newly-encoded bytes object above, thats
|
| 621 |
+
# rarely the case). Therefore, we must keep a reference to the produced cdata object
|
| 622 |
+
# so that the struct ev_stat_watcher's `path` pointer doesn't become invalid/deallocated
|
| 623 |
+
self._cpath = self._FFI.new('char[]', self._paths)
|
| 624 |
+
|
| 625 |
+
self._interval = interval
|
| 626 |
+
super(StatMixin, self).__init__(_loop, ref=ref, priority=priority,
|
| 627 |
+
args=(self._cpath,
|
| 628 |
+
interval))
|
| 629 |
+
|
| 630 |
+
@property
|
| 631 |
+
def path(self):
|
| 632 |
+
return self._path
|
| 633 |
+
|
| 634 |
+
@property
|
| 635 |
+
def attr(self):
|
| 636 |
+
raise NotImplementedError
|
| 637 |
+
|
| 638 |
+
@property
|
| 639 |
+
def prev(self):
|
| 640 |
+
raise NotImplementedError
|
| 641 |
+
|
| 642 |
+
@property
|
| 643 |
+
def interval(self):
|
| 644 |
+
return self._interval
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/core.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2015 Denis Bilenko and gevent contributors. See LICENSE for details.
|
| 2 |
+
"""
|
| 3 |
+
Deprecated; this does not reflect all the possible options
|
| 4 |
+
and its interface varies.
|
| 5 |
+
|
| 6 |
+
.. versionchanged:: 1.3a2
|
| 7 |
+
Deprecated.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import absolute_import
|
| 10 |
+
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
from gevent._config import config
|
| 14 |
+
from gevent._util import copy_globals
|
| 15 |
+
|
| 16 |
+
_core = sys.modules[config.loop.__module__]
|
| 17 |
+
|
| 18 |
+
copy_globals(_core, globals())
|
| 19 |
+
|
| 20 |
+
__all__ = _core.__all__ # pylint:disable=no-member
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/event.py
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2016 Denis Bilenko, gevent contributors. See LICENSE for details.
|
| 2 |
+
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False,infer_types=True
|
| 3 |
+
|
| 4 |
+
"""Basic synchronization primitives: Event and AsyncResult"""
|
| 5 |
+
from __future__ import print_function
|
| 6 |
+
|
| 7 |
+
from gevent._util import _NONE
|
| 8 |
+
from gevent._compat import reraise
|
| 9 |
+
from gevent._tblib import dump_traceback, load_traceback
|
| 10 |
+
|
| 11 |
+
from gevent.timeout import Timeout
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
'Event',
|
| 16 |
+
'AsyncResult',
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
def _get_linkable():
|
| 20 |
+
x = __import__('gevent._abstract_linkable')
|
| 21 |
+
return x._abstract_linkable.AbstractLinkable
|
| 22 |
+
locals()['AbstractLinkable'] = _get_linkable()
|
| 23 |
+
del _get_linkable
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Event(AbstractLinkable): # pylint:disable=undefined-variable
|
| 27 |
+
"""
|
| 28 |
+
A synchronization primitive that allows one greenlet to wake up
|
| 29 |
+
one or more others. It has the same interface as
|
| 30 |
+
:class:`threading.Event` but works across greenlets.
|
| 31 |
+
|
| 32 |
+
.. important::
|
| 33 |
+
This object is for communicating among greenlets within the
|
| 34 |
+
same thread *only*! Do not try to use it to communicate across threads.
|
| 35 |
+
|
| 36 |
+
An event object manages an internal flag that can be set to true
|
| 37 |
+
with the :meth:`set` method and reset to false with the
|
| 38 |
+
:meth:`clear` method. The :meth:`wait` method blocks until the
|
| 39 |
+
flag is true; as soon as the flag is set to true, all greenlets
|
| 40 |
+
that are currently blocked in a call to :meth:`wait` will be scheduled
|
| 41 |
+
to awaken.
|
| 42 |
+
|
| 43 |
+
Note that the flag may be cleared and set many times before
|
| 44 |
+
any individual greenlet runs; all the greenlet can know for sure is that the
|
| 45 |
+
flag was set *at least once* while it was waiting.
|
| 46 |
+
If the greenlet cares whether the flag is still
|
| 47 |
+
set, it must check with :meth:`ready` and possibly call back into
|
| 48 |
+
:meth:`wait` again.
|
| 49 |
+
|
| 50 |
+
.. note::
|
| 51 |
+
|
| 52 |
+
The exact order and timing in which waiting greenlets are awakened is not determined.
|
| 53 |
+
|
| 54 |
+
Once the event is set, other greenlets may run before any waiting greenlets
|
| 55 |
+
are awakened.
|
| 56 |
+
|
| 57 |
+
While the code here will awaken greenlets in the order in which they
|
| 58 |
+
waited, each such greenlet that runs may in turn cause other greenlets
|
| 59 |
+
to run.
|
| 60 |
+
|
| 61 |
+
These details may change in the future.
|
| 62 |
+
|
| 63 |
+
.. versionchanged:: 1.5a3
|
| 64 |
+
|
| 65 |
+
Waiting greenlets are now awakened in
|
| 66 |
+
the order in which they waited.
|
| 67 |
+
|
| 68 |
+
.. versionchanged:: 1.5a3
|
| 69 |
+
|
| 70 |
+
The low-level ``rawlink`` method (most users won't use this) now
|
| 71 |
+
automatically unlinks waiters before calling them.
|
| 72 |
+
|
| 73 |
+
.. versionchanged:: 20.5.1
|
| 74 |
+
|
| 75 |
+
Callers to ``wait`` that find the event already set will now run
|
| 76 |
+
after any other waiters that had to block. See :issue:`1520`.
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
__slots__ = ('_flag',)
|
| 80 |
+
|
| 81 |
+
def __init__(self):
|
| 82 |
+
super(Event, self).__init__()
|
| 83 |
+
self._flag = False
|
| 84 |
+
|
| 85 |
+
def __str__(self):
|
| 86 |
+
return '<%s.%s %s _links[%s]>' % (
|
| 87 |
+
self.__class__.__module__,
|
| 88 |
+
self.__class__.__name__,
|
| 89 |
+
'set' if self._flag else 'clear',
|
| 90 |
+
self.linkcount()
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def is_set(self):
|
| 94 |
+
"""Return true if and only if the internal flag is true."""
|
| 95 |
+
return self._flag
|
| 96 |
+
|
| 97 |
+
def isSet(self):
|
| 98 |
+
# makes it a better drop-in replacement for threading.Event
|
| 99 |
+
return self._flag
|
| 100 |
+
|
| 101 |
+
def ready(self):
|
| 102 |
+
# makes it compatible with AsyncResult and Greenlet (for
|
| 103 |
+
# example in wait())
|
| 104 |
+
return self._flag
|
| 105 |
+
|
| 106 |
+
def set(self):
|
| 107 |
+
"""
|
| 108 |
+
Set the internal flag to true.
|
| 109 |
+
|
| 110 |
+
All greenlets waiting for it to become true are awakened in
|
| 111 |
+
some order at some time in the future. Greenlets that call
|
| 112 |
+
:meth:`wait` once the flag is true will not block at all
|
| 113 |
+
(until :meth:`clear` is called).
|
| 114 |
+
"""
|
| 115 |
+
self._flag = True
|
| 116 |
+
self._check_and_notify()
|
| 117 |
+
|
| 118 |
+
def clear(self):
|
| 119 |
+
"""
|
| 120 |
+
Reset the internal flag to false.
|
| 121 |
+
|
| 122 |
+
Subsequently, threads calling :meth:`wait` will block until
|
| 123 |
+
:meth:`set` is called to set the internal flag to true again.
|
| 124 |
+
"""
|
| 125 |
+
self._flag = False
|
| 126 |
+
|
| 127 |
+
def _wait_return_value(self, waited, wait_success):
|
| 128 |
+
# To avoid the race condition outlined in http://bugs.python.org/issue13502,
|
| 129 |
+
# if we had to wait, then we need to return whether or not
|
| 130 |
+
# the condition got changed. Otherwise we simply echo
|
| 131 |
+
# the current state of the flag (which should be true)
|
| 132 |
+
if not waited:
|
| 133 |
+
flag = self._flag
|
| 134 |
+
assert flag, "if we didn't wait we should already be set"
|
| 135 |
+
return flag
|
| 136 |
+
|
| 137 |
+
return wait_success
|
| 138 |
+
|
| 139 |
+
def wait(self, timeout=None):
|
| 140 |
+
"""
|
| 141 |
+
Block until this object is :meth:`ready`.
|
| 142 |
+
|
| 143 |
+
If the internal flag is true on entry, return immediately. Otherwise,
|
| 144 |
+
block until another thread (greenlet) calls :meth:`set` to set the flag to true,
|
| 145 |
+
or until the optional *timeout* expires.
|
| 146 |
+
|
| 147 |
+
When the *timeout* argument is present and not ``None``, it should be a
|
| 148 |
+
floating point number specifying a timeout for the operation in seconds
|
| 149 |
+
(or fractions thereof).
|
| 150 |
+
|
| 151 |
+
:return: This method returns true if and only if the internal flag has been set to
|
| 152 |
+
true, either before the wait call or after the wait starts, so it will
|
| 153 |
+
always return ``True`` except if a timeout is given and the operation
|
| 154 |
+
times out.
|
| 155 |
+
|
| 156 |
+
.. versionchanged:: 1.1
|
| 157 |
+
The return value represents the flag during the elapsed wait, not
|
| 158 |
+
just after it elapses. This solves a race condition if one greenlet
|
| 159 |
+
sets and then clears the flag without switching, while other greenlets
|
| 160 |
+
are waiting. When the waiters wake up, this will return True; previously,
|
| 161 |
+
they would still wake up, but the return value would be False. This is most
|
| 162 |
+
noticeable when the *timeout* is present.
|
| 163 |
+
"""
|
| 164 |
+
return self._wait(timeout)
|
| 165 |
+
|
| 166 |
+
def _reset_internal_locks(self): # pragma: no cover
|
| 167 |
+
# for compatibility with threading.Event
|
| 168 |
+
# Exception AttributeError: AttributeError("'Event' object has no attribute '_reset_internal_locks'",)
|
| 169 |
+
# in <module 'threading' from '/usr/lib/python2.7/threading.pyc'> ignored
|
| 170 |
+
pass
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
class AsyncResult(AbstractLinkable): # pylint:disable=undefined-variable
|
| 174 |
+
"""
|
| 175 |
+
A one-time event that stores a value or an exception.
|
| 176 |
+
|
| 177 |
+
Like :class:`Event` it wakes up all the waiters when :meth:`set`
|
| 178 |
+
or :meth:`set_exception` is called. Waiters may receive the passed
|
| 179 |
+
value or exception by calling :meth:`get` instead of :meth:`wait`.
|
| 180 |
+
An :class:`AsyncResult` instance cannot be reset.
|
| 181 |
+
|
| 182 |
+
.. important::
|
| 183 |
+
This object is for communicating among greenlets within the
|
| 184 |
+
same thread *only*! Do not try to use it to communicate across threads.
|
| 185 |
+
|
| 186 |
+
To pass a value call :meth:`set`. Calls to :meth:`get` (those that
|
| 187 |
+
are currently blocking as well as those made in the future) will
|
| 188 |
+
return the value::
|
| 189 |
+
|
| 190 |
+
>>> from gevent.event import AsyncResult
|
| 191 |
+
>>> result = AsyncResult()
|
| 192 |
+
>>> result.set(100)
|
| 193 |
+
>>> result.get()
|
| 194 |
+
100
|
| 195 |
+
|
| 196 |
+
To pass an exception call :meth:`set_exception`. This will cause
|
| 197 |
+
:meth:`get` to raise that exception::
|
| 198 |
+
|
| 199 |
+
>>> result = AsyncResult()
|
| 200 |
+
>>> result.set_exception(RuntimeError('failure'))
|
| 201 |
+
>>> result.get()
|
| 202 |
+
Traceback (most recent call last):
|
| 203 |
+
...
|
| 204 |
+
RuntimeError: failure
|
| 205 |
+
|
| 206 |
+
:class:`AsyncResult` implements :meth:`__call__` and thus can be
|
| 207 |
+
used as :meth:`link` target::
|
| 208 |
+
|
| 209 |
+
>>> import gevent
|
| 210 |
+
>>> result = AsyncResult()
|
| 211 |
+
>>> gevent.spawn(lambda : 1/0).link(result)
|
| 212 |
+
>>> try:
|
| 213 |
+
... result.get()
|
| 214 |
+
... except ZeroDivisionError:
|
| 215 |
+
... print('ZeroDivisionError')
|
| 216 |
+
ZeroDivisionError
|
| 217 |
+
|
| 218 |
+
.. note::
|
| 219 |
+
|
| 220 |
+
The order and timing in which waiting greenlets are awakened is not determined.
|
| 221 |
+
As an implementation note, in gevent 1.1 and 1.0, waiting greenlets are awakened in a
|
| 222 |
+
undetermined order sometime *after* the current greenlet yields to the event loop. Other greenlets
|
| 223 |
+
(those not waiting to be awakened) may run between the current greenlet yielding and
|
| 224 |
+
the waiting greenlets being awakened. These details may change in the future.
|
| 225 |
+
|
| 226 |
+
.. versionchanged:: 1.1
|
| 227 |
+
|
| 228 |
+
The exact order in which waiting greenlets
|
| 229 |
+
are awakened is not the same as in 1.0.
|
| 230 |
+
|
| 231 |
+
.. versionchanged:: 1.1
|
| 232 |
+
|
| 233 |
+
Callbacks :meth:`linked <rawlink>` to this object are required to
|
| 234 |
+
be hashable, and duplicates are merged.
|
| 235 |
+
|
| 236 |
+
.. versionchanged:: 1.5a3
|
| 237 |
+
|
| 238 |
+
Waiting greenlets are now awakened in the order in which they
|
| 239 |
+
waited.
|
| 240 |
+
|
| 241 |
+
.. versionchanged:: 1.5a3
|
| 242 |
+
|
| 243 |
+
The low-level ``rawlink`` method
|
| 244 |
+
(most users won't use this) now automatically unlinks waiters
|
| 245 |
+
before calling them.
|
| 246 |
+
"""
|
| 247 |
+
|
| 248 |
+
__slots__ = ('_value', '_exc_info', '_imap_task_index')
|
| 249 |
+
|
| 250 |
+
def __init__(self):
|
| 251 |
+
super(AsyncResult, self).__init__()
|
| 252 |
+
self._value = _NONE
|
| 253 |
+
self._exc_info = ()
|
| 254 |
+
|
| 255 |
+
@property
|
| 256 |
+
def _exception(self):
|
| 257 |
+
return self._exc_info[1] if self._exc_info else _NONE
|
| 258 |
+
|
| 259 |
+
@property
|
| 260 |
+
def value(self):
|
| 261 |
+
"""
|
| 262 |
+
Holds the value passed to :meth:`set` if :meth:`set` was called. Otherwise,
|
| 263 |
+
``None``
|
| 264 |
+
"""
|
| 265 |
+
return self._value if self._value is not _NONE else None
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def exc_info(self):
|
| 269 |
+
"""
|
| 270 |
+
The three-tuple of exception information if :meth:`set_exception` was called.
|
| 271 |
+
"""
|
| 272 |
+
if self._exc_info:
|
| 273 |
+
return (self._exc_info[0], self._exc_info[1], load_traceback(self._exc_info[2]))
|
| 274 |
+
return ()
|
| 275 |
+
|
| 276 |
+
def __str__(self):
|
| 277 |
+
result = '<%s ' % (self.__class__.__name__, )
|
| 278 |
+
if self.value is not None or self._exception is not _NONE:
|
| 279 |
+
result += 'value=%r ' % self.value
|
| 280 |
+
if self._exception is not None and self._exception is not _NONE:
|
| 281 |
+
result += 'exception=%r ' % self._exception
|
| 282 |
+
if self._exception is _NONE:
|
| 283 |
+
result += 'unset '
|
| 284 |
+
return result + ' _links[%s]>' % self.linkcount()
|
| 285 |
+
|
| 286 |
+
def ready(self):
|
| 287 |
+
"""Return true if and only if it holds a value or an exception"""
|
| 288 |
+
return self._exc_info or self._value is not _NONE
|
| 289 |
+
|
| 290 |
+
def successful(self):
|
| 291 |
+
"""Return true if and only if it is ready and holds a value"""
|
| 292 |
+
return self._value is not _NONE
|
| 293 |
+
|
| 294 |
+
@property
|
| 295 |
+
def exception(self):
|
| 296 |
+
"""Holds the exception instance passed to :meth:`set_exception` if :meth:`set_exception` was called.
|
| 297 |
+
Otherwise ``None``."""
|
| 298 |
+
if self._exc_info:
|
| 299 |
+
return self._exc_info[1]
|
| 300 |
+
|
| 301 |
+
def set(self, value=None):
|
| 302 |
+
"""Store the value and wake up any waiters.
|
| 303 |
+
|
| 304 |
+
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
|
| 305 |
+
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
|
| 306 |
+
"""
|
| 307 |
+
self._value = value
|
| 308 |
+
self._check_and_notify()
|
| 309 |
+
|
| 310 |
+
def set_exception(self, exception, exc_info=None):
|
| 311 |
+
"""Store the exception and wake up any waiters.
|
| 312 |
+
|
| 313 |
+
All greenlets blocking on :meth:`get` or :meth:`wait` are awakened.
|
| 314 |
+
Subsequent calls to :meth:`wait` and :meth:`get` will not block at all.
|
| 315 |
+
|
| 316 |
+
:keyword tuple exc_info: If given, a standard three-tuple of type, value, :class:`traceback`
|
| 317 |
+
as returned by :func:`sys.exc_info`. This will be used when the exception
|
| 318 |
+
is re-raised to propagate the correct traceback.
|
| 319 |
+
"""
|
| 320 |
+
if exc_info:
|
| 321 |
+
self._exc_info = (exc_info[0], exc_info[1], dump_traceback(exc_info[2]))
|
| 322 |
+
else:
|
| 323 |
+
self._exc_info = (type(exception), exception, dump_traceback(None))
|
| 324 |
+
|
| 325 |
+
self._check_and_notify()
|
| 326 |
+
|
| 327 |
+
def _raise_exception(self):
|
| 328 |
+
reraise(*self.exc_info)
|
| 329 |
+
|
| 330 |
+
def get(self, block=True, timeout=None):
|
| 331 |
+
"""Return the stored value or raise the exception.
|
| 332 |
+
|
| 333 |
+
If this instance already holds a value or an exception, return or raise it immediately.
|
| 334 |
+
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception` or
|
| 335 |
+
until the optional timeout occurs.
|
| 336 |
+
|
| 337 |
+
When the *timeout* argument is present and not ``None``, it should be a
|
| 338 |
+
floating point number specifying a timeout for the operation in seconds
|
| 339 |
+
(or fractions thereof). If the *timeout* elapses, the *Timeout* exception will
|
| 340 |
+
be raised.
|
| 341 |
+
|
| 342 |
+
:keyword bool block: If set to ``False`` and this instance is not ready,
|
| 343 |
+
immediately raise a :class:`Timeout` exception.
|
| 344 |
+
"""
|
| 345 |
+
if self._value is not _NONE:
|
| 346 |
+
return self._value
|
| 347 |
+
if self._exc_info:
|
| 348 |
+
return self._raise_exception()
|
| 349 |
+
|
| 350 |
+
if not block:
|
| 351 |
+
# Not ready and not blocking, so immediately timeout
|
| 352 |
+
raise Timeout()
|
| 353 |
+
|
| 354 |
+
self._capture_hub(True)
|
| 355 |
+
|
| 356 |
+
# Wait, raising a timeout that elapses
|
| 357 |
+
self._wait_core(timeout, ())
|
| 358 |
+
|
| 359 |
+
# by definition we are now ready
|
| 360 |
+
return self.get(block=False)
|
| 361 |
+
|
| 362 |
+
def get_nowait(self):
|
| 363 |
+
"""
|
| 364 |
+
Return the value or raise the exception without blocking.
|
| 365 |
+
|
| 366 |
+
If this object is not yet :meth:`ready <ready>`, raise
|
| 367 |
+
:class:`gevent.Timeout` immediately.
|
| 368 |
+
"""
|
| 369 |
+
return self.get(block=False)
|
| 370 |
+
|
| 371 |
+
def _wait_return_value(self, waited, wait_success):
|
| 372 |
+
# pylint:disable=unused-argument
|
| 373 |
+
# Always return the value. Since this is a one-shot event,
|
| 374 |
+
# no race condition should reset it.
|
| 375 |
+
return self.value
|
| 376 |
+
|
| 377 |
+
def wait(self, timeout=None):
|
| 378 |
+
"""Block until the instance is ready.
|
| 379 |
+
|
| 380 |
+
If this instance already holds a value, it is returned immediately. If this
|
| 381 |
+
instance already holds an exception, ``None`` is returned immediately.
|
| 382 |
+
|
| 383 |
+
Otherwise, block until another greenlet calls :meth:`set` or :meth:`set_exception`
|
| 384 |
+
(at which point either the value or ``None`` will be returned, respectively),
|
| 385 |
+
or until the optional timeout expires (at which point ``None`` will also be
|
| 386 |
+
returned).
|
| 387 |
+
|
| 388 |
+
When the *timeout* argument is present and not ``None``, it should be a
|
| 389 |
+
floating point number specifying a timeout for the operation in seconds
|
| 390 |
+
(or fractions thereof).
|
| 391 |
+
|
| 392 |
+
.. note:: If a timeout is given and expires, ``None`` will be returned
|
| 393 |
+
(no timeout exception will be raised).
|
| 394 |
+
|
| 395 |
+
"""
|
| 396 |
+
return self._wait(timeout)
|
| 397 |
+
|
| 398 |
+
# link protocol
|
| 399 |
+
def __call__(self, source):
|
| 400 |
+
if source.successful():
|
| 401 |
+
self.set(source.value)
|
| 402 |
+
else:
|
| 403 |
+
self.set_exception(source.exception, getattr(source, 'exc_info', None))
|
| 404 |
+
|
| 405 |
+
# Methods to make us more like concurrent.futures.Future
|
| 406 |
+
|
| 407 |
+
def result(self, timeout=None):
|
| 408 |
+
return self.get(timeout=timeout)
|
| 409 |
+
|
| 410 |
+
set_result = set
|
| 411 |
+
|
| 412 |
+
def done(self):
|
| 413 |
+
return self.ready()
|
| 414 |
+
|
| 415 |
+
# we don't support cancelling
|
| 416 |
+
|
| 417 |
+
def cancel(self):
|
| 418 |
+
return False
|
| 419 |
+
|
| 420 |
+
def cancelled(self):
|
| 421 |
+
return False
|
| 422 |
+
|
| 423 |
+
# exception is a method, we use it as a property
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
from gevent._util import import_c_accel
|
| 427 |
+
import_c_accel(globals(), 'gevent._event')
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/events.py
ADDED
|
@@ -0,0 +1,516 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright 2018 gevent. See LICENSE for details.
|
| 3 |
+
"""
|
| 4 |
+
Publish/subscribe event infrastructure.
|
| 5 |
+
|
| 6 |
+
When certain "interesting" things happen during the lifetime of the
|
| 7 |
+
process, gevent will "publish" an event (an object). That event is
|
| 8 |
+
delivered to interested "subscribers" (functions that take one
|
| 9 |
+
parameter, the event object).
|
| 10 |
+
|
| 11 |
+
Higher level frameworks may take this foundation and build richer
|
| 12 |
+
models on it.
|
| 13 |
+
|
| 14 |
+
:mod:`zope.event` will be used to provide the functionality of
|
| 15 |
+
`notify` and `subscribers`. See :mod:`zope.event.classhandler` for a
|
| 16 |
+
simple class-based approach to subscribing to a filtered list of
|
| 17 |
+
events, and see `zope.component
|
| 18 |
+
<https://zopecomponent.readthedocs.io/en/latest/event.html>`_ for a
|
| 19 |
+
much higher-level, flexible system. If you are using one of these
|
| 20 |
+
systems, you generally will not want to directly modify `subscribers`.
|
| 21 |
+
|
| 22 |
+
.. versionadded:: 1.3b1
|
| 23 |
+
|
| 24 |
+
.. versionchanged:: 23.7.0
|
| 25 |
+
Now uses :mod:`importlib.metadata` instead of :mod:`pkg_resources`
|
| 26 |
+
to locate entry points.
|
| 27 |
+
"""
|
| 28 |
+
from __future__ import absolute_import
|
| 29 |
+
from __future__ import division
|
| 30 |
+
from __future__ import print_function
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
__all__ = [
|
| 34 |
+
'subscribers',
|
| 35 |
+
|
| 36 |
+
# monitor thread
|
| 37 |
+
'IEventLoopBlocked',
|
| 38 |
+
'EventLoopBlocked',
|
| 39 |
+
'IMemoryUsageThresholdExceeded',
|
| 40 |
+
'MemoryUsageThresholdExceeded',
|
| 41 |
+
'IMemoryUsageUnderThreshold',
|
| 42 |
+
'MemoryUsageUnderThreshold',
|
| 43 |
+
|
| 44 |
+
# Hub
|
| 45 |
+
'IPeriodicMonitorThread',
|
| 46 |
+
'IPeriodicMonitorThreadStartedEvent',
|
| 47 |
+
'PeriodicMonitorThreadStartedEvent',
|
| 48 |
+
|
| 49 |
+
# monkey
|
| 50 |
+
'IGeventPatchEvent',
|
| 51 |
+
'GeventPatchEvent',
|
| 52 |
+
'IGeventWillPatchEvent',
|
| 53 |
+
'DoNotPatch',
|
| 54 |
+
'GeventWillPatchEvent',
|
| 55 |
+
'IGeventDidPatchEvent',
|
| 56 |
+
'IGeventWillPatchModuleEvent',
|
| 57 |
+
'GeventWillPatchModuleEvent',
|
| 58 |
+
'IGeventDidPatchModuleEvent',
|
| 59 |
+
'GeventDidPatchModuleEvent',
|
| 60 |
+
'IGeventWillPatchAllEvent',
|
| 61 |
+
'GeventWillPatchAllEvent',
|
| 62 |
+
'IGeventDidPatchBuiltinModulesEvent',
|
| 63 |
+
'GeventDidPatchBuiltinModulesEvent',
|
| 64 |
+
'IGeventDidPatchAllEvent',
|
| 65 |
+
'GeventDidPatchAllEvent',
|
| 66 |
+
]
|
| 67 |
+
|
| 68 |
+
# pylint:disable=no-self-argument,inherit-non-class
|
| 69 |
+
import platform
|
| 70 |
+
|
| 71 |
+
from zope.interface import Interface
|
| 72 |
+
from zope.interface import Attribute
|
| 73 |
+
from zope.interface import implementer
|
| 74 |
+
|
| 75 |
+
from zope.event import subscribers
|
| 76 |
+
from zope.event import notify
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
#: Applications may register for notification of events by appending a
|
| 81 |
+
#: callable to the ``subscribers`` list.
|
| 82 |
+
#:
|
| 83 |
+
#: Each subscriber takes a single argument, which is the event object
|
| 84 |
+
#: being published.
|
| 85 |
+
#:
|
| 86 |
+
#: Exceptions raised by subscribers will be propagated *without* running
|
| 87 |
+
#: any remaining subscribers.
|
| 88 |
+
#:
|
| 89 |
+
#: This is an alias for `zope.event.subscribers`; prefer to use
|
| 90 |
+
#: that attribute directly.
|
| 91 |
+
subscribers = subscribers
|
| 92 |
+
|
| 93 |
+
try:
|
| 94 |
+
# Cache the platform info. pkg_resources uses
|
| 95 |
+
# platform.machine() for environment markers, and
|
| 96 |
+
# platform.machine() wants to call os.popen('uname'), which is
|
| 97 |
+
# broken on Py2 when the gevent child signal handler is
|
| 98 |
+
# installed. (see test__monkey_sigchild_2.py)
|
| 99 |
+
platform.uname()
|
| 100 |
+
except: # pylint:disable=bare-except
|
| 101 |
+
pass
|
| 102 |
+
finally:
|
| 103 |
+
del platform
|
| 104 |
+
|
| 105 |
+
def notify_and_call_entry_points(event):
|
| 106 |
+
notify(event)
|
| 107 |
+
from importlib import metadata
|
| 108 |
+
import sys
|
| 109 |
+
# This used to use the old ``pkg_resources.iter_entry_points(group,name=None)``
|
| 110 |
+
# API, passing it just the first argument, ``group=event.ENTRY_POINT_NAME``.
|
| 111 |
+
# In other words, we don't care about the ``name``.
|
| 112 |
+
if sys.version_info[:2] >= (3, 10):
|
| 113 |
+
# pylint:disable-next=unexpected-keyword-arg
|
| 114 |
+
# The only thing you can do with this is iterate it to get
|
| 115 |
+
# EntryPoint objects. (e.g., accessing by index raises a warning)
|
| 116 |
+
entry_points = metadata.entry_points(group=event.ENTRY_POINT_NAME)
|
| 117 |
+
else:
|
| 118 |
+
# Prior to 3.10, we have to do this all manually (keyword selection
|
| 119 |
+
# was introduced in 3.10; in 3.9 and before, entry_points returns a plain
|
| 120 |
+
# ``dict``). Using it like this is deprecated in 3.10, so to avoid warnings
|
| 121 |
+
# we have to write it twice.
|
| 122 |
+
#
|
| 123 |
+
# Prior to 3.9, there is no ``.module`` attribute, so if we
|
| 124 |
+
# needed that we'd have to look at the complete ``.value``
|
| 125 |
+
# attribute.
|
| 126 |
+
ep_dict = metadata.entry_points()
|
| 127 |
+
__traceback_info__ = ep_dict
|
| 128 |
+
# On Python 3.8, we can get duplicate EntryPoint objects; it is unclear
|
| 129 |
+
# why. Drop them into a set to make sure we only get one.
|
| 130 |
+
#
|
| 131 |
+
# Running a more recent pylint flags the non-existence of ``get``
|
| 132 |
+
# pylint:disable=no-member
|
| 133 |
+
entry_points = set(
|
| 134 |
+
ep
|
| 135 |
+
for ep
|
| 136 |
+
in ep_dict.get(event.ENTRY_POINT_NAME, ())
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
for plugin in entry_points:
|
| 140 |
+
subscriber = plugin.load()
|
| 141 |
+
subscriber(event)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
class IPeriodicMonitorThread(Interface):
|
| 145 |
+
"""
|
| 146 |
+
The contract for the periodic monitoring thread that is started
|
| 147 |
+
by the hub.
|
| 148 |
+
"""
|
| 149 |
+
|
| 150 |
+
def add_monitoring_function(function, period):
|
| 151 |
+
"""
|
| 152 |
+
Schedule the *function* to be called approximately every *period* fractional seconds.
|
| 153 |
+
|
| 154 |
+
The *function* receives one argument, the hub being monitored. It is called
|
| 155 |
+
in the monitoring thread, *not* the hub thread. It **must not** attempt to
|
| 156 |
+
use the gevent asynchronous API.
|
| 157 |
+
|
| 158 |
+
If the *function* is already a monitoring function, then its *period*
|
| 159 |
+
will be updated for future runs.
|
| 160 |
+
|
| 161 |
+
If the *period* is ``None``, then the function will be removed.
|
| 162 |
+
|
| 163 |
+
A *period* less than or equal to zero is not allowed.
|
| 164 |
+
"""
|
| 165 |
+
|
| 166 |
+
class IPeriodicMonitorThreadStartedEvent(Interface):
|
| 167 |
+
"""
|
| 168 |
+
The event emitted when a hub starts a periodic monitoring thread.
|
| 169 |
+
|
| 170 |
+
You can use this event to add additional monitoring functions.
|
| 171 |
+
"""
|
| 172 |
+
|
| 173 |
+
monitor = Attribute("The instance of `IPeriodicMonitorThread` that was started.")
|
| 174 |
+
|
| 175 |
+
@implementer(IPeriodicMonitorThreadStartedEvent)
|
| 176 |
+
class PeriodicMonitorThreadStartedEvent(object):
|
| 177 |
+
"""
|
| 178 |
+
The implementation of :class:`IPeriodicMonitorThreadStartedEvent`.
|
| 179 |
+
|
| 180 |
+
.. versionchanged:: 24.11.1
|
| 181 |
+
Now actually implements the promised interface.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
#: The name of the setuptools entry point that is called when this
|
| 185 |
+
#: event is emitted.
|
| 186 |
+
ENTRY_POINT_NAME = 'gevent.plugins.hub.periodic_monitor_thread_started'
|
| 187 |
+
|
| 188 |
+
def __init__(self, monitor):
|
| 189 |
+
self.monitor = monitor
|
| 190 |
+
|
| 191 |
+
class IEventLoopBlocked(Interface):
|
| 192 |
+
"""
|
| 193 |
+
The event emitted when the event loop is blocked.
|
| 194 |
+
|
| 195 |
+
This event is emitted in the monitor thread.
|
| 196 |
+
|
| 197 |
+
.. versionchanged:: 24.11.1
|
| 198 |
+
Add the *hub* attribute.
|
| 199 |
+
"""
|
| 200 |
+
|
| 201 |
+
greenlet = Attribute("The greenlet that appeared to be blocking the loop.")
|
| 202 |
+
blocking_time = Attribute("The approximate time in seconds the loop has been blocked.")
|
| 203 |
+
info = Attribute("A list of string lines providing extra info. You may modify this list.")
|
| 204 |
+
hub = Attribute("""If not None, the hub being blocked.""")
|
| 205 |
+
|
| 206 |
+
@implementer(IEventLoopBlocked)
|
| 207 |
+
class EventLoopBlocked(object):
|
| 208 |
+
"""
|
| 209 |
+
The event emitted when the event loop is blocked.
|
| 210 |
+
|
| 211 |
+
Implements `IEventLoopBlocked`.
|
| 212 |
+
"""
|
| 213 |
+
|
| 214 |
+
def __init__(self, greenlet, blocking_time, info, *, hub=None):
|
| 215 |
+
self.greenlet = greenlet
|
| 216 |
+
self.blocking_time = blocking_time
|
| 217 |
+
self.info = info
|
| 218 |
+
self.hub = hub
|
| 219 |
+
|
| 220 |
+
class IMemoryUsageThresholdExceeded(Interface):
|
| 221 |
+
"""
|
| 222 |
+
The event emitted when the memory usage threshold is exceeded.
|
| 223 |
+
|
| 224 |
+
This event is emitted only while memory continues to grow
|
| 225 |
+
above the threshold. Only if the condition or stabilized is corrected (memory
|
| 226 |
+
usage drops) will the event be emitted in the future.
|
| 227 |
+
|
| 228 |
+
This event is emitted in the monitor thread.
|
| 229 |
+
"""
|
| 230 |
+
|
| 231 |
+
mem_usage = Attribute("The current process memory usage, in bytes.")
|
| 232 |
+
max_allowed = Attribute("The maximum allowed memory usage, in bytes.")
|
| 233 |
+
memory_info = Attribute("The tuple of memory usage stats return by psutil.")
|
| 234 |
+
|
| 235 |
+
class _AbstractMemoryEvent(object):
|
| 236 |
+
|
| 237 |
+
def __init__(self, mem_usage, max_allowed, memory_info):
|
| 238 |
+
self.mem_usage = mem_usage
|
| 239 |
+
self.max_allowed = max_allowed
|
| 240 |
+
self.memory_info = memory_info
|
| 241 |
+
|
| 242 |
+
def __repr__(self):
|
| 243 |
+
return "<%s used=%d max=%d details=%r>" % (
|
| 244 |
+
self.__class__.__name__,
|
| 245 |
+
self.mem_usage,
|
| 246 |
+
self.max_allowed,
|
| 247 |
+
self.memory_info,
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
@implementer(IMemoryUsageThresholdExceeded)
|
| 251 |
+
class MemoryUsageThresholdExceeded(_AbstractMemoryEvent):
|
| 252 |
+
"""
|
| 253 |
+
Implementation of `IMemoryUsageThresholdExceeded`.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class IMemoryUsageUnderThreshold(Interface):
|
| 258 |
+
"""
|
| 259 |
+
The event emitted when the memory usage drops below the
|
| 260 |
+
threshold after having previously been above it.
|
| 261 |
+
|
| 262 |
+
This event is emitted only the first time memory usage is detected
|
| 263 |
+
to be below the threshold after having previously been above it.
|
| 264 |
+
If memory usage climbs again, a `IMemoryUsageThresholdExceeded`
|
| 265 |
+
event will be broadcast, and then this event could be broadcast again.
|
| 266 |
+
|
| 267 |
+
This event is emitted in the monitor thread.
|
| 268 |
+
"""
|
| 269 |
+
|
| 270 |
+
mem_usage = Attribute("The current process memory usage, in bytes.")
|
| 271 |
+
max_allowed = Attribute("The maximum allowed memory usage, in bytes.")
|
| 272 |
+
max_memory_usage = Attribute("The memory usage that caused the previous "
|
| 273 |
+
"IMemoryUsageThresholdExceeded event.")
|
| 274 |
+
memory_info = Attribute("The tuple of memory usage stats return by psutil.")
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@implementer(IMemoryUsageUnderThreshold)
|
| 278 |
+
class MemoryUsageUnderThreshold(_AbstractMemoryEvent):
|
| 279 |
+
"""
|
| 280 |
+
Implementation of `IMemoryUsageUnderThreshold`.
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
def __init__(self, mem_usage, max_allowed, memory_info, max_usage):
|
| 284 |
+
super(MemoryUsageUnderThreshold, self).__init__(mem_usage, max_allowed, memory_info)
|
| 285 |
+
self.max_memory_usage = max_usage
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
class IGeventPatchEvent(Interface):
|
| 289 |
+
"""
|
| 290 |
+
The root for all monkey-patch events gevent emits.
|
| 291 |
+
"""
|
| 292 |
+
|
| 293 |
+
source = Attribute("The source object containing the patches.")
|
| 294 |
+
target = Attribute("The destination object to be patched.")
|
| 295 |
+
|
| 296 |
+
@implementer(IGeventPatchEvent)
|
| 297 |
+
class GeventPatchEvent(object):
|
| 298 |
+
"""
|
| 299 |
+
Implementation of `IGeventPatchEvent`.
|
| 300 |
+
"""
|
| 301 |
+
|
| 302 |
+
def __init__(self, source, target):
|
| 303 |
+
self.source = source
|
| 304 |
+
self.target = target
|
| 305 |
+
|
| 306 |
+
def __repr__(self):
|
| 307 |
+
return '<%s source=%r target=%r at %x>' % (self.__class__.__name__,
|
| 308 |
+
self.source,
|
| 309 |
+
self.target,
|
| 310 |
+
id(self))
|
| 311 |
+
|
| 312 |
+
class IGeventWillPatchEvent(IGeventPatchEvent):
|
| 313 |
+
"""
|
| 314 |
+
An event emitted *before* gevent monkey-patches something.
|
| 315 |
+
|
| 316 |
+
If a subscriber raises `DoNotPatch`, then patching this particular
|
| 317 |
+
item will not take place.
|
| 318 |
+
"""
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
class DoNotPatch(BaseException):
|
| 322 |
+
"""
|
| 323 |
+
Subscribers to will-patch events can raise instances
|
| 324 |
+
of this class to tell gevent not to patch that particular item.
|
| 325 |
+
"""
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
@implementer(IGeventWillPatchEvent)
|
| 329 |
+
class GeventWillPatchEvent(GeventPatchEvent):
|
| 330 |
+
"""
|
| 331 |
+
Implementation of `IGeventWillPatchEvent`.
|
| 332 |
+
"""
|
| 333 |
+
|
| 334 |
+
class IGeventDidPatchEvent(IGeventPatchEvent):
|
| 335 |
+
"""
|
| 336 |
+
An event emitted *after* gevent has patched something.
|
| 337 |
+
"""
|
| 338 |
+
|
| 339 |
+
@implementer(IGeventDidPatchEvent)
|
| 340 |
+
class GeventDidPatchEvent(GeventPatchEvent):
|
| 341 |
+
"""
|
| 342 |
+
Implementation of `IGeventDidPatchEvent`.
|
| 343 |
+
"""
|
| 344 |
+
|
| 345 |
+
class IGeventWillPatchModuleEvent(IGeventWillPatchEvent):
|
| 346 |
+
"""
|
| 347 |
+
An event emitted *before* gevent begins patching a specific module.
|
| 348 |
+
|
| 349 |
+
Both *source* and *target* attributes are module objects.
|
| 350 |
+
"""
|
| 351 |
+
|
| 352 |
+
module_name = Attribute("The name of the module being patched. "
|
| 353 |
+
"This is the same as ``target.__name__``.")
|
| 354 |
+
|
| 355 |
+
target_item_names = Attribute("The list of item names to patch. "
|
| 356 |
+
"This can be modified in place with caution.")
|
| 357 |
+
|
| 358 |
+
@implementer(IGeventWillPatchModuleEvent)
|
| 359 |
+
class GeventWillPatchModuleEvent(GeventWillPatchEvent):
|
| 360 |
+
"""
|
| 361 |
+
Implementation of `IGeventWillPatchModuleEvent`.
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
#: The name of the setuptools entry point that is called when this
|
| 365 |
+
#: event is emitted.
|
| 366 |
+
ENTRY_POINT_NAME = 'gevent.plugins.monkey.will_patch_module'
|
| 367 |
+
|
| 368 |
+
def __init__(self, module_name, source, target, items):
|
| 369 |
+
super(GeventWillPatchModuleEvent, self).__init__(source, target)
|
| 370 |
+
self.module_name = module_name
|
| 371 |
+
self.target_item_names = items
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class IGeventDidPatchModuleEvent(IGeventDidPatchEvent):
|
| 375 |
+
"""
|
| 376 |
+
An event emitted *after* gevent has completed patching a specific
|
| 377 |
+
module.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
module_name = Attribute("The name of the module being patched. "
|
| 381 |
+
"This is the same as ``target.__name__``.")
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
@implementer(IGeventDidPatchModuleEvent)
|
| 385 |
+
class GeventDidPatchModuleEvent(GeventDidPatchEvent):
|
| 386 |
+
"""
|
| 387 |
+
Implementation of `IGeventDidPatchModuleEvent`.
|
| 388 |
+
"""
|
| 389 |
+
|
| 390 |
+
#: The name of the setuptools entry point that is called when this
|
| 391 |
+
#: event is emitted.
|
| 392 |
+
ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_module'
|
| 393 |
+
|
| 394 |
+
def __init__(self, module_name, source, target):
|
| 395 |
+
super(GeventDidPatchModuleEvent, self).__init__(source, target)
|
| 396 |
+
self.module_name = module_name
|
| 397 |
+
|
| 398 |
+
# TODO: Maybe it would be useful for the the module patch events
|
| 399 |
+
# to have an attribute telling if they're being done during patch_all?
|
| 400 |
+
|
| 401 |
+
class IGeventWillPatchAllEvent(IGeventWillPatchEvent):
|
| 402 |
+
"""
|
| 403 |
+
An event emitted *before* gevent begins patching the system.
|
| 404 |
+
|
| 405 |
+
Following this event will be a series of
|
| 406 |
+
`IGeventWillPatchModuleEvent` and `IGeventDidPatchModuleEvent` for
|
| 407 |
+
each patched module.
|
| 408 |
+
|
| 409 |
+
Once the gevent builtin modules have been processed,
|
| 410 |
+
`IGeventDidPatchBuiltinModulesEvent` will be emitted. Processing
|
| 411 |
+
this event is an ideal time for third-party modules to be imported
|
| 412 |
+
and patched (which may trigger its own will/did patch module
|
| 413 |
+
events).
|
| 414 |
+
|
| 415 |
+
Finally, a `IGeventDidPatchAllEvent` will be sent.
|
| 416 |
+
|
| 417 |
+
If a subscriber to this event raises `DoNotPatch`, no patching
|
| 418 |
+
will be done.
|
| 419 |
+
|
| 420 |
+
The *source* and *target* attributes have undefined values.
|
| 421 |
+
"""
|
| 422 |
+
|
| 423 |
+
patch_all_arguments = Attribute(
|
| 424 |
+
"A dictionary of all the arguments to `gevent.monkey.patch_all`. "
|
| 425 |
+
"This dictionary should not be modified. "
|
| 426 |
+
)
|
| 427 |
+
|
| 428 |
+
patch_all_kwargs = Attribute(
|
| 429 |
+
"A dictionary of the extra arguments to `gevent.monkey.patch_all`. "
|
| 430 |
+
"This dictionary should not be modified. "
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
def will_patch_module(module_name):
|
| 434 |
+
"""
|
| 435 |
+
Return whether the module named *module_name* will be patched.
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
class _PatchAllMixin(object):
|
| 439 |
+
def __init__(self, patch_all_arguments, patch_all_kwargs):
|
| 440 |
+
super(_PatchAllMixin, self).__init__(None, None)
|
| 441 |
+
self._patch_all_arguments = patch_all_arguments
|
| 442 |
+
self._patch_all_kwargs = patch_all_kwargs
|
| 443 |
+
|
| 444 |
+
@property
|
| 445 |
+
def patch_all_arguments(self):
|
| 446 |
+
return self._patch_all_arguments.copy()
|
| 447 |
+
|
| 448 |
+
@property
|
| 449 |
+
def patch_all_kwargs(self):
|
| 450 |
+
return self._patch_all_kwargs.copy()
|
| 451 |
+
|
| 452 |
+
def __repr__(self):
|
| 453 |
+
return '<%s %r at %x>' % (self.__class__.__name__,
|
| 454 |
+
self._patch_all_arguments,
|
| 455 |
+
id(self))
|
| 456 |
+
|
| 457 |
+
@implementer(IGeventWillPatchAllEvent)
|
| 458 |
+
class GeventWillPatchAllEvent(_PatchAllMixin, GeventWillPatchEvent):
|
| 459 |
+
"""
|
| 460 |
+
Implementation of `IGeventWillPatchAllEvent`.
|
| 461 |
+
"""
|
| 462 |
+
|
| 463 |
+
#: The name of the setuptools entry point that is called when this
|
| 464 |
+
#: event is emitted.
|
| 465 |
+
ENTRY_POINT_NAME = 'gevent.plugins.monkey.will_patch_all'
|
| 466 |
+
|
| 467 |
+
def will_patch_module(self, module_name):
|
| 468 |
+
return self.patch_all_arguments.get(module_name)
|
| 469 |
+
|
| 470 |
+
class IGeventDidPatchBuiltinModulesEvent(IGeventDidPatchEvent):
|
| 471 |
+
"""
|
| 472 |
+
Event emitted *after* the builtin modules have been patched.
|
| 473 |
+
|
| 474 |
+
If you're going to monkey-patch a third-party library, this is
|
| 475 |
+
usually the event to listen for.
|
| 476 |
+
|
| 477 |
+
The values of the *source* and *target* attributes are undefined.
|
| 478 |
+
"""
|
| 479 |
+
|
| 480 |
+
patch_all_arguments = Attribute(
|
| 481 |
+
"A dictionary of all the arguments to `gevent.monkey.patch_all`. "
|
| 482 |
+
"This dictionary should not be modified. "
|
| 483 |
+
)
|
| 484 |
+
|
| 485 |
+
patch_all_kwargs = Attribute(
|
| 486 |
+
"A dictionary of the extra arguments to `gevent.monkey.patch_all`. "
|
| 487 |
+
"This dictionary should not be modified. "
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
@implementer(IGeventDidPatchBuiltinModulesEvent)
|
| 491 |
+
class GeventDidPatchBuiltinModulesEvent(_PatchAllMixin, GeventDidPatchEvent):
|
| 492 |
+
"""
|
| 493 |
+
Implementation of `IGeventDidPatchBuiltinModulesEvent`.
|
| 494 |
+
"""
|
| 495 |
+
|
| 496 |
+
#: The name of the setuptools entry point that is called when this
|
| 497 |
+
#: event is emitted.
|
| 498 |
+
ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_builtins'
|
| 499 |
+
|
| 500 |
+
class IGeventDidPatchAllEvent(IGeventDidPatchEvent):
|
| 501 |
+
"""
|
| 502 |
+
Event emitted after gevent has patched all modules, both builtin
|
| 503 |
+
and those provided by plugins/subscribers.
|
| 504 |
+
|
| 505 |
+
The values of the *source* and *target* attributes are undefined.
|
| 506 |
+
"""
|
| 507 |
+
|
| 508 |
+
@implementer(IGeventDidPatchAllEvent)
|
| 509 |
+
class GeventDidPatchAllEvent(_PatchAllMixin, GeventDidPatchEvent):
|
| 510 |
+
"""
|
| 511 |
+
Implementation of `IGeventDidPatchAllEvent`.
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
#: The name of the setuptools entry point that is called when this
|
| 515 |
+
#: event is emitted.
|
| 516 |
+
ENTRY_POINT_NAME = 'gevent.plugins.monkey.did_patch_all'
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/ex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import division
|
| 11 |
+
from __future__ import print_function
|
| 12 |
+
|
| 13 |
+
from greenlet import GreenletExit
|
| 14 |
+
|
| 15 |
+
__all__ = [
|
| 16 |
+
'LoopExit',
|
| 17 |
+
]
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class LoopExit(Exception):
|
| 21 |
+
"""
|
| 22 |
+
Exception thrown when the hub finishes running (`gevent.hub.Hub.run`
|
| 23 |
+
would return).
|
| 24 |
+
|
| 25 |
+
In a normal application, this is never thrown or caught
|
| 26 |
+
explicitly. The internal implementation of functions like
|
| 27 |
+
:meth:`gevent.hub.Hub.join` and :func:`gevent.joinall` may catch it, but user code
|
| 28 |
+
generally should not.
|
| 29 |
+
|
| 30 |
+
.. caution::
|
| 31 |
+
Errors in application programming can also lead to this exception being
|
| 32 |
+
raised. Some examples include (but are not limited too):
|
| 33 |
+
|
| 34 |
+
- greenlets deadlocking on a lock;
|
| 35 |
+
- using a socket or other gevent object with native thread
|
| 36 |
+
affinity from a different thread
|
| 37 |
+
|
| 38 |
+
"""
|
| 39 |
+
|
| 40 |
+
@property
|
| 41 |
+
def hub(self):
|
| 42 |
+
"""
|
| 43 |
+
The (optional) hub that raised the error.
|
| 44 |
+
|
| 45 |
+
.. versionadded:: 20.12.0
|
| 46 |
+
"""
|
| 47 |
+
# XXX: Note that semaphore.py does this manually.
|
| 48 |
+
if len(self.args) == 3: # From the hub
|
| 49 |
+
return self.args[1]
|
| 50 |
+
|
| 51 |
+
def __repr__(self):
|
| 52 |
+
# pylint:disable=unsubscriptable-object
|
| 53 |
+
if len(self.args) == 3: # From the hub
|
| 54 |
+
import pprint
|
| 55 |
+
return (
|
| 56 |
+
"%s\n"
|
| 57 |
+
"\tHub: %s\n"
|
| 58 |
+
"\tHandles:\n%s"
|
| 59 |
+
) % (
|
| 60 |
+
self.args[0],
|
| 61 |
+
self.args[1],
|
| 62 |
+
pprint.pformat(self.args[2])
|
| 63 |
+
)
|
| 64 |
+
return Exception.__repr__(self)
|
| 65 |
+
|
| 66 |
+
def __str__(self):
|
| 67 |
+
return repr(self)
|
| 68 |
+
|
| 69 |
+
class BlockingSwitchOutError(AssertionError):
|
| 70 |
+
"""
|
| 71 |
+
Raised when a gevent synchronous function is called from a
|
| 72 |
+
low-level event loop callback.
|
| 73 |
+
|
| 74 |
+
This is usually a programming error.
|
| 75 |
+
"""
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
class InvalidSwitchError(AssertionError):
|
| 79 |
+
"""
|
| 80 |
+
Raised when the event loop returns control to a greenlet in an
|
| 81 |
+
unexpected way.
|
| 82 |
+
|
| 83 |
+
This is usually a bug in gevent, greenlet, or the event loop.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
class ConcurrentObjectUseError(AssertionError):
|
| 87 |
+
"""
|
| 88 |
+
Raised when an object is used (waited on) by two greenlets
|
| 89 |
+
independently, meaning the object was entered into a blocking
|
| 90 |
+
state by one greenlet and then another while still blocking in the
|
| 91 |
+
first one.
|
| 92 |
+
|
| 93 |
+
This is usually a programming error.
|
| 94 |
+
|
| 95 |
+
.. seealso:: `gevent.socket.wait`
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
class InvalidThreadUseError(RuntimeError):
|
| 99 |
+
"""
|
| 100 |
+
Raised when an object is used from a different thread than
|
| 101 |
+
the one it is bound to.
|
| 102 |
+
|
| 103 |
+
Some objects, such as gevent sockets, semaphores, and threadpools,
|
| 104 |
+
are tightly bound to their hub and its loop. The hub and loop
|
| 105 |
+
are not thread safe, with a few exceptions. Attempting to use
|
| 106 |
+
such objects from a different thread is an error, and may cause
|
| 107 |
+
problems ranging from incorrect results to memory corruption
|
| 108 |
+
and a crashed process.
|
| 109 |
+
|
| 110 |
+
In some cases, gevent catches this "accidentally", and the result is
|
| 111 |
+
a `LoopExit`. In some cases, gevent doesn't catch this at all.
|
| 112 |
+
|
| 113 |
+
In other cases (typically when the consequences are suspected to
|
| 114 |
+
be more on the more severe end of the scale, and when the operation in
|
| 115 |
+
question is already relatively heavyweight), gevent explicitly checks
|
| 116 |
+
for this usage and will raise this exception when it is detected.
|
| 117 |
+
|
| 118 |
+
.. versionadded:: 1.5a3
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class HubDestroyed(GreenletExit):
|
| 123 |
+
"""
|
| 124 |
+
Internal exception, raised when we're trying to destroy the
|
| 125 |
+
hub and we want the loop to stop running callbacks now.
|
| 126 |
+
|
| 127 |
+
This must not be subclassed; the type is tested by identity.
|
| 128 |
+
|
| 129 |
+
Clients outside of gevent must not raise this exception.
|
| 130 |
+
|
| 131 |
+
.. versionadded:: 20.12.0
|
| 132 |
+
"""
|
| 133 |
+
|
| 134 |
+
def __init__(self, destroy_loop):
|
| 135 |
+
GreenletExit.__init__(self, destroy_loop)
|
| 136 |
+
self.destroy_loop = destroy_loop
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/fileobject.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Wrappers to make file-like objects cooperative.
|
| 3 |
+
|
| 4 |
+
.. class:: FileObject(fobj, mode='r', buffering=-1, closefd=True, encoding=None, errors=None, newline=None)
|
| 5 |
+
|
| 6 |
+
The main entry point to the file-like gevent-compatible behaviour. It
|
| 7 |
+
will be defined to be the best available implementation.
|
| 8 |
+
|
| 9 |
+
All the parameters are as for :func:`io.open`.
|
| 10 |
+
|
| 11 |
+
:param fobj: Usually a file descriptor of a socket. Can also be
|
| 12 |
+
another object with a ``fileno()`` method, or an object that can
|
| 13 |
+
be passed to ``io.open()`` (e.g., a file system path). If the object
|
| 14 |
+
is not a socket, the results will vary based on the platform and the
|
| 15 |
+
type of object being opened.
|
| 16 |
+
|
| 17 |
+
All supported versions of Python allow :class:`os.PathLike` objects.
|
| 18 |
+
|
| 19 |
+
.. versionchanged:: 1.5
|
| 20 |
+
Accept str and ``PathLike`` objects for *fobj* on all versions of Python.
|
| 21 |
+
.. versionchanged:: 1.5
|
| 22 |
+
Add *encoding*, *errors* and *newline* arguments.
|
| 23 |
+
.. versionchanged:: 1.5
|
| 24 |
+
Accept *closefd* and *buffering* instead of *close* and *bufsize* arguments.
|
| 25 |
+
The latter remain for backwards compatibility.
|
| 26 |
+
|
| 27 |
+
There are two main implementations of ``FileObject``. On all systems,
|
| 28 |
+
there is :class:`FileObjectThread` which uses the built-in native
|
| 29 |
+
threadpool to avoid blocking the entire interpreter. On UNIX systems
|
| 30 |
+
(those that support the :mod:`fcntl` module), there is also
|
| 31 |
+
:class:`FileObjectPosix` which uses native non-blocking semantics.
|
| 32 |
+
|
| 33 |
+
A third class, :class:`FileObjectBlock`, is simply a wrapper that
|
| 34 |
+
executes everything synchronously (and so is not gevent-compatible).
|
| 35 |
+
It is provided for testing and debugging purposes.
|
| 36 |
+
|
| 37 |
+
All classes have the same signature; some may accept extra keyword arguments.
|
| 38 |
+
|
| 39 |
+
Configuration
|
| 40 |
+
=============
|
| 41 |
+
|
| 42 |
+
You may change the default value for ``FileObject`` using the
|
| 43 |
+
``GEVENT_FILE`` environment variable. Set it to ``posix``, ``thread``,
|
| 44 |
+
or ``block`` to choose from :class:`FileObjectPosix`,
|
| 45 |
+
:class:`FileObjectThread` and :class:`FileObjectBlock`, respectively.
|
| 46 |
+
You may also set it to the fully qualified class name of another
|
| 47 |
+
object that implements the file interface to use one of your own
|
| 48 |
+
objects.
|
| 49 |
+
|
| 50 |
+
.. note::
|
| 51 |
+
|
| 52 |
+
The environment variable must be set at the time this module
|
| 53 |
+
is first imported.
|
| 54 |
+
|
| 55 |
+
Classes
|
| 56 |
+
=======
|
| 57 |
+
"""
|
| 58 |
+
from __future__ import absolute_import
|
| 59 |
+
|
| 60 |
+
from gevent._config import config
|
| 61 |
+
|
| 62 |
+
__all__ = [
|
| 63 |
+
'FileObjectPosix',
|
| 64 |
+
'FileObjectThread',
|
| 65 |
+
'FileObjectBlock',
|
| 66 |
+
'FileObject',
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
from fcntl import fcntl
|
| 71 |
+
except ImportError:
|
| 72 |
+
__all__.remove("FileObjectPosix")
|
| 73 |
+
else:
|
| 74 |
+
del fcntl
|
| 75 |
+
from gevent._fileobjectposix import FileObjectPosix
|
| 76 |
+
|
| 77 |
+
from gevent._fileobjectcommon import FileObjectThread
|
| 78 |
+
from gevent._fileobjectcommon import FileObjectBlock
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
# None of the possible objects can live in this module because
|
| 82 |
+
# we would get an import cycle and the config couldn't be set from code.
|
| 83 |
+
# TODO: zope.hookable would be great for allowing this to be imported
|
| 84 |
+
# without requiring configuration but still being very fast.
|
| 85 |
+
FileObject = config.fileobject
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/greenlet.py
ADDED
|
@@ -0,0 +1,1186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
|
| 2 |
+
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False
|
| 3 |
+
# pylint:disable=too-many-lines
|
| 4 |
+
from __future__ import absolute_import, print_function, division
|
| 5 |
+
|
| 6 |
+
from sys import _getframe as sys_getframe
|
| 7 |
+
from sys import exc_info as sys_exc_info
|
| 8 |
+
from weakref import ref as wref
|
| 9 |
+
|
| 10 |
+
# XXX: How to get cython to let us rename this as RawGreenlet
|
| 11 |
+
# like we prefer?
|
| 12 |
+
from greenlet import greenlet
|
| 13 |
+
from greenlet import GreenletExit
|
| 14 |
+
|
| 15 |
+
from gevent._compat import reraise
|
| 16 |
+
from gevent._compat import PYPY as _PYPY
|
| 17 |
+
from gevent._tblib import dump_traceback
|
| 18 |
+
from gevent._tblib import load_traceback
|
| 19 |
+
|
| 20 |
+
from gevent.exceptions import InvalidSwitchError
|
| 21 |
+
|
| 22 |
+
from gevent._hub_primitives import iwait_on_objects as iwait
|
| 23 |
+
from gevent._hub_primitives import wait_on_objects as wait
|
| 24 |
+
|
| 25 |
+
from gevent.timeout import Timeout
|
| 26 |
+
|
| 27 |
+
from gevent._config import config as GEVENT_CONFIG
|
| 28 |
+
from gevent._util import readproperty
|
| 29 |
+
from gevent._hub_local import get_hub_noargs as get_hub
|
| 30 |
+
from gevent import _waiter
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
__all__ = [
|
| 34 |
+
'Greenlet',
|
| 35 |
+
'joinall',
|
| 36 |
+
'killall',
|
| 37 |
+
]
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# In Cython, we define these as 'cdef inline' functions. The
|
| 41 |
+
# compilation unit cannot have a direct assignment to them (import
|
| 42 |
+
# is assignment) without generating a 'lvalue is not valid target'
|
| 43 |
+
# error.
|
| 44 |
+
locals()['getcurrent'] = __import__('greenlet').getcurrent
|
| 45 |
+
locals()['greenlet_init'] = lambda: None
|
| 46 |
+
locals()['Waiter'] = _waiter.Waiter
|
| 47 |
+
# With Cython, this raises a TypeError if the parent is *not*
|
| 48 |
+
# the hub (SwitchOutGreenletWithLoop); in pure-Python, we will
|
| 49 |
+
# very likely get an AttributeError immediately after when we access `loop`;
|
| 50 |
+
# The TypeError message is more informative on Python 2.
|
| 51 |
+
# This must ONLY be called when we know that `s` is not None and is in fact a greenlet
|
| 52 |
+
# object (e.g., when called on `self`)
|
| 53 |
+
locals()['get_my_hub'] = lambda s: s.parent
|
| 54 |
+
# This must also ONLY be called when we know that S is not None and is in fact a greenlet
|
| 55 |
+
# object (including the result of getcurrent())
|
| 56 |
+
locals()['get_generic_parent'] = lambda s: s.parent
|
| 57 |
+
|
| 58 |
+
# Frame access
|
| 59 |
+
locals()['Gevent_PyFrame_GetCode'] = lambda frame: frame.f_code
|
| 60 |
+
locals()['Gevent_PyFrame_GetLineNumber'] = lambda frame: frame.f_lineno
|
| 61 |
+
locals()['Gevent_PyFrame_GetBack'] = lambda frame: frame.f_back
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
if _PYPY:
|
| 65 |
+
import _continuation # pylint:disable=import-error
|
| 66 |
+
_continulet = _continuation.continulet
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class SpawnedLink(object):
|
| 70 |
+
"""
|
| 71 |
+
A wrapper around link that calls it in another greenlet.
|
| 72 |
+
|
| 73 |
+
Can be called only from main loop.
|
| 74 |
+
"""
|
| 75 |
+
__slots__ = ['callback']
|
| 76 |
+
|
| 77 |
+
def __init__(self, callback):
|
| 78 |
+
if not callable(callback):
|
| 79 |
+
raise TypeError("Expected callable: %r" % (callback, ))
|
| 80 |
+
self.callback = callback
|
| 81 |
+
|
| 82 |
+
def __call__(self, source):
|
| 83 |
+
g = greenlet(self.callback, get_hub())
|
| 84 |
+
g.switch(source)
|
| 85 |
+
|
| 86 |
+
def __hash__(self):
|
| 87 |
+
return hash(self.callback)
|
| 88 |
+
|
| 89 |
+
def __eq__(self, other):
|
| 90 |
+
return self.callback == getattr(other, 'callback', other)
|
| 91 |
+
|
| 92 |
+
def __str__(self):
|
| 93 |
+
return str(self.callback)
|
| 94 |
+
|
| 95 |
+
def __repr__(self):
|
| 96 |
+
return repr(self.callback)
|
| 97 |
+
|
| 98 |
+
def __getattr__(self, item):
|
| 99 |
+
assert item != 'callback'
|
| 100 |
+
return getattr(self.callback, item)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class SuccessSpawnedLink(SpawnedLink):
|
| 104 |
+
"""A wrapper around link that calls it in another greenlet only if source succeed.
|
| 105 |
+
|
| 106 |
+
Can be called only from main loop.
|
| 107 |
+
"""
|
| 108 |
+
__slots__ = []
|
| 109 |
+
|
| 110 |
+
def __call__(self, source):
|
| 111 |
+
if source.successful():
|
| 112 |
+
return SpawnedLink.__call__(self, source)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class FailureSpawnedLink(SpawnedLink):
|
| 116 |
+
"""A wrapper around link that calls it in another greenlet only if source failed.
|
| 117 |
+
|
| 118 |
+
Can be called only from main loop.
|
| 119 |
+
"""
|
| 120 |
+
__slots__ = []
|
| 121 |
+
|
| 122 |
+
def __call__(self, source):
|
| 123 |
+
if not source.successful():
|
| 124 |
+
return SpawnedLink.__call__(self, source)
|
| 125 |
+
|
| 126 |
+
class _Frame(object):
|
| 127 |
+
|
| 128 |
+
__slots__ = ('f_code', 'f_lineno', 'f_back')
|
| 129 |
+
|
| 130 |
+
def __init__(self):
|
| 131 |
+
self.f_code = None
|
| 132 |
+
self.f_back = None
|
| 133 |
+
self.f_lineno = 0
|
| 134 |
+
|
| 135 |
+
@property
|
| 136 |
+
def f_globals(self):
|
| 137 |
+
return None
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _extract_stack(limit):
|
| 141 |
+
try:
|
| 142 |
+
frame = sys_getframe()
|
| 143 |
+
except ValueError:
|
| 144 |
+
# In certain embedded cases that directly use the Python C api
|
| 145 |
+
# to call Greenlet.spawn (e.g., uwsgi) this can raise
|
| 146 |
+
# `ValueError: call stack is not deep enough`. This is because
|
| 147 |
+
# the Cython stack frames for Greenlet.spawn ->
|
| 148 |
+
# Greenlet.__init__ -> _extract_stack are all on the C level,
|
| 149 |
+
# not the Python level.
|
| 150 |
+
# See https://github.com/gevent/gevent/issues/1212
|
| 151 |
+
frame = None
|
| 152 |
+
|
| 153 |
+
newest_Frame = None
|
| 154 |
+
newer_Frame = None
|
| 155 |
+
|
| 156 |
+
while limit and frame is not None:
|
| 157 |
+
limit -= 1
|
| 158 |
+
older_Frame = _Frame()
|
| 159 |
+
# Arguments are always passed to the constructor as Python objects,
|
| 160 |
+
# meaning we wind up boxing the f_lineno just to unbox it if we pass it.
|
| 161 |
+
# It's faster to simply assign once the object is created.
|
| 162 |
+
older_Frame.f_code = Gevent_PyFrame_GetCode(frame) # pylint:disable=undefined-variable
|
| 163 |
+
older_Frame.f_lineno = Gevent_PyFrame_GetLineNumber(frame) # pylint:disable=undefined-variable
|
| 164 |
+
if newer_Frame is not None:
|
| 165 |
+
newer_Frame.f_back = older_Frame
|
| 166 |
+
newer_Frame = older_Frame
|
| 167 |
+
if newest_Frame is None:
|
| 168 |
+
newest_Frame = newer_Frame
|
| 169 |
+
|
| 170 |
+
frame = Gevent_PyFrame_GetBack(frame) # pylint:disable=undefined-variable
|
| 171 |
+
|
| 172 |
+
return newest_Frame
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
_greenlet__init__ = greenlet.__init__
|
| 176 |
+
|
| 177 |
+
class Greenlet(greenlet):
|
| 178 |
+
"""
|
| 179 |
+
A light-weight cooperatively-scheduled execution unit.
|
| 180 |
+
"""
|
| 181 |
+
# pylint:disable=too-many-public-methods,too-many-instance-attributes
|
| 182 |
+
|
| 183 |
+
spawning_stack_limit = 10
|
| 184 |
+
|
| 185 |
+
# pylint:disable=keyword-arg-before-vararg,super-init-not-called
|
| 186 |
+
def __init__(self, run=None, *args, **kwargs):
|
| 187 |
+
"""
|
| 188 |
+
:param args: The arguments passed to the ``run`` function.
|
| 189 |
+
:param kwargs: The keyword arguments passed to the ``run`` function.
|
| 190 |
+
:keyword callable run: The callable object to run. If not given, this object's
|
| 191 |
+
`_run` method will be invoked (typically defined by subclasses).
|
| 192 |
+
|
| 193 |
+
.. versionchanged:: 1.1b1
|
| 194 |
+
The ``run`` argument to the constructor is now verified to be a callable
|
| 195 |
+
object. Previously, passing a non-callable object would fail after the greenlet
|
| 196 |
+
was spawned.
|
| 197 |
+
|
| 198 |
+
.. versionchanged:: 1.3b1
|
| 199 |
+
The ``GEVENT_TRACK_GREENLET_TREE`` configuration value may be set to
|
| 200 |
+
a false value to disable ``spawn_tree_locals``, ``spawning_greenlet``,
|
| 201 |
+
and ``spawning_stack``. The first two will be None in that case, and the
|
| 202 |
+
latter will be empty.
|
| 203 |
+
|
| 204 |
+
.. versionchanged:: 1.5
|
| 205 |
+
Greenlet objects are now more careful to verify that their ``parent`` is really
|
| 206 |
+
a gevent hub, raising a ``TypeError`` earlier instead of an ``AttributeError`` later.
|
| 207 |
+
|
| 208 |
+
.. versionchanged:: 20.12.1
|
| 209 |
+
Greenlet objects now function as context managers. Exiting the ``with`` suite
|
| 210 |
+
ensures that the greenlet has completed by :meth:`joining <join>`
|
| 211 |
+
the greenlet (blocking, with
|
| 212 |
+
no timeout). If the body of the suite raises an exception, the greenlet is
|
| 213 |
+
:meth:`killed <kill>` with the default arguments and not joined in that case.
|
| 214 |
+
"""
|
| 215 |
+
# The attributes are documented in the .rst file
|
| 216 |
+
|
| 217 |
+
# greenlet.greenlet(run=None, parent=None)
|
| 218 |
+
# Calling it with both positional arguments instead of a keyword
|
| 219 |
+
# argument (parent=get_hub()) speeds up creation of this object ~30%:
|
| 220 |
+
# python -m timeit -s 'import gevent' 'gevent.Greenlet()'
|
| 221 |
+
# Python 3.5: 2.70usec with keywords vs 1.94usec with positional
|
| 222 |
+
# Python 3.4: 2.32usec with keywords vs 1.74usec with positional
|
| 223 |
+
# Python 3.3: 2.55usec with keywords vs 1.92usec with positional
|
| 224 |
+
# Python 2.7: 1.73usec with keywords vs 1.40usec with positional
|
| 225 |
+
|
| 226 |
+
# Timings taken Feb 21 2018 prior to integration of #755
|
| 227 |
+
# python -m perf timeit -s 'import gevent' 'gevent.Greenlet()'
|
| 228 |
+
# 3.6.4 : Mean +- std dev: 1.08 us +- 0.05 us
|
| 229 |
+
# 2.7.14 : Mean +- std dev: 1.44 us +- 0.06 us
|
| 230 |
+
# PyPy2 5.10.0: Mean +- std dev: 2.14 ns +- 0.08 ns
|
| 231 |
+
|
| 232 |
+
# After the integration of spawning_stack, spawning_greenlet,
|
| 233 |
+
# and spawn_tree_locals on that same date:
|
| 234 |
+
# 3.6.4 : Mean +- std dev: 8.92 us +- 0.36 us -> 8.2x
|
| 235 |
+
# 2.7.14 : Mean +- std dev: 14.8 us +- 0.5 us -> 10.2x
|
| 236 |
+
# PyPy2 5.10.0: Mean +- std dev: 3.24 us +- 0.17 us -> 1.5x
|
| 237 |
+
|
| 238 |
+
# Compiling with Cython gets us to these numbers:
|
| 239 |
+
# 3.6.4 : Mean +- std dev: 3.63 us +- 0.14 us
|
| 240 |
+
# 2.7.14 : Mean +- std dev: 3.37 us +- 0.20 us
|
| 241 |
+
# PyPy2 5.10.0 : Mean +- std dev: 4.44 us +- 0.28 us
|
| 242 |
+
|
| 243 |
+
# Switching to reified frames and some more tuning gets us here:
|
| 244 |
+
# 3.7.2 : Mean +- std dev: 2.53 us +- 0.15 us
|
| 245 |
+
# 2.7.16 : Mean +- std dev: 2.35 us +- 0.12 us
|
| 246 |
+
# PyPy2 7.1 : Mean +- std dev: 11.6 us +- 0.4 us
|
| 247 |
+
|
| 248 |
+
# Compared to the released 1.4 (tested at the same time):
|
| 249 |
+
# 3.7.2 : Mean +- std dev: 3.21 us +- 0.32 us
|
| 250 |
+
# 2.7.16 : Mean +- std dev: 3.11 us +- 0.19 us
|
| 251 |
+
# PyPy2 7.1 : Mean +- std dev: 12.3 us +- 0.8 us
|
| 252 |
+
|
| 253 |
+
_greenlet__init__(self, None, get_hub())
|
| 254 |
+
|
| 255 |
+
if run is not None:
|
| 256 |
+
self._run = run
|
| 257 |
+
|
| 258 |
+
# If they didn't pass a callable at all, then they must
|
| 259 |
+
# already have one. Note that subclassing to override the run() method
|
| 260 |
+
# itself has never been documented or supported.
|
| 261 |
+
if not callable(self._run):
|
| 262 |
+
raise TypeError("The run argument or self._run must be callable")
|
| 263 |
+
|
| 264 |
+
self.args = args
|
| 265 |
+
self.kwargs = kwargs
|
| 266 |
+
self.value = None
|
| 267 |
+
|
| 268 |
+
#: An event, such as a timer or a callback that fires. It is established in
|
| 269 |
+
#: start() and start_later() as those two objects, respectively.
|
| 270 |
+
#: Once this becomes non-None, the Greenlet cannot be started again. Conversely,
|
| 271 |
+
#: kill() and throw() check for non-None to determine if this object has ever been
|
| 272 |
+
#: scheduled for starting. A placeholder _cancelled_start_event is assigned by them to prevent
|
| 273 |
+
#: the greenlet from being started in the future, if necessary.
|
| 274 |
+
#: In the usual case, this transitions as follows: None -> event -> _start_completed_event.
|
| 275 |
+
#: A value of None means we've never been started.
|
| 276 |
+
self._start_event = None
|
| 277 |
+
|
| 278 |
+
self._notifier = None
|
| 279 |
+
self._formatted_info = None
|
| 280 |
+
self._links = []
|
| 281 |
+
self._ident = None
|
| 282 |
+
|
| 283 |
+
# Initial state: None.
|
| 284 |
+
# Completed successfully: (None, None, None)
|
| 285 |
+
# Failed with exception: (t, v, dump_traceback(tb)))
|
| 286 |
+
self._exc_info = None
|
| 287 |
+
|
| 288 |
+
if GEVENT_CONFIG.track_greenlet_tree:
|
| 289 |
+
spawner = getcurrent() # pylint:disable=undefined-variable
|
| 290 |
+
self.spawning_greenlet = wref(spawner)
|
| 291 |
+
try:
|
| 292 |
+
self.spawn_tree_locals = spawner.spawn_tree_locals
|
| 293 |
+
except AttributeError:
|
| 294 |
+
self.spawn_tree_locals = {}
|
| 295 |
+
if get_generic_parent(spawner) is not None: # pylint:disable=undefined-variable
|
| 296 |
+
# The main greenlet has no parent.
|
| 297 |
+
# Its children get separate locals.
|
| 298 |
+
spawner.spawn_tree_locals = self.spawn_tree_locals
|
| 299 |
+
|
| 300 |
+
self.spawning_stack = _extract_stack(self.spawning_stack_limit)
|
| 301 |
+
# Don't copy the spawning greenlet's
|
| 302 |
+
# '_spawning_stack_frames' into ours. That's somewhat
|
| 303 |
+
# confusing, and, if we're not careful, a deep spawn tree
|
| 304 |
+
# can lead to excessive memory usage (an infinite spawning
|
| 305 |
+
# tree could lead to unbounded memory usage without care
|
| 306 |
+
# --- see https://github.com/gevent/gevent/issues/1371)
|
| 307 |
+
# The _spawning_stack_frames may be cleared out later if we access spawning_stack
|
| 308 |
+
else:
|
| 309 |
+
# None is the default for all of these in Cython, but we
|
| 310 |
+
# need to declare them for pure-Python mode.
|
| 311 |
+
self.spawning_greenlet = None
|
| 312 |
+
self.spawn_tree_locals = None
|
| 313 |
+
self.spawning_stack = None
|
| 314 |
+
|
| 315 |
+
def _get_minimal_ident(self):
|
| 316 |
+
# Helper function for cython, to allow typing `reg` and making a
|
| 317 |
+
# C call to get_ident.
|
| 318 |
+
|
| 319 |
+
# If we're being accessed from a hub different than the one running
|
| 320 |
+
# us, aka get_hub() is not self.parent, then calling hub.ident_registry.get_ident()
|
| 321 |
+
# may be quietly broken: it's not thread safe.
|
| 322 |
+
# If our parent is no longer the hub for whatever reason, this will raise a
|
| 323 |
+
# AttributeError or TypeError.
|
| 324 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 325 |
+
|
| 326 |
+
reg = hub.ident_registry
|
| 327 |
+
return reg.get_ident(self)
|
| 328 |
+
|
| 329 |
+
@property
|
| 330 |
+
def minimal_ident(self):
|
| 331 |
+
"""
|
| 332 |
+
A small, unique non-negative integer that identifies this object.
|
| 333 |
+
|
| 334 |
+
This is similar to :attr:`threading.Thread.ident` (and `id`)
|
| 335 |
+
in that as long as this object is alive, no other greenlet *in
|
| 336 |
+
this hub* will have the same id, but it makes a stronger
|
| 337 |
+
guarantee that the assigned values will be small and
|
| 338 |
+
sequential. Sometime after this object has died, the value
|
| 339 |
+
will be available for reuse.
|
| 340 |
+
|
| 341 |
+
To get ids that are unique across all hubs, combine this with
|
| 342 |
+
the hub's (``self.parent``) ``minimal_ident``.
|
| 343 |
+
|
| 344 |
+
Accessing this property from threads other than the thread running
|
| 345 |
+
this greenlet is not defined.
|
| 346 |
+
|
| 347 |
+
.. versionadded:: 1.3a2
|
| 348 |
+
|
| 349 |
+
"""
|
| 350 |
+
# Not @Lazy, implemented manually because _ident is in the structure
|
| 351 |
+
# of the greenlet for fast access
|
| 352 |
+
if self._ident is None:
|
| 353 |
+
self._ident = self._get_minimal_ident()
|
| 354 |
+
return self._ident
|
| 355 |
+
|
| 356 |
+
@readproperty
|
| 357 |
+
def name(self):
|
| 358 |
+
"""
|
| 359 |
+
The greenlet name. By default, a unique name is constructed using
|
| 360 |
+
the :attr:`minimal_ident`. You can assign a string to this
|
| 361 |
+
value to change it. It is shown in the `repr` of this object if it
|
| 362 |
+
has been assigned to or if the `minimal_ident` has already been generated.
|
| 363 |
+
|
| 364 |
+
.. versionadded:: 1.3a2
|
| 365 |
+
.. versionchanged:: 1.4
|
| 366 |
+
Stop showing generated names in the `repr` when the ``minimal_ident``
|
| 367 |
+
hasn't been requested. This reduces overhead and may be less confusing,
|
| 368 |
+
since ``minimal_ident`` can get reused.
|
| 369 |
+
"""
|
| 370 |
+
return 'Greenlet-%d' % (self.minimal_ident,)
|
| 371 |
+
|
| 372 |
+
def _raise_exception(self):
|
| 373 |
+
reraise(*self.exc_info)
|
| 374 |
+
|
| 375 |
+
@property
|
| 376 |
+
def loop(self):
|
| 377 |
+
# needed by killall
|
| 378 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 379 |
+
return hub.loop
|
| 380 |
+
|
| 381 |
+
def __bool__(self):
|
| 382 |
+
return self._start_event is not None and self._exc_info is None
|
| 383 |
+
|
| 384 |
+
### Lifecycle
|
| 385 |
+
|
| 386 |
+
if _PYPY:
|
| 387 |
+
# oops - pypy's .dead relies on __nonzero__ which we overriden above
|
| 388 |
+
@property
|
| 389 |
+
def dead(self):
|
| 390 |
+
"Boolean indicating that the greenlet is dead and will not run again."
|
| 391 |
+
# pylint:disable=no-member
|
| 392 |
+
if self._greenlet__main:
|
| 393 |
+
return False
|
| 394 |
+
if self.__start_cancelled_by_kill() or self.__started_but_aborted():
|
| 395 |
+
return True
|
| 396 |
+
|
| 397 |
+
return self._greenlet__started and not _continulet.is_pending(self)
|
| 398 |
+
else:
|
| 399 |
+
@property
|
| 400 |
+
def dead(self):
|
| 401 |
+
"""
|
| 402 |
+
Boolean indicating that the greenlet is dead and will not run again.
|
| 403 |
+
|
| 404 |
+
This is true if:
|
| 405 |
+
|
| 406 |
+
1. We were never started, but were :meth:`killed <kill>`
|
| 407 |
+
immediately after creation (not possible with :meth:`spawn`); OR
|
| 408 |
+
2. We were started, but were killed before running; OR
|
| 409 |
+
3. We have run and terminated (by raising an exception out of the
|
| 410 |
+
started function or by reaching the end of the started function).
|
| 411 |
+
"""
|
| 412 |
+
return (
|
| 413 |
+
self.__start_cancelled_by_kill()
|
| 414 |
+
or self.__started_but_aborted()
|
| 415 |
+
or greenlet.dead.__get__(self)
|
| 416 |
+
)
|
| 417 |
+
|
| 418 |
+
def __never_started_or_killed(self):
|
| 419 |
+
return self._start_event is None
|
| 420 |
+
|
| 421 |
+
def __start_pending(self):
|
| 422 |
+
return (
|
| 423 |
+
self._start_event is not None
|
| 424 |
+
and (self._start_event.pending or getattr(self._start_event, 'active', False))
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
def __start_cancelled_by_kill(self):
|
| 428 |
+
return self._start_event is _cancelled_start_event
|
| 429 |
+
|
| 430 |
+
def __start_completed(self):
|
| 431 |
+
return self._start_event is _start_completed_event
|
| 432 |
+
|
| 433 |
+
def __started_but_aborted(self):
|
| 434 |
+
return (
|
| 435 |
+
not self.__never_started_or_killed() # we have been started or killed
|
| 436 |
+
and not self.__start_cancelled_by_kill() # we weren't killed, so we must have been started
|
| 437 |
+
and not self.__start_completed() # the start never completed
|
| 438 |
+
and not self.__start_pending() # and we're not pending, so we must have been aborted
|
| 439 |
+
)
|
| 440 |
+
|
| 441 |
+
def __cancel_start(self):
|
| 442 |
+
if self._start_event is None:
|
| 443 |
+
# prevent self from ever being started in the future
|
| 444 |
+
self._start_event = _cancelled_start_event
|
| 445 |
+
# cancel any pending start event
|
| 446 |
+
# NOTE: If this was a real pending start event, this will leave a
|
| 447 |
+
# "dangling" callback/timer object in the hub.loop.callbacks list;
|
| 448 |
+
# depending on where we are in the event loop, it may even be in a local
|
| 449 |
+
# variable copy of that list (in _run_callbacks). This isn't a problem,
|
| 450 |
+
# except for the leak-tests.
|
| 451 |
+
self._start_event.stop()
|
| 452 |
+
self._start_event.close()
|
| 453 |
+
|
| 454 |
+
def __handle_death_before_start(self, args):
|
| 455 |
+
# args is (t, v, tb) or simply t or v.
|
| 456 |
+
# The last two cases are transformed into (t, v, None);
|
| 457 |
+
# if the single argument is an exception type, a new instance
|
| 458 |
+
# is created; if the single argument is not an exception type and also
|
| 459 |
+
# not an exception, it is wrapped in a BaseException (this is not
|
| 460 |
+
# documented, but should result in better behaviour in the event of a
|
| 461 |
+
# user error---instead of silently printing something to stderr, we still
|
| 462 |
+
# kill the greenlet).
|
| 463 |
+
if self._exc_info is None and self.dead:
|
| 464 |
+
# the greenlet was never switched to before and it will
|
| 465 |
+
# never be; _report_error was not called, the result was
|
| 466 |
+
# not set, and the links weren't notified. Let's do it
|
| 467 |
+
# here.
|
| 468 |
+
#
|
| 469 |
+
# checking that self.dead is true is essential, because
|
| 470 |
+
# throw() does not necessarily kill the greenlet (if the
|
| 471 |
+
# exception raised by throw() is caught somewhere inside
|
| 472 |
+
# the greenlet).
|
| 473 |
+
if len(args) == 1:
|
| 474 |
+
arg = args[0]
|
| 475 |
+
if isinstance(arg, type) and issubclass(arg, BaseException):
|
| 476 |
+
args = (arg, arg(), None)
|
| 477 |
+
else:
|
| 478 |
+
args = (type(arg), arg, None)
|
| 479 |
+
elif not args:
|
| 480 |
+
args = (GreenletExit, GreenletExit(), None)
|
| 481 |
+
if not issubclass(args[0], BaseException):
|
| 482 |
+
# Random non-type, non-exception arguments.
|
| 483 |
+
args = (BaseException, BaseException(args), None)
|
| 484 |
+
assert issubclass(args[0], BaseException)
|
| 485 |
+
self.__report_error(args)
|
| 486 |
+
|
| 487 |
+
@property
|
| 488 |
+
def started(self):
|
| 489 |
+
# DEPRECATED
|
| 490 |
+
return bool(self)
|
| 491 |
+
|
| 492 |
+
def ready(self):
|
| 493 |
+
"""
|
| 494 |
+
Return a true value if and only if the greenlet has finished
|
| 495 |
+
execution.
|
| 496 |
+
|
| 497 |
+
.. versionchanged:: 1.1
|
| 498 |
+
This function is only guaranteed to return true or false *values*, not
|
| 499 |
+
necessarily the literal constants ``True`` or ``False``.
|
| 500 |
+
"""
|
| 501 |
+
return self.dead or self._exc_info is not None
|
| 502 |
+
|
| 503 |
+
def successful(self):
|
| 504 |
+
"""
|
| 505 |
+
Return a true value if and only if the greenlet has finished execution
|
| 506 |
+
successfully, that is, without raising an error.
|
| 507 |
+
|
| 508 |
+
.. tip:: A greenlet that has been killed with the default
|
| 509 |
+
:class:`GreenletExit` exception is considered successful.
|
| 510 |
+
That is, ``GreenletExit`` is not considered an error.
|
| 511 |
+
|
| 512 |
+
.. note:: This function is only guaranteed to return true or false *values*,
|
| 513 |
+
not necessarily the literal constants ``True`` or ``False``.
|
| 514 |
+
"""
|
| 515 |
+
return self._exc_info is not None and self._exc_info[1] is None
|
| 516 |
+
|
| 517 |
+
def __repr__(self):
|
| 518 |
+
classname = self.__class__.__name__
|
| 519 |
+
# If no name has been assigned, don't generate one, including a minimal_ident,
|
| 520 |
+
# if not necessary. This reduces the use of weak references and associated
|
| 521 |
+
# overhead.
|
| 522 |
+
if 'name' not in self.__dict__ and self._ident is None:
|
| 523 |
+
name = ' '
|
| 524 |
+
else:
|
| 525 |
+
name = ' "%s" ' % (self.name,)
|
| 526 |
+
result = '<%s%sat %s' % (classname, name, hex(id(self)))
|
| 527 |
+
formatted = self._formatinfo()
|
| 528 |
+
if formatted:
|
| 529 |
+
result += ': ' + formatted
|
| 530 |
+
return result + '>'
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _formatinfo(self):
|
| 534 |
+
info = self._formatted_info
|
| 535 |
+
if info is not None:
|
| 536 |
+
return info
|
| 537 |
+
|
| 538 |
+
# Are we running an arbitrary function provided to the constructor,
|
| 539 |
+
# or did a subclass override _run?
|
| 540 |
+
func = self._run
|
| 541 |
+
im_self = getattr(func, '__self__', None)
|
| 542 |
+
if im_self is self:
|
| 543 |
+
funcname = '_run'
|
| 544 |
+
elif im_self is not None:
|
| 545 |
+
funcname = repr(func)
|
| 546 |
+
else:
|
| 547 |
+
funcname = getattr(func, '__name__', '') or repr(func)
|
| 548 |
+
|
| 549 |
+
result = funcname
|
| 550 |
+
args = []
|
| 551 |
+
if self.args:
|
| 552 |
+
args = [repr(x)[:50] for x in self.args]
|
| 553 |
+
if self.kwargs:
|
| 554 |
+
args.extend(['%s=%s' % (key, repr(value)[:50]) for (key, value) in self.kwargs.items()])
|
| 555 |
+
if args:
|
| 556 |
+
result += '(' + ', '.join(args) + ')'
|
| 557 |
+
# it is important to save the result here, because once the greenlet exits '_run' attribute will be removed
|
| 558 |
+
self._formatted_info = result
|
| 559 |
+
return result
|
| 560 |
+
|
| 561 |
+
@property
|
| 562 |
+
def exception(self):
|
| 563 |
+
"""
|
| 564 |
+
Holds the exception instance raised by the function if the
|
| 565 |
+
greenlet has finished with an error. Otherwise ``None``.
|
| 566 |
+
"""
|
| 567 |
+
return self._exc_info[1] if self._exc_info is not None else None
|
| 568 |
+
|
| 569 |
+
@property
|
| 570 |
+
def exc_info(self):
|
| 571 |
+
"""
|
| 572 |
+
Holds the exc_info three-tuple raised by the function if the
|
| 573 |
+
greenlet finished with an error. Otherwise a false value.
|
| 574 |
+
|
| 575 |
+
.. note:: This is a provisional API and may change.
|
| 576 |
+
|
| 577 |
+
.. versionadded:: 1.1
|
| 578 |
+
"""
|
| 579 |
+
ei = self._exc_info
|
| 580 |
+
if ei is not None and ei[0] is not None:
|
| 581 |
+
return (
|
| 582 |
+
ei[0],
|
| 583 |
+
ei[1],
|
| 584 |
+
# The pickled traceback may be None if we couldn't pickle it.
|
| 585 |
+
load_traceback(ei[2]) if ei[2] else None
|
| 586 |
+
)
|
| 587 |
+
|
| 588 |
+
def throw(self, *args):
|
| 589 |
+
"""Immediately switch into the greenlet and raise an exception in it.
|
| 590 |
+
|
| 591 |
+
Should only be called from the HUB, otherwise the current greenlet is left unscheduled forever.
|
| 592 |
+
To raise an exception in a safe manner from any greenlet, use :meth:`kill`.
|
| 593 |
+
|
| 594 |
+
If a greenlet was started but never switched to yet, then also
|
| 595 |
+
a) cancel the event that will start it
|
| 596 |
+
b) fire the notifications as if an exception was raised in a greenlet
|
| 597 |
+
"""
|
| 598 |
+
self.__cancel_start()
|
| 599 |
+
|
| 600 |
+
try:
|
| 601 |
+
if not self.dead:
|
| 602 |
+
# Prevent switching into a greenlet *at all* if we had never
|
| 603 |
+
# started it. Usually this is the same thing that happens by throwing,
|
| 604 |
+
# but if this is done from the hub with nothing else running, prevents a
|
| 605 |
+
# LoopExit.
|
| 606 |
+
greenlet.throw(self, *args)
|
| 607 |
+
finally:
|
| 608 |
+
self.__handle_death_before_start(args)
|
| 609 |
+
|
| 610 |
+
def start(self):
|
| 611 |
+
"""Schedule the greenlet to run in this loop iteration"""
|
| 612 |
+
if self._start_event is None:
|
| 613 |
+
_call_spawn_callbacks(self)
|
| 614 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 615 |
+
self._start_event = hub.loop.run_callback(self.switch)
|
| 616 |
+
|
| 617 |
+
def start_later(self, seconds):
|
| 618 |
+
"""
|
| 619 |
+
start_later(seconds) -> None
|
| 620 |
+
|
| 621 |
+
Schedule the greenlet to run in the future loop iteration
|
| 622 |
+
*seconds* later
|
| 623 |
+
"""
|
| 624 |
+
if self._start_event is None:
|
| 625 |
+
_call_spawn_callbacks(self)
|
| 626 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 627 |
+
self._start_event = hub.loop.timer(seconds)
|
| 628 |
+
self._start_event.start(self.switch)
|
| 629 |
+
|
| 630 |
+
@staticmethod
|
| 631 |
+
def add_spawn_callback(callback):
|
| 632 |
+
"""
|
| 633 |
+
add_spawn_callback(callback) -> None
|
| 634 |
+
|
| 635 |
+
Set up a *callback* to be invoked when :class:`Greenlet` objects
|
| 636 |
+
are started.
|
| 637 |
+
|
| 638 |
+
The invocation order of spawn callbacks is unspecified. Adding the
|
| 639 |
+
same callback more than one time will not cause it to be called more
|
| 640 |
+
than once.
|
| 641 |
+
|
| 642 |
+
.. versionadded:: 1.4.0
|
| 643 |
+
"""
|
| 644 |
+
global _spawn_callbacks
|
| 645 |
+
if _spawn_callbacks is None: # pylint:disable=used-before-assignment
|
| 646 |
+
_spawn_callbacks = set()
|
| 647 |
+
_spawn_callbacks.add(callback)
|
| 648 |
+
|
| 649 |
+
@staticmethod
|
| 650 |
+
def remove_spawn_callback(callback):
|
| 651 |
+
"""
|
| 652 |
+
remove_spawn_callback(callback) -> None
|
| 653 |
+
|
| 654 |
+
Remove *callback* function added with :meth:`Greenlet.add_spawn_callback`.
|
| 655 |
+
This function will not fail if *callback* has been already removed or
|
| 656 |
+
if *callback* was never added.
|
| 657 |
+
|
| 658 |
+
.. versionadded:: 1.4.0
|
| 659 |
+
"""
|
| 660 |
+
global _spawn_callbacks
|
| 661 |
+
if _spawn_callbacks is not None:
|
| 662 |
+
_spawn_callbacks.discard(callback)
|
| 663 |
+
if not _spawn_callbacks:
|
| 664 |
+
_spawn_callbacks = None
|
| 665 |
+
|
| 666 |
+
@classmethod
|
| 667 |
+
def spawn(cls, *args, **kwargs):
|
| 668 |
+
"""
|
| 669 |
+
spawn(function, *args, **kwargs) -> Greenlet
|
| 670 |
+
|
| 671 |
+
Create a new :class:`Greenlet` object and schedule it to run ``function(*args, **kwargs)``.
|
| 672 |
+
This can be used as ``gevent.spawn`` or ``Greenlet.spawn``.
|
| 673 |
+
|
| 674 |
+
The arguments are passed to :meth:`Greenlet.__init__`.
|
| 675 |
+
|
| 676 |
+
.. versionchanged:: 1.1b1
|
| 677 |
+
If a *function* is given that is not callable, immediately raise a :exc:`TypeError`
|
| 678 |
+
instead of spawning a greenlet that will raise an uncaught TypeError.
|
| 679 |
+
"""
|
| 680 |
+
g = cls(*args, **kwargs)
|
| 681 |
+
g.start()
|
| 682 |
+
return g
|
| 683 |
+
|
| 684 |
+
@classmethod
|
| 685 |
+
def spawn_later(cls, seconds, *args, **kwargs):
|
| 686 |
+
"""
|
| 687 |
+
spawn_later(seconds, function, *args, **kwargs) -> Greenlet
|
| 688 |
+
|
| 689 |
+
Create and return a new `Greenlet` object scheduled to run ``function(*args, **kwargs)``
|
| 690 |
+
in a future loop iteration *seconds* later. This can be used as ``Greenlet.spawn_later``
|
| 691 |
+
or ``gevent.spawn_later``.
|
| 692 |
+
|
| 693 |
+
The arguments are passed to :meth:`Greenlet.__init__`.
|
| 694 |
+
|
| 695 |
+
.. versionchanged:: 1.1b1
|
| 696 |
+
If an argument that's meant to be a function (the first argument in *args*, or the ``run`` keyword )
|
| 697 |
+
is given to this classmethod (and not a classmethod of a subclass),
|
| 698 |
+
it is verified to be callable. Previously, the spawned greenlet would have failed
|
| 699 |
+
when it started running.
|
| 700 |
+
"""
|
| 701 |
+
if cls is Greenlet and not args and 'run' not in kwargs:
|
| 702 |
+
raise TypeError("")
|
| 703 |
+
g = cls(*args, **kwargs)
|
| 704 |
+
g.start_later(seconds)
|
| 705 |
+
return g
|
| 706 |
+
|
| 707 |
+
def _maybe_kill_before_start(self, exception):
|
| 708 |
+
# Helper for Greenlet.kill(), and also for killall()
|
| 709 |
+
self.__cancel_start()
|
| 710 |
+
self.__free()
|
| 711 |
+
dead = self.dead
|
| 712 |
+
if dead:
|
| 713 |
+
if isinstance(exception, tuple) and len(exception) == 3:
|
| 714 |
+
args = exception
|
| 715 |
+
else:
|
| 716 |
+
args = (exception,)
|
| 717 |
+
self.__handle_death_before_start(args)
|
| 718 |
+
return dead
|
| 719 |
+
|
| 720 |
+
def kill(self, exception=GreenletExit, block=True, timeout=None):
|
| 721 |
+
"""
|
| 722 |
+
Raise the ``exception`` in the greenlet.
|
| 723 |
+
|
| 724 |
+
If ``block`` is ``True`` (the default), wait until the greenlet
|
| 725 |
+
dies or the optional timeout expires; this may require switching
|
| 726 |
+
greenlets.
|
| 727 |
+
If block is ``False``, the current greenlet is not unscheduled.
|
| 728 |
+
|
| 729 |
+
This function always returns ``None`` and never raises an error. It
|
| 730 |
+
may be called multpile times on the same greenlet object, and may be
|
| 731 |
+
called on an unstarted or dead greenlet.
|
| 732 |
+
|
| 733 |
+
.. note::
|
| 734 |
+
|
| 735 |
+
Depending on what this greenlet is executing and the state
|
| 736 |
+
of the event loop, the exception may or may not be raised
|
| 737 |
+
immediately when this greenlet resumes execution. It may
|
| 738 |
+
be raised on a subsequent green call, or, if this greenlet
|
| 739 |
+
exits before making such a call, it may not be raised at
|
| 740 |
+
all. As of 1.1, an example where the exception is raised
|
| 741 |
+
later is if this greenlet had called :func:`sleep(0)
|
| 742 |
+
<gevent.sleep>`; an example where the exception is raised
|
| 743 |
+
immediately is if this greenlet had called
|
| 744 |
+
:func:`sleep(0.1) <gevent.sleep>`.
|
| 745 |
+
|
| 746 |
+
.. caution::
|
| 747 |
+
|
| 748 |
+
Use care when killing greenlets. If the code executing is not
|
| 749 |
+
exception safe (e.g., makes proper use of ``finally``) then an
|
| 750 |
+
unexpected exception could result in corrupted state. Using
|
| 751 |
+
a :meth:`link` or :meth:`rawlink` (cheaper) may be a safer way to
|
| 752 |
+
clean up resources.
|
| 753 |
+
|
| 754 |
+
See also :func:`gevent.kill` and :func:`gevent.killall`.
|
| 755 |
+
|
| 756 |
+
:keyword type exception: The type of exception to raise in the greenlet. The default
|
| 757 |
+
is :class:`GreenletExit`, which indicates a :meth:`successful` completion
|
| 758 |
+
of the greenlet.
|
| 759 |
+
|
| 760 |
+
.. versionchanged:: 0.13.0
|
| 761 |
+
*block* is now ``True`` by default.
|
| 762 |
+
.. versionchanged:: 1.1a2
|
| 763 |
+
If this greenlet had never been switched to, killing it will
|
| 764 |
+
prevent it from *ever* being switched to. Links (:meth:`rawlink`)
|
| 765 |
+
will still be executed, though.
|
| 766 |
+
.. versionchanged:: 20.12.1
|
| 767 |
+
If this greenlet is :meth:`ready`, immediately return instead of
|
| 768 |
+
requiring a trip around the event loop.
|
| 769 |
+
"""
|
| 770 |
+
if not self._maybe_kill_before_start(exception):
|
| 771 |
+
if self.ready():
|
| 772 |
+
return
|
| 773 |
+
|
| 774 |
+
waiter = Waiter() if block else None # pylint:disable=undefined-variable
|
| 775 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 776 |
+
hub.loop.run_callback(_kill, self, exception, waiter)
|
| 777 |
+
if waiter is not None:
|
| 778 |
+
waiter.get()
|
| 779 |
+
self.join(timeout)
|
| 780 |
+
|
| 781 |
+
def get(self, block=True, timeout=None):
|
| 782 |
+
"""
|
| 783 |
+
get(block=True, timeout=None) -> object
|
| 784 |
+
|
| 785 |
+
Return the result the greenlet has returned or re-raise the
|
| 786 |
+
exception it has raised.
|
| 787 |
+
|
| 788 |
+
If block is ``False``, raise :class:`gevent.Timeout` if the
|
| 789 |
+
greenlet is still alive. If block is ``True``, unschedule the
|
| 790 |
+
current greenlet until the result is available or the timeout
|
| 791 |
+
expires. In the latter case, :class:`gevent.Timeout` is
|
| 792 |
+
raised.
|
| 793 |
+
"""
|
| 794 |
+
if self.ready():
|
| 795 |
+
if self.successful():
|
| 796 |
+
return self.value
|
| 797 |
+
self._raise_exception()
|
| 798 |
+
if not block:
|
| 799 |
+
raise Timeout()
|
| 800 |
+
|
| 801 |
+
switch = getcurrent().switch # pylint:disable=undefined-variable
|
| 802 |
+
self.rawlink(switch)
|
| 803 |
+
try:
|
| 804 |
+
t = Timeout._start_new_or_dummy(timeout)
|
| 805 |
+
try:
|
| 806 |
+
result = get_my_hub(self).switch() # pylint:disable=undefined-variable
|
| 807 |
+
if result is not self:
|
| 808 |
+
raise InvalidSwitchError('Invalid switch into Greenlet.get(): %r' % (result, ))
|
| 809 |
+
finally:
|
| 810 |
+
t.cancel()
|
| 811 |
+
except:
|
| 812 |
+
# unlinking in 'except' instead of finally is an optimization:
|
| 813 |
+
# if switch occurred normally then link was already removed in _notify_links
|
| 814 |
+
# and there's no need to touch the links set.
|
| 815 |
+
# Note, however, that if "Invalid switch" assert was removed and invalid switch
|
| 816 |
+
# did happen, the link would remain, causing another invalid switch later in this greenlet.
|
| 817 |
+
self.unlink(switch)
|
| 818 |
+
raise
|
| 819 |
+
|
| 820 |
+
if self.ready():
|
| 821 |
+
if self.successful():
|
| 822 |
+
return self.value
|
| 823 |
+
self._raise_exception()
|
| 824 |
+
|
| 825 |
+
def join(self, timeout=None):
|
| 826 |
+
"""
|
| 827 |
+
join(timeout=None) -> None
|
| 828 |
+
|
| 829 |
+
Wait until the greenlet finishes or *timeout* expires. Return
|
| 830 |
+
``None`` regardless.
|
| 831 |
+
"""
|
| 832 |
+
if self.ready():
|
| 833 |
+
return
|
| 834 |
+
|
| 835 |
+
switch = getcurrent().switch # pylint:disable=undefined-variable
|
| 836 |
+
self.rawlink(switch)
|
| 837 |
+
try:
|
| 838 |
+
t = Timeout._start_new_or_dummy(timeout)
|
| 839 |
+
try:
|
| 840 |
+
result = get_my_hub(self).switch() # pylint:disable=undefined-variable
|
| 841 |
+
if result is not self:
|
| 842 |
+
raise InvalidSwitchError('Invalid switch into Greenlet.join(): %r' % (result, ))
|
| 843 |
+
finally:
|
| 844 |
+
t.cancel()
|
| 845 |
+
except Timeout as ex:
|
| 846 |
+
self.unlink(switch)
|
| 847 |
+
if ex is not t:
|
| 848 |
+
raise
|
| 849 |
+
except:
|
| 850 |
+
self.unlink(switch)
|
| 851 |
+
raise
|
| 852 |
+
|
| 853 |
+
def __enter__(self):
|
| 854 |
+
return self
|
| 855 |
+
|
| 856 |
+
def __exit__(self, t, v, tb):
|
| 857 |
+
if t is None:
|
| 858 |
+
try:
|
| 859 |
+
self.join()
|
| 860 |
+
finally:
|
| 861 |
+
self.kill()
|
| 862 |
+
else:
|
| 863 |
+
self.kill((t, v, tb))
|
| 864 |
+
|
| 865 |
+
def __report_result(self, result):
|
| 866 |
+
self._exc_info = (None, None, None)
|
| 867 |
+
self.value = result
|
| 868 |
+
if self._links and not self._notifier:
|
| 869 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 870 |
+
self._notifier = hub.loop.run_callback(self._notify_links)
|
| 871 |
+
|
| 872 |
+
def __report_error(self, exc_info):
|
| 873 |
+
if isinstance(exc_info[1], GreenletExit):
|
| 874 |
+
self.__report_result(exc_info[1])
|
| 875 |
+
return
|
| 876 |
+
|
| 877 |
+
# Depending on the error, we may not be able to pickle it.
|
| 878 |
+
# In particular, RecursionError can be a problem.
|
| 879 |
+
try:
|
| 880 |
+
tb = dump_traceback(exc_info[2])
|
| 881 |
+
except: # pylint:disable=bare-except
|
| 882 |
+
tb = None
|
| 883 |
+
self._exc_info = exc_info[0], exc_info[1], tb
|
| 884 |
+
|
| 885 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 886 |
+
if self._links and not self._notifier:
|
| 887 |
+
self._notifier = hub.loop.run_callback(self._notify_links)
|
| 888 |
+
|
| 889 |
+
try:
|
| 890 |
+
hub.handle_error(self, *exc_info)
|
| 891 |
+
finally:
|
| 892 |
+
del exc_info
|
| 893 |
+
|
| 894 |
+
def run(self):
|
| 895 |
+
try:
|
| 896 |
+
self.__cancel_start()
|
| 897 |
+
self._start_event = _start_completed_event
|
| 898 |
+
|
| 899 |
+
try:
|
| 900 |
+
result = self._run(*self.args, **self.kwargs)
|
| 901 |
+
except: # pylint:disable=bare-except
|
| 902 |
+
self.__report_error(sys_exc_info())
|
| 903 |
+
else:
|
| 904 |
+
self.__report_result(result)
|
| 905 |
+
finally:
|
| 906 |
+
self.__free()
|
| 907 |
+
|
| 908 |
+
def __free(self):
|
| 909 |
+
try:
|
| 910 |
+
# It seems that Cython 0.29.13 sometimes miscompiles
|
| 911 |
+
# self.__dict__.pop('_run', None) ? When we moved this out of the
|
| 912 |
+
# inline finally: block in run(), we started getting strange
|
| 913 |
+
# exceptions from places that subclassed Greenlet.
|
| 914 |
+
del self._run
|
| 915 |
+
except AttributeError:
|
| 916 |
+
pass
|
| 917 |
+
self.args = ()
|
| 918 |
+
self.kwargs.clear()
|
| 919 |
+
|
| 920 |
+
def _run(self):
|
| 921 |
+
"""
|
| 922 |
+
Subclasses may override this method to take any number of
|
| 923 |
+
arguments and keyword arguments.
|
| 924 |
+
|
| 925 |
+
.. versionadded:: 1.1a3
|
| 926 |
+
Previously, if no callable object was
|
| 927 |
+
passed to the constructor, the spawned greenlet would later
|
| 928 |
+
fail with an AttributeError.
|
| 929 |
+
"""
|
| 930 |
+
# We usually override this in __init__
|
| 931 |
+
# pylint: disable=method-hidden
|
| 932 |
+
return
|
| 933 |
+
|
| 934 |
+
def has_links(self):
|
| 935 |
+
return len(self._links)
|
| 936 |
+
|
| 937 |
+
def rawlink(self, callback):
|
| 938 |
+
"""
|
| 939 |
+
Register a callable to be executed when the greenlet finishes
|
| 940 |
+
execution.
|
| 941 |
+
|
| 942 |
+
The *callback* will be called with this instance as an
|
| 943 |
+
argument.
|
| 944 |
+
|
| 945 |
+
The *callback* will be called even if linked after the greenlet
|
| 946 |
+
is already ready().
|
| 947 |
+
|
| 948 |
+
.. caution::
|
| 949 |
+
The *callback* will be called in the hub and
|
| 950 |
+
**MUST NOT** raise an exception.
|
| 951 |
+
"""
|
| 952 |
+
if not callable(callback):
|
| 953 |
+
raise TypeError('Expected callable: %r' % (callback, ))
|
| 954 |
+
self._links.append(callback) # pylint:disable=no-member
|
| 955 |
+
if self.ready() and self._links and not self._notifier:
|
| 956 |
+
hub = get_my_hub(self) # pylint:disable=undefined-variable
|
| 957 |
+
self._notifier = hub.loop.run_callback(self._notify_links)
|
| 958 |
+
|
| 959 |
+
def link(self, callback, SpawnedLink=SpawnedLink):
|
| 960 |
+
"""
|
| 961 |
+
Link greenlet's completion to a callable.
|
| 962 |
+
|
| 963 |
+
The *callback* will be called with this instance as an
|
| 964 |
+
argument once this greenlet is dead. A callable is called in
|
| 965 |
+
its own :class:`greenlet.greenlet` (*not* a
|
| 966 |
+
:class:`Greenlet`).
|
| 967 |
+
|
| 968 |
+
The *callback* will be called even if linked after the greenlet
|
| 969 |
+
is already ready().
|
| 970 |
+
"""
|
| 971 |
+
# XXX: Is the redefinition of SpawnedLink supposed to just be an
|
| 972 |
+
# optimization, or do people use it? It's not documented
|
| 973 |
+
# pylint:disable=redefined-outer-name
|
| 974 |
+
self.rawlink(SpawnedLink(callback))
|
| 975 |
+
|
| 976 |
+
def unlink(self, callback):
|
| 977 |
+
"""Remove the callback set by :meth:`link` or :meth:`rawlink`"""
|
| 978 |
+
try:
|
| 979 |
+
self._links.remove(callback) # pylint:disable=no-member
|
| 980 |
+
except ValueError:
|
| 981 |
+
pass
|
| 982 |
+
|
| 983 |
+
def unlink_all(self):
|
| 984 |
+
"""
|
| 985 |
+
Remove all the callbacks.
|
| 986 |
+
|
| 987 |
+
.. versionadded:: 1.3a2
|
| 988 |
+
"""
|
| 989 |
+
del self._links[:]
|
| 990 |
+
|
| 991 |
+
def link_value(self, callback, SpawnedLink=SuccessSpawnedLink):
|
| 992 |
+
"""
|
| 993 |
+
Like :meth:`link` but *callback* is only notified when the greenlet
|
| 994 |
+
has completed successfully.
|
| 995 |
+
"""
|
| 996 |
+
# pylint:disable=redefined-outer-name
|
| 997 |
+
self.link(callback, SpawnedLink=SpawnedLink)
|
| 998 |
+
|
| 999 |
+
def link_exception(self, callback, SpawnedLink=FailureSpawnedLink):
|
| 1000 |
+
"""
|
| 1001 |
+
Like :meth:`link` but *callback* is only notified when the
|
| 1002 |
+
greenlet dies because of an unhandled exception.
|
| 1003 |
+
"""
|
| 1004 |
+
# pylint:disable=redefined-outer-name
|
| 1005 |
+
self.link(callback, SpawnedLink=SpawnedLink)
|
| 1006 |
+
|
| 1007 |
+
def _notify_links(self):
|
| 1008 |
+
while self._links:
|
| 1009 |
+
# Early links are allowed to remove later links
|
| 1010 |
+
# before we get to them, and they're also allowed to
|
| 1011 |
+
# add new links, so we have to be careful about iterating.
|
| 1012 |
+
|
| 1013 |
+
# We don't expect this list to be very large, so the time spent
|
| 1014 |
+
# manipulating it should be small. a deque is probably not justified.
|
| 1015 |
+
# Cython has optimizations to transform this into a memmove anyway.
|
| 1016 |
+
link = self._links.pop(0)
|
| 1017 |
+
try:
|
| 1018 |
+
link(self)
|
| 1019 |
+
except: # pylint:disable=bare-except, undefined-variable
|
| 1020 |
+
get_my_hub(self).handle_error((link, self), *sys_exc_info())
|
| 1021 |
+
|
| 1022 |
+
|
| 1023 |
+
class _dummy_event(object):
|
| 1024 |
+
__slots__ = ('pending', 'active')
|
| 1025 |
+
|
| 1026 |
+
def __init__(self):
|
| 1027 |
+
self.pending = self.active = False
|
| 1028 |
+
|
| 1029 |
+
def stop(self):
|
| 1030 |
+
pass
|
| 1031 |
+
|
| 1032 |
+
def start(self, cb): # pylint:disable=unused-argument
|
| 1033 |
+
raise AssertionError("Cannot start the dummy event")
|
| 1034 |
+
|
| 1035 |
+
def close(self):
|
| 1036 |
+
pass
|
| 1037 |
+
|
| 1038 |
+
_cancelled_start_event = _dummy_event()
|
| 1039 |
+
_start_completed_event = _dummy_event()
|
| 1040 |
+
|
| 1041 |
+
|
| 1042 |
+
# This is *only* called as a callback from the hub via Greenlet.kill(),
|
| 1043 |
+
# and its first argument is the Greenlet. So we can be sure about the types.
|
| 1044 |
+
def _kill(glet, exception, waiter):
|
| 1045 |
+
try:
|
| 1046 |
+
if isinstance(exception, tuple) and len(exception) == 3:
|
| 1047 |
+
glet.throw(*exception)
|
| 1048 |
+
else:
|
| 1049 |
+
glet.throw(exception)
|
| 1050 |
+
except: # pylint:disable=bare-except, undefined-variable
|
| 1051 |
+
# XXX do we need this here?
|
| 1052 |
+
get_my_hub(glet).handle_error(glet, *sys_exc_info())
|
| 1053 |
+
if waiter is not None:
|
| 1054 |
+
waiter.switch(None)
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def joinall(greenlets, timeout=None, raise_error=False, count=None):
|
| 1058 |
+
"""
|
| 1059 |
+
Wait for the ``greenlets`` to finish.
|
| 1060 |
+
|
| 1061 |
+
:param greenlets: A sequence (supporting :func:`len`) of greenlets to wait for.
|
| 1062 |
+
:keyword float timeout: If given, the maximum number of seconds to wait.
|
| 1063 |
+
:return: A sequence of the greenlets that finished before the timeout (if any)
|
| 1064 |
+
expired.
|
| 1065 |
+
"""
|
| 1066 |
+
if not raise_error:
|
| 1067 |
+
return wait(greenlets, timeout=timeout, count=count)
|
| 1068 |
+
|
| 1069 |
+
done = []
|
| 1070 |
+
for obj in iwait(greenlets, timeout=timeout, count=count):
|
| 1071 |
+
if getattr(obj, 'exception', None) is not None:
|
| 1072 |
+
if hasattr(obj, '_raise_exception'):
|
| 1073 |
+
obj._raise_exception()
|
| 1074 |
+
else:
|
| 1075 |
+
raise obj.exception
|
| 1076 |
+
done.append(obj)
|
| 1077 |
+
return done
|
| 1078 |
+
|
| 1079 |
+
|
| 1080 |
+
def _killall3(greenlets, exception, waiter):
|
| 1081 |
+
diehards = []
|
| 1082 |
+
for g in greenlets:
|
| 1083 |
+
if not g.dead:
|
| 1084 |
+
try:
|
| 1085 |
+
g.throw(exception)
|
| 1086 |
+
except: # pylint:disable=bare-except, undefined-variable
|
| 1087 |
+
get_my_hub(g).handle_error(g, *sys_exc_info())
|
| 1088 |
+
if not g.dead:
|
| 1089 |
+
diehards.append(g)
|
| 1090 |
+
waiter.switch(diehards)
|
| 1091 |
+
|
| 1092 |
+
|
| 1093 |
+
def _killall(greenlets, exception):
|
| 1094 |
+
for g in greenlets:
|
| 1095 |
+
if not g.dead:
|
| 1096 |
+
try:
|
| 1097 |
+
g.throw(exception)
|
| 1098 |
+
except: # pylint:disable=bare-except, undefined-variable
|
| 1099 |
+
get_my_hub(g).handle_error(g, *sys_exc_info())
|
| 1100 |
+
|
| 1101 |
+
|
| 1102 |
+
def _call_spawn_callbacks(gr):
|
| 1103 |
+
if _spawn_callbacks is not None:
|
| 1104 |
+
for cb in _spawn_callbacks:
|
| 1105 |
+
cb(gr)
|
| 1106 |
+
|
| 1107 |
+
|
| 1108 |
+
_spawn_callbacks = None
|
| 1109 |
+
|
| 1110 |
+
|
| 1111 |
+
def killall(greenlets, exception=GreenletExit, block=True, timeout=None):
|
| 1112 |
+
"""
|
| 1113 |
+
Forceably terminate all the *greenlets* by causing them to raise *exception*.
|
| 1114 |
+
|
| 1115 |
+
.. caution:: Use care when killing greenlets. If they are not prepared for exceptions,
|
| 1116 |
+
this could result in corrupted state.
|
| 1117 |
+
|
| 1118 |
+
:param greenlets: A **bounded** iterable of the non-None greenlets to terminate.
|
| 1119 |
+
*All* the items in this iterable must be greenlets that belong to the same hub,
|
| 1120 |
+
which should be the hub for this current thread. If this is a generator or iterator
|
| 1121 |
+
that switches greenlets, the results are undefined.
|
| 1122 |
+
:keyword exception: The type of exception to raise in the greenlets. By default this is
|
| 1123 |
+
:class:`GreenletExit`.
|
| 1124 |
+
:keyword bool block: If True (the default) then this function only returns when all the
|
| 1125 |
+
greenlets are dead; the current greenlet is unscheduled during that process.
|
| 1126 |
+
If greenlets ignore the initial exception raised in them,
|
| 1127 |
+
then they will be joined (with :func:`gevent.joinall`) and allowed to die naturally.
|
| 1128 |
+
If False, this function returns immediately and greenlets will raise
|
| 1129 |
+
the exception asynchronously.
|
| 1130 |
+
:keyword float timeout: A time in seconds to wait for greenlets to die. If given, it is
|
| 1131 |
+
only honored when ``block`` is True.
|
| 1132 |
+
:raise Timeout: If blocking and a timeout is given that elapses before
|
| 1133 |
+
all the greenlets are dead.
|
| 1134 |
+
|
| 1135 |
+
.. versionchanged:: 1.1a2
|
| 1136 |
+
*greenlets* can be any iterable of greenlets, like an iterator or a set.
|
| 1137 |
+
Previously it had to be a list or tuple.
|
| 1138 |
+
.. versionchanged:: 1.5a3
|
| 1139 |
+
Any :class:`Greenlet` in the *greenlets* list that hadn't been switched to before
|
| 1140 |
+
calling this method will never be switched to. This makes this function
|
| 1141 |
+
behave like :meth:`Greenlet.kill`. This does not apply to raw greenlets.
|
| 1142 |
+
.. versionchanged:: 1.5a3
|
| 1143 |
+
Now accepts raw greenlets created by :func:`gevent.spawn_raw`.
|
| 1144 |
+
"""
|
| 1145 |
+
|
| 1146 |
+
need_killed = []
|
| 1147 |
+
for glet in greenlets:
|
| 1148 |
+
# Quick pass through to prevent any greenlet from
|
| 1149 |
+
# actually being switched to if it hasn't already.
|
| 1150 |
+
# (Previously we called ``list(greenlets)`` so we're still
|
| 1151 |
+
# linear.)
|
| 1152 |
+
#
|
| 1153 |
+
# We don't use glet.kill() here because we don't want to schedule
|
| 1154 |
+
# any callbacks in the loop; we're about to handle that more directly.
|
| 1155 |
+
try:
|
| 1156 |
+
cancel = glet._maybe_kill_before_start
|
| 1157 |
+
except AttributeError:
|
| 1158 |
+
need_killed.append(glet)
|
| 1159 |
+
else:
|
| 1160 |
+
if not cancel(exception):
|
| 1161 |
+
need_killed.append(glet)
|
| 1162 |
+
|
| 1163 |
+
if not need_killed:
|
| 1164 |
+
return
|
| 1165 |
+
|
| 1166 |
+
loop = glet.loop # pylint:disable=undefined-loop-variable
|
| 1167 |
+
if block:
|
| 1168 |
+
waiter = Waiter() # pylint:disable=undefined-variable
|
| 1169 |
+
loop.run_callback(_killall3, need_killed, exception, waiter)
|
| 1170 |
+
t = Timeout._start_new_or_dummy(timeout)
|
| 1171 |
+
try:
|
| 1172 |
+
alive = waiter.get()
|
| 1173 |
+
if alive:
|
| 1174 |
+
joinall(alive, raise_error=False)
|
| 1175 |
+
finally:
|
| 1176 |
+
t.cancel()
|
| 1177 |
+
else:
|
| 1178 |
+
loop.run_callback(_killall, need_killed, exception)
|
| 1179 |
+
|
| 1180 |
+
def _init():
|
| 1181 |
+
greenlet_init() # pylint:disable=undefined-variable
|
| 1182 |
+
|
| 1183 |
+
_init()
|
| 1184 |
+
|
| 1185 |
+
from gevent._util import import_c_accel
|
| 1186 |
+
import_c_accel(globals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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2015 Denis Bilenko. See LICENSE for details.
|
| 2 |
+
"""
|
| 3 |
+
Event-loop hub.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import absolute_import, print_function
|
| 6 |
+
# XXX: FIXME: Refactor to make this smaller
|
| 7 |
+
# pylint:disable=too-many-lines
|
| 8 |
+
from functools import partial as _functools_partial
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
import traceback
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
from greenlet import greenlet as RawGreenlet
|
| 15 |
+
from greenlet import getcurrent
|
| 16 |
+
from greenlet import GreenletExit
|
| 17 |
+
from greenlet import error as GreenletError
|
| 18 |
+
|
| 19 |
+
__all__ = [
|
| 20 |
+
'getcurrent',
|
| 21 |
+
'GreenletExit',
|
| 22 |
+
'spawn_raw',
|
| 23 |
+
'sleep',
|
| 24 |
+
'kill',
|
| 25 |
+
'signal',
|
| 26 |
+
'reinit',
|
| 27 |
+
'get_hub',
|
| 28 |
+
'Hub',
|
| 29 |
+
'Waiter',
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
from gevent._config import config as GEVENT_CONFIG
|
| 33 |
+
from gevent._compat import thread_mod_name
|
| 34 |
+
from gevent._compat import reraise
|
| 35 |
+
from gevent._util import readproperty
|
| 36 |
+
from gevent._util import Lazy
|
| 37 |
+
from gevent._util import gmctime
|
| 38 |
+
from gevent._ident import IdentRegistry
|
| 39 |
+
|
| 40 |
+
from gevent._hub_local import get_hub
|
| 41 |
+
from gevent._hub_local import get_loop
|
| 42 |
+
from gevent._hub_local import set_hub
|
| 43 |
+
from gevent._hub_local import set_loop
|
| 44 |
+
from gevent._hub_local import get_hub_if_exists as _get_hub
|
| 45 |
+
from gevent._hub_local import get_hub_noargs as _get_hub_noargs
|
| 46 |
+
from gevent._hub_local import set_default_hub_class
|
| 47 |
+
|
| 48 |
+
from gevent._greenlet_primitives import TrackedRawGreenlet
|
| 49 |
+
from gevent._hub_primitives import WaitOperationsGreenlet
|
| 50 |
+
|
| 51 |
+
# Export
|
| 52 |
+
from gevent import _hub_primitives
|
| 53 |
+
wait = _hub_primitives.wait_on_objects
|
| 54 |
+
iwait = _hub_primitives.iwait_on_objects
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
from gevent.exceptions import LoopExit
|
| 58 |
+
from gevent.exceptions import HubDestroyed
|
| 59 |
+
|
| 60 |
+
from gevent._waiter import Waiter
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Need the real get_ident. We're imported early enough (by gevent/__init__.py)
|
| 64 |
+
# that we can be sure nothing is monkey patched yet.
|
| 65 |
+
get_thread_ident = __import__(thread_mod_name).get_ident
|
| 66 |
+
MAIN_THREAD_IDENT = get_thread_ident() # XXX: Assuming import is done on the main thread.
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def spawn_raw(function, *args, **kwargs):
|
| 71 |
+
"""
|
| 72 |
+
Create a new :class:`greenlet.greenlet` object and schedule it to
|
| 73 |
+
run ``function(*args, **kwargs)``.
|
| 74 |
+
|
| 75 |
+
This returns a raw :class:`~greenlet.greenlet` which does not have all the useful
|
| 76 |
+
methods that :class:`gevent.Greenlet` has. Typically, applications
|
| 77 |
+
should prefer :func:`~gevent.spawn`, but this method may
|
| 78 |
+
occasionally be useful as an optimization if there are many
|
| 79 |
+
greenlets involved.
|
| 80 |
+
|
| 81 |
+
.. versionchanged:: 1.1a3
|
| 82 |
+
Verify that ``function`` is callable, raising a TypeError if not. Previously,
|
| 83 |
+
the spawned greenlet would have failed the first time it was switched to.
|
| 84 |
+
|
| 85 |
+
.. versionchanged:: 1.1b1
|
| 86 |
+
If *function* is not callable, immediately raise a :exc:`TypeError`
|
| 87 |
+
instead of spawning a greenlet that will raise an uncaught TypeError.
|
| 88 |
+
|
| 89 |
+
.. versionchanged:: 1.1rc2
|
| 90 |
+
Accept keyword arguments for ``function`` as previously (incorrectly)
|
| 91 |
+
documented. Note that this may incur an additional expense.
|
| 92 |
+
|
| 93 |
+
.. versionchanged:: 1.3a2
|
| 94 |
+
Populate the ``spawning_greenlet`` and ``spawn_tree_locals``
|
| 95 |
+
attributes of the returned greenlet.
|
| 96 |
+
|
| 97 |
+
.. versionchanged:: 1.3b1
|
| 98 |
+
*Only* populate ``spawning_greenlet`` and ``spawn_tree_locals``
|
| 99 |
+
if ``GEVENT_TRACK_GREENLET_TREE`` is enabled (the default). If not enabled,
|
| 100 |
+
those attributes will not be set.
|
| 101 |
+
|
| 102 |
+
.. versionchanged:: 1.5a3
|
| 103 |
+
The returned greenlet always has a *loop* attribute matching the
|
| 104 |
+
current hub's loop. This helps it work better with more gevent APIs.
|
| 105 |
+
"""
|
| 106 |
+
if not callable(function):
|
| 107 |
+
raise TypeError("function must be callable")
|
| 108 |
+
|
| 109 |
+
# The hub is always the parent.
|
| 110 |
+
hub = _get_hub_noargs()
|
| 111 |
+
loop = hub.loop
|
| 112 |
+
|
| 113 |
+
factory = TrackedRawGreenlet if GEVENT_CONFIG.track_greenlet_tree else RawGreenlet
|
| 114 |
+
|
| 115 |
+
# The callback class object that we use to run this doesn't
|
| 116 |
+
# accept kwargs (and those objects are heavily used, as well as being
|
| 117 |
+
# implemented twice in core.ppyx and corecffi.py) so do it with a partial
|
| 118 |
+
if kwargs:
|
| 119 |
+
function = _functools_partial(function, *args, **kwargs)
|
| 120 |
+
g = factory(function, hub)
|
| 121 |
+
loop.run_callback(g.switch)
|
| 122 |
+
else:
|
| 123 |
+
g = factory(function, hub)
|
| 124 |
+
loop.run_callback(g.switch, *args)
|
| 125 |
+
g.loop = hub.loop
|
| 126 |
+
return g
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def sleep(seconds=0, ref=True):
|
| 130 |
+
"""
|
| 131 |
+
Put the current greenlet to sleep for at least *seconds*.
|
| 132 |
+
|
| 133 |
+
*seconds* may be specified as an integer, or a float if fractional
|
| 134 |
+
seconds are desired.
|
| 135 |
+
|
| 136 |
+
.. tip:: In the current implementation, a value of 0 (the default)
|
| 137 |
+
means to yield execution to any other runnable greenlets, but
|
| 138 |
+
this greenlet may be scheduled again before the event loop
|
| 139 |
+
cycles (in an extreme case, a greenlet that repeatedly sleeps
|
| 140 |
+
with 0 can prevent greenlets that are ready to do I/O from
|
| 141 |
+
being scheduled for some (small) period of time); a value greater than
|
| 142 |
+
0, on the other hand, will delay running this greenlet until
|
| 143 |
+
the next iteration of the loop.
|
| 144 |
+
|
| 145 |
+
If *ref* is False, the greenlet running ``sleep()`` will not prevent :func:`gevent.wait`
|
| 146 |
+
from exiting.
|
| 147 |
+
|
| 148 |
+
.. versionchanged:: 1.3a1
|
| 149 |
+
Sleeping with a value of 0 will now be bounded to approximately block the
|
| 150 |
+
loop for no longer than :func:`gevent.getswitchinterval`.
|
| 151 |
+
|
| 152 |
+
.. seealso:: :func:`idle`
|
| 153 |
+
"""
|
| 154 |
+
hub = _get_hub_noargs()
|
| 155 |
+
loop = hub.loop
|
| 156 |
+
if seconds <= 0:
|
| 157 |
+
waiter = Waiter(hub)
|
| 158 |
+
loop.run_callback(waiter.switch, None)
|
| 159 |
+
waiter.get()
|
| 160 |
+
else:
|
| 161 |
+
with loop.timer(seconds, ref=ref) as t:
|
| 162 |
+
# Sleeping is expected to be an "absolute" measure with
|
| 163 |
+
# respect to time.time(), not a relative measure, so it's
|
| 164 |
+
# important to update the loop's notion of now before we start
|
| 165 |
+
loop.update_now()
|
| 166 |
+
hub.wait(t)
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def idle(priority=0):
|
| 170 |
+
"""
|
| 171 |
+
Cause the calling greenlet to wait until the event loop is idle.
|
| 172 |
+
|
| 173 |
+
Idle is defined as having no other events of the same or higher
|
| 174 |
+
*priority* pending. That is, as long as sockets, timeouts or even
|
| 175 |
+
signals of the same or higher priority are being processed, the loop
|
| 176 |
+
is not idle.
|
| 177 |
+
|
| 178 |
+
.. seealso:: :func:`sleep`
|
| 179 |
+
"""
|
| 180 |
+
hub = _get_hub_noargs()
|
| 181 |
+
with hub.loop.idle() as watcher:
|
| 182 |
+
if priority:
|
| 183 |
+
watcher.priority = priority
|
| 184 |
+
hub.wait(watcher)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def kill(greenlet, exception=GreenletExit):
|
| 188 |
+
"""
|
| 189 |
+
Kill greenlet asynchronously. The current greenlet is not unscheduled.
|
| 190 |
+
|
| 191 |
+
.. note::
|
| 192 |
+
|
| 193 |
+
The method :meth:`Greenlet.kill` method does the same and
|
| 194 |
+
more (and the same caveats listed there apply here). However, the MAIN
|
| 195 |
+
greenlet - the one that exists initially - does not have a
|
| 196 |
+
``kill()`` method, and neither do any created with :func:`spawn_raw`,
|
| 197 |
+
so you have to use this function.
|
| 198 |
+
|
| 199 |
+
.. caution:: Use care when killing greenlets. If they are not prepared for
|
| 200 |
+
exceptions, this could result in corrupted state.
|
| 201 |
+
|
| 202 |
+
.. versionchanged:: 1.1a2
|
| 203 |
+
If the ``greenlet`` has a :meth:`kill <Greenlet.kill>` method, calls it. This prevents a
|
| 204 |
+
greenlet from being switched to for the first time after it's been
|
| 205 |
+
killed but not yet executed.
|
| 206 |
+
"""
|
| 207 |
+
if not greenlet.dead:
|
| 208 |
+
if hasattr(greenlet, 'kill'):
|
| 209 |
+
# dealing with gevent.greenlet.Greenlet. Use it, especially
|
| 210 |
+
# to avoid allowing one to be switched to for the first time
|
| 211 |
+
# after it's been killed
|
| 212 |
+
greenlet.kill(exception=exception, block=False)
|
| 213 |
+
else:
|
| 214 |
+
_get_hub_noargs().loop.run_callback(greenlet.throw, exception)
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
class signal(object):
|
| 218 |
+
"""
|
| 219 |
+
signal_handler(signalnum, handler, *args, **kwargs) -> object
|
| 220 |
+
|
| 221 |
+
Call the *handler* with the *args* and *kwargs* when the process
|
| 222 |
+
receives the signal *signalnum*.
|
| 223 |
+
|
| 224 |
+
The *handler* will be run in a new greenlet when the signal is
|
| 225 |
+
delivered.
|
| 226 |
+
|
| 227 |
+
This returns an object with the useful method ``cancel``, which,
|
| 228 |
+
when called, will prevent future deliveries of *signalnum* from
|
| 229 |
+
calling *handler*. It's best to keep the returned object alive
|
| 230 |
+
until you call ``cancel``.
|
| 231 |
+
|
| 232 |
+
.. note::
|
| 233 |
+
|
| 234 |
+
This may not operate correctly with ``SIGCHLD`` if libev child
|
| 235 |
+
watchers are used (as they are by default with
|
| 236 |
+
`gevent.os.fork`). See :mod:`gevent.signal` for a more
|
| 237 |
+
general purpose solution.
|
| 238 |
+
|
| 239 |
+
.. versionchanged:: 1.2a1
|
| 240 |
+
|
| 241 |
+
The ``handler`` argument is required to
|
| 242 |
+
be callable at construction time.
|
| 243 |
+
|
| 244 |
+
.. versionchanged:: 20.5.1
|
| 245 |
+
The ``cancel`` method now properly cleans up all native resources,
|
| 246 |
+
and drops references to all the arguments of this function.
|
| 247 |
+
"""
|
| 248 |
+
# This is documented as a function, not a class,
|
| 249 |
+
# so we're free to change implementation details.
|
| 250 |
+
|
| 251 |
+
greenlet_class = None
|
| 252 |
+
|
| 253 |
+
def __init__(self, signalnum, handler, *args, **kwargs):
|
| 254 |
+
if not callable(handler):
|
| 255 |
+
raise TypeError("signal handler must be callable.")
|
| 256 |
+
|
| 257 |
+
self.hub = _get_hub_noargs()
|
| 258 |
+
self.watcher = self.hub.loop.signal(signalnum, ref=False)
|
| 259 |
+
self.handler = handler
|
| 260 |
+
self.args = args
|
| 261 |
+
self.kwargs = kwargs
|
| 262 |
+
if self.greenlet_class is None:
|
| 263 |
+
from gevent import Greenlet
|
| 264 |
+
type(self).greenlet_class = Greenlet
|
| 265 |
+
self.greenlet_class = Greenlet
|
| 266 |
+
|
| 267 |
+
self.watcher.start(self._start)
|
| 268 |
+
|
| 269 |
+
ref = property(
|
| 270 |
+
lambda self: self.watcher.ref,
|
| 271 |
+
lambda self, nv: setattr(self.watcher, 'ref', nv)
|
| 272 |
+
)
|
| 273 |
+
|
| 274 |
+
def cancel(self):
|
| 275 |
+
if self.watcher is not None:
|
| 276 |
+
self.watcher.stop()
|
| 277 |
+
# Must close the watcher at a deterministic time, otherwise
|
| 278 |
+
# when CFFI reclaims the memory, the native loop might still
|
| 279 |
+
# have some reference to it; if anything tries to touch it
|
| 280 |
+
# we can wind up writing to memory that is no longer valid,
|
| 281 |
+
# leading to a wide variety of crashes.
|
| 282 |
+
self.watcher.close()
|
| 283 |
+
self.watcher = None
|
| 284 |
+
self.handler = None
|
| 285 |
+
self.args = None
|
| 286 |
+
self.kwargs = None
|
| 287 |
+
self.hub = None
|
| 288 |
+
self.greenlet_class = None
|
| 289 |
+
|
| 290 |
+
def _start(self):
|
| 291 |
+
# TODO: Maybe this should just be Greenlet.spawn()?
|
| 292 |
+
try:
|
| 293 |
+
greenlet = self.greenlet_class(self.handle)
|
| 294 |
+
greenlet.switch()
|
| 295 |
+
except: # pylint:disable=bare-except
|
| 296 |
+
self.hub.handle_error(None, *sys._exc_info()) # pylint:disable=no-member
|
| 297 |
+
|
| 298 |
+
def handle(self):
|
| 299 |
+
try:
|
| 300 |
+
self.handler(*self.args, **self.kwargs)
|
| 301 |
+
except: # pylint:disable=bare-except
|
| 302 |
+
self.hub.handle_error(None, *sys.exc_info())
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def reinit(hub=None):
|
| 306 |
+
"""
|
| 307 |
+
reinit() -> None
|
| 308 |
+
|
| 309 |
+
Prepare the gevent hub to run in a new (forked) process.
|
| 310 |
+
|
| 311 |
+
This should be called *immediately* after :func:`os.fork` in the
|
| 312 |
+
child process. This is done automatically by
|
| 313 |
+
:func:`gevent.os.fork` or if the :mod:`os` module has been
|
| 314 |
+
monkey-patched. If this function is not called in a forked
|
| 315 |
+
process, symptoms may include hanging of functions like
|
| 316 |
+
:func:`socket.getaddrinfo`, and the hub's threadpool is unlikely
|
| 317 |
+
to work.
|
| 318 |
+
|
| 319 |
+
.. note:: Registered fork watchers may or may not run before
|
| 320 |
+
this function (and thus ``gevent.os.fork``) return. If they have
|
| 321 |
+
not run, they will run "soon", after an iteration of the event loop.
|
| 322 |
+
You can force this by inserting a few small (but non-zero) calls to :func:`sleep`
|
| 323 |
+
after fork returns. (As of gevent 1.1 and before, fork watchers will
|
| 324 |
+
not have run, but this may change in the future.)
|
| 325 |
+
|
| 326 |
+
.. note:: This function may be removed in a future major release
|
| 327 |
+
if the fork process can be more smoothly managed.
|
| 328 |
+
|
| 329 |
+
.. warning:: See remarks in :func:`gevent.os.fork` about greenlets
|
| 330 |
+
and event loop watchers in the child process.
|
| 331 |
+
"""
|
| 332 |
+
# Note the signature line in the docstring: hub is not a public param.
|
| 333 |
+
|
| 334 |
+
# The loop reinit function in turn calls libev's ev_loop_fork
|
| 335 |
+
# function.
|
| 336 |
+
hub = _get_hub() if hub is None else hub
|
| 337 |
+
if hub is None:
|
| 338 |
+
return
|
| 339 |
+
|
| 340 |
+
# Note that we reinit the existing loop, not destroy it.
|
| 341 |
+
# See https://github.com/gevent/gevent/issues/200.
|
| 342 |
+
hub.loop.reinit()
|
| 343 |
+
# libev's fork watchers are slow to fire because the only fire
|
| 344 |
+
# at the beginning of a loop; due to our use of callbacks that
|
| 345 |
+
# run at the end of the loop, that may be too late. The
|
| 346 |
+
# threadpool and resolvers depend on the fork handlers being
|
| 347 |
+
# run (specifically, the threadpool will fail in the forked
|
| 348 |
+
# child if there were any threads in it, which there will be
|
| 349 |
+
# if the resolver_thread was in use (the default) before the
|
| 350 |
+
# fork.)
|
| 351 |
+
#
|
| 352 |
+
# If the forked process wants to use the threadpool or
|
| 353 |
+
# resolver immediately (in a queued callback), it would hang.
|
| 354 |
+
#
|
| 355 |
+
# The below is a workaround. Fortunately, all of these
|
| 356 |
+
# methods are idempotent and can be called multiple times
|
| 357 |
+
# following a fork if the suddenly started working, or were
|
| 358 |
+
# already working on some platforms. Other threadpools and fork handlers
|
| 359 |
+
# will be called at an arbitrary time later ('soon')
|
| 360 |
+
for obj in (hub._threadpool, hub._resolver, hub.periodic_monitoring_thread):
|
| 361 |
+
getattr(obj, '_on_fork', lambda: None)()
|
| 362 |
+
|
| 363 |
+
# TODO: We'd like to sleep for a non-zero amount of time to force the loop to make a
|
| 364 |
+
# pass around before returning to this greenlet. That will allow any
|
| 365 |
+
# user-provided fork watchers to run. (Two calls are necessary.) HOWEVER, if
|
| 366 |
+
# we do this, certain tests that heavily mix threads and forking,
|
| 367 |
+
# like 2.7/test_threading:test_reinit_tls_after_fork, fail. It's not immediately clear
|
| 368 |
+
# why.
|
| 369 |
+
#sleep(0.00001)
|
| 370 |
+
#sleep(0.00001)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class Hub(WaitOperationsGreenlet):
|
| 374 |
+
"""
|
| 375 |
+
A greenlet that runs the event loop.
|
| 376 |
+
|
| 377 |
+
It is created automatically by :func:`get_hub`.
|
| 378 |
+
|
| 379 |
+
.. rubric:: Switching
|
| 380 |
+
|
| 381 |
+
Every time this greenlet (i.e., the event loop) is switched *to*,
|
| 382 |
+
if the current greenlet has a ``switch_out`` method, it will be
|
| 383 |
+
called. This allows a greenlet to take some cleanup actions before
|
| 384 |
+
yielding control. This method should not call any gevent blocking
|
| 385 |
+
functions.
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
#: If instances of these classes are raised into the event loop,
|
| 389 |
+
#: they will be propagated out to the main greenlet (where they will
|
| 390 |
+
#: usually be caught by Python itself)
|
| 391 |
+
SYSTEM_ERROR = (KeyboardInterrupt, SystemExit, SystemError)
|
| 392 |
+
|
| 393 |
+
#: Instances of these classes are not considered to be errors and
|
| 394 |
+
#: do not get logged/printed when raised by the event loop.
|
| 395 |
+
NOT_ERROR = (GreenletExit, SystemExit)
|
| 396 |
+
|
| 397 |
+
#: The size we use for our threadpool. Either use a subclass
|
| 398 |
+
#: for this, or change it immediately after creating the hub.
|
| 399 |
+
threadpool_size = 10
|
| 400 |
+
|
| 401 |
+
# An instance of PeriodicMonitoringThread, if started.
|
| 402 |
+
periodic_monitoring_thread = None
|
| 403 |
+
|
| 404 |
+
# The ident of the thread we were created in, which should be the
|
| 405 |
+
# thread that we run in.
|
| 406 |
+
thread_ident = None
|
| 407 |
+
|
| 408 |
+
#: A string giving the name of this hub. Useful for associating hubs
|
| 409 |
+
#: with particular threads. Printed as part of the default repr.
|
| 410 |
+
#:
|
| 411 |
+
#: .. versionadded:: 1.3b1
|
| 412 |
+
name = ''
|
| 413 |
+
|
| 414 |
+
# NOTE: We cannot define a class-level 'loop' attribute
|
| 415 |
+
# because that conflicts with the slot we inherit from the
|
| 416 |
+
# Cythonized-bases.
|
| 417 |
+
|
| 418 |
+
# This is the source for our 'minimal_ident' property. We don't use a
|
| 419 |
+
# IdentRegistry because we've seen some crashes having to do with
|
| 420 |
+
# clearing weak references on shutdown in Windows (see known_failures.py).
|
| 421 |
+
# This gives us slightly different semantics than a greenlet's minimal_ident
|
| 422 |
+
# (notably, there can be holes) but we never documented this object's minimal_ident,
|
| 423 |
+
# and there should be few enough hub's over the lifetime of a process so as not
|
| 424 |
+
# to matter much.
|
| 425 |
+
_hub_counter = 0
|
| 426 |
+
|
| 427 |
+
def __init__(self, loop=None, default=None):
|
| 428 |
+
WaitOperationsGreenlet.__init__(self, None, None)
|
| 429 |
+
self.thread_ident = get_thread_ident()
|
| 430 |
+
if hasattr(loop, 'run'):
|
| 431 |
+
if default is not None:
|
| 432 |
+
raise TypeError("Unexpected argument: default")
|
| 433 |
+
self.loop = loop
|
| 434 |
+
elif get_loop() is not None:
|
| 435 |
+
# Reuse a loop instance previously set by
|
| 436 |
+
# destroying a hub without destroying the associated
|
| 437 |
+
# loop. See #237 and #238.
|
| 438 |
+
self.loop = get_loop()
|
| 439 |
+
else:
|
| 440 |
+
if default is None and self.thread_ident != MAIN_THREAD_IDENT:
|
| 441 |
+
default = False
|
| 442 |
+
|
| 443 |
+
if loop is None:
|
| 444 |
+
loop = self.backend
|
| 445 |
+
self.loop = self.loop_class(flags=loop, default=default) # pylint:disable=not-callable
|
| 446 |
+
self._resolver = None
|
| 447 |
+
self._threadpool = None
|
| 448 |
+
self.format_context = GEVENT_CONFIG.format_context
|
| 449 |
+
|
| 450 |
+
Hub._hub_counter += 1
|
| 451 |
+
self.minimal_ident = Hub._hub_counter
|
| 452 |
+
|
| 453 |
+
@Lazy
|
| 454 |
+
def ident_registry(self):
|
| 455 |
+
return IdentRegistry()
|
| 456 |
+
|
| 457 |
+
@property
|
| 458 |
+
def loop_class(self):
|
| 459 |
+
return GEVENT_CONFIG.loop
|
| 460 |
+
|
| 461 |
+
@property
|
| 462 |
+
def backend(self):
|
| 463 |
+
return GEVENT_CONFIG.libev_backend
|
| 464 |
+
|
| 465 |
+
@property
|
| 466 |
+
def main_hub(self):
|
| 467 |
+
"""
|
| 468 |
+
Is this the hub for the main thread?
|
| 469 |
+
|
| 470 |
+
.. versionadded:: 1.3b1
|
| 471 |
+
"""
|
| 472 |
+
return self.thread_ident == MAIN_THREAD_IDENT
|
| 473 |
+
|
| 474 |
+
def __repr__(self):
|
| 475 |
+
if self.loop is None:
|
| 476 |
+
info = 'destroyed'
|
| 477 |
+
else:
|
| 478 |
+
try:
|
| 479 |
+
info = self.loop._format()
|
| 480 |
+
except Exception as ex: # pylint:disable=broad-except
|
| 481 |
+
info = str(ex) or repr(ex) or 'error'
|
| 482 |
+
result = '<%s %r at 0x%x %s' % (
|
| 483 |
+
self.__class__.__name__,
|
| 484 |
+
self.name,
|
| 485 |
+
id(self),
|
| 486 |
+
info)
|
| 487 |
+
if self._resolver is not None:
|
| 488 |
+
result += ' resolver=%r' % self._resolver
|
| 489 |
+
if self._threadpool is not None:
|
| 490 |
+
result += ' threadpool=%r' % self._threadpool
|
| 491 |
+
result += ' thread_ident=%s' % (hex(self.thread_ident), )
|
| 492 |
+
return result + '>'
|
| 493 |
+
|
| 494 |
+
def _normalize_exception(self, t, v, tb):
|
| 495 |
+
# Allow passing in all None if the caller doesn't have
|
| 496 |
+
# easy access to sys.exc_info()
|
| 497 |
+
if (t, v, tb) == (None, None, None):
|
| 498 |
+
t, v, tb = sys.exc_info()
|
| 499 |
+
|
| 500 |
+
if isinstance(v, str):
|
| 501 |
+
# Cython can raise errors where the value is a plain string
|
| 502 |
+
# e.g., AttributeError, "_semaphore.Semaphore has no attr", <traceback>
|
| 503 |
+
v = t(v)
|
| 504 |
+
|
| 505 |
+
return t, v, tb
|
| 506 |
+
|
| 507 |
+
def handle_error(self, context, type, value, tb):
|
| 508 |
+
"""
|
| 509 |
+
Called by the event loop when an error occurs. The default
|
| 510 |
+
action is to print the exception to the :attr:`exception
|
| 511 |
+
stream <exception_stream>`.
|
| 512 |
+
|
| 513 |
+
The arguments ``type``, ``value``, and ``tb`` are the standard
|
| 514 |
+
tuple as returned by :func:`sys.exc_info`. (Note that when
|
| 515 |
+
this is called, it may not be safe to call
|
| 516 |
+
:func:`sys.exc_info`.)
|
| 517 |
+
|
| 518 |
+
Errors that are :attr:`not errors <NOT_ERROR>` are not
|
| 519 |
+
printed.
|
| 520 |
+
|
| 521 |
+
Errors that are :attr:`system errors <SYSTEM_ERROR>` are
|
| 522 |
+
passed to :meth:`handle_system_error` after being printed.
|
| 523 |
+
|
| 524 |
+
Applications can set a property on the hub instance with this
|
| 525 |
+
same signature to override the error handling provided by this
|
| 526 |
+
class. This is an advanced usage and requires great care. This
|
| 527 |
+
function *must not* raise any exceptions.
|
| 528 |
+
|
| 529 |
+
:param context: If this is ``None``, indicates a system error
|
| 530 |
+
that should generally result in exiting the loop and being
|
| 531 |
+
thrown to the parent greenlet.
|
| 532 |
+
"""
|
| 533 |
+
type, value, tb = self._normalize_exception(type, value, tb)
|
| 534 |
+
|
| 535 |
+
if type is HubDestroyed:
|
| 536 |
+
# We must continue propagating this for it to properly
|
| 537 |
+
# exit.
|
| 538 |
+
reraise(type, value, tb)
|
| 539 |
+
|
| 540 |
+
if not issubclass(type, self.NOT_ERROR):
|
| 541 |
+
self.print_exception(context, type, value, tb)
|
| 542 |
+
if context is None or issubclass(type, self.SYSTEM_ERROR):
|
| 543 |
+
self.handle_system_error(type, value, tb)
|
| 544 |
+
|
| 545 |
+
def handle_system_error(self, type, value, tb=None):
|
| 546 |
+
"""
|
| 547 |
+
Called from `handle_error` when the exception type is determined
|
| 548 |
+
to be a :attr:`system error <SYSTEM_ERROR>`.
|
| 549 |
+
|
| 550 |
+
System errors cause the exception to be raised in the main
|
| 551 |
+
greenlet (the parent of this hub).
|
| 552 |
+
|
| 553 |
+
.. versionchanged:: 20.5.1
|
| 554 |
+
Allow passing the traceback to associate with the
|
| 555 |
+
exception if it is rethrown into the main greenlet.
|
| 556 |
+
"""
|
| 557 |
+
current = getcurrent()
|
| 558 |
+
if current is self or current is self.parent or self.loop is None:
|
| 559 |
+
self.parent.throw(type, value, tb)
|
| 560 |
+
else:
|
| 561 |
+
# in case system error was handled and life goes on
|
| 562 |
+
# switch back to this greenlet as well
|
| 563 |
+
cb = None
|
| 564 |
+
try:
|
| 565 |
+
cb = self.loop.run_callback(current.switch)
|
| 566 |
+
except: # pylint:disable=bare-except
|
| 567 |
+
traceback.print_exc(file=self.exception_stream)
|
| 568 |
+
try:
|
| 569 |
+
self.parent.throw(type, value, tb)
|
| 570 |
+
finally:
|
| 571 |
+
if cb is not None:
|
| 572 |
+
cb.stop()
|
| 573 |
+
|
| 574 |
+
@readproperty
|
| 575 |
+
def exception_stream(self):
|
| 576 |
+
"""
|
| 577 |
+
The stream to which exceptions will be written.
|
| 578 |
+
Defaults to ``sys.stderr`` unless assigned. Assigning a
|
| 579 |
+
false (None) value disables printing exceptions.
|
| 580 |
+
|
| 581 |
+
.. versionadded:: 1.2a1
|
| 582 |
+
"""
|
| 583 |
+
# Unwrap any FileObjectThread we have thrown around sys.stderr
|
| 584 |
+
# (because it can't be used in the hub). Tricky because we are
|
| 585 |
+
# called in error situations when it's not safe to import.
|
| 586 |
+
# Be careful not to access sys if we're in the process of interpreter
|
| 587 |
+
# shutdown.
|
| 588 |
+
stderr = sys.stderr if sys else None # pylint:disable=using-constant-test
|
| 589 |
+
if type(stderr).__name__ == 'FileObjectThread':
|
| 590 |
+
stderr = stderr.io # pylint:disable=no-member
|
| 591 |
+
return stderr
|
| 592 |
+
|
| 593 |
+
def print_exception(self, context, t, v, tb):
|
| 594 |
+
# Python 3 does not gracefully handle None value or tb in
|
| 595 |
+
# traceback.print_exception() as previous versions did.
|
| 596 |
+
# pylint:disable=no-member
|
| 597 |
+
errstream = self.exception_stream
|
| 598 |
+
if not errstream: # pragma: no cover
|
| 599 |
+
# If the error stream is gone, such as when the sys dict
|
| 600 |
+
# gets cleared during interpreter shutdown,
|
| 601 |
+
# don't cause follow-on errors.
|
| 602 |
+
# See https://github.com/gevent/gevent/issues/1295
|
| 603 |
+
return
|
| 604 |
+
|
| 605 |
+
t, v, tb = self._normalize_exception(t, v, tb)
|
| 606 |
+
|
| 607 |
+
if v is None:
|
| 608 |
+
errstream.write('%s\n' % t.__name__)
|
| 609 |
+
else:
|
| 610 |
+
traceback.print_exception(t, v, tb, file=errstream)
|
| 611 |
+
del tb
|
| 612 |
+
|
| 613 |
+
try:
|
| 614 |
+
errstream.write(gmctime())
|
| 615 |
+
errstream.write(' ' if context is not None else '\n')
|
| 616 |
+
except: # pylint:disable=bare-except
|
| 617 |
+
# Possible not safe to import under certain
|
| 618 |
+
# error conditions in Python 2
|
| 619 |
+
pass
|
| 620 |
+
|
| 621 |
+
if context is not None:
|
| 622 |
+
if not isinstance(context, str):
|
| 623 |
+
try:
|
| 624 |
+
context = self.format_context(context)
|
| 625 |
+
except: # pylint:disable=bare-except
|
| 626 |
+
traceback.print_exc(file=self.exception_stream)
|
| 627 |
+
context = repr(context)
|
| 628 |
+
errstream.write('%s failed with %s\n\n' % (context, getattr(t, '__name__', 'exception'), ))
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def run(self):
|
| 632 |
+
"""
|
| 633 |
+
Entry-point to running the loop. This method is called automatically
|
| 634 |
+
when the hub greenlet is scheduled; do not call it directly.
|
| 635 |
+
|
| 636 |
+
:raises gevent.exceptions.LoopExit: If the loop finishes running. This means
|
| 637 |
+
that there are no other scheduled greenlets, and no active
|
| 638 |
+
watchers or servers. In some situations, this indicates a
|
| 639 |
+
programming error.
|
| 640 |
+
"""
|
| 641 |
+
assert self is getcurrent(), 'Do not call Hub.run() directly'
|
| 642 |
+
self.start_periodic_monitoring_thread()
|
| 643 |
+
while 1:
|
| 644 |
+
loop = self.loop
|
| 645 |
+
loop.error_handler = self
|
| 646 |
+
try:
|
| 647 |
+
loop.run()
|
| 648 |
+
finally:
|
| 649 |
+
loop.error_handler = None # break the refcount cycle
|
| 650 |
+
|
| 651 |
+
# This function must never return, as it will cause
|
| 652 |
+
# switch() in the parent greenlet to return an unexpected
|
| 653 |
+
# value. This can show up as unexpected failures e.g.,
|
| 654 |
+
# from Waiters raising AssertionError or MulitpleWaiter
|
| 655 |
+
# raising invalid IndexError.
|
| 656 |
+
#
|
| 657 |
+
# It is still possible to kill this greenlet with throw.
|
| 658 |
+
# However, in that case switching to it is no longer safe,
|
| 659 |
+
# as switch will return immediately.
|
| 660 |
+
#
|
| 661 |
+
# Note that there's a problem with simply doing
|
| 662 |
+
# ``self.parent.throw()`` and never actually exiting this
|
| 663 |
+
# greenlet: The greenlet tends to stay alive. This is
|
| 664 |
+
# because throwing the exception captures stack frames
|
| 665 |
+
# (regardless of what we do with the argument) and those
|
| 666 |
+
# get saved. In addition to this object having
|
| 667 |
+
# ``gr_frame`` pointing to this method, which contains
|
| 668 |
+
# ``self``, which points to the parent, and both of which point to
|
| 669 |
+
# an internal thread state dict that points back to the current greenlet for the thread,
|
| 670 |
+
# which is likely to be the parent: a cycle.
|
| 671 |
+
#
|
| 672 |
+
# We can't have ``join()`` tell us to finish, because we
|
| 673 |
+
# need to be able to resume after this throw. The only way
|
| 674 |
+
# to dispose of the greenlet is to use ``self.destroy()``.
|
| 675 |
+
|
| 676 |
+
debug = []
|
| 677 |
+
if hasattr(loop, 'debug'):
|
| 678 |
+
debug = loop.debug()
|
| 679 |
+
loop = None
|
| 680 |
+
|
| 681 |
+
self.parent.throw(LoopExit('This operation would block forever',
|
| 682 |
+
self,
|
| 683 |
+
debug))
|
| 684 |
+
# Execution could resume here if another blocking API call is made
|
| 685 |
+
# in the same thread and the hub hasn't been destroyed, so clean
|
| 686 |
+
# up anything left.
|
| 687 |
+
debug = None
|
| 688 |
+
|
| 689 |
+
def start_periodic_monitoring_thread(self):
|
| 690 |
+
if self.periodic_monitoring_thread is None and GEVENT_CONFIG.monitor_thread:
|
| 691 |
+
# Note that it is possible for one real thread to
|
| 692 |
+
# (temporarily) wind up with multiple monitoring threads,
|
| 693 |
+
# if hubs are started and stopped within the thread. This shows up
|
| 694 |
+
# in the threadpool tests. The monitoring threads will eventually notice their
|
| 695 |
+
# hub object is gone.
|
| 696 |
+
from gevent._monitor import PeriodicMonitoringThread
|
| 697 |
+
from gevent.events import PeriodicMonitorThreadStartedEvent
|
| 698 |
+
from gevent.events import notify_and_call_entry_points
|
| 699 |
+
self.periodic_monitoring_thread = PeriodicMonitoringThread(self)
|
| 700 |
+
|
| 701 |
+
if self.main_hub:
|
| 702 |
+
self.periodic_monitoring_thread.install_monitor_memory_usage()
|
| 703 |
+
|
| 704 |
+
notify_and_call_entry_points(PeriodicMonitorThreadStartedEvent(
|
| 705 |
+
self.periodic_monitoring_thread))
|
| 706 |
+
|
| 707 |
+
return self.periodic_monitoring_thread
|
| 708 |
+
|
| 709 |
+
def join(self, timeout=None):
|
| 710 |
+
"""
|
| 711 |
+
Wait for the event loop to finish. Exits only when there
|
| 712 |
+
are no more spawned greenlets, started servers, active
|
| 713 |
+
timeouts or watchers.
|
| 714 |
+
|
| 715 |
+
.. caution:: This doesn't clean up all resources associated
|
| 716 |
+
with the hub. For that, see :meth:`destroy`.
|
| 717 |
+
|
| 718 |
+
:param float timeout: If *timeout* is provided, wait no longer
|
| 719 |
+
than the specified number of seconds.
|
| 720 |
+
|
| 721 |
+
:return: `True` if this method returns because the loop
|
| 722 |
+
finished execution. Or `False` if the timeout
|
| 723 |
+
expired.
|
| 724 |
+
"""
|
| 725 |
+
assert getcurrent() is self.parent, "only possible from the MAIN greenlet"
|
| 726 |
+
if self.dead:
|
| 727 |
+
return True
|
| 728 |
+
|
| 729 |
+
waiter = Waiter(self)
|
| 730 |
+
|
| 731 |
+
if timeout is not None:
|
| 732 |
+
timeout = self.loop.timer(timeout, ref=False)
|
| 733 |
+
timeout.start(waiter.switch, None)
|
| 734 |
+
|
| 735 |
+
try:
|
| 736 |
+
try:
|
| 737 |
+
# Switch to the hub greenlet and let it continue.
|
| 738 |
+
# Since we're the parent greenlet of the hub, when it exits
|
| 739 |
+
# by `parent.throw(LoopExit)`, control will resume here.
|
| 740 |
+
# If the timer elapses, however, ``waiter.switch()`` is called and
|
| 741 |
+
# again control resumes here, but without an exception.
|
| 742 |
+
waiter.get()
|
| 743 |
+
except LoopExit:
|
| 744 |
+
# Control will immediately be returned to this greenlet.
|
| 745 |
+
return True
|
| 746 |
+
finally:
|
| 747 |
+
# Clean up as much junk as we can. There is a small cycle in the frames,
|
| 748 |
+
# and it won't be GC'd.
|
| 749 |
+
# this greenlet -> this frame
|
| 750 |
+
# this greenlet -> the exception that was thrown
|
| 751 |
+
# the exception that was thrown -> a bunch of other frames, including this frame.
|
| 752 |
+
# some frame calling self.run() -> self
|
| 753 |
+
del waiter # this frame -> waiter -> self
|
| 754 |
+
del self # this frame -> self
|
| 755 |
+
if timeout is not None:
|
| 756 |
+
timeout.stop()
|
| 757 |
+
timeout.close()
|
| 758 |
+
del timeout
|
| 759 |
+
return False
|
| 760 |
+
|
| 761 |
+
def destroy(self, destroy_loop=None):
|
| 762 |
+
"""
|
| 763 |
+
Destroy this hub and clean up its resources.
|
| 764 |
+
|
| 765 |
+
If you manually create hubs, or you use a hub or the gevent
|
| 766 |
+
blocking API from multiple native threads, you *should* call this
|
| 767 |
+
method before disposing of the hub object reference. Ideally,
|
| 768 |
+
this should be called from the same thread running the hub, but
|
| 769 |
+
it can be called from other threads after that thread has exited.
|
| 770 |
+
|
| 771 |
+
Once this is done, it is impossible to continue running the
|
| 772 |
+
hub. Attempts to use the blocking gevent API with pre-existing
|
| 773 |
+
objects from this native thread and bound to this hub will fail.
|
| 774 |
+
|
| 775 |
+
.. versionchanged:: 20.5.1
|
| 776 |
+
Attempt to ensure that Python stack frames and greenlets referenced by this
|
| 777 |
+
hub are cleaned up. This guarantees that switching to the hub again
|
| 778 |
+
is not safe after this. (It was never safe, but it's even less safe.)
|
| 779 |
+
|
| 780 |
+
Note that this only works if the hub is destroyed in the same thread it
|
| 781 |
+
is running in. If the hub is destroyed by a different thread
|
| 782 |
+
after a ``fork()``, for example, expect some garbage to leak.
|
| 783 |
+
"""
|
| 784 |
+
if destroy_loop is None:
|
| 785 |
+
destroy_loop = not self.loop.default
|
| 786 |
+
|
| 787 |
+
if self.periodic_monitoring_thread is not None:
|
| 788 |
+
self.periodic_monitoring_thread.kill()
|
| 789 |
+
self.periodic_monitoring_thread = None
|
| 790 |
+
if self._resolver is not None:
|
| 791 |
+
self._resolver.close()
|
| 792 |
+
del self._resolver
|
| 793 |
+
if self._threadpool is not None:
|
| 794 |
+
self._threadpool.kill()
|
| 795 |
+
del self._threadpool
|
| 796 |
+
|
| 797 |
+
# Let the frame be cleaned up by causing the run() function to
|
| 798 |
+
# exit. This is the only way to guarantee that the hub itself
|
| 799 |
+
# and the main greenlet, if this was a secondary thread, get
|
| 800 |
+
# cleaned up. Otherwise there are likely to be reference
|
| 801 |
+
# cycles still around. We MUST do this before we destroy the
|
| 802 |
+
# loop; if we destroy the loop and then switch into the hub,
|
| 803 |
+
# things will go VERY, VERY wrong (because we will have destroyed
|
| 804 |
+
# the C datastructures in the middle of the C function that's
|
| 805 |
+
# using them; the best we can hope for is a segfault).
|
| 806 |
+
try:
|
| 807 |
+
self.throw(HubDestroyed(destroy_loop))
|
| 808 |
+
except LoopExit:
|
| 809 |
+
# Expected.
|
| 810 |
+
pass
|
| 811 |
+
except GreenletError:
|
| 812 |
+
# Must be coming from a different thread.
|
| 813 |
+
# Note that python stack frames are likely to leak
|
| 814 |
+
# in this case.
|
| 815 |
+
pass
|
| 816 |
+
|
| 817 |
+
if destroy_loop:
|
| 818 |
+
if get_loop() is self.loop:
|
| 819 |
+
# Don't let anyone try to reuse this
|
| 820 |
+
set_loop(None)
|
| 821 |
+
self.loop.destroy()
|
| 822 |
+
else:
|
| 823 |
+
# Store in case another hub is created for this
|
| 824 |
+
# thread.
|
| 825 |
+
set_loop(self.loop)
|
| 826 |
+
|
| 827 |
+
self.loop = None
|
| 828 |
+
if _get_hub() is self:
|
| 829 |
+
set_hub(None)
|
| 830 |
+
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
# XXX: We can probably simplify the resolver and threadpool properties.
|
| 834 |
+
|
| 835 |
+
@property
|
| 836 |
+
def resolver_class(self):
|
| 837 |
+
return GEVENT_CONFIG.resolver
|
| 838 |
+
|
| 839 |
+
def _get_resolver(self):
|
| 840 |
+
if self._resolver is None:
|
| 841 |
+
self._resolver = self.resolver_class(hub=self) # pylint:disable=not-callable
|
| 842 |
+
return self._resolver
|
| 843 |
+
|
| 844 |
+
def _set_resolver(self, value):
|
| 845 |
+
self._resolver = value
|
| 846 |
+
|
| 847 |
+
def _del_resolver(self):
|
| 848 |
+
self._resolver = None
|
| 849 |
+
|
| 850 |
+
resolver = property(_get_resolver, _set_resolver, _del_resolver,
|
| 851 |
+
"""
|
| 852 |
+
The DNS resolver that the socket functions will use.
|
| 853 |
+
|
| 854 |
+
.. seealso:: :doc:`/dns`
|
| 855 |
+
""")
|
| 856 |
+
|
| 857 |
+
|
| 858 |
+
@property
|
| 859 |
+
def threadpool_class(self):
|
| 860 |
+
return GEVENT_CONFIG.threadpool
|
| 861 |
+
|
| 862 |
+
def _get_threadpool(self):
|
| 863 |
+
if self._threadpool is None:
|
| 864 |
+
# pylint:disable=not-callable
|
| 865 |
+
self._threadpool = self.threadpool_class(
|
| 866 |
+
self.threadpool_size,
|
| 867 |
+
hub=self,
|
| 868 |
+
idle_task_timeout=GEVENT_CONFIG.threadpool_idle_task_timeout
|
| 869 |
+
)
|
| 870 |
+
return self._threadpool
|
| 871 |
+
|
| 872 |
+
def _set_threadpool(self, value):
|
| 873 |
+
self._threadpool = value
|
| 874 |
+
|
| 875 |
+
def _del_threadpool(self):
|
| 876 |
+
self._threadpool = None
|
| 877 |
+
|
| 878 |
+
threadpool = property(_get_threadpool, _set_threadpool, _del_threadpool,
|
| 879 |
+
"""
|
| 880 |
+
The threadpool associated with this hub.
|
| 881 |
+
|
| 882 |
+
Usually this is a
|
| 883 |
+
:class:`gevent.threadpool.ThreadPool`, but
|
| 884 |
+
you :attr:`can customize that
|
| 885 |
+
<gevent._config.Config.threadpool>`.
|
| 886 |
+
|
| 887 |
+
Use this object to schedule blocking
|
| 888 |
+
(non-cooperative) operations in a different
|
| 889 |
+
thread to prevent them from halting the event loop.
|
| 890 |
+
""")
|
| 891 |
+
|
| 892 |
+
|
| 893 |
+
set_default_hub_class(Hub)
|
| 894 |
+
|
| 895 |
+
|
| 896 |
+
|
| 897 |
+
class linkproxy(object):
|
| 898 |
+
__slots__ = ['callback', 'obj']
|
| 899 |
+
|
| 900 |
+
def __init__(self, callback, obj):
|
| 901 |
+
self.callback = callback
|
| 902 |
+
self.obj = obj
|
| 903 |
+
|
| 904 |
+
def __call__(self, *args):
|
| 905 |
+
callback = self.callback
|
| 906 |
+
obj = self.obj
|
| 907 |
+
self.callback = None
|
| 908 |
+
self.obj = None
|
| 909 |
+
callback(obj)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from __future__ import absolute_import
|
| 3 |
+
from __future__ import division
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
# Nothing public here
|
| 7 |
+
__all__ = []
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libev/_corecffi_build.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable=no-member
|
| 2 |
+
|
| 3 |
+
# This module is only used to create and compile the gevent._corecffi module;
|
| 4 |
+
# nothing should be directly imported from it except `ffi`, which should only be
|
| 5 |
+
# used for `ffi.compile()`; programs should import gevent._corecfffi.
|
| 6 |
+
# However, because we are using "out-of-line" mode, it is necessary to examine
|
| 7 |
+
# this file to know what functions are created and available on the generated
|
| 8 |
+
# module.
|
| 9 |
+
from __future__ import absolute_import, print_function
|
| 10 |
+
import sys
|
| 11 |
+
import os
|
| 12 |
+
import os.path # pylint:disable=no-name-in-module
|
| 13 |
+
from cffi import FFI
|
| 14 |
+
|
| 15 |
+
sys.path.append(".")
|
| 16 |
+
try:
|
| 17 |
+
import _setuplibev
|
| 18 |
+
import _setuputils
|
| 19 |
+
except ImportError:
|
| 20 |
+
print("This file must be imported with setup.py in the current working dir.")
|
| 21 |
+
raise
|
| 22 |
+
|
| 23 |
+
thisdir = os.path.dirname(os.path.abspath(__file__))
|
| 24 |
+
parentdir = os.path.abspath(os.path.join(thisdir, '..'))
|
| 25 |
+
setup_dir = os.path.abspath(os.path.join(thisdir, '..', '..', '..'))
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
__all__ = []
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
ffi = FFI()
|
| 32 |
+
distutils_ext = _setuplibev.build_extension()
|
| 33 |
+
|
| 34 |
+
def read_source(name):
|
| 35 |
+
# pylint:disable=unspecified-encoding
|
| 36 |
+
with open(os.path.join(thisdir, name), 'r') as f:
|
| 37 |
+
return f.read()
|
| 38 |
+
|
| 39 |
+
# cdef goes to the cffi library and determines what can be used in
|
| 40 |
+
# Python.
|
| 41 |
+
_cdef = read_source('_corecffi_cdef.c')
|
| 42 |
+
|
| 43 |
+
# These defines and uses help keep the C file readable and lintable by
|
| 44 |
+
# C tools.
|
| 45 |
+
_cdef = _cdef.replace('#define GEVENT_STRUCT_DONE int', '')
|
| 46 |
+
_cdef = _cdef.replace("GEVENT_STRUCT_DONE _;", '...;')
|
| 47 |
+
|
| 48 |
+
_cdef = _cdef.replace('#define GEVENT_ST_NLINK_T int',
|
| 49 |
+
'typedef int... nlink_t;')
|
| 50 |
+
_cdef = _cdef.replace('GEVENT_ST_NLINK_T', 'nlink_t')
|
| 51 |
+
|
| 52 |
+
if _setuplibev.LIBEV_EMBED:
|
| 53 |
+
# Arrange access to the loop internals
|
| 54 |
+
_cdef += """
|
| 55 |
+
struct ev_loop {
|
| 56 |
+
int backend_fd;
|
| 57 |
+
int activecnt;
|
| 58 |
+
...;
|
| 59 |
+
};
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
# arrange to be configured.
|
| 63 |
+
_setuputils.ConfiguringBuildExt.gevent_add_pre_run_action(distutils_ext.configure)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
if sys.platform.startswith('win'):
|
| 67 |
+
# We must have the vfd_open, etc, functions on
|
| 68 |
+
# Windows. But on other platforms, going through
|
| 69 |
+
# CFFI to just return the file-descriptor is slower
|
| 70 |
+
# than just doing it in Python, so we check for and
|
| 71 |
+
# workaround their absence in corecffi.py
|
| 72 |
+
_cdef += """
|
| 73 |
+
typedef int... vfd_socket_t;
|
| 74 |
+
int vfd_open(vfd_socket_t);
|
| 75 |
+
vfd_socket_t vfd_get(int);
|
| 76 |
+
void vfd_free(int);
|
| 77 |
+
"""
|
| 78 |
+
|
| 79 |
+
# source goes to the C compiler
|
| 80 |
+
_source = read_source('_corecffi_source.c')
|
| 81 |
+
|
| 82 |
+
macros = list(distutils_ext.define_macros)
|
| 83 |
+
try:
|
| 84 |
+
# We need the data pointer.
|
| 85 |
+
macros.remove(('EV_COMMON', ''))
|
| 86 |
+
except ValueError:
|
| 87 |
+
pass
|
| 88 |
+
|
| 89 |
+
ffi.cdef(_cdef)
|
| 90 |
+
ffi.set_source(
|
| 91 |
+
'gevent.libev._corecffi',
|
| 92 |
+
_source,
|
| 93 |
+
include_dirs=distutils_ext.include_dirs + [
|
| 94 |
+
thisdir, # "libev.h"
|
| 95 |
+
parentdir, # _ffi/alloc.c
|
| 96 |
+
],
|
| 97 |
+
define_macros=macros,
|
| 98 |
+
undef_macros=distutils_ext.undef_macros,
|
| 99 |
+
libraries=distutils_ext.libraries,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
# XXX: Note, on Windows, we would need to specify the external libraries
|
| 104 |
+
# that should be linked in, such as ws2_32 and (because libev_vfd.h makes
|
| 105 |
+
# Python.h calls) the proper Python library---at least for PyPy. I never got
|
| 106 |
+
# that to work though, and calling python functions is strongly discouraged
|
| 107 |
+
# from CFFI code.
|
| 108 |
+
|
| 109 |
+
# On macOS to make the non-embedded case work correctly, against
|
| 110 |
+
# our local copy of libev:
|
| 111 |
+
#
|
| 112 |
+
# 1) configure and make libev
|
| 113 |
+
# 2) CPPFLAGS=-Ideps/libev/ LDFLAGS=-Ldeps/libev/.libs GEVENTSETUP_EMBED_LIBEV=0 \
|
| 114 |
+
# python setup.py build_ext -i
|
| 115 |
+
# 3) export DYLD_LIBRARY_PATH=`pwd`/deps/libev/.libs
|
| 116 |
+
#
|
| 117 |
+
# The DYLD_LIBRARY_PATH is because the linker hard-codes
|
| 118 |
+
# /usr/local/lib/libev.4.dylib in the corecffi.so dylib, because
|
| 119 |
+
# that's the "install name" of the libev dylib that was built.
|
| 120 |
+
# Adding a -rpath to the LDFLAGS doesn't change things.
|
| 121 |
+
# This can be fixed with `install_name_tool`:
|
| 122 |
+
#
|
| 123 |
+
# 3) install_name_tool -change /usr/local/lib/libev.4.dylib \
|
| 124 |
+
# `pwd`/deps/libev/.libs/libev.4.dylib \
|
| 125 |
+
# src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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
|
| 2 |
+
# pylint: disable=no-member
|
| 3 |
+
from __future__ import absolute_import, print_function
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
# pylint: disable=undefined-all-variable
|
| 7 |
+
__all__ = [
|
| 8 |
+
'get_version',
|
| 9 |
+
'get_header_version',
|
| 10 |
+
'supported_backends',
|
| 11 |
+
'recommended_backends',
|
| 12 |
+
'embeddable_backends',
|
| 13 |
+
'time',
|
| 14 |
+
'loop',
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
from zope.interface import implementer
|
| 18 |
+
|
| 19 |
+
from gevent._interfaces import ILoop
|
| 20 |
+
|
| 21 |
+
from gevent.libev import _corecffi # pylint:disable=no-name-in-module,import-error
|
| 22 |
+
|
| 23 |
+
ffi = _corecffi.ffi # pylint:disable=no-member
|
| 24 |
+
libev = _corecffi.lib # pylint:disable=no-member
|
| 25 |
+
|
| 26 |
+
if hasattr(libev, 'vfd_open'):
|
| 27 |
+
# Must be on windows
|
| 28 |
+
# pylint:disable=c-extension-no-member
|
| 29 |
+
assert sys.platform.startswith("win"), "vfd functions only needed on windows"
|
| 30 |
+
vfd_open = libev.vfd_open
|
| 31 |
+
vfd_free = libev.vfd_free
|
| 32 |
+
vfd_get = libev.vfd_get
|
| 33 |
+
else:
|
| 34 |
+
vfd_open = vfd_free = vfd_get = lambda fd: fd
|
| 35 |
+
|
| 36 |
+
libev.gevent_set_ev_alloc()
|
| 37 |
+
|
| 38 |
+
#####
|
| 39 |
+
## NOTE on Windows:
|
| 40 |
+
# The C implementation does several things specially for Windows;
|
| 41 |
+
# a possibly incomplete list is:
|
| 42 |
+
#
|
| 43 |
+
# - the loop runs a periodic signal checker;
|
| 44 |
+
# - the io watcher constructor is different and it has a destructor;
|
| 45 |
+
# - the child watcher is not defined
|
| 46 |
+
#
|
| 47 |
+
# The CFFI implementation does none of these things, and so
|
| 48 |
+
# is possibly NOT FUNCTIONALLY CORRECT on Win32
|
| 49 |
+
#####
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
from gevent._ffi.loop import AbstractCallbacks
|
| 53 |
+
from gevent._ffi.loop import assign_standard_callbacks
|
| 54 |
+
|
| 55 |
+
class _Callbacks(AbstractCallbacks):
|
| 56 |
+
# pylint:disable=arguments-differ,arguments-renamed
|
| 57 |
+
|
| 58 |
+
def python_check_callback(self, *args):
|
| 59 |
+
# There's a pylint bug (pylint 2.9.3, astroid 2.6.2) that causes pylint to crash
|
| 60 |
+
# with an AttributeError on certain types of arguments-differ errors
|
| 61 |
+
# But code in _ffi/loop depends on being able to find the watcher_ptr
|
| 62 |
+
# argument is the local frame. BUT it gets invoked before the function body runs.
|
| 63 |
+
# Hence the override of _find_watcher_ptr_in_traceback.
|
| 64 |
+
# pylint:disable=unused-variable
|
| 65 |
+
_loop, watcher_ptr, _events = args
|
| 66 |
+
AbstractCallbacks.python_check_callback(self, watcher_ptr)
|
| 67 |
+
|
| 68 |
+
def _find_watcher_ptr_in_traceback(self, tb):
|
| 69 |
+
if tb is not None:
|
| 70 |
+
l = tb.tb_frame.f_locals
|
| 71 |
+
if 'watcher_ptr' in l:
|
| 72 |
+
return l['watcher_ptr']
|
| 73 |
+
if 'args' in l and len(l['args']) == 3:
|
| 74 |
+
return l['args'][1]
|
| 75 |
+
return AbstractCallbacks._find_watcher_ptr_in_traceback(self, tb)
|
| 76 |
+
|
| 77 |
+
def python_prepare_callback(self, _loop_ptr, watcher_ptr, _events):
|
| 78 |
+
AbstractCallbacks.python_prepare_callback(self, watcher_ptr)
|
| 79 |
+
|
| 80 |
+
def _find_loop_from_c_watcher(self, watcher_ptr):
|
| 81 |
+
loop_handle = ffi.cast('struct ev_watcher*', watcher_ptr).data
|
| 82 |
+
return self.from_handle(loop_handle)
|
| 83 |
+
|
| 84 |
+
_callbacks = assign_standard_callbacks(ffi, libev, _Callbacks)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
UNDEF = libev.EV_UNDEF
|
| 88 |
+
NONE = libev.EV_NONE
|
| 89 |
+
READ = libev.EV_READ
|
| 90 |
+
WRITE = libev.EV_WRITE
|
| 91 |
+
TIMER = libev.EV_TIMER
|
| 92 |
+
PERIODIC = libev.EV_PERIODIC
|
| 93 |
+
SIGNAL = libev.EV_SIGNAL
|
| 94 |
+
CHILD = libev.EV_CHILD
|
| 95 |
+
STAT = libev.EV_STAT
|
| 96 |
+
IDLE = libev.EV_IDLE
|
| 97 |
+
PREPARE = libev.EV_PREPARE
|
| 98 |
+
CHECK = libev.EV_CHECK
|
| 99 |
+
EMBED = libev.EV_EMBED
|
| 100 |
+
FORK = libev.EV_FORK
|
| 101 |
+
CLEANUP = libev.EV_CLEANUP
|
| 102 |
+
ASYNC = libev.EV_ASYNC
|
| 103 |
+
CUSTOM = libev.EV_CUSTOM
|
| 104 |
+
ERROR = libev.EV_ERROR
|
| 105 |
+
|
| 106 |
+
READWRITE = libev.EV_READ | libev.EV_WRITE
|
| 107 |
+
|
| 108 |
+
MINPRI = libev.EV_MINPRI
|
| 109 |
+
MAXPRI = libev.EV_MAXPRI
|
| 110 |
+
|
| 111 |
+
BACKEND_PORT = libev.EVBACKEND_PORT
|
| 112 |
+
BACKEND_KQUEUE = libev.EVBACKEND_KQUEUE
|
| 113 |
+
BACKEND_EPOLL = libev.EVBACKEND_EPOLL
|
| 114 |
+
BACKEND_POLL = libev.EVBACKEND_POLL
|
| 115 |
+
BACKEND_SELECT = libev.EVBACKEND_SELECT
|
| 116 |
+
FORKCHECK = libev.EVFLAG_FORKCHECK
|
| 117 |
+
NOINOTIFY = libev.EVFLAG_NOINOTIFY
|
| 118 |
+
SIGNALFD = libev.EVFLAG_SIGNALFD
|
| 119 |
+
NOSIGMASK = libev.EVFLAG_NOSIGMASK
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
from gevent._ffi.loop import EVENTS
|
| 123 |
+
GEVENT_CORE_EVENTS = EVENTS
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_version():
|
| 127 |
+
return 'libev-%d.%02d' % (libev.ev_version_major(), libev.ev_version_minor())
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def get_header_version():
|
| 131 |
+
return 'libev-%d.%02d' % (libev.EV_VERSION_MAJOR, libev.EV_VERSION_MINOR)
|
| 132 |
+
|
| 133 |
+
# This list backends in the order they are actually tried by libev,
|
| 134 |
+
# as defined in loop_init. The names must be lower case.
|
| 135 |
+
_flags = [
|
| 136 |
+
# IOCP --- not supported/used.
|
| 137 |
+
(libev.EVBACKEND_PORT, 'port'),
|
| 138 |
+
(libev.EVBACKEND_KQUEUE, 'kqueue'),
|
| 139 |
+
(libev.EVBACKEND_IOURING, 'linux_iouring'),
|
| 140 |
+
(libev.EVBACKEND_LINUXAIO, "linux_aio"),
|
| 141 |
+
(libev.EVBACKEND_EPOLL, 'epoll'),
|
| 142 |
+
(libev.EVBACKEND_POLL, 'poll'),
|
| 143 |
+
(libev.EVBACKEND_SELECT, 'select'),
|
| 144 |
+
|
| 145 |
+
(libev.EVFLAG_NOENV, 'noenv'),
|
| 146 |
+
(libev.EVFLAG_FORKCHECK, 'forkcheck'),
|
| 147 |
+
(libev.EVFLAG_SIGNALFD, 'signalfd'),
|
| 148 |
+
(libev.EVFLAG_NOSIGMASK, 'nosigmask')
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
_flags_str2int = dict((string, flag) for (flag, string) in _flags)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _flags_to_list(flags):
|
| 156 |
+
result = []
|
| 157 |
+
for code, value in _flags:
|
| 158 |
+
if flags & code:
|
| 159 |
+
result.append(value)
|
| 160 |
+
flags &= ~code
|
| 161 |
+
if not flags:
|
| 162 |
+
break
|
| 163 |
+
if flags:
|
| 164 |
+
result.append(flags)
|
| 165 |
+
return result
|
| 166 |
+
|
| 167 |
+
if sys.version_info[0] >= 3:
|
| 168 |
+
basestring = (bytes, str)
|
| 169 |
+
integer_types = (int,)
|
| 170 |
+
else:
|
| 171 |
+
import __builtin__ # pylint:disable=import-error
|
| 172 |
+
basestring = (__builtin__.basestring,)
|
| 173 |
+
integer_types = (int, __builtin__.long)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _flags_to_int(flags):
|
| 177 |
+
# Note, that order does not matter, libev has its own predefined order
|
| 178 |
+
if not flags:
|
| 179 |
+
return 0
|
| 180 |
+
if isinstance(flags, integer_types):
|
| 181 |
+
return flags
|
| 182 |
+
result = 0
|
| 183 |
+
try:
|
| 184 |
+
if isinstance(flags, basestring):
|
| 185 |
+
flags = flags.split(',')
|
| 186 |
+
for value in flags:
|
| 187 |
+
value = value.strip().lower()
|
| 188 |
+
if value:
|
| 189 |
+
result |= _flags_str2int[value]
|
| 190 |
+
except KeyError as ex:
|
| 191 |
+
raise ValueError('Invalid backend or flag: %s\nPossible values: %s' % (ex, ', '.join(sorted(_flags_str2int.keys()))))
|
| 192 |
+
return result
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _str_hex(flag):
|
| 196 |
+
if isinstance(flag, integer_types):
|
| 197 |
+
return hex(flag)
|
| 198 |
+
return str(flag)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def _check_flags(flags):
|
| 202 |
+
as_list = []
|
| 203 |
+
flags &= libev.EVBACKEND_MASK
|
| 204 |
+
if not flags:
|
| 205 |
+
return
|
| 206 |
+
if not flags & libev.EVBACKEND_ALL:
|
| 207 |
+
raise ValueError('Invalid value for backend: 0x%x' % flags)
|
| 208 |
+
if not flags & libev.ev_supported_backends():
|
| 209 |
+
as_list = [_str_hex(x) for x in _flags_to_list(flags)]
|
| 210 |
+
raise ValueError('Unsupported backend: %s' % '|'.join(as_list))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def supported_backends():
|
| 214 |
+
return _flags_to_list(libev.ev_supported_backends())
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def recommended_backends():
|
| 218 |
+
return _flags_to_list(libev.ev_recommended_backends())
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def embeddable_backends():
|
| 222 |
+
return _flags_to_list(libev.ev_embeddable_backends())
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def time():
|
| 226 |
+
return libev.ev_time()
|
| 227 |
+
|
| 228 |
+
from gevent._ffi.loop import AbstractLoop
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
from gevent.libev import watcher as _watchers
|
| 232 |
+
_events_to_str = _watchers._events_to_str # exported
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
@implementer(ILoop)
|
| 236 |
+
class loop(AbstractLoop):
|
| 237 |
+
# pylint:disable=too-many-public-methods
|
| 238 |
+
|
| 239 |
+
# libuv parameters simply won't accept anything lower than 1ms
|
| 240 |
+
# (0.001s), but libev takes fractional seconds. In practice, on
|
| 241 |
+
# one machine, libev can sleep for very small periods of time:
|
| 242 |
+
#
|
| 243 |
+
# sleep(0.00001) -> 0.000024
|
| 244 |
+
# sleep(0.0001) -> 0.000156
|
| 245 |
+
# sleep(0.001) -> 0.00136 (which is comparable to libuv)
|
| 246 |
+
|
| 247 |
+
approx_timer_resolution = 0.00001
|
| 248 |
+
|
| 249 |
+
error_handler = None
|
| 250 |
+
|
| 251 |
+
_CHECK_POINTER = 'struct ev_check *'
|
| 252 |
+
|
| 253 |
+
_PREPARE_POINTER = 'struct ev_prepare *'
|
| 254 |
+
|
| 255 |
+
_TIMER_POINTER = 'struct ev_timer *'
|
| 256 |
+
|
| 257 |
+
def __init__(self, flags=None, default=None):
|
| 258 |
+
AbstractLoop.__init__(self, ffi, libev, _watchers, flags, default)
|
| 259 |
+
self._default = bool(libev.ev_is_default_loop(self._ptr))
|
| 260 |
+
|
| 261 |
+
def _init_loop(self, flags, default):
|
| 262 |
+
c_flags = _flags_to_int(flags)
|
| 263 |
+
_check_flags(c_flags)
|
| 264 |
+
c_flags |= libev.EVFLAG_NOENV
|
| 265 |
+
c_flags |= libev.EVFLAG_FORKCHECK
|
| 266 |
+
if default is None:
|
| 267 |
+
default = True
|
| 268 |
+
if default:
|
| 269 |
+
ptr = libev.gevent_ev_default_loop(c_flags)
|
| 270 |
+
if not ptr:
|
| 271 |
+
raise SystemError("ev_default_loop(%s) failed" % (c_flags, ))
|
| 272 |
+
else:
|
| 273 |
+
ptr = libev.ev_loop_new(c_flags)
|
| 274 |
+
if not ptr:
|
| 275 |
+
raise SystemError("ev_loop_new(%s) failed" % (c_flags, ))
|
| 276 |
+
if default or SYSERR_CALLBACK is None:
|
| 277 |
+
set_syserr_cb(self._handle_syserr)
|
| 278 |
+
|
| 279 |
+
# Mark this loop as being used.
|
| 280 |
+
libev.ev_set_userdata(ptr, ptr)
|
| 281 |
+
return ptr
|
| 282 |
+
|
| 283 |
+
def _init_and_start_check(self):
|
| 284 |
+
libev.ev_check_init(self._check, libev.python_check_callback)
|
| 285 |
+
self._check.data = self._handle_to_self
|
| 286 |
+
libev.ev_check_start(self._ptr, self._check)
|
| 287 |
+
self.unref()
|
| 288 |
+
|
| 289 |
+
def _init_and_start_prepare(self):
|
| 290 |
+
libev.ev_prepare_init(self._prepare, libev.python_prepare_callback)
|
| 291 |
+
libev.ev_prepare_start(self._ptr, self._prepare)
|
| 292 |
+
self.unref()
|
| 293 |
+
|
| 294 |
+
def _init_callback_timer(self):
|
| 295 |
+
libev.ev_timer_init(self._timer0, libev.gevent_noop, 0.0, 0.0)
|
| 296 |
+
|
| 297 |
+
def _stop_callback_timer(self):
|
| 298 |
+
libev.ev_timer_stop(self._ptr, self._timer0)
|
| 299 |
+
|
| 300 |
+
def _start_callback_timer(self):
|
| 301 |
+
libev.ev_timer_start(self._ptr, self._timer0)
|
| 302 |
+
|
| 303 |
+
def _stop_aux_watchers(self):
|
| 304 |
+
super(loop, self)._stop_aux_watchers()
|
| 305 |
+
if libev.ev_is_active(self._prepare):
|
| 306 |
+
self.ref()
|
| 307 |
+
libev.ev_prepare_stop(self._ptr, self._prepare)
|
| 308 |
+
if libev.ev_is_active(self._check):
|
| 309 |
+
self.ref()
|
| 310 |
+
libev.ev_check_stop(self._ptr, self._check)
|
| 311 |
+
if libev.ev_is_active(self._timer0):
|
| 312 |
+
libev.ev_timer_stop(self._timer0)
|
| 313 |
+
|
| 314 |
+
def _setup_for_run_callback(self):
|
| 315 |
+
# XXX: libuv needs to start the callback timer to be sure
|
| 316 |
+
# that the loop wakes up and calls this. Our C version doesn't
|
| 317 |
+
# do this.
|
| 318 |
+
# self._start_callback_timer()
|
| 319 |
+
self.ref() # we should go through the loop now
|
| 320 |
+
|
| 321 |
+
def destroy(self):
|
| 322 |
+
if self._ptr:
|
| 323 |
+
super(loop, self).destroy()
|
| 324 |
+
# pylint:disable=comparison-with-callable
|
| 325 |
+
if globals()["SYSERR_CALLBACK"] == self._handle_syserr:
|
| 326 |
+
set_syserr_cb(None)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def _can_destroy_loop(self, ptr):
|
| 330 |
+
# Is it marked as destroyed?
|
| 331 |
+
return libev.ev_userdata(ptr)
|
| 332 |
+
|
| 333 |
+
def _destroy_loop(self, ptr):
|
| 334 |
+
# Mark as destroyed.
|
| 335 |
+
libev.ev_set_userdata(ptr, ffi.NULL)
|
| 336 |
+
libev.ev_loop_destroy(ptr)
|
| 337 |
+
|
| 338 |
+
libev.gevent_zero_prepare(self._prepare)
|
| 339 |
+
libev.gevent_zero_check(self._check)
|
| 340 |
+
libev.gevent_zero_timer(self._timer0)
|
| 341 |
+
|
| 342 |
+
del self._prepare
|
| 343 |
+
del self._check
|
| 344 |
+
del self._timer0
|
| 345 |
+
|
| 346 |
+
|
| 347 |
+
@property
|
| 348 |
+
def MAXPRI(self):
|
| 349 |
+
return libev.EV_MAXPRI
|
| 350 |
+
|
| 351 |
+
@property
|
| 352 |
+
def MINPRI(self):
|
| 353 |
+
return libev.EV_MINPRI
|
| 354 |
+
|
| 355 |
+
def _default_handle_error(self, context, type, value, tb): # pylint:disable=unused-argument
|
| 356 |
+
super(loop, self)._default_handle_error(context, type, value, tb)
|
| 357 |
+
libev.ev_break(self._ptr, libev.EVBREAK_ONE)
|
| 358 |
+
|
| 359 |
+
def run(self, nowait=False, once=False):
|
| 360 |
+
flags = 0
|
| 361 |
+
if nowait:
|
| 362 |
+
flags |= libev.EVRUN_NOWAIT
|
| 363 |
+
if once:
|
| 364 |
+
flags |= libev.EVRUN_ONCE
|
| 365 |
+
|
| 366 |
+
libev.ev_run(self._ptr, flags)
|
| 367 |
+
|
| 368 |
+
def reinit(self):
|
| 369 |
+
libev.ev_loop_fork(self._ptr)
|
| 370 |
+
|
| 371 |
+
def ref(self):
|
| 372 |
+
libev.ev_ref(self._ptr)
|
| 373 |
+
|
| 374 |
+
def unref(self):
|
| 375 |
+
libev.ev_unref(self._ptr)
|
| 376 |
+
|
| 377 |
+
def break_(self, how=libev.EVBREAK_ONE):
|
| 378 |
+
libev.ev_break(self._ptr, how)
|
| 379 |
+
|
| 380 |
+
def verify(self):
|
| 381 |
+
libev.ev_verify(self._ptr)
|
| 382 |
+
|
| 383 |
+
def now(self):
|
| 384 |
+
return libev.ev_now(self._ptr)
|
| 385 |
+
|
| 386 |
+
def update_now(self):
|
| 387 |
+
libev.ev_now_update(self._ptr)
|
| 388 |
+
|
| 389 |
+
def __repr__(self):
|
| 390 |
+
return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self._format())
|
| 391 |
+
|
| 392 |
+
@property
|
| 393 |
+
def iteration(self):
|
| 394 |
+
return libev.ev_iteration(self._ptr)
|
| 395 |
+
|
| 396 |
+
@property
|
| 397 |
+
def depth(self):
|
| 398 |
+
return libev.ev_depth(self._ptr)
|
| 399 |
+
|
| 400 |
+
@property
|
| 401 |
+
def backend_int(self):
|
| 402 |
+
return libev.ev_backend(self._ptr)
|
| 403 |
+
|
| 404 |
+
@property
|
| 405 |
+
def backend(self):
|
| 406 |
+
backend = libev.ev_backend(self._ptr)
|
| 407 |
+
for key, value in _flags:
|
| 408 |
+
if key == backend:
|
| 409 |
+
return value
|
| 410 |
+
return backend
|
| 411 |
+
|
| 412 |
+
@property
|
| 413 |
+
def pendingcnt(self):
|
| 414 |
+
return libev.ev_pending_count(self._ptr)
|
| 415 |
+
|
| 416 |
+
def closing_fd(self, fd):
|
| 417 |
+
pending_before = libev.ev_pending_count(self._ptr)
|
| 418 |
+
libev.ev_feed_fd_event(self._ptr, fd, 0xFFFF)
|
| 419 |
+
pending_after = libev.ev_pending_count(self._ptr)
|
| 420 |
+
return pending_after > pending_before
|
| 421 |
+
|
| 422 |
+
if sys.platform != "win32":
|
| 423 |
+
|
| 424 |
+
def install_sigchld(self):
|
| 425 |
+
libev.gevent_install_sigchld_handler()
|
| 426 |
+
|
| 427 |
+
def reset_sigchld(self):
|
| 428 |
+
libev.gevent_reset_sigchld_handler()
|
| 429 |
+
|
| 430 |
+
def fileno(self):
|
| 431 |
+
if self._ptr and LIBEV_EMBED:
|
| 432 |
+
# If we don't embed, we can't access these fields,
|
| 433 |
+
# the type is opaque
|
| 434 |
+
fd = self._ptr.backend_fd
|
| 435 |
+
if fd >= 0:
|
| 436 |
+
return fd
|
| 437 |
+
|
| 438 |
+
@property
|
| 439 |
+
def activecnt(self):
|
| 440 |
+
if not self._ptr:
|
| 441 |
+
raise ValueError('operation on destroyed loop')
|
| 442 |
+
if LIBEV_EMBED:
|
| 443 |
+
return self._ptr.activecnt
|
| 444 |
+
return -1
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
@ffi.def_extern()
|
| 448 |
+
def _syserr_cb(msg):
|
| 449 |
+
try:
|
| 450 |
+
msg = ffi.string(msg)
|
| 451 |
+
SYSERR_CALLBACK(msg, ffi.errno)
|
| 452 |
+
except:
|
| 453 |
+
set_syserr_cb(None)
|
| 454 |
+
raise # let cffi print the traceback
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def set_syserr_cb(callback):
|
| 458 |
+
global SYSERR_CALLBACK
|
| 459 |
+
if callback is None:
|
| 460 |
+
libev.ev_set_syserr_cb(ffi.NULL)
|
| 461 |
+
SYSERR_CALLBACK = None
|
| 462 |
+
elif callable(callback):
|
| 463 |
+
libev.ev_set_syserr_cb(libev._syserr_cb)
|
| 464 |
+
SYSERR_CALLBACK = callback
|
| 465 |
+
else:
|
| 466 |
+
raise TypeError('Expected callable or None, got %r' % (callback, ))
|
| 467 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
|
| 2 |
+
# pylint: disable=no-member
|
| 3 |
+
from __future__ import absolute_import, print_function
|
| 4 |
+
import sys
|
| 5 |
+
|
| 6 |
+
from gevent.libev import _corecffi # pylint:disable=no-name-in-module,import-error
|
| 7 |
+
|
| 8 |
+
# Nothing public here
|
| 9 |
+
__all__ = []
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ffi = _corecffi.ffi # pylint:disable=no-member
|
| 13 |
+
libev = _corecffi.lib # pylint:disable=no-member
|
| 14 |
+
|
| 15 |
+
if hasattr(libev, 'vfd_open'):
|
| 16 |
+
# Must be on windows
|
| 17 |
+
# pylint:disable=c-extension-no-member
|
| 18 |
+
assert sys.platform.startswith("win"), "vfd functions only needed on windows"
|
| 19 |
+
vfd_open = libev.vfd_open
|
| 20 |
+
vfd_free = libev.vfd_free
|
| 21 |
+
vfd_get = libev.vfd_get
|
| 22 |
+
else:
|
| 23 |
+
vfd_open = vfd_free = vfd_get = lambda fd: fd
|
| 24 |
+
|
| 25 |
+
#####
|
| 26 |
+
## NOTE on Windows:
|
| 27 |
+
# The C implementation does several things specially for Windows;
|
| 28 |
+
# a possibly incomplete list is:
|
| 29 |
+
#
|
| 30 |
+
# - the loop runs a periodic signal checker;
|
| 31 |
+
# - the io watcher constructor is different and it has a destructor;
|
| 32 |
+
# - the child watcher is not defined
|
| 33 |
+
#
|
| 34 |
+
# The CFFI implementation does none of these things, and so
|
| 35 |
+
# is possibly NOT FUNCTIONALLY CORRECT on Win32
|
| 36 |
+
#####
|
| 37 |
+
_NOARGS = ()
|
| 38 |
+
_events = [(libev.EV_READ, 'READ'),
|
| 39 |
+
(libev.EV_WRITE, 'WRITE'),
|
| 40 |
+
(libev.EV__IOFDSET, '_IOFDSET'),
|
| 41 |
+
(libev.EV_PERIODIC, 'PERIODIC'),
|
| 42 |
+
(libev.EV_SIGNAL, 'SIGNAL'),
|
| 43 |
+
(libev.EV_CHILD, 'CHILD'),
|
| 44 |
+
(libev.EV_STAT, 'STAT'),
|
| 45 |
+
(libev.EV_IDLE, 'IDLE'),
|
| 46 |
+
(libev.EV_PREPARE, 'PREPARE'),
|
| 47 |
+
(libev.EV_CHECK, 'CHECK'),
|
| 48 |
+
(libev.EV_EMBED, 'EMBED'),
|
| 49 |
+
(libev.EV_FORK, 'FORK'),
|
| 50 |
+
(libev.EV_CLEANUP, 'CLEANUP'),
|
| 51 |
+
(libev.EV_ASYNC, 'ASYNC'),
|
| 52 |
+
(libev.EV_CUSTOM, 'CUSTOM'),
|
| 53 |
+
(libev.EV_ERROR, 'ERROR')]
|
| 54 |
+
|
| 55 |
+
from gevent._ffi import watcher as _base
|
| 56 |
+
|
| 57 |
+
def _events_to_str(events):
|
| 58 |
+
return _base.events_to_str(events, _events)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class watcher(_base.watcher):
|
| 63 |
+
_FFI = ffi
|
| 64 |
+
_LIB = libev
|
| 65 |
+
_watcher_prefix = 'ev'
|
| 66 |
+
|
| 67 |
+
# Flags is a bitfield with the following meaning:
|
| 68 |
+
# 0000 -> default, referenced (when active)
|
| 69 |
+
# 0010 -> ev_unref has been called
|
| 70 |
+
# 0100 -> not referenced; independent of 0010
|
| 71 |
+
_flags = 0
|
| 72 |
+
|
| 73 |
+
def __init__(self, _loop, ref=True, priority=None, args=_base._NOARGS):
|
| 74 |
+
if ref:
|
| 75 |
+
self._flags = 0
|
| 76 |
+
else:
|
| 77 |
+
self._flags = 4
|
| 78 |
+
|
| 79 |
+
super(watcher, self).__init__(_loop, ref=ref, priority=priority, args=args)
|
| 80 |
+
|
| 81 |
+
def _watcher_ffi_set_priority(self, priority):
|
| 82 |
+
libev.ev_set_priority(self._watcher, priority)
|
| 83 |
+
|
| 84 |
+
def _watcher_ffi_init(self, args):
|
| 85 |
+
self._watcher_init(self._watcher,
|
| 86 |
+
self._watcher_callback,
|
| 87 |
+
*args)
|
| 88 |
+
|
| 89 |
+
def _watcher_ffi_start(self):
|
| 90 |
+
self._watcher_start(self.loop._ptr, self._watcher)
|
| 91 |
+
|
| 92 |
+
def _watcher_ffi_ref(self):
|
| 93 |
+
if self._flags & 2: # we've told libev we're not referenced
|
| 94 |
+
self.loop.ref()
|
| 95 |
+
self._flags &= ~2
|
| 96 |
+
|
| 97 |
+
def _watcher_ffi_unref(self):
|
| 98 |
+
if self._flags & 6 == 4:
|
| 99 |
+
# We're not referenced, but we haven't told libev that
|
| 100 |
+
self.loop.unref()
|
| 101 |
+
self._flags |= 2 # now we've told libev
|
| 102 |
+
|
| 103 |
+
def _get_ref(self):
|
| 104 |
+
return not self._flags & 4
|
| 105 |
+
|
| 106 |
+
def _set_ref(self, value):
|
| 107 |
+
if value:
|
| 108 |
+
if not self._flags & 4:
|
| 109 |
+
return # ref is already True
|
| 110 |
+
if self._flags & 2: # ev_unref was called, undo
|
| 111 |
+
self.loop.ref()
|
| 112 |
+
self._flags &= ~6 # do not want unref, no outstanding unref
|
| 113 |
+
else:
|
| 114 |
+
if self._flags & 4:
|
| 115 |
+
return # ref is already False
|
| 116 |
+
self._flags |= 4 # we're not referenced
|
| 117 |
+
if not self._flags & 2 and libev.ev_is_active(self._watcher):
|
| 118 |
+
# we haven't told libev we're not referenced, but it thinks we're
|
| 119 |
+
# active so we need to undo that
|
| 120 |
+
self.loop.unref()
|
| 121 |
+
self._flags |= 2 # libev knows we're not referenced
|
| 122 |
+
|
| 123 |
+
ref = property(_get_ref, _set_ref)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _get_priority(self):
|
| 127 |
+
return libev.ev_priority(self._watcher)
|
| 128 |
+
|
| 129 |
+
@_base.not_while_active
|
| 130 |
+
def _set_priority(self, priority):
|
| 131 |
+
libev.ev_set_priority(self._watcher, priority)
|
| 132 |
+
|
| 133 |
+
priority = property(_get_priority, _set_priority)
|
| 134 |
+
|
| 135 |
+
def feed(self, revents, callback, *args):
|
| 136 |
+
self.callback = callback
|
| 137 |
+
self.args = args or _NOARGS
|
| 138 |
+
if self._flags & 6 == 4:
|
| 139 |
+
self.loop.unref()
|
| 140 |
+
self._flags |= 2
|
| 141 |
+
libev.ev_feed_event(self.loop._ptr, self._watcher, revents)
|
| 142 |
+
if not self._flags & 1:
|
| 143 |
+
# Py_INCREF(<PyObjectPtr>self)
|
| 144 |
+
self._flags |= 1
|
| 145 |
+
|
| 146 |
+
@property
|
| 147 |
+
def pending(self):
|
| 148 |
+
return bool(self._watcher and libev.ev_is_pending(self._watcher))
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class io(_base.IoMixin, watcher):
|
| 152 |
+
|
| 153 |
+
EVENT_MASK = libev.EV__IOFDSET | libev.EV_READ | libev.EV_WRITE
|
| 154 |
+
|
| 155 |
+
def _get_fd(self):
|
| 156 |
+
return vfd_get(self._watcher.fd)
|
| 157 |
+
|
| 158 |
+
@_base.not_while_active
|
| 159 |
+
def _set_fd(self, fd):
|
| 160 |
+
vfd = vfd_open(fd)
|
| 161 |
+
vfd_free(self._watcher.fd)
|
| 162 |
+
self._watcher_init(self._watcher, self._watcher_callback, vfd, self._watcher.events)
|
| 163 |
+
|
| 164 |
+
fd = property(_get_fd, _set_fd)
|
| 165 |
+
|
| 166 |
+
def _get_events(self):
|
| 167 |
+
return self._watcher.events
|
| 168 |
+
|
| 169 |
+
@_base.not_while_active
|
| 170 |
+
def _set_events(self, events):
|
| 171 |
+
self._watcher_init(self._watcher, self._watcher_callback, self._watcher.fd, events)
|
| 172 |
+
|
| 173 |
+
events = property(_get_events, _set_events)
|
| 174 |
+
|
| 175 |
+
@property
|
| 176 |
+
def events_str(self):
|
| 177 |
+
return _events_to_str(self._watcher.events)
|
| 178 |
+
|
| 179 |
+
def _format(self):
|
| 180 |
+
return ' fd=%s events=%s' % (self.fd, self.events_str)
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class timer(_base.TimerMixin, watcher):
|
| 184 |
+
|
| 185 |
+
@property
|
| 186 |
+
def at(self):
|
| 187 |
+
return self._watcher.at
|
| 188 |
+
|
| 189 |
+
def again(self, callback, *args, **kw):
|
| 190 |
+
# Exactly the same as start(), just with a different initializer
|
| 191 |
+
# function
|
| 192 |
+
self._watcher_start = libev.ev_timer_again
|
| 193 |
+
try:
|
| 194 |
+
self.start(callback, *args, **kw)
|
| 195 |
+
finally:
|
| 196 |
+
del self._watcher_start
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class signal(_base.SignalMixin, watcher):
|
| 200 |
+
pass
|
| 201 |
+
|
| 202 |
+
class idle(_base.IdleMixin, watcher):
|
| 203 |
+
pass
|
| 204 |
+
|
| 205 |
+
class prepare(_base.PrepareMixin, watcher):
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
class check(_base.CheckMixin, watcher):
|
| 209 |
+
pass
|
| 210 |
+
|
| 211 |
+
class fork(_base.ForkMixin, watcher):
|
| 212 |
+
pass
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
class async_(_base.AsyncMixin, watcher):
|
| 216 |
+
|
| 217 |
+
def send(self):
|
| 218 |
+
libev.ev_async_send(self.loop._ptr, self._watcher)
|
| 219 |
+
|
| 220 |
+
@property
|
| 221 |
+
def pending(self):
|
| 222 |
+
return self._watcher is not None and bool(libev.ev_async_pending(self._watcher))
|
| 223 |
+
|
| 224 |
+
# Provide BWC for those that have async
|
| 225 |
+
locals()['async'] = async_
|
| 226 |
+
|
| 227 |
+
class _ClosedWatcher(object):
|
| 228 |
+
__slots__ = ('pid', 'rpid', 'rstatus')
|
| 229 |
+
|
| 230 |
+
def __init__(self, other):
|
| 231 |
+
self.pid = other.pid
|
| 232 |
+
self.rpid = other.rpid
|
| 233 |
+
self.rstatus = other.rstatus
|
| 234 |
+
|
| 235 |
+
def __bool__(self):
|
| 236 |
+
return False
|
| 237 |
+
__nonzero__ = __bool__
|
| 238 |
+
|
| 239 |
+
class child(_base.ChildMixin, watcher):
|
| 240 |
+
_watcher_type = 'child'
|
| 241 |
+
|
| 242 |
+
def close(self):
|
| 243 |
+
# Capture the properties we defer to our _watcher, because
|
| 244 |
+
# we're about to discard it.
|
| 245 |
+
closed_watcher = _ClosedWatcher(self._watcher)
|
| 246 |
+
super(child, self).close()
|
| 247 |
+
self._watcher = closed_watcher
|
| 248 |
+
|
| 249 |
+
@property
|
| 250 |
+
def pid(self):
|
| 251 |
+
return self._watcher.pid
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def rpid(self):
|
| 255 |
+
return self._watcher.rpid
|
| 256 |
+
|
| 257 |
+
@rpid.setter
|
| 258 |
+
def rpid(self, value):
|
| 259 |
+
self._watcher.rpid = value
|
| 260 |
+
|
| 261 |
+
@property
|
| 262 |
+
def rstatus(self):
|
| 263 |
+
return self._watcher.rstatus
|
| 264 |
+
|
| 265 |
+
@rstatus.setter
|
| 266 |
+
def rstatus(self, value):
|
| 267 |
+
self._watcher.rstatus = value
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class stat(_base.StatMixin, watcher):
|
| 271 |
+
_watcher_type = 'stat'
|
| 272 |
+
|
| 273 |
+
@property
|
| 274 |
+
def attr(self):
|
| 275 |
+
if not self._watcher.attr.st_nlink:
|
| 276 |
+
return
|
| 277 |
+
return self._watcher.attr
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def prev(self):
|
| 281 |
+
if not self._watcher.prev.st_nlink:
|
| 282 |
+
return
|
| 283 |
+
return self._watcher.prev
|
| 284 |
+
|
| 285 |
+
@property
|
| 286 |
+
def interval(self):
|
| 287 |
+
return self._watcher.interval
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/__init__.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
from __future__ import absolute_import
|
| 3 |
+
from __future__ import division
|
| 4 |
+
from __future__ import print_function
|
| 5 |
+
|
| 6 |
+
# Nothing public here
|
| 7 |
+
__all__ = []
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/_corecffi_build.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
# nothing should be directly imported from it except `ffi`, which should only be
|
| 5 |
+
# used for `ffi.compile()`; programs should import gevent._corecfffi.
|
| 6 |
+
# However, because we are using "out-of-line" mode, it is necessary to examine
|
| 7 |
+
# this file to know what functions are created and available on the generated
|
| 8 |
+
# module.
|
| 9 |
+
from __future__ import absolute_import, print_function
|
| 10 |
+
import os
|
| 11 |
+
import os.path # pylint:disable=no-name-in-module
|
| 12 |
+
import platform
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
from cffi import FFI
|
| 16 |
+
|
| 17 |
+
sys.path.append(".")
|
| 18 |
+
|
| 19 |
+
try:
|
| 20 |
+
import _setuputils
|
| 21 |
+
except ImportError:
|
| 22 |
+
print("This file must be imported with setup.py in the current working dir.")
|
| 23 |
+
raise
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = []
|
| 27 |
+
|
| 28 |
+
WIN = sys.platform.startswith('win32')
|
| 29 |
+
LIBUV_EMBED = _setuputils.should_embed('libuv')
|
| 30 |
+
PY2 = sys.version_info[0] == 2
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
ffi = FFI()
|
| 34 |
+
|
| 35 |
+
thisdir = os.path.dirname(os.path.abspath(__file__))
|
| 36 |
+
parentdir = os.path.abspath(os.path.join(thisdir, '..'))
|
| 37 |
+
setup_py_dir = os.path.abspath(os.path.join(thisdir, '..', '..', '..'))
|
| 38 |
+
libuv_dir = os.path.abspath(os.path.join(setup_py_dir, 'deps', 'libuv'))
|
| 39 |
+
|
| 40 |
+
def read_source(name):
|
| 41 |
+
# pylint:disable=unspecified-encoding
|
| 42 |
+
with open(os.path.join(thisdir, name), 'r') as f:
|
| 43 |
+
return f.read()
|
| 44 |
+
|
| 45 |
+
_cdef = read_source('_corecffi_cdef.c')
|
| 46 |
+
_source = read_source('_corecffi_source.c')
|
| 47 |
+
|
| 48 |
+
# These defines and uses help keep the C file readable and lintable by
|
| 49 |
+
# C tools.
|
| 50 |
+
_cdef = _cdef.replace('#define GEVENT_STRUCT_DONE int', '')
|
| 51 |
+
_cdef = _cdef.replace("GEVENT_STRUCT_DONE _;", '...;')
|
| 52 |
+
|
| 53 |
+
# nlink_t is not used in libuv.
|
| 54 |
+
_cdef = _cdef.replace('#define GEVENT_ST_NLINK_T int',
|
| 55 |
+
'')
|
| 56 |
+
_cdef = _cdef.replace('GEVENT_ST_NLINK_T', 'nlink_t')
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
_cdef = _cdef.replace('#define GEVENT_UV_OS_SOCK_T int', '')
|
| 60 |
+
# uv_os_sock_t is int on POSIX and SOCKET on Win32, but socket is
|
| 61 |
+
# just another name for handle, which is just another name for 'void*'
|
| 62 |
+
# which we will treat as an 'unsigned long' or 'unsigned long long'
|
| 63 |
+
# since it comes through 'fileno()' where it has been cast as an int.
|
| 64 |
+
# See class watcher.io
|
| 65 |
+
_void_pointer_as_integer = 'intptr_t'
|
| 66 |
+
_cdef = _cdef.replace("GEVENT_UV_OS_SOCK_T", 'int' if not WIN else _void_pointer_as_integer)
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
LIBUV_INCLUDE_DIRS = [
|
| 72 |
+
os.path.join(libuv_dir, 'include'),
|
| 73 |
+
os.path.join(libuv_dir, 'src'),
|
| 74 |
+
]
|
| 75 |
+
|
| 76 |
+
# Initially based on https://github.com/saghul/pyuv/blob/v1.x/setup_libuv.py
|
| 77 |
+
|
| 78 |
+
def _libuv_source(rel_path):
|
| 79 |
+
# Certain versions of setuptools, notably on windows, are *very*
|
| 80 |
+
# picky about what we feed to sources= "setup() arguments must
|
| 81 |
+
# *always* be /-separated paths relative to the setup.py
|
| 82 |
+
# directory, *never* absolute paths." POSIX doesn't have that issue.
|
| 83 |
+
path = os.path.join('deps', 'libuv', 'src', rel_path)
|
| 84 |
+
return path
|
| 85 |
+
|
| 86 |
+
LIBUV_SOURCES = [
|
| 87 |
+
_libuv_source('fs-poll.c'),
|
| 88 |
+
_libuv_source('inet.c'),
|
| 89 |
+
_libuv_source('threadpool.c'),
|
| 90 |
+
_libuv_source('uv-common.c'),
|
| 91 |
+
_libuv_source('version.c'),
|
| 92 |
+
_libuv_source('uv-data-getter-setters.c'),
|
| 93 |
+
_libuv_source('timer.c'),
|
| 94 |
+
_libuv_source('idna.c'),
|
| 95 |
+
_libuv_source('strscpy.c'),
|
| 96 |
+
# Added between 1.42.0 and 1.44.2; only used
|
| 97 |
+
# on unix in that release, but generic
|
| 98 |
+
_libuv_source('strtok.c'),
|
| 99 |
+
]
|
| 100 |
+
|
| 101 |
+
if WIN:
|
| 102 |
+
LIBUV_SOURCES += [
|
| 103 |
+
_libuv_source('win/async.c'),
|
| 104 |
+
_libuv_source('win/core.c'),
|
| 105 |
+
_libuv_source('win/detect-wakeup.c'),
|
| 106 |
+
_libuv_source('win/dl.c'),
|
| 107 |
+
_libuv_source('win/error.c'),
|
| 108 |
+
_libuv_source('win/fs-event.c'),
|
| 109 |
+
_libuv_source('win/fs.c'),
|
| 110 |
+
# getaddrinfo.c refers to ConvertInterfaceIndexToLuid
|
| 111 |
+
# and ConvertInterfaceLuidToNameA, which are supposedly in iphlpapi.h
|
| 112 |
+
# and iphlpapi.lib/dll. But on Windows 10 with Python 3.5 and VC 14 (Visual Studio 2015),
|
| 113 |
+
# I get an undefined warning from the compiler for those functions and
|
| 114 |
+
# a link error from the linker, so this file can't be included.
|
| 115 |
+
# This is possibly because the functions are defined for Windows Vista, and
|
| 116 |
+
# Python 3.5 builds with at earlier SDK?
|
| 117 |
+
# Fortunately we don't use those functions.
|
| 118 |
+
#_libuv_source('win/getaddrinfo.c'),
|
| 119 |
+
# getnameinfo.c refers to uv__getaddrinfo_translate_error from
|
| 120 |
+
# getaddrinfo.c, which we don't have.
|
| 121 |
+
#_libuv_source('win/getnameinfo.c'),
|
| 122 |
+
_libuv_source('win/handle.c'),
|
| 123 |
+
_libuv_source('win/loop-watcher.c'),
|
| 124 |
+
_libuv_source('win/pipe.c'),
|
| 125 |
+
_libuv_source('win/poll.c'),
|
| 126 |
+
_libuv_source('win/process-stdio.c'),
|
| 127 |
+
_libuv_source('win/process.c'),
|
| 128 |
+
_libuv_source('win/signal.c'),
|
| 129 |
+
_libuv_source('win/snprintf.c'),
|
| 130 |
+
_libuv_source('win/stream.c'),
|
| 131 |
+
_libuv_source('win/tcp.c'),
|
| 132 |
+
_libuv_source('win/thread.c'),
|
| 133 |
+
_libuv_source('win/tty.c'),
|
| 134 |
+
_libuv_source('win/udp.c'),
|
| 135 |
+
_libuv_source('win/util.c'),
|
| 136 |
+
_libuv_source('win/winapi.c'),
|
| 137 |
+
_libuv_source('win/winsock.c'),
|
| 138 |
+
]
|
| 139 |
+
else:
|
| 140 |
+
LIBUV_SOURCES += [
|
| 141 |
+
_libuv_source('unix/async.c'),
|
| 142 |
+
_libuv_source('unix/core.c'),
|
| 143 |
+
_libuv_source('unix/dl.c'),
|
| 144 |
+
_libuv_source('unix/fs.c'),
|
| 145 |
+
_libuv_source('unix/getaddrinfo.c'),
|
| 146 |
+
_libuv_source('unix/getnameinfo.c'),
|
| 147 |
+
_libuv_source('unix/loop-watcher.c'),
|
| 148 |
+
_libuv_source('unix/loop.c'),
|
| 149 |
+
_libuv_source('unix/pipe.c'),
|
| 150 |
+
_libuv_source('unix/poll.c'),
|
| 151 |
+
_libuv_source('unix/process.c'),
|
| 152 |
+
_libuv_source('unix/signal.c'),
|
| 153 |
+
_libuv_source('unix/stream.c'),
|
| 154 |
+
_libuv_source('unix/tcp.c'),
|
| 155 |
+
_libuv_source('unix/thread.c'),
|
| 156 |
+
_libuv_source('unix/tty.c'),
|
| 157 |
+
_libuv_source('unix/udp.c'),
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
if sys.platform.startswith('linux'):
|
| 162 |
+
LIBUV_SOURCES += [
|
| 163 |
+
_libuv_source('unix/linux-core.c'),
|
| 164 |
+
_libuv_source('unix/linux-inotify.c'),
|
| 165 |
+
_libuv_source('unix/linux-syscalls.c'),
|
| 166 |
+
_libuv_source('unix/procfs-exepath.c'),
|
| 167 |
+
_libuv_source('unix/proctitle.c'),
|
| 168 |
+
_libuv_source('unix/random-sysctl-linux.c'),
|
| 169 |
+
_libuv_source('unix/epoll.c'),
|
| 170 |
+
]
|
| 171 |
+
elif sys.platform == 'darwin':
|
| 172 |
+
LIBUV_SOURCES += [
|
| 173 |
+
_libuv_source('unix/bsd-ifaddrs.c'),
|
| 174 |
+
_libuv_source('unix/darwin.c'),
|
| 175 |
+
_libuv_source('unix/darwin-proctitle.c'),
|
| 176 |
+
_libuv_source('unix/fsevents.c'),
|
| 177 |
+
_libuv_source('unix/kqueue.c'),
|
| 178 |
+
_libuv_source('unix/proctitle.c'),
|
| 179 |
+
]
|
| 180 |
+
elif sys.platform.startswith(('freebsd', 'dragonfly')): # pragma: no cover
|
| 181 |
+
# Not tested
|
| 182 |
+
LIBUV_SOURCES += [
|
| 183 |
+
_libuv_source('unix/bsd-ifaddrs.c'),
|
| 184 |
+
_libuv_source('unix/freebsd.c'),
|
| 185 |
+
_libuv_source('unix/kqueue.c'),
|
| 186 |
+
_libuv_source('unix/posix-hrtime.c'),
|
| 187 |
+
_libuv_source('unix/bsd-proctitle.c'),
|
| 188 |
+
]
|
| 189 |
+
elif sys.platform.startswith('openbsd'): # pragma: no cover
|
| 190 |
+
# Not tested
|
| 191 |
+
LIBUV_SOURCES += [
|
| 192 |
+
_libuv_source('unix/bsd-ifaddrs.c'),
|
| 193 |
+
_libuv_source('unix/kqueue.c'),
|
| 194 |
+
_libuv_source('unix/openbsd.c'),
|
| 195 |
+
_libuv_source('unix/posix-hrtime.c'),
|
| 196 |
+
_libuv_source('unix/bsd-proctitle.c'),
|
| 197 |
+
]
|
| 198 |
+
elif sys.platform.startswith('netbsd'): # pragma: no cover
|
| 199 |
+
# Not tested
|
| 200 |
+
LIBUV_SOURCES += [
|
| 201 |
+
_libuv_source('unix/bsd-ifaddrs.c'),
|
| 202 |
+
_libuv_source('unix/kqueue.c'),
|
| 203 |
+
_libuv_source('unix/netbsd.c'),
|
| 204 |
+
_libuv_source('unix/posix-hrtime.c'),
|
| 205 |
+
_libuv_source('unix/bsd-proctitle.c'),
|
| 206 |
+
]
|
| 207 |
+
elif sys.platform.startswith('sunos'): # pragma: no cover
|
| 208 |
+
# Not tested.
|
| 209 |
+
LIBUV_SOURCES += [
|
| 210 |
+
_libuv_source('unix/no-proctitle.c'),
|
| 211 |
+
_libuv_source('unix/sunos.c'),
|
| 212 |
+
]
|
| 213 |
+
elif sys.platform.startswith('aix'): # pragma: no cover
|
| 214 |
+
# Not tested.
|
| 215 |
+
LIBUV_SOURCES += [
|
| 216 |
+
_libuv_source('unix/aix.c'),
|
| 217 |
+
_libuv_source('unix/aix-common.c'),
|
| 218 |
+
]
|
| 219 |
+
elif sys.platform.startswith('haiku'): # pragma: no cover
|
| 220 |
+
# Not tested
|
| 221 |
+
LIBUV_SOURCES += [
|
| 222 |
+
_libuv_source('unix/haiku.c')
|
| 223 |
+
]
|
| 224 |
+
elif sys.platform.startswith('cygwin'): # pragma: no cover
|
| 225 |
+
# Not tested.
|
| 226 |
+
|
| 227 |
+
# Based on Cygwin package sources /usr/src/libuv-1.32.0-1.src/libuv-1.32.0/Makefile.am
|
| 228 |
+
# Apparently the same upstream at https://github.com/libuv/libuv/blob/v1.x/Makefile.am
|
| 229 |
+
LIBUV_SOURCES += [
|
| 230 |
+
_libuv_source('unix/cygwin.c'),
|
| 231 |
+
_libuv_source('unix/bsd-ifaddrs.c'),
|
| 232 |
+
_libuv_source('unix/no-fsevents.c'),
|
| 233 |
+
_libuv_source('unix/no-proctitle.c'),
|
| 234 |
+
_libuv_source('unix/posix-hrtime.c'),
|
| 235 |
+
_libuv_source('unix/posix-poll.c'),
|
| 236 |
+
_libuv_source('unix/procfs-exepath.c'),
|
| 237 |
+
_libuv_source('unix/sysinfo-loadavg.c'),
|
| 238 |
+
_libuv_source('unix/sysinfo-memory.c'),
|
| 239 |
+
]
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
LIBUV_MACROS = [
|
| 243 |
+
('LIBUV_EMBED', int(LIBUV_EMBED)),
|
| 244 |
+
]
|
| 245 |
+
|
| 246 |
+
def _define_macro(name, value):
|
| 247 |
+
LIBUV_MACROS.append((name, value))
|
| 248 |
+
|
| 249 |
+
LIBUV_LIBRARIES = []
|
| 250 |
+
|
| 251 |
+
def _add_library(name):
|
| 252 |
+
LIBUV_LIBRARIES.append(name)
|
| 253 |
+
|
| 254 |
+
if sys.platform != 'win32':
|
| 255 |
+
_define_macro('_LARGEFILE_SOURCE', 1)
|
| 256 |
+
_define_macro('_FILE_OFFSET_BITS', 64)
|
| 257 |
+
|
| 258 |
+
if sys.platform.startswith('linux'):
|
| 259 |
+
_add_library('dl')
|
| 260 |
+
_add_library('rt')
|
| 261 |
+
_define_macro('_GNU_SOURCE', 1)
|
| 262 |
+
_define_macro('_POSIX_C_SOURCE', '200112')
|
| 263 |
+
elif sys.platform == 'darwin':
|
| 264 |
+
_define_macro('_DARWIN_USE_64_BIT_INODE', 1)
|
| 265 |
+
_define_macro('_DARWIN_UNLIMITED_SELECT', 1)
|
| 266 |
+
elif sys.platform.startswith('netbsd'): # pragma: no cover
|
| 267 |
+
_add_library('kvm')
|
| 268 |
+
elif sys.platform.startswith('sunos'): # pragma: no cover
|
| 269 |
+
_define_macro('__EXTENSIONS__', 1)
|
| 270 |
+
_define_macro('_XOPEN_SOURCE', 500)
|
| 271 |
+
_define_macro('_REENTRANT', 1)
|
| 272 |
+
_add_library('kstat')
|
| 273 |
+
_add_library('nsl')
|
| 274 |
+
_add_library('sendfile')
|
| 275 |
+
_add_library('socket')
|
| 276 |
+
if platform.release() == '5.10':
|
| 277 |
+
# https://github.com/libuv/libuv/issues/1458
|
| 278 |
+
# https://github.com/giampaolo/psutil/blob/4d6a086411c77b7909cce8f4f141bbdecfc0d354/setup.py#L298-L300
|
| 279 |
+
_define_macro('SUNOS_NO_IFADDRS', '')
|
| 280 |
+
elif sys.platform.startswith('aix'): # pragma: no cover
|
| 281 |
+
_define_macro('_LINUX_SOURCE_COMPAT', 1)
|
| 282 |
+
if os.uname().sysname != 'OS400':
|
| 283 |
+
_add_library('perfstat')
|
| 284 |
+
elif WIN:
|
| 285 |
+
# All other gevent .pyd files link to the specific minor-version Python
|
| 286 |
+
# DLL, so we should do the same here. In virtual environments that don't
|
| 287 |
+
# contain the major-version python?.dll stub, _corecffi.pyd would otherwise
|
| 288 |
+
# cause the Windows DLL loader to search the entire PATH for a DLL with
|
| 289 |
+
# that name. This might end up bringing a second, ABI-incompatible Python
|
| 290 |
+
# version into the process, which can easily lead to crashes.
|
| 291 |
+
# See https://github.com/gevent/gevent/pull/1814/files
|
| 292 |
+
_define_macro('_CFFI_NO_LIMITED_API', 1)
|
| 293 |
+
|
| 294 |
+
_define_macro('_GNU_SOURCE', 1)
|
| 295 |
+
_define_macro('WIN32', 1)
|
| 296 |
+
_define_macro('_CRT_SECURE_NO_DEPRECATE', 1)
|
| 297 |
+
_define_macro('_CRT_NONSTDC_NO_DEPRECATE', 1)
|
| 298 |
+
_define_macro('_CRT_SECURE_NO_WARNINGS', 1)
|
| 299 |
+
_define_macro('_WIN32_WINNT', '0x0602')
|
| 300 |
+
_define_macro('WIN32_LEAN_AND_MEAN', 1)
|
| 301 |
+
# This value isn't available on the platform that we build and
|
| 302 |
+
# test Python 2.7 on. It's used for getting power management
|
| 303 |
+
# suspend/resume notifications, maybe for keeping timers accurate?
|
| 304 |
+
#
|
| 305 |
+
# TODO: This should be a more targeted check based on the platform
|
| 306 |
+
# version, but that's complicated because it depends on having a
|
| 307 |
+
# particular patch installed to the OS, and I don't know how to
|
| 308 |
+
# check for that...but we're dropping Python 2 support soon, so
|
| 309 |
+
# I suspect it really doesn't matter.
|
| 310 |
+
if PY2:
|
| 311 |
+
_define_macro('LOAD_LIBRARY_SEARCH_SYSTEM32', 0)
|
| 312 |
+
_add_library('advapi32')
|
| 313 |
+
_add_library('iphlpapi')
|
| 314 |
+
_add_library('psapi')
|
| 315 |
+
_add_library('shell32')
|
| 316 |
+
_add_library('user32')
|
| 317 |
+
_add_library('userenv')
|
| 318 |
+
_add_library('ws2_32')
|
| 319 |
+
|
| 320 |
+
if not LIBUV_EMBED:
|
| 321 |
+
del LIBUV_SOURCES[:]
|
| 322 |
+
del LIBUV_INCLUDE_DIRS[:]
|
| 323 |
+
_add_library('uv')
|
| 324 |
+
|
| 325 |
+
LIBUV_INCLUDE_DIRS.append(parentdir)
|
| 326 |
+
|
| 327 |
+
ffi.cdef(_cdef)
|
| 328 |
+
ffi.set_source(
|
| 329 |
+
'gevent.libuv._corecffi',
|
| 330 |
+
_source,
|
| 331 |
+
sources=LIBUV_SOURCES,
|
| 332 |
+
depends=LIBUV_SOURCES,
|
| 333 |
+
include_dirs=LIBUV_INCLUDE_DIRS,
|
| 334 |
+
libraries=list(LIBUV_LIBRARIES),
|
| 335 |
+
define_macros=list(LIBUV_MACROS),
|
| 336 |
+
extra_compile_args=list(_setuputils.IGNORE_THIRD_PARTY_WARNINGS),
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
if __name__ == '__main__':
|
| 340 |
+
# See notes in libev/_corecffi_build.py for how to test this.
|
| 341 |
+
#
|
| 342 |
+
# Other than the obvious directory changes, the changes are:
|
| 343 |
+
#
|
| 344 |
+
# CPPFLAGS=-Ideps/libuv/include/ -Isrc/gevent/
|
| 345 |
+
ffi.compile(verbose=True)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/loop.py
ADDED
|
@@ -0,0 +1,690 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
libuv loop implementation
|
| 3 |
+
"""
|
| 4 |
+
# pylint: disable=no-member
|
| 5 |
+
from __future__ import absolute_import, print_function
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
from collections import defaultdict
|
| 9 |
+
from collections import namedtuple
|
| 10 |
+
from operator import delitem
|
| 11 |
+
import signal
|
| 12 |
+
|
| 13 |
+
from zope.interface import implementer
|
| 14 |
+
|
| 15 |
+
from gevent import getcurrent
|
| 16 |
+
from gevent.exceptions import LoopExit
|
| 17 |
+
|
| 18 |
+
from gevent._ffi import _dbg # pylint: disable=unused-import
|
| 19 |
+
from gevent._ffi.loop import AbstractLoop
|
| 20 |
+
from gevent._ffi.loop import assign_standard_callbacks
|
| 21 |
+
from gevent._ffi.loop import AbstractCallbacks
|
| 22 |
+
from gevent._interfaces import ILoop
|
| 23 |
+
from gevent.libuv import _corecffi # pylint:disable=no-name-in-module,import-error
|
| 24 |
+
|
| 25 |
+
ffi = _corecffi.ffi
|
| 26 |
+
libuv = _corecffi.lib
|
| 27 |
+
|
| 28 |
+
__all__ = [
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class _Callbacks(AbstractCallbacks):
|
| 33 |
+
|
| 34 |
+
def _find_loop_from_c_watcher(self, watcher_ptr):
|
| 35 |
+
loop_handle = ffi.cast('uv_handle_t*', watcher_ptr).data
|
| 36 |
+
return self.from_handle(loop_handle) if loop_handle else None
|
| 37 |
+
|
| 38 |
+
def python_sigchld_callback(self, watcher_ptr, _signum):
|
| 39 |
+
self.from_handle(ffi.cast('uv_handle_t*', watcher_ptr).data)._sigchld_callback()
|
| 40 |
+
|
| 41 |
+
def python_timer0_callback(self, watcher_ptr):
|
| 42 |
+
return self.python_prepare_callback(watcher_ptr)
|
| 43 |
+
|
| 44 |
+
def python_queue_callback(self, watcher_ptr, revents):
|
| 45 |
+
watcher_handle = watcher_ptr.data
|
| 46 |
+
the_watcher = self.from_handle(watcher_handle)
|
| 47 |
+
|
| 48 |
+
the_watcher.loop._queue_callback(watcher_ptr, revents)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_callbacks = assign_standard_callbacks(
|
| 52 |
+
ffi, libuv, _Callbacks,
|
| 53 |
+
[
|
| 54 |
+
'python_sigchld_callback',
|
| 55 |
+
'python_timer0_callback',
|
| 56 |
+
'python_queue_callback',
|
| 57 |
+
]
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
from gevent._ffi.loop import EVENTS
|
| 61 |
+
GEVENT_CORE_EVENTS = EVENTS # export
|
| 62 |
+
|
| 63 |
+
from gevent.libuv import watcher as _watchers # pylint:disable=no-name-in-module
|
| 64 |
+
|
| 65 |
+
_events_to_str = _watchers._events_to_str # export
|
| 66 |
+
|
| 67 |
+
READ = libuv.UV_READABLE
|
| 68 |
+
WRITE = libuv.UV_WRITABLE
|
| 69 |
+
|
| 70 |
+
def get_version():
|
| 71 |
+
uv_bytes = ffi.string(libuv.uv_version_string())
|
| 72 |
+
if not isinstance(uv_bytes, str):
|
| 73 |
+
# Py3
|
| 74 |
+
uv_str = uv_bytes.decode("ascii")
|
| 75 |
+
else:
|
| 76 |
+
uv_str = uv_bytes
|
| 77 |
+
|
| 78 |
+
return 'libuv-' + uv_str
|
| 79 |
+
|
| 80 |
+
def get_header_version():
|
| 81 |
+
return 'libuv-%d.%d.%d' % (libuv.UV_VERSION_MAJOR, libuv.UV_VERSION_MINOR, libuv.UV_VERSION_PATCH)
|
| 82 |
+
|
| 83 |
+
def supported_backends():
|
| 84 |
+
return ['default']
|
| 85 |
+
|
| 86 |
+
libuv.gevent_set_uv_alloc()
|
| 87 |
+
|
| 88 |
+
@implementer(ILoop)
|
| 89 |
+
class loop(AbstractLoop):
|
| 90 |
+
|
| 91 |
+
# libuv parameters simply won't accept anything lower than 1ms. In
|
| 92 |
+
# practice, looping on gevent.sleep(0.001) takes about 0.00138 s
|
| 93 |
+
# (+- 0.000036s)
|
| 94 |
+
approx_timer_resolution = 0.001 # 1ms
|
| 95 |
+
|
| 96 |
+
# It's relatively more expensive to break from the callback loop
|
| 97 |
+
# because we don't do it "inline" from C, we're looping in Python
|
| 98 |
+
CALLBACK_CHECK_COUNT = max(AbstractLoop.CALLBACK_CHECK_COUNT, 100)
|
| 99 |
+
|
| 100 |
+
# Defines the maximum amount of time the loop will sleep waiting for IO,
|
| 101 |
+
# which is also the interval at which signals are checked and handled.
|
| 102 |
+
SIGNAL_CHECK_INTERVAL_MS = 300
|
| 103 |
+
|
| 104 |
+
error_handler = None
|
| 105 |
+
|
| 106 |
+
_CHECK_POINTER = 'uv_check_t *'
|
| 107 |
+
|
| 108 |
+
_PREPARE_POINTER = 'uv_prepare_t *'
|
| 109 |
+
_PREPARE_CALLBACK_SIG = "void(*)(void*)"
|
| 110 |
+
|
| 111 |
+
_TIMER_POINTER = _CHECK_POINTER # This is poorly named. It's for the callback "timer"
|
| 112 |
+
|
| 113 |
+
def __init__(self, flags=None, default=None):
|
| 114 |
+
AbstractLoop.__init__(self, ffi, libuv, _watchers, flags, default)
|
| 115 |
+
self._child_watchers = defaultdict(list)
|
| 116 |
+
self._io_watchers = {}
|
| 117 |
+
self._fork_watchers = set()
|
| 118 |
+
self._pid = os.getpid()
|
| 119 |
+
# pylint:disable-next=superfluous-parens
|
| 120 |
+
self._default = (self._ptr == libuv.uv_default_loop())
|
| 121 |
+
self._queued_callbacks = []
|
| 122 |
+
|
| 123 |
+
def _queue_callback(self, watcher_ptr, revents):
|
| 124 |
+
self._queued_callbacks.append((watcher_ptr, revents))
|
| 125 |
+
|
| 126 |
+
def _init_loop(self, flags, default):
|
| 127 |
+
if default is None:
|
| 128 |
+
default = True
|
| 129 |
+
# Unlike libev, libuv creates a new default
|
| 130 |
+
# loop automatically if the old default loop was
|
| 131 |
+
# closed.
|
| 132 |
+
|
| 133 |
+
if default:
|
| 134 |
+
# XXX: If the default loop had been destroyed, this
|
| 135 |
+
# will create a new one, but we won't destroy it
|
| 136 |
+
ptr = libuv.uv_default_loop()
|
| 137 |
+
else:
|
| 138 |
+
ptr = libuv.uv_loop_new()
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
if not ptr:
|
| 142 |
+
raise SystemError("Failed to get loop")
|
| 143 |
+
|
| 144 |
+
# Track whether or not any object has destroyed
|
| 145 |
+
# this loop. See _can_destroy_default_loop
|
| 146 |
+
ptr.data = self._handle_to_self
|
| 147 |
+
return ptr
|
| 148 |
+
|
| 149 |
+
_signal_idle = None
|
| 150 |
+
|
| 151 |
+
@property
|
| 152 |
+
def ptr(self):
|
| 153 |
+
if not self._ptr:
|
| 154 |
+
return None
|
| 155 |
+
if self._ptr and not self._ptr.data:
|
| 156 |
+
# Another instance of the Python loop destroyed
|
| 157 |
+
# the C loop. It was probably the default.
|
| 158 |
+
self._ptr = None
|
| 159 |
+
return self._ptr
|
| 160 |
+
|
| 161 |
+
def _init_and_start_check(self):
|
| 162 |
+
libuv.uv_check_init(self.ptr, self._check)
|
| 163 |
+
libuv.uv_check_start(self._check, libuv.python_check_callback)
|
| 164 |
+
libuv.uv_unref(self._check)
|
| 165 |
+
|
| 166 |
+
# We also have to have an idle watcher to be able to handle
|
| 167 |
+
# signals in a timely manner. Without them, libuv won't loop again
|
| 168 |
+
# and call into its check and prepare handlers.
|
| 169 |
+
# Note that this basically forces us into a busy-loop
|
| 170 |
+
# XXX: As predicted, using an idle watcher causes our process
|
| 171 |
+
# to eat 100% CPU time. We instead use a timer with a max of a .3 second
|
| 172 |
+
# delay to notice signals. Note that this timeout also implements fork
|
| 173 |
+
# watchers, effectively.
|
| 174 |
+
|
| 175 |
+
# XXX: Perhaps we could optimize this to notice when there are other
|
| 176 |
+
# timers in the loop and start/stop it then. When we have a callback
|
| 177 |
+
# scheduled, this should also be the same and unnecessary?
|
| 178 |
+
# libev does takes this basic approach on Windows.
|
| 179 |
+
self._signal_idle = ffi.new("uv_timer_t*")
|
| 180 |
+
libuv.uv_timer_init(self.ptr, self._signal_idle)
|
| 181 |
+
self._signal_idle.data = self._handle_to_self
|
| 182 |
+
sig_cb = ffi.cast('void(*)(uv_timer_t*)', libuv.python_check_callback)
|
| 183 |
+
libuv.uv_timer_start(self._signal_idle,
|
| 184 |
+
sig_cb,
|
| 185 |
+
self.SIGNAL_CHECK_INTERVAL_MS,
|
| 186 |
+
self.SIGNAL_CHECK_INTERVAL_MS)
|
| 187 |
+
libuv.uv_unref(self._signal_idle)
|
| 188 |
+
|
| 189 |
+
def __check_and_die(self):
|
| 190 |
+
if not self.ptr:
|
| 191 |
+
# We've been destroyed during the middle of self.run().
|
| 192 |
+
# This method is being called into from C, and it's not
|
| 193 |
+
# safe to go back to C (Windows in particular can abort
|
| 194 |
+
# the process with "GetQueuedCompletionStatusEx: (6) The
|
| 195 |
+
# handle is invalid.") So switch to the parent greenlet.
|
| 196 |
+
getcurrent().parent.throw(LoopExit('Destroyed during run'))
|
| 197 |
+
|
| 198 |
+
def _run_callbacks(self):
|
| 199 |
+
self.__check_and_die()
|
| 200 |
+
# Manually handle fork watchers.
|
| 201 |
+
curpid = os.getpid()
|
| 202 |
+
if curpid != self._pid:
|
| 203 |
+
self._pid = curpid
|
| 204 |
+
for watcher in self._fork_watchers:
|
| 205 |
+
watcher._on_fork()
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
# The contents of queued_callbacks at this point should be timers
|
| 209 |
+
# that expired when the loop began along with any idle watchers.
|
| 210 |
+
# We need to run them so that any manual callbacks they want to schedule
|
| 211 |
+
# get added to the list and ran next before we go on to poll for IO.
|
| 212 |
+
# This is critical for libuv on linux: closing a socket schedules some manual
|
| 213 |
+
# callbacks to actually stop the watcher; if those don't run before
|
| 214 |
+
# we poll for IO, then libuv can abort the process for the closed file descriptor.
|
| 215 |
+
|
| 216 |
+
# XXX: There's still a race condition here because we may not run *all* the manual
|
| 217 |
+
# callbacks. We need a way to prioritize those.
|
| 218 |
+
|
| 219 |
+
# Running these before the manual callbacks lead to some
|
| 220 |
+
# random test failures. In test__event.TestEvent_SetThenClear
|
| 221 |
+
# we would get a LoopExit sometimes. The problem occurred when
|
| 222 |
+
# a timer expired on entering the first loop; we would process
|
| 223 |
+
# it there, and then process the callback that it created
|
| 224 |
+
# below, leaving nothing for the loop to do. Having the
|
| 225 |
+
# self.run() manually process manual callbacks before
|
| 226 |
+
# continuing solves the problem. (But we must still run callbacks
|
| 227 |
+
# here again.)
|
| 228 |
+
self._prepare_ran_callbacks = self.__run_queued_callbacks()
|
| 229 |
+
|
| 230 |
+
super(loop, self)._run_callbacks()
|
| 231 |
+
|
| 232 |
+
def _init_and_start_prepare(self):
|
| 233 |
+
libuv.uv_prepare_init(self.ptr, self._prepare)
|
| 234 |
+
libuv.uv_prepare_start(self._prepare, libuv.python_prepare_callback)
|
| 235 |
+
libuv.uv_unref(self._prepare)
|
| 236 |
+
|
| 237 |
+
def _init_callback_timer(self):
|
| 238 |
+
libuv.uv_check_init(self.ptr, self._timer0)
|
| 239 |
+
|
| 240 |
+
def _stop_callback_timer(self):
|
| 241 |
+
libuv.uv_check_stop(self._timer0)
|
| 242 |
+
|
| 243 |
+
def _start_callback_timer(self):
|
| 244 |
+
# The purpose of the callback timer is to ensure that we run
|
| 245 |
+
# callbacks as soon as possible on the next iteration of the event loop.
|
| 246 |
+
|
| 247 |
+
# In libev, we set a 0 duration timer with a no-op callback.
|
| 248 |
+
# This executes immediately *after* the IO poll is done (it
|
| 249 |
+
# actually determines the time that the IO poll will block
|
| 250 |
+
# for), so having the timer present simply spins the loop, and
|
| 251 |
+
# our normal prepare watcher kicks in to run the callbacks.
|
| 252 |
+
|
| 253 |
+
# In libuv, however, timers are run *first*, before prepare
|
| 254 |
+
# callbacks and before polling for IO. So a no-op 0 duration
|
| 255 |
+
# timer actually does *nothing*. (Also note that libev queues all
|
| 256 |
+
# watchers found during IO poll to run at the end (I think), while libuv
|
| 257 |
+
# runs them in uv__io_poll itself.)
|
| 258 |
+
|
| 259 |
+
# From the loop inside uv_run:
|
| 260 |
+
# while True:
|
| 261 |
+
# uv__update_time(loop);
|
| 262 |
+
# uv__run_timers(loop);
|
| 263 |
+
# # we don't use pending watchers. They are how libuv
|
| 264 |
+
# # implements the pipe/udp/tcp streams.
|
| 265 |
+
# ran_pending = uv__run_pending(loop);
|
| 266 |
+
# uv__run_idle(loop);
|
| 267 |
+
# uv__run_prepare(loop);
|
| 268 |
+
# ...
|
| 269 |
+
# uv__io_poll(loop, timeout); # <--- IO watchers run here!
|
| 270 |
+
# uv__run_check(loop);
|
| 271 |
+
|
| 272 |
+
# libev looks something like this (pseudo code because the real code is
|
| 273 |
+
# hard to read):
|
| 274 |
+
#
|
| 275 |
+
# do {
|
| 276 |
+
# run_fork_callbacks();
|
| 277 |
+
# run_prepare_callbacks();
|
| 278 |
+
# timeout = min(time of all timers or normal block time)
|
| 279 |
+
# io_poll() # <--- Only queues IO callbacks
|
| 280 |
+
# update_now(); calculate_expired_timers();
|
| 281 |
+
# run callbacks in this order: (although specificying priorities changes it)
|
| 282 |
+
# check
|
| 283 |
+
# stat
|
| 284 |
+
# child
|
| 285 |
+
# signal
|
| 286 |
+
# timer
|
| 287 |
+
# io
|
| 288 |
+
# }
|
| 289 |
+
|
| 290 |
+
# So instead of running a no-op and letting the side-effect of spinning
|
| 291 |
+
# the loop run the callbacks, we must explicitly run them here.
|
| 292 |
+
|
| 293 |
+
# If we don't, test__systemerror:TestCallback will be flaky, failing
|
| 294 |
+
# one time out of ~20, depending on timing.
|
| 295 |
+
|
| 296 |
+
# To get them to run immediately after this current loop,
|
| 297 |
+
# we use a check watcher, instead of a 0 duration timer entirely.
|
| 298 |
+
# If we use a 0 duration timer, we can get stuck in a timer loop.
|
| 299 |
+
# Python 3.6 fails in test_ftplib.py
|
| 300 |
+
|
| 301 |
+
# As a final note, if we have not yet entered the loop *at
|
| 302 |
+
# all*, and a timer was created with a duration shorter than
|
| 303 |
+
# the amount of time it took for us to enter the loop in the
|
| 304 |
+
# first place, it may expire and get called before our callback
|
| 305 |
+
# does. This could also lead to test__systemerror:TestCallback
|
| 306 |
+
# appearing to be flaky.
|
| 307 |
+
|
| 308 |
+
# As yet another final note, if we are currently running a
|
| 309 |
+
# timer callback, meaning we're inside uv__run_timers() in C,
|
| 310 |
+
# and the Python starts a new timer, if the Python code then
|
| 311 |
+
# update's the loop's time, it's possible that timer will
|
| 312 |
+
# expire *and be run in the same iteration of the loop*. This
|
| 313 |
+
# is trivial to do: In sequential code, anything after
|
| 314 |
+
# `gevent.sleep(0.1)` is running in a timer callback. Starting
|
| 315 |
+
# a new timer---e.g., another gevent.sleep() call---will
|
| 316 |
+
# update the time, *before* uv__run_timers exits, meaning
|
| 317 |
+
# other timers get a chance to run before our check or prepare
|
| 318 |
+
# watcher callbacks do. Therefore, we do indeed have to have a 0
|
| 319 |
+
# timer to run callbacks---it gets inserted before any other user
|
| 320 |
+
# timers---ideally, this should be especially careful about how much time
|
| 321 |
+
# it runs for.
|
| 322 |
+
|
| 323 |
+
# AND YET: We can't actually do that. We get timeouts that I haven't fully
|
| 324 |
+
# investigated if we do. Probably stuck in a timer loop.
|
| 325 |
+
|
| 326 |
+
# As a partial remedy to this, unlike libev, our timer watcher
|
| 327 |
+
# class doesn't update the loop time by default.
|
| 328 |
+
|
| 329 |
+
libuv.uv_check_start(self._timer0, libuv.python_timer0_callback)
|
| 330 |
+
|
| 331 |
+
|
| 332 |
+
def _stop_aux_watchers(self):
|
| 333 |
+
super(loop, self)._stop_aux_watchers()
|
| 334 |
+
assert self._prepare
|
| 335 |
+
assert self._check
|
| 336 |
+
assert self._signal_idle
|
| 337 |
+
libuv.uv_prepare_stop(self._prepare)
|
| 338 |
+
libuv.uv_ref(self._prepare) # Why are we doing this?
|
| 339 |
+
|
| 340 |
+
libuv.uv_check_stop(self._check)
|
| 341 |
+
libuv.uv_ref(self._check)
|
| 342 |
+
|
| 343 |
+
libuv.uv_timer_stop(self._signal_idle)
|
| 344 |
+
libuv.uv_ref(self._signal_idle)
|
| 345 |
+
|
| 346 |
+
libuv.uv_check_stop(self._timer0)
|
| 347 |
+
|
| 348 |
+
def _setup_for_run_callback(self):
|
| 349 |
+
self._start_callback_timer()
|
| 350 |
+
libuv.uv_ref(self._timer0)
|
| 351 |
+
|
| 352 |
+
def _can_destroy_loop(self, ptr):
|
| 353 |
+
return ptr
|
| 354 |
+
|
| 355 |
+
def __close_loop(self, ptr):
|
| 356 |
+
closed_failed = 1
|
| 357 |
+
|
| 358 |
+
while closed_failed:
|
| 359 |
+
closed_failed = libuv.uv_loop_close(ptr)
|
| 360 |
+
if not closed_failed:
|
| 361 |
+
break
|
| 362 |
+
|
| 363 |
+
if closed_failed != libuv.UV_EBUSY:
|
| 364 |
+
raise SystemError("Unknown close failure reason", closed_failed)
|
| 365 |
+
# We already closed all the handles. Run the loop
|
| 366 |
+
# once to let them be cut off from the loop.
|
| 367 |
+
ran_has_more_callbacks = libuv.uv_run(ptr, libuv.UV_RUN_ONCE)
|
| 368 |
+
if ran_has_more_callbacks:
|
| 369 |
+
libuv.uv_run(ptr, libuv.UV_RUN_NOWAIT)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def _destroy_loop(self, ptr):
|
| 373 |
+
# We're being asked to destroy a loop that's, potentially, at
|
| 374 |
+
# the time it was constructed, was the default loop. If loop
|
| 375 |
+
# objects were constructed more than once, it may have already
|
| 376 |
+
# been destroyed, though. We track this in the data member.
|
| 377 |
+
data = ptr.data
|
| 378 |
+
ptr.data = ffi.NULL
|
| 379 |
+
try:
|
| 380 |
+
if data:
|
| 381 |
+
libuv.uv_stop(ptr)
|
| 382 |
+
libuv.gevent_close_all_handles(ptr)
|
| 383 |
+
finally:
|
| 384 |
+
ptr.data = ffi.NULL
|
| 385 |
+
|
| 386 |
+
try:
|
| 387 |
+
if data:
|
| 388 |
+
self.__close_loop(ptr)
|
| 389 |
+
finally:
|
| 390 |
+
# Destroy the native resources *after* we have closed
|
| 391 |
+
# the loop. If we do it before, walking the handles
|
| 392 |
+
# attached to the loop is likely to segfault.
|
| 393 |
+
# Note that these may have been closed already if the default loop was shared.
|
| 394 |
+
if data:
|
| 395 |
+
libuv.gevent_zero_check(self._check)
|
| 396 |
+
libuv.gevent_zero_check(self._timer0)
|
| 397 |
+
libuv.gevent_zero_prepare(self._prepare)
|
| 398 |
+
libuv.gevent_zero_timer(self._signal_idle)
|
| 399 |
+
libuv.gevent_zero_loop(ptr)
|
| 400 |
+
|
| 401 |
+
del self._check
|
| 402 |
+
del self._prepare
|
| 403 |
+
del self._signal_idle
|
| 404 |
+
del self._timer0
|
| 405 |
+
|
| 406 |
+
# Destroy any watchers we're still holding on to.
|
| 407 |
+
del self._io_watchers
|
| 408 |
+
del self._fork_watchers
|
| 409 |
+
del self._child_watchers
|
| 410 |
+
|
| 411 |
+
_HandleState = namedtuple("HandleState",
|
| 412 |
+
['handle',
|
| 413 |
+
'type',
|
| 414 |
+
'watcher',
|
| 415 |
+
'ref',
|
| 416 |
+
'active',
|
| 417 |
+
'closing'])
|
| 418 |
+
def debug(self):
|
| 419 |
+
"""
|
| 420 |
+
Return all the handles that are open and their ref status.
|
| 421 |
+
"""
|
| 422 |
+
if not self.ptr:
|
| 423 |
+
return ["Loop has been destroyed"]
|
| 424 |
+
|
| 425 |
+
handle_state = self._HandleState
|
| 426 |
+
handles = []
|
| 427 |
+
|
| 428 |
+
# XXX: Convert this to a modern callback.
|
| 429 |
+
def walk(handle, _arg):
|
| 430 |
+
data = handle.data
|
| 431 |
+
if data:
|
| 432 |
+
watcher = ffi.from_handle(data)
|
| 433 |
+
else:
|
| 434 |
+
watcher = None
|
| 435 |
+
handles.append(handle_state(handle,
|
| 436 |
+
ffi.string(libuv.uv_handle_type_name(handle.type)),
|
| 437 |
+
watcher,
|
| 438 |
+
libuv.uv_has_ref(handle),
|
| 439 |
+
libuv.uv_is_active(handle),
|
| 440 |
+
libuv.uv_is_closing(handle)))
|
| 441 |
+
|
| 442 |
+
libuv.uv_walk(self.ptr,
|
| 443 |
+
ffi.callback("void(*)(uv_handle_t*,void*)",
|
| 444 |
+
walk),
|
| 445 |
+
ffi.NULL)
|
| 446 |
+
return handles
|
| 447 |
+
|
| 448 |
+
def ref(self):
|
| 449 |
+
pass
|
| 450 |
+
|
| 451 |
+
def unref(self):
|
| 452 |
+
# XXX: Called by _run_callbacks.
|
| 453 |
+
pass
|
| 454 |
+
|
| 455 |
+
def break_(self, how=None):
|
| 456 |
+
if self.ptr:
|
| 457 |
+
libuv.uv_stop(self.ptr)
|
| 458 |
+
|
| 459 |
+
def reinit(self):
|
| 460 |
+
# TODO: How to implement? We probably have to simply
|
| 461 |
+
# re-__init__ this whole class? Does it matter?
|
| 462 |
+
# OR maybe we need to uv_walk() and close all the handles?
|
| 463 |
+
|
| 464 |
+
# XXX: libuv < 1.12 simply CANNOT handle a fork unless you immediately
|
| 465 |
+
# exec() in the child. There are multiple calls to abort() that
|
| 466 |
+
# will kill the child process:
|
| 467 |
+
# - The OS X poll implementation (kqueue) aborts on an error return
|
| 468 |
+
# value; since kqueue FDs can't be inherited, then the next call
|
| 469 |
+
# to kqueue in the child will fail and get aborted; fork() is likely
|
| 470 |
+
# to be called during the gevent loop, meaning we're deep inside the
|
| 471 |
+
# runloop already, so we can't even close the loop that we're in:
|
| 472 |
+
# it's too late, the next call to kqueue is already scheduled.
|
| 473 |
+
# - The threadpool, should it be in use, also aborts
|
| 474 |
+
# (https://github.com/joyent/libuv/pull/1136)
|
| 475 |
+
# - There global shared state that breaks signal handling
|
| 476 |
+
# and leads to an abort() in the child, EVEN IF the loop in the parent
|
| 477 |
+
# had already been closed
|
| 478 |
+
# (https://github.com/joyent/libuv/issues/1405)
|
| 479 |
+
|
| 480 |
+
# In 1.12, the uv_loop_fork function was added (by gevent!)
|
| 481 |
+
libuv.uv_loop_fork(self.ptr)
|
| 482 |
+
|
| 483 |
+
_prepare_ran_callbacks = False
|
| 484 |
+
|
| 485 |
+
def __run_queued_callbacks(self):
|
| 486 |
+
if not self._queued_callbacks:
|
| 487 |
+
return False
|
| 488 |
+
|
| 489 |
+
cbs = self._queued_callbacks[:]
|
| 490 |
+
del self._queued_callbacks[:]
|
| 491 |
+
|
| 492 |
+
for watcher_ptr, arg in cbs:
|
| 493 |
+
handle = watcher_ptr.data
|
| 494 |
+
if not handle:
|
| 495 |
+
# It's been stopped and possibly closed
|
| 496 |
+
assert not libuv.uv_is_active(watcher_ptr)
|
| 497 |
+
continue
|
| 498 |
+
val = _callbacks.python_callback(handle, arg)
|
| 499 |
+
if val == -1: # Failure.
|
| 500 |
+
_callbacks.python_handle_error(handle, arg)
|
| 501 |
+
elif val == 1: # Success, and we may need to close the Python watcher.
|
| 502 |
+
if not libuv.uv_is_active(watcher_ptr):
|
| 503 |
+
# The callback closed the native watcher resources. Good.
|
| 504 |
+
# It's *supposed* to also reset the .data handle to NULL at
|
| 505 |
+
# that same time. If it resets it to something else, we're
|
| 506 |
+
# re-using the same watcher object, and that's not correct either.
|
| 507 |
+
# On Windows in particular, if the .data handle is changed because
|
| 508 |
+
# the IO multiplexer is being restarted, trying to dereference the
|
| 509 |
+
# *old* handle can crash with an FFI error.
|
| 510 |
+
handle_after_callback = watcher_ptr.data
|
| 511 |
+
try:
|
| 512 |
+
if handle_after_callback and handle_after_callback == handle:
|
| 513 |
+
_callbacks.python_stop(handle_after_callback)
|
| 514 |
+
finally:
|
| 515 |
+
watcher_ptr.data = ffi.NULL
|
| 516 |
+
return True
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def run(self, nowait=False, once=False):
|
| 520 |
+
# we can only respect one flag or the other.
|
| 521 |
+
# nowait takes precedence because it can't block
|
| 522 |
+
mode = libuv.UV_RUN_DEFAULT
|
| 523 |
+
if once:
|
| 524 |
+
mode = libuv.UV_RUN_ONCE
|
| 525 |
+
if nowait:
|
| 526 |
+
mode = libuv.UV_RUN_NOWAIT
|
| 527 |
+
|
| 528 |
+
if mode == libuv.UV_RUN_DEFAULT:
|
| 529 |
+
while self._ptr and self._ptr.data:
|
| 530 |
+
# This is here to better preserve order guarantees.
|
| 531 |
+
# See _run_callbacks for details.
|
| 532 |
+
|
| 533 |
+
# It may get run again from the prepare watcher, so
|
| 534 |
+
# potentially we could take twice as long as the
|
| 535 |
+
# switch interval.
|
| 536 |
+
# If we have *lots* of callbacks to run, we may not actually
|
| 537 |
+
# get through them all before we're requested to poll for IO;
|
| 538 |
+
# so in that case, just spin the loop once (UV_RUN_NOWAIT) and
|
| 539 |
+
# go again.
|
| 540 |
+
self._run_callbacks()
|
| 541 |
+
self._prepare_ran_callbacks = False
|
| 542 |
+
|
| 543 |
+
# UV_RUN_ONCE will poll for IO, blocking for up to the time needed
|
| 544 |
+
# for the next timer to expire. Worst case, that's our _signal_idle
|
| 545 |
+
# timer, about 1/3 second. UV_RUN_ONCE guarantees that some forward progress
|
| 546 |
+
# is made, either by an IO watcher or a timer.
|
| 547 |
+
#
|
| 548 |
+
# In contrast, UV_RUN_NOWAIT makes no such guarantee, it only polls for IO once and
|
| 549 |
+
# immediately returns; it does not update the loop time or timers after
|
| 550 |
+
# polling for IO.
|
| 551 |
+
run_mode = (
|
| 552 |
+
libuv.UV_RUN_ONCE
|
| 553 |
+
if not self._callbacks and not self._queued_callbacks
|
| 554 |
+
else libuv.UV_RUN_NOWAIT
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
ran_status = libuv.uv_run(self._ptr, run_mode)
|
| 558 |
+
# Note that we run queued callbacks when the prepare watcher runs,
|
| 559 |
+
# thus accounting for timers that expired before polling for IO,
|
| 560 |
+
# and idle watchers. This next call should get IO callbacks and
|
| 561 |
+
# callbacks from timers that expired *after* polling for IO.
|
| 562 |
+
ran_callbacks = self.__run_queued_callbacks()
|
| 563 |
+
|
| 564 |
+
if not ran_status and not ran_callbacks and not self._prepare_ran_callbacks:
|
| 565 |
+
# A return of 0 means there are no referenced and
|
| 566 |
+
# active handles. The loop is over.
|
| 567 |
+
# If we didn't run any callbacks, then we couldn't schedule
|
| 568 |
+
# anything to switch in the future, so there's no point
|
| 569 |
+
# running again.
|
| 570 |
+
return ran_status
|
| 571 |
+
return 0 # Somebody closed the loop
|
| 572 |
+
|
| 573 |
+
result = libuv.uv_run(self._ptr, mode)
|
| 574 |
+
self.__run_queued_callbacks()
|
| 575 |
+
return result
|
| 576 |
+
|
| 577 |
+
def now(self):
|
| 578 |
+
self.__check_and_die()
|
| 579 |
+
# libuv's now is expressed as an integer number of
|
| 580 |
+
# milliseconds, so to get it compatible with time.time units
|
| 581 |
+
# that this method is supposed to return, we have to divide by 1000.0
|
| 582 |
+
now = libuv.uv_now(self.ptr)
|
| 583 |
+
return now / 1000.0
|
| 584 |
+
|
| 585 |
+
def update_now(self):
|
| 586 |
+
self.__check_and_die()
|
| 587 |
+
libuv.uv_update_time(self.ptr)
|
| 588 |
+
|
| 589 |
+
def fileno(self):
|
| 590 |
+
if self.ptr:
|
| 591 |
+
fd = libuv.uv_backend_fd(self._ptr)
|
| 592 |
+
if fd >= 0:
|
| 593 |
+
return fd
|
| 594 |
+
|
| 595 |
+
_sigchld_watcher = None
|
| 596 |
+
_sigchld_callback_ffi = None
|
| 597 |
+
|
| 598 |
+
def install_sigchld(self):
|
| 599 |
+
if not self.default:
|
| 600 |
+
return
|
| 601 |
+
|
| 602 |
+
if self._sigchld_watcher:
|
| 603 |
+
return
|
| 604 |
+
|
| 605 |
+
self._sigchld_watcher = ffi.new('uv_signal_t*')
|
| 606 |
+
libuv.uv_signal_init(self.ptr, self._sigchld_watcher)
|
| 607 |
+
self._sigchld_watcher.data = self._handle_to_self
|
| 608 |
+
# Don't let this keep the loop alive
|
| 609 |
+
libuv.uv_unref(self._sigchld_watcher)
|
| 610 |
+
|
| 611 |
+
libuv.uv_signal_start(self._sigchld_watcher,
|
| 612 |
+
libuv.python_sigchld_callback,
|
| 613 |
+
signal.SIGCHLD)
|
| 614 |
+
|
| 615 |
+
def reset_sigchld(self):
|
| 616 |
+
if not self.default or not self._sigchld_watcher:
|
| 617 |
+
return
|
| 618 |
+
|
| 619 |
+
libuv.uv_signal_stop(self._sigchld_watcher)
|
| 620 |
+
# Must go through this to manage the memory lifetime
|
| 621 |
+
# correctly. Alternately, we could just stop it and restart
|
| 622 |
+
# it in install_sigchld?
|
| 623 |
+
_watchers.watcher._watcher_ffi_close(self._sigchld_watcher)
|
| 624 |
+
del self._sigchld_watcher
|
| 625 |
+
|
| 626 |
+
|
| 627 |
+
def _sigchld_callback(self):
|
| 628 |
+
# Signals can arrive at (relatively) any time. To eliminate
|
| 629 |
+
# race conditions, and behave more like libev, we "queue"
|
| 630 |
+
# sigchld to run when we run callbacks.
|
| 631 |
+
while True:
|
| 632 |
+
try:
|
| 633 |
+
pid, status, _usage = os.wait3(os.WNOHANG)
|
| 634 |
+
except OSError:
|
| 635 |
+
# Python 3 raises ChildProcessError
|
| 636 |
+
break
|
| 637 |
+
|
| 638 |
+
if pid == 0:
|
| 639 |
+
break
|
| 640 |
+
children_watchers = self._child_watchers.get(pid, []) + self._child_watchers.get(0, [])
|
| 641 |
+
for watcher in children_watchers:
|
| 642 |
+
self.run_callback(watcher._set_waitpid_status, pid, status)
|
| 643 |
+
|
| 644 |
+
# Don't invoke child watchers for 0 more than once
|
| 645 |
+
self._child_watchers[0] = []
|
| 646 |
+
|
| 647 |
+
def _register_child_watcher(self, watcher):
|
| 648 |
+
self._child_watchers[watcher._pid].append(watcher)
|
| 649 |
+
|
| 650 |
+
def _unregister_child_watcher(self, watcher):
|
| 651 |
+
try:
|
| 652 |
+
# stop() should be idempotent
|
| 653 |
+
self._child_watchers[watcher._pid].remove(watcher)
|
| 654 |
+
except ValueError:
|
| 655 |
+
pass
|
| 656 |
+
|
| 657 |
+
# Now's a good time to clean up any dead watchers we don't need
|
| 658 |
+
# anymore
|
| 659 |
+
for pid in list(self._child_watchers):
|
| 660 |
+
if not self._child_watchers[pid]:
|
| 661 |
+
del self._child_watchers[pid]
|
| 662 |
+
|
| 663 |
+
def io(self, fd, events, ref=True, priority=None):
|
| 664 |
+
# We rely on hard references here and explicit calls to
|
| 665 |
+
# close() on the returned object to correctly manage
|
| 666 |
+
# the watcher lifetimes.
|
| 667 |
+
|
| 668 |
+
io_watchers = self._io_watchers
|
| 669 |
+
try:
|
| 670 |
+
io_watcher = io_watchers[fd]
|
| 671 |
+
assert io_watcher._multiplex_watchers, ("IO Watcher %s unclosed but should be dead" % io_watcher)
|
| 672 |
+
except KeyError:
|
| 673 |
+
# Start the watcher with just the events that we're interested in.
|
| 674 |
+
# as multiplexers are added, the real event mask will be updated to keep in sync.
|
| 675 |
+
# If we watch for too much, we get spurious wakeups and busy loops.
|
| 676 |
+
io_watcher = self._watchers.io(self, fd, 0)
|
| 677 |
+
io_watchers[fd] = io_watcher
|
| 678 |
+
io_watcher._no_more_watchers = lambda: delitem(io_watchers, fd)
|
| 679 |
+
|
| 680 |
+
return io_watcher.multiplex(events)
|
| 681 |
+
|
| 682 |
+
def prepare(self, ref=True, priority=None):
|
| 683 |
+
# We run arbitrary code in python_prepare_callback. That could switch
|
| 684 |
+
# greenlets. If it does that while also manipulating the active prepare
|
| 685 |
+
# watchers, we could corrupt the process state, since the prepare watcher
|
| 686 |
+
# queue is iterated on the stack (on unix). We could workaround this by implementing
|
| 687 |
+
# prepare watchers in pure Python.
|
| 688 |
+
# See https://github.com/gevent/gevent/issues/1126
|
| 689 |
+
raise TypeError("prepare watchers are not currently supported in libuv. "
|
| 690 |
+
"If you need them, please contact the maintainers.")
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/libuv/watcher.py
ADDED
|
@@ -0,0 +1,762 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# pylint: disable=too-many-lines, protected-access, redefined-outer-name, not-callable
|
| 2 |
+
# pylint: disable=no-member
|
| 3 |
+
from __future__ import absolute_import, print_function
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
import sys
|
| 7 |
+
|
| 8 |
+
from gevent.libuv import _corecffi # pylint:disable=no-name-in-module,import-error
|
| 9 |
+
|
| 10 |
+
# Nothing public here
|
| 11 |
+
__all__ = []
|
| 12 |
+
|
| 13 |
+
ffi = _corecffi.ffi
|
| 14 |
+
libuv = _corecffi.lib
|
| 15 |
+
|
| 16 |
+
from gevent._ffi import watcher as _base
|
| 17 |
+
from gevent._ffi import _dbg
|
| 18 |
+
|
| 19 |
+
# A set of uv_handle_t* CFFI objects. Kept around
|
| 20 |
+
# to keep the memory alive until libuv is done with them.
|
| 21 |
+
class _ClosingWatchers(dict):
|
| 22 |
+
__slots__ = ()
|
| 23 |
+
|
| 24 |
+
def remove(self, obj):
|
| 25 |
+
try:
|
| 26 |
+
del self[obj]
|
| 27 |
+
except KeyError: # pragma: no cover
|
| 28 |
+
# This has been seen to happen if the module is executed twice
|
| 29 |
+
# and so the callback doesn't match the storage seen by watcher objects.
|
| 30 |
+
print(
|
| 31 |
+
'gevent error: Unable to remove closing watcher from keepaliveset. '
|
| 32 |
+
'Has the module state been corrupted or executed more than once?',
|
| 33 |
+
file=sys.stderr
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
_closing_watchers = _ClosingWatchers()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
# In debug mode, it would be nice to be able to clear the memory of
|
| 40 |
+
# the watcher (its size determined by
|
| 41 |
+
# libuv.uv_handle_size(ffi_watcher.type)) using memset so that if we
|
| 42 |
+
# are using it after it's supposedly been closed and deleted, we'd
|
| 43 |
+
# catch it sooner. BUT doing so breaks test__threadpool. We get errors
|
| 44 |
+
# about `pthread_mutex_lock[3]: Invalid argument` (and sometimes we
|
| 45 |
+
# crash) suggesting either that we're writing on memory that doesn't
|
| 46 |
+
# belong to us, somehow, or that we haven't actually lost all
|
| 47 |
+
# references...
|
| 48 |
+
_uv_close_callback = ffi.def_extern(name='_uv_close_callback')(
|
| 49 |
+
_closing_watchers.remove
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
_events = [(libuv.UV_READABLE, "READ"),
|
| 54 |
+
(libuv.UV_WRITABLE, "WRITE")]
|
| 55 |
+
|
| 56 |
+
def _events_to_str(events): # export
|
| 57 |
+
return _base.events_to_str(events, _events)
|
| 58 |
+
|
| 59 |
+
class UVFuncallError(ValueError):
|
| 60 |
+
pass
|
| 61 |
+
|
| 62 |
+
class libuv_error_wrapper(object):
|
| 63 |
+
# Makes sure that everything stored as a function
|
| 64 |
+
# on the wrapper instances (classes, actually,
|
| 65 |
+
# because this is used by the metaclass)
|
| 66 |
+
# checks its return value and raises an error.
|
| 67 |
+
# This expects that everything we call has an int
|
| 68 |
+
# or void return value and follows the conventions
|
| 69 |
+
# of error handling (that negative values are errors)
|
| 70 |
+
def __init__(self, uv):
|
| 71 |
+
self._libuv = uv
|
| 72 |
+
|
| 73 |
+
def __getattr__(self, name):
|
| 74 |
+
libuv_func = getattr(self._libuv, name)
|
| 75 |
+
|
| 76 |
+
@functools.wraps(libuv_func)
|
| 77 |
+
def wrap(*args, **kwargs):
|
| 78 |
+
if args and isinstance(args[0], watcher):
|
| 79 |
+
args = args[1:]
|
| 80 |
+
res = libuv_func(*args, **kwargs)
|
| 81 |
+
if res is not None and res < 0:
|
| 82 |
+
raise UVFuncallError(
|
| 83 |
+
str(ffi.string(libuv.uv_err_name(res)).decode('ascii')
|
| 84 |
+
+ ' '
|
| 85 |
+
+ ffi.string(libuv.uv_strerror(res)).decode('ascii'))
|
| 86 |
+
+ " Args: " + repr(args) + " KWARGS: " + repr(kwargs)
|
| 87 |
+
)
|
| 88 |
+
return res
|
| 89 |
+
|
| 90 |
+
setattr(self, name, wrap)
|
| 91 |
+
|
| 92 |
+
return wrap
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class ffi_unwrapper(object):
|
| 96 |
+
# undoes the wrapping of libuv_error_wrapper for
|
| 97 |
+
# the methods used by the metaclass that care
|
| 98 |
+
|
| 99 |
+
def __init__(self, ff):
|
| 100 |
+
self._ffi = ff
|
| 101 |
+
|
| 102 |
+
def __getattr__(self, name):
|
| 103 |
+
return getattr(self._ffi, name)
|
| 104 |
+
|
| 105 |
+
def addressof(self, lib, name):
|
| 106 |
+
assert isinstance(lib, libuv_error_wrapper)
|
| 107 |
+
return self._ffi.addressof(libuv, name)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
class watcher(_base.watcher):
|
| 111 |
+
_FFI = ffi_unwrapper(ffi)
|
| 112 |
+
_LIB = libuv_error_wrapper(libuv)
|
| 113 |
+
|
| 114 |
+
_watcher_prefix = 'uv'
|
| 115 |
+
_watcher_struct_pattern = '%s_t'
|
| 116 |
+
|
| 117 |
+
@classmethod
|
| 118 |
+
def _watcher_ffi_close(cls, ffi_watcher):
|
| 119 |
+
# Managing the lifetime of _watcher is tricky.
|
| 120 |
+
# They have to be uv_close()'d, but that only
|
| 121 |
+
# queues them to be closed in the *next* loop iteration.
|
| 122 |
+
# The memory must stay valid for at least that long,
|
| 123 |
+
# or assert errors are triggered. We can't use a ffi.gc()
|
| 124 |
+
# pointer to queue the uv_close, because by the time the
|
| 125 |
+
# destructor is called, there's no way to keep the memory alive
|
| 126 |
+
# and it could be re-used.
|
| 127 |
+
# So here we resort to resurrecting the pointer object out
|
| 128 |
+
# of our scope, keeping it alive past this object's lifetime.
|
| 129 |
+
# We then use the uv_close callback to handle removing that
|
| 130 |
+
# reference. There's no context passed to the close callback,
|
| 131 |
+
# so we have to do this globally.
|
| 132 |
+
|
| 133 |
+
# Sadly, doing this causes crashes if there were multiple
|
| 134 |
+
# watchers for a given FD, so we have to take special care
|
| 135 |
+
# about that. See https://github.com/gevent/gevent/issues/790#issuecomment-208076604
|
| 136 |
+
|
| 137 |
+
# Note that this cannot be a __del__ method, because we store
|
| 138 |
+
# the CFFI handle to self on self, which is a cycle, and
|
| 139 |
+
# objects with a __del__ method cannot be collected on CPython < 3.4
|
| 140 |
+
|
| 141 |
+
# Instead, this is arranged as a callback to GC when the
|
| 142 |
+
# watcher class dies. Obviously it's important to keep the ffi
|
| 143 |
+
# watcher alive.
|
| 144 |
+
# We can pass in "subclasses" of uv_handle_t that line up at the C level,
|
| 145 |
+
# but that don't in CFFI without a cast. But be careful what we use the cast
|
| 146 |
+
# for, don't pass it back to C.
|
| 147 |
+
ffi_handle_watcher = cls._FFI.cast('uv_handle_t*', ffi_watcher)
|
| 148 |
+
ffi_handle_watcher.data = ffi.NULL
|
| 149 |
+
|
| 150 |
+
if ffi_handle_watcher.type and not libuv.uv_is_closing(ffi_watcher):
|
| 151 |
+
# If the type isn't set, we were never properly initialized,
|
| 152 |
+
# and trying to close it results in libuv terminating the process.
|
| 153 |
+
# Sigh. Same thing if it's already in the process of being
|
| 154 |
+
# closed.
|
| 155 |
+
_closing_watchers[ffi_handle_watcher] = ffi_watcher
|
| 156 |
+
libuv.uv_close(ffi_watcher, libuv._uv_close_callback)
|
| 157 |
+
|
| 158 |
+
def _watcher_ffi_set_init_ref(self, ref):
|
| 159 |
+
self.ref = ref
|
| 160 |
+
|
| 161 |
+
def _watcher_ffi_init(self, args):
|
| 162 |
+
# TODO: we could do a better job chokepointing this
|
| 163 |
+
return self._watcher_init(self.loop.ptr,
|
| 164 |
+
self._watcher,
|
| 165 |
+
*args)
|
| 166 |
+
|
| 167 |
+
def _watcher_ffi_start(self):
|
| 168 |
+
self._watcher_start(self._watcher, self._watcher_callback)
|
| 169 |
+
|
| 170 |
+
def _watcher_ffi_stop(self):
|
| 171 |
+
if self._watcher:
|
| 172 |
+
# The multiplexed io watcher deletes self._watcher
|
| 173 |
+
# when it closes down. If that's in the process of
|
| 174 |
+
# an error handler, AbstractCallbacks.unhandled_onerror
|
| 175 |
+
# will try to close us again.
|
| 176 |
+
self._watcher_stop(self._watcher)
|
| 177 |
+
|
| 178 |
+
@_base.only_if_watcher
|
| 179 |
+
def _watcher_ffi_ref(self):
|
| 180 |
+
libuv.uv_ref(self._watcher)
|
| 181 |
+
|
| 182 |
+
@_base.only_if_watcher
|
| 183 |
+
def _watcher_ffi_unref(self):
|
| 184 |
+
libuv.uv_unref(self._watcher)
|
| 185 |
+
|
| 186 |
+
def _watcher_ffi_start_unref(self):
|
| 187 |
+
pass
|
| 188 |
+
|
| 189 |
+
def _watcher_ffi_stop_ref(self):
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
def _get_ref(self):
|
| 193 |
+
# Convert 1/0 to True/False
|
| 194 |
+
if self._watcher is None:
|
| 195 |
+
return None
|
| 196 |
+
return bool(libuv.uv_has_ref(self._watcher))
|
| 197 |
+
|
| 198 |
+
def _set_ref(self, value):
|
| 199 |
+
if value:
|
| 200 |
+
self._watcher_ffi_ref()
|
| 201 |
+
else:
|
| 202 |
+
self._watcher_ffi_unref()
|
| 203 |
+
|
| 204 |
+
ref = property(_get_ref, _set_ref)
|
| 205 |
+
|
| 206 |
+
def feed(self, _revents, _callback, *_args):
|
| 207 |
+
# pylint:disable-next=broad-exception-raised
|
| 208 |
+
raise Exception("Not implemented")
|
| 209 |
+
|
| 210 |
+
class io(_base.IoMixin, watcher):
|
| 211 |
+
_watcher_type = 'poll'
|
| 212 |
+
_watcher_callback_name = '_gevent_poll_callback2'
|
| 213 |
+
|
| 214 |
+
# On Windows is critical to be able to garbage collect these
|
| 215 |
+
# objects in a timely fashion so that they don't get reused
|
| 216 |
+
# for multiplexing completely different sockets. This is because
|
| 217 |
+
# uv_poll_init_socket does a lot of setup for the socket to make
|
| 218 |
+
# polling work. If get reused for another socket that has the same
|
| 219 |
+
# fileno, things break badly. (In theory this could be a problem
|
| 220 |
+
# on posix too, but in practice it isn't).
|
| 221 |
+
|
| 222 |
+
# TODO: We should probably generalize this to all
|
| 223 |
+
# ffi watchers. Avoiding GC cycles as much as possible
|
| 224 |
+
# is a good thing, and potentially allocating new handles
|
| 225 |
+
# as needed gets us better memory locality.
|
| 226 |
+
|
| 227 |
+
# Especially on Windows, we must also account for the case that a
|
| 228 |
+
# reference to this object has leaked (e.g., the socket object is
|
| 229 |
+
# still around), but the fileno has been closed and a new one
|
| 230 |
+
# opened. We must still get a new native watcher at that point. We
|
| 231 |
+
# handle this case by simply making sure that we don't even have
|
| 232 |
+
# a native watcher until the object is started, and we shut it down
|
| 233 |
+
# when the object is stopped.
|
| 234 |
+
|
| 235 |
+
# XXX: I was able to solve at least Windows test_ftplib.py issues
|
| 236 |
+
# with more of a careful use of io objects in socket.py, so
|
| 237 |
+
# delaying this entirely is at least temporarily on hold. Instead
|
| 238 |
+
# sticking with the _watcher_create function override for the
|
| 239 |
+
# moment.
|
| 240 |
+
|
| 241 |
+
# XXX: Note 2: Moving to a deterministic close model, which was necessary
|
| 242 |
+
# for PyPy, also seems to solve the Windows issues. So we're completely taking
|
| 243 |
+
# this object out of the loop's registration; we don't want GC callbacks and
|
| 244 |
+
# uv_close anywhere *near* this object.
|
| 245 |
+
|
| 246 |
+
_watcher_registers_with_loop_on_create = False
|
| 247 |
+
|
| 248 |
+
EVENT_MASK = libuv.UV_READABLE | libuv.UV_WRITABLE | libuv.UV_DISCONNECT
|
| 249 |
+
|
| 250 |
+
_multiplex_watchers = ()
|
| 251 |
+
|
| 252 |
+
def __init__(self, loop, fd, events, ref=True, priority=None):
|
| 253 |
+
super(io, self).__init__(loop, fd, events, ref=ref, priority=priority, _args=(fd,))
|
| 254 |
+
self._fd = fd
|
| 255 |
+
self._events = events
|
| 256 |
+
self._multiplex_watchers = []
|
| 257 |
+
|
| 258 |
+
def _get_fd(self):
|
| 259 |
+
return self._fd
|
| 260 |
+
|
| 261 |
+
@_base.not_while_active
|
| 262 |
+
def _set_fd(self, fd):
|
| 263 |
+
self._fd = fd
|
| 264 |
+
self._watcher_ffi_init((fd,))
|
| 265 |
+
|
| 266 |
+
def _get_events(self):
|
| 267 |
+
return self._events
|
| 268 |
+
|
| 269 |
+
def _set_events(self, events):
|
| 270 |
+
if events == self._events:
|
| 271 |
+
return
|
| 272 |
+
self._events = events
|
| 273 |
+
if self.active:
|
| 274 |
+
# We're running but libuv specifically says we can
|
| 275 |
+
# call start again to change our event mask.
|
| 276 |
+
assert self._handle is not None
|
| 277 |
+
self._watcher_start(self._watcher, self._events, self._watcher_callback)
|
| 278 |
+
|
| 279 |
+
events = property(_get_events, _set_events)
|
| 280 |
+
|
| 281 |
+
def _watcher_ffi_start(self):
|
| 282 |
+
self._watcher_start(self._watcher, self._events, self._watcher_callback)
|
| 283 |
+
|
| 284 |
+
if sys.platform.startswith('win32'):
|
| 285 |
+
# uv_poll can only handle sockets on Windows, but the plain
|
| 286 |
+
# uv_poll_init we call on POSIX assumes that the fileno
|
| 287 |
+
# argument is already a C fileno, as created by
|
| 288 |
+
# _get_osfhandle. C filenos are limited resources, must be
|
| 289 |
+
# closed with _close. So there are lifetime issues with that:
|
| 290 |
+
# calling the C function _close to dispose of the fileno
|
| 291 |
+
# *also* closes the underlying win32 handle, possibly
|
| 292 |
+
# prematurely. (XXX: Maybe could do something with weak
|
| 293 |
+
# references? But to what?)
|
| 294 |
+
|
| 295 |
+
# All libuv wants to do with the fileno in uv_poll_init is
|
| 296 |
+
# turn it back into a Win32 SOCKET handle.
|
| 297 |
+
|
| 298 |
+
# Now, libuv provides uv_poll_init_socket, which instead of
|
| 299 |
+
# taking a C fileno takes the SOCKET, avoiding the need to dance with
|
| 300 |
+
# the C runtime.
|
| 301 |
+
|
| 302 |
+
# It turns out that SOCKET (win32 handles in general) can be
|
| 303 |
+
# represented with `intptr_t`. It further turns out that
|
| 304 |
+
# CPython *directly* exposes the SOCKET handle as the value of
|
| 305 |
+
# fileno (32-bit PyPy does some munging on it, which should
|
| 306 |
+
# rarely matter). So we can pass socket.fileno() through
|
| 307 |
+
# to uv_poll_init_socket.
|
| 308 |
+
|
| 309 |
+
# See _corecffi_build.
|
| 310 |
+
_watcher_init = watcher._LIB.uv_poll_init_socket
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
class _multiplexwatcher(object):
|
| 314 |
+
|
| 315 |
+
callback = None
|
| 316 |
+
args = ()
|
| 317 |
+
pass_events = False
|
| 318 |
+
ref = True
|
| 319 |
+
|
| 320 |
+
def __init__(self, events, watcher):
|
| 321 |
+
self._events = events
|
| 322 |
+
|
| 323 |
+
# References:
|
| 324 |
+
# These objects must keep the original IO object alive;
|
| 325 |
+
# the IO object SHOULD NOT keep these alive to avoid cycles
|
| 326 |
+
# We MUST NOT rely on GC to clean up the IO objects, but the explicit
|
| 327 |
+
# calls to close(); see _multiplex_closed.
|
| 328 |
+
self._watcher_ref = watcher
|
| 329 |
+
|
| 330 |
+
events = property(
|
| 331 |
+
lambda self: self._events,
|
| 332 |
+
_base.not_while_active(lambda self, nv: setattr(self, '_events', nv)))
|
| 333 |
+
|
| 334 |
+
def start(self, callback, *args, **kwargs):
|
| 335 |
+
self.pass_events = kwargs.get("pass_events")
|
| 336 |
+
self.callback = callback
|
| 337 |
+
self.args = args
|
| 338 |
+
|
| 339 |
+
watcher = self._watcher_ref
|
| 340 |
+
if watcher is not None:
|
| 341 |
+
if not watcher.active:
|
| 342 |
+
watcher._io_start()
|
| 343 |
+
else:
|
| 344 |
+
# Make sure we're in the event mask
|
| 345 |
+
watcher._calc_and_update_events()
|
| 346 |
+
|
| 347 |
+
def stop(self):
|
| 348 |
+
self.callback = None
|
| 349 |
+
self.pass_events = None
|
| 350 |
+
self.args = None
|
| 351 |
+
watcher = self._watcher_ref
|
| 352 |
+
if watcher is not None:
|
| 353 |
+
watcher._io_maybe_stop()
|
| 354 |
+
|
| 355 |
+
def close(self):
|
| 356 |
+
if self._watcher_ref is not None:
|
| 357 |
+
self._watcher_ref._multiplex_closed(self)
|
| 358 |
+
self._watcher_ref = None
|
| 359 |
+
|
| 360 |
+
@property
|
| 361 |
+
def active(self):
|
| 362 |
+
return self.callback is not None
|
| 363 |
+
|
| 364 |
+
@property
|
| 365 |
+
def _watcher(self):
|
| 366 |
+
# For testing.
|
| 367 |
+
return self._watcher_ref._watcher
|
| 368 |
+
|
| 369 |
+
# ares.pyx depends on this property,
|
| 370 |
+
# and test__core uses it too
|
| 371 |
+
fd = property(lambda self: getattr(self._watcher_ref, '_fd', -1),
|
| 372 |
+
lambda self, nv: self._watcher_ref._set_fd(nv))
|
| 373 |
+
|
| 374 |
+
def _io_maybe_stop(self):
|
| 375 |
+
self._calc_and_update_events()
|
| 376 |
+
for w in self._multiplex_watchers:
|
| 377 |
+
if w.callback is not None:
|
| 378 |
+
# There's still a reference to it, and it's started,
|
| 379 |
+
# so we can't stop.
|
| 380 |
+
return
|
| 381 |
+
# If we get here, nothing was started
|
| 382 |
+
# so we can take ourself out of the polling set
|
| 383 |
+
self.stop()
|
| 384 |
+
|
| 385 |
+
def _io_start(self):
|
| 386 |
+
self._calc_and_update_events()
|
| 387 |
+
self.start(self._io_callback, pass_events=True)
|
| 388 |
+
|
| 389 |
+
def _calc_and_update_events(self):
|
| 390 |
+
events = 0
|
| 391 |
+
for watcher in self._multiplex_watchers:
|
| 392 |
+
if watcher.callback is not None:
|
| 393 |
+
# Only ask for events that are active.
|
| 394 |
+
events |= watcher.events
|
| 395 |
+
self._set_events(events)
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def multiplex(self, events):
|
| 399 |
+
watcher = self._multiplexwatcher(events, self)
|
| 400 |
+
self._multiplex_watchers.append(watcher)
|
| 401 |
+
self._calc_and_update_events()
|
| 402 |
+
return watcher
|
| 403 |
+
|
| 404 |
+
def close(self):
|
| 405 |
+
super(io, self).close()
|
| 406 |
+
del self._multiplex_watchers
|
| 407 |
+
|
| 408 |
+
def _multiplex_closed(self, watcher):
|
| 409 |
+
self._multiplex_watchers.remove(watcher)
|
| 410 |
+
if not self._multiplex_watchers:
|
| 411 |
+
self.stop() # should already be stopped
|
| 412 |
+
self._no_more_watchers()
|
| 413 |
+
# It is absolutely critical that we control when the call
|
| 414 |
+
# to uv_close() gets made. uv_close() of a uv_poll_t
|
| 415 |
+
# handle winds up calling uv__platform_invalidate_fd,
|
| 416 |
+
# which, as the name implies, destroys any outstanding
|
| 417 |
+
# events for the *fd* that haven't been delivered yet, and also removes
|
| 418 |
+
# the *fd* from the poll set. So if this happens later, at some
|
| 419 |
+
# non-deterministic time when (cyclic or otherwise) GC runs,
|
| 420 |
+
# *and* we've opened a new watcher for the fd, that watcher will
|
| 421 |
+
# suddenly and mysteriously stop seeing events. So we do this now;
|
| 422 |
+
# this method is smart enough not to close the handle twice.
|
| 423 |
+
self.close()
|
| 424 |
+
else:
|
| 425 |
+
self._calc_and_update_events()
|
| 426 |
+
|
| 427 |
+
def _no_more_watchers(self):
|
| 428 |
+
# The loop sets this on an individual watcher to delete it from
|
| 429 |
+
# the active list where it keeps hard references.
|
| 430 |
+
pass
|
| 431 |
+
|
| 432 |
+
def _io_callback(self, events):
|
| 433 |
+
if events < 0:
|
| 434 |
+
# actually a status error code
|
| 435 |
+
_dbg("Callback error on", self._fd,
|
| 436 |
+
ffi.string(libuv.uv_err_name(events)),
|
| 437 |
+
ffi.string(libuv.uv_strerror(events)))
|
| 438 |
+
# XXX: We've seen one half of a FileObjectPosix pair
|
| 439 |
+
# (the read side of a pipe) report errno 11 'bad file descriptor'
|
| 440 |
+
# after the write side was closed and its watcher removed. But
|
| 441 |
+
# we still need to attempt to read from it to clear out what's in
|
| 442 |
+
# its buffers--if we return with the watcher inactive before proceeding to wake up
|
| 443 |
+
# the reader, we get a LoopExit. So we can't return here and arguably shouldn't print it
|
| 444 |
+
# either. The negative events mask will match the watcher's mask.
|
| 445 |
+
# See test__fileobject.py:Test.test_newlines for an example.
|
| 446 |
+
|
| 447 |
+
# On Windows (at least with PyPy), we can get ENOTSOCK (socket operation on non-socket)
|
| 448 |
+
# if a socket gets closed. If we don't pass the events on, we hang.
|
| 449 |
+
# See test__makefile_ref.TestSSL for examples.
|
| 450 |
+
# return
|
| 451 |
+
|
| 452 |
+
for watcher in self._multiplex_watchers:
|
| 453 |
+
if not watcher.callback:
|
| 454 |
+
# Stopped
|
| 455 |
+
continue
|
| 456 |
+
assert watcher._watcher_ref is self, (self, watcher._watcher_ref)
|
| 457 |
+
|
| 458 |
+
send_event = (events & watcher.events) or events < 0
|
| 459 |
+
if send_event:
|
| 460 |
+
if not watcher.pass_events:
|
| 461 |
+
watcher.callback(*watcher.args)
|
| 462 |
+
else:
|
| 463 |
+
watcher.callback(events, *watcher.args)
|
| 464 |
+
|
| 465 |
+
class _SimulatedWithAsyncMixin(object):
|
| 466 |
+
_watcher_skip_ffi = True
|
| 467 |
+
|
| 468 |
+
def __init__(self, loop, *args, **kwargs):
|
| 469 |
+
self._async = loop.async_()
|
| 470 |
+
try:
|
| 471 |
+
super(_SimulatedWithAsyncMixin, self).__init__(loop, *args, **kwargs)
|
| 472 |
+
except:
|
| 473 |
+
self._async.close()
|
| 474 |
+
raise
|
| 475 |
+
|
| 476 |
+
def _watcher_create(self, _args):
|
| 477 |
+
return
|
| 478 |
+
|
| 479 |
+
@property
|
| 480 |
+
def _watcher_handle(self):
|
| 481 |
+
return None
|
| 482 |
+
|
| 483 |
+
def _watcher_ffi_init(self, _args):
|
| 484 |
+
return
|
| 485 |
+
|
| 486 |
+
def _watcher_ffi_set_init_ref(self, ref):
|
| 487 |
+
self._async.ref = ref
|
| 488 |
+
|
| 489 |
+
@property
|
| 490 |
+
def active(self):
|
| 491 |
+
return self._async.active
|
| 492 |
+
|
| 493 |
+
def start(self, cb, *args):
|
| 494 |
+
assert self._async is not None
|
| 495 |
+
self._register_loop_callback()
|
| 496 |
+
self.callback = cb
|
| 497 |
+
self.args = args
|
| 498 |
+
self._async.start(cb, *args)
|
| 499 |
+
|
| 500 |
+
def stop(self):
|
| 501 |
+
self._unregister_loop_callback()
|
| 502 |
+
self.callback = None
|
| 503 |
+
self.args = None
|
| 504 |
+
if self._async is not None:
|
| 505 |
+
# If we're stop() after close().
|
| 506 |
+
# That should be allowed.
|
| 507 |
+
self._async.stop()
|
| 508 |
+
|
| 509 |
+
def close(self):
|
| 510 |
+
if self._async is not None:
|
| 511 |
+
a = self._async
|
| 512 |
+
self._async = None
|
| 513 |
+
a.close()
|
| 514 |
+
|
| 515 |
+
def _register_loop_callback(self):
|
| 516 |
+
# called from start()
|
| 517 |
+
raise NotImplementedError()
|
| 518 |
+
|
| 519 |
+
def _unregister_loop_callback(self):
|
| 520 |
+
# called from stop
|
| 521 |
+
raise NotImplementedError()
|
| 522 |
+
|
| 523 |
+
class fork(_SimulatedWithAsyncMixin,
|
| 524 |
+
_base.ForkMixin,
|
| 525 |
+
watcher):
|
| 526 |
+
# We'll have to implement this one completely manually.
|
| 527 |
+
_watcher_skip_ffi = False
|
| 528 |
+
|
| 529 |
+
def _register_loop_callback(self):
|
| 530 |
+
self.loop._fork_watchers.add(self)
|
| 531 |
+
|
| 532 |
+
def _unregister_loop_callback(self):
|
| 533 |
+
try:
|
| 534 |
+
# stop() should be idempotent
|
| 535 |
+
self.loop._fork_watchers.remove(self)
|
| 536 |
+
except KeyError:
|
| 537 |
+
pass
|
| 538 |
+
|
| 539 |
+
def _on_fork(self):
|
| 540 |
+
self._async.send()
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
class child(_SimulatedWithAsyncMixin,
|
| 544 |
+
_base.ChildMixin,
|
| 545 |
+
watcher):
|
| 546 |
+
_watcher_skip_ffi = True
|
| 547 |
+
# We'll have to implement this one completely manually.
|
| 548 |
+
# Our approach is to use a SIGCHLD handler and the original
|
| 549 |
+
# os.waitpid call.
|
| 550 |
+
|
| 551 |
+
# On Unix, libuv's uv_process_t and uv_spawn use SIGCHLD,
|
| 552 |
+
# just like libev does for its child watchers. So
|
| 553 |
+
# we're not adding any new SIGCHLD related issues not already
|
| 554 |
+
# present in libev.
|
| 555 |
+
|
| 556 |
+
|
| 557 |
+
def _register_loop_callback(self):
|
| 558 |
+
self.loop._register_child_watcher(self)
|
| 559 |
+
|
| 560 |
+
def _unregister_loop_callback(self):
|
| 561 |
+
self.loop._unregister_child_watcher(self)
|
| 562 |
+
|
| 563 |
+
def _set_waitpid_status(self, pid, status):
|
| 564 |
+
self._rpid = pid
|
| 565 |
+
self._rstatus = status
|
| 566 |
+
self._async.send()
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
class async_(_base.AsyncMixin, watcher):
|
| 570 |
+
_watcher_callback_name = '_gevent_async_callback0'
|
| 571 |
+
|
| 572 |
+
# libuv async watchers are different than all other watchers:
|
| 573 |
+
# They don't have a separate start/stop method (presumably
|
| 574 |
+
# because of race conditions). Simply initing them places them
|
| 575 |
+
# into the active queue.
|
| 576 |
+
#
|
| 577 |
+
# In the past, we sent a NULL C callback to the watcher, trusting
|
| 578 |
+
# that no one would call send() without actually starting us (or after
|
| 579 |
+
# closing us); doing so would crash. But we don't want to delay
|
| 580 |
+
# initing the struct because it will crash in uv_close() when we get GC'd,
|
| 581 |
+
# and send() will also crash. Plus that complicates our lifecycle (managing
|
| 582 |
+
# the memory).
|
| 583 |
+
#
|
| 584 |
+
# Now, we always init the correct C callback, and use a dummy
|
| 585 |
+
# Python callback that gets replaced when we are started and
|
| 586 |
+
# stopped. This prevents mistakes from being crashes.
|
| 587 |
+
_callback = lambda: None
|
| 588 |
+
|
| 589 |
+
def _watcher_ffi_init(self, args):
|
| 590 |
+
# NOTE: uv_async_init is NOT idempotent. Calling it more than
|
| 591 |
+
# once adds the uv_async_t to the internal queue multiple times,
|
| 592 |
+
# and uv_close only cleans up one of them, meaning that we tend to
|
| 593 |
+
# crash. Thus we have to be very careful not to allow that.
|
| 594 |
+
return self._watcher_init(self.loop.ptr, self._watcher,
|
| 595 |
+
self._watcher_callback)
|
| 596 |
+
|
| 597 |
+
def _watcher_ffi_start(self):
|
| 598 |
+
pass
|
| 599 |
+
|
| 600 |
+
def _watcher_ffi_stop(self):
|
| 601 |
+
pass
|
| 602 |
+
|
| 603 |
+
def send(self):
|
| 604 |
+
assert self._callback is not async_._callback, "Sending to a closed watcher"
|
| 605 |
+
if libuv.uv_is_closing(self._watcher):
|
| 606 |
+
# pylint:disable-next=broad-exception-raised
|
| 607 |
+
raise Exception("Closing handle")
|
| 608 |
+
libuv.uv_async_send(self._watcher)
|
| 609 |
+
|
| 610 |
+
@property
|
| 611 |
+
def pending(self):
|
| 612 |
+
return None
|
| 613 |
+
|
| 614 |
+
locals()['async'] = async_
|
| 615 |
+
|
| 616 |
+
class timer(_base.TimerMixin, watcher):
|
| 617 |
+
|
| 618 |
+
_watcher_callback_name = '_gevent_timer_callback0'
|
| 619 |
+
|
| 620 |
+
# In libuv, timer callbacks continue running while any timer is
|
| 621 |
+
# expired, including newly added timers. Newly added non-zero
|
| 622 |
+
# timers (especially of small duration) can be seen to be expired
|
| 623 |
+
# if the loop time is updated while we are in a timer callback.
|
| 624 |
+
# This can lead to us being stuck running timers for a terribly
|
| 625 |
+
# long time, which is not good. So default to not updating the
|
| 626 |
+
# time.
|
| 627 |
+
|
| 628 |
+
# Also, newly-added timers of 0 duration can *also* stall the
|
| 629 |
+
# loop, because they'll be seen to be expired immediately.
|
| 630 |
+
# Updating the time can prevent that, *if* there was already a
|
| 631 |
+
# timer for a longer duration scheduled.
|
| 632 |
+
|
| 633 |
+
# To mitigate the above problems, our loop implementation turns
|
| 634 |
+
# zero duration timers into check watchers instead using OneShotCheck.
|
| 635 |
+
# This ensures the loop cycles. Of course, the 'again' method does
|
| 636 |
+
# nothing on them and doesn't exist. In practice that's not an issue.
|
| 637 |
+
|
| 638 |
+
_again = False
|
| 639 |
+
|
| 640 |
+
def _watcher_ffi_init(self, args):
|
| 641 |
+
self._watcher_init(self.loop.ptr, self._watcher)
|
| 642 |
+
self._after, self._repeat = args
|
| 643 |
+
if self._after and self._after < 0.001:
|
| 644 |
+
import warnings
|
| 645 |
+
# XXX: The stack level is hard to determine, could be getting here
|
| 646 |
+
# through a number of different ways.
|
| 647 |
+
warnings.warn("libuv only supports millisecond timer resolution; "
|
| 648 |
+
"all times less will be set to 1 ms",
|
| 649 |
+
stacklevel=6)
|
| 650 |
+
# The alternative is to effectively pass in int(0.1) == 0, which
|
| 651 |
+
# means no sleep at all, which leads to excessive wakeups
|
| 652 |
+
self._after = 0.001
|
| 653 |
+
if self._repeat and self._repeat < 0.001:
|
| 654 |
+
import warnings
|
| 655 |
+
warnings.warn("libuv only supports millisecond timer resolution; "
|
| 656 |
+
"all times less will be set to 1 ms",
|
| 657 |
+
stacklevel=6)
|
| 658 |
+
self._repeat = 0.001
|
| 659 |
+
|
| 660 |
+
def _watcher_ffi_start(self):
|
| 661 |
+
if self._again:
|
| 662 |
+
libuv.uv_timer_again(self._watcher)
|
| 663 |
+
else:
|
| 664 |
+
try:
|
| 665 |
+
self._watcher_start(self._watcher, self._watcher_callback,
|
| 666 |
+
int(self._after * 1000),
|
| 667 |
+
int(self._repeat * 1000))
|
| 668 |
+
except ValueError:
|
| 669 |
+
# in case of non-ints in _after/_repeat
|
| 670 |
+
raise TypeError()
|
| 671 |
+
|
| 672 |
+
def again(self, callback, *args, **kw):
|
| 673 |
+
if not self.active:
|
| 674 |
+
# If we've never been started, this is the same as starting us.
|
| 675 |
+
# libuv makes the distinction, libev doesn't.
|
| 676 |
+
self.start(callback, *args, **kw)
|
| 677 |
+
return
|
| 678 |
+
|
| 679 |
+
self._again = True
|
| 680 |
+
try:
|
| 681 |
+
self.start(callback, *args, **kw)
|
| 682 |
+
finally:
|
| 683 |
+
del self._again
|
| 684 |
+
|
| 685 |
+
|
| 686 |
+
class stat(_base.StatMixin, watcher):
|
| 687 |
+
_watcher_type = 'fs_poll'
|
| 688 |
+
_watcher_struct_name = 'gevent_fs_poll_t'
|
| 689 |
+
_watcher_callback_name = '_gevent_fs_poll_callback3'
|
| 690 |
+
|
| 691 |
+
def _watcher_set_data(self, the_watcher, data):
|
| 692 |
+
the_watcher.handle.data = data
|
| 693 |
+
return data
|
| 694 |
+
|
| 695 |
+
def _watcher_ffi_init(self, args):
|
| 696 |
+
return self._watcher_init(self.loop.ptr, self._watcher)
|
| 697 |
+
|
| 698 |
+
MIN_STAT_INTERVAL = 0.1074891 # match libev; 0.0 is default
|
| 699 |
+
|
| 700 |
+
def _watcher_ffi_start(self):
|
| 701 |
+
# libev changes this when the watcher is started
|
| 702 |
+
self._interval = max(self._interval, self.MIN_STAT_INTERVAL)
|
| 703 |
+
self._watcher_start(self._watcher, self._watcher_callback,
|
| 704 |
+
self._cpath,
|
| 705 |
+
int(self._interval * 1000))
|
| 706 |
+
|
| 707 |
+
@property
|
| 708 |
+
def _watcher_handle(self):
|
| 709 |
+
return self._watcher.handle.data
|
| 710 |
+
|
| 711 |
+
@property
|
| 712 |
+
def attr(self):
|
| 713 |
+
if not self._watcher.curr.st_nlink:
|
| 714 |
+
return
|
| 715 |
+
return self._watcher.curr
|
| 716 |
+
|
| 717 |
+
@property
|
| 718 |
+
def prev(self):
|
| 719 |
+
if not self._watcher.prev.st_nlink:
|
| 720 |
+
return
|
| 721 |
+
return self._watcher.prev
|
| 722 |
+
|
| 723 |
+
|
| 724 |
+
class signal(_base.SignalMixin, watcher):
|
| 725 |
+
_watcher_callback_name = '_gevent_signal_callback1'
|
| 726 |
+
|
| 727 |
+
def _watcher_ffi_init(self, args):
|
| 728 |
+
self._watcher_init(self.loop.ptr, self._watcher)
|
| 729 |
+
self.ref = False # libev doesn't ref these by default
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
def _watcher_ffi_start(self):
|
| 733 |
+
self._watcher_start(self._watcher, self._watcher_callback,
|
| 734 |
+
self._signalnum)
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
class idle(_base.IdleMixin, watcher):
|
| 738 |
+
# Because libuv doesn't support priorities, idle watchers are
|
| 739 |
+
# potentially quite a bit different than under libev
|
| 740 |
+
_watcher_callback_name = '_gevent_idle_callback0'
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
class check(_base.CheckMixin, watcher):
|
| 744 |
+
_watcher_callback_name = '_gevent_check_callback0'
|
| 745 |
+
|
| 746 |
+
class OneShotCheck(check):
|
| 747 |
+
|
| 748 |
+
_watcher_skip_ffi = True
|
| 749 |
+
|
| 750 |
+
def __make_cb(self, func):
|
| 751 |
+
stop = self.stop
|
| 752 |
+
@functools.wraps(func)
|
| 753 |
+
def cb(*args):
|
| 754 |
+
stop()
|
| 755 |
+
return func(*args)
|
| 756 |
+
return cb
|
| 757 |
+
|
| 758 |
+
def start(self, callback, *args):
|
| 759 |
+
return check.start(self, self.__make_cb(callback), *args)
|
| 760 |
+
|
| 761 |
+
class prepare(_base.PrepareMixin, watcher):
|
| 762 |
+
_watcher_callback_name = '_gevent_prepare_callback0'
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/local.py
ADDED
|
@@ -0,0 +1,610 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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False
|
| 2 |
+
"""
|
| 3 |
+
Greenlet-local objects.
|
| 4 |
+
|
| 5 |
+
This module is based on `_threading_local.py`__ from the standard
|
| 6 |
+
library of Python 3.4.
|
| 7 |
+
|
| 8 |
+
__ https://github.com/python/cpython/blob/3.4/Lib/_threading_local.py
|
| 9 |
+
|
| 10 |
+
Greenlet-local objects support the management of greenlet-local data.
|
| 11 |
+
If you have data that you want to be local to a greenlet, simply create
|
| 12 |
+
a greenlet-local object and use its attributes:
|
| 13 |
+
|
| 14 |
+
>>> import gevent
|
| 15 |
+
>>> from gevent.local import local
|
| 16 |
+
>>> mydata = local()
|
| 17 |
+
>>> mydata.number = 42
|
| 18 |
+
>>> mydata.number
|
| 19 |
+
42
|
| 20 |
+
|
| 21 |
+
You can also access the local-object's dictionary:
|
| 22 |
+
|
| 23 |
+
>>> mydata.__dict__
|
| 24 |
+
{'number': 42}
|
| 25 |
+
>>> mydata.__dict__.setdefault('widgets', [])
|
| 26 |
+
[]
|
| 27 |
+
>>> mydata.widgets
|
| 28 |
+
[]
|
| 29 |
+
|
| 30 |
+
What's important about greenlet-local objects is that their data are
|
| 31 |
+
local to a greenlet. If we access the data in a different greenlet:
|
| 32 |
+
|
| 33 |
+
>>> log = []
|
| 34 |
+
>>> def f():
|
| 35 |
+
... items = list(mydata.__dict__.items())
|
| 36 |
+
... items.sort()
|
| 37 |
+
... log.append(items)
|
| 38 |
+
... mydata.number = 11
|
| 39 |
+
... log.append(mydata.number)
|
| 40 |
+
>>> greenlet = gevent.spawn(f)
|
| 41 |
+
>>> greenlet.join()
|
| 42 |
+
>>> log
|
| 43 |
+
[[], 11]
|
| 44 |
+
|
| 45 |
+
we get different data. Furthermore, changes made in the other greenlet
|
| 46 |
+
don't affect data seen in this greenlet:
|
| 47 |
+
|
| 48 |
+
>>> mydata.number
|
| 49 |
+
42
|
| 50 |
+
|
| 51 |
+
Of course, values you get from a local object, including a __dict__
|
| 52 |
+
attribute, are for whatever greenlet was current at the time the
|
| 53 |
+
attribute was read. For that reason, you generally don't want to save
|
| 54 |
+
these values across greenlets, as they apply only to the greenlet they
|
| 55 |
+
came from.
|
| 56 |
+
|
| 57 |
+
You can create custom local objects by subclassing the local class:
|
| 58 |
+
|
| 59 |
+
>>> class MyLocal(local):
|
| 60 |
+
... number = 2
|
| 61 |
+
... initialized = False
|
| 62 |
+
... def __init__(self, **kw):
|
| 63 |
+
... if self.initialized:
|
| 64 |
+
... raise SystemError('__init__ called too many times')
|
| 65 |
+
... self.initialized = True
|
| 66 |
+
... self.__dict__.update(kw)
|
| 67 |
+
... def squared(self):
|
| 68 |
+
... return self.number ** 2
|
| 69 |
+
|
| 70 |
+
This can be useful to support default values, methods and
|
| 71 |
+
initialization. Note that if you define an __init__ method, it will be
|
| 72 |
+
called each time the local object is used in a separate greenlet. This
|
| 73 |
+
is necessary to initialize each greenlet's dictionary.
|
| 74 |
+
|
| 75 |
+
Now if we create a local object:
|
| 76 |
+
|
| 77 |
+
>>> mydata = MyLocal(color='red')
|
| 78 |
+
|
| 79 |
+
Now we have a default number:
|
| 80 |
+
|
| 81 |
+
>>> mydata.number
|
| 82 |
+
2
|
| 83 |
+
|
| 84 |
+
an initial color:
|
| 85 |
+
|
| 86 |
+
>>> mydata.color
|
| 87 |
+
'red'
|
| 88 |
+
>>> del mydata.color
|
| 89 |
+
|
| 90 |
+
And a method that operates on the data:
|
| 91 |
+
|
| 92 |
+
>>> mydata.squared()
|
| 93 |
+
4
|
| 94 |
+
|
| 95 |
+
As before, we can access the data in a separate greenlet:
|
| 96 |
+
|
| 97 |
+
>>> log = []
|
| 98 |
+
>>> greenlet = gevent.spawn(f)
|
| 99 |
+
>>> greenlet.join()
|
| 100 |
+
>>> log
|
| 101 |
+
[[('color', 'red'), ('initialized', True)], 11]
|
| 102 |
+
|
| 103 |
+
without affecting this greenlet's data:
|
| 104 |
+
|
| 105 |
+
>>> mydata.number
|
| 106 |
+
2
|
| 107 |
+
>>> mydata.color
|
| 108 |
+
Traceback (most recent call last):
|
| 109 |
+
...
|
| 110 |
+
AttributeError: 'MyLocal' object has no attribute 'color'
|
| 111 |
+
|
| 112 |
+
Note that subclasses can define slots, but they are not greenlet
|
| 113 |
+
local. They are shared across greenlets::
|
| 114 |
+
|
| 115 |
+
>>> class MyLocal(local):
|
| 116 |
+
... __slots__ = 'number'
|
| 117 |
+
|
| 118 |
+
>>> mydata = MyLocal()
|
| 119 |
+
>>> mydata.number = 42
|
| 120 |
+
>>> mydata.color = 'red'
|
| 121 |
+
|
| 122 |
+
So, the separate greenlet:
|
| 123 |
+
|
| 124 |
+
>>> greenlet = gevent.spawn(f)
|
| 125 |
+
>>> greenlet.join()
|
| 126 |
+
|
| 127 |
+
affects what we see:
|
| 128 |
+
|
| 129 |
+
>>> mydata.number
|
| 130 |
+
11
|
| 131 |
+
|
| 132 |
+
>>> del mydata
|
| 133 |
+
|
| 134 |
+
.. versionchanged:: 1.1a2
|
| 135 |
+
Update the implementation to match Python 3.4 instead of Python 2.5.
|
| 136 |
+
This results in locals being eligible for garbage collection as soon
|
| 137 |
+
as their greenlet exits.
|
| 138 |
+
|
| 139 |
+
.. versionchanged:: 1.2.3
|
| 140 |
+
Use a weak-reference to clear the greenlet link we establish in case
|
| 141 |
+
the local object dies before the greenlet does.
|
| 142 |
+
|
| 143 |
+
.. versionchanged:: 1.3a1
|
| 144 |
+
Implement the methods for attribute access directly, handling
|
| 145 |
+
descriptors directly here. This allows removing the use of a lock
|
| 146 |
+
and facilitates greatly improved performance.
|
| 147 |
+
|
| 148 |
+
.. versionchanged:: 1.3a1
|
| 149 |
+
The ``__init__`` method of subclasses of ``local`` is no longer
|
| 150 |
+
called with a lock held. CPython does not use such a lock in its
|
| 151 |
+
native implementation. This could potentially show as a difference
|
| 152 |
+
if code that uses multiple dependent attributes in ``__slots__``
|
| 153 |
+
(which are shared across all greenlets) switches during ``__init__``.
|
| 154 |
+
|
| 155 |
+
"""
|
| 156 |
+
from __future__ import print_function
|
| 157 |
+
|
| 158 |
+
from copy import copy
|
| 159 |
+
from weakref import ref
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
locals()['getcurrent'] = __import__('greenlet').getcurrent
|
| 163 |
+
locals()['greenlet_init'] = lambda: None
|
| 164 |
+
|
| 165 |
+
__all__ = [
|
| 166 |
+
"local",
|
| 167 |
+
]
|
| 168 |
+
|
| 169 |
+
# The key used in the Thread objects' attribute dicts.
|
| 170 |
+
# We keep it a string for speed but make it unlikely to clash with
|
| 171 |
+
# a "real" attribute.
|
| 172 |
+
key_prefix = '_gevent_local_localimpl_'
|
| 173 |
+
|
| 174 |
+
# The overall structure is as follows:
|
| 175 |
+
# For each local() object:
|
| 176 |
+
# greenlet.__dict__[key_prefix + str(id(local))]
|
| 177 |
+
# => _localimpl.dicts[id(greenlet)] => (ref(greenlet), {})
|
| 178 |
+
|
| 179 |
+
# That final tuple is actually a localimpl_dict_entry object.
|
| 180 |
+
|
| 181 |
+
def all_local_dicts_for_greenlet(greenlet):
|
| 182 |
+
"""
|
| 183 |
+
Internal debug helper for getting the local values associated
|
| 184 |
+
with a greenlet. This is subject to change or removal at any time.
|
| 185 |
+
|
| 186 |
+
:return: A list of ((type, id), {}) pairs, where the first element
|
| 187 |
+
is the type and id of the local object and the second object is its
|
| 188 |
+
instance dictionary, as seen from this greenlet.
|
| 189 |
+
|
| 190 |
+
.. versionadded:: 1.3a2
|
| 191 |
+
"""
|
| 192 |
+
|
| 193 |
+
result = []
|
| 194 |
+
id_greenlet = id(greenlet)
|
| 195 |
+
greenlet_dict = greenlet.__dict__
|
| 196 |
+
for k, v in greenlet_dict.items():
|
| 197 |
+
if not k.startswith(key_prefix):
|
| 198 |
+
continue
|
| 199 |
+
local_impl = v()
|
| 200 |
+
if local_impl is None:
|
| 201 |
+
continue
|
| 202 |
+
entry = local_impl.dicts.get(id_greenlet)
|
| 203 |
+
if entry is None:
|
| 204 |
+
# Not yet used in this greenlet.
|
| 205 |
+
continue
|
| 206 |
+
assert entry.wrgreenlet() is greenlet
|
| 207 |
+
result.append((local_impl.localtypeid, entry.localdict))
|
| 208 |
+
|
| 209 |
+
return result
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class _wrefdict(dict):
|
| 213 |
+
"""A dict that can be weak referenced"""
|
| 214 |
+
|
| 215 |
+
class _greenlet_deleted(object):
|
| 216 |
+
"""
|
| 217 |
+
A weakref callback for when the greenlet
|
| 218 |
+
is deleted.
|
| 219 |
+
|
| 220 |
+
If the greenlet is a `gevent.greenlet.Greenlet` and
|
| 221 |
+
supplies ``rawlink``, that will be used instead of a
|
| 222 |
+
weakref.
|
| 223 |
+
"""
|
| 224 |
+
__slots__ = ('idt', 'wrdicts')
|
| 225 |
+
|
| 226 |
+
def __init__(self, idt, wrdicts):
|
| 227 |
+
self.idt = idt
|
| 228 |
+
self.wrdicts = wrdicts
|
| 229 |
+
|
| 230 |
+
def __call__(self, _unused):
|
| 231 |
+
dicts = self.wrdicts()
|
| 232 |
+
if dicts:
|
| 233 |
+
dicts.pop(self.idt, None)
|
| 234 |
+
|
| 235 |
+
class _local_deleted(object):
|
| 236 |
+
__slots__ = ('key', 'wrthread', 'greenlet_deleted')
|
| 237 |
+
|
| 238 |
+
def __init__(self, key, wrthread, greenlet_deleted):
|
| 239 |
+
self.key = key
|
| 240 |
+
self.wrthread = wrthread
|
| 241 |
+
self.greenlet_deleted = greenlet_deleted
|
| 242 |
+
|
| 243 |
+
def __call__(self, _unused):
|
| 244 |
+
thread = self.wrthread()
|
| 245 |
+
if thread is not None:
|
| 246 |
+
try:
|
| 247 |
+
unlink = thread.unlink
|
| 248 |
+
except AttributeError:
|
| 249 |
+
pass
|
| 250 |
+
else:
|
| 251 |
+
unlink(self.greenlet_deleted)
|
| 252 |
+
del thread.__dict__[self.key]
|
| 253 |
+
|
| 254 |
+
class _localimpl(object):
|
| 255 |
+
"""A class managing thread-local dicts"""
|
| 256 |
+
__slots__ = ('key', 'dicts',
|
| 257 |
+
'localargs', 'localkwargs',
|
| 258 |
+
'localtypeid',
|
| 259 |
+
'__weakref__',)
|
| 260 |
+
|
| 261 |
+
def __init__(self, args, kwargs, local_type, id_local):
|
| 262 |
+
self.key = key_prefix + str(id(self))
|
| 263 |
+
# { id(greenlet) -> _localimpl_dict_entry(ref(greenlet), greenlet-local dict) }
|
| 264 |
+
self.dicts = _wrefdict()
|
| 265 |
+
self.localargs = args
|
| 266 |
+
self.localkwargs = kwargs
|
| 267 |
+
self.localtypeid = local_type, id_local
|
| 268 |
+
|
| 269 |
+
# We need to create the thread dict in anticipation of
|
| 270 |
+
# __init__ being called, to make sure we don't call it
|
| 271 |
+
# again ourselves. MUST do this before setting any attributes.
|
| 272 |
+
greenlet = getcurrent() # pylint:disable=undefined-variable
|
| 273 |
+
_localimpl_create_dict(self, greenlet, id(greenlet))
|
| 274 |
+
|
| 275 |
+
class _localimpl_dict_entry(object):
|
| 276 |
+
"""
|
| 277 |
+
The object that goes in the ``dicts`` of ``_localimpl``
|
| 278 |
+
object for each thread.
|
| 279 |
+
"""
|
| 280 |
+
# This is a class, not just a tuple, so that cython can optimize
|
| 281 |
+
# attribute access
|
| 282 |
+
__slots__ = ('wrgreenlet', 'localdict')
|
| 283 |
+
|
| 284 |
+
def __init__(self, wrgreenlet, localdict):
|
| 285 |
+
self.wrgreenlet = wrgreenlet
|
| 286 |
+
self.localdict = localdict
|
| 287 |
+
|
| 288 |
+
# We use functions instead of methods so that they can be cdef'd in
|
| 289 |
+
# local.pxd; if they were cdef'd as methods, they would cause
|
| 290 |
+
# the creation of a pointer and a vtable. This happens
|
| 291 |
+
# even if we declare the class @cython.final. functions thus save memory overhead
|
| 292 |
+
# (but not pointer chasing overhead; the vtable isn't used when we declare
|
| 293 |
+
# the class final).
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def _localimpl_create_dict(self, greenlet, id_greenlet):
|
| 297 |
+
"""Create a new dict for the current thread, and return it."""
|
| 298 |
+
localdict = {}
|
| 299 |
+
key = self.key
|
| 300 |
+
|
| 301 |
+
wrdicts = ref(self.dicts)
|
| 302 |
+
|
| 303 |
+
# When the greenlet is deleted, remove the local dict.
|
| 304 |
+
# Note that this is suboptimal if the greenlet object gets
|
| 305 |
+
# caught in a reference loop. We would like to be called
|
| 306 |
+
# as soon as the OS-level greenlet ends instead.
|
| 307 |
+
|
| 308 |
+
# If we are working with a gevent.greenlet.Greenlet, we
|
| 309 |
+
# can pro-actively clear out with a link, avoiding the
|
| 310 |
+
# issue described above. Use rawlink to avoid spawning any
|
| 311 |
+
# more greenlets.
|
| 312 |
+
greenlet_deleted = _greenlet_deleted(id_greenlet, wrdicts)
|
| 313 |
+
|
| 314 |
+
rawlink = getattr(greenlet, 'rawlink', None)
|
| 315 |
+
if rawlink is not None:
|
| 316 |
+
rawlink(greenlet_deleted)
|
| 317 |
+
wrthread = ref(greenlet)
|
| 318 |
+
else:
|
| 319 |
+
wrthread = ref(greenlet, greenlet_deleted)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# When the localimpl is deleted, remove the thread attribute.
|
| 323 |
+
local_deleted = _local_deleted(key, wrthread, greenlet_deleted)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
wrlocal = ref(self, local_deleted)
|
| 327 |
+
greenlet.__dict__[key] = wrlocal
|
| 328 |
+
|
| 329 |
+
self.dicts[id_greenlet] = _localimpl_dict_entry(wrthread, localdict)
|
| 330 |
+
return localdict
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
_marker = object()
|
| 334 |
+
|
| 335 |
+
def _local_get_dict(self):
|
| 336 |
+
impl = self._local__impl
|
| 337 |
+
# Cython can optimize dict[], but not dict.get()
|
| 338 |
+
greenlet = getcurrent() # pylint:disable=undefined-variable
|
| 339 |
+
idg = id(greenlet)
|
| 340 |
+
try:
|
| 341 |
+
entry = impl.dicts[idg]
|
| 342 |
+
dct = entry.localdict
|
| 343 |
+
except KeyError:
|
| 344 |
+
dct = _localimpl_create_dict(impl, greenlet, idg)
|
| 345 |
+
self.__init__(*impl.localargs, **impl.localkwargs)
|
| 346 |
+
return dct
|
| 347 |
+
|
| 348 |
+
def _init():
|
| 349 |
+
greenlet_init() # pylint:disable=undefined-variable
|
| 350 |
+
|
| 351 |
+
_local_attrs = {
|
| 352 |
+
'_local__impl',
|
| 353 |
+
'_local_type_get_descriptors',
|
| 354 |
+
'_local_type_set_or_del_descriptors',
|
| 355 |
+
'_local_type_del_descriptors',
|
| 356 |
+
'_local_type_set_descriptors',
|
| 357 |
+
'_local_type',
|
| 358 |
+
'_local_type_vars',
|
| 359 |
+
'__class__',
|
| 360 |
+
'__cinit__',
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
class local(object):
|
| 364 |
+
"""
|
| 365 |
+
An object whose attributes are greenlet-local.
|
| 366 |
+
"""
|
| 367 |
+
__slots__ = tuple(_local_attrs - {'__class__', '__cinit__'})
|
| 368 |
+
|
| 369 |
+
def __cinit__(self, *args, **kw): # pylint:disable=bad-dunder-name
|
| 370 |
+
if args or kw:
|
| 371 |
+
if type(self).__init__ == object.__init__: # pylint:disable=comparison-with-callable
|
| 372 |
+
raise TypeError("Initialization arguments are not supported", args, kw)
|
| 373 |
+
impl = _localimpl(args, kw, type(self), id(self))
|
| 374 |
+
# pylint:disable=attribute-defined-outside-init
|
| 375 |
+
self._local__impl = impl
|
| 376 |
+
get, dels, sets_or_dels, sets = _local_find_descriptors(self)
|
| 377 |
+
self._local_type_get_descriptors = get
|
| 378 |
+
self._local_type_set_or_del_descriptors = sets_or_dels
|
| 379 |
+
self._local_type_del_descriptors = dels
|
| 380 |
+
self._local_type_set_descriptors = sets
|
| 381 |
+
self._local_type = type(self)
|
| 382 |
+
self._local_type_vars = set(dir(self._local_type))
|
| 383 |
+
|
| 384 |
+
def __getattribute__(self, name): # pylint:disable=too-many-return-statements
|
| 385 |
+
if name in _local_attrs:
|
| 386 |
+
# The _local__impl, __cinit__, etc, won't be hit by the
|
| 387 |
+
# Cython version, if we've done things right. If we haven't,
|
| 388 |
+
# they will be, and this will produce an error.
|
| 389 |
+
return object.__getattribute__(self, name)
|
| 390 |
+
|
| 391 |
+
dct = _local_get_dict(self)
|
| 392 |
+
|
| 393 |
+
if name == '__dict__':
|
| 394 |
+
return dct
|
| 395 |
+
# If there's no possible way we can switch, because this
|
| 396 |
+
# attribute is *not* found in the class where it might be a
|
| 397 |
+
# data descriptor (property), and it *is* in the dict
|
| 398 |
+
# then we don't need to swizzle the dict and take the lock.
|
| 399 |
+
|
| 400 |
+
# We don't have to worry about people overriding __getattribute__
|
| 401 |
+
# because if they did, the dict-swizzling would only last as
|
| 402 |
+
# long as we were in here anyway.
|
| 403 |
+
# Similarly, a __getattr__ will still be called by _oga() if needed
|
| 404 |
+
# if it's not in the dict.
|
| 405 |
+
|
| 406 |
+
# Optimization: If we're not subclassed, then
|
| 407 |
+
# there can be no descriptors except for methods, which will
|
| 408 |
+
# never need to use __dict__.
|
| 409 |
+
if self._local_type is local:
|
| 410 |
+
return dct[name] if name in dct else object.__getattribute__(self, name)
|
| 411 |
+
|
| 412 |
+
# NOTE: If this is a descriptor, this will invoke its __get__.
|
| 413 |
+
# A broken descriptor that doesn't return itself when called with
|
| 414 |
+
# a None for the instance argument could mess us up here.
|
| 415 |
+
# But this is faster than a loop over mro() checking each class __dict__
|
| 416 |
+
# manually.
|
| 417 |
+
if name in dct:
|
| 418 |
+
if name not in self._local_type_vars:
|
| 419 |
+
# If there is a dict value, and nothing in the type,
|
| 420 |
+
# it can't possibly be a descriptor, so it is just returned.
|
| 421 |
+
return dct[name]
|
| 422 |
+
|
| 423 |
+
# It's in the type *and* in the dict. If the type value is
|
| 424 |
+
# a data descriptor (defines __get__ *and* either __set__ or
|
| 425 |
+
# __delete__), then the type wins. If it's a non-data descriptor
|
| 426 |
+
# (defines just __get__), then the instance wins. If it's not a
|
| 427 |
+
# descriptor at all (doesn't have __get__), the instance wins.
|
| 428 |
+
# NOTE that the docs for descriptors say that these methods must be
|
| 429 |
+
# defined on the *class* of the object in the type.
|
| 430 |
+
if name not in self._local_type_get_descriptors:
|
| 431 |
+
# Entirely not a descriptor. Instance wins.
|
| 432 |
+
return dct[name]
|
| 433 |
+
if name in self._local_type_set_or_del_descriptors:
|
| 434 |
+
# A data descriptor.
|
| 435 |
+
# arbitrary code execution while these run. If they touch self again,
|
| 436 |
+
# they'll call back into us and we'll repeat the dance.
|
| 437 |
+
type_attr = getattr(self._local_type, name)
|
| 438 |
+
return type(type_attr).__get__(type_attr, self, self._local_type)
|
| 439 |
+
# Last case is a non-data descriptor. Instance wins.
|
| 440 |
+
return dct[name]
|
| 441 |
+
|
| 442 |
+
if name in self._local_type_vars:
|
| 443 |
+
# Not in the dictionary, but is found in the type. It could be
|
| 444 |
+
# a non-data descriptor still. Some descriptors, like @staticmethod,
|
| 445 |
+
# return objects (functions, in this case), that are *themselves*
|
| 446 |
+
# descriptors, which when invoked, again, would do the wrong thing.
|
| 447 |
+
# So we can't rely on getattr() on the type for them, we have to
|
| 448 |
+
# look through the MRO dicts ourself.
|
| 449 |
+
if name not in self._local_type_get_descriptors:
|
| 450 |
+
# Not a descriptor, can't execute code. So all we need is
|
| 451 |
+
# the return value of getattr() on our type.
|
| 452 |
+
return getattr(self._local_type, name)
|
| 453 |
+
|
| 454 |
+
for base in self._local_type.mro():
|
| 455 |
+
bd = base.__dict__
|
| 456 |
+
if name in bd:
|
| 457 |
+
attr_on_type = bd[name]
|
| 458 |
+
result = type(attr_on_type).__get__(attr_on_type, self, self._local_type)
|
| 459 |
+
return result
|
| 460 |
+
|
| 461 |
+
# It wasn't in the dict and it wasn't in the type.
|
| 462 |
+
# So the next step is to invoke type(self)__getattr__, if it
|
| 463 |
+
# exists, otherwise raise an AttributeError.
|
| 464 |
+
# we will invoke type(self).__getattr__ or raise an attribute error.
|
| 465 |
+
if hasattr(self._local_type, '__getattr__'):
|
| 466 |
+
return self._local_type.__getattr__(self, name)
|
| 467 |
+
raise AttributeError("%r object has no attribute '%s'"
|
| 468 |
+
% (self._local_type.__name__, name))
|
| 469 |
+
|
| 470 |
+
def __setattr__(self, name, value):
|
| 471 |
+
if name == '__dict__':
|
| 472 |
+
raise AttributeError(
|
| 473 |
+
"%r object attribute '__dict__' is read-only"
|
| 474 |
+
% type(self))
|
| 475 |
+
|
| 476 |
+
if name in _local_attrs:
|
| 477 |
+
object.__setattr__(self, name, value)
|
| 478 |
+
return
|
| 479 |
+
|
| 480 |
+
dct = _local_get_dict(self)
|
| 481 |
+
|
| 482 |
+
if self._local_type is local:
|
| 483 |
+
# Optimization: If we're not subclassed, we can't
|
| 484 |
+
# have data descriptors, so this goes right in the dict.
|
| 485 |
+
dct[name] = value
|
| 486 |
+
return
|
| 487 |
+
|
| 488 |
+
if name in self._local_type_vars:
|
| 489 |
+
if name in self._local_type_set_descriptors:
|
| 490 |
+
type_attr = getattr(self._local_type, name, _marker)
|
| 491 |
+
# A data descriptor, like a property or a slot.
|
| 492 |
+
type(type_attr).__set__(type_attr, self, value)
|
| 493 |
+
return
|
| 494 |
+
# Otherwise it goes directly in the dict
|
| 495 |
+
dct[name] = value
|
| 496 |
+
|
| 497 |
+
def __delattr__(self, name):
|
| 498 |
+
if name == '__dict__':
|
| 499 |
+
raise AttributeError(
|
| 500 |
+
"%r object attribute '__dict__' is read-only"
|
| 501 |
+
% self.__class__.__name__)
|
| 502 |
+
|
| 503 |
+
if name in self._local_type_vars:
|
| 504 |
+
if name in self._local_type_del_descriptors:
|
| 505 |
+
# A data descriptor, like a property or a slot.
|
| 506 |
+
type_attr = getattr(self._local_type, name, _marker)
|
| 507 |
+
type(type_attr).__delete__(type_attr, self)
|
| 508 |
+
return
|
| 509 |
+
# Otherwise it goes directly in the dict
|
| 510 |
+
|
| 511 |
+
# Begin inlined function _get_dict()
|
| 512 |
+
dct = _local_get_dict(self)
|
| 513 |
+
|
| 514 |
+
try:
|
| 515 |
+
del dct[name]
|
| 516 |
+
except KeyError:
|
| 517 |
+
raise AttributeError(name)
|
| 518 |
+
|
| 519 |
+
def __copy__(self):
|
| 520 |
+
impl = self._local__impl
|
| 521 |
+
entry = impl.dicts[id(getcurrent())] # pylint:disable=undefined-variable
|
| 522 |
+
|
| 523 |
+
dct = entry.localdict
|
| 524 |
+
duplicate = copy(dct)
|
| 525 |
+
|
| 526 |
+
cls = type(self)
|
| 527 |
+
instance = cls(*impl.localargs, **impl.localkwargs)
|
| 528 |
+
_local__copy_dict_from(instance, impl, duplicate)
|
| 529 |
+
return instance
|
| 530 |
+
|
| 531 |
+
def _local__copy_dict_from(self, impl, duplicate):
|
| 532 |
+
current = getcurrent() # pylint:disable=undefined-variable
|
| 533 |
+
currentId = id(current)
|
| 534 |
+
new_impl = self._local__impl
|
| 535 |
+
assert new_impl is not impl
|
| 536 |
+
entry = new_impl.dicts[currentId]
|
| 537 |
+
new_impl.dicts[currentId] = _localimpl_dict_entry(entry.wrgreenlet, duplicate)
|
| 538 |
+
|
| 539 |
+
def _local_find_descriptors(self):
|
| 540 |
+
type_self = type(self)
|
| 541 |
+
gets = set()
|
| 542 |
+
dels = set()
|
| 543 |
+
set_or_del = set()
|
| 544 |
+
sets = set()
|
| 545 |
+
mro = list(type_self.mro())
|
| 546 |
+
|
| 547 |
+
for attr_name in dir(type_self):
|
| 548 |
+
# Conventionally, descriptors when called on a class
|
| 549 |
+
# return themself, but not all do. Notable exceptions are
|
| 550 |
+
# in the zope.interface package, where things like __provides__
|
| 551 |
+
# return other class attributes. So we can't use getattr, and instead
|
| 552 |
+
# walk up the dicts
|
| 553 |
+
for base in mro:
|
| 554 |
+
bd = base.__dict__
|
| 555 |
+
if attr_name in bd:
|
| 556 |
+
attr = bd[attr_name]
|
| 557 |
+
break
|
| 558 |
+
else:
|
| 559 |
+
raise AttributeError(attr_name)
|
| 560 |
+
|
| 561 |
+
type_attr = type(attr)
|
| 562 |
+
if hasattr(type_attr, '__get__'):
|
| 563 |
+
gets.add(attr_name)
|
| 564 |
+
if hasattr(type_attr, '__delete__'):
|
| 565 |
+
dels.add(attr_name)
|
| 566 |
+
set_or_del.add(attr_name)
|
| 567 |
+
if hasattr(type_attr, '__set__'):
|
| 568 |
+
sets.add(attr_name)
|
| 569 |
+
|
| 570 |
+
return (gets, dels, set_or_del, sets)
|
| 571 |
+
|
| 572 |
+
# Cython doesn't let us use __new__, it requires
|
| 573 |
+
# __cinit__. But we need __new__ if we're not compiled
|
| 574 |
+
# (e.g., on PyPy). So we set it at runtime. Cython
|
| 575 |
+
# will raise an error if we're compiled.
|
| 576 |
+
def __new__(cls, *args, **kw):
|
| 577 |
+
self = super(local, cls).__new__(cls) # pylint:disable=no-value-for-parameter
|
| 578 |
+
# We get the cls in *args for some reason
|
| 579 |
+
# too when we do it this way....except on PyPy3, which does
|
| 580 |
+
# not *unless* it's wrapped in a classmethod (which it is)
|
| 581 |
+
self.__cinit__(*args[1:], **kw)
|
| 582 |
+
return self
|
| 583 |
+
|
| 584 |
+
if local.__module__ == 'gevent.local':
|
| 585 |
+
# PyPy2/3 and CPython handle adding a __new__ to the class
|
| 586 |
+
# in different ways. In CPython and PyPy3, it must be wrapped with classmethod;
|
| 587 |
+
# in PyPy2 < 7.3.3, it must not. In either case, the args that get passed to
|
| 588 |
+
# it are stil wrong.
|
| 589 |
+
#
|
| 590 |
+
# Prior to Python 3.10, Cython-compiled classes were immutable and
|
| 591 |
+
# raised a TypeError on assignment to __new__, and we relied on that
|
| 592 |
+
# to detect the compiled version; but that breaks in
|
| 593 |
+
# 3.10 as classes are now mutable. (See
|
| 594 |
+
# https://github.com/cython/cython/issues/4326).
|
| 595 |
+
#
|
| 596 |
+
# That's OK; post https://github.com/gevent/gevent/issues/1480, the Cython-compiled
|
| 597 |
+
# module has a different name than the pure-Python version and we can check for that.
|
| 598 |
+
# It's not as direct, but it works.
|
| 599 |
+
# So here we're not compiled
|
| 600 |
+
local.__new__ = classmethod(__new__)
|
| 601 |
+
else: # pragma: no cover
|
| 602 |
+
# Make sure we revisit in case of changes to the (accelerator) module names.
|
| 603 |
+
if local.__module__ != 'gevent._gevent_clocal': # pylint:disable=else-if-used
|
| 604 |
+
raise AssertionError("Module names changed (local: %r; __name__: %r); revisit this code" % (
|
| 605 |
+
local.__module__, __name__) )
|
| 606 |
+
|
| 607 |
+
_init()
|
| 608 |
+
|
| 609 |
+
from gevent._util import import_c_accel
|
| 610 |
+
import_c_accel(globals(), 'gevent._local')
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/lock.py
ADDED
|
@@ -0,0 +1,372 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
|
| 2 |
+
"""
|
| 3 |
+
Locking primitives.
|
| 4 |
+
|
| 5 |
+
These include semaphores with arbitrary bounds (:class:`Semaphore` and
|
| 6 |
+
its safer subclass :class:`BoundedSemaphore`) and a semaphore with
|
| 7 |
+
infinite bounds (:class:`DummySemaphore`), along with a reentrant lock
|
| 8 |
+
(:class:`RLock`) with the same API as :class:`threading.RLock`.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import absolute_import
|
| 11 |
+
from __future__ import print_function
|
| 12 |
+
|
| 13 |
+
from gevent.hub import getcurrent
|
| 14 |
+
from gevent._compat import PURE_PYTHON
|
| 15 |
+
|
| 16 |
+
# This is the one exception to the rule of where to
|
| 17 |
+
# import Semaphore, obviously
|
| 18 |
+
from gevent import monkey
|
| 19 |
+
from gevent._semaphore import Semaphore
|
| 20 |
+
from gevent._semaphore import BoundedSemaphore
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = [
|
| 24 |
+
'Semaphore',
|
| 25 |
+
'BoundedSemaphore',
|
| 26 |
+
'DummySemaphore',
|
| 27 |
+
'RLock',
|
| 28 |
+
]
|
| 29 |
+
|
| 30 |
+
# On PyPy, we don't compile the Semaphore class with Cython. Under
|
| 31 |
+
# Cython, each individual method holds the GIL for its entire
|
| 32 |
+
# duration, ensuring that no other thread can interrupt us in an
|
| 33 |
+
# unsafe state (only when we _wait do we call back into Python and
|
| 34 |
+
# allow switching threads; this is broken down into the
|
| 35 |
+
# _drop_lock_for_switch_out and _acquire_lock_for_switch_in methods).
|
| 36 |
+
# Simulate that here through the use of a manual lock. (We use a
|
| 37 |
+
# separate lock for each semaphore to allow sys.settrace functions to
|
| 38 |
+
# use locks *other* than the one being traced.) This, of course, must
|
| 39 |
+
# also hold for PURE_PYTHON mode when no optional C extensions are
|
| 40 |
+
# used.
|
| 41 |
+
|
| 42 |
+
_allocate_lock, _get_ident = monkey.get_original(
|
| 43 |
+
('_thread', 'thread'),
|
| 44 |
+
('allocate_lock', 'get_ident')
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
def atomic(meth):
|
| 48 |
+
def m(self, *args):
|
| 49 |
+
with self._atomic:
|
| 50 |
+
return meth(self, *args)
|
| 51 |
+
return m
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class _GILLock(object):
|
| 55 |
+
__slots__ = (
|
| 56 |
+
'_owned_thread_id',
|
| 57 |
+
'_gil',
|
| 58 |
+
'_atomic',
|
| 59 |
+
'_recursion_depth',
|
| 60 |
+
)
|
| 61 |
+
# Don't allow re-entry to these functions in a single thread, as
|
| 62 |
+
# can happen if a sys.settrace is used. (XXX: What does that even
|
| 63 |
+
# mean? Our original implementation that did that has been
|
| 64 |
+
# replaced by something more robust)
|
| 65 |
+
#
|
| 66 |
+
# This is essentially a variant of the (pure-Python) RLock from the
|
| 67 |
+
# standard library.
|
| 68 |
+
def __init__(self):
|
| 69 |
+
self._owned_thread_id = None
|
| 70 |
+
self._gil = _allocate_lock()
|
| 71 |
+
self._atomic = _allocate_lock()
|
| 72 |
+
self._recursion_depth = 0
|
| 73 |
+
|
| 74 |
+
@atomic
|
| 75 |
+
def acquire(self):
|
| 76 |
+
current_tid = _get_ident()
|
| 77 |
+
if self._owned_thread_id == current_tid:
|
| 78 |
+
self._recursion_depth += 1
|
| 79 |
+
return True
|
| 80 |
+
|
| 81 |
+
# Not owned by this thread. Only one thread will make it through this point.
|
| 82 |
+
while 1:
|
| 83 |
+
self._atomic.release()
|
| 84 |
+
try:
|
| 85 |
+
self._gil.acquire()
|
| 86 |
+
finally:
|
| 87 |
+
self._atomic.acquire()
|
| 88 |
+
if self._owned_thread_id is None:
|
| 89 |
+
break
|
| 90 |
+
|
| 91 |
+
self._owned_thread_id = current_tid
|
| 92 |
+
self._recursion_depth = 1
|
| 93 |
+
return True
|
| 94 |
+
|
| 95 |
+
@atomic
|
| 96 |
+
def release(self):
|
| 97 |
+
current_tid = _get_ident()
|
| 98 |
+
if current_tid != self._owned_thread_id:
|
| 99 |
+
raise RuntimeError("%s: Releasing lock not owned by you. You: 0x%x; Owner: 0x%x" % (
|
| 100 |
+
self,
|
| 101 |
+
current_tid, self._owned_thread_id or 0,
|
| 102 |
+
))
|
| 103 |
+
|
| 104 |
+
self._recursion_depth -= 1
|
| 105 |
+
|
| 106 |
+
if not self._recursion_depth:
|
| 107 |
+
self._owned_thread_id = None
|
| 108 |
+
self._gil.release()
|
| 109 |
+
|
| 110 |
+
def __enter__(self):
|
| 111 |
+
self.acquire()
|
| 112 |
+
|
| 113 |
+
def __exit__(self, t, v, tb):
|
| 114 |
+
self.release()
|
| 115 |
+
|
| 116 |
+
def locked(self):
|
| 117 |
+
return self._gil.locked()
|
| 118 |
+
|
| 119 |
+
class _AtomicSemaphoreMixin(object):
|
| 120 |
+
# Behaves as though the GIL was held for the duration of acquire, wait,
|
| 121 |
+
# and release, just as if we were in Cython.
|
| 122 |
+
#
|
| 123 |
+
# acquire, wait, and release all acquire the lock on entry and release it
|
| 124 |
+
# on exit. acquire and wait can call _wait, which must release it on entry
|
| 125 |
+
# and re-acquire it for them on exit.
|
| 126 |
+
#
|
| 127 |
+
# Note that this does *NOT*, in-and-of itself, make semaphores safe to use from multiple threads
|
| 128 |
+
__slots__ = ()
|
| 129 |
+
def __init__(self, *args, **kwargs):
|
| 130 |
+
self._lock_lock = _GILLock() # pylint:disable=assigning-non-slot
|
| 131 |
+
super(_AtomicSemaphoreMixin, self).__init__(*args, **kwargs)
|
| 132 |
+
|
| 133 |
+
def _acquire_lock_for_switch_in(self):
|
| 134 |
+
self._lock_lock.acquire()
|
| 135 |
+
|
| 136 |
+
def _drop_lock_for_switch_out(self):
|
| 137 |
+
self._lock_lock.release()
|
| 138 |
+
|
| 139 |
+
def _notify_links(self, arrived_while_waiting):
|
| 140 |
+
with self._lock_lock:
|
| 141 |
+
return super(_AtomicSemaphoreMixin, self)._notify_links(arrived_while_waiting)
|
| 142 |
+
|
| 143 |
+
def release(self):
|
| 144 |
+
with self._lock_lock:
|
| 145 |
+
return super(_AtomicSemaphoreMixin, self).release()
|
| 146 |
+
|
| 147 |
+
def acquire(self, blocking=True, timeout=None):
|
| 148 |
+
with self._lock_lock:
|
| 149 |
+
return super(_AtomicSemaphoreMixin, self).acquire(blocking, timeout)
|
| 150 |
+
|
| 151 |
+
_py3k_acquire = acquire
|
| 152 |
+
|
| 153 |
+
def wait(self, timeout=None):
|
| 154 |
+
with self._lock_lock:
|
| 155 |
+
return super(_AtomicSemaphoreMixin, self).wait(timeout)
|
| 156 |
+
|
| 157 |
+
class _AtomicSemaphore(_AtomicSemaphoreMixin, Semaphore):
|
| 158 |
+
__doc__ = Semaphore.__doc__
|
| 159 |
+
__slots__ = (
|
| 160 |
+
'_lock_lock',
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
class _AtomicBoundedSemaphore(_AtomicSemaphoreMixin, BoundedSemaphore):
|
| 165 |
+
__doc__ = BoundedSemaphore.__doc__
|
| 166 |
+
__slots__ = (
|
| 167 |
+
'_lock_lock',
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def release(self): # pylint:disable=useless-super-delegation
|
| 171 |
+
# This method is duplicated here so that it can get
|
| 172 |
+
# properly documented.
|
| 173 |
+
return super(_AtomicBoundedSemaphore, self).release()
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def _fixup_docstrings():
|
| 177 |
+
for c in _AtomicSemaphore, _AtomicBoundedSemaphore:
|
| 178 |
+
b = c.__mro__[2]
|
| 179 |
+
assert b.__name__.endswith('Semaphore') and 'Atomic' not in b.__name__
|
| 180 |
+
assert c.__doc__ == b.__doc__
|
| 181 |
+
for m in 'acquire', 'release', 'wait':
|
| 182 |
+
c_meth = getattr(c, m)
|
| 183 |
+
b_meth = getattr(b, m)
|
| 184 |
+
c_meth.__doc__ = b_meth.__doc__
|
| 185 |
+
|
| 186 |
+
_fixup_docstrings()
|
| 187 |
+
del _fixup_docstrings
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
if PURE_PYTHON:
|
| 191 |
+
Semaphore = _AtomicSemaphore
|
| 192 |
+
Semaphore.__name__ = 'Semaphore'
|
| 193 |
+
BoundedSemaphore = _AtomicBoundedSemaphore
|
| 194 |
+
BoundedSemaphore.__name__ = 'BoundedSemaphore'
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class DummySemaphore(object):
|
| 198 |
+
"""
|
| 199 |
+
DummySemaphore(value=None) -> DummySemaphore
|
| 200 |
+
|
| 201 |
+
An object with the same API as :class:`Semaphore`,
|
| 202 |
+
initialized with "infinite" initial value. None of its
|
| 203 |
+
methods ever block.
|
| 204 |
+
|
| 205 |
+
This can be used to parameterize on whether or not to actually
|
| 206 |
+
guard access to a potentially limited resource. If the resource is
|
| 207 |
+
actually limited, such as a fixed-size thread pool, use a real
|
| 208 |
+
:class:`Semaphore`, but if the resource is unbounded, use an
|
| 209 |
+
instance of this class. In that way none of the supporting code
|
| 210 |
+
needs to change.
|
| 211 |
+
|
| 212 |
+
Similarly, it can be used to parameterize on whether or not to
|
| 213 |
+
enforce mutual exclusion to some underlying object. If the
|
| 214 |
+
underlying object is known to be thread-safe itself mutual
|
| 215 |
+
exclusion is not needed and a ``DummySemaphore`` can be used, but
|
| 216 |
+
if that's not true, use a real ``Semaphore``.
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
# Internally this is used for exactly the purpose described in the
|
| 220 |
+
# documentation. gevent.pool.Pool uses it instead of a Semaphore
|
| 221 |
+
# when the pool size is unlimited, and
|
| 222 |
+
# gevent.fileobject.FileObjectThread takes a parameter that
|
| 223 |
+
# determines whether it should lock around IO to the underlying
|
| 224 |
+
# file object.
|
| 225 |
+
|
| 226 |
+
def __init__(self, value=None):
|
| 227 |
+
"""
|
| 228 |
+
.. versionchanged:: 1.1rc3
|
| 229 |
+
Accept and ignore a *value* argument for compatibility with Semaphore.
|
| 230 |
+
"""
|
| 231 |
+
|
| 232 |
+
def __str__(self):
|
| 233 |
+
return '<%s>' % self.__class__.__name__
|
| 234 |
+
|
| 235 |
+
def locked(self):
|
| 236 |
+
"""A DummySemaphore is never locked so this always returns False."""
|
| 237 |
+
return False
|
| 238 |
+
|
| 239 |
+
def ready(self):
|
| 240 |
+
"""A DummySemaphore is never locked so this always returns True."""
|
| 241 |
+
return True
|
| 242 |
+
|
| 243 |
+
def release(self):
|
| 244 |
+
"""Releasing a dummy semaphore does nothing."""
|
| 245 |
+
|
| 246 |
+
def rawlink(self, callback):
|
| 247 |
+
# XXX should still work and notify?
|
| 248 |
+
pass
|
| 249 |
+
|
| 250 |
+
def unlink(self, callback):
|
| 251 |
+
pass
|
| 252 |
+
|
| 253 |
+
def wait(self, timeout=None): # pylint:disable=unused-argument
|
| 254 |
+
"""Waiting for a DummySemaphore returns immediately."""
|
| 255 |
+
return 1
|
| 256 |
+
|
| 257 |
+
def acquire(self, blocking=True, timeout=None):
|
| 258 |
+
"""
|
| 259 |
+
A DummySemaphore can always be acquired immediately so this always
|
| 260 |
+
returns True and ignores its arguments.
|
| 261 |
+
|
| 262 |
+
.. versionchanged:: 1.1a1
|
| 263 |
+
Always return *true*.
|
| 264 |
+
"""
|
| 265 |
+
# pylint:disable=unused-argument
|
| 266 |
+
return True
|
| 267 |
+
|
| 268 |
+
def __enter__(self):
|
| 269 |
+
pass
|
| 270 |
+
|
| 271 |
+
def __exit__(self, typ, val, tb):
|
| 272 |
+
pass
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
class RLock(object):
|
| 276 |
+
"""
|
| 277 |
+
A mutex that can be acquired more than once by the same greenlet.
|
| 278 |
+
|
| 279 |
+
A mutex can only be locked by one greenlet at a time. A single greenlet
|
| 280 |
+
can `acquire` the mutex as many times as desired, though. Each call to
|
| 281 |
+
`acquire` must be paired with a matching call to `release`.
|
| 282 |
+
|
| 283 |
+
It is an error for a greenlet that has not acquired the mutex
|
| 284 |
+
to release it.
|
| 285 |
+
|
| 286 |
+
Instances are context managers.
|
| 287 |
+
"""
|
| 288 |
+
|
| 289 |
+
__slots__ = (
|
| 290 |
+
'_block',
|
| 291 |
+
'_owner',
|
| 292 |
+
'_count',
|
| 293 |
+
'__weakref__',
|
| 294 |
+
)
|
| 295 |
+
|
| 296 |
+
def __init__(self, hub=None):
|
| 297 |
+
"""
|
| 298 |
+
.. versionchanged:: 20.5.1
|
| 299 |
+
Add the ``hub`` argument.
|
| 300 |
+
"""
|
| 301 |
+
self._block = Semaphore(1, hub)
|
| 302 |
+
self._owner = None
|
| 303 |
+
self._count = 0
|
| 304 |
+
|
| 305 |
+
def __repr__(self):
|
| 306 |
+
return "<%s at 0x%x _block=%s _count=%r _owner=%r)>" % (
|
| 307 |
+
self.__class__.__name__,
|
| 308 |
+
id(self),
|
| 309 |
+
self._block,
|
| 310 |
+
self._count,
|
| 311 |
+
self._owner)
|
| 312 |
+
|
| 313 |
+
def acquire(self, blocking=True, timeout=None):
|
| 314 |
+
"""
|
| 315 |
+
Acquire the mutex, blocking if *blocking* is true, for up to
|
| 316 |
+
*timeout* seconds.
|
| 317 |
+
|
| 318 |
+
.. versionchanged:: 1.5a4
|
| 319 |
+
Added the *timeout* parameter.
|
| 320 |
+
|
| 321 |
+
:return: A boolean indicating whether the mutex was acquired.
|
| 322 |
+
"""
|
| 323 |
+
me = getcurrent()
|
| 324 |
+
if self._owner is me:
|
| 325 |
+
self._count += 1
|
| 326 |
+
return 1
|
| 327 |
+
rc = self._block.acquire(blocking, timeout)
|
| 328 |
+
if rc:
|
| 329 |
+
self._owner = me
|
| 330 |
+
self._count = 1
|
| 331 |
+
return rc
|
| 332 |
+
|
| 333 |
+
def __enter__(self):
|
| 334 |
+
return self.acquire()
|
| 335 |
+
|
| 336 |
+
def release(self):
|
| 337 |
+
"""
|
| 338 |
+
Release the mutex.
|
| 339 |
+
|
| 340 |
+
Only the greenlet that originally acquired the mutex can
|
| 341 |
+
release it.
|
| 342 |
+
"""
|
| 343 |
+
if self._owner is not getcurrent():
|
| 344 |
+
raise RuntimeError("cannot release un-acquired lock. Owner: %r Current: %r" % (
|
| 345 |
+
self._owner, getcurrent()
|
| 346 |
+
))
|
| 347 |
+
self._count = count = self._count - 1 # pylint:disable=consider-using-augmented-assign
|
| 348 |
+
if not count:
|
| 349 |
+
self._owner = None
|
| 350 |
+
self._block.release()
|
| 351 |
+
|
| 352 |
+
def __exit__(self, typ, value, tb):
|
| 353 |
+
self.release()
|
| 354 |
+
|
| 355 |
+
# Internal methods used by condition variables
|
| 356 |
+
|
| 357 |
+
def _acquire_restore(self, count_owner):
|
| 358 |
+
count, owner = count_owner
|
| 359 |
+
self._block.acquire()
|
| 360 |
+
self._count = count
|
| 361 |
+
self._owner = owner
|
| 362 |
+
|
| 363 |
+
def _release_save(self):
|
| 364 |
+
count = self._count
|
| 365 |
+
self._count = 0
|
| 366 |
+
owner = self._owner
|
| 367 |
+
self._owner = None
|
| 368 |
+
self._block.release()
|
| 369 |
+
return (count, owner)
|
| 370 |
+
|
| 371 |
+
def _is_owned(self):
|
| 372 |
+
return self._owner is getcurrent()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__init__.py
ADDED
|
@@ -0,0 +1,704 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2009-2012 Denis Bilenko. See LICENSE for details.
|
| 2 |
+
# pylint: disable=redefined-outer-name,too-many-lines
|
| 3 |
+
"""
|
| 4 |
+
Make the standard library cooperative.
|
| 5 |
+
|
| 6 |
+
The primary purpose of this module is to carefully patch, in place,
|
| 7 |
+
portions of the standard library with gevent-friendly functions that
|
| 8 |
+
behave in the same way as the original (at least as closely as possible).
|
| 9 |
+
|
| 10 |
+
The primary interface to this is the :func:`patch_all` function, which
|
| 11 |
+
performs all the available patches. It accepts arguments to limit the
|
| 12 |
+
patching to certain modules, but most programs **should** use the
|
| 13 |
+
default values as they receive the most wide-spread testing, and some monkey
|
| 14 |
+
patches have dependencies on others.
|
| 15 |
+
|
| 16 |
+
Patching **should be done as early as possible** in the lifecycle of the
|
| 17 |
+
program. For example, the main module (the one that tests against
|
| 18 |
+
``__main__`` or is otherwise the first imported) should begin with
|
| 19 |
+
this code, ideally before any other imports::
|
| 20 |
+
|
| 21 |
+
from gevent import monkey
|
| 22 |
+
monkey.patch_all()
|
| 23 |
+
|
| 24 |
+
A corollary of the above is that patching **should be done on the main
|
| 25 |
+
thread** and **should be done while the program is single-threaded**.
|
| 26 |
+
|
| 27 |
+
.. tip::
|
| 28 |
+
|
| 29 |
+
Some frameworks, such as gunicorn, handle monkey-patching for you.
|
| 30 |
+
Check their documentation to be sure.
|
| 31 |
+
|
| 32 |
+
.. warning::
|
| 33 |
+
|
| 34 |
+
Patching too late can lead to unreliable behaviour (for example, some
|
| 35 |
+
modules may still use blocking sockets) or even errors.
|
| 36 |
+
|
| 37 |
+
.. tip::
|
| 38 |
+
|
| 39 |
+
Be sure to read the documentation for each patch function to check for
|
| 40 |
+
known incompatibilities.
|
| 41 |
+
|
| 42 |
+
Querying
|
| 43 |
+
========
|
| 44 |
+
|
| 45 |
+
Sometimes it is helpful to know if objects have been monkey-patched, and in
|
| 46 |
+
advanced cases even to have access to the original standard library functions. This
|
| 47 |
+
module provides functions for that purpose.
|
| 48 |
+
|
| 49 |
+
- :func:`is_module_patched`
|
| 50 |
+
- :func:`is_object_patched`
|
| 51 |
+
- :func:`get_original`
|
| 52 |
+
|
| 53 |
+
.. _plugins:
|
| 54 |
+
|
| 55 |
+
Plugins and Events
|
| 56 |
+
==================
|
| 57 |
+
|
| 58 |
+
Beginning in gevent 1.3, events are emitted during the monkey patching process.
|
| 59 |
+
These events are delivered first to :mod:`gevent.events` subscribers, and then
|
| 60 |
+
to `setuptools entry points`_.
|
| 61 |
+
|
| 62 |
+
The following events are defined. They are listed in (roughly) the order
|
| 63 |
+
that a call to :func:`patch_all` will emit them.
|
| 64 |
+
|
| 65 |
+
- :class:`gevent.events.GeventWillPatchAllEvent`
|
| 66 |
+
- :class:`gevent.events.GeventWillPatchModuleEvent`
|
| 67 |
+
- :class:`gevent.events.GeventDidPatchModuleEvent`
|
| 68 |
+
- :class:`gevent.events.GeventDidPatchBuiltinModulesEvent`
|
| 69 |
+
- :class:`gevent.events.GeventDidPatchAllEvent`
|
| 70 |
+
|
| 71 |
+
Each event class documents the corresponding setuptools entry point name. The
|
| 72 |
+
entry points will be called with a single argument, the same instance of
|
| 73 |
+
the class that was sent to the subscribers.
|
| 74 |
+
|
| 75 |
+
You can subscribe to the events to monitor the monkey-patching process and
|
| 76 |
+
to manipulate it, for example by raising :exc:`gevent.events.DoNotPatch`.
|
| 77 |
+
|
| 78 |
+
You can also subscribe to the events to provide additional patching beyond what
|
| 79 |
+
gevent distributes, either for additional standard library modules, or
|
| 80 |
+
for third-party packages. The suggested time to do this patching is in
|
| 81 |
+
the subscriber for :class:`gevent.events.GeventDidPatchBuiltinModulesEvent`.
|
| 82 |
+
For example, to automatically patch `psycopg2`_ using `psycogreen`_
|
| 83 |
+
when the call to :func:`patch_all` is made, you could write code like this::
|
| 84 |
+
|
| 85 |
+
# mypackage.py
|
| 86 |
+
def patch_psycopg(event):
|
| 87 |
+
from psycogreen.gevent import patch_psycopg
|
| 88 |
+
patch_psycopg()
|
| 89 |
+
|
| 90 |
+
In your ``setup.py`` you would register it like this::
|
| 91 |
+
|
| 92 |
+
from setuptools import setup
|
| 93 |
+
setup(
|
| 94 |
+
...
|
| 95 |
+
entry_points={
|
| 96 |
+
'gevent.plugins.monkey.did_patch_builtins': [
|
| 97 |
+
'psycopg2 = mypackage:patch_psycopg',
|
| 98 |
+
],
|
| 99 |
+
},
|
| 100 |
+
...
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
For more complex patching, gevent provides a helper method
|
| 104 |
+
that you can call to replace attributes of modules with attributes of your
|
| 105 |
+
own modules. This function also takes care of emitting the appropriate events.
|
| 106 |
+
|
| 107 |
+
- :func:`patch_module`
|
| 108 |
+
|
| 109 |
+
.. _setuptools entry points: http://setuptools.readthedocs.io/en/latest/setuptools.html#dynamic-discovery-of-services-and-plugins
|
| 110 |
+
.. _psycopg2: https://pypi.python.org/pypi/psycopg2
|
| 111 |
+
.. _psycogreen: https://pypi.python.org/pypi/psycogreen
|
| 112 |
+
|
| 113 |
+
Use as a module
|
| 114 |
+
===============
|
| 115 |
+
|
| 116 |
+
Sometimes it is useful to run existing python scripts or modules that
|
| 117 |
+
were not built to be gevent aware under gevent. To do so, this module
|
| 118 |
+
can be run as the main module, passing the script and its arguments.
|
| 119 |
+
For details, see the :func:`main` function.
|
| 120 |
+
|
| 121 |
+
.. versionchanged:: 1.3b1
|
| 122 |
+
Added support for plugins and began emitting will/did patch events.
|
| 123 |
+
"""
|
| 124 |
+
|
| 125 |
+
import sys
|
| 126 |
+
|
| 127 |
+
####
|
| 128 |
+
# gevent developers: IMPORTANT: Keep imports
|
| 129 |
+
# as limited and localized as possible to avoid
|
| 130 |
+
# interfering with the monkey-patch process.
|
| 131 |
+
# This is why many imports are nested inside functions.
|
| 132 |
+
#
|
| 133 |
+
# This applies for this entire package.
|
| 134 |
+
###
|
| 135 |
+
|
| 136 |
+
__all__ = [
|
| 137 |
+
'patch_all',
|
| 138 |
+
'patch_builtins',
|
| 139 |
+
'patch_dns',
|
| 140 |
+
'patch_os',
|
| 141 |
+
'patch_queue',
|
| 142 |
+
'patch_select',
|
| 143 |
+
'patch_signal',
|
| 144 |
+
'patch_socket',
|
| 145 |
+
'patch_ssl',
|
| 146 |
+
'patch_subprocess',
|
| 147 |
+
'patch_sys',
|
| 148 |
+
'patch_thread',
|
| 149 |
+
'patch_time',
|
| 150 |
+
# query functions
|
| 151 |
+
'get_original',
|
| 152 |
+
'is_module_patched',
|
| 153 |
+
'is_object_patched',
|
| 154 |
+
|
| 155 |
+
# 'is_anything_patched', <- see docstring
|
| 156 |
+
|
| 157 |
+
# plugin API
|
| 158 |
+
'patch_module',
|
| 159 |
+
# module functions
|
| 160 |
+
'main',
|
| 161 |
+
# Errors and warnings
|
| 162 |
+
'MonkeyPatchWarning',
|
| 163 |
+
]
|
| 164 |
+
|
| 165 |
+
WIN = sys.platform.startswith("win")
|
| 166 |
+
|
| 167 |
+
# Unused imports may be removed in a major release after 2024-10.
|
| 168 |
+
# Used private imports may be renamed or removed or changed
|
| 169 |
+
# in an incompatible way at that time.
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
from ._errors import MonkeyPatchWarning
|
| 174 |
+
|
| 175 |
+
from ._util import _notify_patch
|
| 176 |
+
from ._util import _ignores_DoNotPatch
|
| 177 |
+
|
| 178 |
+
from ._state import saved
|
| 179 |
+
from ._state import is_module_patched
|
| 180 |
+
from ._state import is_object_patched
|
| 181 |
+
|
| 182 |
+
# Never documented as a public API, but
|
| 183 |
+
# potentially in use by third parties
|
| 184 |
+
# given the naming convention.
|
| 185 |
+
from ._state import is_anything_patched # pylint:disable=unused-import
|
| 186 |
+
from ._errors import _BadImplements # pylint:disable=unused-import
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
from .api import get_original
|
| 191 |
+
from .api import patch_module
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
# These are not part of the documented public API,
|
| 196 |
+
# but they could be used by plugins. TODO: Do we
|
| 197 |
+
# want to make them public with __all__?
|
| 198 |
+
from .api import patch_item
|
| 199 |
+
from .api import remove_item
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
from ._util import _check_availability
|
| 209 |
+
from ._util import _patch_module
|
| 210 |
+
from ._util import _queue_warning
|
| 211 |
+
from ._util import _process_warnings
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def _patch_sys_std(name):
|
| 216 |
+
from gevent.fileobject import FileObjectThread
|
| 217 |
+
orig = getattr(sys, name)
|
| 218 |
+
if not isinstance(orig, FileObjectThread):
|
| 219 |
+
patch_item(sys, name, FileObjectThread(orig))
|
| 220 |
+
|
| 221 |
+
@_ignores_DoNotPatch
|
| 222 |
+
def patch_sys(stdin=True, stdout=True, stderr=True): # pylint:disable=unused-argument
|
| 223 |
+
"""
|
| 224 |
+
Patch sys.std[in,out,err] to use a cooperative IO via a
|
| 225 |
+
threadpool.
|
| 226 |
+
|
| 227 |
+
This is relatively dangerous and can have unintended consequences
|
| 228 |
+
such as hanging the process or `misinterpreting control keys`_
|
| 229 |
+
when :func:`input` and :func:`raw_input` are used. :func:`patch_all`
|
| 230 |
+
does *not* call this function by default.
|
| 231 |
+
|
| 232 |
+
This method does nothing on Python 3. The Python 3 interpreter
|
| 233 |
+
wants to flush the TextIOWrapper objects that make up
|
| 234 |
+
stderr/stdout at shutdown time, but using a threadpool at that
|
| 235 |
+
time leads to a hang.
|
| 236 |
+
|
| 237 |
+
.. _`misinterpreting control keys`: https://github.com/gevent/gevent/issues/274
|
| 238 |
+
|
| 239 |
+
.. deprecated:: 23.7.0
|
| 240 |
+
Does nothing on any supported version.
|
| 241 |
+
"""
|
| 242 |
+
return
|
| 243 |
+
|
| 244 |
+
@_ignores_DoNotPatch
|
| 245 |
+
def patch_os():
|
| 246 |
+
"""
|
| 247 |
+
Replace :func:`os.fork` with :func:`gevent.fork`, and, on POSIX,
|
| 248 |
+
:func:`os.waitpid` with :func:`gevent.os.waitpid` (if the
|
| 249 |
+
environment variable ``GEVENT_NOWAITPID`` is not defined). Does
|
| 250 |
+
nothing if fork is not available.
|
| 251 |
+
|
| 252 |
+
.. caution:: This method must be used with :func:`patch_signal` to have proper `SIGCHLD`
|
| 253 |
+
handling and thus correct results from ``waitpid``.
|
| 254 |
+
:func:`patch_all` calls both by default.
|
| 255 |
+
|
| 256 |
+
.. caution:: For `SIGCHLD` handling to work correctly, the event loop must run.
|
| 257 |
+
The easiest way to help ensure this is to use :func:`patch_all`.
|
| 258 |
+
"""
|
| 259 |
+
_patch_module('os')
|
| 260 |
+
|
| 261 |
+
|
| 262 |
+
@_ignores_DoNotPatch
|
| 263 |
+
def patch_queue():
|
| 264 |
+
"""
|
| 265 |
+
Patch objects in :mod:`queue`.
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
Currently, this just replaces :class:`queue.SimpleQueue` (implemented
|
| 269 |
+
in C) with its Python counterpart, but the details may change at any time.
|
| 270 |
+
|
| 271 |
+
.. versionadded:: 1.3.5
|
| 272 |
+
"""
|
| 273 |
+
_patch_module('queue', items=[
|
| 274 |
+
'SimpleQueue',
|
| 275 |
+
])
|
| 276 |
+
|
| 277 |
+
|
| 278 |
+
@_ignores_DoNotPatch
|
| 279 |
+
def patch_time():
|
| 280 |
+
"""
|
| 281 |
+
Replace :func:`time.sleep` with :func:`gevent.sleep`.
|
| 282 |
+
"""
|
| 283 |
+
_patch_module('time')
|
| 284 |
+
|
| 285 |
+
@_ignores_DoNotPatch
|
| 286 |
+
def patch_contextvars():
|
| 287 |
+
"""
|
| 288 |
+
Replaces the implementations of :mod:`contextvars` with
|
| 289 |
+
:mod:`gevent.contextvars`.
|
| 290 |
+
|
| 291 |
+
On Python 3.7 and above, this is a standard library module. On
|
| 292 |
+
earlier versions, a backport that uses the same distribution name
|
| 293 |
+
and import name is available on PyPI (though this is not
|
| 294 |
+
recommended). If that is installed, it will be patched.
|
| 295 |
+
|
| 296 |
+
.. versionchanged:: 20.04.0
|
| 297 |
+
Clarify that the backport is also patched.
|
| 298 |
+
|
| 299 |
+
.. versionchanged:: 20.9.0
|
| 300 |
+
This now does nothing on Python 3.7 and above.
|
| 301 |
+
gevent now depends on greenlet 0.4.17, which
|
| 302 |
+
natively handles switching context vars when greenlets are switched.
|
| 303 |
+
Older versions of Python that have the backport installed will
|
| 304 |
+
still be patched.
|
| 305 |
+
|
| 306 |
+
.. deprecated:: 23.7.0
|
| 307 |
+
Does nothing on any supported version.
|
| 308 |
+
"""
|
| 309 |
+
return
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
@_ignores_DoNotPatch
|
| 314 |
+
def patch_thread(threading=True, _threading_local=True, Event=True, logging=True,
|
| 315 |
+
existing_locks=True,
|
| 316 |
+
_warnings=None):
|
| 317 |
+
"""
|
| 318 |
+
patch_thread(threading=True, _threading_local=True, Event=True, logging=True, existing_locks=True) -> None
|
| 319 |
+
|
| 320 |
+
Replace the standard :mod:`thread` module to make it greenlet-based.
|
| 321 |
+
|
| 322 |
+
:keyword bool threading: When True (the default),
|
| 323 |
+
also patch :mod:`threading`.
|
| 324 |
+
:keyword bool _threading_local: When True (the default),
|
| 325 |
+
also patch :class:`_threading_local.local`.
|
| 326 |
+
:keyword bool logging: When True (the default), also patch locks
|
| 327 |
+
taken if the logging module has been configured.
|
| 328 |
+
|
| 329 |
+
:keyword bool existing_locks: When True (the default), and the
|
| 330 |
+
process is still single threaded, make sure that any
|
| 331 |
+
:class:`threading.RLock` (and, under Python 3, :class:`importlib._bootstrap._ModuleLock`)
|
| 332 |
+
instances that are currently locked can be properly unlocked. **Important**: This is a
|
| 333 |
+
best-effort attempt and, on certain implementations, may not detect all
|
| 334 |
+
locks. It is important to monkey-patch extremely early in the startup process.
|
| 335 |
+
Setting this to False is not recommended, especially on Python 2.
|
| 336 |
+
|
| 337 |
+
.. caution::
|
| 338 |
+
Monkey-patching :mod:`thread` and using
|
| 339 |
+
:class:`multiprocessing.Queue` or
|
| 340 |
+
:class:`concurrent.futures.ProcessPoolExecutor` (which uses a
|
| 341 |
+
``Queue``) will hang the process.
|
| 342 |
+
|
| 343 |
+
Monkey-patching with this function and using
|
| 344 |
+
sub-interpreters (and advanced C-level API) and threads may be
|
| 345 |
+
unstable on certain platforms.
|
| 346 |
+
|
| 347 |
+
.. versionchanged:: 1.1b1
|
| 348 |
+
Add *logging* and *existing_locks* params.
|
| 349 |
+
.. versionchanged:: 1.3a2
|
| 350 |
+
``Event`` defaults to True.
|
| 351 |
+
"""
|
| 352 |
+
if sys.version_info[:2] < (3, 13):
|
| 353 |
+
from ._patch_thread_lt313 import Patcher
|
| 354 |
+
else:
|
| 355 |
+
from ._patch_thread_gte313 import Patcher
|
| 356 |
+
patch = Patcher(threading=threading, _threading_local=_threading_local, Event=Event,
|
| 357 |
+
logging=logging, existing_locks=existing_locks, _warnings=_warnings)
|
| 358 |
+
patch()
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
@_ignores_DoNotPatch
|
| 362 |
+
def patch_socket(dns=True, aggressive=True):
|
| 363 |
+
"""
|
| 364 |
+
Replace the standard socket object with gevent's cooperative
|
| 365 |
+
sockets.
|
| 366 |
+
|
| 367 |
+
:keyword bool dns: When true (the default), also patch address
|
| 368 |
+
resolution functions in :mod:`socket`. See :doc:`/dns` for details.
|
| 369 |
+
"""
|
| 370 |
+
from gevent import socket
|
| 371 |
+
# Note: although it seems like it's not strictly necessary to monkey patch 'create_connection',
|
| 372 |
+
# it's better to do it. If 'create_connection' was not monkey patched, but the rest of socket module
|
| 373 |
+
# was, create_connection would still use "green" getaddrinfo and "green" socket.
|
| 374 |
+
# However, because gevent.socket.socket.connect is a Python function, the exception raised by it causes
|
| 375 |
+
# _socket object to be referenced by the frame, thus causing the next invocation of bind(source_address) to fail.
|
| 376 |
+
if dns:
|
| 377 |
+
items = socket.__implements__ # pylint:disable=no-member
|
| 378 |
+
else:
|
| 379 |
+
items = set(socket.__implements__) - set(socket.__dns__) # pylint:disable=no-member
|
| 380 |
+
_patch_module('socket', items=items)
|
| 381 |
+
if aggressive:
|
| 382 |
+
if 'ssl' not in socket.__implements__: # pylint:disable=no-member
|
| 383 |
+
remove_item(socket, 'ssl')
|
| 384 |
+
|
| 385 |
+
@_ignores_DoNotPatch
|
| 386 |
+
def patch_dns():
|
| 387 |
+
"""
|
| 388 |
+
Replace :doc:`DNS functions </dns>` in :mod:`socket` with
|
| 389 |
+
cooperative versions.
|
| 390 |
+
|
| 391 |
+
This is only useful if :func:`patch_socket` has been called and is
|
| 392 |
+
done automatically by that method if requested.
|
| 393 |
+
"""
|
| 394 |
+
from gevent import socket
|
| 395 |
+
_patch_module('socket', items=socket.__dns__) # pylint:disable=no-member
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def _find_module_refs(to, excluding_names=()):
|
| 399 |
+
# Looks specifically for module-level references,
|
| 400 |
+
# i.e., 'from foo import Bar'. We define a module reference
|
| 401 |
+
# as a dict (subclass) that also has a __name__ attribute.
|
| 402 |
+
# This does not handle subclasses, but it does find them.
|
| 403 |
+
# Returns two sets. The first is modules (name, file) that were
|
| 404 |
+
# found. The second is subclasses that were found.
|
| 405 |
+
gc = __import__('gc')
|
| 406 |
+
direct_ref_modules = set()
|
| 407 |
+
subclass_modules = set()
|
| 408 |
+
|
| 409 |
+
def report(mod):
|
| 410 |
+
return mod['__name__'], mod.get('__file__', '<unknown>')
|
| 411 |
+
|
| 412 |
+
for r in gc.get_referrers(to):
|
| 413 |
+
if isinstance(r, dict) and '__name__' in r:
|
| 414 |
+
if r['__name__'] in excluding_names:
|
| 415 |
+
continue
|
| 416 |
+
|
| 417 |
+
for v in r.values():
|
| 418 |
+
if v is to:
|
| 419 |
+
direct_ref_modules.add(report(r))
|
| 420 |
+
elif isinstance(r, type) and to in r.__bases__ and 'gevent.' not in r.__module__:
|
| 421 |
+
subclass_modules.add(r)
|
| 422 |
+
|
| 423 |
+
return direct_ref_modules, subclass_modules
|
| 424 |
+
|
| 425 |
+
@_ignores_DoNotPatch
|
| 426 |
+
def patch_ssl(_warnings=None, _first_time=True):
|
| 427 |
+
"""
|
| 428 |
+
patch_ssl() -> None
|
| 429 |
+
|
| 430 |
+
Replace :class:`ssl.SSLSocket` object and socket wrapping functions in
|
| 431 |
+
:mod:`ssl` with cooperative versions.
|
| 432 |
+
|
| 433 |
+
This is only useful if :func:`patch_socket` has been called.
|
| 434 |
+
"""
|
| 435 |
+
may_need_warning = (
|
| 436 |
+
_first_time
|
| 437 |
+
and 'ssl' in sys.modules
|
| 438 |
+
and hasattr(sys.modules['ssl'], 'SSLContext'))
|
| 439 |
+
# Previously, we didn't warn on Python 2 if pkg_resources has been imported
|
| 440 |
+
# because that imports ssl and it's commonly used for namespace packages,
|
| 441 |
+
# which typically means we're still in some early part of the import cycle.
|
| 442 |
+
# However, with our new more discriminating check, that no longer seems to be a problem.
|
| 443 |
+
# Prior to 3.6, we don't have the RecursionError problem, and prior to 3.7 we don't have the
|
| 444 |
+
# SSLContext.sslsocket_class/SSLContext.sslobject_class problem.
|
| 445 |
+
|
| 446 |
+
gevent_mod, _ = _patch_module('ssl', _warnings=_warnings)
|
| 447 |
+
if may_need_warning:
|
| 448 |
+
direct_ref_modules, subclass_modules = _find_module_refs(
|
| 449 |
+
gevent_mod.orig_SSLContext,
|
| 450 |
+
excluding_names=('ssl', 'gevent.ssl', 'gevent._ssl3', 'gevent._sslgte279'))
|
| 451 |
+
if direct_ref_modules or subclass_modules:
|
| 452 |
+
# Normally you don't want to have dynamic warning strings, because
|
| 453 |
+
# the cache in the warning module is based on the string. But we
|
| 454 |
+
# specifically only do this the first time we patch ourself, so it's
|
| 455 |
+
# ok.
|
| 456 |
+
direct_ref_mod_str = subclass_str = ''
|
| 457 |
+
if direct_ref_modules:
|
| 458 |
+
direct_ref_mod_str = 'Modules that had direct imports (NOT patched): %s. ' % ([
|
| 459 |
+
"%s (%s)" % (name, fname)
|
| 460 |
+
for name, fname in direct_ref_modules
|
| 461 |
+
])
|
| 462 |
+
if subclass_modules:
|
| 463 |
+
subclass_str = 'Subclasses (NOT patched): %s. ' % ([
|
| 464 |
+
str(t) for t in subclass_modules
|
| 465 |
+
])
|
| 466 |
+
_queue_warning(
|
| 467 |
+
'Monkey-patching ssl after ssl has already been imported '
|
| 468 |
+
'may lead to errors, including RecursionError on Python 3.6. '
|
| 469 |
+
'It may also silently lead to incorrect behaviour on Python 3.7. '
|
| 470 |
+
'Please monkey-patch earlier. '
|
| 471 |
+
'See https://github.com/gevent/gevent/issues/1016. '
|
| 472 |
+
+ direct_ref_mod_str + subclass_str,
|
| 473 |
+
_warnings)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
@_ignores_DoNotPatch
|
| 477 |
+
def patch_select(aggressive=True):
|
| 478 |
+
"""
|
| 479 |
+
Replace :func:`select.select` with :func:`gevent.select.select`
|
| 480 |
+
and :func:`select.poll` with :class:`gevent.select.poll` (where available).
|
| 481 |
+
|
| 482 |
+
If ``aggressive`` is true (the default), also remove other
|
| 483 |
+
blocking functions from :mod:`select` .
|
| 484 |
+
|
| 485 |
+
- :func:`select.epoll`
|
| 486 |
+
- :func:`select.kqueue`
|
| 487 |
+
- :func:`select.kevent`
|
| 488 |
+
- :func:`select.devpoll` (Python 3.5+)
|
| 489 |
+
"""
|
| 490 |
+
_patch_module('select',
|
| 491 |
+
_patch_kwargs={'aggressive': aggressive})
|
| 492 |
+
|
| 493 |
+
@_ignores_DoNotPatch
|
| 494 |
+
def patch_selectors(aggressive=True):
|
| 495 |
+
"""
|
| 496 |
+
Replace :class:`selectors.DefaultSelector` with
|
| 497 |
+
:class:`gevent.selectors.GeventSelector`.
|
| 498 |
+
|
| 499 |
+
If ``aggressive`` is true (the default), also remove other
|
| 500 |
+
blocking classes :mod:`selectors`:
|
| 501 |
+
|
| 502 |
+
- :class:`selectors.EpollSelector`
|
| 503 |
+
- :class:`selectors.KqueueSelector`
|
| 504 |
+
- :class:`selectors.DevpollSelector` (Python 3.5+)
|
| 505 |
+
|
| 506 |
+
On Python 2, the :mod:`selectors2` module is used instead
|
| 507 |
+
of :mod:`selectors` if it is available. If this module cannot
|
| 508 |
+
be imported, no patching is done and :mod:`gevent.selectors` is
|
| 509 |
+
not available.
|
| 510 |
+
|
| 511 |
+
In :func:`patch_all`, the *select* argument controls both this function
|
| 512 |
+
and :func:`patch_select`.
|
| 513 |
+
|
| 514 |
+
.. versionadded:: 20.6.0
|
| 515 |
+
"""
|
| 516 |
+
try:
|
| 517 |
+
_check_availability('selectors')
|
| 518 |
+
except ImportError: # pragma: no cover
|
| 519 |
+
return
|
| 520 |
+
|
| 521 |
+
_patch_module('selectors',
|
| 522 |
+
_patch_kwargs={'aggressive': aggressive})
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
@_ignores_DoNotPatch
|
| 526 |
+
def patch_subprocess():
|
| 527 |
+
"""
|
| 528 |
+
Replace :func:`subprocess.call`, :func:`subprocess.check_call`,
|
| 529 |
+
:func:`subprocess.check_output` and :class:`subprocess.Popen` with
|
| 530 |
+
:mod:`cooperative versions <gevent.subprocess>`.
|
| 531 |
+
|
| 532 |
+
.. note::
|
| 533 |
+
On Windows under Python 3, the API support may not completely match
|
| 534 |
+
the standard library.
|
| 535 |
+
|
| 536 |
+
"""
|
| 537 |
+
_patch_module('subprocess')
|
| 538 |
+
|
| 539 |
+
@_ignores_DoNotPatch
|
| 540 |
+
def patch_builtins():
|
| 541 |
+
"""
|
| 542 |
+
Make the builtin :func:`__import__` function `greenlet safe`_ under Python 2.
|
| 543 |
+
|
| 544 |
+
.. note::
|
| 545 |
+
This does nothing under Python 3 as it is not necessary. Python 3 features
|
| 546 |
+
improved import locks that are per-module, not global.
|
| 547 |
+
|
| 548 |
+
.. _greenlet safe: https://github.com/gevent/gevent/issues/108
|
| 549 |
+
|
| 550 |
+
.. deprecated:: 23.7.0
|
| 551 |
+
Does nothing on any supported platform.
|
| 552 |
+
"""
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
@_ignores_DoNotPatch
|
| 556 |
+
def patch_signal():
|
| 557 |
+
"""
|
| 558 |
+
Make the :func:`signal.signal` function work with a :func:`monkey-patched os <patch_os>`.
|
| 559 |
+
|
| 560 |
+
.. caution:: This method must be used with :func:`patch_os` to have proper ``SIGCHLD``
|
| 561 |
+
handling. :func:`patch_all` calls both by default.
|
| 562 |
+
|
| 563 |
+
.. caution:: For proper ``SIGCHLD`` handling, you must yield to the event loop.
|
| 564 |
+
Using :func:`patch_all` is the easiest way to ensure this.
|
| 565 |
+
|
| 566 |
+
.. seealso:: :mod:`gevent.signal`
|
| 567 |
+
"""
|
| 568 |
+
_patch_module("signal")
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def _check_repatching(**module_settings):
|
| 572 |
+
_warnings = []
|
| 573 |
+
key = '_gevent_saved_patch_all_module_settings'
|
| 574 |
+
|
| 575 |
+
del module_settings['kwargs']
|
| 576 |
+
currently_patched = saved.setdefault(key, {})
|
| 577 |
+
first_time = not currently_patched
|
| 578 |
+
if not first_time and currently_patched != module_settings:
|
| 579 |
+
_queue_warning("Patching more than once will result in the union of all True"
|
| 580 |
+
" parameters being patched",
|
| 581 |
+
_warnings)
|
| 582 |
+
|
| 583 |
+
to_patch = {}
|
| 584 |
+
for k, v in module_settings.items():
|
| 585 |
+
# If we haven't seen the setting at all, record it and echo it.
|
| 586 |
+
# If we have seen the setting, but it became true, record it and echo it.
|
| 587 |
+
if k not in currently_patched:
|
| 588 |
+
to_patch[k] = currently_patched[k] = v
|
| 589 |
+
elif v and not currently_patched[k]:
|
| 590 |
+
to_patch[k] = currently_patched[k] = True
|
| 591 |
+
|
| 592 |
+
return _warnings, first_time, to_patch
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
def _subscribe_signal_os(will_patch_all):
|
| 596 |
+
if will_patch_all.will_patch_module('signal') and not will_patch_all.will_patch_module('os'):
|
| 597 |
+
warnings = will_patch_all._warnings # Internal
|
| 598 |
+
_queue_warning('Patching signal but not os will result in SIGCHLD handlers'
|
| 599 |
+
' installed after this not being called and os.waitpid may not'
|
| 600 |
+
' function correctly if gevent.subprocess is used. This may raise an'
|
| 601 |
+
' error in the future.',
|
| 602 |
+
warnings)
|
| 603 |
+
|
| 604 |
+
def patch_all(socket=True, dns=True, time=True, select=True, thread=True, os=True, ssl=True,
|
| 605 |
+
subprocess=True, sys=False, aggressive=True, Event=True,
|
| 606 |
+
builtins=True, signal=True,
|
| 607 |
+
queue=True, contextvars=True,
|
| 608 |
+
**kwargs):
|
| 609 |
+
"""
|
| 610 |
+
Do all of the default monkey patching (calls every other applicable
|
| 611 |
+
function in this module).
|
| 612 |
+
|
| 613 |
+
:return: A true value if patching all modules wasn't cancelled, a false
|
| 614 |
+
value if it was.
|
| 615 |
+
|
| 616 |
+
.. versionchanged:: 1.1
|
| 617 |
+
Issue a :mod:`warning <warnings>` if this function is called multiple times
|
| 618 |
+
with different arguments. The second and subsequent calls will only add more
|
| 619 |
+
patches, they can never remove existing patches by setting an argument to ``False``.
|
| 620 |
+
.. versionchanged:: 1.1
|
| 621 |
+
Issue a :mod:`warning <warnings>` if this function is called with ``os=False``
|
| 622 |
+
and ``signal=True``. This will cause SIGCHLD handlers to not be called. This may
|
| 623 |
+
be an error in the future.
|
| 624 |
+
.. versionchanged:: 1.3a2
|
| 625 |
+
``Event`` defaults to True.
|
| 626 |
+
.. versionchanged:: 1.3b1
|
| 627 |
+
Defined the return values.
|
| 628 |
+
.. versionchanged:: 1.3b1
|
| 629 |
+
Add ``**kwargs`` for the benefit of event subscribers. CAUTION: gevent may add
|
| 630 |
+
and interpret additional arguments in the future, so it is suggested to use prefixes
|
| 631 |
+
for kwarg values to be interpreted by plugins, for example, `patch_all(mylib_futures=True)`.
|
| 632 |
+
.. versionchanged:: 1.3.5
|
| 633 |
+
Add *queue*, defaulting to True, for Python 3.7.
|
| 634 |
+
.. versionchanged:: 1.5
|
| 635 |
+
Remove the ``httplib`` argument. Previously, setting it raised a ``ValueError``.
|
| 636 |
+
.. versionchanged:: 1.5a3
|
| 637 |
+
Add the ``contextvars`` argument.
|
| 638 |
+
.. versionchanged:: 1.5
|
| 639 |
+
Better handling of patching more than once.
|
| 640 |
+
"""
|
| 641 |
+
# pylint:disable=too-many-locals,too-many-branches
|
| 642 |
+
|
| 643 |
+
# Check to see if they're changing the patched list
|
| 644 |
+
_warnings, first_time, modules_to_patch = _check_repatching(**locals())
|
| 645 |
+
|
| 646 |
+
if not modules_to_patch:
|
| 647 |
+
# Nothing to do. Either the arguments were identical to what
|
| 648 |
+
# we previously did, or they specified false values
|
| 649 |
+
# for things we had previously patched.
|
| 650 |
+
_process_warnings(_warnings)
|
| 651 |
+
return
|
| 652 |
+
|
| 653 |
+
for k, v in modules_to_patch.items():
|
| 654 |
+
locals()[k] = v
|
| 655 |
+
|
| 656 |
+
from gevent import events
|
| 657 |
+
try:
|
| 658 |
+
_notify_patch(events.GeventWillPatchAllEvent(modules_to_patch, kwargs), _warnings)
|
| 659 |
+
except events.DoNotPatch:
|
| 660 |
+
return False
|
| 661 |
+
|
| 662 |
+
# order is important
|
| 663 |
+
if os:
|
| 664 |
+
patch_os()
|
| 665 |
+
if thread:
|
| 666 |
+
patch_thread(Event=Event, _warnings=_warnings)
|
| 667 |
+
if time:
|
| 668 |
+
# time must be patched after thread, some modules used by thread
|
| 669 |
+
# need access to the real time.sleep function.
|
| 670 |
+
patch_time()
|
| 671 |
+
|
| 672 |
+
# sys must be patched after thread. in other cases threading._shutdown will be
|
| 673 |
+
# initiated to _MainThread with real thread ident
|
| 674 |
+
if sys:
|
| 675 |
+
patch_sys()
|
| 676 |
+
if socket:
|
| 677 |
+
patch_socket(dns=dns, aggressive=aggressive)
|
| 678 |
+
if select:
|
| 679 |
+
patch_select(aggressive=aggressive)
|
| 680 |
+
patch_selectors(aggressive=aggressive)
|
| 681 |
+
if ssl:
|
| 682 |
+
patch_ssl(_warnings=_warnings, _first_time=first_time)
|
| 683 |
+
if subprocess:
|
| 684 |
+
patch_subprocess()
|
| 685 |
+
if builtins:
|
| 686 |
+
patch_builtins()
|
| 687 |
+
if signal:
|
| 688 |
+
patch_signal()
|
| 689 |
+
if queue:
|
| 690 |
+
patch_queue()
|
| 691 |
+
if contextvars:
|
| 692 |
+
patch_contextvars()
|
| 693 |
+
|
| 694 |
+
_notify_patch(events.GeventDidPatchBuiltinModulesEvent(modules_to_patch, kwargs), _warnings)
|
| 695 |
+
_notify_patch(events.GeventDidPatchAllEvent(modules_to_patch, kwargs), _warnings)
|
| 696 |
+
|
| 697 |
+
_process_warnings(_warnings)
|
| 698 |
+
return True
|
| 699 |
+
|
| 700 |
+
def __getattr__(name):
|
| 701 |
+
if name == 'main':
|
| 702 |
+
from ._main import main
|
| 703 |
+
return main
|
| 704 |
+
raise AttributeError(name)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/__main__.py
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._main import main
|
| 2 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_errors.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Exception classes and errors that this package may raise.
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
class _BadImplements(AttributeError):
|
| 11 |
+
"""
|
| 12 |
+
Raised when ``__implements__`` is incorrect.
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
def __init__(self, module):
|
| 16 |
+
AttributeError.__init__(
|
| 17 |
+
self,
|
| 18 |
+
"Module %r has a bad or missing value for __implements__" % (module,)
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
class MonkeyPatchWarning(RuntimeWarning):
|
| 22 |
+
"""
|
| 23 |
+
The type of warnings we issue.
|
| 24 |
+
|
| 25 |
+
.. versionadded:: 1.3a2
|
| 26 |
+
"""
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_main.py
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
The real functionality to run this package as a main module.
|
| 4 |
+
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def main():
|
| 9 |
+
# TODO: Now that this is its own module, see if
|
| 10 |
+
# we can refactor.
|
| 11 |
+
# pylint:disable=too-many-locals
|
| 12 |
+
import sys
|
| 13 |
+
from . import patch_all
|
| 14 |
+
|
| 15 |
+
args = {}
|
| 16 |
+
argv = sys.argv[1:]
|
| 17 |
+
verbose = False
|
| 18 |
+
run_fn = "run_path"
|
| 19 |
+
script_help, patch_all_args, modules = _get_script_help()
|
| 20 |
+
while argv and argv[0].startswith('--'):
|
| 21 |
+
option = argv[0][2:]
|
| 22 |
+
if option == 'verbose':
|
| 23 |
+
verbose += 1
|
| 24 |
+
elif option == 'module':
|
| 25 |
+
run_fn = "run_module"
|
| 26 |
+
elif option.startswith('no-') and option.replace('no-', '') in patch_all_args:
|
| 27 |
+
args[option[3:]] = False
|
| 28 |
+
elif option in patch_all_args:
|
| 29 |
+
args[option] = True
|
| 30 |
+
if option in modules:
|
| 31 |
+
for module in modules:
|
| 32 |
+
args.setdefault(module, False)
|
| 33 |
+
else:
|
| 34 |
+
sys.exit(script_help + '\n\n' + 'Cannot patch %r' % option)
|
| 35 |
+
del argv[0]
|
| 36 |
+
# TODO: break on --
|
| 37 |
+
if verbose:
|
| 38 |
+
import pprint
|
| 39 |
+
import os
|
| 40 |
+
print('gevent.monkey.patch_all(%s)' % ', '.join('%s=%s' % item for item in args.items()))
|
| 41 |
+
print('sys.version=%s' % (sys.version.strip().replace('\n', ' '), ))
|
| 42 |
+
print('sys.path=%s' % pprint.pformat(sys.path))
|
| 43 |
+
print('sys.modules=%s' % pprint.pformat(sorted(sys.modules.keys())))
|
| 44 |
+
print('cwd=%s' % os.getcwd())
|
| 45 |
+
|
| 46 |
+
if not argv:
|
| 47 |
+
print(script_help)
|
| 48 |
+
return
|
| 49 |
+
|
| 50 |
+
sys.argv[:] = argv
|
| 51 |
+
# Make sure that we don't get imported again under a different
|
| 52 |
+
# name (usually it's ``__main__`` here) because that could lead to
|
| 53 |
+
# double-patching, and making monkey.get_original() not work.
|
| 54 |
+
try:
|
| 55 |
+
mod_name = __spec__.name
|
| 56 |
+
except NameError:
|
| 57 |
+
# Py2: __spec__ is not defined as standard
|
| 58 |
+
mod_name = 'gevent.monkey'
|
| 59 |
+
sys.modules[mod_name] = sys.modules[__name__]
|
| 60 |
+
# On Python 2, we have to set the gevent.monkey attribute
|
| 61 |
+
# manually; putting gevent.monkey into sys.modules stops the
|
| 62 |
+
# import machinery from making that connection, and ``from gevent
|
| 63 |
+
# import monkey`` is broken. On Python 3 (.8 at least) that's not
|
| 64 |
+
# necessary.
|
| 65 |
+
assert 'gevent.monkey' in sys.modules
|
| 66 |
+
|
| 67 |
+
# Running ``patch_all()`` will load pkg_resources entry point plugins
|
| 68 |
+
# which may attempt to import ``gevent.monkey``, so it is critical that
|
| 69 |
+
# we have established the correct saved module name first.
|
| 70 |
+
patch_all(**args)
|
| 71 |
+
|
| 72 |
+
import runpy
|
| 73 |
+
# Use runpy.run_path to closely (exactly) match what the
|
| 74 |
+
# interpreter does given 'python <path>'. This includes allowing
|
| 75 |
+
# passing .pyc/.pyo files and packages with a __main__ and
|
| 76 |
+
# potentially even zip files. Previously we used exec, which only
|
| 77 |
+
# worked if we directly read a python source file.
|
| 78 |
+
run_meth = getattr(runpy, run_fn)
|
| 79 |
+
return run_meth(sys.argv[0], run_name='__main__')
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _get_script_help():
|
| 83 |
+
# pylint:disable=deprecated-method
|
| 84 |
+
import inspect
|
| 85 |
+
from . import patch_all
|
| 86 |
+
getter = inspect.getfullargspec
|
| 87 |
+
|
| 88 |
+
patch_all_args = getter(patch_all)[0]
|
| 89 |
+
modules = [x for x in patch_all_args if 'patch_' + x in globals()]
|
| 90 |
+
script_help = """gevent.monkey - monkey patch the standard modules to use gevent.
|
| 91 |
+
|
| 92 |
+
USAGE: ``python -m gevent.monkey [MONKEY OPTIONS] [--module] (script|module) [SCRIPT OPTIONS]``
|
| 93 |
+
|
| 94 |
+
If no MONKEY OPTIONS are present, monkey patches all the modules as if by calling ``patch_all()``.
|
| 95 |
+
You can exclude a module with --no-<module>, e.g. --no-thread. You can
|
| 96 |
+
specify a module to patch with --<module>, e.g. --socket. In the latter
|
| 97 |
+
case only the modules specified on the command line will be patched.
|
| 98 |
+
|
| 99 |
+
The default behavior is to execute the script passed as argument. If you wish
|
| 100 |
+
to run a module instead, pass the `--module` argument before the module name.
|
| 101 |
+
|
| 102 |
+
.. versionchanged:: 1.3b1
|
| 103 |
+
The *script* argument can now be any argument that can be passed to `runpy.run_path`,
|
| 104 |
+
just like the interpreter itself does, for example a package directory containing ``__main__.py``.
|
| 105 |
+
Previously it had to be the path to
|
| 106 |
+
a .py source file.
|
| 107 |
+
|
| 108 |
+
.. versionchanged:: 1.5
|
| 109 |
+
The `--module` option has been added.
|
| 110 |
+
|
| 111 |
+
MONKEY OPTIONS: ``--verbose %s``""" % ', '.join('--[no-]%s' % m for m in modules)
|
| 112 |
+
return script_help, patch_all_args, modules
|
| 113 |
+
|
| 114 |
+
main.__doc__ = _get_script_help()[0]
|
| 115 |
+
|
| 116 |
+
if __name__ == '__main__':
|
| 117 |
+
main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_common.py
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
The implementation of thread patching for Python versions
|
| 4 |
+
prior to 3.13.
|
| 5 |
+
|
| 6 |
+
Internal use only.
|
| 7 |
+
"""
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
from ._util import _patch_module
|
| 11 |
+
from ._util import _queue_warning
|
| 12 |
+
from ._util import _notify_patch
|
| 13 |
+
|
| 14 |
+
from ._state import is_object_patched
|
| 15 |
+
|
| 16 |
+
def _patch_existing_locks(threading):
|
| 17 |
+
if len(list(threading.enumerate())) != 1:
|
| 18 |
+
return
|
| 19 |
+
# This is used to protect internal data structures for enumerate.
|
| 20 |
+
# It's acquired when threads are started and when they're stopped.
|
| 21 |
+
# Stopping a thread checks a Condition, which on Python 2 wants to test
|
| 22 |
+
# _is_owned of its (patched) Lock. Since our LockType doesn't have
|
| 23 |
+
# _is_owned, it tries to acquire the lock non-blocking; that triggers a
|
| 24 |
+
# switch. If the next thing in the callback list was a thread that needed
|
| 25 |
+
# to start or end, we wouldn't be able to acquire this native lock
|
| 26 |
+
# because it was being held already; we couldn't switch either, so we'd
|
| 27 |
+
# block permanently.
|
| 28 |
+
threading._active_limbo_lock = threading._allocate_lock()
|
| 29 |
+
try:
|
| 30 |
+
tid = threading.get_ident()
|
| 31 |
+
except AttributeError:
|
| 32 |
+
tid = threading._get_ident()
|
| 33 |
+
rlock_type = type(threading.RLock())
|
| 34 |
+
try:
|
| 35 |
+
import importlib._bootstrap
|
| 36 |
+
except ImportError:
|
| 37 |
+
class _ModuleLock(object):
|
| 38 |
+
pass
|
| 39 |
+
else:
|
| 40 |
+
_ModuleLock = importlib._bootstrap._ModuleLock # python 2 pylint: disable=no-member
|
| 41 |
+
# It might be possible to walk up all the existing stack frames to find
|
| 42 |
+
# locked objects...at least if they use `with`. To be sure, we look at every object
|
| 43 |
+
# Since we're supposed to be done very early in the process, there shouldn't be
|
| 44 |
+
# too many.
|
| 45 |
+
|
| 46 |
+
# Note that the C implementation of locks, at least on some
|
| 47 |
+
# versions of CPython, cannot be found and cannot be fixed (they simply
|
| 48 |
+
# don't show up to GC; see https://github.com/gevent/gevent/issues/1354)
|
| 49 |
+
|
| 50 |
+
# By definition there's only one thread running, so the various
|
| 51 |
+
# owner attributes were the old (native) thread id. Make it our
|
| 52 |
+
# current greenlet id so that when it wants to unlock and compare
|
| 53 |
+
# self.__owner with _get_ident(), they match.
|
| 54 |
+
gc = __import__('gc')
|
| 55 |
+
for o in gc.get_objects():
|
| 56 |
+
if isinstance(o, rlock_type):
|
| 57 |
+
for owner_name in (
|
| 58 |
+
'_owner', # Python 3 or backported PyPy2
|
| 59 |
+
'_RLock__owner', # Python 2
|
| 60 |
+
):
|
| 61 |
+
if hasattr(o, owner_name):
|
| 62 |
+
if getattr(o, owner_name) is not None:
|
| 63 |
+
setattr(o, owner_name, tid)
|
| 64 |
+
break
|
| 65 |
+
else: # pragma: no cover
|
| 66 |
+
raise AssertionError(
|
| 67 |
+
"Unsupported Python implementation; "
|
| 68 |
+
"Found unknown lock implementation.",
|
| 69 |
+
vars(o)
|
| 70 |
+
)
|
| 71 |
+
elif isinstance(o, _ModuleLock):
|
| 72 |
+
if o.owner is not None:
|
| 73 |
+
o.owner = tid
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class BasePatcher:
|
| 78 |
+
# Description of the hang:
|
| 79 |
+
# There is an incompatibility with patching 'thread' and the 'multiprocessing' module:
|
| 80 |
+
# The problem is that multiprocessing.queues.Queue uses a half-duplex multiprocessing.Pipe,
|
| 81 |
+
# which is implemented with os.pipe() and _multiprocessing.Connection. os.pipe isn't patched
|
| 82 |
+
# by gevent, as it returns just a fileno. _multiprocessing.Connection is an internal implementation
|
| 83 |
+
# class implemented in C, which exposes a 'poll(timeout)' method; under the covers, this issues a
|
| 84 |
+
# (blocking) select() call: hence the need for a real thread. Except for that method, we could
|
| 85 |
+
# almost replace Connection with gevent.fileobject.SocketAdapter, plus a trivial
|
| 86 |
+
# patch to os.pipe (below). Sigh, so close. (With a little work, we could replicate that method)
|
| 87 |
+
|
| 88 |
+
# import os
|
| 89 |
+
# import fcntl
|
| 90 |
+
# os_pipe = os.pipe
|
| 91 |
+
# def _pipe():
|
| 92 |
+
# r, w = os_pipe()
|
| 93 |
+
# fcntl.fcntl(r, fcntl.F_SETFL, os.O_NONBLOCK)
|
| 94 |
+
# fcntl.fcntl(w, fcntl.F_SETFL, os.O_NONBLOCK)
|
| 95 |
+
# return r, w
|
| 96 |
+
# os.pipe = _pipe
|
| 97 |
+
|
| 98 |
+
gevent_threading_mod = None
|
| 99 |
+
gevent_thread_mod = None
|
| 100 |
+
|
| 101 |
+
thread_mod = None
|
| 102 |
+
threading_mod = None
|
| 103 |
+
orig_current_thread = None
|
| 104 |
+
main_thread = None
|
| 105 |
+
orig_shutdown = None
|
| 106 |
+
|
| 107 |
+
def __init__(self, threading=True, _threading_local=True, Event=True, logging=True,
|
| 108 |
+
existing_locks=True,
|
| 109 |
+
_warnings=None):
|
| 110 |
+
self.threading = threading
|
| 111 |
+
self.threading_local = _threading_local
|
| 112 |
+
self.Event = Event
|
| 113 |
+
self.logging = logging
|
| 114 |
+
self.existing_locks = existing_locks
|
| 115 |
+
self.warnings = _warnings
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def __call__(self):
|
| 120 |
+
# The 'threading' module copies some attributes from the
|
| 121 |
+
# thread module the first time it is imported. If we patch 'thread'
|
| 122 |
+
# before that happens, then we store the wrong values in 'saved',
|
| 123 |
+
# So if we're going to patch threading, we either need to import it
|
| 124 |
+
# before we patch thread, or manually clean up the attributes that
|
| 125 |
+
# are in trouble. The latter is tricky because of the different names
|
| 126 |
+
# on different versions.
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
self.threading_mod = __import__('threading')
|
| 130 |
+
# Capture the *real* current thread object before
|
| 131 |
+
# we start returning DummyThread objects, for comparison
|
| 132 |
+
# to the main thread.
|
| 133 |
+
self.orig_current_thread = self.threading_mod.current_thread()
|
| 134 |
+
self.main_thread = self.threading_mod.main_thread()
|
| 135 |
+
self.orig_shutdown = self.threading_mod._shutdown
|
| 136 |
+
|
| 137 |
+
gevent_thread_mod, thread_mod = _patch_module('thread',
|
| 138 |
+
_warnings=self.warnings,
|
| 139 |
+
_notify_did_subscribers=False)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
if self.threading:
|
| 143 |
+
self.patch_threading_event_logging_existing_locks()
|
| 144 |
+
|
| 145 |
+
if self.threading_local:
|
| 146 |
+
self.patch__threading_local()
|
| 147 |
+
|
| 148 |
+
if self.threading:
|
| 149 |
+
self.patch_active_threads()
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# Issue 18808 changes the nature of Thread.join() to use
|
| 153 |
+
# locks. This means that a greenlet spawned in the main thread
|
| 154 |
+
# (which is already running) cannot wait for the main thread---it
|
| 155 |
+
# hangs forever. We patch around this if possible. See also
|
| 156 |
+
# gevent.threading.
|
| 157 |
+
already_patched = is_object_patched('threading', '_shutdown')
|
| 158 |
+
|
| 159 |
+
if self.orig_current_thread == self.threading_mod.main_thread() and not already_patched:
|
| 160 |
+
self.patch_threading_shutdown_on_main_thread_not_already_patched()
|
| 161 |
+
self.patch_main_thread_cleanup()
|
| 162 |
+
|
| 163 |
+
elif not already_patched:
|
| 164 |
+
self.patch_shutdown_not_on_main_thread()
|
| 165 |
+
|
| 166 |
+
from gevent import events
|
| 167 |
+
_notify_patch(events.GeventDidPatchModuleEvent('thread',
|
| 168 |
+
gevent_thread_mod,
|
| 169 |
+
thread_mod))
|
| 170 |
+
if self.gevent_threading_mod is not None:
|
| 171 |
+
_notify_patch(events.GeventDidPatchModuleEvent('threading',
|
| 172 |
+
self.gevent_threading_mod,
|
| 173 |
+
self.threading_mod))
|
| 174 |
+
|
| 175 |
+
def patch_threading_event_logging_existing_locks(self):
|
| 176 |
+
|
| 177 |
+
self.gevent_threading_mod, patched_mod = _patch_module(
|
| 178 |
+
'threading',
|
| 179 |
+
_warnings=self.warnings,
|
| 180 |
+
_notify_did_subscribers=False)
|
| 181 |
+
|
| 182 |
+
assert patched_mod is self.threading_mod
|
| 183 |
+
|
| 184 |
+
if self.Event:
|
| 185 |
+
self.patch_event()
|
| 186 |
+
|
| 187 |
+
if self.existing_locks:
|
| 188 |
+
_patch_existing_locks(self.threading_mod)
|
| 189 |
+
|
| 190 |
+
if self.logging and 'logging' in sys.modules:
|
| 191 |
+
self.patch_logging()
|
| 192 |
+
|
| 193 |
+
def patch_event(self):
|
| 194 |
+
from .api import patch_item
|
| 195 |
+
from gevent.event import Event
|
| 196 |
+
patch_item(self.threading_mod, 'Event', Event)
|
| 197 |
+
# Python 2 had `Event` as a function returning
|
| 198 |
+
# the private class `_Event`. Some code may be relying
|
| 199 |
+
# on that.
|
| 200 |
+
if hasattr(self.threading_mod, '_Event'):
|
| 201 |
+
patch_item(self.threading_mod, '_Event', Event)
|
| 202 |
+
|
| 203 |
+
def patch_logging(self):
|
| 204 |
+
from .api import patch_item
|
| 205 |
+
logging = __import__('logging')
|
| 206 |
+
patch_item(logging, '_lock', self.threading_mod.RLock())
|
| 207 |
+
for wr in logging._handlerList:
|
| 208 |
+
# In py26, these are actual handlers, not weakrefs
|
| 209 |
+
handler = wr() if callable(wr) else wr
|
| 210 |
+
if handler is None:
|
| 211 |
+
continue
|
| 212 |
+
if not hasattr(handler, 'lock'):
|
| 213 |
+
raise TypeError("Unknown/unsupported handler %r" % handler)
|
| 214 |
+
handler.lock = self.threading_mod.RLock()
|
| 215 |
+
|
| 216 |
+
def patch__threading_local(self):
|
| 217 |
+
_threading_local = __import__('_threading_local')
|
| 218 |
+
from .api import patch_item
|
| 219 |
+
from gevent.local import local
|
| 220 |
+
patch_item(_threading_local, 'local', local)
|
| 221 |
+
|
| 222 |
+
def patch_active_threads(self):
|
| 223 |
+
raise NotImplementedError
|
| 224 |
+
|
| 225 |
+
def patch_threading_shutdown_on_main_thread_not_already_patched(self):
|
| 226 |
+
raise NotImplementedError
|
| 227 |
+
|
| 228 |
+
def patch_main_thread_cleanup(self):
|
| 229 |
+
# We create a bit of a reference cycle here,
|
| 230 |
+
# so main_thread doesn't get to be collected in a timely way.
|
| 231 |
+
# Not good. Take it out of dangling so we don't get
|
| 232 |
+
# warned about it.
|
| 233 |
+
main_thread = self.main_thread
|
| 234 |
+
self.threading_mod._dangling.remove(main_thread)
|
| 235 |
+
|
| 236 |
+
# Patch up the ident of the main thread to match. This
|
| 237 |
+
# matters if threading was imported before monkey-patching
|
| 238 |
+
# thread
|
| 239 |
+
oldid = main_thread.ident
|
| 240 |
+
main_thread._ident = self.threading_mod.get_ident()
|
| 241 |
+
if oldid in self.threading_mod._active:
|
| 242 |
+
self.threading_mod._active[main_thread.ident] = self.threading_mod._active[oldid]
|
| 243 |
+
if oldid != main_thread.ident:
|
| 244 |
+
del self.threading_mod._active[oldid]
|
| 245 |
+
|
| 246 |
+
def patch_shutdown_not_on_main_thread(self):
|
| 247 |
+
_queue_warning("Monkey-patching not on the main thread; "
|
| 248 |
+
"threading.main_thread().join() will hang from a greenlet",
|
| 249 |
+
self.warnings)
|
| 250 |
+
|
| 251 |
+
from .api import patch_item
|
| 252 |
+
|
| 253 |
+
main_thread = self.main_thread
|
| 254 |
+
threading_mod = self.threading_mod
|
| 255 |
+
get_ident = self.threading_mod.get_ident
|
| 256 |
+
orig_shutdown = self.orig_shutdown
|
| 257 |
+
def _shutdown():
|
| 258 |
+
# We've patched get_ident but *did not* patch the
|
| 259 |
+
# main_thread.ident value. Beginning in Python 3.9.8
|
| 260 |
+
# and then later releases (3.10.1, probably), the
|
| 261 |
+
# _main_thread object is only _stop() if the ident of
|
| 262 |
+
# the current thread (the *real* main thread) matches
|
| 263 |
+
# the ident of the _main_thread object. But without doing that,
|
| 264 |
+
# the main thread's shutdown lock (threading._shutdown_locks) is never
|
| 265 |
+
# removed *or released*, thus hanging the interpreter.
|
| 266 |
+
# XXX: There's probably a better way to do this. Probably need to take a
|
| 267 |
+
# step back and look at the whole picture.
|
| 268 |
+
main_thread._ident = get_ident()
|
| 269 |
+
orig_shutdown()
|
| 270 |
+
patch_item(threading_mod, '_shutdown', orig_shutdown)
|
| 271 |
+
patch_item(threading_mod, '_shutdown', _shutdown)
|
| 272 |
+
|
| 273 |
+
@staticmethod # Static to be sure we don't accidentally capture `self` and keep it alive
|
| 274 |
+
def _make_existing_non_main_thread_join_func(thread, thread_greenlet, threading_mod):
|
| 275 |
+
from gevent.hub import sleep
|
| 276 |
+
from time import time
|
| 277 |
+
# TODO: This is almost the algorithm that the 3.13 _ThreadHandle class
|
| 278 |
+
# employs. UNIFY them.
|
| 279 |
+
def join(timeout=None):
|
| 280 |
+
end = None
|
| 281 |
+
if threading_mod.current_thread() is thread:
|
| 282 |
+
raise RuntimeError("Cannot join current thread")
|
| 283 |
+
if thread_greenlet is not None and thread_greenlet.dead:
|
| 284 |
+
return
|
| 285 |
+
# You may ask: Why not call thread_greenlet.join()?
|
| 286 |
+
# Well, in the one case we actually have a greenlet, it's the
|
| 287 |
+
# low-level greenlet.greenlet object for the main thread, which
|
| 288 |
+
# doesn't have a join method.
|
| 289 |
+
#
|
| 290 |
+
# You may ask: Why not become the main greenlet's *parent*
|
| 291 |
+
# so you can get notified when it finishes? Because you can't
|
| 292 |
+
# create a greenlet cycle (the current greenlet is a descendent
|
| 293 |
+
# of the parent), and nor can you set a greenlet's parent to None,
|
| 294 |
+
# so there can only ever be one greenlet with a parent of None: the main
|
| 295 |
+
# greenlet, the one we need to watch.
|
| 296 |
+
#
|
| 297 |
+
# You may ask: why not swizzle out the problematic lock on the main thread
|
| 298 |
+
# into a gevent friendly lock? Well, the interpreter actually depends on that
|
| 299 |
+
# for the main thread in threading._shutdown; see below.
|
| 300 |
+
|
| 301 |
+
if not thread.is_alive():
|
| 302 |
+
return
|
| 303 |
+
|
| 304 |
+
if timeout:
|
| 305 |
+
end = time() + timeout
|
| 306 |
+
|
| 307 |
+
while thread.is_alive():
|
| 308 |
+
if end is not None and time() > end:
|
| 309 |
+
return
|
| 310 |
+
sleep(0.01)
|
| 311 |
+
return join
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_gte313.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
The implementation of thread patching for Python versions
|
| 4 |
+
after 3.13.
|
| 5 |
+
|
| 6 |
+
Internal use only.
|
| 7 |
+
"""
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
from ._patch_thread_common import BasePatcher
|
| 12 |
+
|
| 13 |
+
class Patcher(BasePatcher):
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def patch_active_threads(self):
|
| 17 |
+
from gevent.threading import main_native_thread
|
| 18 |
+
|
| 19 |
+
for thread in self.threading_mod._active.values():
|
| 20 |
+
if thread == main_native_thread():
|
| 21 |
+
from greenlet import getcurrent
|
| 22 |
+
from gevent.thread import _ThreadHandle
|
| 23 |
+
thread._after_fork = lambda new_ident=None: new_ident
|
| 24 |
+
thread._handle = _ThreadHandle()
|
| 25 |
+
thread._handle._set_greenlet(getcurrent())
|
| 26 |
+
thread._ident = thread._handle.ident
|
| 27 |
+
assert thread.ident == thread._handle.ident
|
| 28 |
+
continue
|
| 29 |
+
thread.join = self._make_existing_non_main_thread_join_func(thread,
|
| 30 |
+
None,
|
| 31 |
+
self.threading_mod)
|
| 32 |
+
|
| 33 |
+
def patch_threading_shutdown_on_main_thread_not_already_patched(self):
|
| 34 |
+
import greenlet
|
| 35 |
+
from .api import patch_item
|
| 36 |
+
|
| 37 |
+
main_thread = self.main_thread
|
| 38 |
+
threading_mod = self.threading_mod
|
| 39 |
+
orig_shutdown = self.orig_shutdown
|
| 40 |
+
_greenlet = main_thread._greenlet = greenlet.getcurrent()
|
| 41 |
+
|
| 42 |
+
def _shutdown():
|
| 43 |
+
# Release anyone trying to join() me,
|
| 44 |
+
# and let us switch to them.
|
| 45 |
+
main_thread._handle._set_done()
|
| 46 |
+
from gevent import sleep
|
| 47 |
+
try:
|
| 48 |
+
sleep()
|
| 49 |
+
except: # pylint:disable=bare-except
|
| 50 |
+
# A greenlet could have .kill() us
|
| 51 |
+
# or .throw() to us. I'm the main greenlet,
|
| 52 |
+
# there's no where else for this to go.
|
| 53 |
+
from gevent import get_hub
|
| 54 |
+
get_hub().print_exception(_greenlet, *sys.exc_info())
|
| 55 |
+
|
| 56 |
+
# Now, this may have resulted in us getting stopped
|
| 57 |
+
# if some other greenlet actually just ran there.
|
| 58 |
+
# That's not good, we're not supposed to be stopped
|
| 59 |
+
# when we enter _shutdown.
|
| 60 |
+
class FakeHandle:
|
| 61 |
+
def is_done(self):
|
| 62 |
+
return False
|
| 63 |
+
def _set_done(self):
|
| 64 |
+
return
|
| 65 |
+
def join(self):
|
| 66 |
+
return
|
| 67 |
+
main_thread._handle = FakeHandle()
|
| 68 |
+
assert main_thread.is_alive()
|
| 69 |
+
# main_thread._is_stopped = False
|
| 70 |
+
# main_thread._tstate_lock = main_thread.__real_tstate_lock
|
| 71 |
+
# main_thread.__real_tstate_lock = None
|
| 72 |
+
# The only truly blocking native shutdown lock to
|
| 73 |
+
# acquire should be our own (hopefully), and the call to
|
| 74 |
+
# _stop that orig_shutdown makes will discard it.
|
| 75 |
+
|
| 76 |
+
# XXX: What if more get spawned?
|
| 77 |
+
for t in list(threading_mod.enumerate()):
|
| 78 |
+
if t.daemon or t is main_thread:
|
| 79 |
+
continue
|
| 80 |
+
while t.is_alive():
|
| 81 |
+
try:
|
| 82 |
+
t._handle.join(0.001)
|
| 83 |
+
except RuntimeError:
|
| 84 |
+
# Joining ourself.
|
| 85 |
+
t._handle._set_done()
|
| 86 |
+
break
|
| 87 |
+
|
| 88 |
+
orig_shutdown()
|
| 89 |
+
patch_item(threading_mod, '_shutdown', self.orig_shutdown)
|
| 90 |
+
|
| 91 |
+
patch_item(self.threading_mod, '_shutdown', _shutdown)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_patch_thread_lt313.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
The implementation of thread patching for Python versions
|
| 4 |
+
prior to 3.13.
|
| 5 |
+
|
| 6 |
+
Internal use only.
|
| 7 |
+
"""
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
from ._patch_thread_common import BasePatcher
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Patcher(BasePatcher):
|
| 15 |
+
|
| 16 |
+
def patch_active_threads(self):
|
| 17 |
+
from gevent.threading import main_native_thread
|
| 18 |
+
threading_mod = self.threading_mod
|
| 19 |
+
for thread in threading_mod._active.values():
|
| 20 |
+
if thread == main_native_thread():
|
| 21 |
+
continue
|
| 22 |
+
thread.join = self._make_existing_non_main_thread_join_func(thread, None, threading_mod)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def patch_threading_shutdown_on_main_thread_not_already_patched(self):
|
| 26 |
+
import greenlet
|
| 27 |
+
from .api import patch_item
|
| 28 |
+
threading_mod = self.threading_mod
|
| 29 |
+
main_thread = self.main_thread
|
| 30 |
+
orig_shutdown = self.orig_shutdown
|
| 31 |
+
|
| 32 |
+
_greenlet = main_thread._greenlet = greenlet.getcurrent()
|
| 33 |
+
main_thread._gevent_real_tstate_lock = main_thread._tstate_lock
|
| 34 |
+
assert main_thread._gevent_real_tstate_lock is not None
|
| 35 |
+
# The interpreter will call threading._shutdown
|
| 36 |
+
# when the main thread exits and is about to
|
| 37 |
+
# go away. It is called *in* the main thread. This
|
| 38 |
+
# is a perfect place to notify other greenlets that
|
| 39 |
+
# the main thread is done. We do this by overriding the
|
| 40 |
+
# lock of the main thread during operation, and only restoring
|
| 41 |
+
# it to the native blocking version at shutdown time
|
| 42 |
+
# (the interpreter also has a reference to this lock in a
|
| 43 |
+
# C data structure).
|
| 44 |
+
main_thread._tstate_lock = threading_mod.Lock()
|
| 45 |
+
main_thread._tstate_lock.acquire()
|
| 46 |
+
|
| 47 |
+
def _shutdown():
|
| 48 |
+
# Release anyone trying to join() me,
|
| 49 |
+
# and let us switch to them.
|
| 50 |
+
if not main_thread._tstate_lock:
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
main_thread._tstate_lock.release()
|
| 54 |
+
from gevent import sleep
|
| 55 |
+
try:
|
| 56 |
+
sleep()
|
| 57 |
+
except: # pylint:disable=bare-except
|
| 58 |
+
# A greenlet could have .kill() us
|
| 59 |
+
# or .throw() to us. I'm the main greenlet,
|
| 60 |
+
# there's no where else for this to go.
|
| 61 |
+
from gevent import get_hub
|
| 62 |
+
get_hub().print_exception(_greenlet, *sys.exc_info())
|
| 63 |
+
|
| 64 |
+
# Now, this may have resulted in us getting stopped
|
| 65 |
+
# if some other greenlet actually just ran there.
|
| 66 |
+
# That's not good, we're not supposed to be stopped
|
| 67 |
+
# when we enter _shutdown.
|
| 68 |
+
main_thread._is_stopped = False
|
| 69 |
+
main_thread._tstate_lock = main_thread._gevent_real_tstate_lock
|
| 70 |
+
main_thread._gevent_real_tstate_lock = None
|
| 71 |
+
# The only truly blocking native shutdown lock to
|
| 72 |
+
# acquire should be our own (hopefully), and the call to
|
| 73 |
+
# _stop that orig_shutdown makes will discard it.
|
| 74 |
+
|
| 75 |
+
orig_shutdown()
|
| 76 |
+
patch_item(threading_mod, '_shutdown', orig_shutdown)
|
| 77 |
+
|
| 78 |
+
patch_item(threading_mod, '_shutdown', _shutdown)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_state.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
State management and query functions for tracking and discovering what
|
| 4 |
+
has been patched.
|
| 5 |
+
"""
|
| 6 |
+
import logging
|
| 7 |
+
|
| 8 |
+
logger = logging.getLogger(__name__)
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# maps module name -> {attribute name: original item}
|
| 12 |
+
# e.g. "time" -> {"sleep": built-in function sleep}
|
| 13 |
+
# NOT A PUBLIC API. However, third-party monkey-patchers may be using
|
| 14 |
+
# it? TODO: Provide better API for them.
|
| 15 |
+
saved:dict = {}
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def is_module_patched(mod_name):
|
| 19 |
+
"""
|
| 20 |
+
Check if a module has been replaced with a cooperative version.
|
| 21 |
+
|
| 22 |
+
:param str mod_name: The name of the standard library module,
|
| 23 |
+
e.g., ``'socket'``.
|
| 24 |
+
|
| 25 |
+
"""
|
| 26 |
+
return mod_name in saved
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def is_object_patched(mod_name, item_name):
|
| 30 |
+
"""
|
| 31 |
+
Check if an object in a module has been replaced with a
|
| 32 |
+
cooperative version.
|
| 33 |
+
|
| 34 |
+
:param str mod_name: The name of the standard library module,
|
| 35 |
+
e.g., ``'socket'``.
|
| 36 |
+
:param str item_name: The name of the attribute in the module,
|
| 37 |
+
e.g., ``'create_connection'``.
|
| 38 |
+
|
| 39 |
+
"""
|
| 40 |
+
return is_module_patched(mod_name) and item_name in saved[mod_name]
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def is_anything_patched():
|
| 44 |
+
"""
|
| 45 |
+
Check if this module has done any patching in the current process.
|
| 46 |
+
This is currently only used in gevent tests.
|
| 47 |
+
|
| 48 |
+
Not currently a documented, public API, because I'm not convinced
|
| 49 |
+
it is 100% reliable in the event of third-party patch functions that
|
| 50 |
+
don't use ``saved``.
|
| 51 |
+
|
| 52 |
+
.. versionadded:: 21.1.0
|
| 53 |
+
"""
|
| 54 |
+
return bool(saved)
|
| 55 |
+
|
| 56 |
+
def _get_original(name, items):
|
| 57 |
+
d = saved.get(name, {})
|
| 58 |
+
values = []
|
| 59 |
+
module = None
|
| 60 |
+
for item in items:
|
| 61 |
+
if item in d:
|
| 62 |
+
values.append(d[item])
|
| 63 |
+
else:
|
| 64 |
+
if module is None:
|
| 65 |
+
module = __import__(name)
|
| 66 |
+
values.append(getattr(module, item))
|
| 67 |
+
return values
|
| 68 |
+
|
| 69 |
+
def _save(module, attr_name, item):
|
| 70 |
+
saved.setdefault(module.__name__, {}).setdefault(attr_name, item)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/monkey/_util.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Utilities used in patching.
|
| 4 |
+
|
| 5 |
+
Internal use only.
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _notify_patch(event, _warnings=None):
|
| 12 |
+
# Raises DoNotPatch if we're not supposed to patch
|
| 13 |
+
from gevent.events import notify_and_call_entry_points
|
| 14 |
+
|
| 15 |
+
event._warnings = _warnings
|
| 16 |
+
notify_and_call_entry_points(event)
|
| 17 |
+
|
| 18 |
+
def _ignores_DoNotPatch(func):
|
| 19 |
+
|
| 20 |
+
from functools import wraps
|
| 21 |
+
|
| 22 |
+
@wraps(func)
|
| 23 |
+
def ignores(*args, **kwargs):
|
| 24 |
+
from gevent.events import DoNotPatch
|
| 25 |
+
try:
|
| 26 |
+
return func(*args, **kwargs)
|
| 27 |
+
except DoNotPatch:
|
| 28 |
+
return False
|
| 29 |
+
|
| 30 |
+
return ignores
|
| 31 |
+
|
| 32 |
+
def _check_availability(name):
|
| 33 |
+
"""
|
| 34 |
+
Test that the source and target modules for *name* are
|
| 35 |
+
available and return them.
|
| 36 |
+
|
| 37 |
+
:raise ImportError: If the source or target cannot be imported.
|
| 38 |
+
:return: The tuple ``(gevent_module, target_module, target_module_name)``
|
| 39 |
+
"""
|
| 40 |
+
# Always import the gevent module first. This helps us be sure we can
|
| 41 |
+
# use regular imports in gevent files (when we can't use gevent.monkey.get_original())
|
| 42 |
+
gevent_module = getattr(__import__('gevent.' + name), name)
|
| 43 |
+
target_module_name = getattr(gevent_module, '__target__', name)
|
| 44 |
+
target_module = __import__(target_module_name)
|
| 45 |
+
|
| 46 |
+
return gevent_module, target_module, target_module_name
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _patch_module(name,
|
| 50 |
+
items=None,
|
| 51 |
+
_warnings=None,
|
| 52 |
+
_patch_kwargs=None,
|
| 53 |
+
_notify_will_subscribers=True,
|
| 54 |
+
_notify_did_subscribers=True,
|
| 55 |
+
_call_hooks=True):
|
| 56 |
+
|
| 57 |
+
from .api import patch_module
|
| 58 |
+
|
| 59 |
+
gevent_module, target_module, target_module_name = _check_availability(name)
|
| 60 |
+
|
| 61 |
+
patch_module(target_module, gevent_module, items=items,
|
| 62 |
+
_warnings=_warnings, _patch_kwargs=_patch_kwargs,
|
| 63 |
+
_notify_will_subscribers=_notify_will_subscribers,
|
| 64 |
+
_notify_did_subscribers=_notify_did_subscribers,
|
| 65 |
+
_call_hooks=_call_hooks)
|
| 66 |
+
|
| 67 |
+
# On Python 2, the `futures` package will install
|
| 68 |
+
# a bunch of modules with the same name as those from Python 3,
|
| 69 |
+
# such as `_thread`; primarily these just do `from thread import *`,
|
| 70 |
+
# meaning we have alternate references. If that's already been imported,
|
| 71 |
+
# we need to attempt to patch that too.
|
| 72 |
+
|
| 73 |
+
# Be sure to keep the original states matching also.
|
| 74 |
+
|
| 75 |
+
alternate_names = getattr(gevent_module, '__alternate_targets__', ())
|
| 76 |
+
from ._state import saved # TODO: Add apis for these use cases.
|
| 77 |
+
for alternate_name in alternate_names:
|
| 78 |
+
alternate_module = sys.modules.get(alternate_name)
|
| 79 |
+
if alternate_module is not None and alternate_module is not target_module:
|
| 80 |
+
saved.pop(alternate_name, None)
|
| 81 |
+
patch_module(alternate_module, gevent_module, items=items,
|
| 82 |
+
_warnings=_warnings,
|
| 83 |
+
_notify_will_subscribers=False,
|
| 84 |
+
_notify_did_subscribers=False,
|
| 85 |
+
_call_hooks=False)
|
| 86 |
+
saved[alternate_name] = saved[target_module_name]
|
| 87 |
+
|
| 88 |
+
return gevent_module, target_module
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _queue_warning(message, _warnings):
|
| 92 |
+
# Queues a warning to show after the monkey-patching process is all done.
|
| 93 |
+
# Done this way to avoid extra imports during the process itself, just
|
| 94 |
+
# in case. If we're calling a function one-off (unusual) go ahead and do it
|
| 95 |
+
if _warnings is None:
|
| 96 |
+
_process_warnings([message])
|
| 97 |
+
else:
|
| 98 |
+
_warnings.append(message)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _process_warnings(_warnings):
|
| 102 |
+
import warnings
|
| 103 |
+
from ._errors import MonkeyPatchWarning
|
| 104 |
+
for warning in _warnings:
|
| 105 |
+
warnings.warn(warning, MonkeyPat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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""
|
| 3 |
+
Higher level functions that comprise parts of
|
| 4 |
+
the public monkey patching API.
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def get_original(mod_name, item_name):
|
| 11 |
+
"""
|
| 12 |
+
Retrieve the original object from a module.
|
| 13 |
+
|
| 14 |
+
If the object has not been patched, then that object will still be
|
| 15 |
+
retrieved.
|
| 16 |
+
|
| 17 |
+
:param str|sequence mod_name: The name of the standard library module,
|
| 18 |
+
e.g., ``'socket'``. Can also be a sequence of standard library
|
| 19 |
+
modules giving alternate names to try, e.g., ``('thread', '_thread')``;
|
| 20 |
+
the first importable module will supply all *item_name* items.
|
| 21 |
+
:param str|sequence item_name: A string or sequence of strings naming the
|
| 22 |
+
attribute(s) on the module ``mod_name`` to return.
|
| 23 |
+
|
| 24 |
+
:return: The original value if a string was given for
|
| 25 |
+
``item_name`` or a sequence of original values if a
|
| 26 |
+
sequence was passed.
|
| 27 |
+
"""
|
| 28 |
+
from ._state import _get_original
|
| 29 |
+
|
| 30 |
+
mod_names = [mod_name] if isinstance(mod_name, str) else mod_name
|
| 31 |
+
if isinstance(item_name, str):
|
| 32 |
+
item_names = [item_name]
|
| 33 |
+
unpack = True
|
| 34 |
+
else:
|
| 35 |
+
item_names = item_name
|
| 36 |
+
unpack = False
|
| 37 |
+
|
| 38 |
+
for mod in mod_names:
|
| 39 |
+
try:
|
| 40 |
+
result = _get_original(mod, item_names)
|
| 41 |
+
except ImportError:
|
| 42 |
+
if mod is mod_names[-1]:
|
| 43 |
+
raise
|
| 44 |
+
else:
|
| 45 |
+
return result[0] if unpack else result
|
| 46 |
+
|
| 47 |
+
_NONE = object()
|
| 48 |
+
|
| 49 |
+
def patch_item(module, attr, newitem):
|
| 50 |
+
from ._state import _save
|
| 51 |
+
|
| 52 |
+
olditem = getattr(module, attr, _NONE)
|
| 53 |
+
if olditem is not _NONE:
|
| 54 |
+
_save(module, attr, olditem)
|
| 55 |
+
setattr(module, attr, newitem)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def remove_item(module, attr):
|
| 59 |
+
from ._state import _save
|
| 60 |
+
|
| 61 |
+
olditem = getattr(module, attr, _NONE)
|
| 62 |
+
if olditem is _NONE:
|
| 63 |
+
return
|
| 64 |
+
_save(module, attr, olditem)
|
| 65 |
+
|
| 66 |
+
delattr(module, attr)
|
| 67 |
+
|
| 68 |
+
def patch_module(target_module, source_module, items=None,
|
| 69 |
+
_warnings=None,
|
| 70 |
+
_patch_kwargs=None,
|
| 71 |
+
_notify_will_subscribers=True,
|
| 72 |
+
_notify_did_subscribers=True,
|
| 73 |
+
_call_hooks=True):
|
| 74 |
+
"""
|
| 75 |
+
patch_module(target_module, source_module, items=None)
|
| 76 |
+
|
| 77 |
+
Replace attributes in *target_module* with the attributes of the
|
| 78 |
+
same name in *source_module*.
|
| 79 |
+
|
| 80 |
+
The *source_module* can provide some attributes to customize the process:
|
| 81 |
+
|
| 82 |
+
* ``__implements__`` is a list of attribute names to copy; if not present,
|
| 83 |
+
the *items* keyword argument is mandatory. ``__implements__`` must only have
|
| 84 |
+
names from the standard library module in it.
|
| 85 |
+
* ``_gevent_will_monkey_patch(target_module, items, warn, **kwargs)``
|
| 86 |
+
* ``_gevent_did_monkey_patch(target_module, items, warn, **kwargs)``
|
| 87 |
+
These two functions in the *source_module* are called *if* they exist,
|
| 88 |
+
before and after copying attributes, respectively. The "will" function
|
| 89 |
+
may modify *items*. The value of *warn* is a function that should be called
|
| 90 |
+
with a single string argument to issue a warning to the user. If the "will"
|
| 91 |
+
function raises :exc:`gevent.events.DoNotPatch`, no patching will be done. These functions
|
| 92 |
+
are called before any event subscribers or plugins.
|
| 93 |
+
|
| 94 |
+
:keyword list items: A list of attribute names to replace. If
|
| 95 |
+
not given, this will be taken from the *source_module* ``__implements__``
|
| 96 |
+
attribute.
|
| 97 |
+
:return: A true value if patching was done, a false value if patching was canceled.
|
| 98 |
+
|
| 99 |
+
.. versionadded:: 1.3b1
|
| 100 |
+
"""
|
| 101 |
+
from gevent import events
|
| 102 |
+
from ._errors import _BadImplements
|
| 103 |
+
from ._util import _notify_patch
|
| 104 |
+
|
| 105 |
+
if items is None:
|
| 106 |
+
try:
|
| 107 |
+
items = source_module.__implements__
|
| 108 |
+
except AttributeError as e:
|
| 109 |
+
raise _BadImplements(source_module) from e
|
| 110 |
+
|
| 111 |
+
if items is None:
|
| 112 |
+
raise _BadImplements(source_module)
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
if _call_hooks:
|
| 116 |
+
__call_module_hook(source_module, 'will', target_module, items, _warnings)
|
| 117 |
+
if _notify_will_subscribers:
|
| 118 |
+
_notify_patch(
|
| 119 |
+
events.GeventWillPatchModuleEvent(target_module.__name__, source_module,
|
| 120 |
+
target_module, items),
|
| 121 |
+
_warnings)
|
| 122 |
+
except events.DoNotPatch:
|
| 123 |
+
return False
|
| 124 |
+
|
| 125 |
+
# Undocumented, internal use: If the module defines
|
| 126 |
+
# `_gevent_do_monkey_patch(patch_request: _GeventDoPatchRequest)` call that;
|
| 127 |
+
# the module is responsible for its own patching.
|
| 128 |
+
do_patch = getattr(
|
| 129 |
+
source_module,
|
| 130 |
+
'_gevent_do_monkey_patch',
|
| 131 |
+
_GeventDoPatchRequest.default_patch_items
|
| 132 |
+
)
|
| 133 |
+
request = _GeventDoPatchRequest(target_module, source_module, items, _patch_kwargs)
|
| 134 |
+
do_patch(request)
|
| 135 |
+
|
| 136 |
+
if _call_hooks:
|
| 137 |
+
__call_module_hook(source_module, 'did', target_module, items, _warnings)
|
| 138 |
+
|
| 139 |
+
if _notify_did_subscribers:
|
| 140 |
+
# We allow turning off the broadcast of the 'did' event for the benefit
|
| 141 |
+
# of our internal functions which need to do additional work (besides copying
|
| 142 |
+
# attributes) before their patch can be considered complete.
|
| 143 |
+
_notify_patch(
|
| 144 |
+
events.GeventDidPatchModuleEvent(target_module.__name__, source_module,
|
| 145 |
+
target_module)
|
| 146 |
+
)
|
| 147 |
+
|
| 148 |
+
return True
|
| 149 |
+
|
| 150 |
+
class _GeventDoPatchRequest(object):
|
| 151 |
+
|
| 152 |
+
get_original = staticmethod(get_original)
|
| 153 |
+
|
| 154 |
+
def __init__(self,
|
| 155 |
+
target_module,
|
| 156 |
+
source_module,
|
| 157 |
+
items,
|
| 158 |
+
patch_kwargs):
|
| 159 |
+
self.target_module = target_module
|
| 160 |
+
self.source_module = source_module
|
| 161 |
+
self.items = items
|
| 162 |
+
self.patch_kwargs = patch_kwargs or {}
|
| 163 |
+
|
| 164 |
+
def __repr__(self):
|
| 165 |
+
return '<%s target=%r source=%r items=%r kwargs=%r>' % (
|
| 166 |
+
self.__class__.__name__,
|
| 167 |
+
self.target_module,
|
| 168 |
+
self.source_module,
|
| 169 |
+
self.items,
|
| 170 |
+
self.patch_kwargs
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
def default_patch_items(self):
|
| 174 |
+
for attr in self.items:
|
| 175 |
+
patch_item(self.target_module, attr, getattr(self.source_module, attr))
|
| 176 |
+
|
| 177 |
+
def remove_item(self, target_module, *items):
|
| 178 |
+
if isinstance(target_module, str):
|
| 179 |
+
items = (target_module,) + items
|
| 180 |
+
target_module = self.target_module
|
| 181 |
+
|
| 182 |
+
for item in items:
|
| 183 |
+
remove_item(target_module, item)
|
| 184 |
+
|
| 185 |
+
def __call_module_hook(gevent_module, name, module, items, _warnings):
|
| 186 |
+
# This function can raise DoNotPatch on 'will'
|
| 187 |
+
|
| 188 |
+
def warn(message):
|
| 189 |
+
from ._util import _queue_warning
|
| 190 |
+
_queue_warning(message, _warnings)
|
| 191 |
+
|
| 192 |
+
func_name = '_gevent_' + name + '_monkey_patch'
|
| 193 |
+
try:
|
| 194 |
+
func = getattr(gevent_module, func_name)
|
| 195 |
+
except AttributeError:
|
| 196 |
+
func = lambda *args: None
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
func(module, items, warn)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/os.py
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Low-level operating system functions from :mod:`os`.
|
| 3 |
+
|
| 4 |
+
Cooperative I/O
|
| 5 |
+
===============
|
| 6 |
+
|
| 7 |
+
This module provides cooperative versions of :func:`os.read` and
|
| 8 |
+
:func:`os.write`. These functions are *not* monkey-patched; you
|
| 9 |
+
must explicitly call them or monkey patch them yourself.
|
| 10 |
+
|
| 11 |
+
POSIX functions
|
| 12 |
+
---------------
|
| 13 |
+
|
| 14 |
+
On POSIX, non-blocking IO is available.
|
| 15 |
+
|
| 16 |
+
- :func:`nb_read`
|
| 17 |
+
- :func:`nb_write`
|
| 18 |
+
- :func:`make_nonblocking`
|
| 19 |
+
|
| 20 |
+
All Platforms
|
| 21 |
+
-------------
|
| 22 |
+
|
| 23 |
+
On non-POSIX platforms (e.g., Windows), non-blocking IO is not
|
| 24 |
+
available. On those platforms (and on POSIX), cooperative IO can
|
| 25 |
+
be done with the threadpool.
|
| 26 |
+
|
| 27 |
+
- :func:`tp_read`
|
| 28 |
+
- :func:`tp_write`
|
| 29 |
+
|
| 30 |
+
Child Processes
|
| 31 |
+
===============
|
| 32 |
+
|
| 33 |
+
The functions :func:`fork` and (on POSIX) :func:`forkpty` and :func:`waitpid` can be used
|
| 34 |
+
to manage child processes.
|
| 35 |
+
|
| 36 |
+
.. warning::
|
| 37 |
+
|
| 38 |
+
Forking a process that uses greenlets does not eliminate all non-running
|
| 39 |
+
greenlets. Any that were scheduled in the hub of the forking thread in the parent
|
| 40 |
+
remain scheduled in the child; compare this to how normal threads operate. (This behaviour
|
| 41 |
+
may change is a subsequent major release.)
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
from __future__ import absolute_import
|
| 45 |
+
|
| 46 |
+
import os
|
| 47 |
+
|
| 48 |
+
from gevent.hub import _get_hub_noargs as get_hub
|
| 49 |
+
from gevent.hub import reinit
|
| 50 |
+
from gevent._config import config
|
| 51 |
+
from gevent._util import copy_globals
|
| 52 |
+
import errno
|
| 53 |
+
|
| 54 |
+
EAGAIN = getattr(errno, 'EAGAIN', 11)
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
import fcntl
|
| 58 |
+
except ImportError:
|
| 59 |
+
fcntl = None
|
| 60 |
+
|
| 61 |
+
__implements__ = ['fork']
|
| 62 |
+
__extensions__ = ['tp_read', 'tp_write']
|
| 63 |
+
|
| 64 |
+
_read = os.read
|
| 65 |
+
_write = os.write
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
ignored_errors = [EAGAIN, errno.EINTR]
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
if fcntl:
|
| 72 |
+
|
| 73 |
+
__extensions__ += ['make_nonblocking', 'nb_read', 'nb_write']
|
| 74 |
+
|
| 75 |
+
def make_nonblocking(fd):
|
| 76 |
+
"""Put the file descriptor *fd* into non-blocking mode if
|
| 77 |
+
possible.
|
| 78 |
+
|
| 79 |
+
:return: A boolean value that evaluates to True if successful.
|
| 80 |
+
"""
|
| 81 |
+
flags = fcntl.fcntl(fd, fcntl.F_GETFL, 0)
|
| 82 |
+
if not bool(flags & os.O_NONBLOCK):
|
| 83 |
+
fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
|
| 84 |
+
return True
|
| 85 |
+
|
| 86 |
+
def nb_read(fd, n):
|
| 87 |
+
"""
|
| 88 |
+
Read up to *n* bytes from file descriptor *fd*. Return a
|
| 89 |
+
byte string containing the bytes read, which may be shorter than
|
| 90 |
+
*n*. If end-of-file is reached, an empty string is returned.
|
| 91 |
+
|
| 92 |
+
The descriptor must be in non-blocking mode.
|
| 93 |
+
"""
|
| 94 |
+
hub = None
|
| 95 |
+
event = None
|
| 96 |
+
try:
|
| 97 |
+
while 1:
|
| 98 |
+
try:
|
| 99 |
+
result = _read(fd, n)
|
| 100 |
+
return result
|
| 101 |
+
except OSError as e:
|
| 102 |
+
if e.errno not in ignored_errors:
|
| 103 |
+
raise
|
| 104 |
+
if hub is None:
|
| 105 |
+
hub = get_hub()
|
| 106 |
+
event = hub.loop.io(fd, 1)
|
| 107 |
+
hub.wait(event)
|
| 108 |
+
finally:
|
| 109 |
+
if event is not None:
|
| 110 |
+
event.close()
|
| 111 |
+
event = None
|
| 112 |
+
hub = None
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def nb_write(fd, buf):
|
| 116 |
+
"""
|
| 117 |
+
Write some number of bytes from buffer *buf* to file
|
| 118 |
+
descriptor *fd*. Return the number of bytes written, which may
|
| 119 |
+
be less than the length of *buf*.
|
| 120 |
+
|
| 121 |
+
The file descriptor must be in non-blocking mode.
|
| 122 |
+
"""
|
| 123 |
+
hub = None
|
| 124 |
+
event = None
|
| 125 |
+
try:
|
| 126 |
+
while 1:
|
| 127 |
+
try:
|
| 128 |
+
result = _write(fd, buf)
|
| 129 |
+
return result
|
| 130 |
+
except OSError as e:
|
| 131 |
+
if e.errno not in ignored_errors:
|
| 132 |
+
raise
|
| 133 |
+
if hub is None:
|
| 134 |
+
hub = get_hub()
|
| 135 |
+
event = hub.loop.io(fd, 2)
|
| 136 |
+
hub.wait(event)
|
| 137 |
+
finally:
|
| 138 |
+
if event is not None:
|
| 139 |
+
event.close()
|
| 140 |
+
event = None
|
| 141 |
+
hub = None
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def tp_read(fd, n):
|
| 145 |
+
"""Read up to *n* bytes from file descriptor *fd*. Return a string
|
| 146 |
+
containing the bytes read. If end-of-file is reached, an empty string
|
| 147 |
+
is returned.
|
| 148 |
+
|
| 149 |
+
Reading is done using the threadpool.
|
| 150 |
+
"""
|
| 151 |
+
return get_hub().threadpool.apply(_read, (fd, n))
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def tp_write(fd, buf):
|
| 155 |
+
"""Write bytes from buffer *buf* to file descriptor *fd*. Return the
|
| 156 |
+
number of bytes written.
|
| 157 |
+
|
| 158 |
+
Writing is done using the threadpool.
|
| 159 |
+
"""
|
| 160 |
+
return get_hub().threadpool.apply(_write, (fd, buf))
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
if hasattr(os, 'fork'):
|
| 164 |
+
# pylint:disable=function-redefined,redefined-outer-name
|
| 165 |
+
|
| 166 |
+
_raw_fork = os.fork
|
| 167 |
+
|
| 168 |
+
def fork_gevent():
|
| 169 |
+
"""
|
| 170 |
+
Forks the process using :func:`os.fork` and prepares the
|
| 171 |
+
child process to continue using gevent before returning.
|
| 172 |
+
|
| 173 |
+
.. note::
|
| 174 |
+
|
| 175 |
+
The PID returned by this function may not be waitable with
|
| 176 |
+
either the original :func:`os.waitpid` or this module's
|
| 177 |
+
:func:`waitpid` and it may not generate SIGCHLD signals if
|
| 178 |
+
libev child watchers are or ever have been in use. For
|
| 179 |
+
example, the :mod:`gevent.subprocess` module uses libev
|
| 180 |
+
child watchers (which parts of gevent use libev child
|
| 181 |
+
watchers is subject to change at any time). Most
|
| 182 |
+
applications should use :func:`fork_and_watch`, which is
|
| 183 |
+
monkey-patched as the default replacement for
|
| 184 |
+
:func:`os.fork` and implements the ``fork`` function of
|
| 185 |
+
this module by default, unless the environment variable
|
| 186 |
+
``GEVENT_NOWAITPID`` is defined before this module is
|
| 187 |
+
imported.
|
| 188 |
+
|
| 189 |
+
.. versionadded:: 1.1b2
|
| 190 |
+
"""
|
| 191 |
+
import warnings
|
| 192 |
+
# The simple `catch_warnings(action='ignore', category=DeprecationWarning)`
|
| 193 |
+
# is only available in 3.11+.
|
| 194 |
+
with warnings.catch_warnings():
|
| 195 |
+
warnings.simplefilter('ignore', DeprecationWarning)
|
| 196 |
+
result = _raw_fork()
|
| 197 |
+
if not result:
|
| 198 |
+
reinit()
|
| 199 |
+
return result
|
| 200 |
+
|
| 201 |
+
def fork():
|
| 202 |
+
"""
|
| 203 |
+
A wrapper for :func:`fork_gevent` for non-POSIX platforms.
|
| 204 |
+
"""
|
| 205 |
+
return fork_gevent()
|
| 206 |
+
|
| 207 |
+
if hasattr(os, 'forkpty'):
|
| 208 |
+
_raw_forkpty = os.forkpty
|
| 209 |
+
|
| 210 |
+
def forkpty_gevent():
|
| 211 |
+
"""
|
| 212 |
+
Forks the process using :func:`os.forkpty` and prepares the
|
| 213 |
+
child process to continue using gevent before returning.
|
| 214 |
+
|
| 215 |
+
Returns a tuple (pid, master_fd). The `master_fd` is *not* put into
|
| 216 |
+
non-blocking mode.
|
| 217 |
+
|
| 218 |
+
Availability: Some Unix systems.
|
| 219 |
+
|
| 220 |
+
.. seealso:: This function has the same limitations as :func:`fork_gevent`.
|
| 221 |
+
|
| 222 |
+
.. versionadded:: 1.1b5
|
| 223 |
+
"""
|
| 224 |
+
pid, master_fd = _raw_forkpty()
|
| 225 |
+
if not pid:
|
| 226 |
+
reinit()
|
| 227 |
+
return pid, master_fd
|
| 228 |
+
|
| 229 |
+
forkpty = forkpty_gevent
|
| 230 |
+
|
| 231 |
+
__implements__.append('forkpty')
|
| 232 |
+
__extensions__.append("forkpty_gevent")
|
| 233 |
+
|
| 234 |
+
if hasattr(os, 'WNOWAIT') or hasattr(os, 'WNOHANG'):
|
| 235 |
+
# We can only do this on POSIX
|
| 236 |
+
import time
|
| 237 |
+
|
| 238 |
+
_waitpid = os.waitpid
|
| 239 |
+
_WNOHANG = os.WNOHANG
|
| 240 |
+
|
| 241 |
+
# replaced by the signal module.
|
| 242 |
+
_on_child_hook = lambda: None
|
| 243 |
+
|
| 244 |
+
# {pid -> watcher or tuple(pid, rstatus, timestamp)}
|
| 245 |
+
_watched_children = {}
|
| 246 |
+
|
| 247 |
+
def _on_child(watcher, callback):
|
| 248 |
+
# XXX: Could handle tracing here by not stopping
|
| 249 |
+
# until the pid is terminated
|
| 250 |
+
watcher.stop()
|
| 251 |
+
try:
|
| 252 |
+
_watched_children[watcher.pid] = (watcher.pid, watcher.rstatus, time.time())
|
| 253 |
+
if callback:
|
| 254 |
+
callback(watcher)
|
| 255 |
+
# dispatch an "event"; used by gevent.signal.signal
|
| 256 |
+
_on_child_hook()
|
| 257 |
+
# now is as good a time as any to reap children
|
| 258 |
+
_reap_children()
|
| 259 |
+
finally:
|
| 260 |
+
watcher.close()
|
| 261 |
+
|
| 262 |
+
def _reap_children(timeout=60):
|
| 263 |
+
# Remove all the dead children that haven't been waited on
|
| 264 |
+
# for the *timeout* seconds.
|
| 265 |
+
# Some platforms queue delivery of SIGCHLD for all children that die;
|
| 266 |
+
# in that case, a well-behaved application should call waitpid() for each
|
| 267 |
+
# signal.
|
| 268 |
+
# Some platforms (linux) only guarantee one delivery if multiple children
|
| 269 |
+
# die. On that platform, the well-behave application calls waitpid() in a loop
|
| 270 |
+
# until it gets back -1, indicating no more dead children need to be waited for.
|
| 271 |
+
# In either case, waitpid should be called the same number of times as dead children,
|
| 272 |
+
# thus removing all the watchers when a SIGCHLD arrives. The (generous) timeout
|
| 273 |
+
# is to work with applications that neglect to call waitpid and prevent "unlimited"
|
| 274 |
+
# growth.
|
| 275 |
+
# Note that we don't watch for the case of pid wraparound. That is, we fork a new
|
| 276 |
+
# child with the same pid as an existing watcher, but the child is already dead,
|
| 277 |
+
# just not waited on yet.
|
| 278 |
+
now = time.time()
|
| 279 |
+
oldest_allowed = now - timeout
|
| 280 |
+
dead = [
|
| 281 |
+
pid for pid, val
|
| 282 |
+
in _watched_children.items()
|
| 283 |
+
if isinstance(val, tuple) and val[2] < oldest_allowed
|
| 284 |
+
]
|
| 285 |
+
for pid in dead:
|
| 286 |
+
del _watched_children[pid]
|
| 287 |
+
|
| 288 |
+
def waitpid(pid, options):
|
| 289 |
+
"""
|
| 290 |
+
Wait for a child process to finish.
|
| 291 |
+
|
| 292 |
+
If the child process was spawned using
|
| 293 |
+
:func:`fork_and_watch`, then this function behaves
|
| 294 |
+
cooperatively. If not, it *may* have race conditions; see
|
| 295 |
+
:func:`fork_gevent` for more information.
|
| 296 |
+
|
| 297 |
+
The arguments are as for the underlying
|
| 298 |
+
:func:`os.waitpid`. Some combinations of *options* may not
|
| 299 |
+
be supported cooperatively (as of 1.1 that includes
|
| 300 |
+
WUNTRACED). Using a *pid* of 0 to request waiting on only processes
|
| 301 |
+
from the current process group is not cooperative. A *pid* of -1
|
| 302 |
+
to wait for any child is non-blocking, but may or may not
|
| 303 |
+
require a trip around the event loop, depending on whether any children
|
| 304 |
+
have already terminated but not been waited on.
|
| 305 |
+
|
| 306 |
+
Availability: POSIX.
|
| 307 |
+
|
| 308 |
+
.. versionadded:: 1.1b1
|
| 309 |
+
.. versionchanged:: 1.2a1
|
| 310 |
+
More cases are handled in a cooperative manner.
|
| 311 |
+
"""
|
| 312 |
+
# pylint: disable=too-many-return-statements
|
| 313 |
+
# XXX Does not handle tracing children
|
| 314 |
+
|
| 315 |
+
# So long as libev's loop doesn't run, it's OK to add
|
| 316 |
+
# child watchers. The SIGCHLD handler only feeds events
|
| 317 |
+
# for the next iteration of the loop to handle. (And the
|
| 318 |
+
# signal handler itself is only called from the next loop
|
| 319 |
+
# iteration.)
|
| 320 |
+
|
| 321 |
+
if pid <= 0:
|
| 322 |
+
# magic functions for multiple children.
|
| 323 |
+
if pid == -1:
|
| 324 |
+
# Any child. If we have one that we're watching
|
| 325 |
+
# and that finished, we will use that one,
|
| 326 |
+
# preferring the oldest. Otherwise, let the OS
|
| 327 |
+
# take care of it.
|
| 328 |
+
finished_at = None
|
| 329 |
+
for k, v in _watched_children.items():
|
| 330 |
+
if (
|
| 331 |
+
isinstance(v, tuple)
|
| 332 |
+
and (finished_at is None or v[2] < finished_at)
|
| 333 |
+
):
|
| 334 |
+
pid = k
|
| 335 |
+
finished_at = v[2]
|
| 336 |
+
|
| 337 |
+
if pid <= 0:
|
| 338 |
+
# We didn't have one that was ready. If there are
|
| 339 |
+
# no funky options set, and the pid was -1
|
| 340 |
+
# (meaning any process, not 0, which means process
|
| 341 |
+
# group--- libev doesn't know about process
|
| 342 |
+
# groups) then we can use a child watcher of pid 0; otherwise,
|
| 343 |
+
# pass through to the OS.
|
| 344 |
+
if pid == -1 and options == 0:
|
| 345 |
+
hub = get_hub()
|
| 346 |
+
with hub.loop.child(0, False) as watcher:
|
| 347 |
+
hub.wait(watcher)
|
| 348 |
+
return watcher.rpid, watcher.rstatus
|
| 349 |
+
# There were funky options/pid, so we must go to the OS.
|
| 350 |
+
return _waitpid(pid, options)
|
| 351 |
+
|
| 352 |
+
if pid in _watched_children:
|
| 353 |
+
# yes, we're watching it
|
| 354 |
+
|
| 355 |
+
# Note that the remainder of this code must be careful to NOT
|
| 356 |
+
# yield to the event loop except at well known times, or
|
| 357 |
+
# we have a race condition between the _on_child callback and the
|
| 358 |
+
# code here that could lead to a process to hang.
|
| 359 |
+
if options & _WNOHANG or isinstance(_watched_children[pid], tuple):
|
| 360 |
+
# We're either asked not to block, or it already finished, in which
|
| 361 |
+
# case blocking doesn't matter
|
| 362 |
+
result = _watched_children[pid]
|
| 363 |
+
if isinstance(result, tuple):
|
| 364 |
+
# it finished. libev child watchers
|
| 365 |
+
# are one-shot
|
| 366 |
+
del _watched_children[pid]
|
| 367 |
+
return result[:2]
|
| 368 |
+
# it's not finished
|
| 369 |
+
return (0, 0)
|
| 370 |
+
|
| 371 |
+
# Ok, we need to "block". Do so via a watcher so that we're
|
| 372 |
+
# cooperative. We know it's our child, etc, so this should work.
|
| 373 |
+
watcher = _watched_children[pid]
|
| 374 |
+
# We can't start a watcher that's already started,
|
| 375 |
+
# so we can't reuse the existing watcher. Notice that the
|
| 376 |
+
# old watcher must not have fired already, or during this time, but
|
| 377 |
+
# only after we successfully `start()` the watcher. So this must
|
| 378 |
+
# not yield to the event loop.
|
| 379 |
+
with watcher.loop.child(pid, False) as new_watcher:
|
| 380 |
+
get_hub().wait(new_watcher)
|
| 381 |
+
# Ok, so now the new watcher is done. That means
|
| 382 |
+
# the old watcher's callback (_on_child) should
|
| 383 |
+
# have fired, potentially taking this child out of
|
| 384 |
+
# _watched_children (but that could depend on how
|
| 385 |
+
# many callbacks there were to run, so use the
|
| 386 |
+
# watcher object directly; libev sets all the
|
| 387 |
+
# watchers at the same time).
|
| 388 |
+
return watcher.rpid, watcher.rstatus
|
| 389 |
+
|
| 390 |
+
# we're not watching it and it may not even be our child,
|
| 391 |
+
# so we must go to the OS to be sure to get the right semantics (exception)
|
| 392 |
+
# XXX
|
| 393 |
+
# libuv has a race condition because the signal
|
| 394 |
+
# handler is a Python function, so the InterruptedError
|
| 395 |
+
# is raised before the signal handler runs and calls the
|
| 396 |
+
# child watcher
|
| 397 |
+
# we're not watching it
|
| 398 |
+
return _waitpid(pid, options)
|
| 399 |
+
|
| 400 |
+
def _watch_child(pid, callback=None, loop=None, ref=False):
|
| 401 |
+
loop = loop or get_hub().loop
|
| 402 |
+
watcher = loop.child(pid, ref=ref)
|
| 403 |
+
_watched_children[pid] = watcher
|
| 404 |
+
watcher.start(_on_child, watcher, callback)
|
| 405 |
+
|
| 406 |
+
def fork_and_watch(callback=None, loop=None, ref=False, fork=fork_gevent):
|
| 407 |
+
"""
|
| 408 |
+
Fork a child process and start a child watcher for it in the parent process.
|
| 409 |
+
|
| 410 |
+
This call cooperates with :func:`waitpid` to enable cooperatively waiting
|
| 411 |
+
for children to finish. When monkey-patching, these functions are patched in as
|
| 412 |
+
:func:`os.fork` and :func:`os.waitpid`, respectively.
|
| 413 |
+
|
| 414 |
+
In the child process, this function calls :func:`gevent.hub.reinit` before returning.
|
| 415 |
+
|
| 416 |
+
Availability: POSIX.
|
| 417 |
+
|
| 418 |
+
:keyword callback: If given, a callable that will be called with the child watcher
|
| 419 |
+
when the child finishes.
|
| 420 |
+
:keyword loop: The loop to start the watcher in. Defaults to the
|
| 421 |
+
loop of the current hub.
|
| 422 |
+
:keyword fork: The fork function. Defaults to :func:`the one defined in this
|
| 423 |
+
module <gevent.os.fork_gevent>` (which automatically calls :func:`gevent.hub.reinit`).
|
| 424 |
+
Pass the builtin :func:`os.fork` function if you do not need to
|
| 425 |
+
initialize gevent in the child process.
|
| 426 |
+
|
| 427 |
+
.. versionadded:: 1.1b1
|
| 428 |
+
.. seealso::
|
| 429 |
+
:func:`gevent.monkey.get_original` To access the builtin :func:`os.fork`.
|
| 430 |
+
"""
|
| 431 |
+
pid = fork()
|
| 432 |
+
if pid:
|
| 433 |
+
# parent
|
| 434 |
+
_watch_child(pid, callback, loop, ref)
|
| 435 |
+
return pid
|
| 436 |
+
|
| 437 |
+
__extensions__.append('fork_and_watch')
|
| 438 |
+
__extensions__.append('fork_gevent')
|
| 439 |
+
|
| 440 |
+
if 'forkpty' in __implements__:
|
| 441 |
+
def forkpty_and_watch(callback=None, loop=None, ref=False, forkpty=forkpty_gevent):
|
| 442 |
+
"""
|
| 443 |
+
Like :func:`fork_and_watch`, except using :func:`forkpty_gevent`.
|
| 444 |
+
|
| 445 |
+
Availability: Some Unix systems.
|
| 446 |
+
|
| 447 |
+
.. versionadded:: 1.1b5
|
| 448 |
+
"""
|
| 449 |
+
result = []
|
| 450 |
+
|
| 451 |
+
def _fork():
|
| 452 |
+
pid_and_fd = forkpty()
|
| 453 |
+
result.append(pid_and_fd)
|
| 454 |
+
return pid_and_fd[0]
|
| 455 |
+
fork_and_watch(callback, loop, ref, _fork)
|
| 456 |
+
return result[0]
|
| 457 |
+
|
| 458 |
+
__extensions__.append('forkpty_and_watch')
|
| 459 |
+
|
| 460 |
+
# Watch children by default
|
| 461 |
+
if not config.disable_watch_children:
|
| 462 |
+
# Broken out into separate functions instead of simple name aliases
|
| 463 |
+
# for documentation purposes.
|
| 464 |
+
def fork(*args, **kwargs):
|
| 465 |
+
"""
|
| 466 |
+
Forks a child process and starts a child watcher for it in the
|
| 467 |
+
parent process so that ``waitpid`` and SIGCHLD work as expected.
|
| 468 |
+
|
| 469 |
+
This implementation of ``fork`` is a wrapper for :func:`fork_and_watch`
|
| 470 |
+
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
|
| 471 |
+
This is the default and should be used by most applications.
|
| 472 |
+
|
| 473 |
+
.. versionchanged:: 1.1b2
|
| 474 |
+
"""
|
| 475 |
+
# take any args to match fork_and_watch
|
| 476 |
+
return fork_and_watch(*args, **kwargs)
|
| 477 |
+
|
| 478 |
+
if 'forkpty' in __implements__:
|
| 479 |
+
def forkpty(*args, **kwargs):
|
| 480 |
+
"""
|
| 481 |
+
Like :func:`fork`, but using :func:`forkpty_gevent`.
|
| 482 |
+
|
| 483 |
+
This implementation of ``forkpty`` is a wrapper for :func:`forkpty_and_watch`
|
| 484 |
+
when the environment variable ``GEVENT_NOWAITPID`` is *not* defined.
|
| 485 |
+
This is the default and should be used by most applications.
|
| 486 |
+
|
| 487 |
+
.. versionadded:: 1.1b5
|
| 488 |
+
"""
|
| 489 |
+
# take any args to match fork_and_watch
|
| 490 |
+
return forkpty_and_watch(*args, **kwargs)
|
| 491 |
+
__implements__.append("waitpid")
|
| 492 |
+
|
| 493 |
+
if hasattr(os, 'posix_spawn'):
|
| 494 |
+
_raw_posix_spawn = os.posix_spawn
|
| 495 |
+
_raw_posix_spawnp = os.posix_spawnp
|
| 496 |
+
|
| 497 |
+
def posix_spawn(*args, **kwargs):
|
| 498 |
+
pid = _raw_posix_spawn(*args, **kwargs)
|
| 499 |
+
_watch_child(pid)
|
| 500 |
+
return pid
|
| 501 |
+
|
| 502 |
+
def posix_spawnp(*args, **kwargs):
|
| 503 |
+
pid = _raw_posix_spawnp(*args, **kwargs)
|
| 504 |
+
_watch_child(pid)
|
| 505 |
+
return pid
|
| 506 |
+
|
| 507 |
+
__implements__.append("posix_spawn")
|
| 508 |
+
__implements__.append("posix_spawnp")
|
| 509 |
+
else:
|
| 510 |
+
def fork():
|
| 511 |
+
"""
|
| 512 |
+
Forks a child process, initializes gevent in the child,
|
| 513 |
+
but *does not* prepare the parent to wait for the child or receive SIGCHLD.
|
| 514 |
+
|
| 515 |
+
This implementation of ``fork`` is a wrapper for :func:`fork_gevent`
|
| 516 |
+
when the environment variable ``GEVENT_NOWAITPID`` *is* defined.
|
| 517 |
+
This is not recommended for most applications.
|
| 518 |
+
"""
|
| 519 |
+
return fork_gevent()
|
| 520 |
+
|
| 521 |
+
if 'forkpty' in __implements__:
|
| 522 |
+
def forkpty():
|
| 523 |
+
"""
|
| 524 |
+
Like :func:`fork`, but using :func:`os.forkpty`
|
| 525 |
+
|
| 526 |
+
This implementation of ``forkpty`` is a wrapper for :func:`forkpty_gevent`
|
| 527 |
+
when the environment variable ``GEVENT_NOWAITPID`` *is* defined.
|
| 528 |
+
This is not recommended for most applications.
|
| 529 |
+
|
| 530 |
+
.. versionadded:: 1.1b5
|
| 531 |
+
"""
|
| 532 |
+
return forkpty_gevent()
|
| 533 |
+
__extensions__.append("waitpid")
|
| 534 |
+
|
| 535 |
+
else:
|
| 536 |
+
__implements__.remove('fork')
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
__imports__ = copy_globals(os, globals(),
|
| 540 |
+
names_to_ignore=__implements__ + __extensions__,
|
| 541 |
+
dunder_names_to_keep=())
|
| 542 |
+
|
| 543 |
+
__all__ = list(set(__implements__ + __extensions__))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pool.py
ADDED
|
@@ -0,0 +1,677 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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in a group.
|
| 4 |
+
|
| 5 |
+
The :class:`Group` class in this module abstracts a group of running
|
| 6 |
+
greenlets. When a greenlet dies, it's automatically removed from the
|
| 7 |
+
group. All running greenlets in a group can be waited on with
|
| 8 |
+
:meth:`Group.join`, or all running greenlets can be killed with
|
| 9 |
+
:meth:`Group.kill`.
|
| 10 |
+
|
| 11 |
+
The :class:`Pool` class, which is a subclass of :class:`Group`,
|
| 12 |
+
provides a way to limit concurrency: its :meth:`spawn <Pool.spawn>`
|
| 13 |
+
method blocks if the number of greenlets in the pool has already
|
| 14 |
+
reached the limit, until there is a free slot.
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import print_function, absolute_import, division
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
from gevent.hub import GreenletExit, getcurrent, kill as _kill
|
| 20 |
+
from gevent.greenlet import joinall, Greenlet
|
| 21 |
+
from gevent.queue import Full as QueueFull
|
| 22 |
+
from gevent.timeout import Timeout
|
| 23 |
+
from gevent.event import Event
|
| 24 |
+
from gevent.lock import Semaphore, DummySemaphore
|
| 25 |
+
|
| 26 |
+
from gevent._compat import izip
|
| 27 |
+
from gevent._imap import IMap
|
| 28 |
+
from gevent._imap import IMapUnordered
|
| 29 |
+
|
| 30 |
+
__all__ = [
|
| 31 |
+
'Group',
|
| 32 |
+
'Pool',
|
| 33 |
+
'PoolFull',
|
| 34 |
+
]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class GroupMappingMixin(object):
|
| 40 |
+
# Internal, non-public API class.
|
| 41 |
+
# Provides mixin methods for implementing mapping pools. Subclasses must define:
|
| 42 |
+
|
| 43 |
+
__slots__ = ()
|
| 44 |
+
|
| 45 |
+
def spawn(self, func, *args, **kwargs):
|
| 46 |
+
"""
|
| 47 |
+
A function that runs *func* with *args* and *kwargs*, potentially
|
| 48 |
+
asynchronously. Return a value with a ``get`` method that blocks
|
| 49 |
+
until the results of func are available, and a ``rawlink`` method
|
| 50 |
+
that calls a callback when the results are available.
|
| 51 |
+
|
| 52 |
+
If this object has an upper bound on how many asyncronously executing
|
| 53 |
+
tasks can exist, this method may block until a slot becomes available.
|
| 54 |
+
"""
|
| 55 |
+
raise NotImplementedError()
|
| 56 |
+
|
| 57 |
+
def _apply_immediately(self):
|
| 58 |
+
"""
|
| 59 |
+
should the function passed to apply be called immediately,
|
| 60 |
+
synchronously?
|
| 61 |
+
"""
|
| 62 |
+
raise NotImplementedError()
|
| 63 |
+
|
| 64 |
+
def _apply_async_use_greenlet(self):
|
| 65 |
+
"""
|
| 66 |
+
Should apply_async directly call Greenlet.spawn(), bypassing
|
| 67 |
+
`spawn`?
|
| 68 |
+
|
| 69 |
+
Return true when self.spawn would block.
|
| 70 |
+
"""
|
| 71 |
+
raise NotImplementedError()
|
| 72 |
+
|
| 73 |
+
def _apply_async_cb_spawn(self, callback, result):
|
| 74 |
+
"""
|
| 75 |
+
Run the given callback function, possibly
|
| 76 |
+
asynchronously, possibly synchronously.
|
| 77 |
+
"""
|
| 78 |
+
raise NotImplementedError()
|
| 79 |
+
|
| 80 |
+
def apply_cb(self, func, args=None, kwds=None, callback=None):
|
| 81 |
+
"""
|
| 82 |
+
:meth:`apply` the given *func(\\*args, \\*\\*kwds)*, and, if a *callback* is given, run it with the
|
| 83 |
+
results of *func* (unless an exception was raised.)
|
| 84 |
+
|
| 85 |
+
The *callback* may be called synchronously or asynchronously. If called
|
| 86 |
+
asynchronously, it will not be tracked by this group. (:class:`Group` and :class:`Pool`
|
| 87 |
+
call it asynchronously in a new greenlet; :class:`~gevent.threadpool.ThreadPool` calls
|
| 88 |
+
it synchronously in the current greenlet.)
|
| 89 |
+
"""
|
| 90 |
+
result = self.apply(func, args, kwds)
|
| 91 |
+
if callback is not None:
|
| 92 |
+
self._apply_async_cb_spawn(callback, result)
|
| 93 |
+
return result
|
| 94 |
+
|
| 95 |
+
def apply_async(self, func, args=None, kwds=None, callback=None):
|
| 96 |
+
"""
|
| 97 |
+
A variant of the :meth:`apply` method which returns a :class:`~.Greenlet` object.
|
| 98 |
+
|
| 99 |
+
When the returned greenlet gets to run, it *will* call :meth:`apply`,
|
| 100 |
+
passing in *func*, *args* and *kwds*.
|
| 101 |
+
|
| 102 |
+
If *callback* is specified, then it should be a callable which
|
| 103 |
+
accepts a single argument. When the result becomes ready
|
| 104 |
+
callback is applied to it (unless the call failed).
|
| 105 |
+
|
| 106 |
+
This method will never block, even if this group is full (that is,
|
| 107 |
+
even if :meth:`spawn` would block, this method will not).
|
| 108 |
+
|
| 109 |
+
.. caution:: The returned greenlet may or may not be tracked
|
| 110 |
+
as part of this group, so :meth:`joining <join>` this group is
|
| 111 |
+
not a reliable way to wait for the results to be available or
|
| 112 |
+
for the returned greenlet to run; instead, join the returned
|
| 113 |
+
greenlet.
|
| 114 |
+
|
| 115 |
+
.. tip:: Because :class:`~.ThreadPool` objects do not track greenlets, the returned
|
| 116 |
+
greenlet will never be a part of it. To reduce overhead and improve performance,
|
| 117 |
+
:class:`Group` and :class:`Pool` may choose to track the returned
|
| 118 |
+
greenlet. These are implementation details that may change.
|
| 119 |
+
"""
|
| 120 |
+
if args is None:
|
| 121 |
+
args = ()
|
| 122 |
+
if kwds is None:
|
| 123 |
+
kwds = {}
|
| 124 |
+
if self._apply_async_use_greenlet():
|
| 125 |
+
# cannot call self.spawn() directly because it will block
|
| 126 |
+
# XXX: This is always the case for ThreadPool, but for Group/Pool
|
| 127 |
+
# of greenlets, this is only the case when they are full...hence
|
| 128 |
+
# the weasely language about "may or may not be tracked". Should we make
|
| 129 |
+
# Group/Pool always return true as well so it's never tracked by any
|
| 130 |
+
# implementation? That would simplify that logic, but could increase
|
| 131 |
+
# the total number of greenlets in the system and add a layer of
|
| 132 |
+
# overhead for the simple cases when the pool isn't full.
|
| 133 |
+
return Greenlet.spawn(self.apply_cb, func, args, kwds, callback)
|
| 134 |
+
|
| 135 |
+
greenlet = self.spawn(func, *args, **kwds)
|
| 136 |
+
if callback is not None:
|
| 137 |
+
greenlet.link(pass_value(callback))
|
| 138 |
+
return greenlet
|
| 139 |
+
|
| 140 |
+
def apply(self, func, args=None, kwds=None):
|
| 141 |
+
"""
|
| 142 |
+
Rough quivalent of the :func:`apply()` builtin function blocking until
|
| 143 |
+
the result is ready and returning it.
|
| 144 |
+
|
| 145 |
+
The ``func`` will *usually*, but not *always*, be run in a way
|
| 146 |
+
that allows the current greenlet to switch out (for example,
|
| 147 |
+
in a new greenlet or thread, depending on implementation). But
|
| 148 |
+
if the current greenlet or thread is already one that was
|
| 149 |
+
spawned by this pool, the pool may choose to immediately run
|
| 150 |
+
the `func` synchronously.
|
| 151 |
+
|
| 152 |
+
Any exception ``func`` raises will be propagated to the caller of ``apply`` (that is,
|
| 153 |
+
this method will raise the exception that ``func`` raised).
|
| 154 |
+
"""
|
| 155 |
+
if args is None:
|
| 156 |
+
args = ()
|
| 157 |
+
if kwds is None:
|
| 158 |
+
kwds = {}
|
| 159 |
+
if self._apply_immediately():
|
| 160 |
+
return func(*args, **kwds)
|
| 161 |
+
return self.spawn(func, *args, **kwds).get()
|
| 162 |
+
|
| 163 |
+
def __map(self, func, iterable):
|
| 164 |
+
return [g.get() for g in
|
| 165 |
+
[self.spawn(func, i) for i in iterable]]
|
| 166 |
+
|
| 167 |
+
def map(self, func, iterable):
|
| 168 |
+
"""Return a list made by applying the *func* to each element of
|
| 169 |
+
the iterable.
|
| 170 |
+
|
| 171 |
+
.. seealso:: :meth:`imap`
|
| 172 |
+
"""
|
| 173 |
+
# We can't return until they're all done and in order. It
|
| 174 |
+
# wouldn't seem to much matter what order we wait on them in,
|
| 175 |
+
# so the simple, fast (50% faster than imap) solution would be:
|
| 176 |
+
|
| 177 |
+
# return [g.get() for g in
|
| 178 |
+
# [self.spawn(func, i) for i in iterable]]
|
| 179 |
+
|
| 180 |
+
# If the pool size is unlimited (or more than the len(iterable)), this
|
| 181 |
+
# is equivalent to imap (spawn() will never block, all of them run concurrently,
|
| 182 |
+
# we call get() in the order the iterable was given).
|
| 183 |
+
|
| 184 |
+
# Now lets imagine the pool if is limited size. Suppose the
|
| 185 |
+
# func is time.sleep, our pool is limited to 3 threads, and
|
| 186 |
+
# our input is [10, 1, 10, 1, 1] We would start three threads,
|
| 187 |
+
# one to sleep for 10, one to sleep for 1, and the last to
|
| 188 |
+
# sleep for 10. We would block starting the fourth thread. At
|
| 189 |
+
# time 1, we would finish the second thread and start another
|
| 190 |
+
# one for time 1. At time 2, we would finish that one and
|
| 191 |
+
# start the last thread, and then begin executing get() on the first
|
| 192 |
+
# thread.
|
| 193 |
+
|
| 194 |
+
# Because it's spawn that blocks, this is *also* equivalent to what
|
| 195 |
+
# imap would do.
|
| 196 |
+
|
| 197 |
+
# The one remaining difference is that imap runs in its own
|
| 198 |
+
# greenlet, potentially changing the way the event loop runs.
|
| 199 |
+
# That's easy enough to do.
|
| 200 |
+
|
| 201 |
+
g = Greenlet.spawn(self.__map, func, iterable)
|
| 202 |
+
return g.get()
|
| 203 |
+
|
| 204 |
+
def map_cb(self, func, iterable, callback=None):
|
| 205 |
+
result = self.map(func, iterable)
|
| 206 |
+
if callback is not None:
|
| 207 |
+
callback(result) # pylint:disable=not-callable
|
| 208 |
+
return result
|
| 209 |
+
|
| 210 |
+
def map_async(self, func, iterable, callback=None):
|
| 211 |
+
"""
|
| 212 |
+
A variant of the map() method which returns a Greenlet object that is executing
|
| 213 |
+
the map function.
|
| 214 |
+
|
| 215 |
+
If callback is specified then it should be a callable which accepts a
|
| 216 |
+
single argument.
|
| 217 |
+
"""
|
| 218 |
+
return Greenlet.spawn(self.map_cb, func, iterable, callback)
|
| 219 |
+
|
| 220 |
+
def __imap(self, cls, func, *iterables, **kwargs):
|
| 221 |
+
# Python 2 doesn't support the syntax that lets us mix varargs and
|
| 222 |
+
# a named kwarg, so we have to unpack manually
|
| 223 |
+
maxsize = kwargs.pop('maxsize', None)
|
| 224 |
+
if kwargs:
|
| 225 |
+
raise TypeError("Unsupported keyword arguments")
|
| 226 |
+
return cls.spawn(func, izip(*iterables), spawn=self.spawn,
|
| 227 |
+
_zipped=True, maxsize=maxsize)
|
| 228 |
+
|
| 229 |
+
def imap(self, func, *iterables, **kwargs):
|
| 230 |
+
"""
|
| 231 |
+
imap(func, *iterables, maxsize=None) -> iterable
|
| 232 |
+
|
| 233 |
+
An equivalent of :func:`itertools.imap`, operating in parallel.
|
| 234 |
+
The *func* is applied to each element yielded from each
|
| 235 |
+
iterable in *iterables* in turn, collecting the result.
|
| 236 |
+
|
| 237 |
+
If this object has a bound on the number of active greenlets it can
|
| 238 |
+
contain (such as :class:`Pool`), then at most that number of tasks will operate
|
| 239 |
+
in parallel.
|
| 240 |
+
|
| 241 |
+
:keyword int maxsize: If given and not-None, specifies the maximum number of
|
| 242 |
+
finished results that will be allowed to accumulate awaiting the reader;
|
| 243 |
+
more than that number of results will cause map function greenlets to begin
|
| 244 |
+
to block. This is most useful if there is a great disparity in the speed of
|
| 245 |
+
the mapping code and the consumer and the results consume a great deal of resources.
|
| 246 |
+
|
| 247 |
+
.. note:: This is separate from any bound on the number of active parallel
|
| 248 |
+
tasks, though they may have some interaction (for example, limiting the
|
| 249 |
+
number of parallel tasks to the smallest bound).
|
| 250 |
+
|
| 251 |
+
.. note:: Using a bound is slightly more computationally expensive than not using a bound.
|
| 252 |
+
|
| 253 |
+
.. tip:: The :meth:`imap_unordered` method makes much better
|
| 254 |
+
use of this parameter. Some additional, unspecified,
|
| 255 |
+
number of objects may be required to be kept in memory
|
| 256 |
+
to maintain order by this function.
|
| 257 |
+
|
| 258 |
+
:return: An iterable object.
|
| 259 |
+
|
| 260 |
+
.. versionchanged:: 1.1b3
|
| 261 |
+
Added the *maxsize* keyword parameter.
|
| 262 |
+
.. versionchanged:: 1.1a1
|
| 263 |
+
Accept multiple *iterables* to iterate in parallel.
|
| 264 |
+
"""
|
| 265 |
+
return self.__imap(IMap, func, *iterables, **kwargs)
|
| 266 |
+
|
| 267 |
+
def imap_unordered(self, func, *iterables, **kwargs):
|
| 268 |
+
"""
|
| 269 |
+
imap_unordered(func, *iterables, maxsize=None) -> iterable
|
| 270 |
+
|
| 271 |
+
The same as :meth:`imap` except that the ordering of the results
|
| 272 |
+
from the returned iterator should be considered in arbitrary
|
| 273 |
+
order.
|
| 274 |
+
|
| 275 |
+
This is lighter weight than :meth:`imap` and should be preferred if order
|
| 276 |
+
doesn't matter.
|
| 277 |
+
|
| 278 |
+
.. seealso:: :meth:`imap` for more details.
|
| 279 |
+
"""
|
| 280 |
+
return self.__imap(IMapUnordered, func, *iterables, **kwargs)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
class Group(GroupMappingMixin):
|
| 284 |
+
"""
|
| 285 |
+
Maintain a group of greenlets that are still running, without
|
| 286 |
+
limiting their number.
|
| 287 |
+
|
| 288 |
+
Links to each item and removes it upon notification.
|
| 289 |
+
|
| 290 |
+
Groups can be iterated to discover what greenlets they are tracking,
|
| 291 |
+
they can be tested to see if they contain a greenlet, and they know the
|
| 292 |
+
number (len) of greenlets they are tracking. If they are not tracking any
|
| 293 |
+
greenlets, they are False in a boolean context.
|
| 294 |
+
|
| 295 |
+
.. attribute:: greenlet_class
|
| 296 |
+
|
| 297 |
+
Either :class:`gevent.Greenlet` (the default) or a subclass.
|
| 298 |
+
These are the type of
|
| 299 |
+
object we will :meth:`spawn`. This can be
|
| 300 |
+
changed on an instance or in a subclass.
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
greenlet_class = Greenlet
|
| 304 |
+
|
| 305 |
+
def __init__(self, *args):
|
| 306 |
+
assert len(args) <= 1, args
|
| 307 |
+
self.greenlets = set(*args)
|
| 308 |
+
if args:
|
| 309 |
+
for greenlet in args[0]:
|
| 310 |
+
greenlet.rawlink(self._discard)
|
| 311 |
+
# each item we kill we place in dying, to avoid killing the same greenlet twice
|
| 312 |
+
self.dying = set()
|
| 313 |
+
self._empty_event = Event()
|
| 314 |
+
self._empty_event.set()
|
| 315 |
+
|
| 316 |
+
def __repr__(self):
|
| 317 |
+
return '<%s at 0x%x %s>' % (self.__class__.__name__, id(self), self.greenlets)
|
| 318 |
+
|
| 319 |
+
def __len__(self):
|
| 320 |
+
"""
|
| 321 |
+
Answer how many greenlets we are tracking. Note that if we are empty,
|
| 322 |
+
we are False in a boolean context.
|
| 323 |
+
"""
|
| 324 |
+
return len(self.greenlets)
|
| 325 |
+
|
| 326 |
+
def __contains__(self, item):
|
| 327 |
+
"""
|
| 328 |
+
Answer if we are tracking the given greenlet.
|
| 329 |
+
"""
|
| 330 |
+
return item in self.greenlets
|
| 331 |
+
|
| 332 |
+
def __iter__(self):
|
| 333 |
+
"""
|
| 334 |
+
Iterate across all the greenlets we are tracking, in no particular order.
|
| 335 |
+
"""
|
| 336 |
+
return iter(self.greenlets)
|
| 337 |
+
|
| 338 |
+
def add(self, greenlet):
|
| 339 |
+
"""
|
| 340 |
+
Begin tracking the *greenlet*.
|
| 341 |
+
|
| 342 |
+
If this group is :meth:`full`, then this method may block
|
| 343 |
+
until it is possible to track the greenlet.
|
| 344 |
+
|
| 345 |
+
Typically the *greenlet* should **not** be started when
|
| 346 |
+
it is added because if this object blocks in this method,
|
| 347 |
+
then the *greenlet* may run to completion before it is tracked.
|
| 348 |
+
"""
|
| 349 |
+
try:
|
| 350 |
+
rawlink = greenlet.rawlink
|
| 351 |
+
except AttributeError:
|
| 352 |
+
pass # non-Greenlet greenlet, like MAIN
|
| 353 |
+
else:
|
| 354 |
+
rawlink(self._discard)
|
| 355 |
+
self.greenlets.add(greenlet)
|
| 356 |
+
self._empty_event.clear()
|
| 357 |
+
|
| 358 |
+
def _discard(self, greenlet):
|
| 359 |
+
self.greenlets.discard(greenlet)
|
| 360 |
+
self.dying.discard(greenlet)
|
| 361 |
+
if not self.greenlets:
|
| 362 |
+
self._empty_event.set()
|
| 363 |
+
|
| 364 |
+
def discard(self, greenlet):
|
| 365 |
+
"""
|
| 366 |
+
Stop tracking the greenlet.
|
| 367 |
+
"""
|
| 368 |
+
self._discard(greenlet)
|
| 369 |
+
try:
|
| 370 |
+
unlink = greenlet.unlink
|
| 371 |
+
except AttributeError:
|
| 372 |
+
pass # non-Greenlet greenlet, like MAIN
|
| 373 |
+
else:
|
| 374 |
+
unlink(self._discard)
|
| 375 |
+
|
| 376 |
+
def start(self, greenlet):
|
| 377 |
+
"""
|
| 378 |
+
Add the **unstarted** *greenlet* to the collection of greenlets
|
| 379 |
+
this group is monitoring, and then start it.
|
| 380 |
+
"""
|
| 381 |
+
self.add(greenlet)
|
| 382 |
+
greenlet.start()
|
| 383 |
+
|
| 384 |
+
def spawn(self, *args, **kwargs): # pylint:disable=arguments-differ
|
| 385 |
+
"""
|
| 386 |
+
Begin a new greenlet with the given arguments (which are passed
|
| 387 |
+
to the greenlet constructor) and add it to the collection of greenlets
|
| 388 |
+
this group is monitoring.
|
| 389 |
+
|
| 390 |
+
:return: The newly started greenlet.
|
| 391 |
+
"""
|
| 392 |
+
greenlet = self.greenlet_class(*args, **kwargs)
|
| 393 |
+
self.start(greenlet)
|
| 394 |
+
return greenlet
|
| 395 |
+
|
| 396 |
+
# def close(self):
|
| 397 |
+
# """Prevents any more tasks from being submitted to the pool"""
|
| 398 |
+
# self.add = RaiseException("This %s has been closed" % self.__class__.__name__)
|
| 399 |
+
|
| 400 |
+
def join(self, timeout=None, raise_error=False):
|
| 401 |
+
"""
|
| 402 |
+
Wait for this group to become empty *at least once*.
|
| 403 |
+
|
| 404 |
+
If there are no greenlets in the group, returns immediately.
|
| 405 |
+
|
| 406 |
+
.. note:: By the time the waiting code (the caller of this
|
| 407 |
+
method) regains control, a greenlet may have been added to
|
| 408 |
+
this group, and so this object may no longer be empty. (That
|
| 409 |
+
is, ``group.join(); assert len(group) == 0`` is not
|
| 410 |
+
guaranteed to hold.) This method only guarantees that the group
|
| 411 |
+
reached a ``len`` of 0 at some point.
|
| 412 |
+
|
| 413 |
+
:keyword bool raise_error: If True (*not* the default), if any
|
| 414 |
+
greenlet that finished while the join was in progress raised
|
| 415 |
+
an exception, that exception will be raised to the caller of
|
| 416 |
+
this method. If multiple greenlets raised exceptions, which
|
| 417 |
+
one gets re-raised is not determined. Only greenlets currently
|
| 418 |
+
in the group when this method is called are guaranteed to
|
| 419 |
+
be checked for exceptions.
|
| 420 |
+
|
| 421 |
+
:return bool: A value indicating whether this group became empty.
|
| 422 |
+
If the timeout is specified and the group did not become empty
|
| 423 |
+
during that timeout, then this will be a false value. Otherwise
|
| 424 |
+
it will be a true value.
|
| 425 |
+
|
| 426 |
+
.. versionchanged:: 1.2a1
|
| 427 |
+
Add the return value.
|
| 428 |
+
"""
|
| 429 |
+
greenlets = list(self.greenlets) if raise_error else ()
|
| 430 |
+
result = self._empty_event.wait(timeout=timeout)
|
| 431 |
+
|
| 432 |
+
for greenlet in greenlets:
|
| 433 |
+
if greenlet.exception is not None:
|
| 434 |
+
if hasattr(greenlet, '_raise_exception'):
|
| 435 |
+
greenlet._raise_exception()
|
| 436 |
+
raise greenlet.exception
|
| 437 |
+
|
| 438 |
+
return result
|
| 439 |
+
|
| 440 |
+
def kill(self, exception=GreenletExit, block=True, timeout=None):
|
| 441 |
+
"""
|
| 442 |
+
Kill all greenlets being tracked by this group.
|
| 443 |
+
"""
|
| 444 |
+
timer = Timeout._start_new_or_dummy(timeout)
|
| 445 |
+
try:
|
| 446 |
+
while self.greenlets:
|
| 447 |
+
for greenlet in list(self.greenlets):
|
| 448 |
+
if greenlet in self.dying:
|
| 449 |
+
continue
|
| 450 |
+
try:
|
| 451 |
+
kill = greenlet.kill
|
| 452 |
+
except AttributeError:
|
| 453 |
+
_kill(greenlet, exception)
|
| 454 |
+
else:
|
| 455 |
+
kill(exception, block=False)
|
| 456 |
+
self.dying.add(greenlet)
|
| 457 |
+
if not block:
|
| 458 |
+
break
|
| 459 |
+
joinall(self.greenlets)
|
| 460 |
+
except Timeout as ex:
|
| 461 |
+
if ex is not timer:
|
| 462 |
+
raise
|
| 463 |
+
finally:
|
| 464 |
+
timer.cancel()
|
| 465 |
+
|
| 466 |
+
def killone(self, greenlet, exception=GreenletExit, block=True, timeout=None):
|
| 467 |
+
"""
|
| 468 |
+
If the given *greenlet* is running and being tracked by this group,
|
| 469 |
+
kill it.
|
| 470 |
+
"""
|
| 471 |
+
if greenlet not in self.dying and greenlet in self.greenlets:
|
| 472 |
+
greenlet.kill(exception, block=False)
|
| 473 |
+
self.dying.add(greenlet)
|
| 474 |
+
if block:
|
| 475 |
+
greenlet.join(timeout)
|
| 476 |
+
|
| 477 |
+
def full(self):
|
| 478 |
+
"""
|
| 479 |
+
Return a value indicating whether this group can track more greenlets.
|
| 480 |
+
|
| 481 |
+
In this implementation, because there are no limits on the number of
|
| 482 |
+
tracked greenlets, this will always return a ``False`` value.
|
| 483 |
+
"""
|
| 484 |
+
return False
|
| 485 |
+
|
| 486 |
+
def wait_available(self, timeout=None):
|
| 487 |
+
"""
|
| 488 |
+
Block until it is possible to :meth:`spawn` a new greenlet.
|
| 489 |
+
|
| 490 |
+
In this implementation, because there are no limits on the number
|
| 491 |
+
of tracked greenlets, this will always return immediately.
|
| 492 |
+
"""
|
| 493 |
+
|
| 494 |
+
# MappingMixin methods
|
| 495 |
+
|
| 496 |
+
def _apply_immediately(self):
|
| 497 |
+
# If apply() is called from one of our own
|
| 498 |
+
# worker greenlets, don't spawn a new one---if we're full, that
|
| 499 |
+
# could deadlock.
|
| 500 |
+
return getcurrent() in self
|
| 501 |
+
|
| 502 |
+
def _apply_async_cb_spawn(self, callback, result):
|
| 503 |
+
Greenlet.spawn(callback, result)
|
| 504 |
+
|
| 505 |
+
def _apply_async_use_greenlet(self):
|
| 506 |
+
# cannot call self.spawn() because it will block, so
|
| 507 |
+
# use a fresh, untracked greenlet that when run will
|
| 508 |
+
# (indirectly) call self.spawn() for us.
|
| 509 |
+
return self.full()
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
class PoolFull(QueueFull):
|
| 514 |
+
"""
|
| 515 |
+
Raised when a Pool is full and an attempt was made to
|
| 516 |
+
add a new greenlet to it in non-blocking mode.
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
class Pool(Group):
|
| 521 |
+
|
| 522 |
+
def __init__(self, size=None, greenlet_class=None):
|
| 523 |
+
"""
|
| 524 |
+
Create a new pool.
|
| 525 |
+
|
| 526 |
+
A pool is like a group, but the maximum number of members
|
| 527 |
+
is governed by the *size* parameter.
|
| 528 |
+
|
| 529 |
+
:keyword int size: If given, this non-negative integer is the
|
| 530 |
+
maximum count of active greenlets that will be allowed in
|
| 531 |
+
this pool. A few values have special significance:
|
| 532 |
+
|
| 533 |
+
* `None` (the default) places no limit on the number of
|
| 534 |
+
greenlets. This is useful when you want to track, but not limit,
|
| 535 |
+
greenlets. In general, a :class:`Group`
|
| 536 |
+
may be a more efficient way to achieve the same effect, but some things
|
| 537 |
+
need the additional abilities of this class (one example being the *spawn*
|
| 538 |
+
parameter of :class:`gevent.baseserver.BaseServer` and
|
| 539 |
+
its subclass :class:`gevent.pywsgi.WSGIServer`).
|
| 540 |
+
|
| 541 |
+
* ``0`` creates a pool that can never have any active greenlets. Attempting
|
| 542 |
+
to spawn in this pool will block forever. This is only useful
|
| 543 |
+
if an application uses :meth:`wait_available` with a timeout and checks
|
| 544 |
+
:meth:`free_count` before attempting to spawn.
|
| 545 |
+
"""
|
| 546 |
+
if size is not None and size < 0:
|
| 547 |
+
raise ValueError('size must not be negative: %r' % (size, ))
|
| 548 |
+
Group.__init__(self)
|
| 549 |
+
self.size = size
|
| 550 |
+
if greenlet_class is not None:
|
| 551 |
+
self.greenlet_class = greenlet_class
|
| 552 |
+
if size is None:
|
| 553 |
+
factory = DummySemaphore
|
| 554 |
+
else:
|
| 555 |
+
factory = Semaphore
|
| 556 |
+
self._semaphore = factory(size)
|
| 557 |
+
|
| 558 |
+
def wait_available(self, timeout=None):
|
| 559 |
+
"""
|
| 560 |
+
Wait until it's possible to spawn a greenlet in this pool.
|
| 561 |
+
|
| 562 |
+
:param float timeout: If given, only wait the specified number
|
| 563 |
+
of seconds.
|
| 564 |
+
|
| 565 |
+
.. warning:: If the pool was initialized with a size of 0, this
|
| 566 |
+
method will block forever unless a timeout is given.
|
| 567 |
+
|
| 568 |
+
:return: A number indicating how many new greenlets can be put into
|
| 569 |
+
the pool without blocking.
|
| 570 |
+
|
| 571 |
+
.. versionchanged:: 1.1a3
|
| 572 |
+
Added the ``timeout`` parameter.
|
| 573 |
+
"""
|
| 574 |
+
return self._semaphore.wait(timeout=timeout)
|
| 575 |
+
|
| 576 |
+
def full(self):
|
| 577 |
+
"""
|
| 578 |
+
Return a boolean indicating whether this pool is full, e.g. if
|
| 579 |
+
:meth:`add` would block.
|
| 580 |
+
|
| 581 |
+
:return: False if there is room for new members, True if there isn't.
|
| 582 |
+
"""
|
| 583 |
+
return self.free_count() <= 0
|
| 584 |
+
|
| 585 |
+
def free_count(self):
|
| 586 |
+
"""
|
| 587 |
+
Return a number indicating *approximately* how many more members
|
| 588 |
+
can be added to this pool.
|
| 589 |
+
"""
|
| 590 |
+
if self.size is None:
|
| 591 |
+
return 1
|
| 592 |
+
return max(0, self.size - len(self))
|
| 593 |
+
|
| 594 |
+
def start(self, greenlet, *args, **kwargs): # pylint:disable=arguments-differ
|
| 595 |
+
"""
|
| 596 |
+
start(greenlet, blocking=True, timeout=None) -> None
|
| 597 |
+
|
| 598 |
+
Add the **unstarted** *greenlet* to the collection of greenlets
|
| 599 |
+
this group is monitoring and then start it.
|
| 600 |
+
|
| 601 |
+
Parameters are as for :meth:`add`.
|
| 602 |
+
"""
|
| 603 |
+
self.add(greenlet, *args, **kwargs)
|
| 604 |
+
greenlet.start()
|
| 605 |
+
|
| 606 |
+
def add(self, greenlet, blocking=True, timeout=None): # pylint:disable=arguments-differ
|
| 607 |
+
"""
|
| 608 |
+
Begin tracking the given **unstarted** greenlet, possibly blocking
|
| 609 |
+
until space is available.
|
| 610 |
+
|
| 611 |
+
Usually you should call :meth:`start` to track and start the greenlet
|
| 612 |
+
instead of using this lower-level method, or :meth:`spawn` to
|
| 613 |
+
also create the greenlet.
|
| 614 |
+
|
| 615 |
+
:keyword bool blocking: If True (the default), this function
|
| 616 |
+
will block until the pool has space or a timeout occurs. If
|
| 617 |
+
False, this function will immediately raise a Timeout if the
|
| 618 |
+
pool is currently full.
|
| 619 |
+
:keyword float timeout: The maximum number of seconds this
|
| 620 |
+
method will block, if ``blocking`` is True. (Ignored if
|
| 621 |
+
``blocking`` is False.)
|
| 622 |
+
:raises PoolFull: if either ``blocking`` is False and the pool
|
| 623 |
+
was full, or if ``blocking`` is True and ``timeout`` was
|
| 624 |
+
exceeded.
|
| 625 |
+
|
| 626 |
+
.. caution:: If the *greenlet* has already been started and
|
| 627 |
+
*blocking* is true, then the greenlet may run to completion
|
| 628 |
+
while the current greenlet blocks waiting to track it. This would
|
| 629 |
+
enable higher concurrency than desired.
|
| 630 |
+
|
| 631 |
+
.. seealso:: :meth:`Group.add`
|
| 632 |
+
|
| 633 |
+
.. versionchanged:: 1.3.0 Added the ``blocking`` and
|
| 634 |
+
``timeout`` parameters.
|
| 635 |
+
"""
|
| 636 |
+
if not self._semaphore.acquire(blocking=blocking, timeout=timeout):
|
| 637 |
+
# We failed to acquire the semaphore.
|
| 638 |
+
# If blocking was True, then there was a timeout. If blocking was
|
| 639 |
+
# False, then there was no capacity. Either way, raise PoolFull.
|
| 640 |
+
raise PoolFull()
|
| 641 |
+
|
| 642 |
+
try:
|
| 643 |
+
Group.add(self, greenlet)
|
| 644 |
+
except:
|
| 645 |
+
self._semaphore.release()
|
| 646 |
+
raise
|
| 647 |
+
|
| 648 |
+
def _discard(self, greenlet):
|
| 649 |
+
Group._discard(self, greenlet)
|
| 650 |
+
self._semaphore.release()
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class pass_value(object):
|
| 654 |
+
__slots__ = ['callback']
|
| 655 |
+
|
| 656 |
+
def __init__(self, callback):
|
| 657 |
+
self.callback = callback
|
| 658 |
+
|
| 659 |
+
def __call__(self, source):
|
| 660 |
+
if source.successful():
|
| 661 |
+
self.callback(source.value)
|
| 662 |
+
|
| 663 |
+
def __hash__(self):
|
| 664 |
+
return hash(self.callback)
|
| 665 |
+
|
| 666 |
+
def __eq__(self, other):
|
| 667 |
+
return self.callback == getattr(other, 'callback', other)
|
| 668 |
+
|
| 669 |
+
def __str__(self):
|
| 670 |
+
return str(self.callback)
|
| 671 |
+
|
| 672 |
+
def __repr__(self):
|
| 673 |
+
return repr(self.callback)
|
| 674 |
+
|
| 675 |
+
def __getattr__(self, item):
|
| 676 |
+
assert item != 'callback'
|
| 677 |
+
return getattr(self.callback, item)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/pywsgi.py
ADDED
|
@@ -0,0 +1,1727 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2005-2009, eventlet contributors
|
| 2 |
+
# Copyright (c) 2009-2018, gevent contributors
|
| 3 |
+
"""
|
| 4 |
+
A pure-Python, gevent-friendly WSGI server implementing HTTP/1.1.
|
| 5 |
+
|
| 6 |
+
The server is provided in :class:`WSGIServer`, but most of the actual
|
| 7 |
+
WSGI work is handled by :class:`WSGIHandler` --- a new instance is
|
| 8 |
+
created for each request. The server can be customized to use
|
| 9 |
+
different subclasses of :class:`WSGIHandler`.
|
| 10 |
+
|
| 11 |
+
.. important::
|
| 12 |
+
|
| 13 |
+
This server is intended primarily for development and testing, and
|
| 14 |
+
secondarily for other "safe" scenarios where it will not be exposed to
|
| 15 |
+
potentially malicious input. The code has not been security audited,
|
| 16 |
+
and is not intended for direct exposure to the public Internet. For production
|
| 17 |
+
usage on the Internet, either choose a production-strength server such as
|
| 18 |
+
gunicorn, or put a reverse proxy between gevent and the Internet.
|
| 19 |
+
|
| 20 |
+
.. versionchanged:: 23.9.0
|
| 21 |
+
|
| 22 |
+
Complies more closely with the HTTP specification for chunked transfer encoding.
|
| 23 |
+
In particular, we are much stricter about trailers, and trailers that
|
| 24 |
+
are invalid (too long or featuring disallowed characters) forcibly close
|
| 25 |
+
the connection to the client *after* the results have been sent.
|
| 26 |
+
|
| 27 |
+
Trailers otherwise continue to be ignored and are not available to the
|
| 28 |
+
WSGI application.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
from __future__ import absolute_import
|
| 32 |
+
|
| 33 |
+
# FIXME: Can we refactor to make smallor?
|
| 34 |
+
# pylint:disable=too-many-lines
|
| 35 |
+
|
| 36 |
+
import errno
|
| 37 |
+
from io import BytesIO
|
| 38 |
+
import string
|
| 39 |
+
import sys
|
| 40 |
+
import time
|
| 41 |
+
import traceback
|
| 42 |
+
from datetime import datetime
|
| 43 |
+
|
| 44 |
+
from urllib.parse import unquote
|
| 45 |
+
|
| 46 |
+
from gevent import socket
|
| 47 |
+
import gevent
|
| 48 |
+
from gevent.server import StreamServer
|
| 49 |
+
from gevent.hub import GreenletExit
|
| 50 |
+
from gevent._compat import reraise
|
| 51 |
+
|
| 52 |
+
from functools import partial
|
| 53 |
+
unquote_latin1 = partial(unquote, encoding='latin-1')
|
| 54 |
+
|
| 55 |
+
_no_undoc_members = True # Don't put undocumented things into sphinx
|
| 56 |
+
|
| 57 |
+
__all__ = [
|
| 58 |
+
'WSGIServer',
|
| 59 |
+
'WSGIHandler',
|
| 60 |
+
'LoggingLogAdapter',
|
| 61 |
+
'Environ',
|
| 62 |
+
'SecureEnviron',
|
| 63 |
+
'WSGISecureEnviron',
|
| 64 |
+
]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
MAX_REQUEST_LINE = 8192
|
| 68 |
+
# Weekday and month names for HTTP date/time formatting; always English!
|
| 69 |
+
_WEEKDAYNAME = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
| 70 |
+
_MONTHNAME = (None, # Dummy so we can use 1-based month numbers
|
| 71 |
+
"Jan", "Feb", "Mar", "Apr", "May", "Jun",
|
| 72 |
+
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
| 73 |
+
|
| 74 |
+
# The contents of the "HEX" grammar rule for HTTP, upper and lowercase A-F plus digits,
|
| 75 |
+
# in byte form for comparing to the network.
|
| 76 |
+
_HEX = string.hexdigits.encode('ascii')
|
| 77 |
+
|
| 78 |
+
# The characters allowed in "token" rules.
|
| 79 |
+
|
| 80 |
+
# token = 1*tchar
|
| 81 |
+
# tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*"
|
| 82 |
+
# / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
|
| 83 |
+
# / DIGIT / ALPHA
|
| 84 |
+
# ; any VCHAR, except delimiters
|
| 85 |
+
# ALPHA = %x41-5A / %x61-7A ; A-Z / a-z
|
| 86 |
+
_ALLOWED_TOKEN_CHARS = frozenset(
|
| 87 |
+
# Remember we have to be careful because bytestrings
|
| 88 |
+
# inexplicably iterate as integers, which are not equal to bytes.
|
| 89 |
+
|
| 90 |
+
# explicit chars then DIGIT
|
| 91 |
+
(c.encode('ascii') for c in "!#$%&'*+-.^_`|~0123456789")
|
| 92 |
+
# Then we add ALPHA
|
| 93 |
+
) | {c.encode('ascii') for c in string.ascii_letters}
|
| 94 |
+
assert b'A' in _ALLOWED_TOKEN_CHARS
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# Errors
|
| 98 |
+
_ERRORS = {}
|
| 99 |
+
_INTERNAL_ERROR_STATUS = '500 Internal Server Error'
|
| 100 |
+
_INTERNAL_ERROR_BODY = b'Internal Server Error'
|
| 101 |
+
_INTERNAL_ERROR_HEADERS = (
|
| 102 |
+
('Content-Type', 'text/plain'),
|
| 103 |
+
('Connection', 'close'),
|
| 104 |
+
('Content-Length', str(len(_INTERNAL_ERROR_BODY)))
|
| 105 |
+
)
|
| 106 |
+
_ERRORS[500] = (_INTERNAL_ERROR_STATUS, _INTERNAL_ERROR_HEADERS, _INTERNAL_ERROR_BODY)
|
| 107 |
+
|
| 108 |
+
_BAD_REQUEST_STATUS = '400 Bad Request'
|
| 109 |
+
_BAD_REQUEST_BODY = ''
|
| 110 |
+
_BAD_REQUEST_HEADERS = (
|
| 111 |
+
('Content-Type', 'text/plain'),
|
| 112 |
+
('Connection', 'close'),
|
| 113 |
+
('Content-Length', str(len(_BAD_REQUEST_BODY)))
|
| 114 |
+
)
|
| 115 |
+
_ERRORS[400] = (_BAD_REQUEST_STATUS, _BAD_REQUEST_HEADERS, _BAD_REQUEST_BODY)
|
| 116 |
+
|
| 117 |
+
_REQUEST_TOO_LONG_RESPONSE = b"HTTP/1.1 414 Request URI Too Long\r\nConnection: close\r\nContent-length: 0\r\n\r\n"
|
| 118 |
+
_BAD_REQUEST_RESPONSE = b"HTTP/1.1 400 Bad Request\r\nConnection: close\r\nContent-length: 0\r\n\r\n"
|
| 119 |
+
_CONTINUE_RESPONSE = b"HTTP/1.1 100 Continue\r\n\r\n"
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def format_date_time(timestamp):
|
| 123 |
+
# Return a byte-string of the date and time in HTTP format
|
| 124 |
+
# .. versionchanged:: 1.1b5
|
| 125 |
+
# Return a byte string, not a native string
|
| 126 |
+
year, month, day, hh, mm, ss, wd, _y, _z = time.gmtime(timestamp)
|
| 127 |
+
value = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (_WEEKDAYNAME[wd], day, _MONTHNAME[month], year, hh, mm, ss)
|
| 128 |
+
value = value.encode("latin-1")
|
| 129 |
+
return value
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
class _InvalidClientInput(IOError):
|
| 133 |
+
# Internal exception raised by Input indicating that the client
|
| 134 |
+
# sent invalid data at the lowest level of the stream. The result
|
| 135 |
+
# *should* be a HTTP 400 error.
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class _InvalidClientRequest(ValueError):
|
| 140 |
+
# Internal exception raised by WSGIHandler.read_request indicating
|
| 141 |
+
# that the client sent an HTTP request that cannot be parsed
|
| 142 |
+
# (e.g., invalid grammar). The result *should* be an HTTP 400
|
| 143 |
+
# error. It must have exactly one argument, the fully formatted
|
| 144 |
+
# error string.
|
| 145 |
+
|
| 146 |
+
def __init__(self, message):
|
| 147 |
+
ValueError.__init__(self, message)
|
| 148 |
+
self.formatted_message = message
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Input(object):
|
| 152 |
+
|
| 153 |
+
__slots__ = ('rfile', 'content_length', 'socket', 'position',
|
| 154 |
+
'chunked_input', 'chunk_length', '_chunked_input_error')
|
| 155 |
+
|
| 156 |
+
def __init__(self, rfile, content_length, socket=None, chunked_input=False):
|
| 157 |
+
# pylint:disable=redefined-outer-name
|
| 158 |
+
self.rfile = rfile
|
| 159 |
+
self.content_length = content_length
|
| 160 |
+
self.socket = socket
|
| 161 |
+
self.position = 0
|
| 162 |
+
self.chunked_input = chunked_input
|
| 163 |
+
self.chunk_length = -1
|
| 164 |
+
self._chunked_input_error = False
|
| 165 |
+
|
| 166 |
+
def _discard(self):
|
| 167 |
+
if self._chunked_input_error:
|
| 168 |
+
# We are in an unknown state, so we can't necessarily discard
|
| 169 |
+
# the body (e.g., if the client keeps the socket open, we could hang
|
| 170 |
+
# here forever).
|
| 171 |
+
# In this case, we've raised an exception and the user of this object
|
| 172 |
+
# is going to close the socket, so we don't have to discard
|
| 173 |
+
return
|
| 174 |
+
|
| 175 |
+
if self.socket is None and (self.position < (self.content_length or 0) or self.chunked_input):
|
| 176 |
+
# ## Read and discard body
|
| 177 |
+
while 1:
|
| 178 |
+
d = self.read(16384)
|
| 179 |
+
if not d:
|
| 180 |
+
break
|
| 181 |
+
|
| 182 |
+
def _send_100_continue(self):
|
| 183 |
+
if self.socket is not None:
|
| 184 |
+
self.socket.sendall(_CONTINUE_RESPONSE)
|
| 185 |
+
self.socket = None
|
| 186 |
+
|
| 187 |
+
def _do_read(self, length=None, use_readline=False):
|
| 188 |
+
if use_readline:
|
| 189 |
+
reader = self.rfile.readline
|
| 190 |
+
else:
|
| 191 |
+
reader = self.rfile.read
|
| 192 |
+
content_length = self.content_length
|
| 193 |
+
if content_length is None:
|
| 194 |
+
# Either Content-Length or "Transfer-Encoding: chunked" must be present in a request with a body
|
| 195 |
+
# if it was chunked, then this function would have not been called
|
| 196 |
+
return b''
|
| 197 |
+
|
| 198 |
+
self._send_100_continue()
|
| 199 |
+
left = content_length - self.position
|
| 200 |
+
if length is None:
|
| 201 |
+
length = left
|
| 202 |
+
elif length > left:
|
| 203 |
+
length = left
|
| 204 |
+
if not length:
|
| 205 |
+
return b''
|
| 206 |
+
|
| 207 |
+
# On Python 2, self.rfile is usually socket.makefile(), which
|
| 208 |
+
# uses cStringIO.StringIO. If *length* is greater than the C
|
| 209 |
+
# sizeof(int) (typically 32 bits signed), parsing the argument to
|
| 210 |
+
# readline raises OverflowError. StringIO.read(), OTOH, uses
|
| 211 |
+
# PySize_t, typically a long (64 bits). In a bare readline()
|
| 212 |
+
# case, because the header lines we're trying to read with
|
| 213 |
+
# readline are typically expected to be small, we can correct
|
| 214 |
+
# that failure by simply doing a smaller call to readline and
|
| 215 |
+
# appending; failures in read we let propagate.
|
| 216 |
+
try:
|
| 217 |
+
read = reader(length)
|
| 218 |
+
except OverflowError:
|
| 219 |
+
if not use_readline:
|
| 220 |
+
# Expecting to read more than 64 bits of data. Ouch!
|
| 221 |
+
raise
|
| 222 |
+
# We could loop on calls to smaller readline(), appending them
|
| 223 |
+
# until we actually get a newline. For uses in this module,
|
| 224 |
+
# we expect the actual length to be small, but WSGI applications
|
| 225 |
+
# are allowed to pass in an arbitrary length. (This loop isn't optimal,
|
| 226 |
+
# but even client applications *probably* have short lines.)
|
| 227 |
+
read = b''
|
| 228 |
+
while len(read) < length and not read.endswith(b'\n'):
|
| 229 |
+
read += reader(MAX_REQUEST_LINE)
|
| 230 |
+
|
| 231 |
+
self.position += len(read)
|
| 232 |
+
if len(read) < length:
|
| 233 |
+
if (use_readline and not read.endswith(b"\n")) or not use_readline:
|
| 234 |
+
raise IOError("unexpected end of file while reading request at position %s" % (self.position,))
|
| 235 |
+
|
| 236 |
+
return read
|
| 237 |
+
|
| 238 |
+
def __read_chunk_length(self, rfile):
|
| 239 |
+
# Read and return the next integer chunk length. If no
|
| 240 |
+
# chunk length can be read, raises _InvalidClientInput.
|
| 241 |
+
|
| 242 |
+
# Here's the production for a chunk (actually the whole body):
|
| 243 |
+
# (https://www.rfc-editor.org/rfc/rfc7230#section-4.1)
|
| 244 |
+
|
| 245 |
+
# chunked-body = *chunk
|
| 246 |
+
# last-chunk
|
| 247 |
+
# trailer-part
|
| 248 |
+
# CRLF
|
| 249 |
+
#
|
| 250 |
+
# chunk = chunk-size [ chunk-ext ] CRLF
|
| 251 |
+
# chunk-data CRLF
|
| 252 |
+
# chunk-size = 1*HEXDIG
|
| 253 |
+
# last-chunk = 1*("0") [ chunk-ext ] CRLF
|
| 254 |
+
# trailer-part = *( header-field CRLF )
|
| 255 |
+
# chunk-data = 1*OCTET ; a sequence of chunk-size octets
|
| 256 |
+
#
|
| 257 |
+
# chunk-ext = *( ";" chunk-ext-name [ "=" chunk-ext-val ] )
|
| 258 |
+
#
|
| 259 |
+
# chunk-ext-name = token
|
| 260 |
+
# chunk-ext-val = token / quoted-string
|
| 261 |
+
|
| 262 |
+
# To cope with malicious or broken clients that fail to send
|
| 263 |
+
# valid chunk lines, the strategy is to read character by
|
| 264 |
+
# character until we either reach a ; or newline. If at any
|
| 265 |
+
# time we read a non-HEX digit, we bail. If we hit a ;,
|
| 266 |
+
# indicating an chunk-extension, we'll read up to the next
|
| 267 |
+
# MAX_REQUEST_LINE characters ("A server ought to limit the
|
| 268 |
+
# total length of chunk extensions received") looking for the
|
| 269 |
+
# CRLF, and if we don't find it, we bail. If we read more than
|
| 270 |
+
# 16 hex characters, (the number needed to represent a 64-bit
|
| 271 |
+
# chunk size), we bail (this protects us from a client that
|
| 272 |
+
# sends an infinite stream of `F`, for example).
|
| 273 |
+
|
| 274 |
+
buf = BytesIO()
|
| 275 |
+
while 1:
|
| 276 |
+
char = rfile.read(1)
|
| 277 |
+
if not char:
|
| 278 |
+
self._chunked_input_error = True
|
| 279 |
+
raise _InvalidClientInput("EOF before chunk end reached")
|
| 280 |
+
|
| 281 |
+
if char in (
|
| 282 |
+
b'\r', # Beginning EOL
|
| 283 |
+
b';', # Beginning extension
|
| 284 |
+
):
|
| 285 |
+
break
|
| 286 |
+
|
| 287 |
+
if char not in _HEX: # Invalid data.
|
| 288 |
+
self._chunked_input_error = True
|
| 289 |
+
raise _InvalidClientInput("Non-hex data", char)
|
| 290 |
+
|
| 291 |
+
buf.write(char)
|
| 292 |
+
|
| 293 |
+
if buf.tell() > 16: # Too many hex bytes
|
| 294 |
+
self._chunked_input_error = True
|
| 295 |
+
raise _InvalidClientInput("Chunk-size too large.")
|
| 296 |
+
|
| 297 |
+
if char == b';':
|
| 298 |
+
i = 0
|
| 299 |
+
while i < MAX_REQUEST_LINE:
|
| 300 |
+
char = rfile.read(1)
|
| 301 |
+
if char == b'\r':
|
| 302 |
+
break
|
| 303 |
+
i += 1
|
| 304 |
+
else:
|
| 305 |
+
# we read more than MAX_REQUEST_LINE without
|
| 306 |
+
# hitting CR
|
| 307 |
+
self._chunked_input_error = True
|
| 308 |
+
raise _InvalidClientInput("Too large chunk extension")
|
| 309 |
+
|
| 310 |
+
if char == b'\r':
|
| 311 |
+
# We either got here from the main loop or from the
|
| 312 |
+
# end of an extension
|
| 313 |
+
self.__read_chunk_size_crlf(rfile, newline_only=True)
|
| 314 |
+
result = int(buf.getvalue(), 16)
|
| 315 |
+
if result == 0:
|
| 316 |
+
# The only time a chunk size of zero is allowed is the final
|
| 317 |
+
# chunk. It is either followed by another \r\n, or some trailers
|
| 318 |
+
# which are then followed by \r\n.
|
| 319 |
+
while self.__read_chunk_trailer(rfile):
|
| 320 |
+
pass
|
| 321 |
+
return result
|
| 322 |
+
|
| 323 |
+
# Trailers have the following production (they are a header-field followed by CRLF)
|
| 324 |
+
# See above for the definition of "token".
|
| 325 |
+
#
|
| 326 |
+
# header-field = field-name ":" OWS field-value OWS
|
| 327 |
+
# field-name = token
|
| 328 |
+
# field-value = *( field-content / obs-fold )
|
| 329 |
+
# field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
|
| 330 |
+
# field-vchar = VCHAR / obs-text
|
| 331 |
+
# obs-fold = CRLF 1*( SP / HTAB )
|
| 332 |
+
# ; obsolete line folding
|
| 333 |
+
# ; see Section 3.2.4
|
| 334 |
+
|
| 335 |
+
|
| 336 |
+
def __read_chunk_trailer(self, rfile, ):
|
| 337 |
+
# With rfile positioned just after a \r\n, read a trailer line.
|
| 338 |
+
# Return a true value if a non-empty trailer was read, and
|
| 339 |
+
# return false if an empty trailer was read (meaning the trailers are
|
| 340 |
+
# done).
|
| 341 |
+
# If a single line exceeds the MAX_REQUEST_LINE, raise an exception.
|
| 342 |
+
# If the field-name portion contains invalid characters, raise an exception.
|
| 343 |
+
|
| 344 |
+
i = 0
|
| 345 |
+
empty = True
|
| 346 |
+
seen_field_name = False
|
| 347 |
+
while i < MAX_REQUEST_LINE:
|
| 348 |
+
char = rfile.read(1)
|
| 349 |
+
if char == b'\r':
|
| 350 |
+
# Either read the next \n or raise an error.
|
| 351 |
+
self.__read_chunk_size_crlf(rfile, newline_only=True)
|
| 352 |
+
break
|
| 353 |
+
# Not a \r, so we are NOT an empty chunk.
|
| 354 |
+
empty = False
|
| 355 |
+
if char == b':' and i > 0:
|
| 356 |
+
# We're ending the field-name part; stop validating characters.
|
| 357 |
+
# Unless : was the first character...
|
| 358 |
+
seen_field_name = True
|
| 359 |
+
if not seen_field_name and char not in _ALLOWED_TOKEN_CHARS:
|
| 360 |
+
raise _InvalidClientInput('Invalid token character: %r' % (char,))
|
| 361 |
+
i += 1
|
| 362 |
+
else:
|
| 363 |
+
# We read too much
|
| 364 |
+
self._chunked_input_error = True
|
| 365 |
+
raise _InvalidClientInput("Too large chunk trailer")
|
| 366 |
+
return not empty
|
| 367 |
+
|
| 368 |
+
def __read_chunk_size_crlf(self, rfile, newline_only=False):
|
| 369 |
+
# Also for safety, correctly verify that we get \r\n when expected.
|
| 370 |
+
if not newline_only:
|
| 371 |
+
char = rfile.read(1)
|
| 372 |
+
if char != b'\r':
|
| 373 |
+
self._chunked_input_error = True
|
| 374 |
+
raise _InvalidClientInput("Line didn't end in CRLF: %r" % (char,))
|
| 375 |
+
char = rfile.read(1)
|
| 376 |
+
if char != b'\n':
|
| 377 |
+
self._chunked_input_error = True
|
| 378 |
+
raise _InvalidClientInput("Line didn't end in LF: %r" % (char,))
|
| 379 |
+
|
| 380 |
+
def _chunked_read(self, length=None, use_readline=False):
|
| 381 |
+
# pylint:disable=too-many-branches
|
| 382 |
+
rfile = self.rfile
|
| 383 |
+
self._send_100_continue()
|
| 384 |
+
|
| 385 |
+
if length == 0:
|
| 386 |
+
return b""
|
| 387 |
+
|
| 388 |
+
if use_readline:
|
| 389 |
+
reader = self.rfile.readline
|
| 390 |
+
else:
|
| 391 |
+
reader = self.rfile.read
|
| 392 |
+
|
| 393 |
+
response = []
|
| 394 |
+
while self.chunk_length != 0:
|
| 395 |
+
maxreadlen = self.chunk_length - self.position
|
| 396 |
+
if length is not None and length < maxreadlen:
|
| 397 |
+
maxreadlen = length
|
| 398 |
+
|
| 399 |
+
if maxreadlen > 0:
|
| 400 |
+
data = reader(maxreadlen)
|
| 401 |
+
if not data:
|
| 402 |
+
self.chunk_length = 0
|
| 403 |
+
self._chunked_input_error = True
|
| 404 |
+
raise IOError("unexpected end of file while parsing chunked data")
|
| 405 |
+
|
| 406 |
+
datalen = len(data)
|
| 407 |
+
response.append(data)
|
| 408 |
+
|
| 409 |
+
self.position += datalen
|
| 410 |
+
if self.chunk_length == self.position:
|
| 411 |
+
self.__read_chunk_size_crlf(rfile)
|
| 412 |
+
|
| 413 |
+
if length is not None:
|
| 414 |
+
length -= datalen
|
| 415 |
+
if length == 0:
|
| 416 |
+
break
|
| 417 |
+
if use_readline and data[-1] == b"\n"[0]:
|
| 418 |
+
break
|
| 419 |
+
else:
|
| 420 |
+
# We're at the beginning of a chunk, so we need to
|
| 421 |
+
# determine the next size to read
|
| 422 |
+
self.chunk_length = self.__read_chunk_length(rfile)
|
| 423 |
+
self.position = 0
|
| 424 |
+
# If chunk_length was 0, we already read any trailers and
|
| 425 |
+
# validated that we have ended with \r\n\r\n.
|
| 426 |
+
|
| 427 |
+
return b''.join(response)
|
| 428 |
+
|
| 429 |
+
def read(self, length=None):
|
| 430 |
+
if length is not None and length < 0:
|
| 431 |
+
length = None
|
| 432 |
+
if self.chunked_input:
|
| 433 |
+
return self._chunked_read(length)
|
| 434 |
+
return self._do_read(length)
|
| 435 |
+
|
| 436 |
+
def readline(self, size=None):
|
| 437 |
+
if size is not None and size < 0:
|
| 438 |
+
size = None
|
| 439 |
+
if self.chunked_input:
|
| 440 |
+
return self._chunked_read(size, True)
|
| 441 |
+
return self._do_read(size, use_readline=True)
|
| 442 |
+
|
| 443 |
+
def readlines(self, hint=None):
|
| 444 |
+
# pylint:disable=unused-argument
|
| 445 |
+
return list(self)
|
| 446 |
+
|
| 447 |
+
def __iter__(self):
|
| 448 |
+
return self
|
| 449 |
+
|
| 450 |
+
def next(self):
|
| 451 |
+
line = self.readline()
|
| 452 |
+
if not line:
|
| 453 |
+
raise StopIteration
|
| 454 |
+
return line
|
| 455 |
+
__next__ = next
|
| 456 |
+
|
| 457 |
+
|
| 458 |
+
try:
|
| 459 |
+
import mimetools
|
| 460 |
+
headers_factory = mimetools.Message
|
| 461 |
+
except ImportError:
|
| 462 |
+
# adapt Python 3 HTTP headers to old API
|
| 463 |
+
from http import client # pylint:disable=import-error
|
| 464 |
+
|
| 465 |
+
class OldMessage(client.HTTPMessage):
|
| 466 |
+
def __init__(self, **kwargs):
|
| 467 |
+
super(client.HTTPMessage, self).__init__(**kwargs) # pylint:disable=bad-super-call
|
| 468 |
+
self.status = ''
|
| 469 |
+
|
| 470 |
+
def getheader(self, name, default=None):
|
| 471 |
+
return self.get(name, default)
|
| 472 |
+
|
| 473 |
+
@property
|
| 474 |
+
def headers(self):
|
| 475 |
+
for key, value in self._headers:
|
| 476 |
+
yield '%s: %s\r\n' % (key, value)
|
| 477 |
+
|
| 478 |
+
@property
|
| 479 |
+
def typeheader(self):
|
| 480 |
+
return self.get('content-type')
|
| 481 |
+
|
| 482 |
+
def headers_factory(fp, *args): # pylint:disable=unused-argument
|
| 483 |
+
try:
|
| 484 |
+
ret = client.parse_headers(fp, _class=OldMessage)
|
| 485 |
+
except client.LineTooLong:
|
| 486 |
+
ret = OldMessage()
|
| 487 |
+
ret.status = 'Line too long'
|
| 488 |
+
return ret
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
class WSGIHandler(object):
|
| 492 |
+
"""
|
| 493 |
+
Handles HTTP requests from a socket, creates the WSGI environment, and
|
| 494 |
+
interacts with the WSGI application.
|
| 495 |
+
|
| 496 |
+
This is the default value of :attr:`WSGIServer.handler_class`.
|
| 497 |
+
This class may be subclassed carefully, and that class set on a
|
| 498 |
+
:class:`WSGIServer` instance through a keyword argument at
|
| 499 |
+
construction time.
|
| 500 |
+
|
| 501 |
+
Instances are constructed with the same arguments as passed to the
|
| 502 |
+
server's :meth:`WSGIServer.handle` method followed by the server
|
| 503 |
+
itself. The application and environment are obtained from the server.
|
| 504 |
+
|
| 505 |
+
"""
|
| 506 |
+
# pylint:disable=too-many-instance-attributes
|
| 507 |
+
|
| 508 |
+
protocol_version = 'HTTP/1.1'
|
| 509 |
+
|
| 510 |
+
def MessageClass(self, *args):
|
| 511 |
+
return headers_factory(*args)
|
| 512 |
+
|
| 513 |
+
# Attributes reset at various times for each request; not public
|
| 514 |
+
# documented. Class attributes to keep the constructor fast
|
| 515 |
+
# (but not make lint tools complain)
|
| 516 |
+
|
| 517 |
+
status = None # byte string: b'200 OK'
|
| 518 |
+
_orig_status = None # native string: '200 OK'
|
| 519 |
+
response_headers = None # list of tuples (b'name', b'value')
|
| 520 |
+
code = None # Integer parsed from status
|
| 521 |
+
provided_date = None
|
| 522 |
+
provided_content_length = None
|
| 523 |
+
close_connection = False
|
| 524 |
+
time_start = 0 # time.time() when begin handling request
|
| 525 |
+
time_finish = 0 # time.time() when done handling request
|
| 526 |
+
headers_sent = False # Have we already sent headers?
|
| 527 |
+
response_use_chunked = False # Write with transfer-encoding chunked
|
| 528 |
+
# Was the connection upgraded? We shouldn't try to chunk writes in that
|
| 529 |
+
# case.
|
| 530 |
+
connection_upgraded = False
|
| 531 |
+
environ = None # Dict from self.get_environ
|
| 532 |
+
application = None # application callable from self.server.application
|
| 533 |
+
requestline = None # native str 'GET / HTTP/1.1'
|
| 534 |
+
response_length = 0 # How much data we sent
|
| 535 |
+
result = None # The return value of the WSGI application
|
| 536 |
+
wsgi_input = None # Instance of Input()
|
| 537 |
+
content_length = 0 # From application-provided headers Incoming
|
| 538 |
+
# request headers, instance of MessageClass (gunicorn uses hasattr
|
| 539 |
+
# on this so the default value needs to be compatible with the
|
| 540 |
+
# API)
|
| 541 |
+
headers = headers_factory(BytesIO())
|
| 542 |
+
request_version = None # str: 'HTTP 1.1'
|
| 543 |
+
command = None # str: 'GET'
|
| 544 |
+
path = None # str: '/'
|
| 545 |
+
|
| 546 |
+
def __init__(self, sock, address, server, rfile=None):
|
| 547 |
+
# Deprecation: The rfile kwarg was introduced in 1.0a1 as part
|
| 548 |
+
# of a refactoring. It was never documented or used. It is
|
| 549 |
+
# considered DEPRECATED and may be removed in the future. Its
|
| 550 |
+
# use is not supported.
|
| 551 |
+
|
| 552 |
+
self.socket = sock
|
| 553 |
+
self.client_address = address
|
| 554 |
+
self.server = server
|
| 555 |
+
if rfile is None:
|
| 556 |
+
self.rfile = sock.makefile('rb', -1)
|
| 557 |
+
else:
|
| 558 |
+
self.rfile = rfile
|
| 559 |
+
|
| 560 |
+
def handle(self):
|
| 561 |
+
"""
|
| 562 |
+
The main request handling method, called by the server.
|
| 563 |
+
|
| 564 |
+
This method runs a request handling loop, calling
|
| 565 |
+
:meth:`handle_one_request` until all requests on the
|
| 566 |
+
connection have been handled (that is, it implements
|
| 567 |
+
keep-alive).
|
| 568 |
+
"""
|
| 569 |
+
try:
|
| 570 |
+
while self.socket is not None:
|
| 571 |
+
self.time_start = time.time()
|
| 572 |
+
self.time_finish = 0
|
| 573 |
+
|
| 574 |
+
result = self.handle_one_request()
|
| 575 |
+
if result is None:
|
| 576 |
+
break
|
| 577 |
+
if result is True:
|
| 578 |
+
continue
|
| 579 |
+
|
| 580 |
+
self.status, response_body = result # pylint:disable=unpacking-non-sequence
|
| 581 |
+
self.socket.sendall(response_body)
|
| 582 |
+
if self.time_finish == 0:
|
| 583 |
+
self.time_finish = time.time()
|
| 584 |
+
self.log_request()
|
| 585 |
+
break
|
| 586 |
+
finally:
|
| 587 |
+
if self.socket is not None:
|
| 588 |
+
_sock = getattr(self.socket, '_sock', None) # Python 3
|
| 589 |
+
try:
|
| 590 |
+
# read out request data to prevent error: [Errno 104] Connection reset by peer
|
| 591 |
+
if _sock:
|
| 592 |
+
try:
|
| 593 |
+
# socket.recv would hang
|
| 594 |
+
_sock.recv(16384)
|
| 595 |
+
finally:
|
| 596 |
+
_sock.close()
|
| 597 |
+
self.socket.close()
|
| 598 |
+
except socket.error:
|
| 599 |
+
pass
|
| 600 |
+
self.__dict__.pop('socket', None)
|
| 601 |
+
self.__dict__.pop('rfile', None)
|
| 602 |
+
self.__dict__.pop('wsgi_input', None)
|
| 603 |
+
|
| 604 |
+
def _check_http_version(self):
|
| 605 |
+
version_str = self.request_version
|
| 606 |
+
if not version_str.startswith("HTTP/"):
|
| 607 |
+
return False
|
| 608 |
+
version = tuple(int(x) for x in version_str[5:].split(".")) # "HTTP/"
|
| 609 |
+
if version[1] < 0 or version < (0, 9) or version >= (2, 0):
|
| 610 |
+
return False
|
| 611 |
+
return True
|
| 612 |
+
|
| 613 |
+
def read_request(self, raw_requestline):
|
| 614 |
+
"""
|
| 615 |
+
Parse the incoming request.
|
| 616 |
+
|
| 617 |
+
Parses various headers into ``self.headers`` using
|
| 618 |
+
:attr:`MessageClass`. Other attributes that are set upon a successful
|
| 619 |
+
return of this method include ``self.content_length`` and ``self.close_connection``.
|
| 620 |
+
|
| 621 |
+
:param str raw_requestline: A native :class:`str` representing
|
| 622 |
+
the request line. A processed version of this will be stored
|
| 623 |
+
into ``self.requestline``.
|
| 624 |
+
|
| 625 |
+
:raises ValueError: If the request is invalid. This error will
|
| 626 |
+
not be logged as a traceback (because it's a client issue, not a server problem).
|
| 627 |
+
:return: A boolean value indicating whether the request was successfully parsed.
|
| 628 |
+
This method should either return a true value or have raised a ValueError
|
| 629 |
+
with details about the parsing error.
|
| 630 |
+
|
| 631 |
+
.. versionchanged:: 1.1b6
|
| 632 |
+
Raise the previously documented :exc:`ValueError` in more cases instead of returning a
|
| 633 |
+
false value; this allows subclasses more opportunity to customize behaviour.
|
| 634 |
+
"""
|
| 635 |
+
# pylint:disable=too-many-branches
|
| 636 |
+
self.requestline = raw_requestline.rstrip()
|
| 637 |
+
words = self.requestline.split()
|
| 638 |
+
if len(words) == 3:
|
| 639 |
+
self.command, self.path, self.request_version = words
|
| 640 |
+
if not self._check_http_version():
|
| 641 |
+
raise _InvalidClientRequest('Invalid http version: %r' % (raw_requestline,))
|
| 642 |
+
elif len(words) == 2:
|
| 643 |
+
self.command, self.path = words
|
| 644 |
+
if self.command != "GET":
|
| 645 |
+
raise _InvalidClientRequest('Expected GET method; Got command=%r; path=%r; raw=%r' % (
|
| 646 |
+
self.command, self.path, raw_requestline,))
|
| 647 |
+
self.request_version = "HTTP/0.9"
|
| 648 |
+
# QQQ I'm pretty sure we can drop support for HTTP/0.9
|
| 649 |
+
else:
|
| 650 |
+
raise _InvalidClientRequest('Invalid HTTP method: %r' % (raw_requestline,))
|
| 651 |
+
|
| 652 |
+
self.headers = self.MessageClass(self.rfile, 0)
|
| 653 |
+
|
| 654 |
+
if self.headers.status:
|
| 655 |
+
raise _InvalidClientRequest('Invalid headers status: %r' % (self.headers.status,))
|
| 656 |
+
|
| 657 |
+
if self.headers.get("transfer-encoding", "").lower() == "chunked":
|
| 658 |
+
try:
|
| 659 |
+
del self.headers["content-length"]
|
| 660 |
+
except KeyError:
|
| 661 |
+
pass
|
| 662 |
+
|
| 663 |
+
content_length = self.headers.get("content-length")
|
| 664 |
+
if content_length is not None:
|
| 665 |
+
content_length = int(content_length)
|
| 666 |
+
if content_length < 0:
|
| 667 |
+
raise _InvalidClientRequest('Invalid Content-Length: %r' % (content_length,))
|
| 668 |
+
|
| 669 |
+
if content_length and self.command in ('HEAD', ):
|
| 670 |
+
raise _InvalidClientRequest('Unexpected Content-Length')
|
| 671 |
+
|
| 672 |
+
self.content_length = content_length
|
| 673 |
+
|
| 674 |
+
if self.request_version == "HTTP/1.1":
|
| 675 |
+
conntype = self.headers.get("Connection", "").lower()
|
| 676 |
+
self.close_connection = (conntype == 'close') # pylint:disable=superfluous-parens
|
| 677 |
+
elif self.request_version == 'HTTP/1.0':
|
| 678 |
+
conntype = self.headers.get("Connection", "close").lower()
|
| 679 |
+
self.close_connection = (conntype != 'keep-alive') # pylint:disable=superfluous-parens
|
| 680 |
+
else:
|
| 681 |
+
# XXX: HTTP 0.9. We should drop support
|
| 682 |
+
self.close_connection = True
|
| 683 |
+
|
| 684 |
+
return True
|
| 685 |
+
|
| 686 |
+
_print_unexpected_exc = staticmethod(traceback.print_exc)
|
| 687 |
+
|
| 688 |
+
def log_error(self, msg, *args):
|
| 689 |
+
if not args:
|
| 690 |
+
# Already fully formatted, no need to do it again; msg
|
| 691 |
+
# might contain % chars that would lead to a formatting
|
| 692 |
+
# error.
|
| 693 |
+
message = msg
|
| 694 |
+
else:
|
| 695 |
+
try:
|
| 696 |
+
message = msg % args
|
| 697 |
+
except Exception: # pylint:disable=broad-except
|
| 698 |
+
self._print_unexpected_exc()
|
| 699 |
+
message = '%r %r' % (msg, args)
|
| 700 |
+
try:
|
| 701 |
+
message = '%s: %s' % (self.socket, message)
|
| 702 |
+
except Exception: # pylint:disable=broad-except
|
| 703 |
+
pass
|
| 704 |
+
|
| 705 |
+
try:
|
| 706 |
+
self.server.error_log.write(message + '\n')
|
| 707 |
+
except Exception: # pylint:disable=broad-except
|
| 708 |
+
self._print_unexpected_exc()
|
| 709 |
+
|
| 710 |
+
def read_requestline(self):
|
| 711 |
+
"""
|
| 712 |
+
Read and return the HTTP request line.
|
| 713 |
+
|
| 714 |
+
Under both Python 2 and 3, this should return the native
|
| 715 |
+
``str`` type; under Python 3, this probably means the bytes read
|
| 716 |
+
from the network need to be decoded (using the ISO-8859-1 charset, aka
|
| 717 |
+
latin-1).
|
| 718 |
+
"""
|
| 719 |
+
line = self.rfile.readline(MAX_REQUEST_LINE)
|
| 720 |
+
line = line.decode('latin-1')
|
| 721 |
+
return line
|
| 722 |
+
|
| 723 |
+
def handle_one_request(self):
|
| 724 |
+
"""
|
| 725 |
+
Handles one HTTP request using ``self.socket`` and ``self.rfile``.
|
| 726 |
+
|
| 727 |
+
Each invocation of this method will do several things, including (but not limited to):
|
| 728 |
+
|
| 729 |
+
- Read the request line using :meth:`read_requestline`;
|
| 730 |
+
- Read the rest of the request, including headers, with :meth:`read_request`;
|
| 731 |
+
- Construct a new WSGI environment in ``self.environ`` using :meth:`get_environ`;
|
| 732 |
+
- Store the application in ``self.application``, retrieving it from the server;
|
| 733 |
+
- Handle the remainder of the request, including invoking the application,
|
| 734 |
+
with :meth:`handle_one_response`
|
| 735 |
+
|
| 736 |
+
There are several possible return values to indicate the state
|
| 737 |
+
of the client connection:
|
| 738 |
+
|
| 739 |
+
- ``None``
|
| 740 |
+
The client connection is already closed or should
|
| 741 |
+
be closed because the WSGI application or client set the
|
| 742 |
+
``Connection: close`` header. The request handling
|
| 743 |
+
loop should terminate and perform cleanup steps.
|
| 744 |
+
- (status, body)
|
| 745 |
+
An HTTP status and body tuple. The request was in error,
|
| 746 |
+
as detailed by the status and body. The request handling
|
| 747 |
+
loop should terminate, close the connection, and perform
|
| 748 |
+
cleanup steps. Note that the ``body`` is the complete contents
|
| 749 |
+
to send to the client, including all headers and the initial
|
| 750 |
+
status line.
|
| 751 |
+
- ``True``
|
| 752 |
+
The literal ``True`` value. The request was successfully handled
|
| 753 |
+
and the response sent to the client by :meth:`handle_one_response`.
|
| 754 |
+
The connection remains open to process more requests and the connection
|
| 755 |
+
handling loop should call this method again. This is the typical return
|
| 756 |
+
value.
|
| 757 |
+
|
| 758 |
+
.. seealso:: :meth:`handle`
|
| 759 |
+
|
| 760 |
+
.. versionchanged:: 1.1b6
|
| 761 |
+
Funnel exceptions having to do with invalid HTTP requests through
|
| 762 |
+
:meth:`_handle_client_error` to allow subclasses to customize. Note that
|
| 763 |
+
this is experimental and may change in the future.
|
| 764 |
+
"""
|
| 765 |
+
# pylint:disable=too-many-return-statements
|
| 766 |
+
if self.rfile.closed:
|
| 767 |
+
return
|
| 768 |
+
|
| 769 |
+
try:
|
| 770 |
+
self.requestline = self.read_requestline()
|
| 771 |
+
# Account for old subclasses that haven't done this
|
| 772 |
+
if isinstance(self.requestline, bytes):
|
| 773 |
+
self.requestline = self.requestline.decode('latin-1')
|
| 774 |
+
except socket.error:
|
| 775 |
+
# "Connection reset by peer" or other socket errors aren't interesting here
|
| 776 |
+
return
|
| 777 |
+
|
| 778 |
+
if not self.requestline:
|
| 779 |
+
return
|
| 780 |
+
|
| 781 |
+
self.response_length = 0
|
| 782 |
+
|
| 783 |
+
if len(self.requestline) >= MAX_REQUEST_LINE:
|
| 784 |
+
return ('414', _REQUEST_TOO_LONG_RESPONSE)
|
| 785 |
+
|
| 786 |
+
try:
|
| 787 |
+
# for compatibility with older versions of pywsgi, we pass self.requestline as an argument there
|
| 788 |
+
# NOTE: read_request is supposed to raise ValueError on invalid input; allow old
|
| 789 |
+
# subclasses that return a False value instead.
|
| 790 |
+
# NOTE: This can mutate the value of self.headers, so self.get_environ() must not be
|
| 791 |
+
# called until AFTER this call is done.
|
| 792 |
+
if not self.read_request(self.requestline):
|
| 793 |
+
return ('400', _BAD_REQUEST_RESPONSE)
|
| 794 |
+
except Exception as ex: # pylint:disable=broad-except
|
| 795 |
+
# Notice we don't use self.handle_error because it reports
|
| 796 |
+
# a 500 error to the client, and this is almost certainly
|
| 797 |
+
# a client error.
|
| 798 |
+
# Provide a hook for subclasses.
|
| 799 |
+
return self._handle_client_error(ex)
|
| 800 |
+
|
| 801 |
+
self.environ = self.get_environ()
|
| 802 |
+
self.application = self.server.application
|
| 803 |
+
|
| 804 |
+
self.handle_one_response()
|
| 805 |
+
|
| 806 |
+
if self.close_connection:
|
| 807 |
+
return
|
| 808 |
+
|
| 809 |
+
if self.rfile.closed:
|
| 810 |
+
return
|
| 811 |
+
|
| 812 |
+
return True # read more requests
|
| 813 |
+
|
| 814 |
+
def _connection_upgrade_requested(self):
|
| 815 |
+
if self.headers.get('Connection', '').lower() == 'upgrade':
|
| 816 |
+
return True
|
| 817 |
+
if self.headers.get('Upgrade', '').lower() == 'websocket':
|
| 818 |
+
return True
|
| 819 |
+
return False
|
| 820 |
+
|
| 821 |
+
def finalize_headers(self):
|
| 822 |
+
if self.provided_date is None:
|
| 823 |
+
self.response_headers.append((b'Date', format_date_time(time.time())))
|
| 824 |
+
|
| 825 |
+
self.connection_upgraded = self.code == 101
|
| 826 |
+
|
| 827 |
+
if self.code not in (304, 204):
|
| 828 |
+
# the reply will include message-body; make sure we have either Content-Length or chunked
|
| 829 |
+
if self.provided_content_length is None:
|
| 830 |
+
if hasattr(self.result, '__len__'):
|
| 831 |
+
total_len = sum(len(chunk) for chunk in self.result)
|
| 832 |
+
total_len_str = str(total_len)
|
| 833 |
+
total_len_str = total_len_str.encode("latin-1")
|
| 834 |
+
self.response_headers.append((b'Content-Length', total_len_str))
|
| 835 |
+
else:
|
| 836 |
+
self.response_use_chunked = (
|
| 837 |
+
not self.connection_upgraded
|
| 838 |
+
and self.request_version != 'HTTP/1.0'
|
| 839 |
+
)
|
| 840 |
+
if self.response_use_chunked:
|
| 841 |
+
self.response_headers.append((b'Transfer-Encoding', b'chunked'))
|
| 842 |
+
|
| 843 |
+
def _sendall(self, data):
|
| 844 |
+
try:
|
| 845 |
+
self.socket.sendall(data)
|
| 846 |
+
except socket.error as ex:
|
| 847 |
+
self.status = 'socket error: %s' % ex
|
| 848 |
+
if self.code > 0:
|
| 849 |
+
self.code = -self.code
|
| 850 |
+
raise
|
| 851 |
+
self.response_length += len(data)
|
| 852 |
+
|
| 853 |
+
def _write(self, data,
|
| 854 |
+
_bytearray=bytearray):
|
| 855 |
+
if not data:
|
| 856 |
+
# The application/middleware are allowed to yield
|
| 857 |
+
# empty bytestrings.
|
| 858 |
+
return
|
| 859 |
+
|
| 860 |
+
if self.response_use_chunked:
|
| 861 |
+
# Write the chunked encoding header
|
| 862 |
+
header_str = b'%x\r\n' % len(data)
|
| 863 |
+
towrite = _bytearray(header_str)
|
| 864 |
+
|
| 865 |
+
# data
|
| 866 |
+
towrite += data
|
| 867 |
+
# trailer
|
| 868 |
+
towrite += b'\r\n'
|
| 869 |
+
self._sendall(towrite)
|
| 870 |
+
else:
|
| 871 |
+
self._sendall(data)
|
| 872 |
+
|
| 873 |
+
ApplicationError = AssertionError
|
| 874 |
+
|
| 875 |
+
def write(self, data):
|
| 876 |
+
# The write() callable we return from start_response.
|
| 877 |
+
# https://www.python.org/dev/peps/pep-3333/#the-write-callable
|
| 878 |
+
# Supposed to do pretty much the same thing as yielding values
|
| 879 |
+
# from the application's return.
|
| 880 |
+
if self.code in (304, 204) and data:
|
| 881 |
+
raise self.ApplicationError('The %s response must have no body' % self.code)
|
| 882 |
+
|
| 883 |
+
if self.headers_sent:
|
| 884 |
+
self._write(data)
|
| 885 |
+
else:
|
| 886 |
+
if not self.status:
|
| 887 |
+
raise self.ApplicationError("The application did not call start_response()")
|
| 888 |
+
self._write_with_headers(data)
|
| 889 |
+
|
| 890 |
+
def _write_with_headers(self, data):
|
| 891 |
+
self.headers_sent = True
|
| 892 |
+
self.finalize_headers()
|
| 893 |
+
|
| 894 |
+
# self.response_headers and self.status are already in latin-1, as encoded by self.start_response
|
| 895 |
+
towrite = bytearray(b'HTTP/1.1 ')
|
| 896 |
+
towrite += self.status
|
| 897 |
+
towrite += b'\r\n'
|
| 898 |
+
for header, value in self.response_headers:
|
| 899 |
+
towrite += header
|
| 900 |
+
towrite += b': '
|
| 901 |
+
towrite += value
|
| 902 |
+
towrite += b"\r\n"
|
| 903 |
+
|
| 904 |
+
towrite += b'\r\n'
|
| 905 |
+
self._sendall(towrite)
|
| 906 |
+
# No need to copy the data into towrite; we may make an extra syscall
|
| 907 |
+
# but the copy time could be substantial too, and it reduces the chances
|
| 908 |
+
# of sendall being able to send everything in one go
|
| 909 |
+
self._write(data)
|
| 910 |
+
|
| 911 |
+
def start_response(self, status, headers, exc_info=None):
|
| 912 |
+
"""
|
| 913 |
+
.. versionchanged:: 1.2a1
|
| 914 |
+
Avoid HTTP header injection by raising a :exc:`ValueError`
|
| 915 |
+
if *status* or any *header* name or value contains a carriage
|
| 916 |
+
return or newline.
|
| 917 |
+
.. versionchanged:: 1.1b5
|
| 918 |
+
Pro-actively handle checking the encoding of the status line
|
| 919 |
+
and headers during this method. On Python 2, avoid some
|
| 920 |
+
extra encodings.
|
| 921 |
+
"""
|
| 922 |
+
# pylint:disable=too-many-branches,too-many-statements
|
| 923 |
+
if exc_info:
|
| 924 |
+
try:
|
| 925 |
+
if self.headers_sent:
|
| 926 |
+
# Re-raise original exception if headers sent
|
| 927 |
+
reraise(*exc_info)
|
| 928 |
+
finally:
|
| 929 |
+
# Avoid dangling circular ref
|
| 930 |
+
exc_info = None
|
| 931 |
+
|
| 932 |
+
# Pep 3333, "The start_response callable":
|
| 933 |
+
# https://www.python.org/dev/peps/pep-3333/#the-start-response-callable
|
| 934 |
+
# "Servers should check for errors in the headers at the time
|
| 935 |
+
# start_response is called, so that an error can be raised
|
| 936 |
+
# while the application is still running." Here, we check the encoding.
|
| 937 |
+
# This aids debugging: headers especially are generated programmatically
|
| 938 |
+
# and an encoding error in a loop or list comprehension yields an opaque
|
| 939 |
+
# UnicodeError without any clue which header was wrong.
|
| 940 |
+
# Note that this results in copying the header list at this point, not modifying it,
|
| 941 |
+
# although we are allowed to do so if needed. This slightly increases memory usage.
|
| 942 |
+
# We also check for HTTP Response Splitting vulnerabilities
|
| 943 |
+
response_headers = []
|
| 944 |
+
header = None
|
| 945 |
+
value = None
|
| 946 |
+
try:
|
| 947 |
+
for header, value in headers:
|
| 948 |
+
if not isinstance(header, str):
|
| 949 |
+
raise UnicodeError("The header must be a native string", header, value)
|
| 950 |
+
if not isinstance(value, str):
|
| 951 |
+
raise UnicodeError("The value must be a native string", header, value)
|
| 952 |
+
if '\r' in header or '\n' in header:
|
| 953 |
+
raise ValueError('carriage return or newline in header name', header)
|
| 954 |
+
if '\r' in value or '\n' in value:
|
| 955 |
+
raise ValueError('carriage return or newline in header value', value)
|
| 956 |
+
# Either we're on Python 2, in which case bytes is correct, or
|
| 957 |
+
# we're on Python 3 and the user screwed up (because it should be a native
|
| 958 |
+
# string). In either case, make sure that this is latin-1 compatible. Under
|
| 959 |
+
# Python 2, bytes.encode() will take a round-trip through the system encoding,
|
| 960 |
+
# which may be ascii, which is not really what we want. However, the latin-1 encoding
|
| 961 |
+
# can encode everything except control characters and the block from 0x7F to 0x9F, so
|
| 962 |
+
# explicitly round-tripping bytes through the encoding is unlikely to be of much
|
| 963 |
+
# benefit, so we go for speed (the WSGI spec specifically calls out allowing the range
|
| 964 |
+
# from 0x00 to 0xFF, although the HTTP spec forbids the control characters).
|
| 965 |
+
# Note: Some Python 2 implementations, like Jython, may allow non-octet (above 255) values
|
| 966 |
+
# in their str implementation; this is mentioned in the WSGI spec, but we don't
|
| 967 |
+
# run on any platform like that so we can assume that a str value is pure bytes.
|
| 968 |
+
response_headers.append((header.encode("latin-1"),
|
| 969 |
+
value.encode("latin-1")))
|
| 970 |
+
except UnicodeEncodeError:
|
| 971 |
+
# If we get here, we're guaranteed to have a header and value
|
| 972 |
+
raise UnicodeError("Non-latin1 header", repr(header), repr(value))
|
| 973 |
+
|
| 974 |
+
# Same as above
|
| 975 |
+
if not isinstance(status, str):
|
| 976 |
+
raise UnicodeError("The status string must be a native string")
|
| 977 |
+
if '\r' in status or '\n' in status:
|
| 978 |
+
raise ValueError("carriage return or newline in status", status)
|
| 979 |
+
# don't assign to anything until the validation is complete, including parsing the
|
| 980 |
+
# code
|
| 981 |
+
code = int(status.split(' ', 1)[0])
|
| 982 |
+
|
| 983 |
+
self.status = status.encode("latin-1")
|
| 984 |
+
self._orig_status = status # Preserve the native string for logging
|
| 985 |
+
self.response_headers = response_headers
|
| 986 |
+
self.code = code
|
| 987 |
+
|
| 988 |
+
provided_connection = None # Did the wsgi app give us a Connection header?
|
| 989 |
+
self.provided_date = None
|
| 990 |
+
self.provided_content_length = None
|
| 991 |
+
|
| 992 |
+
for header, value in headers:
|
| 993 |
+
header = header.lower()
|
| 994 |
+
if header == 'connection':
|
| 995 |
+
provided_connection = value
|
| 996 |
+
elif header == 'date':
|
| 997 |
+
self.provided_date = value
|
| 998 |
+
elif header == 'content-length':
|
| 999 |
+
self.provided_content_length = value
|
| 1000 |
+
|
| 1001 |
+
if self.request_version == 'HTTP/1.0' and provided_connection is None:
|
| 1002 |
+
conntype = b'close' if self.close_connection else b'keep-alive'
|
| 1003 |
+
response_headers.append((b'Connection', conntype))
|
| 1004 |
+
elif provided_connection == 'close':
|
| 1005 |
+
self.close_connection = True
|
| 1006 |
+
|
| 1007 |
+
if self.code in (304, 204):
|
| 1008 |
+
if self.provided_content_length is not None and self.provided_content_length != '0':
|
| 1009 |
+
msg = 'Invalid Content-Length for %s response: %r (must be absent or zero)' % (self.code, self.provided_content_length)
|
| 1010 |
+
msg = msg.encode('latin-1')
|
| 1011 |
+
raise self.ApplicationError(msg)
|
| 1012 |
+
|
| 1013 |
+
return self.write
|
| 1014 |
+
|
| 1015 |
+
def log_request(self):
|
| 1016 |
+
self.server.log.write(self.format_request() + '\n')
|
| 1017 |
+
|
| 1018 |
+
def format_request(self):
|
| 1019 |
+
now = datetime.now().replace(microsecond=0)
|
| 1020 |
+
length = self.response_length or '-'
|
| 1021 |
+
if self.time_finish:
|
| 1022 |
+
delta = '%.6f' % (self.time_finish - self.time_start)
|
| 1023 |
+
else:
|
| 1024 |
+
delta = '-'
|
| 1025 |
+
client_address = self.client_address[0] if isinstance(self.client_address, tuple) else self.client_address
|
| 1026 |
+
return '%s - - [%s] "%s" %s %s %s' % (
|
| 1027 |
+
client_address or '-',
|
| 1028 |
+
now,
|
| 1029 |
+
self.requestline or '',
|
| 1030 |
+
# Use the native string version of the status, saved so we don't have to
|
| 1031 |
+
# decode. But fallback to the encoded 'status' in case of subclasses
|
| 1032 |
+
# (Is that really necessary? At least there's no overhead.)
|
| 1033 |
+
(self._orig_status or self.status or '000').split()[0],
|
| 1034 |
+
length,
|
| 1035 |
+
delta)
|
| 1036 |
+
|
| 1037 |
+
def process_result(self):
|
| 1038 |
+
for data in self.result:
|
| 1039 |
+
if data:
|
| 1040 |
+
self.write(data)
|
| 1041 |
+
if self.status and not self.headers_sent:
|
| 1042 |
+
# In other words, the application returned an empty
|
| 1043 |
+
# result iterable (and did not use the write callable)
|
| 1044 |
+
# Trigger the flush of the headers.
|
| 1045 |
+
self.write(b'')
|
| 1046 |
+
if self.response_use_chunked:
|
| 1047 |
+
self._sendall(b'0\r\n\r\n')
|
| 1048 |
+
|
| 1049 |
+
|
| 1050 |
+
def run_application(self):
|
| 1051 |
+
assert self.result is None
|
| 1052 |
+
try:
|
| 1053 |
+
self.result = self.application(self.environ, self.start_response)
|
| 1054 |
+
self.process_result()
|
| 1055 |
+
finally:
|
| 1056 |
+
close = getattr(self.result, 'close', None)
|
| 1057 |
+
try:
|
| 1058 |
+
if close is not None:
|
| 1059 |
+
close()
|
| 1060 |
+
finally:
|
| 1061 |
+
# Discard the result. If it's a generator this can
|
| 1062 |
+
# free a lot of hidden resources (if we failed to iterate
|
| 1063 |
+
# all the way through it---the frames are automatically
|
| 1064 |
+
# cleaned up when StopIteration is raised); but other cases
|
| 1065 |
+
# could still free up resources sooner than otherwise.
|
| 1066 |
+
close = None
|
| 1067 |
+
self.result = None
|
| 1068 |
+
|
| 1069 |
+
#: These errors are silently ignored by :meth:`handle_one_response` to avoid producing
|
| 1070 |
+
#: excess log entries on normal operating conditions. They indicate
|
| 1071 |
+
#: a remote client has disconnected and there is little or nothing
|
| 1072 |
+
#: this process can be expected to do about it. You may change this
|
| 1073 |
+
#: value in a subclass.
|
| 1074 |
+
#:
|
| 1075 |
+
#: The default value includes :data:`errno.EPIPE` and :data:`errno.ECONNRESET`.
|
| 1076 |
+
#: On Windows this also includes :data:`errno.WSAECONNABORTED`.
|
| 1077 |
+
#:
|
| 1078 |
+
#: This is a provisional API, subject to change. See :pr:`377`, :pr:`999`
|
| 1079 |
+
#: and :issue:`136`.
|
| 1080 |
+
#:
|
| 1081 |
+
#: .. versionadded:: 1.3
|
| 1082 |
+
ignored_socket_errors = (errno.EPIPE, errno.ECONNRESET)
|
| 1083 |
+
try:
|
| 1084 |
+
ignored_socket_errors += (errno.WSAECONNABORTED,)
|
| 1085 |
+
except AttributeError:
|
| 1086 |
+
pass # Not windows
|
| 1087 |
+
|
| 1088 |
+
def handle_one_response(self):
|
| 1089 |
+
"""
|
| 1090 |
+
Invoke the application to produce one response.
|
| 1091 |
+
|
| 1092 |
+
This is called by :meth:`handle_one_request` after all the
|
| 1093 |
+
state for the request has been established. It is responsible
|
| 1094 |
+
for error handling.
|
| 1095 |
+
"""
|
| 1096 |
+
self.time_start = time.time()
|
| 1097 |
+
self.status = None
|
| 1098 |
+
self.headers_sent = False
|
| 1099 |
+
|
| 1100 |
+
self.result = None
|
| 1101 |
+
self.response_use_chunked = False
|
| 1102 |
+
self.connection_upgraded = False
|
| 1103 |
+
self.response_length = 0
|
| 1104 |
+
|
| 1105 |
+
try:
|
| 1106 |
+
try:
|
| 1107 |
+
self.run_application()
|
| 1108 |
+
finally:
|
| 1109 |
+
try:
|
| 1110 |
+
self.wsgi_input._discard()
|
| 1111 |
+
except _InvalidClientInput:
|
| 1112 |
+
# This one is deliberately raised to the outer
|
| 1113 |
+
# scope, because, with the incoming stream in some bad state,
|
| 1114 |
+
# we can't be sure we can synchronize and properly parse the next
|
| 1115 |
+
# request.
|
| 1116 |
+
raise
|
| 1117 |
+
except socket.error:
|
| 1118 |
+
# Don't let socket exceptions during discarding
|
| 1119 |
+
# input override any exception that may have been
|
| 1120 |
+
# raised by the application, such as our own _InvalidClientInput.
|
| 1121 |
+
# In the general case, these aren't even worth logging (see the comment
|
| 1122 |
+
# just below)
|
| 1123 |
+
pass
|
| 1124 |
+
except _InvalidClientInput as ex:
|
| 1125 |
+
# DO log this one because:
|
| 1126 |
+
# - Some of the data may have been read and acted on by the
|
| 1127 |
+
# application;
|
| 1128 |
+
# - The response may or may not have been sent;
|
| 1129 |
+
# - It's likely that the client is bad, or malicious, and
|
| 1130 |
+
# users might wish to take steps to block the client.
|
| 1131 |
+
self._handle_client_error(ex)
|
| 1132 |
+
self.close_connection = True
|
| 1133 |
+
self._send_error_response_if_possible(400)
|
| 1134 |
+
except socket.error as ex:
|
| 1135 |
+
if ex.args[0] in self.ignored_socket_errors:
|
| 1136 |
+
# See description of self.ignored_socket_errors.
|
| 1137 |
+
self.close_connection = True
|
| 1138 |
+
else:
|
| 1139 |
+
self.handle_error(*sys.exc_info())
|
| 1140 |
+
except: # pylint:disable=bare-except
|
| 1141 |
+
self.handle_error(*sys.exc_info())
|
| 1142 |
+
finally:
|
| 1143 |
+
self.time_finish = time.time()
|
| 1144 |
+
self.log_request()
|
| 1145 |
+
|
| 1146 |
+
def _send_error_response_if_possible(self, error_code):
|
| 1147 |
+
if self.response_length:
|
| 1148 |
+
self.close_connection = True
|
| 1149 |
+
else:
|
| 1150 |
+
status, headers, body = _ERRORS[error_code]
|
| 1151 |
+
try:
|
| 1152 |
+
self.start_response(status, headers[:])
|
| 1153 |
+
self.write(body)
|
| 1154 |
+
except socket.error:
|
| 1155 |
+
self.close_connection = True
|
| 1156 |
+
|
| 1157 |
+
def _log_error(self, t, v, tb):
|
| 1158 |
+
# TODO: Shouldn't we dump this to wsgi.errors? If we did that now, it would
|
| 1159 |
+
# wind up getting logged twice
|
| 1160 |
+
if not issubclass(t, GreenletExit):
|
| 1161 |
+
context = self.environ
|
| 1162 |
+
if not isinstance(context, self.server.secure_environ_class):
|
| 1163 |
+
context = self.server.secure_environ_class(context)
|
| 1164 |
+
self.server.loop.handle_error(context, t, v, tb)
|
| 1165 |
+
|
| 1166 |
+
def handle_error(self, t, v, tb):
|
| 1167 |
+
# Called for internal, unexpected errors, NOT invalid client input
|
| 1168 |
+
self._log_error(t, v, tb)
|
| 1169 |
+
t = v = tb = None
|
| 1170 |
+
self._send_error_response_if_possible(500)
|
| 1171 |
+
|
| 1172 |
+
def _handle_client_error(self, ex):
|
| 1173 |
+
# Called for invalid client input
|
| 1174 |
+
# Returns the appropriate error response.
|
| 1175 |
+
if not isinstance(ex, (ValueError, _InvalidClientInput)):
|
| 1176 |
+
# XXX: Why not self._log_error to send it through the loop's
|
| 1177 |
+
# handle_error method?
|
| 1178 |
+
# _InvalidClientRequest is a ValueError; _InvalidClientInput is an IOError.
|
| 1179 |
+
traceback.print_exc()
|
| 1180 |
+
if isinstance(ex, _InvalidClientRequest):
|
| 1181 |
+
# No formatting needed, that's already been handled. In fact, because the
|
| 1182 |
+
# formatted message contains user input, it might have a % in it, and attempting
|
| 1183 |
+
# to format that with no arguments would be an error.
|
| 1184 |
+
# However, the error messages do not include the requesting IP
|
| 1185 |
+
# necessarily, so we do add that.
|
| 1186 |
+
self.log_error('(from %s) %s', self.client_address, ex.formatted_message)
|
| 1187 |
+
else:
|
| 1188 |
+
self.log_error('Invalid request (from %s): %s',
|
| 1189 |
+
self.client_address,
|
| 1190 |
+
str(ex) or ex.__class__.__name__)
|
| 1191 |
+
return ('400', _BAD_REQUEST_RESPONSE)
|
| 1192 |
+
|
| 1193 |
+
def _headers(self):
|
| 1194 |
+
key = None
|
| 1195 |
+
value = None
|
| 1196 |
+
IGNORED_KEYS = (None, 'CONTENT_TYPE', 'CONTENT_LENGTH')
|
| 1197 |
+
for header in self.headers.headers:
|
| 1198 |
+
if key is not None and header[:1] in " \t":
|
| 1199 |
+
value += header
|
| 1200 |
+
continue
|
| 1201 |
+
|
| 1202 |
+
if key not in IGNORED_KEYS:
|
| 1203 |
+
yield 'HTTP_' + key, value.strip()
|
| 1204 |
+
|
| 1205 |
+
key, value = header.split(':', 1)
|
| 1206 |
+
if '_' in key:
|
| 1207 |
+
# strip incoming bad veaders
|
| 1208 |
+
key = None
|
| 1209 |
+
else:
|
| 1210 |
+
key = key.replace('-', '_').upper()
|
| 1211 |
+
|
| 1212 |
+
if key not in IGNORED_KEYS:
|
| 1213 |
+
yield 'HTTP_' + key, value.strip()
|
| 1214 |
+
|
| 1215 |
+
def get_environ(self):
|
| 1216 |
+
"""
|
| 1217 |
+
Construct and return a new WSGI environment dictionary for a specific request.
|
| 1218 |
+
|
| 1219 |
+
This should begin with asking the server for the base environment
|
| 1220 |
+
using :meth:`WSGIServer.get_environ`, and then proceed to add the
|
| 1221 |
+
request specific values.
|
| 1222 |
+
|
| 1223 |
+
By the time this method is invoked the request line and request shall have
|
| 1224 |
+
been parsed and ``self.headers`` shall be populated.
|
| 1225 |
+
"""
|
| 1226 |
+
env = self.server.get_environ()
|
| 1227 |
+
env['REQUEST_METHOD'] = self.command
|
| 1228 |
+
# SCRIPT_NAME is explicitly implementation defined. Using an
|
| 1229 |
+
# empty value for SCRIPT_NAME is both explicitly allowed by
|
| 1230 |
+
# both the CGI standard and WSGI PEPs, and also the thing that
|
| 1231 |
+
# makes the most sense from a generic server perspective (we
|
| 1232 |
+
# have no hierarchy or understanding of URLs or files, just a
|
| 1233 |
+
# single application to call. The empty string represents the
|
| 1234 |
+
# application root, which is what we have). Different WSGI
|
| 1235 |
+
# implementations handle this very differently, so portable
|
| 1236 |
+
# applications that rely on SCRIPT_NAME will have to use a
|
| 1237 |
+
# WSGI middleware to set it to a defined value, or otherwise
|
| 1238 |
+
# rely on server-specific mechanisms (e.g, on waitress, use
|
| 1239 |
+
# ``--url-prefix``, in gunicorn set the ``SCRIPT_NAME`` header
|
| 1240 |
+
# or process environment variable, in gevent subclass
|
| 1241 |
+
# WSGIHandler.)
|
| 1242 |
+
#
|
| 1243 |
+
# See https://github.com/gevent/gevent/issues/1667 for discussion.
|
| 1244 |
+
env['SCRIPT_NAME'] = ''
|
| 1245 |
+
|
| 1246 |
+
path, query = self.path.split('?', 1) if '?' in self.path else (self.path, '')
|
| 1247 |
+
# Note that self.path contains the original str object; if it contains
|
| 1248 |
+
# encoded escapes, it will NOT match PATH_INFO.
|
| 1249 |
+
env['PATH_INFO'] = unquote_latin1(path)
|
| 1250 |
+
env['QUERY_STRING'] = query
|
| 1251 |
+
|
| 1252 |
+
if self.headers.typeheader is not None:
|
| 1253 |
+
env['CONTENT_TYPE'] = self.headers.typeheader
|
| 1254 |
+
|
| 1255 |
+
length = self.headers.getheader('content-length')
|
| 1256 |
+
if length:
|
| 1257 |
+
env['CONTENT_LENGTH'] = length
|
| 1258 |
+
env['SERVER_PROTOCOL'] = self.request_version
|
| 1259 |
+
|
| 1260 |
+
client_address = self.client_address
|
| 1261 |
+
if isinstance(client_address, tuple):
|
| 1262 |
+
env['REMOTE_ADDR'] = str(client_address[0])
|
| 1263 |
+
env['REMOTE_PORT'] = str(client_address[1])
|
| 1264 |
+
|
| 1265 |
+
for key, value in self._headers():
|
| 1266 |
+
if key in env:
|
| 1267 |
+
if 'COOKIE' in key:
|
| 1268 |
+
env[key] += '; ' + value
|
| 1269 |
+
else:
|
| 1270 |
+
env[key] += ',' + value
|
| 1271 |
+
else:
|
| 1272 |
+
env[key] = value
|
| 1273 |
+
|
| 1274 |
+
sock = self.socket if env.get('HTTP_EXPECT') == '100-continue' else None
|
| 1275 |
+
|
| 1276 |
+
chunked = env.get('HTTP_TRANSFER_ENCODING', '').lower() == 'chunked'
|
| 1277 |
+
# Input refuses to read if the data isn't chunked, and there is no content_length
|
| 1278 |
+
# provided. For 'Upgrade: Websocket' requests, neither of those things is true.
|
| 1279 |
+
handling_reads = not self._connection_upgrade_requested()
|
| 1280 |
+
|
| 1281 |
+
self.wsgi_input = Input(self.rfile, self.content_length, socket=sock, chunked_input=chunked)
|
| 1282 |
+
|
| 1283 |
+
env['wsgi.input'] = self.wsgi_input if handling_reads else self.rfile
|
| 1284 |
+
# This is a non-standard flag indicating that our input stream is
|
| 1285 |
+
# self-terminated (returns EOF when consumed).
|
| 1286 |
+
# See https://github.com/gevent/gevent/issues/1308
|
| 1287 |
+
env['wsgi.input_terminated'] = handling_reads
|
| 1288 |
+
return env
|
| 1289 |
+
|
| 1290 |
+
|
| 1291 |
+
class _NoopLog(object):
|
| 1292 |
+
# Does nothing; implements just enough file-like methods
|
| 1293 |
+
# to pass the WSGI validator
|
| 1294 |
+
|
| 1295 |
+
def write(self, *args, **kwargs):
|
| 1296 |
+
# pylint:disable=unused-argument
|
| 1297 |
+
return
|
| 1298 |
+
|
| 1299 |
+
def flush(self):
|
| 1300 |
+
pass
|
| 1301 |
+
|
| 1302 |
+
def writelines(self, *args, **kwargs):
|
| 1303 |
+
pass
|
| 1304 |
+
|
| 1305 |
+
|
| 1306 |
+
class LoggingLogAdapter(object):
|
| 1307 |
+
"""
|
| 1308 |
+
An adapter for :class:`logging.Logger` instances
|
| 1309 |
+
to let them be used with :class:`WSGIServer`.
|
| 1310 |
+
|
| 1311 |
+
.. warning:: Unless the entire process is monkey-patched at a very
|
| 1312 |
+
early part of the lifecycle (before logging is configured),
|
| 1313 |
+
loggers are likely to not be gevent-cooperative. For example,
|
| 1314 |
+
the socket and syslog handlers use the socket module in a way
|
| 1315 |
+
that can block, and most handlers acquire threading locks.
|
| 1316 |
+
|
| 1317 |
+
.. warning:: It *may* be possible for the logging functions to be
|
| 1318 |
+
called in the :class:`gevent.Hub` greenlet. Code running in the
|
| 1319 |
+
hub greenlet cannot use any gevent blocking functions without triggering
|
| 1320 |
+
a ``LoopExit``.
|
| 1321 |
+
|
| 1322 |
+
.. versionadded:: 1.1a3
|
| 1323 |
+
|
| 1324 |
+
.. versionchanged:: 1.1b6
|
| 1325 |
+
Attributes not present on this object are proxied to the underlying
|
| 1326 |
+
logger instance. This permits using custom :class:`~logging.Logger`
|
| 1327 |
+
subclasses (or indeed, even duck-typed objects).
|
| 1328 |
+
|
| 1329 |
+
.. versionchanged:: 1.1
|
| 1330 |
+
Strip trailing newline characters on the message passed to :meth:`write`
|
| 1331 |
+
because log handlers will usually add one themselves.
|
| 1332 |
+
"""
|
| 1333 |
+
|
| 1334 |
+
# gevent avoids importing and using logging because importing it and
|
| 1335 |
+
# creating loggers creates native locks unless monkey-patched.
|
| 1336 |
+
|
| 1337 |
+
__slots__ = ('_logger', '_level')
|
| 1338 |
+
|
| 1339 |
+
def __init__(self, logger, level=20):
|
| 1340 |
+
"""
|
| 1341 |
+
Write information to the *logger* at the given *level* (default to INFO).
|
| 1342 |
+
"""
|
| 1343 |
+
self._logger = logger
|
| 1344 |
+
self._level = level
|
| 1345 |
+
|
| 1346 |
+
def write(self, msg):
|
| 1347 |
+
if msg and msg.endswith('\n'):
|
| 1348 |
+
msg = msg[:-1]
|
| 1349 |
+
self._logger.log(self._level, msg)
|
| 1350 |
+
|
| 1351 |
+
def flush(self):
|
| 1352 |
+
"No-op; required to be a file-like object"
|
| 1353 |
+
|
| 1354 |
+
def writelines(self, lines):
|
| 1355 |
+
for line in lines:
|
| 1356 |
+
self.write(line)
|
| 1357 |
+
|
| 1358 |
+
def __getattr__(self, name):
|
| 1359 |
+
return getattr(self._logger, name)
|
| 1360 |
+
|
| 1361 |
+
def __setattr__(self, name, value):
|
| 1362 |
+
if name not in LoggingLogAdapter.__slots__:
|
| 1363 |
+
setattr(self._logger, name, value)
|
| 1364 |
+
else:
|
| 1365 |
+
object.__setattr__(self, name, value)
|
| 1366 |
+
|
| 1367 |
+
def __delattr__(self, name):
|
| 1368 |
+
delattr(self._logger, name)
|
| 1369 |
+
|
| 1370 |
+
####
|
| 1371 |
+
## Environ classes.
|
| 1372 |
+
# These subclass dict. They could subclass collections.UserDict on
|
| 1373 |
+
# 3.3+ and proxy to the underlying real dict to avoid a copy if we
|
| 1374 |
+
# have to print them (on 2.7 it's slightly more complicated to be an
|
| 1375 |
+
# instance of collections.MutableMapping; UserDict.UserDict isn't.)
|
| 1376 |
+
# Then we could have either the WSGIHandler.get_environ or the
|
| 1377 |
+
# WSGIServer.get_environ return one of these proxies, and
|
| 1378 |
+
# WSGIHandler.run_application would know to access the `environ.data`
|
| 1379 |
+
# attribute to be able to pass the *real* dict to the application
|
| 1380 |
+
# (because PEP3333 requires no subclasses, only actual dict objects;
|
| 1381 |
+
# wsgiref.validator and webob.Request both enforce this). This has the
|
| 1382 |
+
# advantage of not being fragile if anybody else tries to print/log
|
| 1383 |
+
# self.environ (and not requiring a copy). However, if there are any
|
| 1384 |
+
# subclasses of Handler or Server, this could break if they don't know
|
| 1385 |
+
# to return this type.
|
| 1386 |
+
####
|
| 1387 |
+
|
| 1388 |
+
class Environ(dict):
|
| 1389 |
+
"""
|
| 1390 |
+
A base class that can be used for WSGI environment objects.
|
| 1391 |
+
|
| 1392 |
+
Provisional API.
|
| 1393 |
+
|
| 1394 |
+
.. versionadded:: 1.2a1
|
| 1395 |
+
"""
|
| 1396 |
+
|
| 1397 |
+
__slots__ = () # add no ivars or weakref ability
|
| 1398 |
+
|
| 1399 |
+
def copy(self):
|
| 1400 |
+
return self.__class__(self)
|
| 1401 |
+
|
| 1402 |
+
if not hasattr(dict, 'iteritems'):
|
| 1403 |
+
# Python 3
|
| 1404 |
+
def iteritems(self):
|
| 1405 |
+
return self.items()
|
| 1406 |
+
|
| 1407 |
+
def __reduce_ex__(self, proto):
|
| 1408 |
+
return (dict, (), None, None, iter(self.iteritems()))
|
| 1409 |
+
|
| 1410 |
+
class SecureEnviron(Environ):
|
| 1411 |
+
"""
|
| 1412 |
+
An environment that does not print its keys and values
|
| 1413 |
+
by default.
|
| 1414 |
+
|
| 1415 |
+
Provisional API.
|
| 1416 |
+
|
| 1417 |
+
This is intended to keep potentially sensitive information like
|
| 1418 |
+
HTTP authorization and cookies from being inadvertently printed
|
| 1419 |
+
or logged.
|
| 1420 |
+
|
| 1421 |
+
For debugging, each instance can have its *secure_repr* attribute
|
| 1422 |
+
set to ``False``, which will cause it to print like a normal dict.
|
| 1423 |
+
|
| 1424 |
+
When *secure_repr* is ``True`` (the default), then the value of
|
| 1425 |
+
the *whitelist_keys* attribute is consulted; if this value is
|
| 1426 |
+
true-ish, it should be a container (something that responds to
|
| 1427 |
+
``in``) of key names (typically a list or set). Keys and values in
|
| 1428 |
+
this dictionary that are in *whitelist_keys* will then be printed,
|
| 1429 |
+
while all other values will be masked. These values may be
|
| 1430 |
+
customized on the class by setting the *default_secure_repr* and
|
| 1431 |
+
*default_whitelist_keys*, respectively::
|
| 1432 |
+
|
| 1433 |
+
>>> environ = SecureEnviron(key='value')
|
| 1434 |
+
>>> environ # doctest: +ELLIPSIS
|
| 1435 |
+
<pywsgi.SecureEnviron dict (keys: 1) at ...
|
| 1436 |
+
|
| 1437 |
+
If we whitelist the key, it gets printed::
|
| 1438 |
+
|
| 1439 |
+
>>> environ.whitelist_keys = {'key'}
|
| 1440 |
+
>>> environ
|
| 1441 |
+
{'key': 'value'}
|
| 1442 |
+
|
| 1443 |
+
A non-whitelisted key (*only*, to avoid doctest issues) is masked::
|
| 1444 |
+
|
| 1445 |
+
>>> environ['secure'] = 'secret'; del environ['key']
|
| 1446 |
+
>>> environ
|
| 1447 |
+
{'secure': '<MASKED>'}
|
| 1448 |
+
|
| 1449 |
+
We can turn it off entirely for the instance::
|
| 1450 |
+
|
| 1451 |
+
>>> environ.secure_repr = False
|
| 1452 |
+
>>> environ
|
| 1453 |
+
{'secure': 'secret'}
|
| 1454 |
+
|
| 1455 |
+
We can also customize it at the class level (here we use a new
|
| 1456 |
+
class to be explicit and to avoid polluting the true default
|
| 1457 |
+
values; we would set this class to be the ``environ_class`` of the
|
| 1458 |
+
server)::
|
| 1459 |
+
|
| 1460 |
+
>>> class MyEnviron(SecureEnviron):
|
| 1461 |
+
... default_whitelist_keys = ('key',)
|
| 1462 |
+
...
|
| 1463 |
+
>>> environ = MyEnviron({'key': 'value'})
|
| 1464 |
+
>>> environ
|
| 1465 |
+
{'key': 'value'}
|
| 1466 |
+
|
| 1467 |
+
.. versionadded:: 1.2a1
|
| 1468 |
+
"""
|
| 1469 |
+
|
| 1470 |
+
default_secure_repr = True
|
| 1471 |
+
default_whitelist_keys = ()
|
| 1472 |
+
default_print_masked_keys = True
|
| 1473 |
+
|
| 1474 |
+
# Allow instances to override the class values,
|
| 1475 |
+
# but inherit from the class if not present. Keeps instances
|
| 1476 |
+
# small since we can't combine __slots__ with class attributes
|
| 1477 |
+
# of the same name.
|
| 1478 |
+
__slots__ = ('secure_repr', 'whitelist_keys', 'print_masked_keys')
|
| 1479 |
+
|
| 1480 |
+
def __getattr__(self, name):
|
| 1481 |
+
if name in SecureEnviron.__slots__:
|
| 1482 |
+
return getattr(type(self), 'default_' + name)
|
| 1483 |
+
raise AttributeError(name)
|
| 1484 |
+
|
| 1485 |
+
def __repr__(self):
|
| 1486 |
+
if self.secure_repr:
|
| 1487 |
+
whitelist = self.whitelist_keys
|
| 1488 |
+
print_masked = self.print_masked_keys
|
| 1489 |
+
if whitelist:
|
| 1490 |
+
safe = {k: self[k] if k in whitelist else "<MASKED>"
|
| 1491 |
+
for k in self
|
| 1492 |
+
if k in whitelist or print_masked}
|
| 1493 |
+
safe_repr = repr(safe)
|
| 1494 |
+
if not print_masked and len(safe) != len(self):
|
| 1495 |
+
safe_repr = safe_repr[:-1] + ", (hidden keys: %d)}" % (len(self) - len(safe))
|
| 1496 |
+
return safe_repr
|
| 1497 |
+
return "<pywsgi.SecureEnviron dict (keys: %d) at %s>" % (len(self), id(self))
|
| 1498 |
+
return Environ.__repr__(self)
|
| 1499 |
+
__str__ = __repr__
|
| 1500 |
+
|
| 1501 |
+
|
| 1502 |
+
class WSGISecureEnviron(SecureEnviron):
|
| 1503 |
+
"""
|
| 1504 |
+
Specializes the default list of whitelisted keys to a few
|
| 1505 |
+
common WSGI variables.
|
| 1506 |
+
|
| 1507 |
+
Example::
|
| 1508 |
+
|
| 1509 |
+
>>> environ = WSGISecureEnviron(REMOTE_ADDR='::1', HTTP_AUTHORIZATION='secret')
|
| 1510 |
+
>>> environ
|
| 1511 |
+
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
|
| 1512 |
+
>>> import pprint
|
| 1513 |
+
>>> pprint.pprint(environ)
|
| 1514 |
+
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
|
| 1515 |
+
>>> print(pprint.pformat(environ))
|
| 1516 |
+
{'REMOTE_ADDR': '::1', (hidden keys: 1)}
|
| 1517 |
+
"""
|
| 1518 |
+
default_whitelist_keys = ('REMOTE_ADDR', 'REMOTE_PORT', 'HTTP_HOST')
|
| 1519 |
+
default_print_masked_keys = False
|
| 1520 |
+
|
| 1521 |
+
|
| 1522 |
+
class WSGIServer(StreamServer):
|
| 1523 |
+
"""
|
| 1524 |
+
A WSGI server based on :class:`StreamServer` that supports HTTPS.
|
| 1525 |
+
|
| 1526 |
+
|
| 1527 |
+
:keyword log: If given, an object with a ``write`` method to which
|
| 1528 |
+
request (access) logs will be written. If not given, defaults
|
| 1529 |
+
to :obj:`sys.stderr`. You may pass ``None`` to disable request
|
| 1530 |
+
logging. You may use a wrapper, around e.g., :mod:`logging`,
|
| 1531 |
+
to support objects that don't implement a ``write`` method.
|
| 1532 |
+
(If you pass a :class:`~logging.Logger` instance, or in
|
| 1533 |
+
general something that provides a ``log`` method but not a
|
| 1534 |
+
``write`` method, such a wrapper will automatically be created
|
| 1535 |
+
and it will be logged to at the :data:`~logging.INFO` level.)
|
| 1536 |
+
|
| 1537 |
+
:keyword error_log: If given, a file-like object with ``write``,
|
| 1538 |
+
``writelines`` and ``flush`` methods to which error logs will
|
| 1539 |
+
be written. If not given, defaults to :obj:`sys.stderr`. You
|
| 1540 |
+
may pass ``None`` to disable error logging (not recommended).
|
| 1541 |
+
You may use a wrapper, around e.g., :mod:`logging`, to support
|
| 1542 |
+
objects that don't implement the proper methods. This
|
| 1543 |
+
parameter will become the value for ``wsgi.errors`` in the
|
| 1544 |
+
WSGI environment (if not already set). (As with *log*,
|
| 1545 |
+
wrappers for :class:`~logging.Logger` instances and the like
|
| 1546 |
+
will be created automatically and logged to at the :data:`~logging.ERROR`
|
| 1547 |
+
level.)
|
| 1548 |
+
|
| 1549 |
+
.. seealso::
|
| 1550 |
+
|
| 1551 |
+
:class:`LoggingLogAdapter`
|
| 1552 |
+
See important warnings before attempting to use :mod:`logging`.
|
| 1553 |
+
|
| 1554 |
+
.. versionchanged:: 1.1a3
|
| 1555 |
+
Added the ``error_log`` parameter, and set ``wsgi.errors`` in the WSGI
|
| 1556 |
+
environment to this value.
|
| 1557 |
+
.. versionchanged:: 1.1a3
|
| 1558 |
+
Add support for passing :class:`logging.Logger` objects to the ``log`` and
|
| 1559 |
+
``error_log`` arguments.
|
| 1560 |
+
.. versionchanged:: 20.6.0
|
| 1561 |
+
Passing a ``handle`` kwarg to the constructor is now officially deprecated.
|
| 1562 |
+
"""
|
| 1563 |
+
|
| 1564 |
+
#: A callable taking three arguments: (socket, address, server) and returning
|
| 1565 |
+
#: an object with a ``handle()`` method. The callable is called once for
|
| 1566 |
+
#: each incoming socket request, as is its handle method. The handle method should not
|
| 1567 |
+
#: return until all use of the socket is complete.
|
| 1568 |
+
#:
|
| 1569 |
+
#: This class uses the :class:`WSGIHandler` object as the default value. You may
|
| 1570 |
+
#: subclass this class and set a different default value, or you may pass
|
| 1571 |
+
#: a value to use in the ``handler_class`` keyword constructor argument.
|
| 1572 |
+
handler_class = WSGIHandler
|
| 1573 |
+
|
| 1574 |
+
#: The object to which request logs will be written.
|
| 1575 |
+
#: It must never be None. Initialized from the ``log`` constructor
|
| 1576 |
+
#: parameter.
|
| 1577 |
+
log = None
|
| 1578 |
+
|
| 1579 |
+
#: The object to which error logs will be written.
|
| 1580 |
+
#: It must never be None. Initialized from the ``error_log`` constructor
|
| 1581 |
+
#: parameter.
|
| 1582 |
+
error_log = None
|
| 1583 |
+
|
| 1584 |
+
#: The class of environ objects passed to the handlers.
|
| 1585 |
+
#: Must be a dict subclass. For compliance with :pep:`3333`
|
| 1586 |
+
#: and libraries like WebOb, this is simply :class:`dict`
|
| 1587 |
+
#: but this can be customized in a subclass or per-instance
|
| 1588 |
+
#: (probably to :class:`WSGISecureEnviron`).
|
| 1589 |
+
#:
|
| 1590 |
+
#: .. versionadded:: 1.2a1
|
| 1591 |
+
environ_class = dict
|
| 1592 |
+
|
| 1593 |
+
# Undocumented internal detail: the class that WSGIHandler._log_error
|
| 1594 |
+
# will cast to before passing to the loop.
|
| 1595 |
+
secure_environ_class = WSGISecureEnviron
|
| 1596 |
+
|
| 1597 |
+
base_env = {'GATEWAY_INTERFACE': 'CGI/1.1',
|
| 1598 |
+
'SERVER_SOFTWARE': 'gevent/%d.%d Python/%d.%d' % (gevent.version_info[:2] + sys.version_info[:2]),
|
| 1599 |
+
'SCRIPT_NAME': '',
|
| 1600 |
+
'wsgi.version': (1, 0),
|
| 1601 |
+
'wsgi.multithread': False, # XXX: Aren't we really, though?
|
| 1602 |
+
'wsgi.multiprocess': False,
|
| 1603 |
+
'wsgi.run_once': False}
|
| 1604 |
+
|
| 1605 |
+
def __init__(self, listener, application=None, backlog=None, spawn='default',
|
| 1606 |
+
log='default', error_log='default',
|
| 1607 |
+
handler_class=None,
|
| 1608 |
+
environ=None, **ssl_args):
|
| 1609 |
+
if 'handle' in ssl_args:
|
| 1610 |
+
# The ultimate base class (BaseServer) uses 'handle' for
|
| 1611 |
+
# the thing we call 'application'. We never deliberately
|
| 1612 |
+
# bass a `handle` argument to the base class, but one
|
| 1613 |
+
# could sneak in through ``**ssl_args``, even though that
|
| 1614 |
+
# is not the intent, while application is None. That
|
| 1615 |
+
# causes our own ``def handle`` method to be replaced,
|
| 1616 |
+
# probably leading to bad results. Passing a 'handle'
|
| 1617 |
+
# instead of an 'application' can really confuse things.
|
| 1618 |
+
import warnings
|
| 1619 |
+
warnings.warn("Passing 'handle' kwarg to WSGIServer is deprecated. "
|
| 1620 |
+
"Did you mean application?", DeprecationWarning, stacklevel=2)
|
| 1621 |
+
|
| 1622 |
+
StreamServer.__init__(self, listener, backlog=backlog, spawn=spawn, **ssl_args)
|
| 1623 |
+
|
| 1624 |
+
if application is not None:
|
| 1625 |
+
self.application = application
|
| 1626 |
+
if handler_class is not None:
|
| 1627 |
+
self.handler_class = handler_class
|
| 1628 |
+
|
| 1629 |
+
# Note that we can't initialize these as class variables:
|
| 1630 |
+
# sys.stderr might get monkey patched at runtime.
|
| 1631 |
+
def _make_log(l, level=20):
|
| 1632 |
+
if l == 'default':
|
| 1633 |
+
return sys.stderr
|
| 1634 |
+
if l is None:
|
| 1635 |
+
return _NoopLog()
|
| 1636 |
+
if not hasattr(l, 'write') and hasattr(l, 'log'):
|
| 1637 |
+
return LoggingLogAdapter(l, level)
|
| 1638 |
+
return l
|
| 1639 |
+
self.log = _make_log(log)
|
| 1640 |
+
self.error_log = _make_log(error_log, 40) # logging.ERROR
|
| 1641 |
+
|
| 1642 |
+
self.set_environ(environ)
|
| 1643 |
+
self.set_max_accept()
|
| 1644 |
+
|
| 1645 |
+
def set_environ(self, environ=None):
|
| 1646 |
+
if environ is not None:
|
| 1647 |
+
self.environ = environ
|
| 1648 |
+
environ_update = getattr(self, 'environ', None)
|
| 1649 |
+
|
| 1650 |
+
self.environ = self.environ_class(self.base_env)
|
| 1651 |
+
if self.ssl_enabled:
|
| 1652 |
+
self.environ['wsgi.url_scheme'] = 'https'
|
| 1653 |
+
else:
|
| 1654 |
+
self.environ['wsgi.url_scheme'] = 'http'
|
| 1655 |
+
if environ_update is not None:
|
| 1656 |
+
self.environ.update(environ_update)
|
| 1657 |
+
if self.environ.get('wsgi.errors') is None:
|
| 1658 |
+
self.environ['wsgi.errors'] = self.error_log
|
| 1659 |
+
|
| 1660 |
+
def set_max_accept(self):
|
| 1661 |
+
if self.environ.get('wsgi.multiprocess'):
|
| 1662 |
+
self.max_accept = 1
|
| 1663 |
+
|
| 1664 |
+
def get_environ(self):
|
| 1665 |
+
return self.environ_class(self.environ)
|
| 1666 |
+
|
| 1667 |
+
def init_socket(self):
|
| 1668 |
+
StreamServer.init_socket(self)
|
| 1669 |
+
self.update_environ()
|
| 1670 |
+
|
| 1671 |
+
def update_environ(self):
|
| 1672 |
+
"""
|
| 1673 |
+
Called before the first request is handled to fill in WSGI environment values.
|
| 1674 |
+
|
| 1675 |
+
This includes getting the correct server name and port.
|
| 1676 |
+
"""
|
| 1677 |
+
address = self.address
|
| 1678 |
+
if isinstance(address, tuple):
|
| 1679 |
+
if 'SERVER_NAME' not in self.environ:
|
| 1680 |
+
try:
|
| 1681 |
+
name = socket.getfqdn(address[0])
|
| 1682 |
+
except socket.error:
|
| 1683 |
+
name = str(address[0])
|
| 1684 |
+
if not isinstance(name, str):
|
| 1685 |
+
name = name.decode('ascii')
|
| 1686 |
+
self.environ['SERVER_NAME'] = name
|
| 1687 |
+
self.environ.setdefault('SERVER_PORT', str(address[1]))
|
| 1688 |
+
else:
|
| 1689 |
+
self.environ.setdefault('SERVER_NAME', '')
|
| 1690 |
+
self.environ.setdefault('SERVER_PORT', '')
|
| 1691 |
+
|
| 1692 |
+
def handle(self, sock, address):
|
| 1693 |
+
"""
|
| 1694 |
+
Create an instance of :attr:`handler_class` to handle the request.
|
| 1695 |
+
|
| 1696 |
+
This method blocks until the handler returns.
|
| 1697 |
+
"""
|
| 1698 |
+
# pylint:disable=method-hidden
|
| 1699 |
+
handler = self.handler_class(sock, address, self)
|
| 1700 |
+
handler.handle()
|
| 1701 |
+
|
| 1702 |
+
def _main():
|
| 1703 |
+
# Provisional main handler, for quick tests, not production
|
| 1704 |
+
# usage.
|
| 1705 |
+
from gevent import monkey; monkey.patch_all()
|
| 1706 |
+
|
| 1707 |
+
import argparse
|
| 1708 |
+
import importlib
|
| 1709 |
+
|
| 1710 |
+
parser = argparse.ArgumentParser()
|
| 1711 |
+
parser.add_argument("app", help="dotted name of WSGI app callable [module:callable]")
|
| 1712 |
+
parser.add_argument("-b", "--bind",
|
| 1713 |
+
help="The socket to bind",
|
| 1714 |
+
default=":8080")
|
| 1715 |
+
|
| 1716 |
+
args = parser.parse_args()
|
| 1717 |
+
|
| 1718 |
+
module_name, app_name = args.app.split(':')
|
| 1719 |
+
module = importlib.import_module(module_name)
|
| 1720 |
+
app = getattr(module, app_name)
|
| 1721 |
+
bind = args.bind
|
| 1722 |
+
|
| 1723 |
+
server = WSGIServer(bind, app)
|
| 1724 |
+
server.serve_forever()
|
| 1725 |
+
|
| 1726 |
+
if __name__ == '__main__':
|
| 1727 |
+
_main()
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/queue.py
ADDED
|
@@ -0,0 +1,772 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 3 |
+
# cython: auto_pickle=False,embedsignature=True,always_allow_keywords=False
|
| 4 |
+
"""
|
| 5 |
+
Synchronized queues.
|
| 6 |
+
|
| 7 |
+
The :mod:`gevent.queue` module implements multi-producer, multi-consumer queues
|
| 8 |
+
that work across greenlets, with the API similar to the classes found in the
|
| 9 |
+
standard :mod:`Queue` and :class:`multiprocessing <multiprocessing.Queue>` modules.
|
| 10 |
+
|
| 11 |
+
The classes in this module implement the iterator protocol. Iterating
|
| 12 |
+
over a queue means repeatedly calling :meth:`get <Queue.get>` until
|
| 13 |
+
:meth:`get <Queue.get>` returns ``StopIteration`` (specifically that
|
| 14 |
+
class, not an instance or subclass).
|
| 15 |
+
|
| 16 |
+
>>> import gevent.queue
|
| 17 |
+
>>> queue = gevent.queue.Queue()
|
| 18 |
+
>>> queue.put(1)
|
| 19 |
+
>>> queue.put(2)
|
| 20 |
+
>>> queue.put(StopIteration)
|
| 21 |
+
>>> for item in queue:
|
| 22 |
+
... print(item)
|
| 23 |
+
1
|
| 24 |
+
2
|
| 25 |
+
|
| 26 |
+
.. versionchanged:: 1.0
|
| 27 |
+
``Queue(0)`` now means queue of infinite size, not a channel. A :exc:`DeprecationWarning`
|
| 28 |
+
will be issued with this argument.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
import sys
|
| 33 |
+
from heapq import heappush as _heappush
|
| 34 |
+
from heapq import heappop as _heappop
|
| 35 |
+
from heapq import heapify as _heapify
|
| 36 |
+
import collections
|
| 37 |
+
|
| 38 |
+
import queue as __queue__
|
| 39 |
+
# We re-export these exceptions to client modules.
|
| 40 |
+
# But we also want fast access to them from Cython with a cdef,
|
| 41 |
+
# and we do that with the _ definition.
|
| 42 |
+
_Full = Full = __queue__.Full
|
| 43 |
+
_Empty = Empty = __queue__.Empty
|
| 44 |
+
|
| 45 |
+
from gevent.timeout import Timeout
|
| 46 |
+
from gevent._hub_local import get_hub_noargs as get_hub
|
| 47 |
+
from gevent.exceptions import InvalidSwitchError
|
| 48 |
+
|
| 49 |
+
__all__ = []
|
| 50 |
+
__implements__ = ['Queue', 'PriorityQueue', 'LifoQueue']
|
| 51 |
+
__extensions__ = ['JoinableQueue', 'Channel']
|
| 52 |
+
__imports__ = ['Empty', 'Full']
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
__all__.append('SimpleQueue')
|
| 56 |
+
# SimpleQueue is implemented in C and directly allocates locks
|
| 57 |
+
# unaffected by monkey patching. We need the Python version.
|
| 58 |
+
SimpleQueue = __queue__._PySimpleQueue # pylint:disable=no-member
|
| 59 |
+
|
| 60 |
+
if hasattr(__queue__, 'ShutDown'): # New in 3.13
|
| 61 |
+
ShutDown = __queue__.ShutDown
|
| 62 |
+
__imports__.append('ShutDown')
|
| 63 |
+
else:
|
| 64 |
+
class ShutDown(Exception):
|
| 65 |
+
"""
|
| 66 |
+
gevent extension for Python versions less than 3.13
|
| 67 |
+
"""
|
| 68 |
+
__extensions__.append('ShutDown')
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
__all__ += (__implements__ + __extensions__ + __imports__)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# pylint 2.0.dev2 things collections.dequeue.popleft() doesn't return
|
| 75 |
+
# pylint:disable=assignment-from-no-return
|
| 76 |
+
|
| 77 |
+
def _safe_remove(deq, item):
|
| 78 |
+
# For when the item may have been removed by
|
| 79 |
+
# Queue._unlock
|
| 80 |
+
try:
|
| 81 |
+
deq.remove(item)
|
| 82 |
+
except ValueError:
|
| 83 |
+
pass
|
| 84 |
+
|
| 85 |
+
import gevent._waiter
|
| 86 |
+
locals()['Waiter'] = gevent._waiter.Waiter
|
| 87 |
+
locals()['getcurrent'] = __import__('greenlet').getcurrent
|
| 88 |
+
locals()['greenlet_init'] = lambda: None
|
| 89 |
+
|
| 90 |
+
class ItemWaiter(Waiter): # pylint:disable=undefined-variable
|
| 91 |
+
# pylint:disable=assigning-non-slot
|
| 92 |
+
__slots__ = (
|
| 93 |
+
'item',
|
| 94 |
+
'queue',
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
def __init__(self, item, queue):
|
| 98 |
+
Waiter.__init__(self) # pylint:disable=undefined-variable
|
| 99 |
+
self.item = item
|
| 100 |
+
self.queue = queue
|
| 101 |
+
|
| 102 |
+
def put_and_switch(self):
|
| 103 |
+
self.queue._put(self.item)
|
| 104 |
+
self.queue = None
|
| 105 |
+
self.item = None
|
| 106 |
+
return self.switch(self)
|
| 107 |
+
|
| 108 |
+
class Queue(object):
|
| 109 |
+
"""
|
| 110 |
+
Create a queue object with a given maximum size.
|
| 111 |
+
|
| 112 |
+
If *maxsize* is less than or equal to zero or ``None``, the queue
|
| 113 |
+
size is infinite.
|
| 114 |
+
|
| 115 |
+
Queues have a ``len`` equal to the number of items in them (the :meth:`qsize`),
|
| 116 |
+
but in a boolean context they are always True.
|
| 117 |
+
|
| 118 |
+
.. versionchanged:: 1.1b3
|
| 119 |
+
Queues now support :func:`len`; it behaves the same as :meth:`qsize`.
|
| 120 |
+
.. versionchanged:: 1.1b3
|
| 121 |
+
Multiple greenlets that block on a call to :meth:`put` for a full queue
|
| 122 |
+
will now be awakened to put their items into the queue in the order in which
|
| 123 |
+
they arrived. Likewise, multiple greenlets that block on a call to :meth:`get` for
|
| 124 |
+
an empty queue will now receive items in the order in which they blocked. An
|
| 125 |
+
implementation quirk under CPython *usually* ensured this was roughly the case
|
| 126 |
+
previously anyway, but that wasn't the case for PyPy.
|
| 127 |
+
.. versionchanged:: 24.10.1
|
| 128 |
+
Implement the ``shutdown`` methods from Python 3.13.
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
__slots__ = (
|
| 132 |
+
'_maxsize',
|
| 133 |
+
'getters',
|
| 134 |
+
'putters',
|
| 135 |
+
'hub',
|
| 136 |
+
'_event_unlock',
|
| 137 |
+
'queue',
|
| 138 |
+
'__weakref__',
|
| 139 |
+
'is_shutdown', # 3.13
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def __init__(self, maxsize=None, items=(), _warn_depth=2):
|
| 144 |
+
if maxsize is not None and maxsize <= 0:
|
| 145 |
+
if maxsize == 0:
|
| 146 |
+
import warnings
|
| 147 |
+
warnings.warn(
|
| 148 |
+
'Queue(0) now equivalent to Queue(None); if you want a channel, use Channel',
|
| 149 |
+
DeprecationWarning,
|
| 150 |
+
stacklevel=_warn_depth)
|
| 151 |
+
maxsize = None
|
| 152 |
+
|
| 153 |
+
self._maxsize = maxsize if maxsize is not None else -1
|
| 154 |
+
# Explicitly maintain order for getters and putters that block
|
| 155 |
+
# so that callers can consistently rely on getting things out
|
| 156 |
+
# in the apparent order they went in. This was once required by
|
| 157 |
+
# imap_unordered. Previously these were set() objects, and the
|
| 158 |
+
# items put in the set have default hash() and eq() methods;
|
| 159 |
+
# under CPython, since new objects tend to have increasing
|
| 160 |
+
# hash values, this tended to roughly maintain order anyway,
|
| 161 |
+
# but that's not true under PyPy. An alternative to a deque
|
| 162 |
+
# (to avoid the linear scan of remove()) might be an
|
| 163 |
+
# OrderedDict, but it's 2.7 only; we don't expect to have so
|
| 164 |
+
# many waiters that removing an arbitrary element is a
|
| 165 |
+
# bottleneck, though.
|
| 166 |
+
self.getters = collections.deque()
|
| 167 |
+
self.putters = collections.deque()
|
| 168 |
+
self.hub = get_hub()
|
| 169 |
+
self._event_unlock = None
|
| 170 |
+
self.queue = self._create_queue(items)
|
| 171 |
+
self.is_shutdown = False
|
| 172 |
+
|
| 173 |
+
@property
|
| 174 |
+
def maxsize(self):
|
| 175 |
+
return self._maxsize if self._maxsize > 0 else None
|
| 176 |
+
|
| 177 |
+
@maxsize.setter
|
| 178 |
+
def maxsize(self, nv):
|
| 179 |
+
# QQQ make maxsize into a property with setter that schedules unlock if necessary
|
| 180 |
+
if nv is None or nv <= 0:
|
| 181 |
+
self._maxsize = -1
|
| 182 |
+
else:
|
| 183 |
+
self._maxsize = nv
|
| 184 |
+
|
| 185 |
+
def copy(self):
|
| 186 |
+
return type(self)(self.maxsize, self.queue)
|
| 187 |
+
|
| 188 |
+
def _create_queue(self, items=()):
|
| 189 |
+
return collections.deque(items)
|
| 190 |
+
|
| 191 |
+
def _get(self):
|
| 192 |
+
return self.queue.popleft()
|
| 193 |
+
|
| 194 |
+
def _peek(self):
|
| 195 |
+
return self.queue[0]
|
| 196 |
+
|
| 197 |
+
def _put(self, item):
|
| 198 |
+
self.queue.append(item)
|
| 199 |
+
|
| 200 |
+
def __repr__(self):
|
| 201 |
+
return '<%s at %s%s>' % (type(self).__name__, hex(id(self)), self._format())
|
| 202 |
+
|
| 203 |
+
def __str__(self):
|
| 204 |
+
return '<%s%s>' % (type(self).__name__, self._format())
|
| 205 |
+
|
| 206 |
+
def _format(self):
|
| 207 |
+
result = []
|
| 208 |
+
if self.maxsize is not None:
|
| 209 |
+
result.append('maxsize=%r' % (self.maxsize, ))
|
| 210 |
+
if getattr(self, 'queue', None):
|
| 211 |
+
result.append('queue=%r' % (self.queue, ))
|
| 212 |
+
if self.getters:
|
| 213 |
+
result.append('getters[%s]' % len(self.getters))
|
| 214 |
+
if self.putters:
|
| 215 |
+
result.append('putters[%s]' % len(self.putters))
|
| 216 |
+
if result:
|
| 217 |
+
return ' ' + ' '.join(result)
|
| 218 |
+
return ''
|
| 219 |
+
|
| 220 |
+
def qsize(self):
|
| 221 |
+
"""Return the size of the queue."""
|
| 222 |
+
return len(self.queue)
|
| 223 |
+
|
| 224 |
+
def __len__(self):
|
| 225 |
+
"""
|
| 226 |
+
Return the size of the queue. This is the same as :meth:`qsize`.
|
| 227 |
+
|
| 228 |
+
.. versionadded: 1.1b3
|
| 229 |
+
|
| 230 |
+
Previously, getting len() of a queue would raise a TypeError.
|
| 231 |
+
"""
|
| 232 |
+
|
| 233 |
+
return self.qsize()
|
| 234 |
+
|
| 235 |
+
def __bool__(self):
|
| 236 |
+
"""
|
| 237 |
+
A queue object is always True.
|
| 238 |
+
|
| 239 |
+
.. versionadded: 1.1b3
|
| 240 |
+
|
| 241 |
+
Now that queues support len(), they need to implement ``__bool__``
|
| 242 |
+
to return True for backwards compatibility.
|
| 243 |
+
"""
|
| 244 |
+
return True
|
| 245 |
+
|
| 246 |
+
def empty(self):
|
| 247 |
+
"""Return ``True`` if the queue is empty, ``False`` otherwise."""
|
| 248 |
+
return not self.qsize()
|
| 249 |
+
|
| 250 |
+
def full(self):
|
| 251 |
+
"""Return ``True`` if the queue is full, ``False`` otherwise.
|
| 252 |
+
|
| 253 |
+
``Queue(None)`` is never full.
|
| 254 |
+
"""
|
| 255 |
+
return self._maxsize > 0 and self.qsize() >= self._maxsize
|
| 256 |
+
|
| 257 |
+
def put(self, item, block=True, timeout=None):
|
| 258 |
+
"""
|
| 259 |
+
Put an item into the queue.
|
| 260 |
+
|
| 261 |
+
If optional arg *block* is true and *timeout* is ``None`` (the default),
|
| 262 |
+
block if necessary until a free slot is available. If *timeout* is
|
| 263 |
+
a positive number, it blocks at most *timeout* seconds and raises
|
| 264 |
+
the :class:`Full` exception if no free slot was available within that time.
|
| 265 |
+
Otherwise (*block* is false), put an item on the queue if a free slot
|
| 266 |
+
is immediately available, else raise the :class:`Full` exception (*timeout*
|
| 267 |
+
is ignored in that case).
|
| 268 |
+
|
| 269 |
+
... versionchanged:: 24.10.1
|
| 270 |
+
Now raises a ``ValueError`` for a negative *timeout* in the cases
|
| 271 |
+
that CPython does.
|
| 272 |
+
"""
|
| 273 |
+
if self.is_shutdown:
|
| 274 |
+
raise ShutDown
|
| 275 |
+
if self._maxsize == -1 or self.qsize() < self._maxsize:
|
| 276 |
+
# there's a free slot, put an item right away.
|
| 277 |
+
# For compatibility with CPython, verify that the timeout is non-negative.
|
| 278 |
+
if block and timeout is not None and timeout < 0:
|
| 279 |
+
raise ValueError("'timeout' must be a non-negative number")
|
| 280 |
+
self._put(item)
|
| 281 |
+
if self.getters:
|
| 282 |
+
self._schedule_unlock()
|
| 283 |
+
return
|
| 284 |
+
|
| 285 |
+
if self.hub is getcurrent(): # pylint:disable=undefined-variable
|
| 286 |
+
# We're in the mainloop, so we cannot wait; we can switch to other greenlets though.
|
| 287 |
+
# Check if possible to get a free slot in the queue.
|
| 288 |
+
while self.getters and self.qsize() and self.qsize() >= self._maxsize:
|
| 289 |
+
getter = self.getters.popleft()
|
| 290 |
+
getter.switch(getter)
|
| 291 |
+
if self.qsize() < self._maxsize:
|
| 292 |
+
self._put(item)
|
| 293 |
+
return
|
| 294 |
+
raise Full
|
| 295 |
+
|
| 296 |
+
if block:
|
| 297 |
+
waiter = ItemWaiter(item, self)
|
| 298 |
+
self.putters.append(waiter)
|
| 299 |
+
timeout = Timeout._start_new_or_dummy(timeout, Full)
|
| 300 |
+
try:
|
| 301 |
+
if self.getters:
|
| 302 |
+
self._schedule_unlock()
|
| 303 |
+
result = waiter.get()
|
| 304 |
+
if result is not waiter:
|
| 305 |
+
raise InvalidSwitchError("Invalid switch into Queue.put: %r" % (result, ))
|
| 306 |
+
finally:
|
| 307 |
+
timeout.cancel()
|
| 308 |
+
_safe_remove(self.putters, waiter)
|
| 309 |
+
return
|
| 310 |
+
|
| 311 |
+
raise Full
|
| 312 |
+
|
| 313 |
+
def put_nowait(self, item):
|
| 314 |
+
"""Put an item into the queue without blocking.
|
| 315 |
+
|
| 316 |
+
Only enqueue the item if a free slot is immediately available.
|
| 317 |
+
Otherwise raise the :class:`Full` exception.
|
| 318 |
+
"""
|
| 319 |
+
self.put(item, False)
|
| 320 |
+
|
| 321 |
+
def __get_or_peek(self, method, block, timeout):
|
| 322 |
+
# Internal helper method. The `method` should be either
|
| 323 |
+
# self._get when called from self.get() or self._peek when
|
| 324 |
+
# called from self.peek(). Call this after the initial check
|
| 325 |
+
# to see if there are items in the queue.
|
| 326 |
+
|
| 327 |
+
if self.is_shutdown:
|
| 328 |
+
raise ShutDown
|
| 329 |
+
|
| 330 |
+
if block and timeout is not None and timeout < 0:
|
| 331 |
+
raise ValueError("'timeout' must be a non-negative number")
|
| 332 |
+
if self.hub is getcurrent(): # pylint:disable=undefined-variable
|
| 333 |
+
# special case to make get_nowait() or peek_nowait() runnable in the mainloop greenlet
|
| 334 |
+
# there are no items in the queue; try to fix the situation by unlocking putters
|
| 335 |
+
while self.putters:
|
| 336 |
+
# Note: get() used popleft(), peek used pop(); popleft
|
| 337 |
+
# is almost certainly correct.
|
| 338 |
+
self.putters.popleft().put_and_switch()
|
| 339 |
+
if self.qsize():
|
| 340 |
+
return method()
|
| 341 |
+
raise Empty
|
| 342 |
+
|
| 343 |
+
if not block:
|
| 344 |
+
# We can't block, we're not the hub, and we have nothing
|
| 345 |
+
# to return. No choice but to raise the Empty exception.
|
| 346 |
+
#
|
| 347 |
+
# CAUTION: Calling ``q.get(False)`` in a tight loop won't
|
| 348 |
+
# work like it does in CPython where it should eventually
|
| 349 |
+
# let another thread make progress, because there's never
|
| 350 |
+
# a chance to switch greenlets here. We don't sleep()
|
| 351 |
+
# to enforce that, as that would be a significant behaviour
|
| 352 |
+
# change.
|
| 353 |
+
raise Empty
|
| 354 |
+
|
| 355 |
+
waiter = Waiter() # pylint:disable=undefined-variable
|
| 356 |
+
timeout = Timeout._start_new_or_dummy(timeout, Empty)
|
| 357 |
+
try:
|
| 358 |
+
self.getters.append(waiter)
|
| 359 |
+
if self.putters:
|
| 360 |
+
self._schedule_unlock()
|
| 361 |
+
result = waiter.get()
|
| 362 |
+
if result is not waiter:
|
| 363 |
+
raise InvalidSwitchError('Invalid switch into Queue.get: %r' % (result, ))
|
| 364 |
+
return method()
|
| 365 |
+
finally:
|
| 366 |
+
timeout.cancel()
|
| 367 |
+
_safe_remove(self.getters, waiter)
|
| 368 |
+
|
| 369 |
+
def get(self, block=True, timeout=None):
|
| 370 |
+
"""
|
| 371 |
+
Remove and return an item from the queue.
|
| 372 |
+
|
| 373 |
+
If optional args *block* is true and *timeout* is ``None`` (the default),
|
| 374 |
+
block if necessary until an item is available. If *timeout* is a positive number,
|
| 375 |
+
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
|
| 376 |
+
if no item was available within that time. Otherwise (*block* is false), return
|
| 377 |
+
an item if one is immediately available, else raise the :class:`Empty` exception
|
| 378 |
+
(*timeout* is ignored in that case).
|
| 379 |
+
"""
|
| 380 |
+
if self.qsize():
|
| 381 |
+
if self.putters:
|
| 382 |
+
self._schedule_unlock()
|
| 383 |
+
return self._get()
|
| 384 |
+
|
| 385 |
+
return self.__get_or_peek(self._get, block, timeout)
|
| 386 |
+
|
| 387 |
+
def get_nowait(self):
|
| 388 |
+
"""Remove and return an item from the queue without blocking.
|
| 389 |
+
|
| 390 |
+
Only get an item if one is immediately available. Otherwise
|
| 391 |
+
raise the :class:`Empty` exception.
|
| 392 |
+
"""
|
| 393 |
+
return self.get(False)
|
| 394 |
+
|
| 395 |
+
def peek(self, block=True, timeout=None):
|
| 396 |
+
"""Return an item from the queue without removing it.
|
| 397 |
+
|
| 398 |
+
If optional args *block* is true and *timeout* is ``None`` (the default),
|
| 399 |
+
block if necessary until an item is available. If *timeout* is a positive number,
|
| 400 |
+
it blocks at most *timeout* seconds and raises the :class:`Empty` exception
|
| 401 |
+
if no item was available within that time. Otherwise (*block* is false), return
|
| 402 |
+
an item if one is immediately available, else raise the :class:`Empty` exception
|
| 403 |
+
(*timeout* is ignored in that case).
|
| 404 |
+
"""
|
| 405 |
+
if self.qsize():
|
| 406 |
+
# This doesn't schedule an unlock like get() does because we're not
|
| 407 |
+
# actually making any space.
|
| 408 |
+
return self._peek()
|
| 409 |
+
|
| 410 |
+
return self.__get_or_peek(self._peek, block, timeout)
|
| 411 |
+
|
| 412 |
+
def peek_nowait(self):
|
| 413 |
+
"""Return an item from the queue without blocking.
|
| 414 |
+
|
| 415 |
+
Only return an item if one is immediately available. Otherwise
|
| 416 |
+
raise the :class:`Empty` exception.
|
| 417 |
+
"""
|
| 418 |
+
return self.peek(False)
|
| 419 |
+
|
| 420 |
+
def _unlock(self):
|
| 421 |
+
while True:
|
| 422 |
+
repeat = False
|
| 423 |
+
if self.putters and (self._maxsize == -1 or self.qsize() < self._maxsize):
|
| 424 |
+
repeat = True
|
| 425 |
+
try:
|
| 426 |
+
putter = self.putters.popleft()
|
| 427 |
+
self._put(putter.item)
|
| 428 |
+
except: # pylint:disable=bare-except
|
| 429 |
+
putter.throw(*sys.exc_info())
|
| 430 |
+
else:
|
| 431 |
+
putter.switch(putter)
|
| 432 |
+
if self.getters and self.qsize():
|
| 433 |
+
repeat = True
|
| 434 |
+
getter = self.getters.popleft()
|
| 435 |
+
getter.switch(getter)
|
| 436 |
+
if not repeat:
|
| 437 |
+
return
|
| 438 |
+
|
| 439 |
+
def _schedule_unlock(self):
|
| 440 |
+
if not self._event_unlock:
|
| 441 |
+
self._event_unlock = self.hub.loop.run_callback(self._unlock)
|
| 442 |
+
|
| 443 |
+
def __iter__(self):
|
| 444 |
+
return self
|
| 445 |
+
|
| 446 |
+
def __next__(self):
|
| 447 |
+
result = self.get()
|
| 448 |
+
if result is StopIteration:
|
| 449 |
+
raise result
|
| 450 |
+
return result
|
| 451 |
+
|
| 452 |
+
def shutdown(self, immediate=False):
|
| 453 |
+
"""
|
| 454 |
+
"Shut-down the queue, making queue gets and puts raise
|
| 455 |
+
`ShutDown`.
|
| 456 |
+
|
| 457 |
+
By default, gets will only raise once the queue is empty. Set
|
| 458 |
+
*immediate* to True to make gets raise immediately instead.
|
| 459 |
+
|
| 460 |
+
All blocked callers of `put` and `get` will be unblocked.
|
| 461 |
+
|
| 462 |
+
In joinable queues, if *immediate*, a task is marked as done
|
| 463 |
+
for each item remaining in the queue, which may unblock
|
| 464 |
+
callers of `join`.
|
| 465 |
+
"""
|
| 466 |
+
self.is_shutdown = True
|
| 467 |
+
if immediate:
|
| 468 |
+
self._drain_for_immediate_shutdown()
|
| 469 |
+
getters = list(self.getters)
|
| 470 |
+
putters = list(self.putters)
|
| 471 |
+
self.getters.clear()
|
| 472 |
+
self.putters.clear()
|
| 473 |
+
for waiter in getters + putters:
|
| 474 |
+
self.hub.loop.run_callback(waiter.throw, ShutDown)
|
| 475 |
+
|
| 476 |
+
def _drain_for_immediate_shutdown(self):
|
| 477 |
+
while self.qsize():
|
| 478 |
+
self.get()
|
| 479 |
+
|
| 480 |
+
class UnboundQueue(Queue):
|
| 481 |
+
# A specialization of Queue that knows it can never
|
| 482 |
+
# be bound. Changing its maxsize has no effect.
|
| 483 |
+
|
| 484 |
+
__slots__ = ()
|
| 485 |
+
|
| 486 |
+
def __init__(self, maxsize=None, items=()):
|
| 487 |
+
if maxsize is not None:
|
| 488 |
+
raise ValueError("UnboundQueue has no maxsize")
|
| 489 |
+
Queue.__init__(self, maxsize, items)
|
| 490 |
+
self.putters = None # Will never be used.
|
| 491 |
+
|
| 492 |
+
def put(self, item, block=True, timeout=None):
|
| 493 |
+
self._put(item)
|
| 494 |
+
if self.getters:
|
| 495 |
+
self._schedule_unlock()
|
| 496 |
+
|
| 497 |
+
|
| 498 |
+
class PriorityQueue(Queue):
|
| 499 |
+
'''A subclass of :class:`Queue` that retrieves entries in priority order (lowest first).
|
| 500 |
+
|
| 501 |
+
Entries are typically tuples of the form: ``(priority number, data)``.
|
| 502 |
+
|
| 503 |
+
.. versionchanged:: 1.2a1
|
| 504 |
+
Any *items* given to the constructor will now be passed through
|
| 505 |
+
:func:`heapq.heapify` to ensure the invariants of this class hold.
|
| 506 |
+
Previously it was just assumed that they were already a heap.
|
| 507 |
+
'''
|
| 508 |
+
|
| 509 |
+
__slots__ = ()
|
| 510 |
+
|
| 511 |
+
def _create_queue(self, items=()):
|
| 512 |
+
q = list(items)
|
| 513 |
+
_heapify(q)
|
| 514 |
+
return q
|
| 515 |
+
|
| 516 |
+
def _put(self, item):
|
| 517 |
+
_heappush(self.queue, item)
|
| 518 |
+
|
| 519 |
+
def _get(self):
|
| 520 |
+
return _heappop(self.queue)
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class JoinableQueue(Queue):
|
| 524 |
+
"""
|
| 525 |
+
A subclass of :class:`Queue` that additionally has
|
| 526 |
+
:meth:`task_done` and :meth:`join` methods.
|
| 527 |
+
"""
|
| 528 |
+
|
| 529 |
+
__slots__ = (
|
| 530 |
+
'_cond',
|
| 531 |
+
'unfinished_tasks',
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
def __init__(self, maxsize=None, items=(), unfinished_tasks=None):
|
| 535 |
+
"""
|
| 536 |
+
|
| 537 |
+
.. versionchanged:: 1.1a1
|
| 538 |
+
If *unfinished_tasks* is not given, then all the given *items*
|
| 539 |
+
(if any) will be considered unfinished.
|
| 540 |
+
|
| 541 |
+
"""
|
| 542 |
+
Queue.__init__(self, maxsize, items, _warn_depth=3)
|
| 543 |
+
|
| 544 |
+
from gevent.event import Event
|
| 545 |
+
self._cond = Event()
|
| 546 |
+
self._cond.set()
|
| 547 |
+
|
| 548 |
+
if unfinished_tasks:
|
| 549 |
+
self.unfinished_tasks = unfinished_tasks
|
| 550 |
+
elif items:
|
| 551 |
+
self.unfinished_tasks = len(items)
|
| 552 |
+
else:
|
| 553 |
+
self.unfinished_tasks = 0
|
| 554 |
+
|
| 555 |
+
if self.unfinished_tasks:
|
| 556 |
+
self._cond.clear()
|
| 557 |
+
|
| 558 |
+
def copy(self):
|
| 559 |
+
return type(self)(self.maxsize, self.queue, self.unfinished_tasks)
|
| 560 |
+
|
| 561 |
+
def _format(self):
|
| 562 |
+
result = Queue._format(self)
|
| 563 |
+
if self.unfinished_tasks:
|
| 564 |
+
result += ' tasks=%s _cond=%s' % (self.unfinished_tasks, self._cond)
|
| 565 |
+
return result
|
| 566 |
+
|
| 567 |
+
def _put(self, item):
|
| 568 |
+
Queue._put(self, item)
|
| 569 |
+
self._did_put_task()
|
| 570 |
+
|
| 571 |
+
def _did_put_task(self):
|
| 572 |
+
self.unfinished_tasks += 1
|
| 573 |
+
self._cond.clear()
|
| 574 |
+
|
| 575 |
+
def task_done(self):
|
| 576 |
+
'''Indicate that a formerly enqueued task is complete. Used by queue consumer threads.
|
| 577 |
+
For each :meth:`get <Queue.get>` used to fetch a task, a subsequent call to :meth:`task_done` tells the queue
|
| 578 |
+
that the processing on the task is complete.
|
| 579 |
+
|
| 580 |
+
If a :meth:`join` is currently blocking, it will resume when all items have been processed
|
| 581 |
+
(meaning that a :meth:`task_done` call was received for every item that had been
|
| 582 |
+
:meth:`put <Queue.put>` into the queue).
|
| 583 |
+
|
| 584 |
+
Raises a :exc:`ValueError` if called more times than there were items placed in the queue.
|
| 585 |
+
'''
|
| 586 |
+
if self.unfinished_tasks <= 0:
|
| 587 |
+
raise ValueError('task_done() called too many times')
|
| 588 |
+
self.unfinished_tasks -= 1
|
| 589 |
+
if self.unfinished_tasks == 0:
|
| 590 |
+
self._cond.set()
|
| 591 |
+
|
| 592 |
+
def join(self, timeout=None):
|
| 593 |
+
'''
|
| 594 |
+
Block until all items in the queue have been gotten and processed.
|
| 595 |
+
|
| 596 |
+
The count of unfinished tasks goes up whenever an item is added to the queue.
|
| 597 |
+
The count goes down whenever a consumer thread calls :meth:`task_done` to indicate
|
| 598 |
+
that the item was retrieved and all work on it is complete. When the count of
|
| 599 |
+
unfinished tasks drops to zero, :meth:`join` unblocks.
|
| 600 |
+
|
| 601 |
+
:param float timeout: If not ``None``, then wait no more than this time in seconds
|
| 602 |
+
for all tasks to finish.
|
| 603 |
+
:return: ``True`` if all tasks have finished; if ``timeout`` was given and expired before
|
| 604 |
+
all tasks finished, ``False``.
|
| 605 |
+
|
| 606 |
+
.. versionchanged:: 1.1a1
|
| 607 |
+
Add the *timeout* parameter.
|
| 608 |
+
'''
|
| 609 |
+
return self._cond.wait(timeout=timeout)
|
| 610 |
+
|
| 611 |
+
def _drain_for_immediate_shutdown(self):
|
| 612 |
+
while self.qsize():
|
| 613 |
+
self.get()
|
| 614 |
+
self.task_done()
|
| 615 |
+
|
| 616 |
+
|
| 617 |
+
class LifoQueue(JoinableQueue):
|
| 618 |
+
"""
|
| 619 |
+
A subclass of :class:`JoinableQueue` that retrieves most recently added entries first.
|
| 620 |
+
|
| 621 |
+
.. versionchanged:: 24.10.1
|
| 622 |
+
Now extends :class:`JoinableQueue` instead of just :class:`Queue`.
|
| 623 |
+
|
| 624 |
+
"""
|
| 625 |
+
__slots__ = ()
|
| 626 |
+
|
| 627 |
+
def _create_queue(self, items=()):
|
| 628 |
+
return list(items)
|
| 629 |
+
|
| 630 |
+
def _put(self, item):
|
| 631 |
+
self.queue.append(item)
|
| 632 |
+
self._did_put_task()
|
| 633 |
+
|
| 634 |
+
def _get(self):
|
| 635 |
+
return self.queue.pop()
|
| 636 |
+
|
| 637 |
+
def _peek(self):
|
| 638 |
+
return self.queue[-1]
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
class Channel(object):
|
| 642 |
+
|
| 643 |
+
__slots__ = (
|
| 644 |
+
'getters',
|
| 645 |
+
'putters',
|
| 646 |
+
'hub',
|
| 647 |
+
'_event_unlock',
|
| 648 |
+
'__weakref__',
|
| 649 |
+
)
|
| 650 |
+
|
| 651 |
+
def __init__(self, maxsize=1):
|
| 652 |
+
# We take maxsize to simplify certain kinds of code
|
| 653 |
+
if maxsize != 1:
|
| 654 |
+
raise ValueError("Channels have a maxsize of 1")
|
| 655 |
+
self.getters = collections.deque()
|
| 656 |
+
self.putters = collections.deque()
|
| 657 |
+
self.hub = get_hub()
|
| 658 |
+
self._event_unlock = None
|
| 659 |
+
|
| 660 |
+
def __repr__(self):
|
| 661 |
+
return '<%s at %s %s>' % (type(self).__name__, hex(id(self)), self._format())
|
| 662 |
+
|
| 663 |
+
def __str__(self):
|
| 664 |
+
return '<%s %s>' % (type(self).__name__, self._format())
|
| 665 |
+
|
| 666 |
+
def _format(self):
|
| 667 |
+
result = ''
|
| 668 |
+
if self.getters:
|
| 669 |
+
result += ' getters[%s]' % len(self.getters)
|
| 670 |
+
if self.putters:
|
| 671 |
+
result += ' putters[%s]' % len(self.putters)
|
| 672 |
+
return result
|
| 673 |
+
|
| 674 |
+
@property
|
| 675 |
+
def balance(self):
|
| 676 |
+
return len(self.putters) - len(self.getters)
|
| 677 |
+
|
| 678 |
+
def qsize(self):
|
| 679 |
+
return 0
|
| 680 |
+
|
| 681 |
+
def empty(self):
|
| 682 |
+
return True
|
| 683 |
+
|
| 684 |
+
def full(self):
|
| 685 |
+
return True
|
| 686 |
+
|
| 687 |
+
def put(self, item, block=True, timeout=None):
|
| 688 |
+
if self.hub is getcurrent(): # pylint:disable=undefined-variable
|
| 689 |
+
if self.getters:
|
| 690 |
+
getter = self.getters.popleft()
|
| 691 |
+
getter.switch(item)
|
| 692 |
+
return
|
| 693 |
+
raise Full
|
| 694 |
+
|
| 695 |
+
if not block:
|
| 696 |
+
timeout = 0
|
| 697 |
+
|
| 698 |
+
waiter = Waiter() # pylint:disable=undefined-variable
|
| 699 |
+
item = (item, waiter)
|
| 700 |
+
self.putters.append(item)
|
| 701 |
+
timeout = Timeout._start_new_or_dummy(timeout, Full)
|
| 702 |
+
try:
|
| 703 |
+
if self.getters:
|
| 704 |
+
self._schedule_unlock()
|
| 705 |
+
result = waiter.get()
|
| 706 |
+
if result is not waiter:
|
| 707 |
+
raise InvalidSwitchError("Invalid switch into Channel.put: %r" % (result, ))
|
| 708 |
+
except:
|
| 709 |
+
_safe_remove(self.putters, item)
|
| 710 |
+
raise
|
| 711 |
+
finally:
|
| 712 |
+
timeout.cancel()
|
| 713 |
+
|
| 714 |
+
def put_nowait(self, item):
|
| 715 |
+
self.put(item, False)
|
| 716 |
+
|
| 717 |
+
def get(self, block=True, timeout=None):
|
| 718 |
+
if self.hub is getcurrent(): # pylint:disable=undefined-variable
|
| 719 |
+
if self.putters:
|
| 720 |
+
item, putter = self.putters.popleft()
|
| 721 |
+
self.hub.loop.run_callback(putter.switch, putter)
|
| 722 |
+
return item
|
| 723 |
+
|
| 724 |
+
if not block:
|
| 725 |
+
timeout = 0
|
| 726 |
+
|
| 727 |
+
waiter = Waiter() # pylint:disable=undefined-variable
|
| 728 |
+
timeout = Timeout._start_new_or_dummy(timeout, Empty)
|
| 729 |
+
try:
|
| 730 |
+
self.getters.append(waiter)
|
| 731 |
+
if self.putters:
|
| 732 |
+
self._schedule_unlock()
|
| 733 |
+
return waiter.get()
|
| 734 |
+
except:
|
| 735 |
+
self.getters.remove(waiter)
|
| 736 |
+
raise
|
| 737 |
+
finally:
|
| 738 |
+
timeout.close()
|
| 739 |
+
|
| 740 |
+
def get_nowait(self):
|
| 741 |
+
return self.get(False)
|
| 742 |
+
|
| 743 |
+
def _unlock(self):
|
| 744 |
+
while self.putters and self.getters:
|
| 745 |
+
getter = self.getters.popleft()
|
| 746 |
+
item, putter = self.putters.popleft()
|
| 747 |
+
getter.switch(item)
|
| 748 |
+
putter.switch(putter)
|
| 749 |
+
|
| 750 |
+
def _schedule_unlock(self):
|
| 751 |
+
if not self._event_unlock:
|
| 752 |
+
self._event_unlock = self.hub.loop.run_callback(self._unlock)
|
| 753 |
+
|
| 754 |
+
def __iter__(self):
|
| 755 |
+
return self
|
| 756 |
+
|
| 757 |
+
def __next__(self):
|
| 758 |
+
result = self.get()
|
| 759 |
+
if result is StopIteration:
|
| 760 |
+
raise result
|
| 761 |
+
return result
|
| 762 |
+
|
| 763 |
+
next = __next__ # Py2
|
| 764 |
+
|
| 765 |
+
def _init():
|
| 766 |
+
greenlet_init() # pylint:disable=undefined-variable
|
| 767 |
+
|
| 768 |
+
_init()
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
from gevent._util import import_c_accel
|
| 772 |
+
import_c_accel(globals(), 'gevent._queue')
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/__init__.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2018 gevent contributors. See LICENSE for details.
|
| 2 |
+
|
| 3 |
+
import _socket
|
| 4 |
+
from _socket import AF_INET
|
| 5 |
+
from _socket import AF_UNSPEC
|
| 6 |
+
from _socket import AI_CANONNAME
|
| 7 |
+
from _socket import AI_PASSIVE
|
| 8 |
+
from _socket import AI_NUMERICHOST
|
| 9 |
+
from _socket import EAI_NONAME
|
| 10 |
+
from _socket import EAI_SERVICE
|
| 11 |
+
from _socket import SOCK_DGRAM
|
| 12 |
+
from _socket import SOCK_STREAM
|
| 13 |
+
from _socket import SOL_TCP
|
| 14 |
+
from _socket import error
|
| 15 |
+
from _socket import gaierror
|
| 16 |
+
from _socket import getaddrinfo as native_getaddrinfo
|
| 17 |
+
from _socket import getnameinfo as native_getnameinfo
|
| 18 |
+
from _socket import gethostbyaddr as native_gethostbyaddr
|
| 19 |
+
from _socket import gethostbyname as native_gethostbyname
|
| 20 |
+
from _socket import gethostbyname_ex as native_gethostbyname_ex
|
| 21 |
+
from _socket import getservbyname as native_getservbyname
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
from gevent._compat import string_types
|
| 25 |
+
from gevent._compat import text_type
|
| 26 |
+
from gevent._compat import hostname_types
|
| 27 |
+
from gevent._compat import integer_types
|
| 28 |
+
from gevent._compat import PYPY
|
| 29 |
+
from gevent._compat import MAC
|
| 30 |
+
|
| 31 |
+
from gevent.resolver._addresses import is_ipv6_addr
|
| 32 |
+
# Nothing public here.
|
| 33 |
+
__all__ = ()
|
| 34 |
+
|
| 35 |
+
# trigger import of encodings.idna to avoid https://github.com/gevent/gevent/issues/349
|
| 36 |
+
u'foo'.encode('idna')
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _lookup_port(port, socktype):
|
| 40 |
+
# pylint:disable=too-many-branches
|
| 41 |
+
socktypes = []
|
| 42 |
+
if isinstance(port, string_types):
|
| 43 |
+
try:
|
| 44 |
+
port = int(port)
|
| 45 |
+
except ValueError:
|
| 46 |
+
try:
|
| 47 |
+
if socktype == 0:
|
| 48 |
+
origport = port
|
| 49 |
+
try:
|
| 50 |
+
port = native_getservbyname(port, 'tcp')
|
| 51 |
+
socktypes.append(SOCK_STREAM)
|
| 52 |
+
except error:
|
| 53 |
+
port = native_getservbyname(port, 'udp')
|
| 54 |
+
socktypes.append(SOCK_DGRAM)
|
| 55 |
+
else:
|
| 56 |
+
try:
|
| 57 |
+
if port == native_getservbyname(origport, 'udp'):
|
| 58 |
+
socktypes.append(SOCK_DGRAM)
|
| 59 |
+
except error:
|
| 60 |
+
pass
|
| 61 |
+
elif socktype == SOCK_STREAM:
|
| 62 |
+
port = native_getservbyname(port, 'tcp')
|
| 63 |
+
elif socktype == SOCK_DGRAM:
|
| 64 |
+
port = native_getservbyname(port, 'udp')
|
| 65 |
+
else:
|
| 66 |
+
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
|
| 67 |
+
except error as ex:
|
| 68 |
+
if 'not found' in str(ex):
|
| 69 |
+
raise gaierror(EAI_SERVICE, 'Servname not supported for ai_socktype')
|
| 70 |
+
raise gaierror(str(ex))
|
| 71 |
+
except UnicodeEncodeError:
|
| 72 |
+
raise error('Int or String expected', port)
|
| 73 |
+
elif port is None:
|
| 74 |
+
port = 0
|
| 75 |
+
elif isinstance(port, integer_types):
|
| 76 |
+
pass
|
| 77 |
+
else:
|
| 78 |
+
raise error('Int or String expected', port, type(port))
|
| 79 |
+
port = int(port % 65536)
|
| 80 |
+
if not socktypes and socktype:
|
| 81 |
+
socktypes.append(socktype)
|
| 82 |
+
return port, socktypes
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _resolve_special(hostname, family):
|
| 87 |
+
if not isinstance(hostname, hostname_types):
|
| 88 |
+
raise TypeError("argument 1 must be str, bytes or bytearray, not %s" % (type(hostname),))
|
| 89 |
+
|
| 90 |
+
if hostname in (u'', b''):
|
| 91 |
+
result = native_getaddrinfo(None, 0, family, SOCK_DGRAM, 0, AI_PASSIVE)
|
| 92 |
+
if len(result) != 1:
|
| 93 |
+
raise error('wildcard resolved to multiple address')
|
| 94 |
+
return result[0][4][0]
|
| 95 |
+
return hostname
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
class AbstractResolver(object):
|
| 99 |
+
|
| 100 |
+
HOSTNAME_ENCODING = 'idna'
|
| 101 |
+
|
| 102 |
+
_LOCAL_HOSTNAMES = (
|
| 103 |
+
b'localhost',
|
| 104 |
+
b'ip6-localhost',
|
| 105 |
+
b'::1',
|
| 106 |
+
b'127.0.0.1',
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
_LOCAL_AND_BROADCAST_HOSTNAMES = _LOCAL_HOSTNAMES + (
|
| 110 |
+
b'255.255.255.255',
|
| 111 |
+
b'<broadcast>',
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
EAI_NONAME_MSG = (
|
| 115 |
+
'nodename nor servname provided, or not known'
|
| 116 |
+
if MAC else
|
| 117 |
+
'Name or service not known'
|
| 118 |
+
)
|
| 119 |
+
|
| 120 |
+
EAI_FAMILY_MSG = (
|
| 121 |
+
'ai_family not supported'
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
_KNOWN_ADDR_FAMILIES = {
|
| 125 |
+
v
|
| 126 |
+
for k, v in vars(_socket).items()
|
| 127 |
+
if k.startswith('AF_')
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
_KNOWN_SOCKTYPES = {
|
| 131 |
+
v
|
| 132 |
+
for k, v in vars(_socket).items()
|
| 133 |
+
if k.startswith('SOCK_')
|
| 134 |
+
and k not in ('SOCK_CLOEXEC', 'SOCK_MAX_SIZE')
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
def close(self):
|
| 138 |
+
"""
|
| 139 |
+
Release resources held by this object.
|
| 140 |
+
|
| 141 |
+
Subclasses that define resources should override.
|
| 142 |
+
|
| 143 |
+
.. versionadded:: 22.10.1
|
| 144 |
+
"""
|
| 145 |
+
|
| 146 |
+
@staticmethod
|
| 147 |
+
def fixup_gaierror(func):
|
| 148 |
+
import functools
|
| 149 |
+
|
| 150 |
+
@functools.wraps(func)
|
| 151 |
+
def resolve(self, *args, **kwargs):
|
| 152 |
+
try:
|
| 153 |
+
return func(self, *args, **kwargs)
|
| 154 |
+
except gaierror as ex:
|
| 155 |
+
if ex.args[0] == EAI_NONAME and len(ex.args) == 1:
|
| 156 |
+
# dnspython doesn't set an error message
|
| 157 |
+
ex.args = (EAI_NONAME, self.EAI_NONAME_MSG)
|
| 158 |
+
ex.errno = EAI_NONAME
|
| 159 |
+
raise
|
| 160 |
+
return resolve
|
| 161 |
+
|
| 162 |
+
def _hostname_to_bytes(self, hostname):
|
| 163 |
+
if isinstance(hostname, text_type):
|
| 164 |
+
hostname = hostname.encode(self.HOSTNAME_ENCODING)
|
| 165 |
+
elif not isinstance(hostname, (bytes, bytearray)):
|
| 166 |
+
raise TypeError('Expected str, bytes or bytearray, not %s' % type(hostname).__name__)
|
| 167 |
+
|
| 168 |
+
return bytes(hostname)
|
| 169 |
+
|
| 170 |
+
def gethostbyname(self, hostname, family=AF_INET):
|
| 171 |
+
# The native ``gethostbyname`` and ``gethostbyname_ex`` have some different
|
| 172 |
+
# behaviour with special names. Notably, ``gethostbyname`` will handle
|
| 173 |
+
# both "<broadcast>" and "255.255.255.255", while ``gethostbyname_ex`` refuses to
|
| 174 |
+
# handle those; they result in different errors, too. So we can't
|
| 175 |
+
# pass those through.
|
| 176 |
+
hostname = self._hostname_to_bytes(hostname)
|
| 177 |
+
if hostname in self._LOCAL_AND_BROADCAST_HOSTNAMES:
|
| 178 |
+
return native_gethostbyname(hostname)
|
| 179 |
+
hostname = _resolve_special(hostname, family)
|
| 180 |
+
return self.gethostbyname_ex(hostname, family)[-1][0]
|
| 181 |
+
|
| 182 |
+
def _gethostbyname_ex(self, hostname_bytes, family):
|
| 183 |
+
"""Raise an ``herror`` or a ``gaierror``."""
|
| 184 |
+
aliases = self._getaliases(hostname_bytes, family)
|
| 185 |
+
addresses = []
|
| 186 |
+
tuples = self.getaddrinfo(hostname_bytes, 0, family,
|
| 187 |
+
SOCK_STREAM,
|
| 188 |
+
SOL_TCP, AI_CANONNAME)
|
| 189 |
+
canonical = tuples[0][3]
|
| 190 |
+
for item in tuples:
|
| 191 |
+
addresses.append(item[4][0])
|
| 192 |
+
# XXX we just ignore aliases
|
| 193 |
+
return (canonical, aliases, addresses)
|
| 194 |
+
|
| 195 |
+
def gethostbyname_ex(self, hostname, family=AF_INET):
|
| 196 |
+
hostname = self._hostname_to_bytes(hostname)
|
| 197 |
+
if hostname in self._LOCAL_AND_BROADCAST_HOSTNAMES:
|
| 198 |
+
# The broadcast specials aren't handled here, but they may produce
|
| 199 |
+
# special errors that are hard to replicate across all systems.
|
| 200 |
+
return native_gethostbyname_ex(hostname)
|
| 201 |
+
return self._gethostbyname_ex(hostname, family)
|
| 202 |
+
|
| 203 |
+
def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags):
|
| 204 |
+
raise NotImplementedError
|
| 205 |
+
|
| 206 |
+
def getaddrinfo(self, host, port, family=0, socktype=0, proto=0, flags=0):
|
| 207 |
+
host = self._hostname_to_bytes(host) if host is not None else None
|
| 208 |
+
|
| 209 |
+
if (
|
| 210 |
+
not isinstance(host, bytes) # 1, 2
|
| 211 |
+
or (flags & AI_NUMERICHOST) # 3
|
| 212 |
+
or host in self._LOCAL_HOSTNAMES # 4
|
| 213 |
+
or (is_ipv6_addr(host) and host.startswith(b'fe80')) # 5
|
| 214 |
+
):
|
| 215 |
+
# This handles cases which do not require network access
|
| 216 |
+
# 1) host is None
|
| 217 |
+
# 2) host is of an invalid type
|
| 218 |
+
# 3) AI_NUMERICHOST flag is set
|
| 219 |
+
# 4) It's a well-known alias. TODO: This is special casing for c-ares that we don't
|
| 220 |
+
# really want to do. It's here because it resolves a discrepancy with the system
|
| 221 |
+
# resolvers caught by test cases. In gevent 20.4.0, this only worked correctly on
|
| 222 |
+
# Python 3 and not Python 2, by accident.
|
| 223 |
+
# 5) host is a link-local ipv6; dnspython returns the wrong
|
| 224 |
+
# scope-id for those.
|
| 225 |
+
return native_getaddrinfo(host, port, family, socktype, proto, flags)
|
| 226 |
+
|
| 227 |
+
return self._getaddrinfo(host, port, family, socktype, proto, flags)
|
| 228 |
+
|
| 229 |
+
def _getaliases(self, hostname, family):
|
| 230 |
+
# pylint:disable=unused-argument
|
| 231 |
+
return []
|
| 232 |
+
|
| 233 |
+
def _gethostbyaddr(self, ip_address_bytes):
|
| 234 |
+
"""Raises herror."""
|
| 235 |
+
raise NotImplementedError
|
| 236 |
+
|
| 237 |
+
def gethostbyaddr(self, ip_address):
|
| 238 |
+
ip_address = _resolve_special(ip_address, AF_UNSPEC)
|
| 239 |
+
ip_address = self._hostname_to_bytes(ip_address)
|
| 240 |
+
if ip_address in self._LOCAL_AND_BROADCAST_HOSTNAMES:
|
| 241 |
+
return native_gethostbyaddr(ip_address)
|
| 242 |
+
|
| 243 |
+
return self._gethostbyaddr(ip_address)
|
| 244 |
+
|
| 245 |
+
def _getnameinfo(self, address_bytes, port, sockaddr, flags):
|
| 246 |
+
raise NotImplementedError
|
| 247 |
+
|
| 248 |
+
def getnameinfo(self, sockaddr, flags):
|
| 249 |
+
if not isinstance(flags, integer_types):
|
| 250 |
+
raise TypeError('an integer is required')
|
| 251 |
+
if not isinstance(sockaddr, tuple):
|
| 252 |
+
raise TypeError('getnameinfo() argument 1 must be a tuple')
|
| 253 |
+
|
| 254 |
+
address = sockaddr[0]
|
| 255 |
+
address = self._hostname_to_bytes(sockaddr[0])
|
| 256 |
+
|
| 257 |
+
if address in self._LOCAL_AND_BROADCAST_HOSTNAMES:
|
| 258 |
+
return native_getnameinfo(sockaddr, flags)
|
| 259 |
+
|
| 260 |
+
port = sockaddr[1]
|
| 261 |
+
if not isinstance(port, integer_types):
|
| 262 |
+
raise TypeError('port must be an integer, not %s' % type(port))
|
| 263 |
+
|
| 264 |
+
if not PYPY and port >= 65536:
|
| 265 |
+
# System resolvers do different things with an
|
| 266 |
+
# out-of-bound port; macOS CPython 3.8 raises ``gaierror: [Errno 8]
|
| 267 |
+
# nodename nor servname provided, or not known``, while
|
| 268 |
+
# manylinux CPython 2.7 appears to ignore it and raises ``error:
|
| 269 |
+
# sockaddr resolved to multiple addresses``. TravisCI, at least ot
|
| 270 |
+
# one point, successfully resolved www.gevent.org to ``(readthedocs.org, '0')``.
|
| 271 |
+
# But c-ares 1.16 would raise ``gaierror(25, 'ARES_ESERVICE: unknown')``.
|
| 272 |
+
# Doing this appears to get the expected results on CPython
|
| 273 |
+
port = 0
|
| 274 |
+
if PYPY and (port < 0 or port >= 65536):
|
| 275 |
+
# PyPy seems to always be strict about that and produce the same results
|
| 276 |
+
# on all platforms.
|
| 277 |
+
raise OverflowError("port must be 0-65535.")
|
| 278 |
+
|
| 279 |
+
if len(sockaddr) > 2:
|
| 280 |
+
# Must be IPv6: (host, port, [flowinfo, [scopeid]])
|
| 281 |
+
flowinfo = sockaddr[2]
|
| 282 |
+
if flowinfo > 0xfffff:
|
| 283 |
+
raise OverflowError("getnameinfo(): flowinfo must be 0-1048575.")
|
| 284 |
+
|
| 285 |
+
return self._getnameinfo(address,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2019 gevent contributors. See LICENSE for details.
|
| 3 |
+
#
|
| 4 |
+
# Portions of this code taken from dnspython
|
| 5 |
+
# https://github.com/rthalley/dnspython
|
| 6 |
+
#
|
| 7 |
+
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
|
| 8 |
+
|
| 9 |
+
# Copyright (C) 2003-2017 Nominum, Inc.
|
| 10 |
+
#
|
| 11 |
+
# Permission to use, copy, modify, and distribute this software and its
|
| 12 |
+
# documentation for any purpose with or without fee is hereby granted,
|
| 13 |
+
# provided that the above copyright notice and this permission notice
|
| 14 |
+
# appear in all copies.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
|
| 17 |
+
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
| 18 |
+
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
|
| 19 |
+
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
| 20 |
+
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
| 21 |
+
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 22 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 23 |
+
"""
|
| 24 |
+
Private support for parsing textual addresses.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import absolute_import, division, print_function
|
| 28 |
+
|
| 29 |
+
import binascii
|
| 30 |
+
import re
|
| 31 |
+
import struct
|
| 32 |
+
|
| 33 |
+
from gevent.resolver import hostname_types
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class AddressSyntaxError(ValueError):
|
| 37 |
+
pass
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _ipv4_inet_aton(text):
|
| 41 |
+
"""
|
| 42 |
+
Convert an IPv4 address in text form to binary struct.
|
| 43 |
+
|
| 44 |
+
*text*, a ``text``, the IPv4 address in textual form.
|
| 45 |
+
|
| 46 |
+
Returns a ``binary``.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
if not isinstance(text, bytes):
|
| 50 |
+
text = text.encode()
|
| 51 |
+
parts = text.split(b'.')
|
| 52 |
+
if len(parts) != 4:
|
| 53 |
+
raise AddressSyntaxError(text)
|
| 54 |
+
for part in parts:
|
| 55 |
+
if not part.isdigit():
|
| 56 |
+
raise AddressSyntaxError
|
| 57 |
+
if len(part) > 1 and part[0] == '0':
|
| 58 |
+
# No leading zeros
|
| 59 |
+
raise AddressSyntaxError(text)
|
| 60 |
+
try:
|
| 61 |
+
ints = [int(part) for part in parts]
|
| 62 |
+
return struct.pack('BBBB', *ints)
|
| 63 |
+
except:
|
| 64 |
+
raise AddressSyntaxError(text)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _ipv6_inet_aton(text,
|
| 68 |
+
_v4_ending=re.compile(br'(.*):(\d+\.\d+\.\d+\.\d+)$'),
|
| 69 |
+
_colon_colon_start=re.compile(br'::.*'),
|
| 70 |
+
_colon_colon_end=re.compile(br'.*::$')):
|
| 71 |
+
"""
|
| 72 |
+
Convert an IPv6 address in text form to binary form.
|
| 73 |
+
|
| 74 |
+
*text*, a ``text``, the IPv6 address in textual form.
|
| 75 |
+
|
| 76 |
+
Returns a ``binary``.
|
| 77 |
+
"""
|
| 78 |
+
# pylint:disable=too-many-branches
|
| 79 |
+
|
| 80 |
+
#
|
| 81 |
+
# Our aim here is not something fast; we just want something that works.
|
| 82 |
+
#
|
| 83 |
+
if not isinstance(text, bytes):
|
| 84 |
+
text = text.encode()
|
| 85 |
+
|
| 86 |
+
if text == b'::':
|
| 87 |
+
text = b'0::'
|
| 88 |
+
#
|
| 89 |
+
# Get rid of the icky dot-quad syntax if we have it.
|
| 90 |
+
#
|
| 91 |
+
m = _v4_ending.match(text)
|
| 92 |
+
if not m is None:
|
| 93 |
+
b = bytearray(_ipv4_inet_aton(m.group(2)))
|
| 94 |
+
text = (u"{}:{:02x}{:02x}:{:02x}{:02x}".format(m.group(1).decode(),
|
| 95 |
+
b[0], b[1], b[2],
|
| 96 |
+
b[3])).encode()
|
| 97 |
+
#
|
| 98 |
+
# Try to turn '::<whatever>' into ':<whatever>'; if no match try to
|
| 99 |
+
# turn '<whatever>::' into '<whatever>:'
|
| 100 |
+
#
|
| 101 |
+
m = _colon_colon_start.match(text)
|
| 102 |
+
if not m is None:
|
| 103 |
+
text = text[1:]
|
| 104 |
+
else:
|
| 105 |
+
m = _colon_colon_end.match(text)
|
| 106 |
+
if not m is None:
|
| 107 |
+
text = text[:-1]
|
| 108 |
+
#
|
| 109 |
+
# Now canonicalize into 8 chunks of 4 hex digits each
|
| 110 |
+
#
|
| 111 |
+
chunks = text.split(b':')
|
| 112 |
+
l = len(chunks)
|
| 113 |
+
if l > 8:
|
| 114 |
+
raise SyntaxError
|
| 115 |
+
seen_empty = False
|
| 116 |
+
canonical = []
|
| 117 |
+
for c in chunks:
|
| 118 |
+
if c == b'':
|
| 119 |
+
if seen_empty:
|
| 120 |
+
raise AddressSyntaxError(text)
|
| 121 |
+
seen_empty = True
|
| 122 |
+
for _ in range(0, 8 - l + 1):
|
| 123 |
+
canonical.append(b'0000')
|
| 124 |
+
else:
|
| 125 |
+
lc = len(c)
|
| 126 |
+
if lc > 4:
|
| 127 |
+
raise AddressSyntaxError(text)
|
| 128 |
+
if lc != 4:
|
| 129 |
+
c = (b'0' * (4 - lc)) + c
|
| 130 |
+
canonical.append(c)
|
| 131 |
+
if l < 8 and not seen_empty:
|
| 132 |
+
raise AddressSyntaxError(text)
|
| 133 |
+
text = b''.join(canonical)
|
| 134 |
+
|
| 135 |
+
#
|
| 136 |
+
# Finally we can go to binary.
|
| 137 |
+
#
|
| 138 |
+
try:
|
| 139 |
+
return binascii.unhexlify(text)
|
| 140 |
+
except (binascii.Error, TypeError):
|
| 141 |
+
raise AddressSyntaxError(text)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _is_addr(host, parse=_ipv4_inet_aton):
|
| 145 |
+
if not host or not isinstance(host, hostname_types):
|
| 146 |
+
return False
|
| 147 |
+
|
| 148 |
+
try:
|
| 149 |
+
parse(host)
|
| 150 |
+
except AddressSyntaxError:
|
| 151 |
+
return False
|
| 152 |
+
return True
|
| 153 |
+
|
| 154 |
+
# Return True if host is a valid IPv4 address
|
| 155 |
+
is_ipv4_addr = _is_addr
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def is_ipv6_addr(host):
|
| 159 |
+
# Return True if host is a valid IPv6 address
|
| 160 |
+
if host and isinstance(host, hostname_types):
|
| 161 |
+
s = '%' if isinstance(host, str) else b'%'
|
| 162 |
+
host = host.split(s, 1)[0]
|
| 163 |
+
return _is_addr(host, _ipv6_inet_aton)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/_hostsfile.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
# Copyright (c) 2019 gevent contributors. See LICENSE for details.
|
| 3 |
+
#
|
| 4 |
+
# Portions of this code taken from dnspython
|
| 5 |
+
# https://github.com/rthalley/dnspython
|
| 6 |
+
#
|
| 7 |
+
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license
|
| 8 |
+
|
| 9 |
+
# Copyright (C) 2003-2017 Nominum, Inc.
|
| 10 |
+
#
|
| 11 |
+
# Permission to use, copy, modify, and distribute this software and its
|
| 12 |
+
# documentation for any purpose with or without fee is hereby granted,
|
| 13 |
+
# provided that the above copyright notice and this permission notice
|
| 14 |
+
# appear in all copies.
|
| 15 |
+
#
|
| 16 |
+
# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES
|
| 17 |
+
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
| 18 |
+
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR
|
| 19 |
+
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
| 20 |
+
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
| 21 |
+
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT
|
| 22 |
+
# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
| 23 |
+
"""
|
| 24 |
+
Private support for parsing /etc/hosts.
|
| 25 |
+
|
| 26 |
+
"""
|
| 27 |
+
from __future__ import absolute_import, division, print_function
|
| 28 |
+
|
| 29 |
+
import sys
|
| 30 |
+
import os
|
| 31 |
+
import re
|
| 32 |
+
|
| 33 |
+
from gevent.resolver._addresses import is_ipv4_addr
|
| 34 |
+
from gevent.resolver._addresses import is_ipv6_addr
|
| 35 |
+
|
| 36 |
+
from gevent._compat import iteritems
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class HostsFile(object):
|
| 40 |
+
"""
|
| 41 |
+
A class to read the contents of a hosts file (/etc/hosts).
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
LINES_RE = re.compile(r"""
|
| 45 |
+
\s* # Leading space
|
| 46 |
+
([^\r\n#]+?) # The actual match, non-greedy so as not to include trailing space
|
| 47 |
+
\s* # Trailing space
|
| 48 |
+
(?:[#][^\r\n]+)? # Comments
|
| 49 |
+
(?:$|[\r\n]+) # EOF or newline
|
| 50 |
+
""", re.VERBOSE)
|
| 51 |
+
|
| 52 |
+
def __init__(self, fname=None):
|
| 53 |
+
self.v4 = {} # name -> ipv4
|
| 54 |
+
self.v6 = {} # name -> ipv6
|
| 55 |
+
self.aliases = {} # name -> canonical_name
|
| 56 |
+
self.reverse = {} # ip addr -> some name
|
| 57 |
+
if fname is None:
|
| 58 |
+
if os.name == 'posix':
|
| 59 |
+
fname = '/etc/hosts'
|
| 60 |
+
elif os.name == 'nt': # pragma: no cover
|
| 61 |
+
fname = os.path.expandvars(
|
| 62 |
+
r'%SystemRoot%\system32\drivers\etc\hosts')
|
| 63 |
+
self.fname = fname
|
| 64 |
+
assert self.fname
|
| 65 |
+
self._last_load = 0
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _readlines(self):
|
| 69 |
+
# Read the contents of the hosts file.
|
| 70 |
+
#
|
| 71 |
+
# Return list of lines, comment lines and empty lines are
|
| 72 |
+
# excluded. Note that this performs disk I/O so can be
|
| 73 |
+
# blocking.
|
| 74 |
+
with open(self.fname, 'rb') as fp:
|
| 75 |
+
fdata = fp.read()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
# XXX: Using default decoding. Is that correct?
|
| 79 |
+
udata = fdata.decode(errors='ignore') if not isinstance(fdata, str) else fdata
|
| 80 |
+
|
| 81 |
+
return self.LINES_RE.findall(udata)
|
| 82 |
+
|
| 83 |
+
def load(self): # pylint:disable=too-many-locals
|
| 84 |
+
# Load hosts file
|
| 85 |
+
|
| 86 |
+
# This will (re)load the data from the hosts
|
| 87 |
+
# file if it has changed.
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
load_time = os.stat(self.fname).st_mtime
|
| 91 |
+
needs_load = load_time > self._last_load
|
| 92 |
+
except OSError:
|
| 93 |
+
from gevent import get_hub
|
| 94 |
+
get_hub().handle_error(self, *sys.exc_info())
|
| 95 |
+
needs_load = False
|
| 96 |
+
|
| 97 |
+
if not needs_load:
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
v4 = {}
|
| 101 |
+
v6 = {}
|
| 102 |
+
aliases = {}
|
| 103 |
+
reverse = {}
|
| 104 |
+
|
| 105 |
+
for line in self._readlines():
|
| 106 |
+
parts = line.split()
|
| 107 |
+
if len(parts) < 2:
|
| 108 |
+
continue
|
| 109 |
+
ip = parts.pop(0)
|
| 110 |
+
if is_ipv4_addr(ip):
|
| 111 |
+
ipmap = v4
|
| 112 |
+
elif is_ipv6_addr(ip):
|
| 113 |
+
if ip.startswith('fe80'):
|
| 114 |
+
# Do not use link-local addresses, OSX stores these here
|
| 115 |
+
continue
|
| 116 |
+
ipmap = v6
|
| 117 |
+
else:
|
| 118 |
+
continue
|
| 119 |
+
cname = parts.pop(0).lower()
|
| 120 |
+
ipmap[cname] = ip
|
| 121 |
+
for alias in parts:
|
| 122 |
+
alias = alias.lower()
|
| 123 |
+
ipmap[alias] = ip
|
| 124 |
+
aliases[alias] = cname
|
| 125 |
+
|
| 126 |
+
# XXX: This is wrong for ipv6
|
| 127 |
+
if ipmap is v4:
|
| 128 |
+
ptr = '.'.join(reversed(ip.split('.'))) + '.in-addr.arpa'
|
| 129 |
+
else:
|
| 130 |
+
ptr = ip + '.ip6.arpa.'
|
| 131 |
+
if ptr not in reverse:
|
| 132 |
+
reverse[ptr] = cname
|
| 133 |
+
|
| 134 |
+
self._last_load = load_time
|
| 135 |
+
self.v4 = v4
|
| 136 |
+
self.v6 = v6
|
| 137 |
+
self.aliases = aliases
|
| 138 |
+
self.reverse = reverse
|
| 139 |
+
|
| 140 |
+
def iter_all_host_addr_pairs(self):
|
| 141 |
+
self.load()
|
| 142 |
+
for name, addr in iteritems(self.v4):
|
| 143 |
+
yield name, addr
|
| 144 |
+
for name, addr in iteritems(self.v6):
|
| 145 |
+
yield name, addr
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/ares.py
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2011-2015 Denis Bilenko. See LICENSE for details.
|
| 2 |
+
"""
|
| 3 |
+
c-ares based hostname resolver.
|
| 4 |
+
"""
|
| 5 |
+
from __future__ import absolute_import, print_function, division
|
| 6 |
+
import os
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
from _socket import gaierror
|
| 10 |
+
from _socket import herror
|
| 11 |
+
from _socket import error
|
| 12 |
+
from _socket import EAI_NONAME
|
| 13 |
+
|
| 14 |
+
from gevent._compat import text_type
|
| 15 |
+
from gevent._compat import integer_types
|
| 16 |
+
|
| 17 |
+
from gevent.hub import Waiter
|
| 18 |
+
from gevent.hub import get_hub
|
| 19 |
+
|
| 20 |
+
from gevent.socket import AF_UNSPEC
|
| 21 |
+
from gevent.socket import AF_INET
|
| 22 |
+
from gevent.socket import AF_INET6
|
| 23 |
+
from gevent.socket import SOCK_DGRAM
|
| 24 |
+
from gevent.socket import SOCK_STREAM
|
| 25 |
+
from gevent.socket import SOL_TCP
|
| 26 |
+
from gevent.socket import SOL_UDP
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
from gevent._config import config
|
| 30 |
+
from gevent._config import AresSettingMixin
|
| 31 |
+
|
| 32 |
+
from .cares import channel, InvalidIP # pylint:disable=import-error,no-name-in-module
|
| 33 |
+
from . import _lookup_port as lookup_port
|
| 34 |
+
from . import AbstractResolver
|
| 35 |
+
|
| 36 |
+
__all__ = ['Resolver']
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class Resolver(AbstractResolver):
|
| 40 |
+
"""
|
| 41 |
+
Implementation of the resolver API using the `c-ares`_ library.
|
| 42 |
+
|
| 43 |
+
This implementation uses the c-ares library to handle name
|
| 44 |
+
resolution. c-ares is natively asynchronous at the socket level
|
| 45 |
+
and so integrates well into gevent's event loop.
|
| 46 |
+
|
| 47 |
+
In comparison to :class:`gevent.resolver_thread.Resolver` (which
|
| 48 |
+
delegates to the native system resolver), the implementation is
|
| 49 |
+
much more complex. In addition, there have been reports of it not
|
| 50 |
+
properly honoring certain system configurations (for example, the
|
| 51 |
+
order in which IPv4 and IPv6 results are returned may not match
|
| 52 |
+
the threaded resolver). However, because it does not use threads,
|
| 53 |
+
it may scale better for applications that make many lookups.
|
| 54 |
+
|
| 55 |
+
There are some known differences from the system resolver.
|
| 56 |
+
|
| 57 |
+
- ``gethostbyname_ex`` and ``gethostbyaddr`` may return
|
| 58 |
+
different for the ``aliaslist`` tuple member. (Sometimes the
|
| 59 |
+
same, sometimes in a different order, sometimes a different
|
| 60 |
+
alias altogether.)
|
| 61 |
+
|
| 62 |
+
- ``gethostbyname_ex`` may return the ``ipaddrlist`` in a
|
| 63 |
+
different order.
|
| 64 |
+
|
| 65 |
+
- ``getaddrinfo`` does not return ``SOCK_RAW`` results.
|
| 66 |
+
|
| 67 |
+
- ``getaddrinfo`` may return results in a different order.
|
| 68 |
+
|
| 69 |
+
- Handling of ``.local`` (mDNS) names may be different, even
|
| 70 |
+
if they are listed in the hosts file.
|
| 71 |
+
|
| 72 |
+
- c-ares will not resolve ``broadcasthost``, even if listed in
|
| 73 |
+
the hosts file prior to 2020-04-30.
|
| 74 |
+
|
| 75 |
+
- This implementation may raise ``gaierror(4)`` where the
|
| 76 |
+
system implementation would raise ``herror(1)`` or vice versa,
|
| 77 |
+
with different error numbers. However, after 2020-04-30, this should be
|
| 78 |
+
much reduced.
|
| 79 |
+
|
| 80 |
+
- The results for ``localhost`` may be different. In
|
| 81 |
+
particular, some system resolvers will return more results
|
| 82 |
+
from ``getaddrinfo`` than c-ares does, such as SOCK_DGRAM
|
| 83 |
+
results, and c-ares may report more ips on a multi-homed
|
| 84 |
+
host.
|
| 85 |
+
|
| 86 |
+
- The system implementation may return some names fully qualified, where
|
| 87 |
+
this implementation returns only the host name. This appears to be
|
| 88 |
+
the case only with entries found in ``/etc/hosts``.
|
| 89 |
+
|
| 90 |
+
- c-ares supports a limited set of flags for ``getnameinfo`` and
|
| 91 |
+
``getaddrinfo``; unknown flags are ignored. System-specific flags
|
| 92 |
+
such as ``AI_V4MAPPED_CFG`` are not supported.
|
| 93 |
+
|
| 94 |
+
- ``getaddrinfo`` may return canonical names even without the ``AI_CANONNAME``
|
| 95 |
+
being set.
|
| 96 |
+
|
| 97 |
+
- ``getaddrinfo`` does not appear to support IPv6 symbolic scope IDs.
|
| 98 |
+
|
| 99 |
+
.. caution::
|
| 100 |
+
|
| 101 |
+
This module is considered extremely experimental on PyPy, and
|
| 102 |
+
due to its implementation in cython, it may be slower. It may also lead to
|
| 103 |
+
interpreter crashes.
|
| 104 |
+
|
| 105 |
+
.. versionchanged:: 1.5.0
|
| 106 |
+
This version of gevent typically embeds c-ares 1.15.0 or newer. In
|
| 107 |
+
that version of c-ares, domains ending in ``.onion`` `are never
|
| 108 |
+
resolved <https://github.com/c-ares/c-ares/issues/196>`_ or even
|
| 109 |
+
sent to the DNS server.
|
| 110 |
+
|
| 111 |
+
.. versionchanged:: 20.5.0
|
| 112 |
+
``getaddrinfo`` is now implemented using the native c-ares function
|
| 113 |
+
from c-ares 1.16 or newer.
|
| 114 |
+
|
| 115 |
+
.. versionchanged:: 20.5.0
|
| 116 |
+
Now ``herror`` and ``gaierror`` are raised more consistently with
|
| 117 |
+
the standard library resolver, and have more consistent errno values.
|
| 118 |
+
|
| 119 |
+
Handling of localhost and broadcast names is now more consistent.
|
| 120 |
+
|
| 121 |
+
.. versionchanged:: 22.10.1
|
| 122 |
+
Now has a ``__del__`` method that warns if the object is destroyed
|
| 123 |
+
without being properly closed.
|
| 124 |
+
|
| 125 |
+
.. _c-ares: http://c-ares.haxx.se
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
cares_class = channel
|
| 129 |
+
|
| 130 |
+
def __init__(self, hub=None, use_environ=True, **kwargs):
|
| 131 |
+
AbstractResolver.__init__(self)
|
| 132 |
+
if hub is None:
|
| 133 |
+
hub = get_hub()
|
| 134 |
+
self.hub = hub
|
| 135 |
+
if use_environ:
|
| 136 |
+
for setting in config.settings.values():
|
| 137 |
+
if isinstance(setting, AresSettingMixin):
|
| 138 |
+
value = setting.get()
|
| 139 |
+
if value is not None:
|
| 140 |
+
kwargs.setdefault(setting.kwarg_name, value)
|
| 141 |
+
self.cares = self.cares_class(hub.loop, **kwargs)
|
| 142 |
+
self.pid = os.getpid()
|
| 143 |
+
self.params = kwargs
|
| 144 |
+
self.fork_watcher = hub.loop.fork(ref=False) # We shouldn't keep the loop alive
|
| 145 |
+
self.fork_watcher.start(self._on_fork)
|
| 146 |
+
|
| 147 |
+
def __repr__(self):
|
| 148 |
+
return '<gevent.resolver_ares.Resolver at 0x%x ares=%r>' % (id(self), self.cares)
|
| 149 |
+
|
| 150 |
+
def _on_fork(self):
|
| 151 |
+
# NOTE: See comment in gevent.hub.reinit.
|
| 152 |
+
pid = os.getpid()
|
| 153 |
+
if pid != self.pid:
|
| 154 |
+
self.hub.loop.run_callback(self.cares.destroy)
|
| 155 |
+
self.cares = self.cares_class(self.hub.loop, **self.params)
|
| 156 |
+
self.pid = pid
|
| 157 |
+
|
| 158 |
+
def close(self):
|
| 159 |
+
AbstractResolver.close(self)
|
| 160 |
+
if self.cares is not None:
|
| 161 |
+
self.hub.loop.run_callback(self.cares.destroy)
|
| 162 |
+
self.cares = None
|
| 163 |
+
self.fork_watcher.stop()
|
| 164 |
+
|
| 165 |
+
def __del__(self):
|
| 166 |
+
if self.cares is not None:
|
| 167 |
+
warnings.warn("cares Resolver destroyed while not closed",
|
| 168 |
+
ResourceWarning)
|
| 169 |
+
self.close()
|
| 170 |
+
|
| 171 |
+
def _gethostbyname_ex(self, hostname_bytes, family):
|
| 172 |
+
while True:
|
| 173 |
+
ares = self.cares
|
| 174 |
+
try:
|
| 175 |
+
waiter = Waiter(self.hub)
|
| 176 |
+
ares.gethostbyname(waiter, hostname_bytes, family)
|
| 177 |
+
result = waiter.get()
|
| 178 |
+
if not result[-1]:
|
| 179 |
+
raise herror(EAI_NONAME, self.EAI_NONAME_MSG)
|
| 180 |
+
return result
|
| 181 |
+
except herror as ex:
|
| 182 |
+
if ares is self.cares:
|
| 183 |
+
if ex.args[0] == 1:
|
| 184 |
+
# Somewhere along the line, the internal
|
| 185 |
+
# implementation of gethostbyname_ex changed to invoke
|
| 186 |
+
# getaddrinfo() as a first pass, much like we do for ``getnameinfo()``;
|
| 187 |
+
# this means it raises a different error for not-found hosts.
|
| 188 |
+
raise gaierror(EAI_NONAME, self.EAI_NONAME_MSG)
|
| 189 |
+
raise
|
| 190 |
+
# "self.cares is not ares" means channel was destroyed (because we were forked)
|
| 191 |
+
|
| 192 |
+
def _lookup_port(self, port, socktype):
|
| 193 |
+
return lookup_port(port, socktype)
|
| 194 |
+
|
| 195 |
+
def __getaddrinfo(
|
| 196 |
+
self, host, port,
|
| 197 |
+
family=0, socktype=0, proto=0, flags=0,
|
| 198 |
+
fill_in_type_proto=True
|
| 199 |
+
):
|
| 200 |
+
"""
|
| 201 |
+
Returns a list ``(family, socktype, proto, canonname, sockaddr)``
|
| 202 |
+
|
| 203 |
+
:raises gaierror: If no results are found.
|
| 204 |
+
"""
|
| 205 |
+
# pylint:disable=too-many-locals,too-many-branches
|
| 206 |
+
if isinstance(host, text_type):
|
| 207 |
+
host = host.encode('idna')
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if isinstance(port, text_type):
|
| 211 |
+
port = port.encode('ascii')
|
| 212 |
+
elif isinstance(port, integer_types):
|
| 213 |
+
if port == 0:
|
| 214 |
+
port = None
|
| 215 |
+
else:
|
| 216 |
+
port = str(port).encode('ascii')
|
| 217 |
+
|
| 218 |
+
waiter = Waiter(self.hub)
|
| 219 |
+
self.cares.getaddrinfo(
|
| 220 |
+
waiter,
|
| 221 |
+
host,
|
| 222 |
+
port,
|
| 223 |
+
family,
|
| 224 |
+
socktype,
|
| 225 |
+
proto,
|
| 226 |
+
flags,
|
| 227 |
+
)
|
| 228 |
+
# Result is a list of:
|
| 229 |
+
# (family, socktype, proto, canonname, sockaddr)
|
| 230 |
+
# Where sockaddr depends on family; for INET it is
|
| 231 |
+
# (address, port)
|
| 232 |
+
# and INET6 is
|
| 233 |
+
# (address, port, flow info, scope id)
|
| 234 |
+
result = waiter.get()
|
| 235 |
+
|
| 236 |
+
if not result:
|
| 237 |
+
raise gaierror(EAI_NONAME, self.EAI_NONAME_MSG)
|
| 238 |
+
|
| 239 |
+
if fill_in_type_proto:
|
| 240 |
+
# c-ares 1.16 DOES NOT fill in socktype or proto in the results,
|
| 241 |
+
# ever. It's at least supposed to do that if they were given as
|
| 242 |
+
# hints, but it doesn't (https://github.com/c-ares/c-ares/issues/317)
|
| 243 |
+
# Sigh.
|
| 244 |
+
# The SOL_* constants are another (older?) name for IPPROTO_*
|
| 245 |
+
if socktype:
|
| 246 |
+
hard_type_proto = [
|
| 247 |
+
(socktype, SOL_TCP if socktype == SOCK_STREAM else SOL_UDP),
|
| 248 |
+
]
|
| 249 |
+
elif proto:
|
| 250 |
+
hard_type_proto = [
|
| 251 |
+
(SOCK_STREAM if proto == SOL_TCP else SOCK_DGRAM, proto),
|
| 252 |
+
]
|
| 253 |
+
else:
|
| 254 |
+
hard_type_proto = [
|
| 255 |
+
(SOCK_STREAM, SOL_TCP),
|
| 256 |
+
(SOCK_DGRAM, SOL_UDP),
|
| 257 |
+
]
|
| 258 |
+
|
| 259 |
+
# pylint:disable=not-an-iterable,unsubscriptable-object
|
| 260 |
+
result = [
|
| 261 |
+
(rfamily,
|
| 262 |
+
hard_type if not rtype else rtype,
|
| 263 |
+
hard_proto if not rproto else rproto,
|
| 264 |
+
rcanon,
|
| 265 |
+
raddr)
|
| 266 |
+
for rfamily, rtype, rproto, rcanon, raddr
|
| 267 |
+
in result
|
| 268 |
+
for hard_type, hard_proto
|
| 269 |
+
in hard_type_proto
|
| 270 |
+
]
|
| 271 |
+
return result
|
| 272 |
+
|
| 273 |
+
def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags):
|
| 274 |
+
while True:
|
| 275 |
+
ares = self.cares
|
| 276 |
+
try:
|
| 277 |
+
return self.__getaddrinfo(host_bytes, port, family, socktype, proto, flags)
|
| 278 |
+
except gaierror:
|
| 279 |
+
if ares is self.cares:
|
| 280 |
+
raise
|
| 281 |
+
|
| 282 |
+
def __gethostbyaddr(self, ip_address):
|
| 283 |
+
waiter = Waiter(self.hub)
|
| 284 |
+
try:
|
| 285 |
+
self.cares.gethostbyaddr(waiter, ip_address)
|
| 286 |
+
return waiter.get()
|
| 287 |
+
except InvalidIP:
|
| 288 |
+
result = self._getaddrinfo(ip_address, None,
|
| 289 |
+
family=AF_UNSPEC, socktype=SOCK_DGRAM,
|
| 290 |
+
proto=0, flags=0)
|
| 291 |
+
if not result:
|
| 292 |
+
raise
|
| 293 |
+
# pylint:disable=unsubscriptable-object
|
| 294 |
+
_ip_address = result[0][-1][0]
|
| 295 |
+
if isinstance(_ip_address, text_type):
|
| 296 |
+
_ip_address = _ip_address.encode('ascii')
|
| 297 |
+
if _ip_address == ip_address:
|
| 298 |
+
raise
|
| 299 |
+
waiter.clear()
|
| 300 |
+
self.cares.gethostbyaddr(waiter, _ip_address)
|
| 301 |
+
return waiter.get()
|
| 302 |
+
|
| 303 |
+
def _gethostbyaddr(self, ip_address_bytes):
|
| 304 |
+
while True:
|
| 305 |
+
ares = self.cares
|
| 306 |
+
try:
|
| 307 |
+
return self.__gethostbyaddr(ip_address_bytes)
|
| 308 |
+
except herror:
|
| 309 |
+
if ares is self.cares:
|
| 310 |
+
raise
|
| 311 |
+
|
| 312 |
+
def __getnameinfo(self, hostname, port, sockaddr, flags):
|
| 313 |
+
result = self.__getaddrinfo(
|
| 314 |
+
hostname, port,
|
| 315 |
+
family=AF_UNSPEC, socktype=SOCK_DGRAM,
|
| 316 |
+
proto=0, flags=0,
|
| 317 |
+
fill_in_type_proto=False)
|
| 318 |
+
if len(result) != 1:
|
| 319 |
+
raise error('sockaddr resolved to multiple addresses')
|
| 320 |
+
|
| 321 |
+
family, _socktype, _proto, _name, address = result[0]
|
| 322 |
+
|
| 323 |
+
if family == AF_INET:
|
| 324 |
+
if len(sockaddr) != 2:
|
| 325 |
+
raise error("IPv4 sockaddr must be 2 tuple")
|
| 326 |
+
elif family == AF_INET6:
|
| 327 |
+
address = address[:2] + sockaddr[2:]
|
| 328 |
+
|
| 329 |
+
waiter = Waiter(self.hub)
|
| 330 |
+
self.cares.getnameinfo(waiter, address, flags)
|
| 331 |
+
node, service = waiter.get()
|
| 332 |
+
|
| 333 |
+
if service is None:
|
| 334 |
+
# ares docs: "If the query did not complete
|
| 335 |
+
# successfully, or one of the values was not
|
| 336 |
+
# requested, node or service will be NULL ". Python 2
|
| 337 |
+
# allows that for the service, but Python 3 raises
|
| 338 |
+
# an error. This is tested by test_socket in py 3.4
|
| 339 |
+
err = gaierror(EAI_NONAME, self.EAI_NONAME_MSG)
|
| 340 |
+
err.errno = EAI_NONAME
|
| 341 |
+
raise err
|
| 342 |
+
|
| 343 |
+
return node, service or '0'
|
| 344 |
+
|
| 345 |
+
def _getnameinfo(self, address_bytes, port, sockaddr, flags):
|
| 346 |
+
while True:
|
| 347 |
+
ares = self.cares
|
| 348 |
+
try:
|
| 349 |
+
return self.__getnameinfo(address_bytes, port, sockaddr, flags)
|
| 350 |
+
except gaierror:
|
| 351 |
+
if ares is self.cares:
|
| 352 |
+
raise
|
| 353 |
+
|
| 354 |
+
# # Things that need proper error handling
|
| 355 |
+
# gethostbyaddr = AbstractResolver.convert_gaierror_to_herror(AbstractResolver.gethostbyaddr)
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/blocking.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2018 gevent contributors. See LICENSE for details.
|
| 2 |
+
|
| 3 |
+
import _socket
|
| 4 |
+
|
| 5 |
+
__all__ = [
|
| 6 |
+
'Resolver',
|
| 7 |
+
]
|
| 8 |
+
|
| 9 |
+
class Resolver(object):
|
| 10 |
+
"""
|
| 11 |
+
A resolver that directly uses the system's resolver functions.
|
| 12 |
+
|
| 13 |
+
.. caution::
|
| 14 |
+
|
| 15 |
+
This resolver is *not* cooperative.
|
| 16 |
+
|
| 17 |
+
This resolver has the lowest overhead of any resolver and
|
| 18 |
+
typically approaches the speed of the unmodified :mod:`socket`
|
| 19 |
+
functions. However, it is not cooperative, so if name resolution
|
| 20 |
+
blocks, the entire thread and all its greenlets will be blocked.
|
| 21 |
+
|
| 22 |
+
This can be useful during debugging, or it may be a good choice if
|
| 23 |
+
your operating system provides a good caching resolver (such as
|
| 24 |
+
macOS's Directory Services) that is usually very fast and
|
| 25 |
+
functionally non-blocking.
|
| 26 |
+
|
| 27 |
+
.. versionchanged:: 1.3a2
|
| 28 |
+
This was previously undocumented and existed in :mod:`gevent.socket`.
|
| 29 |
+
|
| 30 |
+
"""
|
| 31 |
+
|
| 32 |
+
def __init__(self, hub=None):
|
| 33 |
+
pass
|
| 34 |
+
|
| 35 |
+
def close(self):
|
| 36 |
+
pass
|
| 37 |
+
|
| 38 |
+
for method in (
|
| 39 |
+
'gethostbyname',
|
| 40 |
+
'gethostbyname_ex',
|
| 41 |
+
'getaddrinfo',
|
| 42 |
+
'gethostbyaddr',
|
| 43 |
+
'getnameinfo'
|
| 44 |
+
):
|
| 45 |
+
locals()[method] = staticmethod(getattr(_socket, method))
|
miniconda3/envs/ladir/lib/python3.10/site-packages/gevent/resolver/dnspython.py
ADDED
|
@@ -0,0 +1,511 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2018 gevent contributors. See LICENSE for details.
|
| 2 |
+
|
| 3 |
+
# Portions of this code taken from the gogreen project:
|
| 4 |
+
# http://github.com/slideinc/gogreen
|
| 5 |
+
#
|
| 6 |
+
# Copyright (c) 2005-2010 Slide, Inc.
|
| 7 |
+
# All rights reserved.
|
| 8 |
+
#
|
| 9 |
+
# Redistribution and use in source and binary forms, with or without
|
| 10 |
+
# modification, are permitted provided that the following conditions are
|
| 11 |
+
# met:
|
| 12 |
+
#
|
| 13 |
+
# * Redistributions of source code must retain the above copyright
|
| 14 |
+
# notice, this list of conditions and the following disclaimer.
|
| 15 |
+
# * Redistributions in binary form must reproduce the above
|
| 16 |
+
# copyright notice, this list of conditions and the following
|
| 17 |
+
# disclaimer in the documentation and/or other materials provided
|
| 18 |
+
# with the distribution.
|
| 19 |
+
# * Neither the name of the author nor the names of other
|
| 20 |
+
# contributors may be used to endorse or promote products derived
|
| 21 |
+
# from this software without specific prior written permission.
|
| 22 |
+
#
|
| 23 |
+
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 24 |
+
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 25 |
+
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 26 |
+
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 27 |
+
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 28 |
+
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
| 29 |
+
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
| 30 |
+
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
| 31 |
+
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
| 32 |
+
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
| 33 |
+
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 34 |
+
|
| 35 |
+
# Portions of this code taken from the eventlet project:
|
| 36 |
+
# https://github.com/eventlet/eventlet/blob/master/eventlet/support/greendns.py
|
| 37 |
+
|
| 38 |
+
# Unless otherwise noted, the files in Eventlet are under the following MIT license:
|
| 39 |
+
|
| 40 |
+
# Copyright (c) 2005-2006, Bob Ippolito
|
| 41 |
+
# Copyright (c) 2007-2010, Linden Research, Inc.
|
| 42 |
+
# Copyright (c) 2008-2010, Eventlet Contributors (see AUTHORS)
|
| 43 |
+
|
| 44 |
+
# Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 45 |
+
# of this software and associated documentation files (the "Software"), to deal
|
| 46 |
+
# in the Software without restriction, including without limitation the rights
|
| 47 |
+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 48 |
+
# copies of the Software, and to permit persons to whom the Software is
|
| 49 |
+
# furnished to do so, subject to the following conditions:
|
| 50 |
+
|
| 51 |
+
# The above copyright notice and this permission notice shall be included in
|
| 52 |
+
# all copies or substantial portions of the Software.
|
| 53 |
+
|
| 54 |
+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 55 |
+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 56 |
+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 57 |
+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 58 |
+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 59 |
+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
| 60 |
+
# THE SOFTWARE.
|
| 61 |
+
from __future__ import absolute_import, print_function, division
|
| 62 |
+
|
| 63 |
+
import sys
|
| 64 |
+
import time
|
| 65 |
+
|
| 66 |
+
from _socket import error
|
| 67 |
+
from _socket import gaierror
|
| 68 |
+
from _socket import herror
|
| 69 |
+
from _socket import NI_NUMERICSERV
|
| 70 |
+
from _socket import AF_INET
|
| 71 |
+
from _socket import AF_INET6
|
| 72 |
+
from _socket import AF_UNSPEC
|
| 73 |
+
from _socket import EAI_NONAME
|
| 74 |
+
from _socket import EAI_FAMILY
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
import socket
|
| 78 |
+
|
| 79 |
+
from gevent.resolver import AbstractResolver
|
| 80 |
+
from gevent.resolver._hostsfile import HostsFile
|
| 81 |
+
|
| 82 |
+
from gevent.builtins import __import__ as g_import
|
| 83 |
+
|
| 84 |
+
from gevent._compat import string_types
|
| 85 |
+
from gevent._compat import iteritems
|
| 86 |
+
from gevent._config import config
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
__all__ = [
|
| 90 |
+
'Resolver',
|
| 91 |
+
]
|
| 92 |
+
|
| 93 |
+
# Import the DNS packages to use the gevent modules,
|
| 94 |
+
# even if the system is not monkey-patched. If it *is* already
|
| 95 |
+
# patched, this imports a second copy under a different name,
|
| 96 |
+
# which is probably not strictly necessary, but matches
|
| 97 |
+
# what we've historically done, and allows configuring the resolvers
|
| 98 |
+
# differently.
|
| 99 |
+
|
| 100 |
+
def _patch_dns():
|
| 101 |
+
from gevent._patcher import import_patched as importer
|
| 102 |
+
# The dns package itself is empty but defines __all__
|
| 103 |
+
# we make sure to import all of those things now under the
|
| 104 |
+
# patch. Note this triggers two DeprecationWarnings,
|
| 105 |
+
# one of which we could avoid.
|
| 106 |
+
extras = {
|
| 107 |
+
'dns': ('rdata', 'resolver', 'rdtypes'),
|
| 108 |
+
'dns.rdtypes': ('IN', 'ANY', ),
|
| 109 |
+
'dns.rdtypes.IN': ('A', 'AAAA',),
|
| 110 |
+
'dns.rdtypes.ANY': ('SOA', 'PTR'),
|
| 111 |
+
}
|
| 112 |
+
def extra_all(mod_name):
|
| 113 |
+
return extras.get(mod_name, ())
|
| 114 |
+
|
| 115 |
+
def after_import_hook(dns): # pylint:disable=redefined-outer-name
|
| 116 |
+
# Runs while still in the original patching scope.
|
| 117 |
+
# The dns.rdata:get_rdata_class() function tries to
|
| 118 |
+
# dynamically import modules using __import__ and then walk
|
| 119 |
+
# through the attribute tree to find classes in `dns.rdtypes`.
|
| 120 |
+
# It is critical that this all matches up, otherwise we can
|
| 121 |
+
# get different exception classes that don't get caught.
|
| 122 |
+
# We could patch __import__ to do things at runtime, but it's
|
| 123 |
+
# easier to enumerate the world and populate the cache now
|
| 124 |
+
# before we then switch the names back.
|
| 125 |
+
rdata = dns.rdata
|
| 126 |
+
get_rdata_class = rdata.get_rdata_class
|
| 127 |
+
try:
|
| 128 |
+
rdclass_values = list(dns.rdataclass.RdataClass)
|
| 129 |
+
except AttributeError:
|
| 130 |
+
# dnspython < 2.0
|
| 131 |
+
rdclass_values = dns.rdataclass._by_value
|
| 132 |
+
|
| 133 |
+
try:
|
| 134 |
+
rdtype_values = list(dns.rdatatype.RdataType)
|
| 135 |
+
except AttributeError:
|
| 136 |
+
# dnspython < 2.0
|
| 137 |
+
rdtype_values = dns.rdatatype._by_value
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
for rdclass in rdclass_values:
|
| 141 |
+
for rdtype in rdtype_values:
|
| 142 |
+
get_rdata_class(rdclass, rdtype)
|
| 143 |
+
|
| 144 |
+
patcher = importer('dns', extra_all, after_import_hook)
|
| 145 |
+
top = patcher.module
|
| 146 |
+
|
| 147 |
+
# Now disable the dynamic imports
|
| 148 |
+
def _no_dynamic_imports(name):
|
| 149 |
+
raise ValueError(name)
|
| 150 |
+
|
| 151 |
+
top.rdata.__import__ = _no_dynamic_imports
|
| 152 |
+
|
| 153 |
+
return top
|
| 154 |
+
|
| 155 |
+
dns = _patch_dns()
|
| 156 |
+
|
| 157 |
+
resolver = dns.resolver
|
| 158 |
+
dTimeout = dns.resolver.Timeout
|
| 159 |
+
|
| 160 |
+
# This is a wrapper for dns.resolver._getaddrinfo with two crucial changes.
|
| 161 |
+
# First, it backports https://github.com/rthalley/dnspython/issues/316
|
| 162 |
+
# from version 2.0. This can be dropped when we support only dnspython 2
|
| 163 |
+
# (which means only Python 3.)
|
| 164 |
+
|
| 165 |
+
# Second, it adds calls to sys.exc_clear() to avoid failing tests in
|
| 166 |
+
# test__refcount.py (timeouts) on Python 2. (Actually, this isn't
|
| 167 |
+
# strictly necessary, it was necessary to increase the timeouts in
|
| 168 |
+
# that function because dnspython is doing some parsing/regex/host
|
| 169 |
+
# lookups that are not super fast. But it does have a habit of leaving
|
| 170 |
+
# exceptions around which can complicate our memleak checks.)
|
| 171 |
+
def _getaddrinfo(host=None, service=None, family=AF_UNSPEC, socktype=0,
|
| 172 |
+
proto=0, flags=0,
|
| 173 |
+
_orig_gai=resolver._getaddrinfo,
|
| 174 |
+
_exc_clear=getattr(sys, 'exc_clear', lambda: None)):
|
| 175 |
+
if flags & (socket.AI_ADDRCONFIG | socket.AI_V4MAPPED) != 0:
|
| 176 |
+
# Not implemented. We raise a gaierror as opposed to a
|
| 177 |
+
# NotImplementedError as it helps callers handle errors more
|
| 178 |
+
# appropriately. [Issue #316]
|
| 179 |
+
raise socket.gaierror(socket.EAI_SYSTEM)
|
| 180 |
+
res = _orig_gai(host, service, family, socktype, proto, flags)
|
| 181 |
+
_exc_clear()
|
| 182 |
+
return res
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
resolver._getaddrinfo = _getaddrinfo
|
| 186 |
+
|
| 187 |
+
HOSTS_TTL = 300.0
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class _HostsAnswer(dns.resolver.Answer):
|
| 191 |
+
# Answer class for HostsResolver object
|
| 192 |
+
|
| 193 |
+
def __init__(self, qname, rdtype, rdclass, rrset, raise_on_no_answer=True):
|
| 194 |
+
self.response = None
|
| 195 |
+
self.qname = qname
|
| 196 |
+
self.rdtype = rdtype
|
| 197 |
+
self.rdclass = rdclass
|
| 198 |
+
self.canonical_name = qname
|
| 199 |
+
if not rrset and raise_on_no_answer:
|
| 200 |
+
raise dns.resolver.NoAnswer()
|
| 201 |
+
self.rrset = rrset
|
| 202 |
+
self.expiration = (time.time() +
|
| 203 |
+
rrset.ttl if hasattr(rrset, 'ttl') else 0)
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
class _HostsResolver(object):
|
| 207 |
+
"""
|
| 208 |
+
Class to parse the hosts file
|
| 209 |
+
"""
|
| 210 |
+
|
| 211 |
+
def __init__(self, fname=None, interval=HOSTS_TTL):
|
| 212 |
+
self.hosts_file = HostsFile(fname)
|
| 213 |
+
self.interval = interval
|
| 214 |
+
self._last_load = 0
|
| 215 |
+
|
| 216 |
+
def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
|
| 217 |
+
tcp=False, source=None, raise_on_no_answer=True): # pylint:disable=unused-argument
|
| 218 |
+
# Query the hosts file
|
| 219 |
+
#
|
| 220 |
+
# The known rdtypes are dns.rdatatype.A, dns.rdatatype.AAAA and
|
| 221 |
+
# dns.rdatatype.CNAME.
|
| 222 |
+
# The ``rdclass`` parameter must be dns.rdataclass.IN while the
|
| 223 |
+
# ``tcp`` and ``source`` parameters are ignored.
|
| 224 |
+
# Return a HostAnswer instance or raise a dns.resolver.NoAnswer
|
| 225 |
+
# exception.
|
| 226 |
+
|
| 227 |
+
now = time.time()
|
| 228 |
+
hosts_file = self.hosts_file
|
| 229 |
+
if self._last_load + self.interval < now:
|
| 230 |
+
self._last_load = now
|
| 231 |
+
hosts_file.load()
|
| 232 |
+
|
| 233 |
+
rdclass = dns.rdataclass.IN # Always
|
| 234 |
+
if isinstance(qname, string_types):
|
| 235 |
+
name = qname
|
| 236 |
+
qname = dns.name.from_text(qname)
|
| 237 |
+
else:
|
| 238 |
+
name = str(qname)
|
| 239 |
+
|
| 240 |
+
name = name.lower()
|
| 241 |
+
rrset = dns.rrset.RRset(qname, rdclass, rdtype)
|
| 242 |
+
rrset.ttl = self._last_load + self.interval - now
|
| 243 |
+
|
| 244 |
+
mapping = None
|
| 245 |
+
kind = None
|
| 246 |
+
if rdtype == dns.rdatatype.A:
|
| 247 |
+
mapping = hosts_file.v4
|
| 248 |
+
kind = dns.rdtypes.IN.A.A
|
| 249 |
+
elif rdtype == dns.rdatatype.AAAA:
|
| 250 |
+
mapping = hosts_file.v6
|
| 251 |
+
kind = dns.rdtypes.IN.AAAA.AAAA
|
| 252 |
+
elif rdtype == dns.rdatatype.CNAME:
|
| 253 |
+
mapping = hosts_file.aliases
|
| 254 |
+
kind = lambda c, t, addr: dns.rdtypes.ANY.CNAME.CNAME(c, t, dns.name.from_text(addr))
|
| 255 |
+
elif rdtype == dns.rdatatype.PTR:
|
| 256 |
+
mapping = hosts_file.reverse
|
| 257 |
+
kind = lambda c, t, addr: dns.rdtypes.ANY.PTR.PTR(c, t, dns.name.from_text(addr))
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
addr = mapping.get(name)
|
| 261 |
+
if not addr and qname.is_absolute():
|
| 262 |
+
addr = mapping.get(name[:-1])
|
| 263 |
+
if addr:
|
| 264 |
+
rrset.add(kind(rdclass, rdtype, addr))
|
| 265 |
+
return _HostsAnswer(qname, rdtype, rdclass, rrset, raise_on_no_answer)
|
| 266 |
+
|
| 267 |
+
def getaliases(self, hostname):
|
| 268 |
+
# Return a list of all the aliases of a given cname
|
| 269 |
+
|
| 270 |
+
# Due to the way store aliases this is a bit inefficient, this
|
| 271 |
+
# clearly was an afterthought. But this is only used by
|
| 272 |
+
# gethostbyname_ex so it's probably fine.
|
| 273 |
+
aliases = self.hosts_file.aliases
|
| 274 |
+
result = []
|
| 275 |
+
if hostname in aliases: # pylint:disable=consider-using-get
|
| 276 |
+
cannon = aliases[hostname]
|
| 277 |
+
else:
|
| 278 |
+
cannon = hostname
|
| 279 |
+
result.append(cannon)
|
| 280 |
+
for alias, cname in iteritems(aliases):
|
| 281 |
+
if cannon == cname:
|
| 282 |
+
result.append(alias)
|
| 283 |
+
result.remove(hostname)
|
| 284 |
+
return result
|
| 285 |
+
|
| 286 |
+
class _DualResolver(object):
|
| 287 |
+
|
| 288 |
+
def __init__(self):
|
| 289 |
+
self.hosts_resolver = _HostsResolver()
|
| 290 |
+
self.network_resolver = resolver.get_default_resolver()
|
| 291 |
+
self.network_resolver.cache = resolver.LRUCache()
|
| 292 |
+
|
| 293 |
+
def query(self, qname, rdtype=dns.rdatatype.A, rdclass=dns.rdataclass.IN,
|
| 294 |
+
tcp=False, source=None, raise_on_no_answer=True,
|
| 295 |
+
_hosts_rdtypes=(dns.rdatatype.A, dns.rdatatype.AAAA, dns.rdatatype.PTR)):
|
| 296 |
+
# Query the resolver, using /etc/hosts
|
| 297 |
+
|
| 298 |
+
# Behavior:
|
| 299 |
+
# 1. if hosts is enabled and contains answer, return it now
|
| 300 |
+
# 2. query nameservers for qname
|
| 301 |
+
if qname is None:
|
| 302 |
+
qname = '0.0.0.0'
|
| 303 |
+
|
| 304 |
+
if not isinstance(qname, string_types):
|
| 305 |
+
if isinstance(qname, bytes):
|
| 306 |
+
qname = qname.decode("idna")
|
| 307 |
+
|
| 308 |
+
if isinstance(qname, string_types):
|
| 309 |
+
qname = dns.name.from_text(qname, None)
|
| 310 |
+
|
| 311 |
+
if isinstance(rdtype, string_types):
|
| 312 |
+
rdtype = dns.rdatatype.from_text(rdtype)
|
| 313 |
+
|
| 314 |
+
if rdclass == dns.rdataclass.IN and rdtype in _hosts_rdtypes:
|
| 315 |
+
try:
|
| 316 |
+
answer = self.hosts_resolver.query(qname, rdtype, raise_on_no_answer=False)
|
| 317 |
+
except Exception: # pylint: disable=broad-except
|
| 318 |
+
from gevent import get_hub
|
| 319 |
+
get_hub().handle_error(self, *sys.exc_info())
|
| 320 |
+
else:
|
| 321 |
+
if answer.rrset:
|
| 322 |
+
return answer
|
| 323 |
+
|
| 324 |
+
return self.network_resolver.query(qname, rdtype, rdclass,
|
| 325 |
+
tcp, source, raise_on_no_answer=raise_on_no_answer)
|
| 326 |
+
|
| 327 |
+
def _family_to_rdtype(family):
|
| 328 |
+
if family == socket.AF_INET:
|
| 329 |
+
rdtype = dns.rdatatype.A
|
| 330 |
+
elif family == socket.AF_INET6:
|
| 331 |
+
rdtype = dns.rdatatype.AAAA
|
| 332 |
+
else:
|
| 333 |
+
raise socket.gaierror(socket.EAI_FAMILY,
|
| 334 |
+
'Address family not supported')
|
| 335 |
+
return rdtype
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class Resolver(AbstractResolver):
|
| 339 |
+
"""
|
| 340 |
+
An *experimental* resolver that uses `dnspython`_.
|
| 341 |
+
|
| 342 |
+
This is typically slower than the default threaded resolver
|
| 343 |
+
(unless there's a cache hit, in which case it can be much faster).
|
| 344 |
+
It is usually much faster than the c-ares resolver. It tends to
|
| 345 |
+
scale well as more concurrent resolutions are attempted.
|
| 346 |
+
|
| 347 |
+
Under Python 2, if the ``idna`` package is installed, this
|
| 348 |
+
resolver can resolve Unicode host names that the system resolver
|
| 349 |
+
cannot.
|
| 350 |
+
|
| 351 |
+
.. note::
|
| 352 |
+
|
| 353 |
+
This **does not** use dnspython's default resolver object, or share any
|
| 354 |
+
classes with ``import dns``. A separate copy of the objects is imported to
|
| 355 |
+
be able to function in a non monkey-patched process. The documentation for the resolver
|
| 356 |
+
object still applies.
|
| 357 |
+
|
| 358 |
+
The resolver that we use is available as the :attr:`resolver` attribute
|
| 359 |
+
of this object (typically ``gevent.get_hub().resolver.resolver``).
|
| 360 |
+
|
| 361 |
+
.. caution::
|
| 362 |
+
|
| 363 |
+
Many of the same caveats about DNS results apply here as are documented
|
| 364 |
+
for :class:`gevent.resolver.ares.Resolver`. In addition, the handling of
|
| 365 |
+
symbolic scope IDs in IPv6 addresses passed to ``getaddrinfo`` exhibits
|
| 366 |
+
some differences.
|
| 367 |
+
|
| 368 |
+
On PyPy, ``getnameinfo`` can produce results when CPython raises
|
| 369 |
+
``socket.error``, and gevent's DNSPython resolver also
|
| 370 |
+
raises ``socket.error``.
|
| 371 |
+
|
| 372 |
+
.. caution::
|
| 373 |
+
|
| 374 |
+
This resolver is experimental. It may be removed or modified in
|
| 375 |
+
the future. As always, feedback is welcome.
|
| 376 |
+
|
| 377 |
+
.. versionadded:: 1.3a2
|
| 378 |
+
|
| 379 |
+
.. versionchanged:: 20.5.0
|
| 380 |
+
The errors raised are now much more consistent with those
|
| 381 |
+
raised by the standard library resolvers.
|
| 382 |
+
|
| 383 |
+
Handling of localhost and broadcast names is now more consistent.
|
| 384 |
+
|
| 385 |
+
.. _dnspython: http://www.dnspython.org
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
def __init__(self, hub=None): # pylint: disable=unused-argument
|
| 389 |
+
if resolver._resolver is None:
|
| 390 |
+
_resolver = resolver._resolver = _DualResolver()
|
| 391 |
+
if config.resolver_nameservers:
|
| 392 |
+
_resolver.network_resolver.nameservers[:] = config.resolver_nameservers
|
| 393 |
+
if config.resolver_timeout:
|
| 394 |
+
_resolver.network_resolver.lifetime = config.resolver_timeout
|
| 395 |
+
# Different hubs in different threads could be sharing the same
|
| 396 |
+
# resolver.
|
| 397 |
+
assert isinstance(resolver._resolver, _DualResolver)
|
| 398 |
+
self._resolver = resolver._resolver
|
| 399 |
+
|
| 400 |
+
@property
|
| 401 |
+
def resolver(self):
|
| 402 |
+
"""
|
| 403 |
+
The dnspython resolver object we use.
|
| 404 |
+
|
| 405 |
+
This object has several useful attributes that can be used to
|
| 406 |
+
adjust the behaviour of the DNS system:
|
| 407 |
+
|
| 408 |
+
* ``cache`` is a :class:`dns.resolver.LRUCache`. Its maximum size
|
| 409 |
+
can be configured by calling :meth:`resolver.cache.set_max_size`
|
| 410 |
+
* ``nameservers`` controls which nameservers to talk to
|
| 411 |
+
* ``lifetime`` configures a timeout for each individual query.
|
| 412 |
+
"""
|
| 413 |
+
return self._resolver.network_resolver
|
| 414 |
+
|
| 415 |
+
def close(self):
|
| 416 |
+
pass
|
| 417 |
+
|
| 418 |
+
def _getaliases(self, hostname, family):
|
| 419 |
+
if not isinstance(hostname, str):
|
| 420 |
+
if isinstance(hostname, bytes):
|
| 421 |
+
hostname = hostname.decode("idna")
|
| 422 |
+
aliases = self._resolver.hosts_resolver.getaliases(hostname)
|
| 423 |
+
net_resolver = self._resolver.network_resolver
|
| 424 |
+
rdtype = _family_to_rdtype(family)
|
| 425 |
+
while 1:
|
| 426 |
+
try:
|
| 427 |
+
ans = net_resolver.query(hostname, dns.rdatatype.CNAME, rdtype)
|
| 428 |
+
except (dns.resolver.NoAnswer, dns.resolver.NXDOMAIN, dns.resolver.NoNameservers):
|
| 429 |
+
break
|
| 430 |
+
except dTimeout:
|
| 431 |
+
break
|
| 432 |
+
except AttributeError as ex:
|
| 433 |
+
if hostname is None or isinstance(hostname, int):
|
| 434 |
+
raise TypeError(ex)
|
| 435 |
+
raise
|
| 436 |
+
else:
|
| 437 |
+
aliases.extend(str(rr.target) for rr in ans.rrset)
|
| 438 |
+
hostname = ans[0].target
|
| 439 |
+
return aliases
|
| 440 |
+
|
| 441 |
+
def _getaddrinfo(self, host_bytes, port, family, socktype, proto, flags):
|
| 442 |
+
# dnspython really wants the host to be in native format.
|
| 443 |
+
if not isinstance(host_bytes, str):
|
| 444 |
+
host_bytes = host_bytes.decode(self.HOSTNAME_ENCODING)
|
| 445 |
+
|
| 446 |
+
if host_bytes == 'ff02::1de:c0:face:8D':
|
| 447 |
+
# This is essentially a hack to make stdlib
|
| 448 |
+
# test_socket:GeneralModuleTests.test_getaddrinfo_ipv6_basic
|
| 449 |
+
# pass. They expect to get back a lowercase ``D``, but
|
| 450 |
+
# dnspython does not do that.
|
| 451 |
+
# ``test_getaddrinfo_ipv6_scopeid_symbolic`` also expect
|
| 452 |
+
# the scopeid to be dropped, but again, dnspython does not
|
| 453 |
+
# do that; we cant fix that here so we skip that test.
|
| 454 |
+
host_bytes = 'ff02::1de:c0:face:8d'
|
| 455 |
+
|
| 456 |
+
if family == AF_UNSPEC:
|
| 457 |
+
# This tends to raise in the case that a v6 address did not exist
|
| 458 |
+
# but a v4 does. So we break it into two parts.
|
| 459 |
+
|
| 460 |
+
# Note that if there is no ipv6 in the hosts file, but there *is*
|
| 461 |
+
# an ipv4, and there *is* an ipv6 in the nameservers, we will return
|
| 462 |
+
# both (from the first call). The system resolver on OS X only returns
|
| 463 |
+
# the results from the hosts file. doubleclick.com is one example.
|
| 464 |
+
|
| 465 |
+
# See also https://github.com/gevent/gevent/issues/1012
|
| 466 |
+
try:
|
| 467 |
+
return _getaddrinfo(host_bytes, port, family, socktype, proto, flags)
|
| 468 |
+
except gaierror:
|
| 469 |
+
try:
|
| 470 |
+
return _getaddrinfo(host_bytes, port, AF_INET6, socktype, proto, flags)
|
| 471 |
+
except gaierror:
|
| 472 |
+
return _getaddrinfo(host_bytes, port, AF_INET, socktype, proto, flags)
|
| 473 |
+
else:
|
| 474 |
+
try:
|
| 475 |
+
return _getaddrinfo(host_bytes, port, family, socktype, proto, flags)
|
| 476 |
+
except gaierror as ex:
|
| 477 |
+
if ex.args[0] == EAI_NONAME and family not in self._KNOWN_ADDR_FAMILIES:
|
| 478 |
+
# It's possible that we got sent an unsupported family. Check
|
| 479 |
+
# that.
|
| 480 |
+
ex.args = (EAI_FAMILY, self.EAI_FAMILY_MSG)
|
| 481 |
+
ex.errno = EAI_FAMILY
|
| 482 |
+
raise
|
| 483 |
+
|
| 484 |
+
def _getnameinfo(self, address_bytes, port, sockaddr, flags):
|
| 485 |
+
try:
|
| 486 |
+
return resolver._getnameinfo(sockaddr, flags)
|
| 487 |
+
except error:
|
| 488 |
+
if not flags:
|
| 489 |
+
# dnspython doesn't like getting ports it can't resolve.
|
| 490 |
+
# We have one test, test__socket_dns.py:Test_getnameinfo_geventorg.test_port_zero
|
| 491 |
+
# that does this. We conservatively fix it here; this could be expanded later.
|
| 492 |
+
return resolver._getnameinfo(sockaddr, NI_NUMERICSERV)
|
| 493 |
+
|
| 494 |
+
def _gethostbyaddr(self, ip_address_bytes):
|
| 495 |
+
try:
|
| 496 |
+
return resolver._gethostbyaddr(ip_address_bytes)
|
| 497 |
+
except gaierror as ex:
|
| 498 |
+
if ex.args[0] == EAI_NONAME:
|
| 499 |
+
# Note: The system doesn't *always* raise herror;
|
| 500 |
+
# sometimes the original gaierror propagates through.
|
| 501 |
+
# It's impossible to say ahead of time or just based
|
| 502 |
+
# on the name which it should be. The herror seems to
|
| 503 |
+
# be by far the most common, though.
|
| 504 |
+
raise herror(1, "Unknown host")
|
| 505 |
+
raise
|
| 506 |
+
|
| 507 |
+
# Things that need proper error handling
|
| 508 |
+
getnameinfo = AbstractResolver.fixup_gaierror(AbstractResolver.getnameinfo)
|
| 509 |
+
gethostbyaddr = AbstractResolver.fixup_gaierror(AbstractResolver.gethostbyaddr)
|
| 510 |
+
gethostbyname_ex = AbstractResolver.fixup_gaierror(AbstractResolver.gethostbyname_ex)
|
| 511 |
+
getaddrinfo = AbstractResolver.fixup_gaierror(AbstractResolver.getaddrinfo)
|