orchestrator-lso 2.4.0__tar.gz → 2.4.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: orchestrator-lso
3
- Version: 2.4.0
3
+ Version: 2.4.1
4
4
  Summary: LSO, an API for remotely running Ansible playbooks.
5
5
  Author: GÉANT Orchestration and Automation Team
6
6
  Author-email: GÉANT Orchestration and Automation Team <goat@geant.org>
@@ -13,7 +13,7 @@
13
13
 
14
14
  """LSO, an API for remotely running Ansible playbooks."""
15
15
 
16
- __version__ = "2.4.0"
16
+ __version__ = "2.4.1"
17
17
 
18
18
  import logging
19
19
 
@@ -0,0 +1,84 @@
1
+ # Copyright 2023-2025 GÉANT Vereniging.
2
+ # Licensed under the Apache License, Version 2.0 (the "License");
3
+ # you may not use this file except in compliance with the License.
4
+ # You may obtain a copy of the License at
5
+ #
6
+ # http://www.apache.org/licenses/LICENSE-2.0
7
+ #
8
+ # Unless required by applicable law or agreed to in writing, software
9
+ # distributed under the License is distributed on an "AS IS" BASIS,
10
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ # See the License for the specific language governing permissions and
12
+ # limitations under the License.
13
+
14
+ """Module that gathers common API responses and data models."""
15
+
16
+ from pathlib import Path
17
+ from typing import Any
18
+ from uuid import UUID, uuid4
19
+
20
+ from pydantic import HttpUrl
21
+
22
+ from lso.config import ExecutorType, settings
23
+ from lso.tasks import run_playbook_proc_task
24
+ from lso.utils import get_thread_pool
25
+
26
+
27
+ def get_playbook_path(playbook_name: Path) -> Path:
28
+ """Get the path of a playbook on the local filesystem."""
29
+ return Path(settings.ANSIBLE_PLAYBOOKS_ROOT_DIR) / playbook_name
30
+
31
+
32
+ def run_playbook(
33
+ playbook_path: Path,
34
+ extra_vars: dict[str, Any],
35
+ inventory: dict[str, Any] | str,
36
+ callback: HttpUrl | None,
37
+ progress: HttpUrl | None,
38
+ *,
39
+ progress_is_incremental: bool,
40
+ ) -> UUID:
41
+ """Run an Ansible playbook against a specified inventory.
42
+
43
+ :param Path playbook_path: Playbook to be executed.
44
+ :param dict[str, Any] extra_vars: Any extra vars needed for the playbook to run.
45
+ :param dict[str, Any] | str inventory: The inventory that the playbook is executed against.
46
+ :param HttpUrl callback: Callback URL where the playbook should send a status update when execution is completed.
47
+ This is used for workflow-orchestrator to continue with the next step in a workflow.
48
+ :return UUID: Job ID of the launched playbook.
49
+ """
50
+ job_id = uuid4()
51
+ callback_str = None
52
+ progress_str = None
53
+ if callback:
54
+ callback_str = str(callback)
55
+ if progress:
56
+ progress_str = str(progress)
57
+
58
+ if settings.EXECUTOR == ExecutorType.THREADPOOL:
59
+ executor = get_thread_pool()
60
+ executor_handle = executor.submit(
61
+ run_playbook_proc_task,
62
+ str(job_id),
63
+ str(playbook_path),
64
+ extra_vars,
65
+ inventory,
66
+ callback_str,
67
+ progress_str,
68
+ progress_is_incremental=progress_is_incremental,
69
+ )
70
+ if settings.TESTING:
71
+ executor_handle.result()
72
+
73
+ elif settings.EXECUTOR == ExecutorType.WORKER:
74
+ run_playbook_proc_task.delay(
75
+ str(job_id),
76
+ str(playbook_path),
77
+ extra_vars,
78
+ inventory,
79
+ callback_str,
80
+ progress_str,
81
+ progress_is_incremental=progress_is_incremental,
82
+ )
83
+
84
+ return job_id
@@ -28,37 +28,101 @@ from starlette import status
28
28
 
29
29
  from lso.config import settings
30
30
  from lso.schema import ExecutableRunResponse
31
- from lso.utils import CallbackFailedError
32
31
  from lso.worker import RUN_EXECUTABLE, RUN_PLAYBOOK, celery
33
32
 
34
33
  logger = logging.getLogger(__name__)
35
34
 
36
35
 
36
+ class CallbackFailedError(Exception):
37
+ """Exception raised when a callback url can't be reached."""
38
+
39
+
40
+ def playbook_event_handler_factory(
41
+ progress: str | None, *, progress_is_incremental: bool
42
+ ) -> Callable[[dict], bool] | None:
43
+ """Create an event handler for Ansible playbook runs.
44
+
45
+ This is used to send incremental progress updates to the external system that called for this playbook to be run.
46
+
47
+ :param str progress: The progress URL where the external system expects to receive updates.
48
+ :param bool progress_is_incremental: Whether progress updates are sent incrementally, or only contain the latest
49
+ event data.
50
+ """
51
+ events_stdout = []
52
+
53
+ def _playbook_event_handler(event: dict) -> bool:
54
+ if progress_is_incremental:
55
+ emit_body = event["stdout"].strip()
56
+ else:
57
+ events_stdout.append(event["stdout"].strip())
58
+ emit_body = events_stdout
59
+
60
+ requests.post(str(progress), json={"progress": emit_body}, timeout=settings.REQUEST_TIMEOUT_SEC)
61
+ return True
62
+
63
+ if progress:
64
+ return _playbook_event_handler
65
+ return None
66
+
67
+
68
+ def playbook_finished_handler_factory(callback: str | None, job_id: str) -> Callable[[Runner], None] | None:
69
+ """Create an event handler for finished Ansible playbook runs.
70
+
71
+ Once Ansible runner is finished, it will call the handler method created by this factory before teardown.
72
+
73
+ :param str callback: The callback URL that ansible runner should report to.
74
+ :param str job_id: The job ID of this playbook run, used for reporting.
75
+ :return Callable: A handler method that sends one request to the callback URL.
76
+ """
77
+
78
+ def _playbook_finished_handler(runner: Runner) -> None:
79
+ payload = {
80
+ "status": runner.status,
81
+ "job_id": job_id,
82
+ "output": runner.stdout.readlines(),
83
+ "return_code": int(runner.rc),
84
+ }
85
+
86
+ response = requests.post(str(callback), json=payload, timeout=settings.REQUEST_TIMEOUT_SEC)
87
+ if not (status.HTTP_200_OK <= response.status_code < status.HTTP_300_MULTIPLE_CHOICES):
88
+ msg = f"Callback failed: {response.text}, url: {callback}"
89
+ raise CallbackFailedError(msg)
90
+
91
+ if callback:
92
+ return _playbook_finished_handler
93
+ return None
94
+
95
+
37
96
  @celery.task(name=RUN_PLAYBOOK) # type: ignore[misc]
38
97
  def run_playbook_proc_task(
98
+ job_id: str,
39
99
  playbook_path: str,
40
100
  extra_vars: dict[str, Any],
41
101
  inventory: dict[str, Any] | str,
42
- event_handler: Callable[[dict], bool] | None = None,
43
- finished_callback: Callable[[Runner], None] | None = None,
102
+ callback: str | None,
103
+ progress: str | None,
104
+ *,
105
+ progress_is_incremental: bool,
44
106
  ) -> None:
45
107
  """Celery task to run a playbook.
46
108
 
109
+ :param str job_id: Identifier of the job being executed.
47
110
  :param str playbook_path: Path to the playbook to be executed.
48
111
  :param dict[str, Any] extra_vars: Extra variables to pass to the playbook.
49
112
  :param dict[str, Any] | str inventory: Inventory to run the playbook against.
50
- :param Callable[[dict], bool] event_handler: Event handler method that is executed on every event while the playbook
51
- runs.
52
- :param Callable[[Runner], None] finished_callback: Callback handler method that is executed once the playbook run is
53
- completed.
113
+ :param str callback: Callback URL for status updates.
114
+ :param str progress: URL for sending progress updates.
115
+ :param bool progress_is_incremental: Whether progress updates include all past progress.
54
116
  :return: None
55
117
  """
118
+ msg = f"playbook_path: {playbook_path}, callback: {callback}"
119
+ logger.info(msg)
56
120
  run(
57
121
  playbook=playbook_path,
58
122
  inventory=inventory,
59
123
  extravars=extra_vars,
60
- event_handler=event_handler,
61
- finished_callback=finished_callback,
124
+ event_handler=playbook_event_handler_factory(progress, progress_is_incremental=progress_is_incremental),
125
+ finished_callback=playbook_finished_handler_factory(callback, job_id),
62
126
  )
63
127
 
64
128
 
@@ -20,10 +20,6 @@ from lso.config import settings
20
20
  _executor = None
21
21
 
22
22
 
23
- class CallbackFailedError(Exception):
24
- """Exception raised when a callback url can't be reached."""
25
-
26
-
27
23
  def get_thread_pool() -> ThreadPoolExecutor:
28
24
  """Initialize or return a cached ThreadPoolExecutor for local asynchronous execution."""
29
25
  global _executor # noqa: PLW0603
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "orchestrator-lso"
3
- version = "2.4.0"
3
+ version = "2.4.1"
4
4
  description = "LSO, an API for remotely running Ansible playbooks."
5
5
  readme = "README.md"
6
6
  license = "Apache-2.0"
@@ -1,143 +0,0 @@
1
- # Copyright 2023-2025 GÉANT Vereniging.
2
- # Licensed under the Apache License, Version 2.0 (the "License");
3
- # you may not use this file except in compliance with the License.
4
- # You may obtain a copy of the License at
5
- #
6
- # http://www.apache.org/licenses/LICENSE-2.0
7
- #
8
- # Unless required by applicable law or agreed to in writing, software
9
- # distributed under the License is distributed on an "AS IS" BASIS,
10
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
- # See the License for the specific language governing permissions and
12
- # limitations under the License.
13
-
14
- """Module that gathers common API responses and data models."""
15
-
16
- import logging
17
- from collections.abc import Callable
18
- from pathlib import Path
19
- from typing import Any
20
- from uuid import UUID, uuid4
21
-
22
- import requests
23
- from ansible_runner import Runner
24
- from pydantic import HttpUrl
25
- from starlette import status
26
-
27
- from lso.config import ExecutorType, settings
28
- from lso.tasks import run_playbook_proc_task
29
- from lso.utils import CallbackFailedError, get_thread_pool
30
-
31
- logger = logging.getLogger(__name__)
32
-
33
-
34
- def get_playbook_path(playbook_name: Path) -> Path:
35
- """Get the path of a playbook on the local filesystem."""
36
- return Path(settings.ANSIBLE_PLAYBOOKS_ROOT_DIR) / playbook_name
37
-
38
-
39
- def playbook_event_handler_factory(progress: str, *, progress_is_incremental: bool) -> Callable[[dict], bool]:
40
- """Create an event handler for Ansible playbook runs.
41
-
42
- This is used to send incremental progress updates to the external system that called for this playbook to be run.
43
-
44
- :param str progress: The progress URL where the external system expects to receive updates.
45
- :param bool progress_is_incremental: Whether progress updates are sent incrementally, or only contain the latest
46
- event data.
47
- :return Callable[[dict], bool]]: A handler method that processes every Ansible playbook event.
48
- """
49
- events_stdout = []
50
-
51
- def _playbook_event_handler(event: dict) -> bool:
52
- if progress_is_incremental:
53
- emit_body = event["stdout"].strip()
54
- else:
55
- events_stdout.append(event["stdout"].strip())
56
- emit_body = events_stdout
57
-
58
- requests.post(str(progress), json={"progress": emit_body}, timeout=settings.REQUEST_TIMEOUT_SEC)
59
- return True
60
-
61
- return _playbook_event_handler
62
-
63
-
64
- def playbook_finished_handler_factory(callback: str, job_id: UUID) -> Callable[[Runner], None]:
65
- """Create an event handler for finished Ansible playbook runs.
66
-
67
- Once Ansible runner is finished, it will call the handler method created by this factory before teardown.
68
-
69
- :param str callback: The callback URL that ansible runner should report to.
70
- :param UUID job_id: The job ID of this playbook run, used for reporting.
71
- :return Callable[[Runner], None]: A handler method that sends one request to the callback URL.
72
- """
73
-
74
- def _playbook_finished_handler(runner: Runner) -> None:
75
- payload = {
76
- "status": runner.status,
77
- "job_id": str(job_id),
78
- "output": runner.stdout.readlines(),
79
- "return_code": int(runner.rc),
80
- }
81
-
82
- response = requests.post(str(callback), json=payload, timeout=settings.REQUEST_TIMEOUT_SEC)
83
- if not (status.HTTP_200_OK <= response.status_code < status.HTTP_300_MULTIPLE_CHOICES):
84
- msg = f"Callback failed: {response.text}, url: {callback}"
85
- raise CallbackFailedError(msg)
86
-
87
- return _playbook_finished_handler
88
-
89
-
90
- def run_playbook(
91
- playbook_path: Path,
92
- extra_vars: dict[str, Any],
93
- inventory: dict[str, Any] | str,
94
- callback: HttpUrl | None,
95
- progress: HttpUrl | None,
96
- *,
97
- progress_is_incremental: bool,
98
- ) -> UUID:
99
- """Run an Ansible playbook against a specified inventory.
100
-
101
- :param Path playbook_path: Playbook to be executed.
102
- :param dict[str, Any] extra_vars: Any extra vars needed for the playbook to run.
103
- :param dict[str, Any] | str inventory: The inventory that the playbook is executed against.
104
- :param HttpUrl callback: Callback URL where the playbook should send a status update when execution is completed.
105
- This is used for workflow-orchestrator to continue with the next step in a workflow.
106
- :return UUID: Job ID of the launched playbook.
107
- """
108
- msg = f"playbook_path: {playbook_path}"
109
- job_id = uuid4()
110
- callback_str = None
111
- progress_str = None
112
- event_handler = None
113
- finished_callback = None
114
-
115
- if callback:
116
- callback_str = str(callback)
117
- msg += f", callback URL: {callback_str}"
118
- finished_callback = playbook_finished_handler_factory(callback_str, job_id)
119
- if progress:
120
- progress_str = str(progress)
121
- msg += f", progress URL: {progress_str}"
122
- event_handler = playbook_event_handler_factory(progress_str, progress_is_incremental=progress_is_incremental)
123
-
124
- logger.info(msg)
125
-
126
- if settings.EXECUTOR == ExecutorType.THREADPOOL:
127
- executor = get_thread_pool()
128
- executor_handle = executor.submit(
129
- run_playbook_proc_task, str(playbook_path), extra_vars, inventory, event_handler, finished_callback
130
- )
131
- if settings.TESTING:
132
- executor_handle.result()
133
-
134
- elif settings.EXECUTOR == ExecutorType.WORKER:
135
- run_playbook_proc_task.delay(
136
- str(playbook_path),
137
- extra_vars,
138
- inventory,
139
- event_handler,
140
- finished_callback,
141
- )
142
-
143
- return job_id