foxops 2.7.0__tar.gz → 2.8.0__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.
Files changed (58) hide show
  1. {foxops-2.7.0 → foxops-2.8.0}/PKG-INFO +7 -4
  2. {foxops-2.7.0 → foxops-2.8.0}/pyproject.toml +12 -13
  3. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/rendering.py +9 -9
  4. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/hosters/types.py +14 -24
  5. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/services/change.py +42 -25
  6. foxops-2.8.0/src/foxops/utils.py +100 -0
  7. foxops-2.7.0/src/foxops/utils.py +0 -65
  8. {foxops-2.7.0 → foxops-2.8.0}/LICENSE +0 -0
  9. {foxops-2.7.0 → foxops-2.8.0}/README.md +0 -0
  10. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/__init__.py +0 -0
  11. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/__main__.py +0 -0
  12. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/__init__.py +0 -0
  13. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/engine.py +0 -0
  14. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/__init__.py +0 -0
  15. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/change/__init__.py +0 -0
  16. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/change/errors.py +0 -0
  17. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/change/model.py +0 -0
  18. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/change/repository.py +0 -0
  19. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/incarnation/__init__.py +0 -0
  20. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/incarnation/errors.py +0 -0
  21. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/incarnation/model.py +0 -0
  22. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/repositories/incarnation/repository.py +0 -0
  23. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/database/schema.py +0 -0
  24. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/dependencies.py +0 -0
  25. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/__init__.py +0 -0
  26. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/__main__.py +0 -0
  27. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/custom_filters.py +0 -0
  28. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/errors.py +0 -0
  29. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/initialization.py +0 -0
  30. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/models/__init__.py +0 -0
  31. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/models/incarnation_state.py +0 -0
  32. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/models/template_config.py +0 -0
  33. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/patching/__init__.py +0 -0
  34. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/patching/git_diff_patch.py +0 -0
  35. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/engine/update.py +0 -0
  36. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/error_handlers.py +0 -0
  37. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/errors.py +0 -0
  38. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/external/__init__.py +0 -0
  39. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/external/git.py +0 -0
  40. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/hosters/__init__.py +0 -0
  41. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/hosters/gitlab.py +0 -0
  42. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/hosters/local.py +0 -0
  43. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/logger.py +0 -0
  44. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/middlewares.py +0 -0
  45. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/models/__init__.py +0 -0
  46. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/models/change.py +0 -0
  47. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/models/errors.py +0 -0
  48. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/models/incarnation.py +0 -0
  49. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/openapi.py +0 -0
  50. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/__init__.py +0 -0
  51. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/auth.py +0 -0
  52. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/changes.py +0 -0
  53. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/incarnations.py +0 -0
  54. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/not_found.py +0 -0
  55. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/routers/version.py +0 -0
  56. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/services/__init__.py +0 -0
  57. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/services/incarnation.py +0 -0
  58. {foxops-2.7.0 → foxops-2.8.0}/src/foxops/settings.py +0 -0
@@ -1,26 +1,29 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: foxops
3
- Version: 2.7.0
3
+ Version: 2.8.0
4
4
  Summary: Foxops 🦊
5
5
  License: Apache-2.0
6
6
  License-File: LICENSE
7
7
  Author: Alexander Hungenberg
8
8
  Author-email: alexander.hungenberg@roche.com
9
- Requires-Python: >=3.12,<3.13
9
+ Requires-Python: >=3.12,<3.15
10
10
  Classifier: License :: OSI Approved :: Apache Software License
11
11
  Classifier: Programming Language :: Python :: 3
12
12
  Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Programming Language :: Python :: 3.13
14
+ Classifier: Programming Language :: Python :: 3.14
13
15
  Requires-Dist: Jinja2 (>=3.0.3,<4.0.0)
14
16
  Requires-Dist: SQLAlchemy[asyncio] (>=2.0.2,<3.0.0)
15
- Requires-Dist: aiopath (>=0.7.7,<0.8.0)
16
17
  Requires-Dist: aiosqlite (>=0.20.0,<0.21.0)
17
18
  Requires-Dist: alembic[tz] (>=1.8.1,<2.0.0)
18
- Requires-Dist: asyncpg (>=0.29.0,<0.30.0)
19
+ Requires-Dist: anyio (>=4.0)
20
+ Requires-Dist: asyncpg (>=0.31.0,<0.32.0)
19
21
  Requires-Dist: fastapi (>=0.120.1)
20
22
  Requires-Dist: greenlet (>=3.1.1,<4.0.0)
21
23
  Requires-Dist: httpx (>=0.27.2,<0.28.0)
22
24
  Requires-Dist: pydantic (>=2.11.7,<3.0.0)
23
25
  Requires-Dist: pydantic-settings (==2.10.1)
26
+ Requires-Dist: requests (==2.33.1)
24
27
  Requires-Dist: rich (>=14.1.0,<15.0.0)
25
28
  Requires-Dist: ruamel.yaml (>=0.17.20,<0.18.0)
26
29
  Requires-Dist: starlette (==0.49.3)
@@ -1,7 +1,7 @@
1
1
  [tool.poetry]
2
2
  name = "foxops"
3
3
  # managed by poetry-dynamic-versioning, do not change.
4
- version = "2.7.0"
4
+ version = "2.8.0"
5
5
  description = "Foxops 🦊"
6
6
  license = "Apache-2.0"
7
7
  authors = [
@@ -14,7 +14,7 @@ readme = "README.md"
14
14
  fengine = 'foxops.engine.__main__:app'
15
15
 
16
16
  [tool.poetry.dependencies]
17
- python = ">=3.12,<3.13"
17
+ python = ">=3.12,<3.15"
18
18
 
19
19
  # Web Framework
20
20
  uvicorn = "0.38.0"
@@ -26,11 +26,11 @@ httpx = "^0.27.2"
26
26
  tenacity = "^9.0.0"
27
27
  pydantic = "^2.11.7"
28
28
  structlog = "25.5.0"
29
- aiopath = "^0.7.7"
29
+ anyio = ">=4.0"
30
30
 
31
31
  # Database
32
32
  SQLAlchemy = {extras = ["asyncio"], version = "^2.0.2"}
33
- asyncpg = "^0.29.0"
33
+ asyncpg = "^0.31.0"
34
34
  aiosqlite = "^0.20.0"
35
35
  alembic = {extras = ["tz"], version = "^1.8.1"}
36
36
  greenlet = "^3.1.1"
@@ -43,11 +43,12 @@ typer = "0.16.0"
43
43
  Jinja2 = "^3.0.3"
44
44
  pydantic-settings = "2.10.1"
45
45
  rich = "^14.1.0"
46
+ requests = "2.33.1"
46
47
 
47
48
  [tool.poetry.dev-dependencies]
48
49
  # Linting
49
50
  flake8 = "^6.0.0"
50
- flake8-bugbear = "^23.5.9"
51
+ flake8-bugbear = "^24.12.12"
51
52
  isort = "5.13.2"
52
53
 
53
54
  # Testing
@@ -61,17 +62,17 @@ mypy = "1.17.0"
61
62
  SQLAlchemy = {extras = ["mypy"], version = "^2.0.2"}
62
63
 
63
64
  # Docs
64
- Sphinx = "^7.2.5"
65
+ Sphinx = "^8.0.0"
65
66
  sphinx-copybutton = "^0.5.0"
66
- sphinx-design = "^0.5.0"
67
+ sphinx-design = "^0.7.0"
67
68
  sphinx-autobuild = "^2021.3.14"
68
69
  sphinxcontrib-mermaid = "^0.9.2"
69
- myst-parser = "^2.0.0"
70
- furo = "^2023.5.20"
70
+ myst-parser = "^5.0.0"
71
+ furo = "^2024.1.29"
71
72
  pytest-alembic = "^0.10.0"
72
73
 
73
74
  [tool.poetry.group.dev.dependencies]
74
- black = {extras = ["d"], version = "^23.3.0"}
75
+ black = {extras = ["d"], version = ">=23.3,<27.0"}
75
76
  coverage = "^7.3.1"
76
77
  pytest-xdist = "^3.3.1"
77
78
 
@@ -97,9 +98,7 @@ asyncio_mode = "auto"
97
98
  plugins = [
98
99
  "pydantic.mypy",
99
100
  ]
100
- overrides = [
101
- {module = "aiopath", ignore_missing_imports = true}
102
- ]
101
+ overrides = []
103
102
 
104
103
  [tool.coverage.run]
105
104
  include = ["src/**"]
@@ -3,7 +3,7 @@ import os
3
3
  import typing
4
4
  from pathlib import Path
5
5
 
6
- from aiopath import AsyncPath
6
+ from anyio import Path as AsyncPath
7
7
  from jinja2 import FileSystemLoader, StrictUndefined
8
8
  from jinja2.sandbox import SandboxedEnvironment
9
9
 
@@ -152,13 +152,13 @@ async def render_template_file(
152
152
  )
153
153
 
154
154
  template_file_stat = template_file_path.stat(follow_symlinks=False) # type: ignore
155
- incarnation_file_path = AsyncPath(incarnation_root_dir, rendered_path)
156
- await incarnation_file_path.parent.mkdir(parents=True, exist_ok=True)
155
+ incarnation_file_path = Path(incarnation_root_dir) / rendered_path
156
+ await AsyncPath(incarnation_file_path).parent.mkdir(parents=True, exist_ok=True)
157
157
  if render_content:
158
- await incarnation_file_path.write_text(rendered_content)
158
+ await AsyncPath(incarnation_file_path).write_text(typing.cast(str, rendered_content))
159
159
  else:
160
- await incarnation_file_path.write_bytes(rendered_content)
161
- apply_path_stats(Path(incarnation_file_path), template_file_stat)
160
+ await AsyncPath(incarnation_file_path).write_bytes(typing.cast(bytes, rendered_content))
161
+ apply_path_stats(incarnation_file_path, template_file_stat)
162
162
  return incarnation_file_path
163
163
 
164
164
 
@@ -179,9 +179,9 @@ async def render_template_dir(
179
179
  logger.debug("rendering directory in incarnation", path=rendered_path)
180
180
 
181
181
  template_dir_stat = template_dir_path.stat(follow_symlinks=False) # type: ignore
182
- incarnation_dir_path = AsyncPath(incarnation_root_dir, rendered_path)
183
- await incarnation_dir_path.mkdir(parents=True, exist_ok=True)
184
- apply_path_stats(Path(incarnation_dir_path), template_dir_stat)
182
+ incarnation_dir_path = Path(incarnation_root_dir) / rendered_path
183
+ await AsyncPath(incarnation_dir_path).mkdir(parents=True, exist_ok=True)
184
+ apply_path_stats(incarnation_dir_path, template_dir_stat)
185
185
  return incarnation_dir_path
186
186
 
187
187
 
@@ -30,13 +30,11 @@ class MergeRequestStatus(Enum):
30
30
 
31
31
 
32
32
  class Hoster(Protocol):
33
- async def validate(self) -> None:
34
- ...
33
+ async def validate(self) -> None: ...
35
34
 
36
35
  async def get_incarnation_state(
37
36
  self, incarnation_repository: str, target_directory: str
38
- ) -> tuple[GitSha, IncarnationState] | None:
39
- ...
37
+ ) -> tuple[GitSha, IncarnationState] | None: ...
40
38
 
41
39
  async def merge_request(
42
40
  self,
@@ -47,24 +45,19 @@ class Hoster(Protocol):
47
45
  description: str,
48
46
  incarnation_sub_directory: str,
49
47
  with_automerge=False
50
- ) -> tuple[GitSha, MergeRequestId]:
51
- ...
48
+ ) -> tuple[GitSha, MergeRequestId]: ...
52
49
 
53
50
  def cloned_repository(
54
51
  self, repository: str, *, refspec: str | None = None, bare: bool = False
55
- ) -> AsyncContextManager[GitRepository]:
56
- ...
52
+ ) -> AsyncContextManager[GitRepository]: ...
57
53
 
58
- async def has_pending_incarnation_branch(self, project_identifier: str, branch: str) -> GitSha | None:
59
- ...
54
+ async def has_pending_incarnation_branch(self, project_identifier: str, branch: str) -> GitSha | None: ...
60
55
 
61
56
  async def has_pending_incarnation_merge_request(
62
57
  self, project_identifier: str, branch: str
63
- ) -> MergeRequestId | None:
64
- ...
58
+ ) -> MergeRequestId | None: ...
65
59
 
66
- async def get_repository_metadata(self, project_identifier: str) -> RepositoryMetadata:
67
- ...
60
+ async def get_repository_metadata(self, project_identifier: str) -> RepositoryMetadata: ...
68
61
 
69
62
  async def get_reconciliation_status(
70
63
  self,
@@ -73,17 +66,14 @@ class Hoster(Protocol):
73
66
  commit_sha: GitSha,
74
67
  merge_request_id: str | None,
75
68
  pipeline_timeout: timedelta | None = None,
76
- ) -> ReconciliationStatus:
77
- ...
69
+ ) -> ReconciliationStatus: ...
78
70
 
79
- async def does_commit_exist(self, incarnation_repository: str, commit_sha: GitSha) -> bool:
80
- ...
71
+ async def does_commit_exist(self, incarnation_repository: str, commit_sha: GitSha) -> bool: ...
81
72
 
82
- async def get_commit_url(self, incarnation_repository: str, commit_sha: GitSha) -> str:
83
- ...
73
+ async def get_commit_url(self, incarnation_repository: str, commit_sha: GitSha) -> str: ...
84
74
 
85
- async def get_merge_request_url(self, incarnation_repository: str, merge_request_id: str) -> str:
86
- ...
75
+ async def get_merge_request_url(self, incarnation_repository: str, merge_request_id: str) -> str: ...
87
76
 
88
- async def get_merge_request_status(self, incarnation_repository: str, merge_request_id: str) -> MergeRequestStatus:
89
- ...
77
+ async def get_merge_request_status(
78
+ self, incarnation_repository: str, merge_request_id: str
79
+ ) -> MergeRequestStatus: ...
@@ -25,7 +25,7 @@ from foxops.engine.patching.git_diff_patch import PatchResult
25
25
  from foxops.errors import RetryableError
26
26
  from foxops.external.git import GitError, GitRepository
27
27
  from foxops.hosters import Hoster
28
- from foxops.hosters.types import MergeRequestStatus
28
+ from foxops.hosters.types import MergeRequestStatus, ReconciliationStatus
29
29
  from foxops.models import IncarnationWithDetails
30
30
  from foxops.models.change import Change, ChangeWithMergeRequest
31
31
  from foxops.utils import get_logger
@@ -545,20 +545,45 @@ class ChangeService:
545
545
  merge_request_status: MergeRequestStatus | None = None
546
546
 
547
547
  change: Change | ChangeWithMergeRequest
548
- if change_type == ChangeType.MERGE_REQUEST:
549
- change = await self.get_change_with_merge_request(change_id)
548
+ try:
549
+ if change_type == ChangeType.MERGE_REQUEST:
550
+ change = await self.get_change_with_merge_request(change_id)
550
551
 
551
- merge_request_id = change.merge_request_id
552
- merge_request_status = await self._hoster.get_merge_request_status(
553
- incarnation.incarnation_repository, merge_request_id
554
- )
555
- merge_request_url = await self._hoster.get_merge_request_url(
556
- incarnation.incarnation_repository, merge_request_id
552
+ merge_request_id = change.merge_request_id
553
+ merge_request_status = await self._hoster.get_merge_request_status(
554
+ incarnation.incarnation_repository, merge_request_id
555
+ )
556
+ merge_request_url = await self._hoster.get_merge_request_url(
557
+ incarnation.incarnation_repository, merge_request_id
558
+ )
559
+ elif change_type == ChangeType.DIRECT:
560
+ change = await self.get_change(change_id)
561
+ else:
562
+ raise ValueError(f"Unknown change type {change_type}")
563
+ except IncompleteChange:
564
+ # The latest change has not been fully committed/pushed yet. Return what is known
565
+ # from the database so that the incarnation remains readable and deletable.
566
+ # Use the fix endpoint to repair the change before attempting further updates.
567
+ change_in_db = await self._change_repository.get_change(change_id)
568
+ return IncarnationWithDetails(
569
+ id=incarnation.id,
570
+ incarnation_repository=incarnation.incarnation_repository,
571
+ target_directory=incarnation.target_directory,
572
+ commit_sha=change_in_db.commit_sha,
573
+ commit_url=await self._hoster.get_commit_url(
574
+ incarnation.incarnation_repository, change_in_db.commit_sha
575
+ ),
576
+ merge_request_id=change_in_db.merge_request_id,
577
+ merge_request_url=None,
578
+ merge_request_status=None,
579
+ status=ReconciliationStatus.UNKNOWN,
580
+ revision=change_in_db.revision,
581
+ template_repository=incarnation.template_repository,
582
+ template_repository_version=change_in_db.requested_version,
583
+ template_repository_version_hash=change_in_db.requested_version_hash,
584
+ template_data=json.loads(change_in_db.requested_data),
585
+ template_data_full=json.loads(change_in_db.template_data_full),
557
586
  )
558
- elif change_type == ChangeType.DIRECT:
559
- change = await self.get_change(change_id)
560
- else:
561
- raise ValueError(f"Unknown change type {change_type}")
562
587
 
563
588
  status = await self._hoster.get_reconciliation_status(
564
589
  incarnation_repository=incarnation.incarnation_repository,
@@ -745,29 +770,21 @@ def _construct_merge_request_conflict_description(
745
770
 
746
771
  if conflict_files:
747
772
  conflict_files_text = "\n".join([f"- {f}" for f in conflict_files])
748
- description_paragraphs.append(
749
- inspect.cleandoc(
750
- f"""
773
+ description_paragraphs.append(inspect.cleandoc(f"""
751
774
  The following files were updated in the template repository - and at the same time - also
752
775
  **modified** in the incarnation repository. Please resolve the conflicts manually:
753
776
 
754
777
  {conflict_files_text}
755
- """
756
- )
757
- )
778
+ """))
758
779
 
759
780
  if deleted_files:
760
781
  deleted_files_text = "\n".join([f"- {f}" for f in deleted_files])
761
- description_paragraphs.append(
762
- inspect.cleandoc(
763
- f"""
782
+ description_paragraphs.append(inspect.cleandoc(f"""
764
783
  The following files were updated in the template repository but are **no longer
765
784
  present** in this incarnation repository. Please resolve the conflicts manually:
766
785
 
767
786
  {deleted_files_text}
768
- """
769
- )
770
- )
787
+ """))
771
788
 
772
789
  return "\n\n".join(description_paragraphs)
773
790
 
@@ -0,0 +1,100 @@
1
+ import asyncio
2
+ import subprocess
3
+ import weakref
4
+
5
+ from .errors import FoxopsError
6
+ from .logger import get_logger
7
+
8
+ logger = get_logger("utils")
9
+
10
+ # One semaphore per event loop — avoids "bound to a different event loop" errors
11
+ # when multiple loops exist (e.g. in tests). Each subprocess with stdout=PIPE,
12
+ # stderr=PIPE holds 2 FDs; the cap of 16 prevents FD exhaustion under concurrency.
13
+ _subprocess_semaphores: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, asyncio.Semaphore] = (
14
+ weakref.WeakKeyDictionary()
15
+ )
16
+
17
+
18
+ def _get_subprocess_semaphore() -> asyncio.Semaphore:
19
+ loop = asyncio.get_running_loop()
20
+ sem = _subprocess_semaphores.get(loop)
21
+ if sem is None:
22
+ sem = asyncio.Semaphore(16)
23
+ _subprocess_semaphores[loop] = sem
24
+ return sem
25
+
26
+
27
+ class CalledProcessError(subprocess.CalledProcessError, FoxopsError):
28
+ """Error raised when copier fails."""
29
+
30
+ def __str__(self):
31
+ def decode(data):
32
+ if isinstance(data, bytes):
33
+ return data.decode(errors="replace")
34
+ return data or ""
35
+
36
+ parts = [f"Command {self.cmd!r} returned non-zero exit status {self.returncode}."]
37
+ stdout = decode(self.stdout).strip()
38
+ stderr = decode(self.stderr).strip()
39
+ if stdout:
40
+ parts.append(f"stdout:\n{stdout}")
41
+ if stderr:
42
+ parts.append(f"stderr:\n{stderr}")
43
+ return "\n".join(parts)
44
+
45
+
46
+ async def check_call(
47
+ program: str,
48
+ *args,
49
+ expected_returncodes: frozenset = frozenset({0}),
50
+ timeout: int | float | None = None,
51
+ **kwargs,
52
+ ) -> asyncio.subprocess.Process:
53
+ """Execute the given executable and raise error on non-zero exit code.
54
+
55
+ This function is simply wrapping `asyncio.create_subprocess_exec()`
56
+ and raises and exception in case the exit code is non-zero,
57
+ similar to what `subprocess.check_call()` does.
58
+
59
+ The timeout parameter can be used to specify a maximum wait time in seconds. If the timeout expires before the
60
+ called process completes, the subprocess will be killed.
61
+ -> Setting the timeout to None (default) will allow the child process to take forever.
62
+ """
63
+ async with _get_subprocess_semaphore():
64
+ proc = await asyncio.create_subprocess_exec(
65
+ program,
66
+ *args,
67
+ stdout=asyncio.subprocess.PIPE,
68
+ stderr=asyncio.subprocess.PIPE,
69
+ **kwargs,
70
+ )
71
+
72
+ try:
73
+ await asyncio.wait_for(proc.wait(), timeout=timeout)
74
+ except asyncio.TimeoutError:
75
+ proc.kill()
76
+ stdout_buffer = None if proc.stdout is None else bytes(proc.stdout._buffer) # type: ignore
77
+ stderr_buffer = None if proc.stderr is None else bytes(proc.stderr._buffer) # type: ignore
78
+
79
+ logger.error(
80
+ "killed process as it exceeded the timeout",
81
+ stdout_buffer=stdout_buffer,
82
+ stderr_buffer=stderr_buffer,
83
+ )
84
+ raise
85
+ except BaseException:
86
+ # Kill the process on cancellation or any other unexpected exception so
87
+ # that orphan subprocesses do not block event-loop shutdown
88
+ # (ThreadedChildWatcher joins child-watcher threads on loop close).
89
+ proc.kill()
90
+ raise
91
+
92
+ if proc.returncode is not None and proc.returncode not in expected_returncodes:
93
+ raise CalledProcessError(
94
+ proc.returncode,
95
+ [program] + list(args),
96
+ await proc.stdout.read() if proc.stdout else None,
97
+ await proc.stderr.read() if proc.stderr else None,
98
+ )
99
+
100
+ return proc
@@ -1,65 +0,0 @@
1
- import asyncio
2
- import subprocess
3
-
4
- from .errors import FoxopsError
5
- from .logger import get_logger
6
-
7
- logger = get_logger("utils")
8
-
9
-
10
- class CalledProcessError(subprocess.CalledProcessError, FoxopsError):
11
- """Error raised when copier fails."""
12
-
13
- def __str__(self):
14
- """Extend so that the string prints stdout and stderr by default."""
15
- return f"{super().__str__()} with stdout '{self.stdout}' and stderr '{self.stderr}'"
16
-
17
-
18
- async def check_call(
19
- program: str,
20
- *args,
21
- expected_returncodes: frozenset = frozenset({0}),
22
- timeout: int | float | None = None,
23
- **kwargs,
24
- ) -> asyncio.subprocess.Process:
25
- """Execute the given executable and raise error on non-zero exit code.
26
-
27
- This function is simply wrapping `asyncio.create_subprocess_exec()`
28
- and raises and exception in case the exit code is non-zero,
29
- similar to what `subprocess.check_call()` does.
30
-
31
- The timeout parameter can be used to specify a maximum wait time in seconds. If the timeout expires before the
32
- called process completes, the subprocess will be killed.
33
- -> Setting the timeout to None (default) will allow the child process to take forever.
34
- """
35
- proc = await asyncio.create_subprocess_exec(
36
- program,
37
- *args,
38
- stdout=asyncio.subprocess.PIPE,
39
- stderr=asyncio.subprocess.PIPE,
40
- **kwargs,
41
- )
42
-
43
- try:
44
- await asyncio.wait_for(proc.wait(), timeout=timeout)
45
- except asyncio.TimeoutError:
46
- proc.kill()
47
- stdout_buffer = None if proc.stdout is None else bytes(proc.stdout._buffer) # type: ignore
48
- stderr_buffer = None if proc.stderr is None else bytes(proc.stderr._buffer) # type: ignore
49
-
50
- logger.error(
51
- "killed process as it exceeded the timeout",
52
- stdout_buffer=stdout_buffer,
53
- stderr_buffer=stderr_buffer,
54
- )
55
- raise
56
-
57
- if proc.returncode is not None and proc.returncode not in expected_returncodes:
58
- raise CalledProcessError(
59
- proc.returncode,
60
- [program] + list(args),
61
- await proc.stdout.read() if proc.stdout else None,
62
- await proc.stderr.read() if proc.stderr else None,
63
- )
64
-
65
- return proc
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes