Skip to content
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

Add initial flask app #2

Merged
merged 24 commits into from
Mar 12, 2024
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
12 changes: 2 additions & 10 deletions .github/workflows/integration_test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,5 @@ jobs:
uses: canonical/operator-workflows/.github/workflows/integration_test.yaml@main
secrets: inherit
with:
load-test-enabled: false
load-test-run-args: "-e LOAD_TEST_HOST=localhost"
zap-before-command: "curl -H \"Host: indico.local\" http://localhost/bootstrap --data-raw 'csrf_token=00000000-0000-0000-0000-000000000000&first_name=admin&last_name=admin&email=admin%40admin.com&username=admin&password=lunarlobster&confirm_password=lunarlobster&affiliation=Canonical'"
zap-enabled: true
zap-cmd-options: '-T 60 -z "-addoninstall jython" --hook "/zap/wrk/tests/zap/hook.py"'
zap-target: localhost
zap-target-port: 80
zap-rules-file-name: "zap_rules.tsv"
trivy-fs-enabled: true
trivy-image-config: "trivy.yaml"
self-hosted-runner: true
self-hosted-runner-label: "edge"
13 changes: 0 additions & 13 deletions .github/workflows/load_test.yaml

This file was deleted.

3 changes: 3 additions & 0 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ jobs:
unit-tests:
uses: canonical/operator-workflows/.github/workflows/test.yaml@main
secrets: inherit
with:
self-hosted-runner: true
self-hosted-runner-label: "edge"
20 changes: 20 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,15 @@ tox devenv -e integration
source venv/bin/activate
```

## Generating src docs for every commit

Run the following command:

```bash
echo -e "tox -e src-docs\ngit add src-docs\n" >> .git/hooks/pre-commit
chmod +x .git/hooks/pre-commit
```

## Testing

This project uses `tox` for managing test environments. There are some pre-configured environments
Expand All @@ -22,6 +31,17 @@ tox run -e integration # integration tests
tox # runs 'format', 'lint', and 'unit' environments
```


## Development server

Flask contains a development server that can be used to test the charm. To start the server, run:

```shell
python -m src.app
```
in your virtual environment and project root.


## Build the charm

Build the charm in this git repository using:
Expand Down
12 changes: 6 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,19 @@ Avoid using this README file for information that is maintained or published els
Use links instead.
-->

# is-charms-template
# github-runner-webhook-router

Charmhub package name: operator-template
More information: https://charmhub.io/is-charms-template
> **Warning**
Work in progress: This charm is not yet ready for use.

The github-runner-webhook-router charm is a Juju charm that provides a webhook router for GitHub Actions self-hosted runners.
This charm is designed to be used in conjunction with the [github-runner-operator](https://github.com/canonical/github-runner-operator) charm.

Describe your charm in one or two sentences.

## Other resources

<!-- If your charm is documented somewhere else other than Charmhub, provide a link separately. -->

- [Read more](https://example.com)

- [Contributing](CONTRIBUTING.md) <!-- or link to other contribution documentation -->

- See the [Juju SDK documentation](https://juju.is/docs/sdk) for more information about developing and improving charms.
13 changes: 0 additions & 13 deletions charmcraft.yaml

This file was deleted.

16 changes: 0 additions & 16 deletions config.yaml

This file was deleted.

50 changes: 0 additions & 50 deletions metadata.yaml

This file was deleted.

2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
ops >= 2.2.0
Flask == 3.0.2
45 changes: 45 additions & 0 deletions src-docs/app.py.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
<!-- markdownlint-disable -->

<a href="../src/app.py#L0"><img align="right" style="float:right;" src="https://img.shields.io/badge/-source-cccccc?style=flat-square"></a>

# <kbd>module</kbd> `app.py`
Flask application which receives GitHub webhooks and logs those.


---

<a href="../src/app.py#L22"><img align="right" style="float:right;" src="https://img.shields.io/badge/-source-cccccc?style=flat-square"></a>

## <kbd>function</kbd> `setup_logger`

```python
setup_logger(log_file: Path) → None
```

Set up the webhook logger to log to a file.



**Args:**

- <b>`log_file`</b>: The log file.


---

<a href="../src/app.py#L50"><img align="right" style="float:right;" src="https://img.shields.io/badge/-source-cccccc?style=flat-square"></a>

## <kbd>function</kbd> `handle_github_webhook`

```python
handle_github_webhook() → tuple[str, int]
```

Receive a GitHub webhook and append the payload to a file.



**Returns:**
A tuple containing an empty string and 200 status code.


67 changes: 67 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# Copyright 2024 Canonical Ltd.
# See LICENSE file for licensing details.

"""Flask application which receives GitHub webhooks and logs those."""

import json
import logging
import os
import sys
from datetime import datetime
from pathlib import Path

from flask import Flask, request

app = Flask(__name__)
app.config.from_prefixed_env()


webhook_logger = logging.getLogger("webhook_logger")


def setup_logger(log_file: Path) -> None:
"""Set up the webhook logger to log to a file.

Args:
log_file: The log file.
"""
webhook_logger.handlers.clear()
fhandler = logging.FileHandler(log_file, delay=True)
fhandler.setLevel(logging.INFO)
webhook_logger.addHandler(fhandler)
webhook_logger.setLevel(logging.INFO)


def _log_filename() -> str:
"""Create the log file name.

Returns:
The log file name.
"""
# We use a unique name to avoid race conditions between multiple instances of the app.
pid = os.getpid()
return datetime.now().strftime(f"webhooks.%Y-%m-%d-%H-%M-%S.{pid}.log")


webhook_logs_dir = Path(os.environ.get("WEBHOOK_LOGS_DIR", "/var/log/whrouter"))
setup_logger(log_file=webhook_logs_dir / _log_filename())


@app.route("/webhook", methods=["POST"])
def handle_github_webhook() -> tuple[str, int]:
"""Receive a GitHub webhook and append the payload to a file.

Returns:
A tuple containing an empty string and 200 status code.
"""
payload = request.get_json()
app.logger.debug("Received webhook: %s", payload)
webhook_logger.log(logging.INFO, json.dumps(payload))
return "", 200


if __name__ == "__main__":
# Start development server
app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.DEBUG)
app.run()
Loading
Loading