Skip to content

Commit

Permalink
feat: @metricq_command as a standardized click command
Browse files Browse the repository at this point in the history
  • Loading branch information
Max KvR authored and devmaxde committed Dec 11, 2024
1 parent 72ee749 commit 61dd594
Show file tree
Hide file tree
Showing 15 changed files with 753 additions and 106 deletions.
34 changes: 34 additions & 0 deletions docs/api/cli.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
CLI
===

This module provides CLI utilities and decorators for MetricQ applications, including custom parameter types for choices, durations, timestamps, templates, and metrics.

The main focus of this module is to standardize the CLI interfaces of different programs.

To use this part of the package you need to install additional dependencies. You can install the dependencies using the following command:

.. code-block:: bash
pip install "metricq[cli]"
..
Decorators
----------

.. automodule:: metricq.cli.decorator
:members: metricq_command, metricq_metric_option, metricq_server_option, metricq_token_option,


Parameter
---------
For you convenience, we provide a set of custom parameter types that you can use as custom types in your click option definitions.

.. automodule:: metricq.cli.params
:members:
:exclude-members: get_metavar, convert, name





1 change: 1 addition & 0 deletions docs/api/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,4 @@ API Reference
client-common
exceptions
misc
cli
14 changes: 2 additions & 12 deletions examples/metricq_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,20 +40,13 @@
`telnet localhost 50101` (or `netcat`), inspect tasks and run code in a REPL.
"""
import asyncio
import logging

import aiomonitor # type: ignore
import click
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command

logger = metricq.get_logger()
click_log.basic_config(logger)
logger.setLevel("INFO")
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


async def run(server: str, token: str) -> None:
Expand All @@ -66,10 +59,7 @@ async def run(server: str, token: str) -> None:
await client.stopped()


@click.command()
@click.option("--server", default="amqp://admin:admin@localhost/")
@click.option("--token", default="client-py-example")
@click_log.simple_verbosity_option(logger) # type: ignore
@metricq_command(default_token="client-py-example")
def main(server: str, token: str) -> None:
asyncio.run(run(server, token))

Expand Down
22 changes: 6 additions & 16 deletions examples/metricq_get_history.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,24 +28,17 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import asyncio
import logging
import pprint
from datetime import timedelta

import click
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command
from metricq.cli.decorator import metricq_metric_option
from metricq.logging import get_logger

logger = metricq.get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
# Use this if we ever use threads
# logger.handlers[0].formatter = logging.Formatter(fmt='%(asctime)s %(threadName)-16s %(levelname)-8s %(message)s')
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)
logger = get_logger()


async def aget_history(
Expand Down Expand Up @@ -98,13 +91,10 @@ async def aget_history(
click.echo(aggregate)


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="history-py-dummy")
@click.option("--metric", default=None)
@metricq_command(default_token="history-py-dummy")
@metricq_metric_option()
@click.option("--list-metrics", is_flag=True)
@click.option("--list-metadata", is_flag=True)
@click_log.simple_verbosity_option(logger) # type: ignore
def get_history(
server: str, token: str, metric: str, list_metrics: bool, list_metadata: bool
) -> None:
Expand Down
21 changes: 4 additions & 17 deletions examples/metricq_get_history_raw.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,15 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import asyncio
import logging
from datetime import timedelta

import click
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command
from metricq.cli.decorator import metricq_metric_option
from metricq.history_client import HistoryRequestType

logger = metricq.get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
# Use this if we ever use threads
# logger.handlers[0].formatter = logging.Formatter(fmt='%(asctime)s %(threadName)-16s %(levelname)-8s %(message)s')
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


async def aget_history(server: str, token: str, metric: str) -> None:
client = metricq.HistoryClient(token=token, url=server)
Expand Down Expand Up @@ -83,11 +73,8 @@ async def aget_history(server: str, token: str, metric: str) -> None:
await client.stop(None)


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="history-py-dummy")
@click.argument("metric")
@click_log.simple_verbosity_option(logger) # type: ignore
@metricq_command(default_token="history-py-dummy")
@metricq_metric_option()
def get_history(server: str, token: str, metric: str) -> None:
asyncio.run(aget_history(server, token, metric))

Expand Down
19 changes: 4 additions & 15 deletions examples/metricq_pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,25 +28,17 @@
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import asyncio
import logging
from datetime import timedelta

import click
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command
from metricq.cli.decorator import metricq_metric_option
from metricq.pandas import PandasHistoryClient

logger = metricq.get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
# Use this if we ever use threads
# logger.handlers[0].formatter = logging.Formatter(fmt='%(asctime)s %(threadName)-16s %(levelname)-8s %(message)s')
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


async def aget_history(server: str, token: str, metric: str) -> None:
async with PandasHistoryClient(token=token, url=server) as client:
Expand Down Expand Up @@ -81,11 +73,8 @@ async def aget_history(server: str, token: str, metric: str) -> None:
click.echo("----------")


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="history-py-dummy")
@click.option("--metric", default="example.quantity")
@click_log.simple_verbosity_option(logger) # type: ignore
@metricq_command(default_token="history-py-dummy")
@metricq_metric_option(default="example.quantity")
def get_history(server: str, token: str, metric: str) -> None:
asyncio.run(aget_history(server, token, metric))

Expand Down
21 changes: 6 additions & 15 deletions examples/metricq_sink.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,18 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import logging
from typing import Any

import click
import click_log # type: ignore

import metricq
from metricq import Metric
from metricq.cli import metricq_command
from metricq.cli.decorator import metricq_metric_option
from metricq.logging import get_logger

logger = get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


# To implement a MetricQ Sink, subclass metricq.Sink
class DummySink(metricq.Sink):
Expand Down Expand Up @@ -76,15 +70,12 @@ async def on_data(
)


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="sink-py-dummy")
@click.option("-m", "--metrics", multiple=True, required=True)
@click_log.simple_verbosity_option(logger) # type: ignore
def source(server: str, token: str, metrics: list[Metric]) -> None:
@metricq_command(default_token="sink-py-dummy")
@metricq_metric_option(multiple=True)
def source(server: str, token: str, metric: list[Metric]) -> None:
# Initialize the DummySink class with a list of metrics given on the
# command line.
sink = DummySink(metrics=metrics, token=token, url=server)
sink = DummySink(metrics=metric, token=token, url=server)

# Run the sink. This call will block until the connection is closed.
sink.run()
Expand Down
16 changes: 2 additions & 14 deletions examples/metricq_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,15 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import logging
import random
from typing import Any

import click
import click_log # type: ignore

import metricq
from metricq.cli import metricq_command
from metricq.logging import get_logger

logger = get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


class DummySource(metricq.IntervalSource):
def __init__(self, *args: Any, **kwargs: Any):
Expand Down Expand Up @@ -74,10 +65,7 @@ async def update(self) -> None:
)


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="source-py-dummy")
@click_log.simple_verbosity_option(logger) # type: ignore
@metricq_command(default_token="source-py-dummy")
def source(server: str, token: str) -> None:
src = DummySource(token=token, url=server)
src.run()
Expand Down
20 changes: 5 additions & 15 deletions examples/metricq_synchronous_source.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,28 +29,18 @@
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

import logging

import random
import time

import click
import click_log # type: ignore

from metricq import SynchronousSource, Timestamp, get_logger
from metricq import SynchronousSource, Timestamp
from metricq.cli import metricq_command
from metricq.logging import get_logger

logger = get_logger()

click_log.basic_config(logger)
logger.setLevel("INFO")
logger.handlers[0].formatter = logging.Formatter(
fmt="%(asctime)s [%(levelname)-8s] [%(name)-20s] %(message)s"
)


@click.command()
@click.option("--server", default="amqp://localhost/")
@click.option("--token", default="source-py-dummy")
@click_log.simple_verbosity_option(logger) # type: ignore
@metricq_command(default_token="source-py-dummy")
def synchronous_source(server: str, token: str) -> None:
ssource = SynchronousSource(token=token, url=server)
ssource.declare_metrics(
Expand Down
27 changes: 27 additions & 0 deletions metricq/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
from .decorator import (
metricq_command,
metricq_metric_option,
metricq_server_option,
metricq_token_option,
)
from .params import (
ChoiceParam,
CommandLineChoice,
DurationParam,
MetricParam,
TemplateStringParam,
TimestampParam,
)

__all__ = [
"ChoiceParam",
"CommandLineChoice",
"DurationParam",
"TemplateStringParam",
"TimestampParam",
"MetricParam",
"metricq_command",
"metricq_metric_option",
"metricq_server_option",
"metricq_token_option",
]
Loading

0 comments on commit 61dd594

Please sign in to comment.