apache-airflow-providers-edge3 1.0.0rc1__py3-none-any.whl

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.
Files changed (39) hide show
  1. airflow/providers/edge3/LICENSE +201 -0
  2. airflow/providers/edge3/__init__.py +39 -0
  3. airflow/providers/edge3/cli/__init__.py +16 -0
  4. airflow/providers/edge3/cli/api_client.py +206 -0
  5. airflow/providers/edge3/cli/dataclasses.py +95 -0
  6. airflow/providers/edge3/cli/edge_command.py +689 -0
  7. airflow/providers/edge3/example_dags/__init__.py +16 -0
  8. airflow/providers/edge3/example_dags/integration_test.py +164 -0
  9. airflow/providers/edge3/example_dags/win_notepad.py +83 -0
  10. airflow/providers/edge3/example_dags/win_test.py +342 -0
  11. airflow/providers/edge3/executors/__init__.py +22 -0
  12. airflow/providers/edge3/executors/edge_executor.py +367 -0
  13. airflow/providers/edge3/get_provider_info.py +99 -0
  14. airflow/providers/edge3/models/__init__.py +16 -0
  15. airflow/providers/edge3/models/edge_job.py +94 -0
  16. airflow/providers/edge3/models/edge_logs.py +73 -0
  17. airflow/providers/edge3/models/edge_worker.py +230 -0
  18. airflow/providers/edge3/openapi/__init__.py +19 -0
  19. airflow/providers/edge3/openapi/edge_worker_api_v1.yaml +808 -0
  20. airflow/providers/edge3/plugins/__init__.py +16 -0
  21. airflow/providers/edge3/plugins/edge_executor_plugin.py +229 -0
  22. airflow/providers/edge3/plugins/templates/edge_worker_hosts.html +175 -0
  23. airflow/providers/edge3/plugins/templates/edge_worker_jobs.html +69 -0
  24. airflow/providers/edge3/version_compat.py +36 -0
  25. airflow/providers/edge3/worker_api/__init__.py +17 -0
  26. airflow/providers/edge3/worker_api/app.py +43 -0
  27. airflow/providers/edge3/worker_api/auth.py +135 -0
  28. airflow/providers/edge3/worker_api/datamodels.py +190 -0
  29. airflow/providers/edge3/worker_api/routes/__init__.py +16 -0
  30. airflow/providers/edge3/worker_api/routes/_v2_compat.py +135 -0
  31. airflow/providers/edge3/worker_api/routes/_v2_routes.py +237 -0
  32. airflow/providers/edge3/worker_api/routes/health.py +28 -0
  33. airflow/providers/edge3/worker_api/routes/jobs.py +162 -0
  34. airflow/providers/edge3/worker_api/routes/logs.py +133 -0
  35. airflow/providers/edge3/worker_api/routes/worker.py +224 -0
  36. apache_airflow_providers_edge3-1.0.0rc1.dist-info/METADATA +117 -0
  37. apache_airflow_providers_edge3-1.0.0rc1.dist-info/RECORD +39 -0
  38. apache_airflow_providers_edge3-1.0.0rc1.dist-info/WHEEL +4 -0
  39. apache_airflow_providers_edge3-1.0.0rc1.dist-info/entry_points.txt +6 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,39 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ #
18
+ # NOTE! THIS FILE IS AUTOMATICALLY GENERATED AND WILL BE
19
+ # OVERWRITTEN WHEN PREPARING DOCUMENTATION FOR THE PACKAGES.
20
+ #
21
+ # IF YOU WANT TO MODIFY THIS FILE, YOU SHOULD MODIFY THE TEMPLATE
22
+ # `PROVIDER__INIT__PY_TEMPLATE.py.jinja2` IN the `dev/breeze/src/airflow_breeze/templates` DIRECTORY
23
+ #
24
+ from __future__ import annotations
25
+
26
+ import packaging.version
27
+
28
+ from airflow import __version__ as airflow_version
29
+
30
+ __all__ = ["__version__"]
31
+
32
+ __version__ = "1.0.0"
33
+
34
+ if packaging.version.parse(packaging.version.parse(airflow_version).base_version) < packaging.version.parse(
35
+ "2.10.0"
36
+ ):
37
+ raise RuntimeError(
38
+ f"The package `apache-airflow-providers-edge3:{__version__}` needs Apache Airflow 2.10.0+"
39
+ )
@@ -0,0 +1,16 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
@@ -0,0 +1,206 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import logging
21
+ import os
22
+ from datetime import datetime
23
+ from http import HTTPStatus
24
+ from pathlib import Path
25
+ from typing import TYPE_CHECKING, Any
26
+ from urllib.parse import quote, urljoin
27
+
28
+ import requests
29
+ from retryhttp import retry, wait_retry_after
30
+ from tenacity import before_log, wait_random_exponential
31
+
32
+ from airflow.configuration import conf
33
+ from airflow.providers.edge3.models.edge_worker import EdgeWorkerVersionException
34
+ from airflow.providers.edge3.version_compat import AIRFLOW_V_3_0_PLUS
35
+ from airflow.providers.edge3.worker_api.datamodels import (
36
+ EdgeJobFetched,
37
+ PushLogsBody,
38
+ WorkerQueuesBody,
39
+ WorkerRegistrationReturn,
40
+ WorkerSetStateReturn,
41
+ WorkerStateBody,
42
+ )
43
+ from airflow.utils.state import TaskInstanceState # noqa: TC001
44
+
45
+ if TYPE_CHECKING:
46
+ from airflow.models.taskinstancekey import TaskInstanceKey
47
+ from airflow.providers.edge3.models.edge_worker import EdgeWorkerState
48
+
49
+ logger = logging.getLogger(__name__)
50
+
51
+
52
+ # Hidden config options for Edge Worker how retries on HTTP requests should be handled
53
+ # Note: Given defaults make attempts after 1, 3, 7, 15, 31seconds, 1:03, 2:07, 3:37 and fails after 5:07min
54
+ # So far there is no other config facility in Task SDK we use ENV for the moment
55
+ # TODO: Consider these env variables jointly in task sdk together with task_sdk/src/airflow/sdk/api/client.py
56
+ API_RETRIES = int(os.getenv("AIRFLOW__EDGE__API_RETRIES", os.getenv("AIRFLOW__WORKERS__API_RETRIES", 10)))
57
+ API_RETRY_WAIT_MIN = float(
58
+ os.getenv("AIRFLOW__EDGE__API_RETRY_WAIT_MIN", os.getenv("AIRFLOW__WORKERS__API_RETRY_WAIT_MIN", 1.0))
59
+ )
60
+ API_RETRY_WAIT_MAX = float(
61
+ os.getenv("AIRFLOW__EDGE__API_RETRY_WAIT_MAX", os.getenv("AIRFLOW__WORKERS__API_RETRY_WAIT_MAX", 90.0))
62
+ )
63
+
64
+
65
+ _default_wait = wait_random_exponential(min=API_RETRY_WAIT_MIN, max=API_RETRY_WAIT_MAX)
66
+
67
+
68
+ @retry(
69
+ reraise=True,
70
+ max_attempt_number=API_RETRIES,
71
+ wait_server_errors=_default_wait,
72
+ wait_network_errors=_default_wait,
73
+ wait_timeouts=_default_wait,
74
+ wait_rate_limited=wait_retry_after(fallback=_default_wait), # No infinite timeout on HTTP 429
75
+ before_sleep=before_log(logger, logging.WARNING),
76
+ )
77
+ def _make_generic_request(method: str, rest_path: str, data: str | None = None) -> Any:
78
+ if AIRFLOW_V_3_0_PLUS:
79
+ from functools import cache
80
+
81
+ from airflow.api_fastapi.auth.tokens import JWTGenerator
82
+
83
+ @cache
84
+ def jwt_generator() -> JWTGenerator:
85
+ clock_grace = conf.getint("core", "internal_api_clock_grace", fallback=30)
86
+ return JWTGenerator(
87
+ secret_key=conf.get("core", "internal_api_secret_key"),
88
+ valid_for=clock_grace,
89
+ audience="api",
90
+ )
91
+
92
+ generator = jwt_generator()
93
+ authorization = generator.generate({"method": rest_path})
94
+ else:
95
+ # Airflow 2.10 compatibility
96
+ from airflow.providers.edge3.worker_api.auth import jwt_signer
97
+
98
+ signer = jwt_signer()
99
+ authorization = signer.generate_signed_token({"method": rest_path})
100
+
101
+ api_url = conf.get("edge", "api_url")
102
+ headers = {
103
+ "Content-Type": "application/json",
104
+ "Accept": "application/json",
105
+ "Authorization": authorization,
106
+ }
107
+ api_endpoint = urljoin(api_url, rest_path)
108
+ response = requests.request(method, url=api_endpoint, data=data, headers=headers)
109
+ response.raise_for_status()
110
+ if response.status_code == HTTPStatus.NO_CONTENT:
111
+ return None
112
+ return json.loads(response.content)
113
+
114
+
115
+ def worker_register(
116
+ hostname: str, state: EdgeWorkerState, queues: list[str] | None, sysinfo: dict
117
+ ) -> WorkerRegistrationReturn:
118
+ """Register worker with the Edge API."""
119
+ try:
120
+ result = _make_generic_request(
121
+ "POST",
122
+ f"worker/{quote(hostname)}",
123
+ WorkerStateBody(state=state, jobs_active=0, queues=queues, sysinfo=sysinfo).model_dump_json(
124
+ exclude_unset=True
125
+ ),
126
+ )
127
+ except requests.HTTPError as e:
128
+ if e.response.status_code == 400:
129
+ raise EdgeWorkerVersionException(str(e))
130
+ raise e
131
+ return WorkerRegistrationReturn(**result)
132
+
133
+
134
+ def worker_set_state(
135
+ hostname: str,
136
+ state: EdgeWorkerState,
137
+ jobs_active: int,
138
+ queues: list[str] | None,
139
+ sysinfo: dict,
140
+ maintenance_comments: str | None = None,
141
+ ) -> WorkerSetStateReturn:
142
+ """Update the state of the worker in the central site and thereby implicitly heartbeat."""
143
+ try:
144
+ result = _make_generic_request(
145
+ "PATCH",
146
+ f"worker/{quote(hostname)}",
147
+ WorkerStateBody(
148
+ state=state,
149
+ jobs_active=jobs_active,
150
+ queues=queues,
151
+ sysinfo=sysinfo,
152
+ maintenance_comments=maintenance_comments,
153
+ ).model_dump_json(exclude_unset=True),
154
+ )
155
+ except requests.HTTPError as e:
156
+ if e.response.status_code == 400:
157
+ raise EdgeWorkerVersionException(str(e))
158
+ raise e
159
+ return WorkerSetStateReturn(**result)
160
+
161
+
162
+ def jobs_fetch(hostname: str, queues: list[str] | None, free_concurrency: int) -> EdgeJobFetched | None:
163
+ """Fetch a job to execute on the edge worker."""
164
+ result = _make_generic_request(
165
+ "POST",
166
+ f"jobs/fetch/{quote(hostname)}",
167
+ WorkerQueuesBody(queues=queues, free_concurrency=free_concurrency).model_dump_json(
168
+ exclude_unset=True
169
+ ),
170
+ )
171
+ if result:
172
+ return EdgeJobFetched(**result)
173
+ return None
174
+
175
+
176
+ def jobs_set_state(key: TaskInstanceKey, state: TaskInstanceState) -> None:
177
+ """Set the state of a job."""
178
+ _make_generic_request(
179
+ "PATCH",
180
+ f"jobs/state/{key.dag_id}/{key.task_id}/{key.run_id}/{key.try_number}/{key.map_index}/{state}",
181
+ )
182
+
183
+
184
+ def logs_logfile_path(task: TaskInstanceKey) -> Path:
185
+ """Elaborate the path and filename to expect from task execution."""
186
+ result = _make_generic_request(
187
+ "GET",
188
+ f"logs/logfile_path/{task.dag_id}/{task.task_id}/{task.run_id}/{task.try_number}/{task.map_index}",
189
+ )
190
+ base_log_folder = conf.get("logging", "base_log_folder", fallback="NOT AVAILABLE")
191
+ return Path(base_log_folder, result)
192
+
193
+
194
+ def logs_push(
195
+ task: TaskInstanceKey,
196
+ log_chunk_time: datetime,
197
+ log_chunk_data: str,
198
+ ) -> None:
199
+ """Push an incremental log chunk from Edge Worker to central site."""
200
+ _make_generic_request(
201
+ "POST",
202
+ f"logs/push/{task.dag_id}/{task.task_id}/{task.run_id}/{task.try_number}/{task.map_index}",
203
+ PushLogsBody(log_chunk_time=log_chunk_time, log_chunk_data=log_chunk_data).model_dump_json(
204
+ exclude_unset=True
205
+ ),
206
+ )
@@ -0,0 +1,95 @@
1
+ # Licensed to the Apache Software Foundation (ASF) under one
2
+ # or more contributor license agreements. See the NOTICE file
3
+ # distributed with this work for additional information
4
+ # regarding copyright ownership. The ASF licenses this file
5
+ # to you under the Apache License, Version 2.0 (the
6
+ # "License"); you may not use this file except in compliance
7
+ # with the License. You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing,
12
+ # software distributed under the License is distributed on an
13
+ # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14
+ # KIND, either express or implied. See the License for the
15
+ # specific language governing permissions and limitations
16
+ # under the License.
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ from dataclasses import asdict, dataclass
21
+ from multiprocessing import Process
22
+ from pathlib import Path
23
+ from typing import TYPE_CHECKING
24
+
25
+ if TYPE_CHECKING:
26
+ from psutil import Popen
27
+
28
+ from airflow.providers.edge3.models.edge_worker import EdgeWorkerState
29
+ from airflow.providers.edge3.worker_api.datamodels import EdgeJobFetched
30
+
31
+
32
+ @dataclass
33
+ class MaintenanceMarker:
34
+ """Maintenance mode status."""
35
+
36
+ maintenance: str
37
+ comments: str | None
38
+
39
+ @property
40
+ def json(self) -> str:
41
+ """Get the maintenance status as JSON."""
42
+ return json.dumps(asdict(self))
43
+
44
+ @staticmethod
45
+ def from_json(json_str: str) -> MaintenanceMarker:
46
+ """Create a Maintenance object from JSON."""
47
+ return MaintenanceMarker(**json.loads(json_str))
48
+
49
+
50
+ @dataclass
51
+ class WorkerStatus:
52
+ """Status of the worker."""
53
+
54
+ job_count: int
55
+ jobs: list
56
+ state: EdgeWorkerState
57
+ maintenance: bool
58
+ maintenance_comments: str | None
59
+ drain: bool
60
+
61
+ @property
62
+ def json(self) -> str:
63
+ """Get the status as JSON."""
64
+ return json.dumps(asdict(self))
65
+
66
+ @staticmethod
67
+ def from_json(json_str: str) -> WorkerStatus:
68
+ """Create a WorkerStatus object from JSON."""
69
+ return WorkerStatus(**json.loads(json_str))
70
+
71
+
72
+ @dataclass
73
+ class Job:
74
+ """Holds all information for a task/job to be executed as bundle."""
75
+
76
+ edge_job: EdgeJobFetched
77
+ process: Popen | Process
78
+ logfile: Path
79
+ logsize: int
80
+ """Last size of log file, point of last chunk push."""
81
+
82
+ @property
83
+ def is_running(self) -> bool:
84
+ """Check if the job is still running."""
85
+ if hasattr(self.process, "returncode") and hasattr(self.process, "poll"):
86
+ self.process.poll()
87
+ return self.process.returncode is None
88
+ return self.process.exitcode is None
89
+
90
+ @property
91
+ def is_success(self) -> bool:
92
+ """Check if the job was successful."""
93
+ if hasattr(self.process, "returncode"):
94
+ return self.process.returncode == 0
95
+ return self.process.exitcode == 0