47 lines
1.7 KiB
Python
47 lines
1.7 KiB
Python
import uuid
|
|
from tkinter.font import names
|
|
|
|
from fastapi import HTTPException
|
|
from sqlalchemy.orm import Session
|
|
from sqlalchemy import select, insert, update
|
|
|
|
from pillar_tool.db.models import Host
|
|
|
|
def list_all_hosts(db: Session) -> list[Host]:
|
|
stmt = select(Host)
|
|
results = db.execute(stmt).fetchall()
|
|
return [ x[0] for x in results ]
|
|
|
|
def create_host(db: Session, fqdn: str, parent: str | None) -> Host:
|
|
# if this host should have a parent, find if it exists
|
|
parent_id = None
|
|
if parent is not None:
|
|
parent_labels = parent.split('/')
|
|
for label in parent_labels:
|
|
parent_stmt = select(Host).where(Host.name == label and Host.parent_id == parent_id)
|
|
results = db.execute(parent_stmt).fetchall()
|
|
if len(results) != 1:
|
|
raise HTTPException(status_code=400, detail="Parent not found")
|
|
parent_host = results[0][0]
|
|
parent_id = parent_host.id
|
|
|
|
# check if the host already exists
|
|
select_stmt = select(Host).where(Host.name == fqdn)
|
|
results = db.execute(select_stmt).fetchall()
|
|
if len(results) == 1:
|
|
host = results[0][0]
|
|
host.parent_id = parent_id
|
|
update_stmt = update(Host).where(Host.name == fqdn).values(parent_id=parent_id)
|
|
db.execute(update_stmt)
|
|
db.commit()
|
|
return host
|
|
elif len(results) == 0:
|
|
host = Host(name=fqdn, parent_id=parent_id, id=uuid.uuid4())
|
|
add_stmt = insert(Host).values(name=host.name, parent_id=host.parent_id, id=host.id)
|
|
db.execute(add_stmt)
|
|
db.commit()
|
|
return host
|
|
else:
|
|
raise HTTPException(status_code=500, detail="Invalid state of database")
|
|
|