Skip to content

Commit 02e765c

Browse files
Merge pull request #12 from openearth/feature/pdf-cloud-function
Feature/pdf-cloud-function
2 parents 86a3c2e + 107bbb1 commit 02e765c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

47 files changed

+9049
-799
lines changed

.github/workflows/deploy_function.yml

+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
# This workflow build and push a Docker container to Google Artifact Registry and deploy it on Cloud Run when a commit is pushed to the "main" branch
2+
#
3+
# Overview:
4+
#
5+
# 1. Authenticate to Google Cloud
6+
# 2. Authenticate Docker to Artifact Registry
7+
# 3. Build a docker container
8+
# 4. Publish it to Google Artifact Registry
9+
# 5. Deploy it to Cloud Run
10+
#
11+
# To configure this workflow:
12+
#
13+
# 1. Ensure the required Google Cloud APIs are enabled:
14+
#
15+
# Cloud Run run.googleapis.com
16+
# Artifact Registry artifactregistry.googleapis.com
17+
#
18+
# 2. Create and configure Workload Identity Federation for GitHub (https://github.com/google-github-actions/auth#setting-up-workload-identity-federation)
19+
#
20+
# 3. Ensure the required IAM permissions are granted
21+
#
22+
# Cloud Run
23+
# roles/run.admin
24+
# roles/iam.serviceAccountUser (to act as the Cloud Run runtime service account)
25+
#
26+
# Artifact Registry
27+
# roles/artifactregistry.admin (project or repository level)
28+
#
29+
# NOTE: You should always follow the principle of least privilege when assigning IAM roles
30+
#
31+
# 4. Create GitHub secrets for WIF_PROVIDER and WIF_SERVICE_ACCOUNT
32+
#
33+
# 5. Change the values for the GAR_LOCATION, SERVICE and REGION environment variables (below).
34+
#
35+
# NOTE: To use Google Container Registry instead, replace ${{ env.GAR_LOCATION }}-docker.pkg.dev with gcr.io
36+
#
37+
# For more support on how to run this workflow, please visit https://github.com/marketplace/actions/deploy-to-cloud-run
38+
#
39+
# Further reading:
40+
# Cloud Run IAM permissions - https://cloud.google.com/run/docs/deploying
41+
# Artifact Registry IAM permissions - https://cloud.google.com/artifact-registry/docs/access-control#roles
42+
# Container Registry vs Artifact Registry - https://cloud.google.com/blog/products/application-development/understanding-artifact-registry-vs-container-registry
43+
# Principle of least privilege - https://cloud.google.com/blog/products/identity-security/dont-get-pwned-practicing-the-principle-of-least-privilege
44+
45+
name: Build and Deploy Report function to Cloud Run
46+
47+
on:
48+
push:
49+
branches:
50+
- "main"
51+
- feature/pdf-cloud-function
52+
53+
env:
54+
PROJECT_ID: dgds-i1000482-002
55+
GAR_LOCATION: europe-west3
56+
SERVICE: gca-report-function
57+
REPOSITORY: gca-artifacts
58+
REGION: europe-west3
59+
60+
jobs:
61+
deploy:
62+
# Add 'id-token' with the intended permissions for workload identity federation
63+
permissions:
64+
contents: "read"
65+
id-token: "write"
66+
67+
runs-on: ubuntu-latest
68+
steps:
69+
- name: Checkout
70+
uses: actions/checkout@v2
71+
72+
# NOTE: Alternative option - authentication via credentials json
73+
- name: Google Auth
74+
id: auth
75+
uses: "google-github-actions/auth@v2"
76+
with:
77+
credentials_json: "${{ secrets.GCP_FUNCTION_CREDENTIALS }}"
78+
79+
# BEGIN - Docker auth and build (NOTE: If you already have a container image, these Docker steps can be omitted)
80+
- name: "Set up Cloud SDK"
81+
uses: "google-github-actions/setup-gcloud@v2"
82+
with:
83+
version: ">= 450.0.0"
84+
85+
# Authenticate Docker to Google Cloud Artifact Registry
86+
- name: Docker Auth
87+
id: docker-auth
88+
run: |-
89+
gcloud auth print-access-token | docker login -u oauth2accesstoken --password-stdin ${{ env.GAR_LOCATION }}-docker.pkg.dev
90+
91+
- name: Build and Push Container
92+
working-directory: App/functions/report-python-cloud-run
93+
run: |-
94+
docker build -t "${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}" .
95+
docker push "${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}"
96+
97+
# END - Docker auth and build
98+
99+
- name: Deploy to Cloud Run
100+
id: deploy
101+
uses: google-github-actions/deploy-cloudrun@v2
102+
with:
103+
service: ${{ env.SERVICE }}
104+
region: ${{ env.REGION }}
105+
# NOTE: If using a pre-built image, update the image name here
106+
image: ${{ env.GAR_LOCATION }}-docker.pkg.dev/${{ env.PROJECT_ID }}/${{ env.REPOSITORY }}/${{ env.SERVICE }}:${{ github.sha }}
107+
108+
# If required, use the Cloud Run url output in later steps
109+
- name: Show Output
110+
run: echo ${{ steps.deploy.outputs.url }}

App/Readme.md

-75
This file was deleted.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
# Copyright 2020 Google, LLC.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
# Use the official lightweight Python image.
16+
# https://hub.docker.com/_/python
17+
FROM python:3.11-slim
18+
19+
# Allow statements and log messages to immediately appear in the Knative logs
20+
ENV PYTHONUNBUFFERED True
21+
22+
# Copy local code to the container image.
23+
ENV APP_HOME /app
24+
WORKDIR $APP_HOME
25+
COPY . ./
26+
27+
# Install production dependencies.
28+
RUN pip install -r requirements.txt
29+
30+
# Run the web service on container startup. Here we use the gunicorn
31+
# webserver, with one worker process and 8 threads.
32+
# For environments with multiple CPU cores, increase the number of workers
33+
# to be equal to the cores available.
34+
CMD exec gunicorn --bind :$PORT --workers 1 --threads 8 --timeout 0 main:app
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# Developing the report-python-cloud-run Function
2+
3+
## Prerequisites
4+
5+
Create a virtual environment and install the dependencies:
6+
7+
```bash
8+
pip install -r requirements.txt
9+
```
10+
11+
## Testing
12+
13+
Run the report function locally:
14+
15+
```bash
16+
python report.py
17+
```
18+
19+
## Deploying
20+
21+
Deploying to Cloud run is done using github actions. The workflow is defined in `.github/workflows/deploy_function.yml`. The workflow is triggered on push to the `main` branch.

App/functions/report-python-cloud-run/__init__.py

Whitespace-only changes.
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import json
2+
import os
3+
4+
from shapely import Polygon # type: ignore
5+
from shapely.geometry import shape # type: ignore
6+
from flask import Flask, make_response, render_template_string, request
7+
8+
from report.report import (
9+
create_report_html,
10+
create_report_pdf,
11+
POLYGON_DEFAULT,
12+
STAC_ROOT_DEFAULT,
13+
)
14+
15+
app = Flask(__name__)
16+
17+
18+
@app.route("/", methods=["GET"])
19+
def return_report():
20+
"""Return a report for the given polygon"""
21+
polygon_str = request.args.get("polygon")
22+
23+
if not polygon_str:
24+
polygon_str = POLYGON_DEFAULT
25+
26+
origin = request.headers.get("Referer")
27+
print(f"detected origin: {origin}")
28+
29+
# For now we pin the stac_root on a default because we
30+
# don't have a way to pass it in from the client and cant handle the password
31+
# protected preview deployments
32+
stac_root = STAC_ROOT_DEFAULT
33+
34+
polygon = shape(json.loads(polygon_str))
35+
if not isinstance(polygon, Polygon):
36+
raise ValueError("Invalid polygon")
37+
38+
web_page_content = create_report_html(polygon=polygon, stac_root=stac_root)
39+
pdf_object = create_report_pdf(web_page_content)
40+
41+
response = make_response(pdf_object.getvalue())
42+
response.headers["Content-Type"] = "application/pdf"
43+
response.headers["Content-Disposition"] = "inline; filename=coastal_report.pdf"
44+
response.headers["Access-Control-Allow-Origin"] = "*" # CORS
45+
return response
46+
47+
48+
@app.route("/html")
49+
def return_html():
50+
"""Return a report for the given polygon"""
51+
polygon_str = request.args.get("polygon")
52+
53+
if not polygon_str:
54+
polygon_str = POLYGON_DEFAULT
55+
56+
origin = request.headers.get("Referer")
57+
print(f"detected origin: {origin}")
58+
59+
# For now we pin the stac_root on a default because we
60+
# don't have a way to pass it in from the client and cant handle the password
61+
# protected preview deployments
62+
stac_root = STAC_ROOT_DEFAULT
63+
64+
polygon = shape(json.loads(polygon_str))
65+
if not isinstance(polygon, Polygon):
66+
raise ValueError("Invalid polygon")
67+
68+
web_page_content = create_report_html(polygon=polygon, stac_root=stac_root)
69+
70+
response = make_response(render_template_string(web_page_content))
71+
response.headers["Access-Control-Allow-Origin"] = "*" # CORS
72+
return response
73+
74+
75+
if __name__ == "__main__":
76+
app.run(debug=True, host="0.0.0.0", port=int(os.environ.get("PORT", 8080)))

App/functions/report-python-cloud-run/report/__init__.py

Whitespace-only changes.

App/functions/report-python-cloud-run/report/datasets/__init__.py

Whitespace-only changes.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
from typing import Optional
2+
import xarray as xr
3+
4+
from .datasetcontent import DatasetContent
5+
from .esl import get_esl_content
6+
7+
8+
def get_dataset_content(dataset_id: str, xarr: xr.Dataset) -> Optional[DatasetContent]:
9+
match dataset_id:
10+
case "esl_gwl":
11+
return get_esl_content(xarr)
12+
case _:
13+
return None
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
from dataclasses import dataclass
2+
from typing import Optional
3+
4+
5+
@dataclass
6+
class DatasetContent:
7+
dataset_id: str
8+
title: str
9+
text: str
10+
image_base64: Optional[str] = None
11+
image_svg: Optional[str] = None

0 commit comments

Comments
 (0)