pglift-api 3.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pglift_api/__init__.py +14 -0
- pglift_api/_compat.py +15 -0
- pglift_api/_site.py +140 -0
- pglift_api/databases.py +105 -0
- pglift_api/deps.py +43 -0
- pglift_api/instances.py +106 -0
- pglift_api/pm.py +14 -0
- pglift_api/py.typed +0 -0
- pglift_api/tasks.py +48 -0
- pglift_api/tasks_manager.py +199 -0
- pglift_api-3.3.0.dist-info/METADATA +49 -0
- pglift_api-3.3.0.dist-info/RECORD +13 -0
- pglift_api-3.3.0.dist-info/WHEEL +4 -0
pglift_api/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
from fastapi import FastAPI
|
|
6
|
+
|
|
7
|
+
from . import databases, instances, tasks
|
|
8
|
+
|
|
9
|
+
app = FastAPI()
|
|
10
|
+
|
|
11
|
+
instances.prefixed_router.include_router(instances.router)
|
|
12
|
+
instances.prefixed_router.include_router(databases.router)
|
|
13
|
+
app.include_router(instances.prefixed_router)
|
|
14
|
+
app.include_router(tasks.router)
|
pglift_api/_compat.py
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
# we cannot simply import TypedDict from typing:
|
|
8
|
+
# https://pydantic.dev/docs/validation/latest/errors/usage_errors/#typed-dict-version
|
|
9
|
+
|
|
10
|
+
if sys.version_info[:2] < (3, 12):
|
|
11
|
+
from typing_extensions import TypedDict
|
|
12
|
+
else:
|
|
13
|
+
from typing import TypedDict
|
|
14
|
+
|
|
15
|
+
__all__ = ["TypedDict"]
|
pglift_api/_site.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
"""Site globals for the API."""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from copy import deepcopy
|
|
10
|
+
from functools import cache
|
|
11
|
+
from typing import TYPE_CHECKING, Annotated, Any, Union, get_args, get_origin
|
|
12
|
+
|
|
13
|
+
from fastapi import HTTPException, status
|
|
14
|
+
from pydantic import BaseModel, ValidationError, create_model
|
|
15
|
+
from pydantic.fields import FieldInfo
|
|
16
|
+
|
|
17
|
+
from pglift import exceptions, plugin_manager
|
|
18
|
+
from pglift.annotations import CREATE_ONLY, api
|
|
19
|
+
from pglift.models import interface
|
|
20
|
+
from pglift.settings import Settings, SiteSettings
|
|
21
|
+
|
|
22
|
+
__all__ = ["SiteSettings"]
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@cache
|
|
26
|
+
def _build_model(model: type[BaseModel], createMode: bool = False) -> type[BaseModel]:
|
|
27
|
+
"""
|
|
28
|
+
Dynamically create a Pydantic model derived from a pglift interface
|
|
29
|
+
model while adjusting readOnly JSON Schema extra metadata.
|
|
30
|
+
|
|
31
|
+
This walks the original model and:
|
|
32
|
+
|
|
33
|
+
- recursively processes nested models and supported generic types
|
|
34
|
+
- makes api.HIDDEN fields as readOnly
|
|
35
|
+
- enforces readOnly on CREATE_ONLY fields when not in create mode (e.g. for
|
|
36
|
+
update operation)
|
|
37
|
+
- keeps all other field definitions unchanged
|
|
38
|
+
|
|
39
|
+
The resulting model reuses the interface model while allowing most fields
|
|
40
|
+
to be used in API input schemas, except those explicitly marked as hidden
|
|
41
|
+
or restricted by CREATE_ONLY.
|
|
42
|
+
"""
|
|
43
|
+
|
|
44
|
+
def _is_readonly(metadata: list[Any]) -> bool:
|
|
45
|
+
return api.HIDDEN in metadata or (CREATE_ONLY in metadata and not createMode)
|
|
46
|
+
|
|
47
|
+
def _enforce_readonly(finfo: FieldInfo) -> FieldInfo:
|
|
48
|
+
extra = getattr(finfo, "json_schema_extra", None)
|
|
49
|
+
if not isinstance(extra, dict):
|
|
50
|
+
extra = {}
|
|
51
|
+
|
|
52
|
+
extra["readOnly"] = True
|
|
53
|
+
finfo.json_schema_extra = extra
|
|
54
|
+
return finfo
|
|
55
|
+
|
|
56
|
+
def _transform_annotation(annotation: Any) -> Any:
|
|
57
|
+
origin = get_origin(annotation)
|
|
58
|
+
args = get_args(annotation)
|
|
59
|
+
|
|
60
|
+
if origin is Annotated:
|
|
61
|
+
inner_type, *metadata = args
|
|
62
|
+
|
|
63
|
+
if _is_readonly(metadata):
|
|
64
|
+
metadata = [
|
|
65
|
+
_enforce_readonly(m) if isinstance(m, FieldInfo) else m
|
|
66
|
+
for m in metadata
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
return Annotated[_transform_annotation(inner_type), tuple(metadata)]
|
|
70
|
+
|
|
71
|
+
if origin in (list, dict, tuple, set, Union):
|
|
72
|
+
return origin[tuple(_transform_annotation(a) for a in args)]
|
|
73
|
+
|
|
74
|
+
if isinstance(annotation, type) and issubclass(annotation, BaseModel):
|
|
75
|
+
return _build_model(annotation, createMode)
|
|
76
|
+
|
|
77
|
+
return annotation
|
|
78
|
+
|
|
79
|
+
fields = {}
|
|
80
|
+
for fname, finfo in deepcopy(model.model_fields).items():
|
|
81
|
+
new_type = _transform_annotation(finfo.annotation)
|
|
82
|
+
|
|
83
|
+
metadata = getattr(finfo, "metadata", [])
|
|
84
|
+
|
|
85
|
+
if _is_readonly(metadata):
|
|
86
|
+
finfo = _enforce_readonly(finfo)
|
|
87
|
+
|
|
88
|
+
fields[fname] = (new_type, finfo)
|
|
89
|
+
|
|
90
|
+
kwargs: dict[str, Any] = {}
|
|
91
|
+
if (doc := model.__doc__) is not None:
|
|
92
|
+
kwargs["__doc__"] = doc
|
|
93
|
+
|
|
94
|
+
kwargs.update(fields)
|
|
95
|
+
modelType = "Create" if createMode else "Update"
|
|
96
|
+
return create_model(
|
|
97
|
+
f"{model.__name__}{modelType}",
|
|
98
|
+
__base__=model,
|
|
99
|
+
__module__=model.__module__,
|
|
100
|
+
__cls_kwargs__={"extra": "forbid"},
|
|
101
|
+
**kwargs,
|
|
102
|
+
)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@cache
|
|
106
|
+
def _settings() -> Settings:
|
|
107
|
+
try:
|
|
108
|
+
return SiteSettings()
|
|
109
|
+
except (exceptions.SettingsError, ValidationError) as e:
|
|
110
|
+
raise HTTPException(
|
|
111
|
+
status.HTTP_500_INTERNAL_SERVER_ERROR, f"invalid site settings\n{e}"
|
|
112
|
+
) from e
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
_default_settings = cache(Settings)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _instance_update_model() -> type[BaseModel]:
|
|
119
|
+
pm = plugin_manager(_settings())
|
|
120
|
+
return _build_model(interface.Instance.composite(pm))
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _instance_create_model() -> type[BaseModel]:
|
|
124
|
+
pm = plugin_manager(_settings())
|
|
125
|
+
return _build_model(interface.Instance.composite(pm), True)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
@cache
|
|
129
|
+
def _role_model() -> type[interface.Role]:
|
|
130
|
+
pm = plugin_manager(_settings())
|
|
131
|
+
return interface.Role.composite(pm)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
SETTINGS = _settings()
|
|
135
|
+
if TYPE_CHECKING:
|
|
136
|
+
InstanceModel = interface.Instance
|
|
137
|
+
InstanceCreateModel = interface.Instance
|
|
138
|
+
else:
|
|
139
|
+
InstanceModel: interface.Instance = _instance_update_model()
|
|
140
|
+
InstanceCreateModel: interface.Instance = _instance_create_model()
|
pglift_api/databases.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
import uuid
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends, HTTPException, status
|
|
8
|
+
|
|
9
|
+
from pglift import databases, postgresql
|
|
10
|
+
from pglift.models import interface, system
|
|
11
|
+
from pglift.settings import Settings
|
|
12
|
+
|
|
13
|
+
from . import deps, tasks_manager
|
|
14
|
+
|
|
15
|
+
router = APIRouter(prefix="/{version}/{instance_name}/databases", tags=["databases"])
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@router.get("")
|
|
19
|
+
async def get_databases(
|
|
20
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
21
|
+
) -> list[interface.DatabaseListItem]:
|
|
22
|
+
return await databases.ls(instance.postgresql)
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@router.get("/{dbname}")
|
|
26
|
+
async def get_database(
|
|
27
|
+
instance: Annotated[system.Instance, Depends(deps.instance)], dbname: str
|
|
28
|
+
) -> interface.Database:
|
|
29
|
+
if not await databases.exists(instance.postgresql, dbname):
|
|
30
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, detail="Database not found")
|
|
31
|
+
return await databases.get(instance.postgresql, dbname)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
async def _apply_database(
|
|
35
|
+
manifest: interface.Database, pg_instance: system.PostgreSQLInstance
|
|
36
|
+
) -> None:
|
|
37
|
+
async with postgresql.running(pg_instance):
|
|
38
|
+
await databases.apply(pg_instance, manifest)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@router.put("/{dbname}")
|
|
42
|
+
async def update_database(
|
|
43
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
44
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
45
|
+
manifest: interface.Database,
|
|
46
|
+
dbname: str,
|
|
47
|
+
background_tasks: Annotated[
|
|
48
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
49
|
+
],
|
|
50
|
+
) -> uuid.UUID:
|
|
51
|
+
if manifest.name != dbname:
|
|
52
|
+
raise HTTPException(
|
|
53
|
+
status_code=400,
|
|
54
|
+
detail="Manifest does not match URI database qualifier",
|
|
55
|
+
)
|
|
56
|
+
return background_tasks.add_task(
|
|
57
|
+
settings,
|
|
58
|
+
f"update database {dbname}",
|
|
59
|
+
_apply_database,
|
|
60
|
+
manifest,
|
|
61
|
+
instance.postgresql,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@router.post("")
|
|
66
|
+
async def create_database(
|
|
67
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
68
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
69
|
+
manifest: interface.Database,
|
|
70
|
+
background_tasks: Annotated[
|
|
71
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
72
|
+
],
|
|
73
|
+
) -> uuid.UUID:
|
|
74
|
+
return background_tasks.add_task(
|
|
75
|
+
settings,
|
|
76
|
+
f"create database {manifest.name}",
|
|
77
|
+
_apply_database,
|
|
78
|
+
manifest,
|
|
79
|
+
instance.postgresql,
|
|
80
|
+
)
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
async def _delete_database(
|
|
84
|
+
instance: system.Instance, database: interface.Database
|
|
85
|
+
) -> None:
|
|
86
|
+
async with postgresql.running(instance.postgresql):
|
|
87
|
+
await databases.drop(instance.postgresql, database)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
@router.delete("/{dbname}")
|
|
91
|
+
async def delete_database(
|
|
92
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
93
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
94
|
+
database: Annotated[interface.Database, Depends(deps.database)],
|
|
95
|
+
background_tasks: Annotated[
|
|
96
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
97
|
+
],
|
|
98
|
+
) -> uuid.UUID:
|
|
99
|
+
return background_tasks.add_task(
|
|
100
|
+
settings,
|
|
101
|
+
f"delete database {database.name}",
|
|
102
|
+
_delete_database,
|
|
103
|
+
instance,
|
|
104
|
+
database,
|
|
105
|
+
)
|
pglift_api/deps.py
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
from typing import Annotated
|
|
6
|
+
|
|
7
|
+
from fastapi import BackgroundTasks, Depends, HTTPException, status
|
|
8
|
+
|
|
9
|
+
from pglift import databases, exceptions
|
|
10
|
+
from pglift.models import interface, system
|
|
11
|
+
from pglift.settings import Settings, _postgresql
|
|
12
|
+
|
|
13
|
+
from . import _site
|
|
14
|
+
from .tasks_manager import CustomBackgroundTasks
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def get_custom_tasks(background_tasks: BackgroundTasks) -> CustomBackgroundTasks:
|
|
18
|
+
return CustomBackgroundTasks(background_tasks)
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def settings() -> Settings:
|
|
22
|
+
return _site.SETTINGS
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def instance(
|
|
26
|
+
version: _postgresql.Version,
|
|
27
|
+
instance_name: str,
|
|
28
|
+
settings: Annotated[Settings, Depends(_site._settings)],
|
|
29
|
+
) -> system.Instance:
|
|
30
|
+
try:
|
|
31
|
+
return system.Instance.system_lookup(
|
|
32
|
+
instance_name, version=version, settings=settings
|
|
33
|
+
)
|
|
34
|
+
except exceptions.InstanceNotFound as e:
|
|
35
|
+
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e)) from e
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
async def database(
|
|
39
|
+
instance: Annotated[system.Instance, Depends(instance)], dbname: str
|
|
40
|
+
) -> interface.Database:
|
|
41
|
+
if not (await databases.exists(instance.postgresql, dbname)):
|
|
42
|
+
raise HTTPException(status.HTTP_404_NOT_FOUND, "Database not found")
|
|
43
|
+
return await databases.get(instance.postgresql, dbname)
|
pglift_api/instances.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
import uuid
|
|
5
|
+
from typing import Annotated, Any
|
|
6
|
+
|
|
7
|
+
from fastapi import APIRouter, Depends, HTTPException, status
|
|
8
|
+
|
|
9
|
+
from pglift import instances, manager
|
|
10
|
+
from pglift.models import interface, system
|
|
11
|
+
from pglift.settings import PostgreSQLVersion, Settings
|
|
12
|
+
|
|
13
|
+
from . import _site, deps, tasks_manager
|
|
14
|
+
|
|
15
|
+
prefixed_router = APIRouter(prefix="/instances")
|
|
16
|
+
router = APIRouter(tags=["instances"])
|
|
17
|
+
|
|
18
|
+
task_registry: dict[str, dict[str, Any]] = {}
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@router.get("/")
|
|
22
|
+
async def get_instances(
|
|
23
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
24
|
+
) -> list[interface.InstanceListItem]:
|
|
25
|
+
return [item async for item in instances.ls(settings)]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@router.get("/{version}")
|
|
29
|
+
async def get_instances_by_version(
|
|
30
|
+
version: PostgreSQLVersion,
|
|
31
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
32
|
+
) -> list[interface.InstanceListItem]:
|
|
33
|
+
return [item async for item in instances.ls(settings, version=version)]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
async def _apply_instance(manifest: interface.Instance, settings: Settings) -> None:
|
|
37
|
+
with manager.from_manifest(manifest, settings):
|
|
38
|
+
await instances.apply(settings, manifest)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@router.put("/{version}/{instance_name}", status_code=status.HTTP_202_ACCEPTED)
|
|
42
|
+
async def update_instance(
|
|
43
|
+
version: PostgreSQLVersion,
|
|
44
|
+
instance_name: str,
|
|
45
|
+
manifest: _site.InstanceModel,
|
|
46
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
47
|
+
background_tasks: Annotated[
|
|
48
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
49
|
+
],
|
|
50
|
+
) -> uuid.UUID:
|
|
51
|
+
if manifest.version != version or manifest.name != instance_name:
|
|
52
|
+
raise HTTPException(
|
|
53
|
+
status_code=400,
|
|
54
|
+
detail="Manifest does not match URI instance qualifier",
|
|
55
|
+
)
|
|
56
|
+
return background_tasks.add_task(
|
|
57
|
+
settings,
|
|
58
|
+
f"update instance {manifest.qualname}",
|
|
59
|
+
_apply_instance,
|
|
60
|
+
manifest,
|
|
61
|
+
settings,
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@router.post("/", status_code=status.HTTP_202_ACCEPTED)
|
|
66
|
+
async def create_instance(
|
|
67
|
+
manifest: _site.InstanceCreateModel,
|
|
68
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
69
|
+
background_tasks: Annotated[
|
|
70
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
71
|
+
],
|
|
72
|
+
) -> uuid.UUID:
|
|
73
|
+
if instances.exists(manifest.name, manifest.version, settings):
|
|
74
|
+
raise HTTPException(status_code=409, detail="Instance already exists")
|
|
75
|
+
return background_tasks.add_task(
|
|
76
|
+
settings,
|
|
77
|
+
f"create instance {manifest.qualname}",
|
|
78
|
+
_apply_instance,
|
|
79
|
+
manifest,
|
|
80
|
+
settings,
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
@router.get("/{version}/{instance_name}")
|
|
85
|
+
async def get_instance(
|
|
86
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
87
|
+
) -> interface.Instance:
|
|
88
|
+
return await instances.get(instance)
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
async def _delete_instance(instance: system.Instance) -> None:
|
|
92
|
+
with manager.from_instance(instance.postgresql):
|
|
93
|
+
await instances.drop(instance)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@router.delete("/{version}/{instance_name}")
|
|
97
|
+
async def delete_instance(
|
|
98
|
+
instance: Annotated[system.Instance, Depends(deps.instance)],
|
|
99
|
+
settings: Annotated[Settings, Depends(deps.settings)],
|
|
100
|
+
background_tasks: Annotated[
|
|
101
|
+
tasks_manager.CustomBackgroundTasks, Depends(deps.get_custom_tasks)
|
|
102
|
+
],
|
|
103
|
+
) -> uuid.UUID:
|
|
104
|
+
return background_tasks.add_task(
|
|
105
|
+
settings, f"delete instance {instance.qualname}", _delete_instance, instance
|
|
106
|
+
)
|
pglift_api/pm.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
from pglift.pm import PluginManager as BasePluginManager
|
|
8
|
+
|
|
9
|
+
from . import __name__ as pkgname
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class PluginManager(BasePluginManager):
|
|
13
|
+
ns = pkgname
|
|
14
|
+
modules = ("patroni", "pgbackrest", "pgbackrest.repo_path", "prometheus")
|
pglift_api/py.typed
ADDED
|
File without changes
|
pglift_api/tasks.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import uuid
|
|
7
|
+
from typing import Annotated
|
|
8
|
+
|
|
9
|
+
from fastapi import APIRouter, Depends, HTTPException
|
|
10
|
+
|
|
11
|
+
from pglift.settings import Settings
|
|
12
|
+
|
|
13
|
+
from . import deps
|
|
14
|
+
from ._compat import TypedDict
|
|
15
|
+
from .tasks_manager import TaskResponse, task_registry
|
|
16
|
+
|
|
17
|
+
router = APIRouter(prefix="/tasks", tags=["tasks"])
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class TaskListItem(TypedDict):
|
|
21
|
+
id: uuid.UUID
|
|
22
|
+
state: str
|
|
23
|
+
description: str
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
@router.get("/")
|
|
27
|
+
def list_tasks() -> list[TaskListItem]:
|
|
28
|
+
"""
|
|
29
|
+
Return all registered background tasks and their current state.
|
|
30
|
+
"""
|
|
31
|
+
return [
|
|
32
|
+
TaskListItem(id=u, state=v.state, description=v.description)
|
|
33
|
+
for u, v in task_registry.tasks.items()
|
|
34
|
+
]
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@router.get("/{task_id}")
|
|
38
|
+
def get_task(
|
|
39
|
+
task_id: uuid.UUID, settings: Annotated[Settings, Depends(deps.settings)]
|
|
40
|
+
) -> TaskResponse:
|
|
41
|
+
"""
|
|
42
|
+
Return logs of a specific background task.
|
|
43
|
+
"""
|
|
44
|
+
task = task_registry.tasks.get(task_id)
|
|
45
|
+
if not task:
|
|
46
|
+
raise HTTPException(status_code=404, detail="Task not found")
|
|
47
|
+
formatter = logging.Formatter(fmt=settings.api.log_format)
|
|
48
|
+
return TaskResponse.from_request(task, formatter)
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Dalibo
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: GPL-3.0-or-later
|
|
4
|
+
|
|
5
|
+
import contextlib
|
|
6
|
+
import dataclasses
|
|
7
|
+
import inspect
|
|
8
|
+
import logging
|
|
9
|
+
import queue
|
|
10
|
+
import uuid
|
|
11
|
+
from collections.abc import Callable, Iterator
|
|
12
|
+
from datetime import datetime, timezone
|
|
13
|
+
from logging.handlers import QueueHandler
|
|
14
|
+
from typing import Annotated, Any, Literal, ParamSpec
|
|
15
|
+
|
|
16
|
+
import pydantic
|
|
17
|
+
from fastapi import BackgroundTasks
|
|
18
|
+
|
|
19
|
+
from pglift.settings import Settings
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclasses.dataclass
|
|
23
|
+
class BaseTask:
|
|
24
|
+
"""
|
|
25
|
+
Base class representing a task. This class represents common task
|
|
26
|
+
metadata such as execution state, error presence, and an optional
|
|
27
|
+
exception message. It is intended to be shared by task request and
|
|
28
|
+
response classes.
|
|
29
|
+
"""
|
|
30
|
+
|
|
31
|
+
description: Annotated[
|
|
32
|
+
str,
|
|
33
|
+
pydantic.Field(description="Description of the current task."),
|
|
34
|
+
]
|
|
35
|
+
created_at: datetime = dataclasses.field(
|
|
36
|
+
default_factory=lambda: datetime.now(tz=timezone.utc)
|
|
37
|
+
)
|
|
38
|
+
completed_at: datetime | None = None
|
|
39
|
+
state: Literal["created", "running", "completed"] = "created"
|
|
40
|
+
error: Annotated[
|
|
41
|
+
bool,
|
|
42
|
+
pydantic.Field(
|
|
43
|
+
description="Indicates whether processing task failed due to an exception."
|
|
44
|
+
),
|
|
45
|
+
] = False
|
|
46
|
+
exception: Annotated[
|
|
47
|
+
str | None,
|
|
48
|
+
pydantic.Field(description="String representation of the raised exception."),
|
|
49
|
+
] = None
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
@dataclasses.dataclass
|
|
53
|
+
class TaskRequest(BaseTask):
|
|
54
|
+
"""
|
|
55
|
+
Mutable task representation used internally during task execution.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
log_queue: queue.Queue[logging.LogRecord] = dataclasses.field(
|
|
59
|
+
default_factory=queue.Queue
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class TaskResponse(pydantic.BaseModel, BaseTask, frozen=True):
|
|
64
|
+
"""
|
|
65
|
+
This combines the base task state with rendered log output to
|
|
66
|
+
produce an immutable, serializable view of task. This could be
|
|
67
|
+
used to expose the task to API consumers.
|
|
68
|
+
"""
|
|
69
|
+
|
|
70
|
+
logs: Annotated[list[str], pydantic.Field(description="")] = []
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_request(
|
|
74
|
+
cls, request: TaskRequest, formatter: logging.Formatter
|
|
75
|
+
) -> "TaskResponse":
|
|
76
|
+
"""
|
|
77
|
+
Build a TaskResponse from a TaskRequest.
|
|
78
|
+
|
|
79
|
+
This copies the request fields (excluding the log_queue), reads and
|
|
80
|
+
formats all log records from the request's log_queue into a list of
|
|
81
|
+
strings, and stores the exception as a string if there is one.
|
|
82
|
+
"""
|
|
83
|
+
|
|
84
|
+
# exclude log_queue, it's not serializable for / by pydantic
|
|
85
|
+
# and fastapi result.
|
|
86
|
+
data = {
|
|
87
|
+
field.name: getattr(request, field.name)
|
|
88
|
+
for field in dataclasses.fields(request)
|
|
89
|
+
if field.name not in {"log_queue"}
|
|
90
|
+
}
|
|
91
|
+
data["logs"] = []
|
|
92
|
+
# read log until the queue is empty with a default timeout.
|
|
93
|
+
while True:
|
|
94
|
+
try:
|
|
95
|
+
data["logs"].append(
|
|
96
|
+
formatter.format(request.log_queue.get(block=True, timeout=0.3))
|
|
97
|
+
)
|
|
98
|
+
except queue.Empty:
|
|
99
|
+
break
|
|
100
|
+
# and store exception if there is one
|
|
101
|
+
data["exception"] = str(request.exception) if request.exception else None
|
|
102
|
+
return cls(**data)
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclasses.dataclass
|
|
106
|
+
class TaskRegistry:
|
|
107
|
+
"""
|
|
108
|
+
Simple class for tracking asynchronous tasks.
|
|
109
|
+
|
|
110
|
+
This maintains a mapping of task IDs to TaskRequest instances,
|
|
111
|
+
allowing to keep track of tasks.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
tasks: dict[uuid.UUID, TaskRequest] = dataclasses.field(default_factory=dict)
|
|
115
|
+
|
|
116
|
+
def createTask(self, description: str) -> uuid.UUID:
|
|
117
|
+
task_id = uuid.uuid4()
|
|
118
|
+
self.tasks.update({task_id: TaskRequest(description=description)})
|
|
119
|
+
return task_id
|
|
120
|
+
|
|
121
|
+
def get(self, t_id: uuid.UUID) -> TaskRequest | None:
|
|
122
|
+
return self.tasks.get(t_id)
|
|
123
|
+
|
|
124
|
+
def update(self, t_id: uuid.UUID, task: TaskRequest) -> None:
|
|
125
|
+
self.tasks.update({t_id: task})
|
|
126
|
+
|
|
127
|
+
@property
|
|
128
|
+
def tasks_ids(self) -> list[uuid.UUID]:
|
|
129
|
+
return list(self.tasks)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
task_registry = TaskRegistry()
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@contextlib.contextmanager
|
|
136
|
+
def logged_task(settings: Settings, task_id: uuid.UUID) -> Iterator[None]:
|
|
137
|
+
"""
|
|
138
|
+
Context manager for running a task with dedicated logging.
|
|
139
|
+
|
|
140
|
+
Registers a new task in the task registry and attaches a logger
|
|
141
|
+
streaming logs into the task's log queue. Any exceptions raised
|
|
142
|
+
during the block are recorded in the task, and the task state
|
|
143
|
+
is marked as completed before exiting the context.
|
|
144
|
+
"""
|
|
145
|
+
|
|
146
|
+
t = task_registry.get(task_id)
|
|
147
|
+
if (t := task_registry.get(task_id)) is None:
|
|
148
|
+
raise ValueError(f"task with ID {task_id} not found in registry.")
|
|
149
|
+
|
|
150
|
+
# Then configure the logger for it
|
|
151
|
+
pglift_logger = logging.getLogger("pglift")
|
|
152
|
+
if settings.api.log_level is not None:
|
|
153
|
+
pglift_logger.setLevel(settings.api.log_level)
|
|
154
|
+
|
|
155
|
+
q_handler = QueueHandler(t.log_queue)
|
|
156
|
+
pglift_logger.addHandler(q_handler)
|
|
157
|
+
pglift_logger.propagate = False
|
|
158
|
+
|
|
159
|
+
# let the task run with the logger configured
|
|
160
|
+
try:
|
|
161
|
+
yield
|
|
162
|
+
except Exception as e: # noqa: BLE001
|
|
163
|
+
t.error = True
|
|
164
|
+
t.exception = str(e)
|
|
165
|
+
finally:
|
|
166
|
+
t.state = "completed"
|
|
167
|
+
t.completed_at = datetime.now(tz=timezone.utc)
|
|
168
|
+
q_handler.close()
|
|
169
|
+
pglift_logger.removeHandler(q_handler)
|
|
170
|
+
task_registry.update(task_id, t)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
P = ParamSpec("P")
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class CustomBackgroundTasks:
|
|
177
|
+
def __init__(self, background_tasks: BackgroundTasks):
|
|
178
|
+
self.background_tasks = background_tasks
|
|
179
|
+
|
|
180
|
+
def add_task(
|
|
181
|
+
self,
|
|
182
|
+
settings: Settings,
|
|
183
|
+
description: str,
|
|
184
|
+
func: Callable[P, Any],
|
|
185
|
+
*args: P.args,
|
|
186
|
+
**kwargs: P.kwargs,
|
|
187
|
+
) -> uuid.UUID:
|
|
188
|
+
|
|
189
|
+
task_id = task_registry.createTask(description)
|
|
190
|
+
|
|
191
|
+
async def wrapper() -> Any:
|
|
192
|
+
with logged_task(settings, task_id=task_id):
|
|
193
|
+
result = func(*args, **kwargs)
|
|
194
|
+
if inspect.isawaitable(result):
|
|
195
|
+
return await result
|
|
196
|
+
return result
|
|
197
|
+
|
|
198
|
+
self.background_tasks.add_task(wrapper)
|
|
199
|
+
return task_id
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pglift_api
|
|
3
|
+
Version: 3.3.0
|
|
4
|
+
Summary: Life-cycle management of production-ready PostgreSQL instances
|
|
5
|
+
Project-URL: Documentation, https://pglift.readthedocs.io/
|
|
6
|
+
Project-URL: Source, https://gitlab.com/dalibo/pglift/
|
|
7
|
+
Project-URL: Tracker, https://gitlab.com/dalibo/pglift/-/issues/
|
|
8
|
+
Author-email: Dalibo SCOP <contact@dalibo.com>
|
|
9
|
+
License: GPLv3
|
|
10
|
+
Keywords: administration,deployment,postgresql
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Classifier: Topic :: Database
|
|
22
|
+
Classifier: Topic :: System :: Systems Administration
|
|
23
|
+
Classifier: Typing :: Typed
|
|
24
|
+
Requires-Python: <4,>=3.10
|
|
25
|
+
Requires-Dist: fastapi
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: pglift[test,typing]; extra == 'dev'
|
|
28
|
+
Requires-Dist: uvicorn; extra == 'dev'
|
|
29
|
+
Provides-Extra: test
|
|
30
|
+
Requires-Dist: pytest-cov; extra == 'test'
|
|
31
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
32
|
+
Provides-Extra: typing
|
|
33
|
+
Requires-Dist: mypy>=1.10.0; extra == 'typing'
|
|
34
|
+
Requires-Dist: types-psutil; extra == 'typing'
|
|
35
|
+
Requires-Dist: types-python-dateutil; extra == 'typing'
|
|
36
|
+
Description-Content-Type: text/markdown
|
|
37
|
+
|
|
38
|
+
<!--
|
|
39
|
+
SPDX-FileCopyrightText: 2026 Dalibo
|
|
40
|
+
|
|
41
|
+
SPDX-License-Identifier: GPL-3.0-or-later
|
|
42
|
+
-->
|
|
43
|
+
|
|
44
|
+
This package contains the HTTP API for
|
|
45
|
+
[pglift](https://pglift.readthedocs.io/). It is a dependency package and
|
|
46
|
+
should not be installed directly but rather through the `api` *optional
|
|
47
|
+
dependency* (aka "extra") of pglift package, e.g.:
|
|
48
|
+
|
|
49
|
+
$ pip install "pglift[api]"
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pglift_api/__init__.py,sha256=ucfLXj-CjocAr0QBeiQ1WnwojlNaix1H5kC0PxHGWII,371
|
|
2
|
+
pglift_api/_compat.py,sha256=9E0h5vB4hHMLR2RfGp7S41KxLuXHCuAOxE7aq9hojeI,376
|
|
3
|
+
pglift_api/_site.py,sha256=GV9MaYIiBEy0BPgac-wUdt5VdGkrToB2N37vUUQkXjI,4289
|
|
4
|
+
pglift_api/databases.py,sha256=eGJDC1KwQW9qBlBFRlAL8MgecAZwOl1DKI-MhzPgFSU,3193
|
|
5
|
+
pglift_api/deps.py,sha256=ev9HMx6U1cGfKjNNiVY9sCUqh_x9oyYEsYEbDx-xBwA,1321
|
|
6
|
+
pglift_api/instances.py,sha256=I5zCPu-BwMFWezr8WqQ3ZSHZr7fD9ecrN9NdPv9A9rI,3391
|
|
7
|
+
pglift_api/pm.py,sha256=3ciIct2FFDlzbu71Z2vgWu1FxYWBjddFiy9VXiEfzTs,350
|
|
8
|
+
pglift_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
+
pglift_api/tasks.py,sha256=obtuG-HxfWeOjVXUfvJe-_6GHZo9ShiF5s1yVxqukUE,1209
|
|
10
|
+
pglift_api/tasks_manager.py,sha256=M9miX1EjtX4hFO4KudAfQehmgTxW0VLcoZr7lgCIZ28,6004
|
|
11
|
+
pglift_api-3.3.0.dist-info/METADATA,sha256=LjTDAhkJFbhqvMSu9T4WgKT-V6zmWQO3i03mxm6-4Gs,1903
|
|
12
|
+
pglift_api-3.3.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
|
|
13
|
+
pglift_api-3.3.0.dist-info/RECORD,,
|