-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
230 lines (199 loc) · 6.82 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
"""Simple app for the SimPARTIX simulation code."""
import json
import logging
from fastapi import FastAPI, HTTPException, Response
from marketplace_standard_app_api.models.transformation import (
TransformationCreateResponse,
TransformationId,
TransformationListResponse,
TransformationModel,
TransformationStateResponse,
TransformationUpdateModel,
TransformationUpdateResponse,
)
from marketplace_standard_app_api.routers import object_storage
from models.transformation import TransformationInput
from simulation_controller.simulation_manager import (
SimulationManager,
mappings,
)
app = FastAPI()
simulation_manager = SimulationManager()
@app.get(
"/heartbeat", operation_id="heartbeat", summary="Check if app is alive"
)
async def heartbeat():
return "SimPARTIX app up and running"
@app.post(
"/transformations",
operation_id="newTransformation",
summary="Create a new transformation",
response_model=TransformationCreateResponse,
)
async def new_simulation(
payload: TransformationInput,
) -> TransformationCreateResponse:
id = simulation_manager.create_simulation(payload)
return {"id": id}
@app.get(
"/transformations/{transformation_id}",
summary="Get a transformation",
response_model=TransformationModel,
operation_id="getTransformation",
responses={
404: {"description": "Not Found."},
400: {"description": "Error executing get operation"},
},
)
def get_simulation(transformation_id: TransformationId):
try:
return simulation_manager.get_simulation(str(transformation_id))
except KeyError as ke:
raise HTTPException(status_code=404, detail=str(ke))
except RuntimeError as re:
raise HTTPException(status_code=400, detail=str(re))
@app.get(
"/transformations",
summary="Get all simulations.",
response_model=TransformationListResponse,
operation_id="getTransformationList",
)
def get_simulations():
try:
items: list = simulation_manager.get_simulations()
logging.info(f"simulations: {items}")
return {"items": items}
except Exception as e:
msg = (
"Unexpected error while fetching the list of simulations. "
f"Error message: {e}"
)
logging.error(msg)
return Response(msg, status=400)
@app.patch(
"/transformations/{transformation_id}",
summary="Update the state of the simulation.",
response_model=TransformationUpdateResponse,
operation_id="updateTransformation",
responses={
404: {"description": "Not Found."},
409: {"description": "Requested state not available"},
400: {"description": "Error executing update operation"},
},
)
def update_simulation_state(
transformation_id: TransformationId, payload: TransformationUpdateModel
) -> TransformationUpdateResponse:
state = payload.state
try:
if state == "RUNNING":
simulation_manager.run_simulation(str(transformation_id))
elif state == "STOPPED":
simulation_manager.stop_simulation(str(transformation_id))
else:
msg = f"{state} is not a supported state."
raise HTTPException(status_code=400, detail=msg)
return {"id": TransformationId(transformation_id), "state": state}
except KeyError:
raise HTTPException(
status_code=404,
detail=f"Transformation not found: {transformation_id}",
)
except RuntimeError as re:
raise HTTPException(status_code=409, detail=str(re))
except Exception as e:
msg = (
"Unexpected error while changing state of simulation "
f"{transformation_id}. Error message: {e}"
)
logging.error(msg)
raise HTTPException(status_code=400, detail=msg)
@app.get(
"/transformations/{transformation_id}/state",
summary="Get the state of the simulation.",
response_model=TransformationStateResponse,
operation_id="getTransformationState",
responses={
404: {"description": "Unknown simulation"},
400: {"description": "Error executing get operation"},
},
)
def get_simulation_state(
transformation_id: TransformationId,
) -> TransformationStateResponse:
"""Get the state of a simulation.
Args:
transformation_id (TransformationId): ID of the simulation
Returns:
TransformationStateResponse: The state of the simulation.
"""
try:
state = simulation_manager.get_simulation_state(str(transformation_id))
return {"id": transformation_id, "state": state}
except KeyError:
raise HTTPException(status_code=404, detail="Simulation not found")
except Exception as e:
msg = (
"Unexpected error while querying for the status of simulation "
f"{transformation_id}. Error message: {e}"
)
raise HTTPException(status_code=400, detail=msg)
@app.delete(
"/transformations/{transformation_id}",
summary="Delete a transformation",
operation_id="deleteTransformation",
responses={
404: {"description": "Unknown simulation"},
400: {"description": "Error executing delete operation"},
},
)
def delete_simulation(transformation_id: TransformationId):
try:
simulation_manager.delete_simulation(str(transformation_id))
return {
"status": f"Simulation '{transformation_id}' deleted successfully!"
}
except KeyError as ke:
raise HTTPException(status_code=404, detail=str(ke))
except RuntimeError as re:
raise HTTPException(status_code=400, detail=str(re))
except Exception as e:
msg = (
"Unexpected error while deleting simulation "
f"{transformation_id}. Error message: {e}"
)
raise HTTPException(status_code=400, detail=msg)
@app.get(
"/results",
summary="Get a simulation's result",
operation_id="getDataset",
responses={200: {"content": {"vnd.sintef.dlite+json"}}},
)
def get_results(
collection_name: object_storage.CollectionName,
dataset_name: object_storage.DatasetName,
response: Response,
):
json_payload = simulation_manager.get_simulation_output(str(dataset_name))
response.headers["x-semantic-mappings"] = "SimpartixOutput"
return json_payload
@app.get(
"/mappings",
summary="Get a list of the available mappings",
operation_id="listSemanticMappings",
)
def list_mappings():
return list(mappings.keys())
@app.get(
"/mappings/{semantic_mapping_id}",
summary="Get a specific mapping",
operation_id="getSemanticMapping",
responses={
404: {"description": "Unknown mapping"},
},
)
def get_mapping(semantic_mapping_id: str):
mapping = json.dumps(mappings.get(semantic_mapping_id))
if not mapping:
raise HTTPException(status_code=404, detail="Mapping not found")
return mapping