1313// limitations under the License.
1414
1515use actix_web:: web:: Path ;
16+ use ainari_api_structs:: task_structs:: TaskState ;
1617use apistos:: actix:: NoContent ;
1718use apistos:: api_operation;
1819use uuid:: Uuid ;
1920
2021use crate :: core:: model_handler;
2122use crate :: database:: model_table;
23+ use crate :: database:: task_table;
2224
23- use ainari_api:: common_functions:: map_ainari_error_to_api_response;
24- use ainari_api:: common_functions:: map_db_uuid_get_delete_error;
25+ use ainari_api:: common_functions:: * ;
2526use ainari_api:: errors:: ErrorResponse ;
2627use ainari_api_structs:: user_context:: UserContext ;
2728
@@ -38,13 +39,50 @@ pub async fn delete_model_internal(
3839 model_uuid : Path < Uuid > ,
3940 context : UserContext ,
4041) -> Result < NoContent , ErrorResponse > {
42+ // list all tasks
43+ let tasks = match task_table:: list_tasks ( & model_uuid, & context) {
44+ Ok ( tasks) => tasks,
45+ Err ( e) => {
46+ log:: error!( "Failed to get list of tasks form database: '{e}'" ) ;
47+ return Err ( ErrorResponse :: InternalError ( "Internal Error" . to_string ( ) ) ) ;
48+ }
49+ } ;
50+
51+ // abort all open tasks
52+ for task in tasks {
53+ let uuid = convert_uuid ( & task. uuid ) ?;
54+ let task_state = super :: task:: convert_task_state ( & task. task_state ) ?;
55+
56+ if task_state == TaskState :: Created
57+ || task_state == TaskState :: Queued
58+ || task_state == TaskState :: Active
59+ {
60+ task_table:: update_task_state ( & uuid, & TaskState :: Aborted )
61+ . map_err ( |e| map_db_uuid_get_delete_error ( "task" , & uuid, e) ) ?;
62+ }
63+ }
64+
65+ // prepare delete of model from core
66+ let model_handle = model_handler:: CLUSTER_HANDLER
67+ . write ( )
68+ . expect ( "mutex poisoned" ) ;
69+ let model_interface = model_handle
70+ . get_model_interface ( & model_uuid)
71+ . map_err ( map_ainari_error_to_api_response) ?;
72+ drop ( model_handle) ;
73+
74+ // stop the interface. This must be done outside of the model_handler to avoid a dead-lock
75+ let mut interface = model_interface. lock ( ) . expect ( "mutex poisoned" ) ;
76+ interface. stop ( ) ;
77+
4178 // delete model from core
4279 let mut model_handle = model_handler:: CLUSTER_HANDLER
4380 . write ( )
4481 . expect ( "mutex poisoned" ) ;
4582 model_handle
4683 . delete_model ( & model_uuid)
4784 . map_err ( map_ainari_error_to_api_response) ?;
85+ drop ( model_handle) ;
4886
4987 // delete model from database
5088 model_table:: delete_model ( & model_uuid, & context)
0 commit comments