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

chores: add nginx to maubot #10

Merged
merged 5 commits into from
Sep 24, 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
1 change: 1 addition & 0 deletions .licenserc.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ header:
paths-ignore:
- '.github/**'
- '.trivyignore'
- '**/*.conf'
- '**/*.json'
- '**/*.md'
- '**/*.txt'
Expand Down
68 changes: 68 additions & 0 deletions maubot_rock/etc/nginx.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
user nginx nginx;
daemon off;

events {
worker_connections 1024;
}
http {
include mime.types;
server_tokens off;

gzip on;
gzip_disable "msie6";
gzip_min_length 256;

gzip_proxied any;
gzip_http_version 1.1;
gzip_types
application/font-woff
application/font-woff2
application/x-javascript
application/xml
application/xml+rss
image/x-icon
font/woff2
text/css
text/javascript
text/plain
text/xml;

add_header X-Content-Type-Options 'nosniff';
add_header X-Frame-Options 'SAMEORIGIN';
add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; preload";
add_header X-XSS-Protection "1; mode=block";

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" "$http_x_forwarded_proto"';
access_log stdout main;

map $http_x_forwarded_proto $proxy_x_forwarded_proto {
default $http_x_forwarded_proto;
'' $scheme;
}

server {
listen 8080;
listen [::]:8080;
error_log stderr error;

location / {
root /var/empty/nginx;
proxy_hide_header Cache-Control;
add_header Cache-Control 'no-cache,private';
client_max_body_size 0;
proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
proxy_set_header X-Forwarded-Host $http_host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://localhost:29316;
}

location /health {
access_log off;
add_header 'Content-Type' 'application/json';
return 204;
}

}
}
19 changes: 19 additions & 0 deletions maubot_rock/rockcraft.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,25 @@ environment:
PYTHONPATH: /usr/lib/python3.12/site-packages/

parts:
nginx-user:
plugin: nil
overlay-script: |
chmod 755 $CRAFT_OVERLAY/etc
groupadd -R $CRAFT_OVERLAY --gid 2000 nginx
useradd -R $CRAFT_OVERLAY --system --gid 2000 --uid 2000 --no-create-home nginx
nginx-conf:
plugin: dump
source: etc
organize:
nginx.conf: etc/nginx/nginx.conf
nginx:
stage-packages:
- logrotate
- nginx
plugin: nil
override-build: |
craftctl default
rm $CRAFT_PART_INSTALL/etc/nginx/nginx.conf
maubot:
plugin: python
source: .
Expand Down
33 changes: 16 additions & 17 deletions src/charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ def __init__(self, *args: typing.Any):
args: Arguments passed to the CharmBase parent constructor.
"""
super().__init__(*args)
self.ingress = IngressPerAppRequirer(self, port=29316)
self.ingress = IngressPerAppRequirer(self, port=8080)
self.postgresql = DatabaseRequires(
self, relation_name="postgresql", database_name=self.app.name
)
Expand All @@ -60,26 +60,18 @@ def _configure_maubot(self, container: ops.Container) -> None:

Args:
container: Container of the charm.

Raises:
ExecError: something went wrong executing command.
PathError: error while interacting with path.
"""
commands = [
["cp", "--update=none", "/example-config.yaml", "/data/config.yaml"],
["mkdir", "-p", "/data/plugins", "/data/trash", "/data/dbs"],
]
try:
for command in commands:
process = container.exec(command, combine_stderr=True)
process.wait()
config_content = str(container.pull("/data/config.yaml", encoding="utf-8").read())
config = yaml.safe_load(config_content)
config["database"] = self._get_postgresql_credentials()
container.push("/data/config.yaml", yaml.safe_dump(config))
except (ops.pebble.ExecError, ops.pebble.PathError) as exc:
jdkandersson marked this conversation as resolved.
Show resolved Hide resolved
logger.exception("Failed to execute command: %r", exc)
raise
for command in commands:
process = container.exec(command, combine_stderr=True)
process.wait()
config_content = str(container.pull("/data/config.yaml", encoding="utf-8").read())
config = yaml.safe_load(config_content)
config["database"] = self._get_postgresql_credentials()
container.push("/data/config.yaml", yaml.safe_dump(config))

def _reconcile(self) -> None:
"""Reconcile workload configuration."""
Expand Down Expand Up @@ -152,13 +144,20 @@ def _pebble_layer(self) -> pebble.LayerDict:
"summary": "maubot layer",
"description": "pebble config layer for maubot",
"services": {
"nginx": {
"override": "replace",
"summary": "nginx",
"command": "/usr/sbin/nginx",
"startup": "enabled",
"after": [MAUBOT_NAME],
},
MAUBOT_NAME: {
"override": "replace",
"summary": "maubot",
"command": "python3 -m maubot -c /data/config.yaml",
"startup": "enabled",
"working-dir": "/data",
}
},
},
}

Expand Down
12 changes: 11 additions & 1 deletion tests/integration/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import logging

import pytest
import requests
from pytest_operator.plugin import OpsTest

logger = logging.getLogger(__name__)
Expand All @@ -22,7 +23,8 @@ async def test_build_and_deploy(
arrange: set up the test Juju model.
act: build and deploy the Maubot charm, check if is blocked and deploy postgresql.
assert: the Maubot charm becomes active once is integrated with postgresql.
Charm is still active after integrating it with Nginx.
Charm is still active after integrating it with Nginx and the request
is successful.
"""
charm = pytestconfig.getoption("--charm-file")
maubot_image = pytestconfig.getoption("--maubot-image")
Expand Down Expand Up @@ -53,3 +55,11 @@ async def test_build_and_deploy(
await ops_test.model.add_relation(maubot.name, nginx_ingress_integrator.name)

await ops_test.model.wait_for_idle(timeout=600, status="active")

response = requests.get(
"http://127.0.0.1/_matrix/maubot/manifest.json",
timeout=5,
headers={"Host": "maubot.local"},
)
assert response.status_code == 200
assert "Maubot Manager" in response.text
9 changes: 8 additions & 1 deletion tests/unit/test_charm.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,14 @@ def test_maubot_pebble_ready(harness):
"command": "python3 -m maubot -c /data/config.yaml",
"startup": "enabled",
"working-dir": "/data",
}
},
"nginx": {
"override": "replace",
"summary": "nginx",
"command": "/usr/sbin/nginx",
"startup": "enabled",
"after": ["maubot"],
},
},
}

Expand Down
Loading