fractal-server 2.8.1__py3-none-any.whl → 2.9.0a1__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 (54) hide show
  1. fractal_server/__init__.py +1 -1
  2. fractal_server/app/db/__init__.py +2 -35
  3. fractal_server/app/models/v2/__init__.py +3 -3
  4. fractal_server/app/models/v2/task.py +0 -72
  5. fractal_server/app/models/v2/task_group.py +102 -0
  6. fractal_server/app/routes/admin/v1.py +1 -20
  7. fractal_server/app/routes/admin/v2/job.py +1 -20
  8. fractal_server/app/routes/admin/v2/task_group.py +53 -13
  9. fractal_server/app/routes/api/v2/__init__.py +11 -2
  10. fractal_server/app/routes/api/v2/{_aux_functions_task_collection.py → _aux_functions_task_lifecycle.py} +43 -0
  11. fractal_server/app/routes/api/v2/_aux_functions_tasks.py +27 -17
  12. fractal_server/app/routes/api/v2/task_collection.py +30 -55
  13. fractal_server/app/routes/api/v2/task_collection_custom.py +3 -3
  14. fractal_server/app/routes/api/v2/task_group.py +83 -14
  15. fractal_server/app/routes/api/v2/task_group_lifecycle.py +221 -0
  16. fractal_server/app/routes/api/v2/workflow.py +1 -1
  17. fractal_server/app/routes/api/v2/workflow_import.py +2 -2
  18. fractal_server/app/routes/aux/_timestamp.py +18 -0
  19. fractal_server/app/schemas/_validators.py +1 -2
  20. fractal_server/app/schemas/v2/__init__.py +3 -2
  21. fractal_server/app/schemas/v2/task_collection.py +0 -21
  22. fractal_server/app/schemas/v2/task_group.py +31 -8
  23. fractal_server/config.py +11 -56
  24. fractal_server/migrations/versions/3082479ac4ea_taskgroup_activity_and_venv_info_to_.py +105 -0
  25. fractal_server/ssh/_fabric.py +18 -0
  26. fractal_server/tasks/utils.py +2 -12
  27. fractal_server/tasks/v2/local/__init__.py +3 -0
  28. fractal_server/tasks/v2/local/collect.py +291 -0
  29. fractal_server/tasks/v2/local/deactivate.py +210 -0
  30. fractal_server/tasks/v2/local/reactivate.py +159 -0
  31. fractal_server/tasks/v2/local/utils_local.py +45 -0
  32. fractal_server/tasks/v2/ssh/__init__.py +0 -0
  33. fractal_server/tasks/v2/ssh/collect.py +386 -0
  34. fractal_server/tasks/v2/ssh/deactivate.py +2 -0
  35. fractal_server/tasks/v2/ssh/reactivate.py +2 -0
  36. fractal_server/tasks/v2/templates/{_2_preliminary_pip_operations.sh → 1_create_venv.sh} +6 -7
  37. fractal_server/tasks/v2/templates/{_3_pip_install.sh → 2_pip_install.sh} +8 -1
  38. fractal_server/tasks/v2/templates/{_4_pip_freeze.sh → 3_pip_freeze.sh} +0 -7
  39. fractal_server/tasks/v2/templates/{_5_pip_show.sh → 4_pip_show.sh} +5 -6
  40. fractal_server/tasks/v2/templates/5_get_venv_size_and_file_number.sh +10 -0
  41. fractal_server/tasks/v2/templates/6_pip_install_from_freeze.sh +35 -0
  42. fractal_server/tasks/v2/utils_background.py +42 -103
  43. fractal_server/tasks/v2/utils_templates.py +32 -2
  44. fractal_server/utils.py +4 -2
  45. {fractal_server-2.8.1.dist-info → fractal_server-2.9.0a1.dist-info}/METADATA +2 -3
  46. {fractal_server-2.8.1.dist-info → fractal_server-2.9.0a1.dist-info}/RECORD +50 -39
  47. fractal_server/app/models/v2/collection_state.py +0 -22
  48. fractal_server/tasks/v2/collection_local.py +0 -357
  49. fractal_server/tasks/v2/collection_ssh.py +0 -352
  50. fractal_server/tasks/v2/templates/_1_create_venv.sh +0 -42
  51. /fractal_server/tasks/v2/{database_operations.py → utils_database.py} +0 -0
  52. {fractal_server-2.8.1.dist-info → fractal_server-2.9.0a1.dist-info}/LICENSE +0 -0
  53. {fractal_server-2.8.1.dist-info → fractal_server-2.9.0a1.dist-info}/WHEEL +0 -0
  54. {fractal_server-2.8.1.dist-info → fractal_server-2.9.0a1.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,210 @@
1
+ import logging
2
+ import shutil
3
+ import time
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+
7
+ from ..utils_background import add_commit_refresh
8
+ from ..utils_background import fail_and_cleanup
9
+ from ..utils_templates import get_collection_replacements
10
+ from .utils_local import _customize_and_run_template
11
+ from fractal_server.app.db import get_sync_db
12
+ from fractal_server.app.models.v2 import TaskGroupActivityV2
13
+ from fractal_server.app.models.v2 import TaskGroupV2
14
+ from fractal_server.app.schemas.v2 import TaskGroupActivityActionV2
15
+ from fractal_server.app.schemas.v2 import TaskGroupV2OriginEnum
16
+ from fractal_server.app.schemas.v2.task_group import TaskGroupActivityStatusV2
17
+ from fractal_server.logger import set_logger
18
+ from fractal_server.tasks.utils import get_log_path
19
+ from fractal_server.tasks.v2.utils_background import get_current_log
20
+ from fractal_server.tasks.v2.utils_templates import SCRIPTS_SUBFOLDER
21
+ from fractal_server.utils import get_timestamp
22
+
23
+ LOGGER_NAME = __name__
24
+
25
+
26
+ def deactivate_local(
27
+ *,
28
+ task_group_activity_id: int,
29
+ task_group_id: int,
30
+ ) -> None:
31
+ """
32
+ Deactivate a task group venv.
33
+
34
+ This function is run as a background task, therefore exceptions must be
35
+ handled.
36
+
37
+ Arguments:
38
+ task_group_id:
39
+ task_group_activity_id:
40
+ """
41
+
42
+ with TemporaryDirectory() as tmpdir:
43
+ log_file_path = get_log_path(Path(tmpdir))
44
+ logger = set_logger(
45
+ logger_name=LOGGER_NAME,
46
+ log_file_path=log_file_path,
47
+ )
48
+
49
+ with next(get_sync_db()) as db:
50
+
51
+ # Get main objects from db
52
+ activity = db.get(TaskGroupActivityV2, task_group_activity_id)
53
+ task_group = db.get(TaskGroupV2, task_group_id)
54
+ if activity is None or task_group is None:
55
+ # Use `logging` directly
56
+ logging.error(
57
+ "Cannot find database rows with "
58
+ f"{task_group_id=} and {task_group_activity_id=}:\n"
59
+ f"{task_group=}\n{activity=}. Exit."
60
+ )
61
+ return
62
+
63
+ # Log some info
64
+ logger.debug("START")
65
+
66
+ for key, value in task_group.model_dump().items():
67
+ logger.debug(f"task_group.{key}: {value}")
68
+
69
+ # Check that the (local) task_group venv_path does exist
70
+ if not Path(task_group.venv_path).exists():
71
+ error_msg = f"{task_group.venv_path} does not exist."
72
+ logger.error(error_msg)
73
+ fail_and_cleanup(
74
+ task_group=task_group,
75
+ task_group_activity=activity,
76
+ logger_name=LOGGER_NAME,
77
+ log_file_path=log_file_path,
78
+ exception=FileNotFoundError(error_msg),
79
+ db=db,
80
+ )
81
+ return
82
+
83
+ try:
84
+
85
+ activity.status = TaskGroupActivityStatusV2.ONGOING
86
+ activity = add_commit_refresh(obj=activity, db=db)
87
+
88
+ if task_group.pip_freeze is None:
89
+ logger.warning(
90
+ "Recreate pip-freeze information, since "
91
+ f"{task_group.pip_freeze=}. NOTE: this should only "
92
+ "happen for task groups created before 2.9.0."
93
+ )
94
+ # Prepare replacements for templates
95
+ replacements = get_collection_replacements(
96
+ task_group=task_group,
97
+ python_bin="/not/applicable",
98
+ )
99
+
100
+ # Prepare common arguments for _customize_and_run_template
101
+ common_args = dict(
102
+ replacements=replacements,
103
+ script_dir=(
104
+ Path(task_group.path) / SCRIPTS_SUBFOLDER
105
+ ).as_posix(),
106
+ prefix=(
107
+ f"{int(time.time())}_"
108
+ f"{TaskGroupActivityActionV2.DEACTIVATE}_"
109
+ ),
110
+ logger_name=LOGGER_NAME,
111
+ )
112
+ pip_freeze_stdout = _customize_and_run_template(
113
+ template_filename="3_pip_freeze.sh",
114
+ **common_args,
115
+ )
116
+ # Update pip-freeze data
117
+ logger.info("Add pip freeze stdout to TaskGroupV2 - start")
118
+ activity.log = get_current_log(log_file_path)
119
+ activity = add_commit_refresh(obj=activity, db=db)
120
+ task_group.pip_freeze = pip_freeze_stdout
121
+ task_group = add_commit_refresh(obj=task_group, db=db)
122
+ logger.info("Add pip freeze stdout to TaskGroupV2 - end")
123
+
124
+ # Handle some specific cases for wheel-file case
125
+ if task_group.origin == TaskGroupV2OriginEnum.WHEELFILE:
126
+
127
+ logger.info(
128
+ f"Handle specific cases for {task_group.origin=}."
129
+ )
130
+
131
+ # Blocking situation: `wheel_path` is not set or points
132
+ # to a missing path
133
+ if (
134
+ task_group.wheel_path is None
135
+ or not Path(task_group.wheel_path).exists()
136
+ ):
137
+ error_msg = (
138
+ "Invalid wheel path for task group with "
139
+ f"{task_group_id=}. {task_group.wheel_path=} is "
140
+ "unset or does not exist."
141
+ )
142
+ logger.error(error_msg)
143
+ fail_and_cleanup(
144
+ task_group=task_group,
145
+ task_group_activity=activity,
146
+ logger_name=LOGGER_NAME,
147
+ log_file_path=log_file_path,
148
+ exception=FileNotFoundError(error_msg),
149
+ db=db,
150
+ )
151
+ return
152
+
153
+ # Recoverable situation: `wheel_path` was not yet copied
154
+ # over to the correct server-side folder
155
+ wheel_path_parent_dir = Path(task_group.wheel_path).parent
156
+ if wheel_path_parent_dir != Path(task_group.path):
157
+ logger.warning(
158
+ f"{wheel_path_parent_dir.as_posix()} differs from "
159
+ f"{task_group.path}. NOTE: this should only "
160
+ "happen for task groups created before 2.9.0."
161
+ )
162
+
163
+ if task_group.wheel_path not in task_group.pip_freeze:
164
+ raise ValueError(
165
+ f"Cannot find {task_group.wheel_path=} in "
166
+ "pip-freeze data. Exit."
167
+ )
168
+
169
+ logger.info(
170
+ f"Now copy wheel file into {task_group.path}."
171
+ )
172
+ new_wheel_path = (
173
+ Path(task_group.path)
174
+ / Path(task_group.wheel_path).name
175
+ ).as_posix()
176
+ shutil.copy(task_group.wheel_path, new_wheel_path)
177
+ logger.info(f"Copied wheel file to {new_wheel_path}.")
178
+
179
+ task_group.wheel_path = new_wheel_path
180
+ new_pip_freeze = task_group.pip_freeze.replace(
181
+ task_group.wheel_path,
182
+ new_wheel_path,
183
+ )
184
+ task_group.pip_freeze = new_pip_freeze
185
+ task_group = add_commit_refresh(obj=task_group, db=db)
186
+ logger.info(
187
+ "Updated `wheel_path` and `pip_freeze` "
188
+ "task-group attributes."
189
+ )
190
+
191
+ # We now have all required information for reactivating the
192
+ # virtual environment at a later point
193
+ logger.info(f"Now removing {task_group.venv_path}.")
194
+ shutil.rmtree(task_group.venv_path)
195
+ logger.info(f"All good, {task_group.venv_path} removed.")
196
+ activity.status = TaskGroupActivityStatusV2.OK
197
+ activity.log = get_current_log(log_file_path)
198
+ activity.timestamp_ended = get_timestamp()
199
+ activity = add_commit_refresh(obj=activity, db=db)
200
+
201
+ except Exception as e:
202
+ fail_and_cleanup(
203
+ task_group=task_group,
204
+ task_group_activity=activity,
205
+ logger_name=LOGGER_NAME,
206
+ log_file_path=log_file_path,
207
+ exception=e,
208
+ db=db,
209
+ )
210
+ return
@@ -0,0 +1,159 @@
1
+ import logging
2
+ import shutil
3
+ import time
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+
7
+ from ..utils_background import add_commit_refresh
8
+ from ..utils_background import fail_and_cleanup
9
+ from ..utils_templates import get_collection_replacements
10
+ from .utils_local import _customize_and_run_template
11
+ from fractal_server.app.db import get_sync_db
12
+ from fractal_server.app.models.v2 import TaskGroupActivityV2
13
+ from fractal_server.app.models.v2 import TaskGroupV2
14
+ from fractal_server.app.schemas.v2 import TaskGroupActivityActionV2
15
+ from fractal_server.app.schemas.v2.task_group import TaskGroupActivityStatusV2
16
+ from fractal_server.logger import set_logger
17
+ from fractal_server.tasks.utils import get_log_path
18
+ from fractal_server.tasks.v2.utils_background import get_current_log
19
+ from fractal_server.tasks.v2.utils_python_interpreter import (
20
+ get_python_interpreter_v2,
21
+ )
22
+ from fractal_server.tasks.v2.utils_templates import SCRIPTS_SUBFOLDER
23
+ from fractal_server.utils import get_timestamp
24
+
25
+
26
+ LOGGER_NAME = __name__
27
+
28
+
29
+ def reactivate_local(
30
+ *,
31
+ task_group_activity_id: int,
32
+ task_group_id: int,
33
+ ) -> None:
34
+ """
35
+ Reactivate a task group venv.
36
+
37
+ This function is run as a background task, therefore exceptions must be
38
+ handled.
39
+
40
+ Arguments:
41
+ task_group_id:
42
+ task_group_activity_id:
43
+ """
44
+
45
+ with TemporaryDirectory() as tmpdir:
46
+ log_file_path = get_log_path(Path(tmpdir))
47
+ logger = set_logger(
48
+ logger_name=LOGGER_NAME,
49
+ log_file_path=log_file_path,
50
+ )
51
+
52
+ with next(get_sync_db()) as db:
53
+
54
+ # Get main objects from db
55
+ activity = db.get(TaskGroupActivityV2, task_group_activity_id)
56
+ task_group = db.get(TaskGroupV2, task_group_id)
57
+ if activity is None or task_group is None:
58
+ # Use `logging` directly
59
+ logging.error(
60
+ "Cannot find database rows with "
61
+ f"{task_group_id=} and {task_group_activity_id=}:\n"
62
+ f"{task_group=}\n{activity=}. Exit."
63
+ )
64
+ return
65
+
66
+ # Log some info
67
+ logger.debug("START")
68
+
69
+ for key, value in task_group.model_dump().items():
70
+ logger.debug(f"task_group.{key}: {value}")
71
+
72
+ # Check that the (local) task_group venv_path does not exist
73
+ if Path(task_group.venv_path).exists():
74
+ error_msg = f"{task_group.venv_path} already exists."
75
+ logger.error(error_msg)
76
+ fail_and_cleanup(
77
+ task_group=task_group,
78
+ task_group_activity=activity,
79
+ logger_name=LOGGER_NAME,
80
+ log_file_path=log_file_path,
81
+ exception=FileExistsError(error_msg),
82
+ db=db,
83
+ )
84
+ return
85
+
86
+ try:
87
+ activity.status = TaskGroupActivityStatusV2.ONGOING
88
+ activity = add_commit_refresh(obj=activity, db=db)
89
+
90
+ # Prepare replacements for templates
91
+ replacements = get_collection_replacements(
92
+ task_group=task_group,
93
+ python_bin=get_python_interpreter_v2(
94
+ python_version=task_group.python_version
95
+ ),
96
+ )
97
+ with open(f"{tmpdir}/pip_freeze.txt", "w") as f:
98
+ f.write(task_group.pip_freeze)
99
+ replacements.append(
100
+ ("__PIP_FREEZE_FILE__", f"{tmpdir}/pip_freeze.txt")
101
+ )
102
+ # Prepare common arguments for `_customize_and_run_template``
103
+ common_args = dict(
104
+ replacements=replacements,
105
+ script_dir=(
106
+ Path(task_group.path) / SCRIPTS_SUBFOLDER
107
+ ).as_posix(),
108
+ prefix=(
109
+ f"{int(time.time())}_"
110
+ f"{TaskGroupActivityActionV2.REACTIVATE}_"
111
+ ),
112
+ logger_name=LOGGER_NAME,
113
+ )
114
+
115
+ logger.debug("start - create venv")
116
+ _customize_and_run_template(
117
+ template_filename="1_create_venv.sh",
118
+ **common_args,
119
+ )
120
+ logger.debug("end - create venv")
121
+ activity.log = get_current_log(log_file_path)
122
+ activity.timestamp_ended = get_timestamp()
123
+ activity = add_commit_refresh(obj=activity, db=db)
124
+
125
+ logger.debug("start - install from pip freeze")
126
+ _customize_and_run_template(
127
+ template_filename="6_pip_install_from_freeze.sh",
128
+ **common_args,
129
+ )
130
+ logger.debug("end - install from pip freeze")
131
+ activity.log = get_current_log(log_file_path)
132
+ activity.status = TaskGroupActivityStatusV2.OK
133
+ activity.timestamp_ended = get_timestamp()
134
+ activity = add_commit_refresh(obj=activity, db=db)
135
+ task_group.active = True
136
+ task_group = add_commit_refresh(obj=task_group, db=db)
137
+ logger.debug("END")
138
+
139
+ except Exception as reactivate_e:
140
+ # Delete corrupted venv_path
141
+ try:
142
+ logger.info(f"Now delete folder {task_group.venv_path}")
143
+ shutil.rmtree(task_group.venv_path)
144
+ logger.info(f"Deleted folder {task_group.venv_path}")
145
+ except Exception as rm_e:
146
+ logger.error(
147
+ "Removing folder failed.\n"
148
+ f"Original error:\n{str(rm_e)}"
149
+ )
150
+
151
+ fail_and_cleanup(
152
+ task_group=task_group,
153
+ task_group_activity=activity,
154
+ logger_name=LOGGER_NAME,
155
+ log_file_path=log_file_path,
156
+ exception=reactivate_e,
157
+ db=db,
158
+ )
159
+ return
@@ -0,0 +1,45 @@
1
+ from pathlib import Path
2
+
3
+ from fractal_server.logger import get_logger
4
+ from fractal_server.tasks.v2.utils_templates import customize_template
5
+ from fractal_server.utils import execute_command_sync
6
+
7
+
8
+ def _customize_and_run_template(
9
+ template_filename: str,
10
+ replacements: list[tuple[str, str]],
11
+ script_dir: str,
12
+ logger_name: str,
13
+ prefix: int,
14
+ ) -> str:
15
+ """
16
+ Customize one of the template bash scripts.
17
+
18
+ Args:
19
+ template_filename: Filename of the template file (ends with ".sh").
20
+ replacements: Dictionary of replacements.
21
+ script_dir: Local folder where the script will be placed.
22
+ prefix: Prefix for the script filename.
23
+ """
24
+ logger = get_logger(logger_name=logger_name)
25
+ logger.debug(f"_customize_and_run_template {template_filename} - START")
26
+
27
+ # Prepare name and path of script
28
+ if not template_filename.endswith(".sh"):
29
+ raise ValueError(
30
+ f"Invalid {template_filename=} (it must end with '.sh')."
31
+ )
32
+
33
+ script_filename = f"{prefix}{template_filename}"
34
+ script_path_local = Path(script_dir) / script_filename
35
+ # Read template
36
+ customize_template(
37
+ template_name=template_filename,
38
+ replacements=replacements,
39
+ script_path=script_path_local,
40
+ )
41
+ cmd = f"bash {script_path_local}"
42
+ logger.debug(f"Now run '{cmd}' ")
43
+ stdout = execute_command_sync(command=cmd, logger_name=logger_name)
44
+ logger.debug(f"_customize_and_run_template {template_filename} - END")
45
+ return stdout
File without changes