-
Notifications
You must be signed in to change notification settings - Fork 137
docs: Pull tutorial code snippets from examples/ #2544
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
Open
tonyandrewmeyer
wants to merge
1
commit into
canonical:main
Choose a base branch
from
tonyandrewmeyer:tutorial-pull-from-files
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -50,33 +50,20 @@ These files currently contain placeholder code and configuration. | |
|
|
||
| Open `~/k8s-tutorial/charmcraft.yaml` in your usual text editor or IDE, then change the values of `title`, `summary`, and `description` to: | ||
|
|
||
| ```yaml | ||
| title: Web Server Demo | ||
| summary: A demo charm that operates a small Python FastAPI server. | ||
| description: | | ||
| This charm demonstrates how to write a Kubernetes charm with Ops. | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/charmcraft.yaml | ||
| :language: yaml | ||
| :start-at: 'title: Web Server Demo' | ||
| :end-at: how to write a Kubernetes charm with Ops. | ||
| ``` | ||
|
|
||
| Next, describe the workload container and its OCI image. | ||
|
|
||
| In `charmcraft.yaml`, replace the `containers` and `resources` blocks with: | ||
|
|
||
| ```yaml | ||
| containers: | ||
| demo-server: | ||
| resource: demo-server-image | ||
|
|
||
| resources: | ||
| # An OCI image resource for the container listed above. | ||
| demo-server-image: | ||
| type: oci-image | ||
| description: OCI image from GitHub Container registry | ||
| # The upstream-source field is ignored by Charmcraft and Juju, but it can be | ||
| # useful to developers in identifying the source of the OCI image. It is also | ||
| # used by the 'canonical/charming-actions' GitHub action for automated releases. | ||
| # The test_deploy function in tests/integration/test_charm.py reads upstream-source | ||
| # to determine which OCI image to use when running the charm's integration tests. | ||
| upstream-source: ghcr.io/canonical/api_demo_server/api-demo-server:2.1.0 | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/charmcraft.yaml | ||
| :language: yaml | ||
| :start-at: 'containers:' | ||
| :end-at: 'upstream-source: ghcr.io/canonical/api_demo_server/api-demo-server:2.1.0' | ||
| ``` | ||
|
|
||
| ### Write a helper module | ||
|
|
@@ -89,23 +76,9 @@ To make things easier for Juju users, your charm should expose the workload vers | |
|
|
||
| Replace the content of `src/fastapi_demo.py` with: | ||
|
|
||
| ```python | ||
| import json | ||
| import logging | ||
| import urllib.request | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| def get_version(port: int) -> str: | ||
| """Get the version of fastapi_demo that is running. | ||
|
|
||
| Args: | ||
| port: The port where fastapi_demo web server is listening. | ||
| """ | ||
| response = urllib.request.urlopen(f"http://localhost:{port}/version") | ||
| data = json.loads(response.read()) | ||
| return data["version"] | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/src/fastapi_demo.py | ||
| :language: python | ||
| :start-at: import json | ||
| ``` | ||
|
|
||
| Notice that the helper module is stateless. In fact, your charm as a whole will be stateless. The main logic of your charm will: | ||
|
|
@@ -153,8 +126,11 @@ As you can see, a charm is a pure Python class that inherits from the [`CharmBas | |
|
|
||
| In the `__init__` function of your charm class, we'll tell Ops which method of your charm class to run for each event. Let's start with when the Juju controller tells us that the workload container's Pebble is up and running. | ||
|
|
||
| ```python | ||
| framework.observe(self.on["demo-server"].pebble_ready, self._on_demo_server_pebble_ready) | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/src/charm.py | ||
| :language: python | ||
| :start-at: framework.observe(self.on["demo-server"] | ||
| :end-at: framework.observe(self.on["demo-server"] | ||
|
Comment on lines
+131
to
+132
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This line is too long and requires scrolling in the docs. I wonder if we should adopt a lower line length for the example charms now that we're using them this way. |
||
| :dedent: | ||
| ``` | ||
|
|
||
|
|
||
|
|
@@ -211,10 +187,11 @@ The workload version is available after the workload starts, which happens after | |
|
|
||
| In `src/charm.py`, add the following lines to the `_on_demo_server_pebble_ready` function before the final `self.unit.status = ops.ActiveStatus()`: | ||
|
|
||
| ```python | ||
| # Set the workload version of this charm. | ||
| version = fastapi_demo.get_version(port=8000) | ||
| self.unit.set_workload_version(version) | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/src/charm.py | ||
| :language: python | ||
| :start-at: "# Set the workload version of this charm." | ||
| :end-at: self.unit.set_workload_version(version) | ||
| :dedent: | ||
| ``` | ||
|
|
||
| We get the workload version over port 8000 because the `fastapi` service runs the app on this port. Then `self.unit.set_workload_version` exposes the workload version to Juju. If the `get_version` call fails (for example, an `URLError` exception is raised), the charm will go into error status. The Juju logs will show the error message, to help you debug the error. | ||
|
|
@@ -354,66 +331,9 @@ In this section we'll write a test to check that the `fastapi` service is starte | |
|
|
||
| Replace the contents of `tests/unit/test_charm.py` with: | ||
|
|
||
| ```python | ||
| import ops | ||
| import pytest | ||
| from ops import testing | ||
|
|
||
| from charm import FastAPIDemoCharm | ||
|
|
||
| # The default Pebble layer in the application image. | ||
| # Defined in https://github.com/canonical/api_demo_server/blob/master/rockcraft.yaml | ||
| ROCK_LAYER = ops.pebble.Layer( | ||
| { | ||
| "services": { | ||
| "fastapi": { | ||
| "override": "replace", | ||
| "summary": "FastAPI demo server", | ||
| "command": "/bin/uvicorn api_demo_server.app:app --host 0.0.0.0 --port 8000", | ||
| "startup": "enabled", | ||
| "environment": {"DEMO_SERVER_LOGFILE": "/tmp/demo_server.log"}, | ||
| "on-success": "shutdown", | ||
| "on-failure": "shutdown", | ||
| } | ||
| }, | ||
| } | ||
| ) | ||
|
|
||
|
|
||
| def mock_get_version(port: int): | ||
| """Get a mock version string without executing the workload code.""" | ||
| return "0.0.1" | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def mock_version(monkeypatch: pytest.MonkeyPatch) -> None: | ||
| monkeypatch.setattr("fastapi_demo.get_version", mock_get_version) | ||
|
|
||
|
|
||
| def test_pebble_layer(mock_version): | ||
| ctx = testing.Context(FastAPIDemoCharm) | ||
| container = testing.Container( | ||
| name="demo-server", can_connect=True, layers={"rock": ROCK_LAYER} | ||
| ) | ||
| state_in = testing.State( | ||
| containers={container}, | ||
| leader=True, | ||
| ) | ||
| state_out = ctx.run(ctx.on.pebble_ready(container), state_in) | ||
| # Expected plan after Pebble ready (our charm doesn't add any layers). | ||
| expected_plan = ops.pebble.Plan(ROCK_LAYER.to_dict()) | ||
|
|
||
| # Check that we have the plan we expected: | ||
| assert state_out.get_container(container.name).plan == expected_plan | ||
| # Check the unit is active: | ||
| assert state_out.unit_status == testing.ActiveStatus() | ||
| # Check the service was started: | ||
| assert ( | ||
| state_out.get_container(container.name).service_statuses["fastapi"] | ||
| == ops.pebble.ServiceStatus.ACTIVE | ||
| ) | ||
| # Check the workload version is set: | ||
| assert state_out.workload_version == "0.0.1" | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/tests/unit/test_charm.py | ||
| :language: python | ||
| :start-at: import ops | ||
| ``` | ||
|
|
||
| This test checks the behaviour of the `_on_demo_server_pebble_ready` function that you set up earlier. The test simulates your charm receiving the pebble-ready event, then checks that the unit and workload container have the correct state. | ||
|
|
@@ -473,34 +393,9 @@ Let's write some integration tests as [smoke tests](https://en.wikipedia.org/wik | |
|
|
||
| Replace the contents of `tests/integration/test_charm.py` with: | ||
|
|
||
| ```python | ||
| import logging | ||
| import pathlib | ||
|
|
||
| import jubilant | ||
| import pytest | ||
| import yaml | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| METADATA = yaml.safe_load(pathlib.Path("charmcraft.yaml").read_text()) | ||
| APP_NAME = METADATA["name"] | ||
|
|
||
|
|
||
| @pytest.mark.juju_setup | ||
| def test_deploy(charm: pathlib.Path, juju: jubilant.Juju): | ||
| """Deploy the charm under test.""" | ||
| resources = { | ||
| "demo-server-image": METADATA["resources"]["demo-server-image"]["upstream-source"] | ||
| } | ||
| juju.deploy(charm, app=APP_NAME, resources=resources) | ||
| juju.wait(jubilant.all_active) | ||
|
|
||
|
|
||
| def test_workload_version_is_set(charm: pathlib.Path, juju: jubilant.Juju): | ||
| """Verify that the workload version has been set.""" | ||
| expected_version = "2.1.0" # Hardcoded for simplicity. | ||
| juju.wait(lambda status: status.apps[APP_NAME].version == expected_version) | ||
| ```{literalinclude} ../../../examples/k8s-1-minimal/tests/integration/test_charm.py | ||
| :language: python | ||
| :start-at: import logging | ||
| ``` | ||
|
|
||
| These tests depend on two fixtures: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We could use
start-afterandend-afterwith comment anchors in cases where we worry that this won't be robust. Thinking about this case specifically, I guess Sphinx would yell at us if we changed the end line of the description so there was no match, so this seems great as-is.