8000 Utilise uvloop automatically for CLI if present by nolar · Pull Request #971 · nolar/kopf · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Utilise uvloop automatically for CLI if present #971

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 1, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ jobs:
matrix:
install-extras: [ "", "full-auth" ]
python-version: [ "3.7", "3.8", "3.9", "3.10", "3.11" ]
include:
- install-extras: "uvloop"
python-version: "3.11"
name: Python ${{ matrix.python-version }} ${{ matrix.install-extras }}
runs-on: ubuntu-22.04
timeout-minutes: 5 # usually 2-3 mins
Expand Down
3 changes: 3 additions & 0 deletions .github/workflows/thorough.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ jobs:
matrix:
install-extras: [ "", "full-auth" ]
python-version: [ "3.7", "3.8", "3.9", "3.10", "3.11" ]
include:
- install-extras: "uvloop"
python-version: "3.11"
name: Python ${{ matrix.python-version }} ${{ matrix.install-extras }}
runs-on: ubuntu-22.04
timeout-minutes: 5 # usually 2-3 mins
Expand Down
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -85,4 +85,4 @@ repos:
rev: v2.34.0
hooks:
- id: pyupgrade
args: [--py37-plus]
args: [--py37-plus, --keep-mock]
48 changes: 48 additions & 0 deletions docs/embedding.rst
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,54 @@ See more on the asyncio event loops and _contexts_ in `Asyncio Policies`__.

__ https://docs.python.org/3/library/asyncio-policy.html

.. _custom-event-loops:


Custom event loops
==================

Kopf can run in any AsyncIO-compatible event loop. For example, uvloop `claims to be 2x–2.5x times faster`__ than asyncio. To run Kopf in uvloop, call it this way:

__ http://magic.io/blog/uvloop-blazing-fast-python-networking/

.. code-block:: python

import kopf
import uvloop

def main():
loop = uvloop.EventLoopPolicy().get_event_loop()
loop.run(kopf.operator())

Or this way:

.. code-block:: python

import kopf
import uvloop

def main():
kopf.run(loop=uvloop.EventLoopPolicy().new_event_loop())

Or this way:

.. code-block:: python

import kopf
import uvloop

def main():
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
kopf.run()

Or any other way the event loop prescribes in its documentation.

Kopf's CLI (i.e. :command:`kopf run`) will use uvloop by default if it is installed. To disable this implicit behaviour, either uninstall uvloop from Kopf's environment, or run Kopf explicitly from the code using the standard event loop.

For convenience, Kopf can be installed as ``pip install kopf[uvloop]`` to enable this mode automatically.

Kopf will never implicitly activate the custom event loops if it is called from the code, not from the CLI.


Multiple operators
==================
Expand Down
4 changes: 4 additions & 0 deletions docs/install.rst
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ authentication beyond username+password, fixed tokens, or client SSL certs

pip install kopf[full-auth]

If you want extra i/o performance under the hood, install it as (also see :ref:`custom-event-loops`)::

pip install kopf[uvloop]

Unless you use the standalone mode,
create a few Kopf-specific custom resources in the cluster::

Expand Down
3 changes: 2 additions & 1 deletion kopf/_kits/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,8 @@ def _target(self) -> None:
ctxobj = cli.CLIControls(
registry=self.registry,
settings=self.settings,
stop_flag=self._stop)
stop_flag=self._stop,
loop=loop)
runner = click.testing.CliRunner()
result = runner.invoke(cli.main, *self.args, **self.kwargs, obj=ctxobj)
except BaseException as e:
Expand Down
14 changes: 12 additions & 2 deletions kopf/cli.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import asyncio
import dataclasses
import functools
import os
Expand All @@ -23,6 +24,7 @@ class CLIControls:
vault: Optional[credentials.Vault] = None
registry: Optional[registries.OperatorRegistry] = None
settings: Optional[configuration.OperatorSettings] = None
loop: Optional[asyncio.AbstractEventLoop] = None


class LogFormatParamType(click.Choice):
Expand Down Expand Up @@ -63,8 +65,15 @@ def wrapper(verbose: bool, quiet: bool, debug: bool,
auto_envvar_prefix='KOPF',
))
@click.version_option(prog_name='kopf')
def main() -> None:
pass
@click.make_pass_decorator(CLIControls, ensure=True)
def main(__controls: CLIControls) -> None:
if __controls.loop is None: # the pure CLI use, not a KopfRunner or other code
try:
import uvloop
except ImportError:
pass
else:
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())


@main.command()
Expand Down Expand Up @@ -113,6 +122,7 @@ def run(
stop_flag=__controls.stop_flag,
ready_flag=__controls.ready_flag,
vault=__controls.vault,
loop=__controls.loop,
)


Expand Down
3 changes: 3 additions & 0 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,9 @@
'pykube-ng', # 4.90 MB
'kubernetes', # 40.0 MB (!)
],
'uvloop': [
'uvloop', # 9.00 MB
],
'dev': [
'pyngrok', # 1.00 MB + downloaded binary
'oscrypto', # 2.80 MB (smaller than cryptography: 8.7 MB)
Expand Down
18 changes: 18 additions & 0 deletions tests/testing/test_runner.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import asyncio

import pytest

from kopf._cogs.configs.configuration import OperatorSettings
Expand All @@ -10,6 +12,22 @@ def no_config_needed(login_mocks):
pass


@pytest.fixture(autouse=True, params=['default', 'uvloop'])
def _event_loop_policy(request):
original_policy = asyncio.get_event_loop_policy()
if request.param == 'default':
policy = asyncio.DefaultEventLoopPolicy()
elif request.param == 'uvloop':
uvloop = pytest.importorskip('uvloop')
policy = uvloop.EventLoopPolicy()
else:
raise RuntimeError(f"Unknown event loop type {request.param!r}")

asyncio.set_event_loop_policy(policy)
yield
asyncio.set_event_loop_policy(original_policy)


def test_command_invocation_works():
with KopfRunner(['--help']) as runner:
pass
Expand Down
2 changes: 1 addition & 1 deletion tests/utilities/aiotasks/test_coro_cancellation.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ async def f(mock):
return mock()


def factory(loop, coro_or_mock):
def factory(loop, coro_or_mock, context=None):
coro = coro_or_mock._mock_wraps if isinstance(coro_or_mock, AsyncMock) else coro_or_mock
return asyncio.Task(coro, loop=loop)

Expand Down
0