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 21 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
39 changes: 39 additions & 0 deletions src-docs/app.py.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<!-- 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#L36"><img align="right" style="float:right;" src="https://img.shields.io/badge/-source-cccccc?style=flat-square"></a>

## <kbd>function</kbd> `setup_config`

```python
setup_config() → None
```

Load and set the config.


---

<a href="../src/app.py#L56"><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.


73 changes: 73 additions & 0 deletions src/app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# 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 pathlib import Path
from typing import Any

from flask import Flask, request

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


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

Returns:
The log file name.
"""
# We use the process ID to avoid race conditions between multiple instances of the app.
pid = os.getpid()
return f"webhooks.{pid}.log"
cbartz marked this conversation as resolved.
Show resolved Hide resolved


def _setup_webhook_log_file() -> None:
"""Set the log file path."""
webhook_logs_dir = Path(os.environ.get("WEBHOOK_LOGS_DIR", "/var/log/whrouter"))
app.config["WEBHOOK_FILE_PATH"] = webhook_logs_dir / _log_file_name()


def setup_config() -> None:
"""Load and set the config."""
app.config.from_prefixed_env()
_setup_webhook_log_file()


setup_config()


def _write_webhook_log(payload: Any) -> None:
"""Append the webhook payload to a file.

Args:
payload: The payload to write.
"""
with app.config["WEBHOOK_FILE_PATH"].open("a") as f:
json.dump(payload, f)
f.write("\n")
cbartz marked this conversation as resolved.
Show resolved Hide resolved


@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)
_write_webhook_log(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