Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
148 changes: 148 additions & 0 deletions pandaserver/api/v1/task_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,10 @@
get_fqan,
has_production_role,
log_task_commands,
parse_utc_time,
request_validation,
)
from pandaserver.config import panda_config
from pandaserver.srvcore.CoreUtils import clean_user_id, make_reassign_comment
from pandaserver.srvcore.panda_request import PandaRequest
from pandaserver.taskbuffer import task_split_rules
Expand All @@ -33,6 +35,9 @@
# only push a None check onto every handler without making any of them safer.
global_task_buffer: TaskBuffer = None # type: ignore[assignment]

# most rows one get_job_rows or get_dataset_rows call returns. A task with more is cut there, and the answer says so
MAX_TASK_ROWS = 1000


def init_task_buffer(task_buffer: TaskBuffer) -> None:
"""
Expand Down Expand Up @@ -1073,6 +1078,149 @@ def get_command_history(req: PandaRequest, task_id: int) -> dict[str, Any]:
return generate_response(True, data=data)


@request_validation(_logger, secure=True, request_method="GET")
def get_job_rows(req: PandaRequest, task_id: int, since: str | None = None, after_panda_id: int | None = None) -> dict[str, Any]:
"""
Get the job rows of a task

Gets the rows of the jobs of a task from jobsDefined4, jobsActive4, jobsArchived4 and the archive, with their number by
status. Requires a secure connection.

jobsArchived4 and the archive are partitioned by day and by a few days on modificationTime, and the task is looked up
once in each of their partitions a window touches. The window starts at since, or at the creation of the task without
since, and ends at the database time. Both ends are moved out by 10 minutes for the clocks of the servers and then to
whole UTC days. A task that is not found and is given no since is read without a start, in every partition. A call
that would look up more partitions than the db_read_probe_budget of the server allows is refused, not cut short; a
later since lets it fit.

The rows of all four tables are read by one statement, so a job moving between tables meanwhile is read once, and a
row the same in two tables is given once. The counts are read by a second statement, so a job that changes its status
in between may be counted under its new status.

A task with more jobs than one call returns is read in pages: ask the next page with after_panda_id set to the last
PandaID of the page before, with the same since, until a page is not truncated. The pages are ordered over all four
tables, so a job moving between tables from one page to the next is still read once.

API details:
HTTP Method: GET
Path: /v1/task/get_job_rows

Args:
req(PandaRequest): internally generated request object
task_id(int): JEDI Task ID
since(str, optional): read the jobs modified at or after this time from jobsArchived4 and the archive, in UTC,
e.g. `2026-10-12 14:30:45` (ISO 8601 is accepted). Defaults to the creation of the task
after_panda_id(int, optional): return only the jobs with a larger PandaID, for the next page. Defaults to from the first

Returns:
dict: The system response `{"success": success, "message": message, "data": data}`.

Response data:
dict: The jobs of the task, and what tells how complete they are.
{"rows": [...], "truncated": bool, "max_rows": int, "after_panda_id": int or None, "counts": {str: int},
"as_of": datetime, "since": datetime or None, "until": datetime, "retained_from": datetime or None,
"partitions": int, "probes": int, "budget": int}
- rows: one dict per job, ordered by PandaID and starting after after_panda_id, with PandaID, jobStatus,
jobSubStatus, creationTime, modificationTime, stateChangeTime, endTime, prodSourceLabel, currentPriority,
computingSite and attemptNr
- truncated, max_rows: whether the rows were cut at max_rows, the most a call returns; when cut, the next
page starts after the last PandaID of rows
- after_panda_id: the one given, or None
- counts: the number of jobs by jobStatus, every job in the window counted, whatever page this is and however
many rows were cut
- as_of: database time in UTC taken before the rows were read
- since, until: the window read on jobsArchived4 and the archive, after the widening. since is None when it
has no start
- retained_from: time from which the archive holds every row, or None when it cannot be told. Old partitions
are dropped, so jobs of a task older than this may be missing
- partitions, probes, budget: the partitions of the two tables the window touches, each table counted as at
least 1, the index lookups of the call, two for each table or partition, and the db_read_probe_budget
On failure, with the reason in the message, the reason as values:
- None: task_id is not an integer
- {"rejected": "invalid_window"}: since is not a time
- {"rejected": "probe_budget", "probes": int, "partitions": int, "budget": int}: the lookups exceed the budget
- {"error": str}: the database failed, with the error code (ORA-xxxxx, or the SQLSTATE on Postgres)
"""
tmp_logger = LogWrapper(_logger, f"get_job_rows < task_id={task_id} since={since} after_panda_id={after_panda_id} >")
tmp_logger.debug("Start")

try:
task_id = int(task_id)
except ValueError:
tmp_logger.error("Failed due to invalid task_id")
return generate_response(False, message=MESSAGE_TASK_ID)

since_time: datetime.datetime | None = None
if since:
try:
since_time = parse_utc_time(since)
except ValueError as e:
message = f"invalid since: {e}"
tmp_logger.debug(message)
return generate_response(False, message=message, data={"rejected": "invalid_window"})

success, message, data = global_task_buffer.get_task_job_rows(task_id, since_time, panda_config.db_read_probe_budget, MAX_TASK_ROWS, after_panda_id)
if not success:
tmp_logger.debug(f"Failed with {message}")
return generate_response(False, message=message, data=data)

tmp_logger.debug(f"""Done with {len(data["rows"])} rows""")
return generate_response(True, data=data)


@request_validation(_logger, secure=True, request_method="GET")
def get_dataset_rows(req: PandaRequest, task_id: int, after_dataset_id: int | None = None) -> dict[str, Any]:
"""
Get the dataset rows of a task

Gets the rows JEDI_Datasets holds for a task, with every column. Requires a secure connection.

A task with more datasets than one call returns is read in pages: ask the next page with after_dataset_id set to the
last datasetID of the page before, until a page is not truncated.

API details:
HTTP Method: GET
Path: /v1/task/get_dataset_rows

Args:
req(PandaRequest): internally generated request object
task_id(int): JEDI Task ID
after_dataset_id(int, optional): return only the datasets with a larger datasetID, for the next page. Defaults to
from the first

Returns:
dict: The system response `{"success": success, "message": message, "data": data}`.

Response data:
dict: The datasets of the task.
{"rows": [...], "truncated": bool, "max_rows": int, "as_of": datetime}
- rows: one dict per dataset, ordered by datasetID and starting after after_dataset_id, with every column keyed
as JediDatasetSpec names it (jediTaskID, datasetID, datasetName, type, masterID, status, nFiles, ...), and
None for NULL. A task that is not found has none
- truncated, max_rows: whether the rows were cut at max_rows, the most a call returns; when cut, the next
page starts after the last datasetID of rows
- as_of: database time in UTC taken before the rows of this page were read
On failure, with the reason in the message: {"error": str} when the database failed, with the error code (ORA-xxxxx,
or the SQLSTATE on Postgres), and None otherwise.
"""
tmp_logger = LogWrapper(_logger, f"get_dataset_rows < task_id={task_id} after_dataset_id={after_dataset_id} >")
tmp_logger.debug("Start")

try:
task_id = int(task_id)
except ValueError:
tmp_logger.error("Failed due to invalid task_id")
return generate_response(False, message=MESSAGE_TASK_ID)

success, message, data = global_task_buffer.get_task_dataset_rows(task_id, MAX_TASK_ROWS, after_dataset_id)
if not success:
tmp_logger.debug(f"Failed with {message}")
return generate_response(False, message=message, data=data)

tmp_logger.debug(f"""Done with {len(data["rows"])} rows""")
return generate_response(True, data=data)


@request_validation(_logger, request_method="GET", secure=True)
def get_details(req: PandaRequest, task_id: int, include_parameters: bool = False, include_status: bool = False) -> dict[str, Any]:
"""
Expand Down
100 changes: 100 additions & 0 deletions pandaserver/api/v1/tests/task_api_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -296,6 +296,106 @@ def test_get_status_history(self) -> None:
for row in output["data"]["rows"]:
self.assertEqual(row["jediTaskID"], int(JEDI_TASK_ID))

def test_get_job_rows(self) -> None:
url = f"{api_url_ssl}/task/get_job_rows"
print(f"Testing URL: {url}")
# a window of a few days fits the budget also where jobsArchived4 keeps years of daily partitions
since = (datetime.utcnow() - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S")
data = {"task_id": JEDI_TASK_ID, "since": since}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
self.assertTrue(output["success"])
keys = {"rows", "truncated", "max_rows", "after_panda_id", "counts", "as_of", "since", "until", "retained_from", "partitions", "probes", "budget"}
self.assertEqual(set(output["data"]), keys)
self.assertIsNotNone(output["data"]["since"])
self.assertLessEqual(output["data"]["probes"], output["data"]["budget"])
columns = {
"PandaID",
"jobStatus",
"jobSubStatus",
"creationTime",
"modificationTime",
"stateChangeTime",
"endTime",
"prodSourceLabel",
"currentPriority",
"computingSite",
"attemptNr",
}
for row in output["data"]["rows"]:
self.assertEqual(set(row), columns)
if JEDI_TASK_ID == -1:
self.assertEqual(output["data"]["rows"], [])
self.assertEqual(output["data"]["counts"], {})

def test_get_job_rows_page(self) -> None:
url = f"{api_url_ssl}/task/get_job_rows"
print(f"Testing URL: {url}")
since = (datetime.utcnow() - timedelta(days=3)).strftime("%Y-%m-%d %H:%M:%S")
data = {"task_id": JEDI_TASK_ID, "since": since, "after_panda_id": 1}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
self.assertTrue(output["success"])
self.assertEqual(output["data"]["after_panda_id"], 1)
for row in output["data"]["rows"]:
self.assertGreater(row["PandaID"], 1)

def test_get_job_rows_default_window(self) -> None:
url = f"{api_url_ssl}/task/get_job_rows"
print(f"Testing URL: {url}")
data = {"task_id": JEDI_TASK_ID}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
if JEDI_TASK_ID == -1:
# an unknown task is read without a window, which the budget may refuse
if output["success"]:
self.assertIsNone(output["data"]["since"])
else:
self.assertEqual(output["data"]["rejected"], "probe_budget")
else:
self.assertTrue(output["success"])
self.assertIsNotNone(output["data"]["since"])

def test_get_job_rows_invalid_since(self) -> None:
url = f"{api_url_ssl}/task/get_job_rows"
print(f"Testing URL: {url}")
data = {"task_id": JEDI_TASK_ID, "since": "yesterday"}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
self.assertFalse(output["success"])
self.assertEqual(output["data"], {"rejected": "invalid_window"})

def test_get_dataset_rows(self) -> None:
url = f"{api_url_ssl}/task/get_dataset_rows"
print(f"Testing URL: {url}")
data = {"task_id": JEDI_TASK_ID}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
self.assertTrue(output["success"])
self.assertEqual(set(output["data"]), {"rows", "truncated", "max_rows", "as_of"})
if JEDI_TASK_ID == -1:
self.assertEqual(output["data"]["rows"], [])
for row in output["data"]["rows"]:
self.assertEqual(row["jediTaskID"], int(JEDI_TASK_ID))
self.assertIn("masterID", row)

def test_get_dataset_rows_page(self) -> None:
url = f"{api_url_ssl}/task/get_dataset_rows"
print(f"Testing URL: {url}")
data = {"task_id": JEDI_TASK_ID, "after_dataset_id": 1}
status, output = self.http_client.get(url, data)
print(output)
self.assertEqual(status, 0)
self.assertTrue(output["success"])
self.assertEqual(set(output["data"]), {"rows", "truncated", "max_rows", "as_of"})
for row in output["data"]["rows"]:
self.assertGreater(row["datasetID"], 1)

def test_get_command_history(self) -> None:
url = f"{api_url_ssl}/task/get_command_history"
print(f"Testing URL: {url}")
Expand Down
6 changes: 2 additions & 4 deletions pandaserver/asyncprocess/db_read/compose.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,8 +141,6 @@ def bind(value: Any) -> str:
order = [f"{expression_of.get(key.name) or _identifier(key.name)}{' DESC' if key.descending else ''}" for key in query.order_by]
sql += " ORDER BY " + ",".join(order)
# each clause starts with a space, which is what keeps a bind variable ending the one before apart from it
if backend == "postgres":
sql += f" LIMIT {query.limit + 1}"
else:
sql += f" FETCH FIRST {query.limit + 1} ROWS ONLY"
# standard SQL that Oracle and Postgres both take as it is
sql += f" FETCH FIRST {query.limit + 1} ROWS ONLY"
return Statement(sql + STATEMENT_COMMENT, binds, tuple(names), query.limit)
4 changes: 2 additions & 2 deletions pandaserver/asyncprocess/tests/db_read_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,7 +348,7 @@ def test_grouped(self) -> None:
self.assertEqual(oracle.names, ("jobstatus", "hour(modificationtime)", "count(*)", "min(pandaid)"))
(postgres,) = self.compose(raw, "postgres")
self.assertIn("date_trunc('hour',modificationtime)", postgres.sql)
self.assertTrue(postgres.sql.endswith(" LIMIT 1001" + STATEMENT_COMMENT))
self.assertTrue(postgres.sql.endswith(" FETCH FIRST 1001 ROWS ONLY" + STATEMENT_COMMENT))

def test_postgres_conversion(self) -> None:
# what WrappedCursor makes of the statement: one %s per bind variable, in order, and nothing else touched
Expand All @@ -368,7 +368,7 @@ def test_postgres_conversion(self) -> None:
sql,
"SELECT date_trunc('day',modificationtime),COUNT(*) FROM ATLAS_PANDA.jobsActive4 "
"WHERE pandaid IN (%s,%s) AND computingsite LIKE %s ESCAPE '!' AND modificationtime < %s "
"GROUP BY date_trunc('day',modificationtime) LIMIT 1001" + STATEMENT_COMMENT,
"GROUP BY date_trunc('day',modificationtime) FETCH FIRST 1001 ROWS ONLY" + STATEMENT_COMMENT,
)
self.assertEqual(params, [[1, 2, "CERN!_1!%%", D0]])

Expand Down
12 changes: 12 additions & 0 deletions pandaserver/taskbuffer/TaskBuffer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2088,6 +2088,18 @@ def get_task_command_history(self, jedi_task_id: int) -> tuple[bool, str, dict[s
with self.proxyPool.get() as proxy:
return proxy.get_task_command_history(jedi_task_id)

# get the rows of the jobs of a task and their number by status
def get_task_job_rows(
self, jedi_task_id: int, since: datetime.datetime | None, probe_budget: int, max_rows: int, after_panda_id: int | None = None
) -> tuple[bool, str, dict[str, Any]]:
with self.proxyPool.get() as proxy:
return proxy.get_task_job_rows(jedi_task_id, since, probe_budget, max_rows, after_panda_id)

# get the rows of the datasets of a task
def get_task_dataset_rows(self, jedi_task_id: int, max_rows: int, after_dataset_id: int | None = None) -> tuple[bool, str, dict[str, Any]]:
with self.proxyPool.get() as proxy:
return proxy.get_task_dataset_rows(jedi_task_id, max_rows, after_dataset_id)

# reactivate task
def reactivateTask(self, jediTaskID: int, keep_attempt_nr: bool = False, trigger_job_generation: bool = False) -> tuple[int | None, str]:
with self.proxyPool.get() as proxy:
Expand Down
Loading