accli 2.1.4__tar.gz → 2.1.6__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 (37) hide show
  1. {accli-2.1.4 → accli-2.1.6}/PKG-INFO +11 -1
  2. {accli-2.1.4 → accli-2.1.6}/README.md +10 -0
  3. {accli-2.1.4 → accli-2.1.6}/accli/AcceleratorTaskDispatcher.py +76 -0
  4. {accli-2.1.4 → accli-2.1.6}/accli/AcceleratorTerminalCliProjectService.py +12 -0
  5. {accli-2.1.4 → accli-2.1.6}/accli/_version.py +1 -1
  6. {accli-2.1.4 → accli-2.1.6}/accli/cli.py +103 -7
  7. {accli-2.1.4 → accli-2.1.6}/accli/mount_downloader.py +1 -1
  8. {accli-2.1.4 → accli-2.1.6}/accli/nfs_watcher.py +21 -2
  9. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/PKG-INFO +11 -1
  10. {accli-2.1.4 → accli-2.1.6}/tests/test_jobs_commands.py +53 -2
  11. {accli-2.1.4 → accli-2.1.6}/LICENSE +0 -0
  12. {accli-2.1.4 → accli-2.1.6}/accli/AcceleratorJobProjectService.py +0 -0
  13. {accli-2.1.4 → accli-2.1.6}/accli/CsvRegionalTimeseriesValidator.py +0 -0
  14. {accli-2.1.4 → accli-2.1.6}/accli/__init__.py +0 -0
  15. {accli-2.1.4 → accli-2.1.6}/accli/__main__.py +0 -0
  16. {accli-2.1.4 → accli-2.1.6}/accli/acc_logo.ico +0 -0
  17. {accli-2.1.4 → accli-2.1.6}/accli/acc_logo.png +0 -0
  18. {accli-2.1.4 → accli-2.1.6}/accli/cleanup-nfs.ps1 +0 -0
  19. {accli-2.1.4 → accli-2.1.6}/accli/common.py +0 -0
  20. {accli-2.1.4 → accli-2.1.6}/accli/gui.py +0 -0
  21. {accli-2.1.4 → accli-2.1.6}/accli/job_views.py +0 -0
  22. {accli-2.1.4 → accli-2.1.6}/accli/log_timeline.py +0 -0
  23. {accli-2.1.4 → accli-2.1.6}/accli/refresh_explorer.ps1 +0 -0
  24. {accli-2.1.4 → accli-2.1.6}/accli/setup-nfs.ps1 +0 -0
  25. {accli-2.1.4 → accli-2.1.6}/accli/token.py +0 -0
  26. {accli-2.1.4 → accli-2.1.6}/accli/version_checker.py +0 -0
  27. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/SOURCES.txt +0 -0
  28. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/dependency_links.txt +0 -0
  29. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/entry_points.txt +0 -0
  30. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/requires.txt +0 -0
  31. {accli-2.1.4 → accli-2.1.6}/accli.egg-info/top_level.txt +0 -0
  32. {accli-2.1.4 → accli-2.1.6}/pyproject.toml +0 -0
  33. {accli-2.1.4 → accli-2.1.6}/setup.cfg +0 -0
  34. {accli-2.1.4 → accli-2.1.6}/tests/test_log_timeline.py +0 -0
  35. {accli-2.1.4 → accli-2.1.6}/tests/test_logs_command.py +0 -0
  36. {accli-2.1.4 → accli-2.1.6}/tests/test_mount_lifecycle.py +0 -0
  37. {accli-2.1.4 → accli-2.1.6}/tests/test_update_check.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: accli
3
- Version: 2.1.4
3
+ Version: 2.1.6
4
4
  Summary: IIASA Accelerator Client
5
5
  Author-email: Wrufesh S <wrufesh@gmail.com>
6
6
  License: The MIT License (MIT)
@@ -150,6 +150,16 @@ Show a job's status and details. For a job holding children or callbacks, Graph
150
150
  ```bash
151
151
  accli job my-project 1234
152
152
  accli job my-project 1234 --json
153
+ accli job show my-project 1234
154
+ ```
155
+
156
+ `accli job <project> <job>` is the same as `accli job show <project> <job>`.
157
+
158
+ Restart a job that is done or failed. The job can be a root job or a child job. The command fails if that job, a parent, or a descendant is still processing. `--rebuild` builds the container image again before the job starts.
159
+
160
+ ```bash
161
+ accli job restart my-project 1234
162
+ accli job restart my-project 1234 --rebuild
153
163
  ```
154
164
 
155
165
  ---
@@ -106,6 +106,16 @@ Show a job's status and details. For a job holding children or callbacks, Graph
106
106
  ```bash
107
107
  accli job my-project 1234
108
108
  accli job my-project 1234 --json
109
+ accli job show my-project 1234
110
+ ```
111
+
112
+ `accli job <project> <job>` is the same as `accli job show <project> <job>`.
113
+
114
+ Restart a job that is done or failed. The job can be a root job or a child job. The command fails if that job, a parent, or a descendant is still processing. `--rebuild` builds the container image again before the job starts.
115
+
116
+ ```bash
117
+ accli job restart my-project 1234
118
+ accli job restart my-project 1234 --rebuild
109
119
  ```
110
120
 
111
121
  ---
@@ -118,6 +118,76 @@ def _upload_cas_file_worker(args):
118
118
  return {"path": rel_path, "hash": file_hash, "mode": mode}
119
119
 
120
120
 
121
+ MAX_JOB_FOLDER_BYTES = 1024 * 1024 * 1024 # 1 GB
122
+
123
+ # Shown when the job folder is too big. These files set up the job's environment and
124
+ # must stay in the job folder. The list is illustrative, not exhaustive.
125
+ DEPENDENCY_FILE_EXAMPLES = (
126
+ " Containers: Dockerfile, *.dockerfile, Containerfile, .dockerignore, docker-compose.yml, "
127
+ "Singularity / *.def, apptainer.def\n"
128
+ " Python: requirements*.txt, constraints.txt, pyproject.toml, setup.py, setup.cfg, Pipfile, "
129
+ "Pipfile.lock, poetry.lock, uv.lock, pdm.lock, environment.yml, conda-lock.yml, .python-version, runtime.txt\n"
130
+ " R: init.R, install.R, install_packages.R, DESCRIPTION, NAMESPACE, renv.lock, renv/activate.R, "
131
+ ".Rprofile, packrat/packrat.lock\n"
132
+ " Julia: Project.toml, Manifest.toml\n"
133
+ " Node/JS: package.json, package-lock.json, yarn.lock, pnpm-lock.yaml, .npmrc, .nvmrc\n"
134
+ " Go: go.mod, go.sum\n"
135
+ " Rust: Cargo.toml, Cargo.lock, rust-toolchain.toml\n"
136
+ " Java/JVM: pom.xml, build.gradle, build.gradle.kts, settings.gradle, gradle.properties, "
137
+ "gradle/wrapper/*, build.sbt\n"
138
+ " C/C++: CMakeLists.txt, *.cmake, Makefile, configure, meson.build, conanfile.txt, conanfile.py, vcpkg.json\n"
139
+ " Fortran: fpm.toml, Makefile\n"
140
+ " Ruby/PHP: Gemfile, Gemfile.lock, composer.json, composer.lock\n"
141
+ " .NET: *.csproj, *.sln, packages.config, global.json\n"
142
+ " MATLAB: *.prj, startup.m, buildfile.m\n"
143
+ " GAMS/Optim: solver option files (*.opt), licence/config files the model reads at startup\n"
144
+ " System: apt.txt, packages.txt, install.sh, setup.sh, entrypoint.sh, startscript.sh, Makefile, "
145
+ "Taskfile.yml, justfile, .env.example, *.conf / config files read during setup\n"
146
+ " Also any local package your dependency file points to, e.g. '-e ./mypkg' in requirements.txt "
147
+ "or a vendored wheel/tarball.\n"
148
+ )
149
+
150
+
151
+ def _format_bytes(num_bytes):
152
+ for unit in ("B", "KB", "MB", "GB"):
153
+ if num_bytes < 1024 or unit == "GB":
154
+ return f"{num_bytes:.1f} {unit}" if unit != "B" else f"{num_bytes} B"
155
+ num_bytes /= 1024
156
+
157
+
158
+ def check_job_folder_size(repo_dir, directory, project_slug):
159
+ """Stop the dispatch if the filtered job folder is larger than MAX_JOB_FOLDER_BYTES."""
160
+ total = 0
161
+ for root, _, files in os.walk(repo_dir):
162
+ for file in files:
163
+ total += os.path.getsize(os.path.join(root, file))
164
+
165
+ if total <= MAX_JOB_FOLDER_BYTES:
166
+ return
167
+
168
+ raise ValueError(
169
+ f"The job folder '{directory}' is {_format_bytes(total)} after applying include/exclude, "
170
+ f"which is more than the {_format_bytes(MAX_JOB_FOLDER_BYTES)} limit for job folder uploads.\n\n"
171
+ f"Upload the full job folder to the project space and run the job from there:\n"
172
+ f" 1. Upload the whole folder: accli copy {directory} acc://{project_slug}/<path>\n"
173
+ f" accli copy has no include/exclude and uploads everything in the folder, so first remove "
174
+ f"or move out anything the job does not need, such as .git/, .venv/, venv/, node_modules/, "
175
+ f"__pycache__/ and local outputs.\n"
176
+ f" 2. Keep only the dependency and build files in the job folder upload:\n"
177
+ f" exclude='*', include='Dockerfile, requirements.txt, init.R, ...'\n"
178
+ f" 3. Run the code from the project space, e.g.\n"
179
+ f" command=\"cd /mnt/wdrv/<path> && <your current command>\"\n"
180
+ f" <path> is any location in the project space you choose; acc://{project_slug}/<path> is "
181
+ f"available in the job at /mnt/wdrv/<path>.\n"
182
+ f"Why the dependency files stay in the job folder: the container image is built from the job "
183
+ f"folder before the job starts, so /mnt/wdrv is not available at build time. Include patterns "
184
+ f"override exclude patterns, which is why exclude='*' plus include works.\n"
185
+ f"Dependency and build files to keep (examples, not a complete list; keep any file your "
186
+ f"language, package manager or build tool reads to set up the environment):\n"
187
+ f"{DEPENDENCY_FILE_EXAMPLES}"
188
+ )
189
+
190
+
121
191
  @lru_cache(maxsize=None)
122
192
  def push_folder_job(directory, include=None, exclude=None):
123
193
  server_url = get_server_url()
@@ -136,6 +206,12 @@ def push_folder_job(directory, include=None, exclude=None):
136
206
  if os.path.isfile(f'{repo_dir}/wkube.py'):
137
207
  os.remove(f'{repo_dir}/wkube.py')
138
208
 
209
+ try:
210
+ check_job_folder_size(repo_dir, directory, project_slug)
211
+ except ValueError:
212
+ shutil.rmtree(repo_dir, ignore_errors=True)
213
+ raise
214
+
139
215
  manifest = {"type": "cas_manifest", "files": []}
140
216
 
141
217
  upload_args = []
@@ -169,6 +169,18 @@ class AcceleratorTerminalCliProjectService:
169
169
  )
170
170
  return todict(res.data)
171
171
 
172
+ def restart_job(self, project_slug, job_id, rebuild_container_image=False):
173
+ query = urlencode({"rebuild_container_image": "true"}) if rebuild_container_image else ""
174
+ url = f"{self.cli_base_url}/{project_slug}/jobs/restart/{job_id}/"
175
+ if query:
176
+ url = f"{url}?{query}"
177
+ res = self.http_client_request(
178
+ "GET",
179
+ url,
180
+ headers=self.common_request_headers
181
+ )
182
+ return todict(res.data)
183
+
172
184
  def get_job_logs(self, project_slug, job_id, sources=None, attempt=None, before=None, after=None, limit=None):
173
185
  params = dict(sources=sources, attempt=attempt, before=before, after=after, limit=limit)
174
186
  query = urlencode({k: v for k, v in params.items() if v is not None})
@@ -1,3 +1,3 @@
1
1
  # Please strictly put double quote to use this info for git tag
2
2
  # Read a developer guide for git tag command with regex
3
- VERSION = "v2.1.4"
3
+ VERSION = "v2.1.6"
@@ -319,7 +319,8 @@ def jobs(
319
319
 
320
320
  TYPE is standalone, children, callback or children+callback. GRAPH is the status
321
321
  of everything below the root job, and what --status filters on. See a job's
322
- status and everything it holds with `accli job <project> <job>`.
322
+ status and everything it holds with `accli job <project> <job>`. Restart a job
323
+ with `accli job restart <project> <job>`.
323
324
  """
324
325
  service = _cli_service_for(project_slug)
325
326
  status_filter = ",".join(t.strip() for s in (status or []) for t in s.split(",") if t.strip()) or None
@@ -344,8 +345,28 @@ def jobs(
344
345
  print(f"[dim]Showing {len(results)} of {count} jobs. Use -n to see more.[/dim]")
345
346
 
346
347
 
347
- @app.command()
348
- def job(
348
+ class JobDefaultGroup(typer.core.TyperGroup):
349
+ """Keep `accli job <project> <job>` as the show command."""
350
+
351
+ def parse_args(self, ctx, args):
352
+ if not args or (args[0] not in self.commands and not args[0].startswith("-")):
353
+ args = ["show", *args]
354
+ return super().parse_args(ctx, args)
355
+
356
+
357
+ job_app = typer.Typer(
358
+ cls=JobDefaultGroup,
359
+ help="Show or restart a job. `accli job <project> <job>` shows the job.",
360
+ no_args_is_help=False,
361
+ add_completion=False,
362
+ pretty_exceptions_show_locals=False,
363
+ context_settings={"help_option_names": ["-h", "--help"]},
364
+ )
365
+ app.add_typer(job_app, name="job")
366
+
367
+
368
+ @job_app.command("show")
369
+ def job_show(
349
370
  project_slug: Annotated[str, typer.Argument(help="Unique Accelerator project slug.")],
350
371
  job_id: Annotated[int, typer.Argument(help="Job ID: a single job, or one holding children and callbacks.")],
351
372
  as_json: Annotated[bool, typer.Option(..., '--json', help="Print the raw JSON.")] = False,
@@ -353,7 +374,8 @@ def job(
353
374
  """Show a job's status and details. For a job holding children or callbacks, Graph status
354
375
  covers the jobs below it, the same as GRAPH in `accli jobs`, and each one is listed.
355
376
 
356
- See a job's output with `accli logs <project> <job>`.
377
+ See a job's output with `accli logs <project> <job>`. Restart it with
378
+ `accli job restart <project> <job>`.
357
379
  """
358
380
  service = _cli_service_for(project_slug)
359
381
  try:
@@ -375,6 +397,27 @@ def job(
375
397
  print(job_views.jobs_table(job_graph, job_id))
376
398
 
377
399
 
400
+ @job_app.command("restart")
401
+ def job_restart(
402
+ project_slug: Annotated[str, typer.Argument(help="Unique Accelerator project slug.")],
403
+ job_id: Annotated[int, typer.Argument(help="Job ID. A root job or a child job.")],
404
+ rebuild: Annotated[
405
+ bool, typer.Option("--rebuild", help="Build the container image again before the job starts.")] = False,
406
+ ):
407
+ """Restart a job that is done or failed.
408
+
409
+ The job can be a root job or a child job. The command fails if that job, a parent,
410
+ or a descendant is still processing.
411
+ """
412
+ service = _cli_service_for(project_slug)
413
+ try:
414
+ service.restart_job(project_slug, job_id, rebuild_container_image=rebuild)
415
+ except AccAPIError as err:
416
+ print(f"[bold red]ERROR: {_api_error_detail(err)}[/bold red]")
417
+ raise typer.Exit(1)
418
+ print(f"Restarted job #ID: {job_id}")
419
+
420
+
378
421
  def compute_sha256(filepath: str) -> str:
379
422
  """Helper to compute the SHA-256 hash of a file locally."""
380
423
  h = hashlib.sha256()
@@ -1064,7 +1107,56 @@ def ensure_nfs_daemon_stable(timeout: float) -> bool:
1064
1107
  return wait_for_nfs_portmapper("127.0.0.1", 111, timeout)
1065
1108
 
1066
1109
 
1067
- def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool, str]:
1110
+ def configure_windows_nfs_drive_cache(drive_str: str):
1111
+ """
1112
+ Configure per-drive Windows Client for NFS registry settings in HKCU before mounting.
1113
+ Disables NfsRdr per-drive lookup/readdir/attribute caching so renamed or recreated
1114
+ directories do not serve stale NFS filehandles from the Windows kernel redirector cache.
1115
+ """
1116
+ letter = drive_str.strip().rstrip(":\\/").upper()
1117
+ if len(letter) != 1 or not letter.isalpha():
1118
+ return
1119
+ try:
1120
+ import winreg
1121
+ base_key_path = f"Software\\Microsoft\\ClientForNFS\\CurrentVersion\\Persistent\\{letter}"
1122
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, base_key_path, 0, winreg.KEY_SET_VALUE) as k:
1123
+ winreg.SetValueEx(k, "NFSLookup", 0, winreg.REG_DWORD, 0)
1124
+ winreg.SetValueEx(k, "NFSReaddir", 0, winreg.REG_DWORD, 0)
1125
+ cache_key_path = f"{base_key_path}\\Cache"
1126
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, cache_key_path, 0, winreg.KEY_SET_VALUE) as ck:
1127
+ winreg.SetValueEx(ck, "FileAttributeCache", 0, winreg.REG_DWORD, 0)
1128
+ winreg.SetValueEx(ck, "AttributeTimeDelta", 0, winreg.REG_DWORD, 1)
1129
+ winreg.SetValueEx(ck, "RemoteWriteCache", 0, winreg.REG_DWORD, 0)
1130
+ except Exception:
1131
+ pass
1132
+
1133
+
1134
+ def configure_windows_explorer_drive_label(drive_root: str, label: str = ""):
1135
+ r"""
1136
+ Set the Windows Explorer MountPoints2 label for \\127.0.0.1\! and broadcast shell notifications
1137
+ so Explorer displays the project/share name instead of a generic 'Network Drive (W:)'.
1138
+ """
1139
+ display_label = f"Accelerator ({label})" if label else "Accelerator"
1140
+ try:
1141
+ import winreg
1142
+ for subkey in ("##127.0.0.1#!", "##127.0.0.1#!#"):
1143
+ key_path = f"Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\MountPoints2\\{subkey}"
1144
+ with winreg.CreateKeyEx(winreg.HKEY_CURRENT_USER, key_path, 0, winreg.KEY_SET_VALUE) as k:
1145
+ winreg.SetValueEx(k, "_LabelFromReg", 0, winreg.REG_SZ, display_label)
1146
+ except Exception:
1147
+ pass
1148
+ try:
1149
+ import ctypes
1150
+ # SHCNE_DRIVEADD (0x00000100), SHCNE_RENAMEFOLDER (0x00020000), SHCNE_UPDATEITEM (0x00002000)
1151
+ # SHCNF_PATHW | SHCNF_FLUSH (0x1005)
1152
+ ctypes.windll.shell32.SHChangeNotify(0x00000100, 0x1005, drive_root, None)
1153
+ ctypes.windll.shell32.SHChangeNotify(0x00020000, 0x1005, drive_root, None)
1154
+ ctypes.windll.shell32.SHChangeNotify(0x00002000, 0x1005, drive_root, None)
1155
+ except Exception:
1156
+ pass
1157
+
1158
+
1159
+ def map_windows_network_drive(mount_point_abs, max_attempts: int, label: str = "") -> tuple[bool, str]:
1068
1160
  """
1069
1161
  Attempt to map the NFS share to the requested drive letter using mount.exe.
1070
1162
  Retries with cleanup if Windows NFS client returns a transient error.
@@ -1074,6 +1166,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1074
1166
  target_str = str(mount_point_abs).rstrip("\\/")
1075
1167
  if re.match(r"^[a-zA-Z]$", target_str):
1076
1168
  target_str += ":"
1169
+ configure_windows_nfs_drive_cache(target_str)
1077
1170
 
1078
1171
  mount_cmd = [
1079
1172
  "C:\\Windows\\System32\\mount.exe",
@@ -1090,6 +1183,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1090
1183
 
1091
1184
  last_err = ""
1092
1185
  drive_root = str(mount_point_abs).rstrip("\\/") + "\\"
1186
+ configure_windows_explorer_drive_label(drive_root, label)
1093
1187
  for attempt in range(1, max_attempts + 1):
1094
1188
  cleanup_stuck_windows_mount_processes()
1095
1189
 
@@ -1117,6 +1211,7 @@ def map_windows_network_drive(mount_point_abs, max_attempts: int) -> tuple[bool,
1117
1211
  entries = os.listdir(drive_root)
1118
1212
  if len(entries) > 0:
1119
1213
  drive_ready = True
1214
+ configure_windows_explorer_drive_label(drive_root, label)
1120
1215
  return True, (res.stdout or "").strip()
1121
1216
  except OSError:
1122
1217
  pass
@@ -1597,7 +1692,7 @@ def mount_start(
1597
1692
  raise typer.Exit(1)
1598
1693
 
1599
1694
  # Map the network drive in the CURRENT user session (so it is visible in Explorer)
1600
- success, err_msg = map_windows_network_drive(mount_point_abs, 5)
1695
+ success, err_msg = map_windows_network_drive(mount_point_abs, 5, label=project_slug)
1601
1696
  if success:
1602
1697
  start_nfs_watcher(str(mount_point_abs), interval=30)
1603
1698
  print(f"[bold green][OK] NFS mount successfully mapped at [white]{mount_point_abs}[/white]![/bold green]")
@@ -1651,6 +1746,7 @@ def mount_start(
1651
1746
  print(f"[yellow]Please check the log file at {log_file_path} for more details.[/yellow]")
1652
1747
  raise typer.Exit(1)
1653
1748
 
1749
+ configure_windows_explorer_drive_label(str(mount_point_abs).rstrip("\\/") + "\\", label=project_slug)
1654
1750
  start_nfs_watcher(str(mount_point_abs), interval=30)
1655
1751
  print(f"[bold green][OK] NFS mount process spawned successfully (PID: {process.pid}).[/bold green]")
1656
1752
  print(f"[cyan]Use 'umount' or 'accli mount stop' to unmount the drive.[/cyan]")
@@ -1692,7 +1788,7 @@ def mount_start(
1692
1788
  raise typer.Exit(1)
1693
1789
 
1694
1790
  # Map the network drive in the CURRENT user session (so it is visible in Explorer)
1695
- success, err_msg = map_windows_network_drive(mount_point_abs, 5)
1791
+ success, err_msg = map_windows_network_drive(mount_point_abs, 5, label=project_slug)
1696
1792
  if success:
1697
1793
  start_nfs_watcher(str(mount_point_abs), interval=30)
1698
1794
  print(f"[bold green][OK] NFS mount successfully mapped at [white]{mount_point_abs}[/white]![/bold green]")
@@ -9,7 +9,7 @@ import typer
9
9
  from rich import print
10
10
  from rich.progress import Progress, TextColumn, BarColumn, TaskProgressColumn, TimeElapsedColumn
11
11
 
12
- DEFAULT_VERSION = "v0.6.5-acc-pr140-p6"
12
+ DEFAULT_VERSION = "v0.6.5-acc-pr140-p16"
13
13
  BINARY_DIR = Path.home() / ".accli" / "bin"
14
14
 
15
15
  # Regex to safely validate version strings to prevent URL manipulation or directory traversal
@@ -7,6 +7,8 @@ from pathlib import Path
7
7
  from datetime import datetime
8
8
 
9
9
  # Windows Shell Notification constants
10
+ SHCNE_MKDIR = 0x00000008
11
+ SHCNE_RMDIR = 0x00000010
10
12
  SHCNE_UPDATEDIR = 0x00001000
11
13
  SHCNF_PATHW = 0x0005
12
14
 
@@ -62,10 +64,18 @@ def get_open_explorer_paths(script_path: Path, mount_point: str) -> list[str]:
62
64
  return []
63
65
 
64
66
 
65
- def notify_explorer(script_path: Path, mount_point: str, path_str: str):
67
+ def notify_explorer(script_path: Path, mount_point: str, path_str: str, removed_dirs: list[str] | None = None, added_dirs: list[str] | None = None):
66
68
  """Notifies Windows Shell and refreshes Explorer windows for path_str."""
67
69
  log(f"Broadcasting SHChangeNotify on '{path_str}'...")
68
70
  try:
71
+ if removed_dirs:
72
+ for dname in removed_dirs:
73
+ child_dir = str(Path(path_str) / dname)
74
+ ctypes.windll.shell32.SHChangeNotify(SHCNE_RMDIR, SHCNF_PATHW, child_dir, None)
75
+ if added_dirs:
76
+ for dname in added_dirs:
77
+ child_dir = str(Path(path_str) / dname)
78
+ ctypes.windll.shell32.SHChangeNotify(SHCNE_MKDIR, SHCNF_PATHW, child_dir, None)
69
79
  ctypes.windll.shell32.SHChangeNotify(
70
80
  SHCNE_UPDATEDIR,
71
81
  SHCNF_PATHW,
@@ -191,14 +201,23 @@ def run_watcher(mount_point: str, interval: float):
191
201
  dpath = Path(dir_str)
192
202
  current_state = scan_directory_state(dpath)
193
203
  if current_state is None:
204
+ if dir_str in cached_states:
205
+ del cached_states[dir_str]
206
+ parent_str = str(dpath.parent)
207
+ log(f"Directory '{dir_str}' disappeared -> notifying shell and refreshing '{parent_str}'")
208
+ notify_explorer(script_path, mount_point, parent_str, removed_dirs=[dpath.name])
194
209
  continue
195
210
 
196
211
  last_state = cached_states.get(dir_str)
197
212
  if last_state is not None:
198
213
  if current_state != last_state:
214
+ old_keys = set(last_state.keys())
215
+ new_keys = set(current_state.keys())
216
+ removed_dirs = [k for k in (old_keys - new_keys) if last_state[k][0]]
217
+ added_dirs = [k for k in (new_keys - old_keys) if current_state[k][0]]
199
218
  diff_summary = describe_changes(last_state, current_state)
200
219
  log(f"Change detected in '{dir_str}' -> {diff_summary}")
201
- notify_explorer(script_path, mount_point, dir_str)
220
+ notify_explorer(script_path, mount_point, dir_str, removed_dirs=removed_dirs, added_dirs=added_dirs)
202
221
  cached_states[dir_str] = current_state
203
222
  else:
204
223
  cached_states[dir_str] = current_state
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: accli
3
- Version: 2.1.4
3
+ Version: 2.1.6
4
4
  Summary: IIASA Accelerator Client
5
5
  Author-email: Wrufesh S <wrufesh@gmail.com>
6
6
  License: The MIT License (MIT)
@@ -150,6 +150,16 @@ Show a job's status and details. For a job holding children or callbacks, Graph
150
150
  ```bash
151
151
  accli job my-project 1234
152
152
  accli job my-project 1234 --json
153
+ accli job show my-project 1234
154
+ ```
155
+
156
+ `accli job <project> <job>` is the same as `accli job show <project> <job>`.
157
+
158
+ Restart a job that is done or failed. The job can be a root job or a child job. The command fails if that job, a parent, or a descendant is still processing. `--rebuild` builds the container image again before the job starts.
159
+
160
+ ```bash
161
+ accli job restart my-project 1234
162
+ accli job restart my-project 1234 --rebuild
153
163
  ```
154
164
 
155
165
  ---
@@ -32,6 +32,14 @@ class FakeService:
32
32
  self.calls.append(dict(job_id=job_id))
33
33
  return self.graph
34
34
 
35
+ def restart_job(self, project_slug, job_id, rebuild_container_image=False):
36
+ self.calls.append(dict(
37
+ project_slug=project_slug, job_id=job_id, rebuild_container_image=rebuild_container_image
38
+ ))
39
+ if self.error:
40
+ raise self.error
41
+ return True
42
+
35
43
 
36
44
  def run(monkeypatch, service, command, *args, exit_code=0):
37
45
  monkeypatch.setattr(cli, "exchange_refresh_token", lambda slug: ("", "token", 0))
@@ -145,6 +153,49 @@ def test_graph_status_leaves_out_the_job_itself(monkeypatch):
145
153
  assert "Graph status DONE 1 jobs below: 1 DONE" in output
146
154
 
147
155
 
156
+ def test_job_restart_sends_project_and_job_id(monkeypatch):
157
+ service = FakeService()
158
+ monkeypatch.setattr(cli, "exchange_refresh_token", lambda slug: ("", "token", 0))
159
+ monkeypatch.setattr(cli, "validate_project_slug", lambda server_url, slug: None)
160
+ monkeypatch.setattr(cli, "get_server_url", lambda: "https://acc.example")
161
+ monkeypatch.setattr(cli, "AcceleratorTerminalCliProjectService", lambda **kw: service)
162
+
163
+ result = CliRunner().invoke(cli.app, ["job", "restart", "demo", "15"])
164
+
165
+ assert result.exit_code == 0, result.output
166
+ assert service.calls == [dict(project_slug="demo", job_id=15, rebuild_container_image=False)]
167
+ assert "Restarted job #ID: 15" in result.output
168
+
169
+
170
+ def test_job_restart_can_rebuild_the_image(monkeypatch):
171
+ service = FakeService()
172
+ monkeypatch.setattr(cli, "exchange_refresh_token", lambda slug: ("", "token", 0))
173
+ monkeypatch.setattr(cli, "validate_project_slug", lambda server_url, slug: None)
174
+ monkeypatch.setattr(cli, "get_server_url", lambda: "https://acc.example")
175
+ monkeypatch.setattr(cli, "AcceleratorTerminalCliProjectService", lambda **kw: service)
176
+
177
+ result = CliRunner().invoke(cli.app, ["job", "restart", "demo", "15", "--rebuild"])
178
+
179
+ assert result.exit_code == 0, result.output
180
+ assert service.calls == [dict(project_slug="demo", job_id=15, rebuild_container_image=True)]
181
+
182
+
183
+ def test_job_restart_shows_api_error(monkeypatch):
184
+ class Res:
185
+ data = b'{"detail": "Jobs which parents or descendants jobs are still in processing state cannot be restarted."}'
186
+
187
+ service = FakeService(error=AccAPIError("bad", Res(), 400))
188
+ monkeypatch.setattr(cli, "exchange_refresh_token", lambda slug: ("", "token", 0))
189
+ monkeypatch.setattr(cli, "validate_project_slug", lambda server_url, slug: None)
190
+ monkeypatch.setattr(cli, "get_server_url", lambda: "https://acc.example")
191
+ monkeypatch.setattr(cli, "AcceleratorTerminalCliProjectService", lambda **kw: service)
192
+
193
+ result = CliRunner().invoke(cli.app, ["job", "restart", "demo", "15"])
194
+
195
+ assert result.exit_code == 1
196
+ assert "still in processing state cannot be restarted" in result.output
197
+
198
+
148
199
  def test_commands_validate_the_project_first(monkeypatch):
149
200
  checked = []
150
201
 
@@ -155,6 +206,6 @@ def test_commands_validate_the_project_first(monkeypatch):
155
206
  monkeypatch.setattr(cli, "get_server_url", lambda: "https://acc.example")
156
207
  monkeypatch.setattr(cli, "validate_project_slug", validate)
157
208
  monkeypatch.setattr(cli, "AcceleratorTerminalCliProjectService", lambda **kw: pytest.fail("API called"))
158
- for args in (["jobs", "nope"], ["job", "nope", "1"], ["logs", "nope", "1"]):
209
+ for args in (["jobs", "nope"], ["job", "nope", "1"], ["job", "restart", "nope", "1"], ["logs", "nope", "1"]):
159
210
  assert CliRunner().invoke(cli.app, args).exit_code == 1
160
- assert checked == [("https://acc.example", "nope")] * 3
211
+ assert checked == [("https://acc.example", "nope")] * 4
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
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
File without changes
File without changes
File without changes