Compare commits

..

No commits in common. "b1d308a9779081034369950802006738ad39fd02" and "9eaf451213529fa44cb58aae7ae67a5844a3365b" have entirely different histories.

5 changed files with 94 additions and 111 deletions

View File

@ -1,24 +1,86 @@
from os import path
from os import getenv, path
from typing import Annotated
from docker import errors, from_env
from docker.models.containers import Container
from dotenv import load_dotenv
from fastapi import Depends, FastAPI, HTTPException
from fastapi import Depends, FastAPI, HTTPException, Request
from fastapi.responses import PlainTextResponse
from fastapi.security import HTTPBasicCredentials
from starlette import status
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from starlette import status, types
from uvicorn import run
from .security import AuthStaticFiles, check_auth, security
from .types import ContainerRequest, SerializedContainer
from .utils import serialize_container
load_dotenv()
client = from_env()
security = HTTPBasic()
def http_401() -> HTTPException:
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
async def check_auth(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
) -> HTTPBasicCredentials:
usernames = getenv("USERNAMES", "").split(",")
passwords = getenv("PASSWORDS", "").split(",")
if credentials.username not in usernames or credentials.password not in passwords:
raise http_401()
user_index = usernames.index(credentials.username)
password = passwords[user_index]
if credentials.password != password:
raise http_401()
return credentials
app = FastAPI(dependencies=[Depends(check_auth)])
class SerializedContainer(BaseModel):
id: str
name: str | None
image: str | None
labels: dict[str, str]
status: str
health: str
engine: str | None
owner: str | None
environment: list[str]
logs: str | None
def container_logs(container: Container, tail: int) -> str | None:
try:
return container.logs(tail=tail).decode()
except errors.APIError:
return None
def serialize_container(container: Container) -> SerializedContainer:
return SerializedContainer(
id=container.short_id,
name=container.name,
image=container.image.tags[0] if container.image else None,
labels=container.labels,
status=container.status,
health=container.health,
engine=container.labels.get("engine"),
owner=container.labels.get("owner"),
environment=container.attrs["Config"]["Env"],
logs=container_logs(container, 100),
)
def select_container(
container_name: str, credentials: Annotated[HTTPBasicCredentials, Depends(security)]
) -> Container:
@ -45,7 +107,8 @@ def get_containers(
return [
serialize_container(container)
for container in client.containers.list(
all=True, filters={"label": ["engine=pilotwings"]}
all=True,
filters={"label": ["engine=pilotwings"]}
)
]
@ -66,6 +129,11 @@ def get_container(
return serialize_container(select_container(container_name, credentials))
class ContainerRequest(BaseModel):
image: str
environment: list[str]
@app.post("/api/container/{container_name}")
def create_or_update_container(
container_name: str,
@ -84,7 +152,7 @@ def create_or_update_container(
except HTTPException:
pass
container = serialize_container(
return serialize_container(
client.containers.run(
request_body.image,
detach=True,
@ -96,10 +164,6 @@ def create_or_update_container(
)
)
client.images.prune({"dangling": True})
return container
@app.post("/api/container/{container_name}/pull")
def pull_container(
@ -168,7 +232,20 @@ def delete_container(
container = select_container(container_name, credentials)
container.stop()
container.remove(v=True, force=True)
client.images.prune({"dangling": True})
class AuthStaticFiles(StaticFiles):
async def __call__(
self, scope: types.Scope, receive: types.Receive, send: types.Send
) -> None:
request = Request(scope, receive)
credentials = await security(request)
if not credentials:
raise http_401()
await check_auth(credentials)
await super().__call__(scope, receive, send)
app.mount(

View File

@ -1,49 +0,0 @@
from os import getenv
from typing import Annotated
from fastapi import Depends, HTTPException, Request
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
from starlette import status, types
security = HTTPBasic()
def http_401() -> HTTPException:
return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
async def check_auth(
credentials: Annotated[HTTPBasicCredentials, Depends(security)],
) -> HTTPBasicCredentials:
usernames = getenv("USERNAMES", "").split(",")
passwords = getenv("PASSWORDS", "").split(",")
if credentials.username not in usernames or credentials.password not in passwords:
raise http_401()
user_index = usernames.index(credentials.username)
password = passwords[user_index]
if credentials.password != password:
raise http_401()
return credentials
class AuthStaticFiles(StaticFiles):
async def __call__(
self, scope: types.Scope, receive: types.Receive, send: types.Send
) -> None:
request = Request(scope, receive)
credentials = await security(request)
if not credentials:
raise http_401()
await check_auth(credentials)
await super().__call__(scope, receive, send)

View File

@ -1,19 +0,0 @@
from pydantic import BaseModel
class ContainerRequest(BaseModel):
image: str
environment: list[str]
class SerializedContainer(BaseModel):
id: str
name: str | None
image: str | None
labels: dict[str, str]
status: str
health: str
engine: str | None
owner: str | None
environment: list[str]
logs: str | None

View File

@ -1,26 +0,0 @@
from docker import errors
from docker.models.containers import Container
from .types import SerializedContainer
def container_logs(container: Container, tail: int) -> str | None:
try:
return container.logs(tail=tail).decode()
except errors.APIError:
return None
def serialize_container(container: Container) -> SerializedContainer:
return SerializedContainer(
id=container.short_id,
name=container.name,
image=container.image.tags[0] if container.image else None,
labels=container.labels,
status=container.status,
health=container.health,
engine=container.labels.get("engine"),
owner=container.labels.get("owner"),
environment=container.attrs["Config"]["Env"],
logs=container_logs(container, 100),
)

View File

@ -43,6 +43,7 @@
v-model="environment"
class="textarea"
placeholder="DURATION=60s"
required
></textarea>
</div>
</div>
@ -74,7 +75,7 @@ export default {
return {
custom_name: null as string | null,
image: null as string | null,
environment: '',
environment: null as string | null,
error: '',
loading: false,
}
@ -106,7 +107,6 @@ export default {
},
methods: {
async submit() {
if (!this.image || !(this.custom_name ?? this.container_name)) return
try {
this.loading = true
const { data } = await axios.post<Container>(