diff --git a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py index 9cd39d618..e10e89494 100644 --- a/pandajedi/jedidog/AtlasDataCarouselWatchDog.py +++ b/pandajedi/jedidog/AtlasDataCarouselWatchDog.py @@ -26,6 +26,7 @@ StageDCRequests_LOCK_TIME_MINUTES = 5 CheckDCRequests_LOCK_TIME_MINUTES = 5 KeepRulesAlive_LOCK_TIME_MINUTES = 60 +UpdateRequestsUsage_LOCK_TIME_MINUTES = 480 CleanDCRequests_LOCK_TIME_MINUTES = 1440 RescuePendingTasks_LOCK_TIME_MINUTES = 120 @@ -123,6 +124,28 @@ def doKeepRulesAlive(self) -> None: errtype, errvalue = sys.exc_info()[:2] tmpLog.error(f"failed with {errtype} {errvalue} {traceback.format_exc()}") + def doUpdateRequestsUsage(self) -> None: + """ + Action to update the usage of DC requests (remove_when_done and last_used_time) according to their related tasks, + and keep alive DDM rules of done requests within grace period after last used + """ + tmpLog = MsgWrapper(logger, " #ATM #KV doUpdateRequestsUsage") + tmpLog.debug("start") + try: + # watchdog lock + got_lock = self.get_process_lock("AtlasDataCarousDog.doUpdateReqUsage", timeLimit=UpdateRequestsUsage_LOCK_TIME_MINUTES) + if not got_lock: + tmpLog.debug("locked by another watchdog process. Skipped") + return + tmpLog.debug("got watchdog lock") + # update usage of requests + self.data_carousel_interface.update_requests_usage() + # done + tmpLog.debug("done") + except Exception: + errtype, errvalue = sys.exc_info()[:2] + tmpLog.error(f"failed with {errtype} {errvalue} {traceback.format_exc()}") + def doCleanDCRequests(self) -> None: """ Action to clean up old DC requests in DB table @@ -171,6 +194,8 @@ def doAction(self) -> Interaction.StatusCode: # get logger origTmpLog = MsgWrapper(logger) origTmpLog.debug("start") + # update usage of DC requests before cleaning them up + self.doUpdateRequestsUsage() # clean up old DC requests self.doCleanDCRequests() # keep staging rules alive diff --git a/pandaserver/taskbuffer/DataCarousel.py b/pandaserver/taskbuffer/DataCarousel.py index ae7959907..286b9f96c 100644 --- a/pandaserver/taskbuffer/DataCarousel.py +++ b/pandaserver/taskbuffer/DataCarousel.py @@ -85,6 +85,12 @@ STAGING_LIFETIME_DAYS = 15 DONE_LIFETIME_DAYS = 30 +# default grace period in days to keep a done request (and its DDM rule) after the last related task ended; overridden by config LAST_USED_GRACE_DAYS +DEFAULT_LAST_USED_GRACE_DAYS = 15 + +# margin in days of DDM rule lifetime beyond the grace period after last used, to cover the interval of clean-up (once a day by watchdog) +LAST_USED_GRACE_RULE_MARGIN_DAYS = 1 + # DDM rule refresh hard lifetime limits (refresh only if lifetime within the range) TO_REFRESH_MAX_LIFETIME_DAYS = 7 TO_REFRESH_MIN_LIFETIME_HOURS = 2 @@ -178,7 +184,10 @@ def parameter_map(self) -> dict[str, Any]: "to_pin" (bool): whether to pin the dataset "to_backfill" (bool): whether the request is to backfill (all its active tasks have data_carousel_backfill), queued with lowest priority "suggested_dst_list" (list[str]): list of suggested destination RSEs - "remove_when_done" (bool): remove request and DDM rule asap when request done to save disk space + "remove_when_done" (bool): remove request and DDM rule asap when request done and all related tasks ended, to save disk space ; + kept updated to be True if any active task of the request has task parameter remove_rule_when_done + "last_used_time" (str): time in ISO format when the request was last used: updated to now periodically while having active tasks, + and to when the last related task ended after all related tasks ended ; the request is kept for a grace period after it "task_id": (int): task_id of the task which initiates the request "init_task_gshare": (str): (deprecated) original gshare of the task which initiates the request, for statistics "task_gshare": (str): original gshare of the task which initiates the request, for statistics @@ -480,6 +489,8 @@ def __init__(self, taskbufferIF: "TaskBuffer", *args: Any, **kwargs: Any) -> Non self._last_update_ts_dict: dict[str, datetime | None] = {} # cache of task params map per task ID; task params do not change after task submission self._task_params_cache: dict[int, dict[str, Any]] = {} + # task IDs still needed in the cache of task params map, per consumer + self._task_params_cache_seen_map: dict[str, set[int]] = {} # full pid self.full_pid = f"{socket.getfqdn().split('.')[0]}-{os.getpgrp()}-{os.getpid()}" # refresh @@ -779,6 +790,7 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener # got_lock = None locked_spec = None + lock_start_time = None try: # try to update locked_by and lock_time sql_lock = ( @@ -803,9 +815,10 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener got_lock = False tmp_log.debug("did not get lock; skipped") else: - # got the lock + # got the lock ; not to log as it is routine got_lock = True - tmp_log.debug("got lock") + lock_start_time = naive_utcnow() + # tmp_log.debug("got lock") if got_lock: # yield the updated request spec locked locked_spec = self.get_request_by_id(request_id) @@ -832,8 +845,11 @@ def request_lock(self, request_id: int, lock_expiration_sec: int = 120) -> Gener tmp_log.error("more than one requests updated to unlock; unexpected") elif row_count == 0: tmp_log.error("no request updated to unlock; skipped") - else: - tmp_log.debug("released lock") + elif lock_start_time is not None and (lock_held_sec := (naive_utcnow() - lock_start_time).total_seconds()) > lock_expiration_sec / 2: + # released the lock ; only to log when held so long that it could expire and be taken by others + tmp_log.warning(f"released lock held for {lock_held_sec:.1f} sec, over half of lock_expiration_sec={lock_expiration_sec}") + # else: + # tmp_log.debug("released lock") def _update_rses(self, time_limit_minutes: int | float = 30) -> None: """ @@ -1771,6 +1787,22 @@ def _get_task_params_map(self, task_id: int) -> dict[str, Any] | None: self._task_params_cache[task_id] = task_params_map return task_params_map + def _prune_task_params_cache(self, consumer: str, seen_task_ids: set[int]) -> None: + """ + Record the task IDs still needed by a consumer of the cache of task params map, and drop the tasks needed by no consumer + + Args: + consumer (str): name of the consumer, e.g. the calling method + seen_task_ids (set[int]): task IDs the consumer saw in its latest run + """ + self._task_params_cache_seen_map[consumer] = seen_task_ids + needed_task_ids: set[int] = set() + for task_ids in self._task_params_cache_seen_map.values(): + needed_task_ids |= task_ids + for task_id in list(self._task_params_cache): + if task_id not in needed_task_ids: + del self._task_params_cache[task_id] + def _all_active_tasks_to_backfill(self, task_specs: list[JediTaskSpec]) -> bool: """ Check whether there are active tasks and all of them have task parameter data_carousel_backfill @@ -1835,9 +1867,7 @@ def _update_to_backfill(self, queued_requests: list[tuple[DataCarouselRequestSpe except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") # clean up cache of tasks not mapped to queued requests anymore - for task_id in list(self._task_params_cache): - if task_id not in seen_task_ids: - del self._task_params_cache[task_id] + self._prune_task_params_cache("_update_to_backfill", seen_task_ids) tmp_log.debug(f"got {n_to_backfill} requests to backfill ; updated {n_updated} requests in DB") def submit_data_carousel_requests( @@ -2826,15 +2856,23 @@ def _check_ddm_rule_of_request( # return return is_valid, ddm_rule_id, the_rule - def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, lifetime_days: int, force_refresh: bool = False, by: str = "unknown") -> bool: + def refresh_ddm_rule_of_request( + self, + dc_req_spec: DataCarouselRequestSpec, + lifetime_days: int | None = None, + force_refresh: bool = False, + by: str = "unknown", + until_time: datetime | None = None, + ) -> bool: """ Refresh lifetime of the DDM rule of one request Args: dc_req_spec (DataCarouselRequestSpec): spec of the request - lifetime_days (int): lifetime in days to set - force_refresh (bool): force to refresh regardless of to_refresh max/min lifetime + lifetime_days (int|None): lifetime in days to set ; ignored if until_time is given + force_refresh (bool): force to refresh regardless of to_refresh max/min lifetime ; ignored if until_time is given by (str): annotation of the caller of this method; default is "watchdog" + until_time (datetime|None): if given, refresh only if the rule expires before until_time, to make it last until until_time Returns: bool : True for success, False otherwise @@ -2848,10 +2886,18 @@ def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, life # rule not valid; skipped tmp_log.error(f"ddm_rule_id={ddm_rule_id} rule not valid; skipped") return ret + now_time = naive_utcnow() + if until_time is not None: + # refresh only if the rule expires before until_time ; rule without expiration lasts long enough + if the_rule["expires_at"] and the_rule["expires_at"] < until_time: + ret = self._refresh_ddm_rule(ddm_rule_id, int((until_time - now_time).total_seconds())) + return ret + if lifetime_days is None: + tmp_log.error("neither lifetime_days nor until_time given ; skipped") + return ret # rule lifetime rule_lifetime = None if the_rule["expires_at"]: - now_time = naive_utcnow() rule_lifetime = the_rule["expires_at"] - now_time # trigger renewal if force_refresh or when lifetime within the range if ( @@ -2870,6 +2916,39 @@ def refresh_ddm_rule_of_request(self, dc_req_spec: DataCarouselRequestSpec, life # return return ret + def _get_last_used_grace_days(self) -> int | float: + """ + Get the grace period in days to keep a done request after its last related task ended + + Returns: + int | float : grace period in days, from config LAST_USED_GRACE_DAYS or default + """ + grace_days = self.taskBufferIF.getConfigValue("data_carousel", "LAST_USED_GRACE_DAYS", "jedi", "atlas") + if not isinstance(grace_days, (int, float)) or grace_days < 0: + return DEFAULT_LAST_USED_GRACE_DAYS + return grace_days + + def _get_grace_end_time(self, dc_req_spec: DataCarouselRequestSpec, grace_days: int | float) -> datetime | None: + """ + Get the end of the grace period of the request, i.e. last_used_time in its parameters plus grace_days + + Args: + dc_req_spec (DataCarouselRequestSpec): spec of the request + grace_days (int|float): grace period in days after last used + + Returns: + datetime | None : end time of the grace period, or None if last_used_time not set or invalid + """ + last_used_time_str = dc_req_spec.get_parameter("last_used_time") + if not last_used_time_str: + return None + try: + return datetime.fromisoformat(last_used_time_str) + timedelta(days=grace_days) + except ValueError: + tmp_log = LogWrapper(logger, f"_get_grace_end_time request_id={dc_req_spec.request_id}") + tmp_log.warning(f"got invalid last_used_time={last_used_time_str} ; ignored") + return None + def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: """ Keep alive DDM rules of requests of active tasks; also check all requests if their DDM rules are valid @@ -2878,20 +2957,23 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: by (str): annotation of the caller of this method; default is "watchdog" """ tmp_log = LogWrapper(logger, "keep_alive_ddm_rules") - # get all requests, and those of active tasks - all_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI() - active_tasked_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_exclusion_list=FINAL_TASK_STATUSES) - if all_requests is None or active_tasked_requests is None: + # get staging and done requests with their related tasks + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI([DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]) + if requests_with_tasks is None: tmp_log.warning("failed to query requests ; skipped") return - all_requests_map, _ = all_requests - active_tasked_requests_map, _ = active_tasked_requests - for dc_req_spec in all_requests_map.values(): + for dc_req_spec, task_specs in requests_with_tasks: try: - if dc_req_spec.status not in [DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]: - # skip requests without need to keep rules alive + if not task_specs: + # requests without tasks ; skipped continue - if dc_req_spec.request_id in active_tasked_requests_map: + # whether with active tasks + has_active_task = False + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + break + if has_active_task: # requests of active tasks; decide lifetime in days days = None if dc_req_spec.status == DataCarouselRequestStatus.staging: @@ -2920,6 +3002,94 @@ def keep_alive_ddm_rules(self, by: str = "watchdog") -> None: except Exception: tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") + def update_requests_usage(self, by: str = "watchdog") -> None: + """ + Update the usage of staging and done requests according to their related tasks: + remove_when_done : if the request has active tasks, True if any of them has task parameter remove_rule_when_done ; unchanged if no active task + last_used_time : now if the request has active tasks ; if all related tasks ended, the latest end time of them + Also keep alive the DDM rules of done requests without active tasks (except remove_when_done) to cover the grace period after last used + + Args: + by (str): annotation of the caller of this method; default is "watchdog" + """ + tmp_log = LogWrapper(logger, f"update_requests_usage by={by}") + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI([DataCarouselRequestStatus.staging, DataCarouselRequestStatus.done]) + if requests_with_tasks is None: + tmp_log.warning("failed to query requests ; skipped") + return + n_updated = 0 + n_rules_refreshed = 0 + seen_task_ids: set[int] = set() + now_time = naive_utcnow() + now_time_str = now_time.replace(microsecond=0).isoformat() + grace_days = self._get_last_used_grace_days() + for dc_req_spec, task_specs in requests_with_tasks: + try: + params_to_update: dict[str, Any] = {} + # active tasks, whether any of them has remove_rule_when_done, and latest end time of ended tasks + has_active_task = False + remove_when_done = False + latest_end_time = None + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + if task_spec.jediTaskID is not None: + seen_task_ids.add(task_spec.jediTaskID) + if not remove_when_done: + task_params_map = self._get_task_params_map(task_spec.jediTaskID) + if task_params_map is not None and task_params_map.get("remove_rule_when_done"): + remove_when_done = True + elif task_spec.endTime is not None and (latest_end_time is None or task_spec.endTime > latest_end_time): + latest_end_time = task_spec.endTime + if has_active_task: + # still used by active tasks + params_to_update["last_used_time"] = now_time_str + # remove_when_done decided by active tasks + if bool(dc_req_spec.get_parameter("remove_when_done")) != remove_when_done: + params_to_update["remove_when_done"] = remove_when_done + elif latest_end_time is not None: + # all related tasks ended ; last used when the last task ended + last_used_time_str = latest_end_time.isoformat() + if dc_req_spec.get_parameter("last_used_time") != last_used_time_str: + params_to_update["last_used_time"] = last_used_time_str + # update DB + if params_to_update: + with self.request_lock(dc_req_spec.request_id) as locked_spec: + if not locked_spec: + # not getting lock; skip + tmp_log.warning(f"request_id={dc_req_spec.request_id} did not get lock; skipped") + continue + locked_spec.update_parameters(params_to_update) + if self.taskBufferIF.update_data_carousel_request_JEDI(locked_spec): + n_updated += 1 + if not has_active_task or "remove_when_done" in params_to_update: + # not to log the routine refresh of last_used_time of requests with active tasks + tmp_log.debug(f"request_id={dc_req_spec.request_id} status={locked_spec.status} updated DB with {params_to_update}") + else: + tmp_log.error(f"request_id={dc_req_spec.request_id} failed to update DB ; skipped") + # keep alive the DDM rule of done request without active tasks until the grace period after last used ends, with margin for the daily clean-up + if ( + not has_active_task + and latest_end_time is not None + and dc_req_spec.status == DataCarouselRequestStatus.done + and not dc_req_spec.get_parameter("remove_when_done") + ): + grace_end_time = latest_end_time + timedelta(days=grace_days) + if grace_end_time > now_time: + until_time = grace_end_time + timedelta(days=LAST_USED_GRACE_RULE_MARGIN_DAYS) + if self.refresh_ddm_rule_of_request(dc_req_spec, by=by, until_time=until_time): + n_rules_refreshed += 1 + tmp_log.debug( + f"request_id={dc_req_spec.request_id} ddm_rule_id={dc_req_spec.ddm_rule_id} refreshed lifetime until {until_time} to cover grace period" + ) + except Exception: + tmp_log.error(f"request_id={dc_req_spec.request_id} got error ; {traceback.format_exc()}") + # clean up cache of tasks not active anymore + self._prune_task_params_cache("update_requests_usage", seen_task_ids) + tmp_log.debug( + f"checked {len(requests_with_tasks)} requests ; updated {n_updated} requests in DB ; refreshed {n_rules_refreshed} DDM rules for grace period" + ) + def _update_staged_files(self, dc_req_spec: DataCarouselRequestSpec, task_id_list: list[int] | None = None) -> bool | None: """ Update status of files in DB Jedi_Dataset_Contents for a request done staging @@ -3199,52 +3369,66 @@ def _get_orphan_requests(self) -> list[DataCarouselRequestSpec] | None: return None def clean_up_requests( - self, done_age_limit_days: int | float = DONE_LIFETIME_DAYS, outdated_age_limit_days: int | float = DONE_LIFETIME_DAYS, by: str = "watchdog" + self, + done_age_limit_days: int | float = DONE_LIFETIME_DAYS, + outdated_age_limit_days: int | float = DONE_LIFETIME_DAYS, + by: str = "watchdog", ) -> None: """ Clean up terminated and outdated requests Args: - done_age_limit_days (int|float): age limit in days for requests done and without active tasks - outdated_age_limit_days (int|float): age limit in days for outdated requests + done_age_limit_days (int|float): age limit in days since end_time for requests done and without active tasks + outdated_age_limit_days (int|float): age limit in days for outdated requests without tasks by (str): annotation of the caller of this method; default is "watchdog" """ tmp_log = LogWrapper(logger, "clean_up_requests") try: + # grace period after last used + last_used_grace_days = self._get_last_used_grace_days() # initialize done_requests_set = set() cancelled_requests_set = set() retired_requests_set = set() - # get requests of terminated and active tasks - terminated_tasks_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_filter_list=FINAL_TASK_STATUSES) - active_tasks_requests = self.taskBufferIF.get_data_carousel_requests_by_task_status_JEDI(status_exclusion_list=FINAL_TASK_STATUSES) - if terminated_tasks_requests is None or active_tasks_requests is None: + # get requests with their related tasks + requests_with_tasks = self.taskBufferIF.get_data_carousel_requests_with_tasks_JEDI( + DataCarouselRequestStatus.active_statuses + DataCarouselRequestStatus.final_statuses + ) + if requests_with_tasks is None: tmp_log.warning("failed to query requests ; skipped") return - terminated_tasks_requests_map, terminated_tasks_relation_map = terminated_tasks_requests - active_tasks_requests_map, active_tasks_relation_map = active_tasks_requests now_time = naive_utcnow() - # set of requests of terminated tasks - request_ids_of_terminated_tasks = set() - for request_id_list in terminated_tasks_relation_map.values(): - request_ids_of_terminated_tasks |= set(request_id_list) - # set of requests of active tasks - request_ids_of_active_tasks = set() - for request_id_list in active_tasks_relation_map.values(): - request_ids_of_active_tasks |= set(request_id_list) - # loop over requests of terminated tasks - for request_id in request_ids_of_terminated_tasks: - if request_id in active_tasks_requests_map: - # the request is also mapped to some active task, not to be cleaned up; skipped + request_spec_map = {} + for dc_req_spec, task_specs in requests_with_tasks: + if not task_specs: + # requests without tasks ; handled as orphan or outdated requests below continue - dc_req_spec = terminated_tasks_requests_map[request_id] - if dc_req_spec.status == DataCarouselRequestStatus.done and ( - (dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days)) - or dc_req_spec.get_parameter("rule_unfound") - or dc_req_spec.get_parameter("remove_when_done") - ): - # requests done, and old enough or DDM rule not found or to remove when done; to clean up - done_requests_set.add(request_id) + request_id = dc_req_spec.request_id + request_spec_map[request_id] = dc_req_spec + is_done = dc_req_spec.status == DataCarouselRequestStatus.done + to_remove = dc_req_spec.get_parameter("rule_unfound") or dc_req_spec.get_parameter("remove_when_done") + if is_done and not to_remove: + grace_end_time = self._get_grace_end_time(dc_req_spec, last_used_grace_days) + if grace_end_time is not None and grace_end_time >= now_time: + # requests done and used within grace period ; not to clean up regardless of tasks + continue + # whether with active tasks + has_active_task = False + for task_spec in task_specs: + if task_spec.status not in FINAL_TASK_STATUSES: + has_active_task = True + break + if has_active_task: + if dc_req_spec.status == DataCarouselRequestStatus.staging and dc_req_spec.get_parameter("rule_unfound"): + # requests staging but DDM rule not found; to cancel + self.cancel_request(dc_req_spec, by=by, reason="rule_unfound") + # requests with active tasks not to be cleaned up + continue + # requests whose related tasks all ended + if is_done: + # requests done ; to clean up if DDM rule not found or to remove when done, or old enough (already not used within grace period) + if to_remove or (dc_req_spec.end_time and dc_req_spec.end_time < now_time - timedelta(days=done_age_limit_days)): + done_requests_set.add(request_id) elif dc_req_spec.status == DataCarouselRequestStatus.queued: # requests queued while related tasks all terminated; to cancel (to clean up in next cycle) self.cancel_request(dc_req_spec, by=by, reason="queued_while_all_tasks_ended") @@ -3257,12 +3441,6 @@ def clean_up_requests( elif dc_req_spec.status == DataCarouselRequestStatus.retired: # requests retired; to clean up retired_requests_set.add(request_id) - # loop over requests of active tasks to cancel bad ones - for request_id in request_ids_of_active_tasks: - dc_req_spec = active_tasks_requests_map[request_id] - if dc_req_spec.status == DataCarouselRequestStatus.staging and dc_req_spec.get_parameter("rule_unfound"): - # requests staging but DDM rule not found; to cancel - self.cancel_request(dc_req_spec, by=by, reason="rule_unfound") # cancel orphan requests orphan_requests = self._get_orphan_requests() if orphan_requests: @@ -3270,7 +3448,7 @@ def clean_up_requests( self.cancel_request(dc_req_spec, by=by, reason="orphan") # delete ddm rules of terminated requests of terminated tasks for request_id in done_requests_set | cancelled_requests_set | retired_requests_set: - dc_req_spec = terminated_tasks_requests_map[request_id] + dc_req_spec = request_spec_map[request_id] ddm_rule_id = dc_req_spec.ddm_rule_id if ddm_rule_id: try: @@ -3289,29 +3467,34 @@ def clean_up_requests( if n_deleted is None: tmp_log.warning("failed to delete done requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} done requests older than {done_age_limit_days} days or rule_unfound or remove_when_done") + tmp_log.debug( + f"deleted {n_deleted} done requests older than {done_age_limit_days} days and last used over {last_used_grace_days} days ago, " + f"or rule_unfound or remove_when_done: {sorted(done_requests_set)}" + ) if cancelled_requests_set: # cancelled requests n_deleted = self.taskBufferIF.delete_data_carousel_requests_JEDI(list(cancelled_requests_set)) if n_deleted is None: tmp_log.warning("failed to delete cancelled requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} cancelled requests") + tmp_log.debug(f"deleted {n_deleted} cancelled requests: {sorted(cancelled_requests_set)}") if retired_requests_set: # retired requests n_deleted = self.taskBufferIF.delete_data_carousel_requests_JEDI(list(retired_requests_set)) if n_deleted is None: tmp_log.warning("failed to delete retired requests; skipped") else: - tmp_log.debug(f"deleted {n_deleted} retired requests") + tmp_log.debug(f"deleted {n_deleted} retired requests: {sorted(retired_requests_set)}") else: tmp_log.debug("no terminated requests to delete; skipped") - # clean up outdated requests - ret_outdated = self.taskBufferIF.clean_up_data_carousel_requests_JEDI(time_limit_days=outdated_age_limit_days) - if ret_outdated is None: + # clean up outdated requests not related to any task + outdated_request_ids = self.taskBufferIF.clean_up_data_carousel_requests_JEDI(time_limit_days=outdated_age_limit_days) + if outdated_request_ids is None: tmp_log.warning("failed to delete outdated requests; skipped") else: - tmp_log.debug(f"deleted {ret_outdated} outdated requests older than {outdated_age_limit_days} days") + tmp_log.debug( + f"deleted {len(outdated_request_ids)} outdated requests older than {outdated_age_limit_days} days and without tasks: {outdated_request_ids}" + ) except Exception: tmp_log.error(f"got error ; {traceback.format_exc()}") diff --git a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py index 891242faa..038002cb2 100644 --- a/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py +++ b/pandaserver/taskbuffer/db_proxy_mods/data_carousel_module.py @@ -252,6 +252,66 @@ def get_data_carousel_queued_requests_JEDI(self) -> list[tuple[DataCarouselReque self.dump_error_message(tmp_log) return None + # get data carousel requests with their related tasks + def get_data_carousel_requests_with_tasks_JEDI(self, status_list: list[str]) -> list[tuple[DataCarouselRequestSpec, list[JediTaskSpec]]] | None: + """ + Get data carousel requests in given statuses with their related tasks + + Args: + status_list (list[str]): statuses of requests to get + + Returns: + list | None : list of tuples in form of (request_spec, [task_spec, ...]) where task specs have jediTaskID, status and endTime (stateChangeTime if endTime is null) ; None if failed + """ + comment = " /* JediDBProxy.get_data_carousel_requests_with_tasks_JEDI */" + tmp_log = self.create_tagged_logger(comment) + tmp_log.debug("start") + try: + # start transaction + self.conn.begin() + status_var_names_str, status_var_map = get_sql_IN_bind_variables(status_list, prefix=":status") + # sql to query requests + sql_query_req = f"SELECT {DataCarouselRequestSpec.columnNames()} FROM {panda_config.schemaJEDI}.data_carousel_requests WHERE status IN ({status_var_names_str}) " + self.cur.execute(sql_query_req + comment, status_var_map) + res_list = self.cur.fetchall() + request_spec_map = {} + for res in res_list: + dc_req_spec = DataCarouselRequestSpec() + dc_req_spec.pack(res) + request_spec_map[dc_req_spec.request_id] = dc_req_spec + # sql to query related tasks of all requests ; tasks of requests not in request_spec_map are skipped + sql_query_tasks = ( + f"SELECT rel.request_id, t.jediTaskID, t.status, COALESCE(t.endTime, t.stateChangeTime) " + f"FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.JEDI_Tasks t " + f"WHERE rel.task_id=t.jediTaskID " + ) + self.cur.execute(sql_query_tasks + comment, {}) + res_tasks = self.cur.fetchall() + task_specs_map: dict[int, list[JediTaskSpec]] = {} + for request_id, task_id, task_status, end_time in res_tasks: + if request_id not in request_spec_map: + continue + task_spec = JediTaskSpec() + task_spec.jediTaskID = task_id + task_spec.status = task_status + task_spec.endTime = end_time + task_specs_map.setdefault(request_id, []).append(task_spec) + # commit + if not self._commit(): + raise RuntimeError("Commit error") + # return + ret_list = [] + for request_id, dc_req_spec in request_spec_map.items(): + ret_list.append((dc_req_spec, task_specs_map.get(request_id, []))) + tmp_log.debug(f"got {len(ret_list)} requests in {status_list}") + return ret_list + except Exception: + # roll back + self._rollback() + # error + self.dump_error_message(tmp_log) + return None + # get data carousel requests of tasks by task status def get_data_carousel_requests_by_task_status_JEDI( self, status_filter_list: list[str] | None = None, status_exclusion_list: list[str] | None = None @@ -466,23 +526,51 @@ def delete_data_carousel_requests_JEDI(self, request_id_list: list[int]) -> int return None # clean up data carousel requests - def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> int | None: + def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> list[int] | None: + """ + Delete terminated requests which ended longer than time_limit_days ago and are not related to any task + Requests related to tasks are cleaned up by clean_up_requests of DataCarousel according to their tasks + + Args: + time_limit_days (float): age limit in days since end_time of the request + + Returns: + list[int] | None : request IDs of the deleted requests, or None if failed + """ comment = " /* JediDBProxy.clean_up_data_carousel_requests_JEDI */" tmp_log = self.create_tagged_logger(comment) tmp_log.debug("start") try: # start transaction self.conn.begin() - # sql to delete terminated requests now_time = naive_utcnow() status_var_names_str, status_var_map = get_sql_IN_bind_variables(DataCarouselRequestStatus.final_statuses, prefix=":status") - sql_delete_req = ( - f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_requests WHERE status IN ({status_var_names_str}) AND end_time<=:end_time_max " + # condition that the request is not related to any task + sql_no_task = ( + f"NOT EXISTS (SELECT 1 FROM {panda_config.schemaJEDI}.data_carousel_relations rel, {panda_config.schemaJEDI}.JEDI_Tasks t " + f"WHERE rel.request_id=req.request_id AND rel.task_id=t.jediTaskID) " + ) + # sql to query terminated requests old enough and without tasks + sql_query_req = ( + f"SELECT req.request_id FROM {panda_config.schemaJEDI}.data_carousel_requests req " + f"WHERE req.status IN ({status_var_names_str}) AND req.end_time<=:end_time_max AND {sql_no_task}" ) var_map = {":end_time_max": now_time - datetime.timedelta(days=time_limit_days)} var_map.update(status_var_map) - self.cur.execute(sql_delete_req + comment, var_map) - ret_req: int = self.cur.rowcount + self.cur.execute(sql_query_req + comment, var_map) + res = self.cur.fetchall() + # sql to delete a request; check conditions again in case it got related to a task in the meantime + sql_delete_req = ( + f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_requests req " + f"WHERE req.request_id=:request_id AND req.status IN ({status_var_names_str}) AND {sql_no_task}" + ) + deleted_request_ids = [] + for (request_id,) in res: + var_map = {":request_id": request_id} + var_map.update(status_var_map) + self.cur.execute(sql_delete_req + comment, var_map) + if self.cur.rowcount: + deleted_request_ids.append(request_id) # sql to delete relations sql_delete_rel = ( f"DELETE FROM {panda_config.schemaJEDI}.data_carousel_relations rel " @@ -495,8 +583,10 @@ def clean_up_data_carousel_requests_JEDI(self, time_limit_days: float = 30) -> i if not self._commit(): raise RuntimeError("Commit error") # return - tmp_log.debug(f"cleaned up {ret_req} requests and {ret_rel} relations older than {time_limit_days} days") - return ret_req + tmp_log.debug( + f"cleaned up {len(deleted_request_ids)} requests and {ret_rel} relations older than {time_limit_days} days and without tasks: {deleted_request_ids}" + ) + return deleted_request_ids except Exception: # roll back self._rollback()