Skip to content

Commit

Permalink
Add api prefix and use k8s ingress
Browse files Browse the repository at this point in the history
  • Loading branch information
thomashbrnrd committed Oct 11, 2023
1 parent f5de603 commit 6695d93
Show file tree
Hide file tree
Showing 11 changed files with 51 additions and 75 deletions.
10 changes: 5 additions & 5 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,20 +27,20 @@ ifeq ("$(wildcard ${DC})","")
endif

check-dc-config-%: check-prerequisites ## Check docker-compose syntax
${DC} -f docker-compose.yml config -q
${DC} config -q

build: check-dc-config-%
TAG=${TAG} ${DC} -f docker-compose.yml build
TAG=${TAG} ${DC} build

up: check-dc-config-%
ifeq ("$(WORKSPACE)","preprod")
TAG=${TAG} PORT_PROD=8080 ${DC} -f docker-compose.yml up -d
TAG=${TAG} PORT_PROD=8080 ${DC} up -d
else
TAG=${TAG} ${DC} -f docker-compose.yml up -d
TAG=${TAG} ${DC} up -d
endif

down:
${DC} -f docker-compose.yml down
${DC} down

tag: show-current-tag
git tag -a v${TAG}
Expand Down
25 changes: 14 additions & 11 deletions backend/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,7 @@
from typing import Union

import boto3
from botocore.client import ClientError
from fastapi import BackgroundTasks, Cookie, FastAPI, File, Form, HTTPException, Request, Response, UploadFile
from fastapi import BackgroundTasks, Cookie, FastAPI, APIRouter, File, Form, HTTPException, Request, Response, UploadFile
from fastapi.responses import PlainTextResponse
from fastapi.middleware.cors import CORSMiddleware
from gelfformatter import GelfFormatter
Expand Down Expand Up @@ -138,7 +137,9 @@ def upload_image(content: bytes, image_key: str):
####################

# FastAPI Setup
app = FastAPI()
app = FastAPI(docs_url="/api/docs")
router = APIRouter(prefix="/api")

origins = [ # allow requests from front-end
"http://basegun.fr",
"https://basegun.fr",
Expand Down Expand Up @@ -198,17 +199,17 @@ def upload_image(content: bytes, image_key: str):
####################
# ROUTES #
####################
@app.get("/", response_class=PlainTextResponse)
@router.get("/", response_class=PlainTextResponse)
def home():
return "Basegun backend"


@app.get("/version", response_class=PlainTextResponse)
@router.get("/version", response_class=PlainTextResponse)
def version():
return APP_VERSION


@app.get("/logs")
@router.get("/logs")
def logs():
if "WORKSPACE" in os.environ and os.environ["WORKSPACE"] != "prod":
with open(os.path.join(PATH_LOGS, "log.json"), "r") as f:
Expand All @@ -220,7 +221,7 @@ def logs():
return PlainTextResponse("Forbidden")


@app.post("/upload")
@router.post("/upload")
async def imageupload(
request: Request,
response: Response,
Expand Down Expand Up @@ -279,7 +280,7 @@ async def imageupload(
raise HTTPException(status_code=500, detail=str(e))


@app.post("/identification-feedback")
@router.post("/identification-feedback")
async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -294,7 +295,7 @@ async def log_feedback(request: Request, user_id: Union[str, None] = Cookie(None
return


@app.post("/tutorial-feedback")
@router.post("/tutorial-feedback")
async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -309,7 +310,7 @@ async def log_tutorial_feedback(request: Request, user_id: Union[str, None] = Co
return


@app.post("/identification-dummy")
@router.post("/identification-dummy")
async def log_identification_dummy(request: Request, user_id: Union[str, None] = Cookie(None)):
res = await request.json()

Expand All @@ -322,4 +323,6 @@ async def log_identification_dummy(request: Request, user_id: Union[str, None] =
extras_logging["bg_"+key] = res[key]

logger.info("Identification dummy", extra=extras_logging)
return
return

app.include_router(router)
12 changes: 6 additions & 6 deletions backend/tests/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,12 @@ def create_bucket():
class TestModel(unittest.TestCase):
def test_home(self):
"""Checks that the route / is alive"""
response = client.get("/")
response = client.get("/api/")
self.assertEqual(response.text, "Basegun backend")

def test_version(self):
"""Checks that the route /version sends a version"""
response = client.get("/version")
response = client.get("/api/version")
self.assertEqual(response.status_code, 200)

def check_log_base(self, log):
Expand All @@ -66,7 +66,7 @@ def test_upload(self):
geoloc = "12.666,7.666"

with open(path, 'rb') as f:
r = client.post("/upload",
r = client.post("/api/upload",
files={"image": f},
data={"date": time.time(), "geolocation": geoloc})
self.assertEqual(r.status_code, 200)
Expand All @@ -77,7 +77,7 @@ def test_upload(self):
self.assertAlmostEqual(res["confidence"], 98.43, places=1)
self.assertTrue(res["confidence_level"], "high")
# checks that the result is written in logs
r = client.get("/logs")
r = client.get("/api/logs")
self.assertEqual(r.status_code, 200)
# checks the latest log with validates upload to object storage
self.assertEqual(r.json()[0]["_bg_image_url"], r.json()[1]["_bg_image_url"])
Expand All @@ -98,11 +98,11 @@ def test_feedback_and_logs(self):
label = "revolver"
confidence_level = "high"
image_url = "https://storage.gra.cloud.ovh.net/v1/test"
r = client.post("/identification-feedback",
r = client.post("/api/identification-feedback",
json={"image_url": image_url, "feedback": True, "confidence": confidence, "label": label, "confidence_level": confidence_level})

self.assertEqual(r.status_code, 200)
r = client.get("/logs")
r = client.get("/api/logs")
self.assertEqual(r.status_code, 200)
log = r.json()[0]
self.check_log_base(log)
Expand Down
1 change: 1 addition & 0 deletions frontend/.env.development
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
VITE_API_HOST=http://localhost:5000
4 changes: 1 addition & 3 deletions frontend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,7 @@ COPY ./cert/. /etc/ssl/certs/
COPY ./package.json ./package-lock.json ./
RUN npm ci --legacy-peer-deps

COPY src ./src
COPY public ./public
COPY vite.config.js index.html ./
COPY . .

FROM base as dev

Expand Down
8 changes: 0 additions & 8 deletions frontend/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -15,14 +15,6 @@ http {
try_files $uri $uri/ /index.html;
}

location /api/ {
proxy_pass http://basegun-backend:5000/;
client_max_body_size 5M;
proxy_read_timeout 1800;
proxy_connect_timeout 1800;
proxy_send_timeout 1800;
}

error_page 404 /404.html;

error_page 500 502 503 504 /50x.html;
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,6 @@ register()

const pinia = createPinia()

axios.defaults.withCredentials = true

// the FastAPI backend
axios.defaults.baseURL = '/api/'

Expand Down
7 changes: 3 additions & 4 deletions frontend/vite.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import transformerDirectives from '@unocss/transformer-directives'
import transformerVariantGroup from '@unocss/transformer-variant-group'

const path = require('path')
const apiHost = process.env.API_HOST || 'basegun-backend'
const apiHost = process.env.API_HOST || 'http://basegun-backend:5000'

// https://vitejs.dev/config/
export default defineConfig({
Expand Down Expand Up @@ -61,9 +61,8 @@ export default defineConfig({
host: true,
proxy: {
'^/api': {
target: `http://${apiHost}:5000`,
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
target: `${apiHost}`,
changeOrigin: true
},
},
},
Expand Down
4 changes: 2 additions & 2 deletions infra/kube/helm/templates/deployment-backend.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -45,13 +45,13 @@ spec:
protocol: TCP
livenessProbe:
httpGet:
path: /
path: /api/
port: api
initialDelaySeconds: 10
periodSeconds: 60
readinessProbe:
httpGet:
path: /
path: /api/
port: api
volumeMounts:
- name: logs
Expand Down
49 changes: 17 additions & 32 deletions infra/kube/helm/templates/ingress.yaml
Original file line number Diff line number Diff line change
@@ -1,18 +1,7 @@
{{- if .Values.ingress.enabled -}}
{{- $fullName := include "basegun.chart" . -}}
{{- $svcPort := .Values.frontend.service.port -}}
{{- if and .Values.ingress.className (not (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion)) }}
{{- if not (hasKey .Values.ingress.annotations "kubernetes.io/ingress.class") }}
{{- $_ := set .Values.ingress.annotations "kubernetes.io/ingress.class" .Values.ingress.className}}
{{- end }}
{{- end }}
{{- if semverCompare ">=1.19-0" .Capabilities.KubeVersion.GitVersion -}}
{{- $svcPortFrontend := .Values.frontend.service.port -}}
{{- $svcPortBackend := .Values.backend.service.port -}}
apiVersion: networking.k8s.io/v1
{{- else if semverCompare ">=1.14-0" .Capabilities.KubeVersion.GitVersion -}}
apiVersion: networking.k8s.io/v1beta1
{{- else -}}
apiVersion: extensions/v1beta1
{{- end }}
kind: Ingress
metadata:
name: "basegun-ingress"
Expand All @@ -23,9 +12,7 @@ metadata:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- if and .Values.ingress.className (semverCompare ">=1.18-0" .Capabilities.KubeVersion.GitVersion) }}
ingressClassName: {{ .Values.ingress.className }}
{{- end }}
{{- if .Values.ingress.tls }}
tls:
{{- range .Values.ingress.tls }}
Expand All @@ -41,21 +28,19 @@ spec:
- host: {{ .host | quote }}
http:
paths:
{{- range .paths }}
- path: {{ .path }}
{{- if and .pathType (semverCompare ">=1.18-0" $.Capabilities.KubeVersion.GitVersion) }}
pathType: {{ .pathType }}
{{- end }}
backend:
{{- if semverCompare ">=1.19-0" $.Capabilities.KubeVersion.GitVersion }}
service:
name: "basegun-frontend"
port:
number: {{ $svcPort }}
{{- else }}
serviceName: "basegun-frontend"
servicePort: {{ $svcPort }}
{{- end }}
{{- end }}
- path: /
pathType: Prefix
backend:
service:
name: basegun-frontend
port:
number: {{ $svcPortFrontend }}
- path: /api/
pathType: Prefix
backend:
service:
name: basegun-backend
port:
number: {{ $svcPortBackend }}
{{- end }}
{{- end }}
{{- end }}
4 changes: 2 additions & 2 deletions infra/kube/helm/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ backend:
memory: 256Mi
service:
type: ClusterIP
port: 5000
port: 80
containerPort: 5000
autoscaling:
enabled: false
Expand Down Expand Up @@ -111,7 +111,7 @@ frontend:

service:
type: ClusterIP
port: 8080
port: 80
containerPort: 8080
resources:
# We usually recommend not to specify default resources and to leave this as a conscious
Expand Down

0 comments on commit 6695d93

Please sign in to comment.