Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-12-02 10:28:11

0001 # Description: Unit tests for the task command log, TASKS_COMMANDLOG: recording the commands around
0002 # the task API endpoints, the encoders, and the SQL the DB proxy issues when a command is registered
0003 # for JEDI or taken by it. No database is used; the TaskBuffer and the cursor are fakes
0004 import datetime
0005 import inspect
0006 import json
0007 import logging
0008 import unittest
0009 from collections.abc import Callable
0010 from typing import TYPE_CHECKING, Any, cast
0011 from unittest import mock
0012 
0013 from pandaserver.api.v1 import common, task_api
0014 from pandaserver.api.v1.common import (
0015     COMMAND_ARGUMENT_SIZE_LIMIT,
0016     COMMAND_RESPONSE_FIELD_LIMIT,
0017     COMMAND_TASK_ID_PARAMETERS,
0018     MESSAGE_COMMAND_LOG,
0019     encode_command_parameters,
0020     encode_command_response,
0021     generate_response,
0022     log_task_commands,
0023     request_validation,
0024 )
0025 from pandaserver.srvcore import task_command_log
0026 from pandaserver.srvcore.CoreUtils import clean_user_id
0027 from pandaserver.taskbuffer.db_proxy_mods.task_complex_module import TaskComplexModule
0028 from pandaserver.taskbuffer.db_proxy_mods.task_event_module import TaskEventModule
0029 
0030 if TYPE_CHECKING:
0031     from pandaserver.taskbuffer.TaskBuffer import TaskBuffer
0032 
0033 _logger = logging.getLogger("task_command_log_tests")
0034 
0035 NOW = datetime.datetime(2026, 11, 17, 12, 0, 0)
0036 KEY: task_command_log.TaskCommandKey = {"command_id": 42, "command_time": NOW}
0037 DN = "/DC=ch/DC=cern/OU=Organic Units/OU=Users/CN=someone/CN=123456/CN=Some One"
0038 TASK_ID = 1234
0039 
0040 
0041 class FakeRequest:
0042     # what request_validation reads of a PandaRequest
0043     def __init__(self, method: str = "POST", remote_host: str = "", remote_addr: str = "192.0.2.10") -> None:
0044         self.subprocess_env: dict[str, str] = {"REQUEST_METHOD": method, "SSL_CLIENT_S_DN": DN, "REMOTE_ADDR": remote_addr}
0045         if remote_host:
0046             self.subprocess_env["REMOTE_HOST"] = remote_host
0047 
0048     def get_remote_host(self) -> str:
0049         return self.subprocess_env.get("REMOTE_HOST", "")
0050 
0051 
0052 class FakeTaskBuffer:
0053     # what run_logged_task_command uses of a TaskBuffer
0054     def __init__(self, key: Any = KEY, response_ok: bool = True) -> None:
0055         self.key = key
0056         self.response_ok = response_ok
0057         self.inserted: list[dict[str, Any]] = []
0058         self.responses: list[tuple[Any, dict[str, Any], bool]] = []
0059 
0060     def insert_task_command(self, task_ids: list[int], command: str, parameters: str, requester: str, prod_role: bool, client_addr: str | None) -> Any:
0061         self.inserted.append(
0062             {
0063                 "task_ids": task_ids,
0064                 "command": command,
0065                 "parameters": json.loads(parameters),
0066                 "requester": requester,
0067                 "prod_role": prod_role,
0068                 "client_addr": client_addr,
0069             }
0070         )
0071         if isinstance(self.key, Exception):
0072             raise self.key
0073         return self.key
0074 
0075     def set_task_command_response(self, command_key: Any, response: str, is_error: bool) -> bool:
0076         self.responses.append((command_key, json.loads(response), is_error))
0077         return self.response_ok
0078 
0079 
0080 fake_task_buffer = FakeTaskBuffer()
0081 # the key each endpoint below saw in current_task_command while it ran
0082 seen_keys: list[Any] = []
0083 
0084 
0085 @request_validation(_logger, secure=True, request_method="POST")
0086 def change_thing(req: Any, task_id: int, value: int, blob: dict[str, Any] | None = None) -> dict[str, Any]:
0087     seen_keys.append(task_command_log.current_task_command.get())
0088     return generate_response(True, message="1 tasks changed", data={"value": value})
0089 
0090 
0091 @request_validation(_logger, secure=True, request_method="POST")
0092 def share_tasks(req: Any, task_id_list: list[int], share: str) -> dict[str, Any]:
0093     seen_keys.append(task_command_log.current_task_command.get())
0094     return generate_response(True)
0095 
0096 
0097 @request_validation(_logger, secure=True, request_method="POST")
0098 def fail_thing(req: Any, task_id: int) -> dict[str, Any]:
0099     seen_keys.append(task_command_log.current_task_command.get())
0100     raise RuntimeError("boom")
0101 
0102 
0103 @request_validation(_logger, secure=True, request_method="GET")
0104 def read_thing(req: Any, task_id: int) -> dict[str, Any]:
0105     seen_keys.append(task_command_log.current_task_command.get())
0106     return generate_response(True)
0107 
0108 
0109 @request_validation(_logger, secure=True, request_method="POST")
0110 def submit_thing(req: Any, task_parameters: dict[str, Any]) -> dict[str, Any]:
0111     seen_keys.append(task_command_log.current_task_command.get())
0112     return generate_response(True)
0113 
0114 
0115 class TestRecordingAroundEndpoints(unittest.TestCase):
0116     def setUp(self) -> None:
0117         global fake_task_buffer
0118         fake_task_buffer = FakeTaskBuffer()
0119         seen_keys.clear()
0120         # the fake implements only what run_logged_task_command uses of a TaskBuffer
0121         log_task_commands(__name__, lambda: cast("TaskBuffer", fake_task_buffer))
0122 
0123     def tearDown(self) -> None:
0124         common._command_logging_modules.pop(__name__, None)
0125 
0126     def test_post_is_recorded_around_the_command(self) -> None:
0127         response = change_thing(FakeRequest(), task_id=TASK_ID, value=3)
0128         self.assertEqual(response, {"success": True, "message": "1 tasks changed", "data": {"value": 3}})
0129         self.assertEqual(
0130             fake_task_buffer.inserted,
0131             [
0132                 {
0133                     "task_ids": [TASK_ID],
0134                     "command": "change_thing",
0135                     "parameters": {"value": 3, "blob": None},
0136                     "requester": clean_user_id(DN),
0137                     "prod_role": False,
0138                     "client_addr": "192.0.2.10",
0139                 }
0140             ],
0141         )
0142         # the key is there while the command runs, and gone after
0143         self.assertEqual(seen_keys, [KEY])
0144         self.assertIsNone(task_command_log.current_task_command.get())
0145         self.assertEqual(fake_task_buffer.responses, [(KEY, {"success": True, "message": "1 tasks changed", "data": {"value": 3}}, False)])
0146 
0147     def test_host_name_is_preferred_to_the_address(self) -> None:
0148         change_thing(FakeRequest(remote_host="client.example.org"), task_id=TASK_ID, value=3)
0149         self.assertEqual(fake_task_buffer.inserted[0]["client_addr"], "client.example.org")
0150 
0151     def test_large_argument_is_omitted(self) -> None:
0152         blob = {"x": "a" * COMMAND_ARGUMENT_SIZE_LIMIT}
0153         change_thing(FakeRequest(), task_id=TASK_ID, value=3, blob=blob)
0154         size = len(json.dumps(blob).encode())
0155         self.assertEqual(fake_task_buffer.inserted[0]["parameters"], {"value": 3, "blob": {"omitted_bytes": size}})
0156 
0157     def test_one_row_per_task_of_a_list(self) -> None:
0158         share_tasks(FakeRequest(), task_id_list=[1, 2], share="Express")
0159         self.assertEqual(fake_task_buffer.inserted[0]["task_ids"], [1, 2])
0160         self.assertEqual(fake_task_buffer.inserted[0]["parameters"], {"share": "Express"})
0161 
0162     def test_command_is_refused_when_it_cannot_be_recorded(self) -> None:
0163         for key in (None, RuntimeError("ORA-00942: table or view does not exist")):
0164             with self.subTest(key=key):
0165                 fake_task_buffer.key = key
0166                 seen_keys.clear()
0167                 response = change_thing(FakeRequest(), task_id=TASK_ID, value=3)
0168                 self.assertEqual(response, {"success": False, "message": MESSAGE_COMMAND_LOG, "data": None})
0169                 self.assertEqual(seen_keys, [])
0170                 self.assertEqual(fake_task_buffer.responses, [])
0171 
0172     def test_exception_is_recorded_then_raised(self) -> None:
0173         with self.assertRaises(RuntimeError):
0174             fail_thing(FakeRequest(), task_id=TASK_ID)
0175         self.assertEqual(seen_keys, [KEY])
0176         self.assertIsNone(task_command_log.current_task_command.get())
0177         self.assertEqual(fake_task_buffer.responses, [(KEY, {"exception": "RuntimeError: boom"}, True)])
0178 
0179     def test_response_is_returned_when_it_cannot_be_recorded(self) -> None:
0180         fake_task_buffer.response_ok = False
0181         response = change_thing(FakeRequest(), task_id=TASK_ID, value=3)
0182         self.assertEqual(response, {"success": True, "message": "1 tasks changed", "data": {"value": 3}})
0183 
0184     def test_not_recorded(self) -> None:
0185         # a GET, an endpoint without a task, a request refused by validation
0186         read_thing(FakeRequest(method="GET"), task_id=str(TASK_ID))
0187         submit_thing(FakeRequest(), task_parameters={"taskName": "x"})
0188         refused = change_thing(FakeRequest(), task_id="not a number", value=3)
0189         self.assertFalse(refused["success"])
0190         self.assertEqual(fake_task_buffer.inserted, [])
0191         self.assertEqual(seen_keys, [None, None])
0192 
0193     def test_unregistered_module_is_not_recorded(self) -> None:
0194         common._command_logging_modules.pop(__name__)
0195         change_thing(FakeRequest(), task_id=TASK_ID, value=3)
0196         self.assertEqual(fake_task_buffer.inserted, [])
0197         self.assertEqual(seen_keys, [None])
0198 
0199 
0200 class TestTaskApiCoverage(unittest.TestCase):
0201     def test_task_api_is_registered(self) -> None:
0202         self.assertIn(task_api.__name__, common._command_logging_modules)
0203 
0204     def test_only_submit_takes_no_task(self) -> None:
0205         # every POST endpoint of the task API is recorded, except those that do not name the task they act on
0206         post_endpoints = []
0207         for name, func in inspect.getmembers(task_api, inspect.isfunction):
0208             if func.__module__ != task_api.__name__ or not hasattr(func, "__wrapped__"):
0209                 continue
0210             if inspect.getclosurevars(func).nonlocals.get("request_method") == "POST":
0211                 post_endpoints.append(name)
0212         self.assertEqual(len(post_endpoints), 21)
0213         without_task = [name for name in post_endpoints if not set(inspect.signature(getattr(task_api, name)).parameters) & set(COMMAND_TASK_ID_PARAMETERS)]
0214         self.assertEqual(without_task, ["submit"])
0215 
0216 
0217 class TestEncoders(unittest.TestCase):
0218     def test_parameters_leave_out_req_and_tasks(self) -> None:
0219         encoded = json.loads(encode_command_parameters({"req": object(), "task_id": 1, "task_id_list": [1], "jedi_task_id": 1, "soft": True}))
0220         self.assertEqual(encoded, {"soft": True})
0221 
0222     def test_parameter_json_cannot_hold_is_kept_as_str(self) -> None:
0223         encoded = json.loads(encode_command_parameters({"value": float("nan"), "when": NOW}))
0224         self.assertEqual(encoded, {"value": "nan", "when": str(NOW)})
0225 
0226     def test_response_is_shortened(self) -> None:
0227         response = generate_response(False, message="m" * (COMMAND_RESPONSE_FIELD_LIMIT + 10), data=list(range(1000)))
0228         encoded = json.loads(encode_command_response(response))
0229         self.assertEqual(encoded["success"], False)
0230         self.assertEqual(encoded["message"], "m" * COMMAND_RESPONSE_FIELD_LIMIT)
0231         self.assertEqual(encoded["data"], {"omitted_bytes": len(json.dumps(list(range(1000))).encode())})
0232 
0233     def test_other_response_is_kept_as_str(self) -> None:
0234         self.assertEqual(json.loads(encode_command_response("plain text")), {"response": "plain text"})
0235 
0236 
0237 Answer = Callable[[str, dict[str, Any]], tuple[list[tuple[Any, ...]], int]]
0238 
0239 
0240 class FakeCursor:
0241     def __init__(self, answer: Answer) -> None:
0242         self.answer = answer
0243         self.executed: list[tuple[str, dict[str, Any]]] = []
0244         self.rows: list[tuple[Any, ...]] = []
0245         self.rowcount = 0
0246         self.arraysize = 0
0247 
0248     def execute(self, sql: str, binds: dict[str, Any] | None = None) -> None:
0249         self.executed.append((sql, dict(binds or {})))
0250         self.rows, self.rowcount = self.answer(sql, binds or {})
0251 
0252     def fetchone(self) -> tuple[Any, ...] | None:
0253         return self.rows[0] if self.rows else None
0254 
0255     def fetchall(self) -> list[tuple[Any, ...]]:
0256         return list(self.rows)
0257 
0258     def __iter__(self) -> Any:
0259         return iter(self.rows)
0260 
0261 
0262 def make_proxy(module_class: type, answer: Answer) -> Any:
0263     # a DB proxy module on a fake cursor, with the writes outside the command log mocked
0264     proxy = module_class(_logger)
0265     proxy.conn = mock.Mock()
0266     proxy.cur = FakeCursor(answer)
0267     proxy.get_db_utc_now = mock.Mock(return_value=NOW)
0268     for name in ("record_task_status_change", "push_task_status_message", "setDeftStatus_JEDI", "setSuperStatus_JEDI", "record_job_status_change"):
0269         setattr(proxy, name, mock.Mock())
0270     return proxy
0271 
0272 
0273 def command_log_writes(proxy: Any) -> list[tuple[str, dict[str, Any]]]:
0274     return [(sql, binds) for sql, binds in proxy.cur.executed if "TASKS_COMMANDLOG" in sql]
0275 
0276 
0277 class TestRegisteringForJedi(unittest.TestCase):
0278     def test_queued_supersedes_the_one_before(self) -> None:
0279         proxy = make_proxy(TaskComplexModule, lambda sql, binds: ([], 1))
0280         proxy.mark_task_command_queued(TASK_ID, KEY, "kill")
0281         writes = command_log_writes(proxy)
0282         self.assertEqual(len(writes), 2)
0283         superseded_sql, superseded_binds = writes[0]
0284         self.assertIn("command_id<>:command_id", superseded_sql)
0285         self.assertEqual(
0286             superseded_binds,
0287             {
0288                 ":jediTaskID": TASK_ID,
0289                 ":new_status": "superseded",
0290                 ":old_status": "queued",
0291                 ":now": NOW,
0292                 ":reason": "superseded by kill",
0293                 ":command_id": 42,
0294             },
0295         )
0296         self.assertEqual(
0297             writes[1][1],
0298             {":command_id": 42, ":jediTaskID": TASK_ID, ":command_time": NOW, ":new_status": "queued", ":old_status": "received", ":now": NOW},
0299         )
0300 
0301     def test_command_without_a_row_only_supersedes(self) -> None:
0302         proxy = make_proxy(TaskComplexModule, lambda sql, binds: ([], 1))
0303         proxy.mark_task_command_queued(TASK_ID, None, "resume")
0304         writes = command_log_writes(proxy)
0305         self.assertEqual(len(writes), 1)
0306         self.assertNotIn("command_id", writes[0][0])
0307         self.assertEqual(writes[0][1][":reason"], "superseded by resume")
0308 
0309     def test_send_command_marks_the_row_in_its_transaction(self) -> None:
0310         def answer(sql: str, binds: dict[str, Any]) -> tuple[list[tuple[Any, ...]], int]:
0311             if sql.startswith("SELECT status, prodSourceLabel"):
0312                 return [("running", "managed")], 1
0313             return [], 1
0314 
0315         proxy = make_proxy(TaskEventModule, answer)
0316         proxy._check_command_allowed = mock.Mock(return_value=(True, ""))
0317         ret = proxy.send_command_task_panda_db(TASK_ID, DN, True, "kill", properErrorCode=True, command_key=KEY)
0318         self.assertEqual(ret[0], 0)
0319         tables = [sql.split()[0] + " " + next(word for word in sql.split() if "." in word) for sql, _ in proxy.cur.executed]
0320         # the row is marked after the command is written, and before the commit
0321         self.assertEqual(tables[-2:], ["UPDATE ATLAS_PANDA.TASKS_COMMANDLOG", "UPDATE ATLAS_PANDA.TASKS_COMMANDLOG"])
0322         self.assertTrue(tables[-3].startswith("INSERT"))
0323         proxy.conn.commit.assert_called_once()
0324 
0325     def test_send_command_rolls_back_when_the_row_cannot_be_marked(self) -> None:
0326         def answer(sql: str, binds: dict[str, Any]) -> tuple[list[tuple[Any, ...]], int]:
0327             if "TASKS_COMMANDLOG" in sql:
0328                 raise RuntimeError("ORA-00942: table or view does not exist")
0329             if sql.startswith("SELECT status, prodSourceLabel"):
0330                 return [("running", "managed")], 1
0331             return [], 1
0332 
0333         proxy = make_proxy(TaskEventModule, answer)
0334         proxy._check_command_allowed = mock.Mock(return_value=(True, ""))
0335         proxy._rollback = mock.Mock()
0336         proxy.dump_error_message = mock.Mock()
0337         ret = proxy.send_command_task_panda_db(TASK_ID, DN, True, "kill", properErrorCode=True, command_key=KEY)
0338         self.assertEqual(ret, (1, "failed to register command"))
0339         proxy.conn.commit.assert_not_called()
0340         proxy._rollback.assert_called_once()
0341 
0342 
0343 class TestTakenByJedi(unittest.TestCase):
0344     def run_exec(self, command: str, task_status: str) -> Any:
0345         def answer(sql: str, binds: dict[str, Any]) -> tuple[list[tuple[Any, ...]], int]:
0346             if sql.startswith("SELECT comm_task,comm_cmd,comm_comment"):
0347                 return [(TASK_ID, command, f"{command} by someone")], 1
0348             if sql.startswith("SELECT comm_cmd FROM"):
0349                 return [(command,)], 1
0350             if sql.startswith("SELECT status,oldStatus,wallTimeUnit,splitRule"):
0351                 return [(task_status, None, None, "")], 1
0352             if sql.startswith("UPDATE"):
0353                 return [], 1
0354             return [], 0
0355 
0356         proxy = make_proxy(TaskComplexModule, answer)
0357         proxy.getTasksToExecCommand_JEDI("atlas", "managed")
0358         return proxy
0359 
0360     def test_accepted(self) -> None:
0361         proxy = self.run_exec("kill", "running")
0362         writes = command_log_writes(proxy)
0363         self.assertEqual(len(writes), 1)
0364         self.assertEqual(
0365             writes[0][1],
0366             {":jediTaskID": TASK_ID, ":new_status": "accepted", ":old_status": "queued", ":now": NOW, ":reason": "running -> aborting"},
0367         )
0368         comm_updates = [binds for sql, binds in proxy.cur.executed if sql.startswith("UPDATE") and "PRODSYS_COMM" in sql]
0369         self.assertEqual(comm_updates[0][":comm_cmd"], "killing")
0370 
0371     def test_rejected(self) -> None:
0372         proxy = self.run_exec("retry", "running")
0373         writes = command_log_writes(proxy)
0374         self.assertEqual(len(writes), 1)
0375         self.assertEqual(writes[0][1][":new_status"], "rejected")
0376         self.assertEqual(writes[0][1][":reason"], "task in running")
0377         comm_updates = [binds for sql, binds in proxy.cur.executed if sql.startswith("UPDATE") and "PRODSYS_COMM" in sql]
0378         self.assertEqual(comm_updates[0][":comm_cmd"], "retry failed")
0379 
0380 
0381 if __name__ == "__main__":
0382     unittest.main()