fleche 6.23.0

Remote job runner for Slurm clusters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
//! Job cleanup operations - cancel and clean.

use crate::error::{FlecheError, Result};
use crate::local;
use crate::output::OutputFormat;
use crate::registry::{JobRecord, JobStatus, LiveStatus, Registry, parse_duration};
use crate::runtime::RuntimeCtx;
use crate::slurm::cancel_job;
use console::style;
use std::collections::HashSet;
use std::io::Write;
use std::path::PathBuf;

use super::cancel_remote_direct_job;
use super::job_path_from_workspace;

/// Options for cleaning up jobs.
#[derive(Debug, Default)]
pub struct CleanJobsOptions {
    /// Clean all completed/failed jobs.
    pub all: bool,
    /// Filter by status (e.g., failed, completed, cancelled).
    pub status_filters: Vec<String>,
    /// Permanently delete instead of archiving.
    pub delete: bool,
    /// Also delete the shared workspace.
    pub clean_workspace: bool,
    /// Target archived jobs.
    pub include_archived: bool,
    /// Restore archived jobs.
    pub unarchive: bool,
    /// Show what would be done without actually doing it.
    pub dry_run: bool,
    /// Skip confirmation prompt.
    pub skip_confirm: bool,
    /// Output format (human-readable or JSON).
    pub format: OutputFormat,
    /// Shared runtime settings.
    pub ctx: RuntimeCtx,
}

/// Options for cancelling jobs.
#[derive(Debug, Default)]
pub struct CancelJobsOptions {
    /// Cancel all active jobs.
    pub all: bool,
    /// Skip confirmation prompt.
    pub skip_confirm: bool,
    /// Show what would be cancelled without actually cancelling.
    pub dry_run: bool,
    /// Output format (human-readable or JSON).
    pub format: OutputFormat,
    /// Shared runtime settings.
    pub ctx: RuntimeCtx,
}

/// Cancels running or pending Slurm jobs.
pub async fn cancel_jobs(
    job_id: Option<&str>,
    tags: &[(String, String)],
    opts: CancelJobsOptions,
) -> Result<()> {
    let registry = Registry::open()?;

    let jobs_to_cancel: Vec<JobRecord> = if let Some(id) = job_id {
        let job = registry.get_job(id)?;
        if matches!(
            job.status,
            JobStatus::Completed | JobStatus::Failed | JobStatus::Cancelled
        ) {
            return Err(FlecheError::CannotCancel(
                id.to_string(),
                job.status.to_string(),
            ));
        }
        vec![job]
    } else if opts.all {
        // Get active jobs, optionally filtered by tags
        if tags.is_empty() {
            registry.list_active_jobs()?
        } else {
            registry
                .list_jobs_by_tags(tags, usize::MAX)?
                .into_iter()
                .filter(|j| matches!(j.status, JobStatus::Pending | JobStatus::Running))
                .collect()
        }
    } else {
        // Cancel most recent active job (optionally filtered by tags)
        let active: Vec<JobRecord> = if tags.is_empty() {
            registry.list_active_jobs()?
        } else {
            registry
                .list_jobs_by_tags(tags, usize::MAX)?
                .into_iter()
                .filter(|j| matches!(j.status, JobStatus::Pending | JobStatus::Running))
                .collect()
        };
        if active.is_empty() {
            let empty: Vec<JobRecord> = Vec::new();
            return opts.format.print(&empty, || {
                println!("No active jobs to cancel.");
                Ok(())
            });
        }
        let mut active = active;
        active.truncate(1);
        active
    };

    if jobs_to_cancel.is_empty() {
        let empty: Vec<JobRecord> = Vec::new();
        return opts.format.print(&empty, || {
            println!("No active jobs to cancel.");
            Ok(())
        });
    }

    // Dry run: show what would be cancelled and exit
    if opts.dry_run {
        return opts.format.print(&jobs_to_cancel, || {
            println!("Would cancel {} job(s):", jobs_to_cancel.len());
            for job in &jobs_to_cancel {
                println!(
                    "  {} ({}) - {}",
                    job.id,
                    style(&job.status).yellow(),
                    job.job_name
                );
            }
            Ok(())
        });
    }

    // Show jobs and confirm if multiple
    if opts.format.is_human() && (jobs_to_cancel.len() > 1 || opts.all) {
        println!("Jobs to cancel:");
        for job in &jobs_to_cancel {
            println!(
                "  {} ({}) - {}",
                job.id,
                style(&job.status).yellow(),
                job.job_name
            );
        }
        println!();

        if !opts.skip_confirm && !confirm("Cancel these jobs?")? {
            println!("Cancelled.");
            return Ok(());
        }
    }

    for job in &jobs_to_cancel {
        if job.remote_host == "local" {
            // Cancel local job
            let project_path = PathBuf::from(&job.project_path);
            match local::cancel_local_job(&project_path, &job.id) {
                Ok(true) => {
                    registry.update_status(
                        &job.id,
                        &LiveStatus::with_exit_code(JobStatus::Cancelled, 143),
                    )?;
                    if opts.format.is_human() {
                        println!("{} Job {} cancelled", style("").green(), job.id);
                    }
                }
                Ok(false) => {
                    eprintln!("  Warning: Could not cancel {} (process not found)", job.id);
                }
                Err(e) => {
                    eprintln!("  Warning: Could not cancel {}: {e}", job.id);
                }
            }
        } else if let Some(ref slurm_id) = job.slurm_id {
            // Cancel remote Slurm job
            let ssh = opts.ctx.ssh(&job.remote_host);
            if let Err(e) = cancel_job(&ssh, slurm_id).await {
                eprintln!("  Warning: Could not cancel {}: {e}", job.id);
                continue;
            }
            registry.update_status(&job.id, &LiveStatus::new(JobStatus::Cancelled))?;
            if opts.format.is_human() {
                println!("{} Job {} cancelled", style("").green(), job.id);
            }
        } else {
            // Cancel remote direct (exec) job
            let ssh = opts.ctx.ssh(&job.remote_host);
            let job_dir = job_path_from_workspace(&job.remote_path, &job.id);
            match cancel_remote_direct_job(&ssh, &job_dir).await {
                Ok(true) => {
                    registry.update_status(
                        &job.id,
                        &LiveStatus::with_exit_code(JobStatus::Cancelled, 143),
                    )?;
                    if opts.format.is_human() {
                        println!("{} Job {} cancelled", style("").green(), job.id);
                    }
                }
                Ok(false) => {
                    eprintln!("  Warning: Could not cancel {} (process not found)", job.id);
                }
                Err(e) => {
                    eprintln!("  Warning: Could not cancel {}: {e}", job.id);
                }
            }
        }
    }

    opts.format.print_json_only(&jobs_to_cancel)
}

/// Cleans up jobs by removing them from the registry and deleting remote job files.
/// Also supports archiving/unarchiving jobs.
pub async fn clean_jobs(
    job_id: Option<&str>,
    older_than: Option<&str>,
    tags: &[(String, String)],
    opts: CleanJobsOptions,
) -> Result<()> {
    let registry = Registry::open()?;

    // Handle --unarchive mode: restore archived jobs
    if opts.unarchive {
        let jobs_to_unarchive: Vec<JobRecord> = if let Some(id) = job_id {
            let job = registry.get_job(id)?;
            if !job.archived {
                println!("Job {} is not archived.", job.id);
                return Ok(());
            }
            vec![job]
        } else if opts.all {
            registry.list_archived_jobs()?
        } else {
            println!("Specify a job ID or --all with --unarchive");
            return Ok(());
        };

        if jobs_to_unarchive.is_empty() {
            let empty: Vec<JobRecord> = Vec::new();
            return opts.format.print(&empty, || {
                println!("No archived jobs to restore.");
                Ok(())
            });
        }

        if opts.dry_run {
            return opts.format.print(&jobs_to_unarchive, || {
                println!(
                    "Would restore {} job(s) from archive:",
                    jobs_to_unarchive.len()
                );
                for job in &jobs_to_unarchive {
                    println!("  {} - {}", job.id, job.job_name);
                }
                Ok(())
            });
        }

        for job in &jobs_to_unarchive {
            registry.unarchive_job(&job.id)?;
            if opts.format.is_human() {
                println!(
                    "{} Restored job {} from archive",
                    style("").green(),
                    job.id
                );
            }
        }

        return opts.format.print_json_only(&jobs_to_unarchive);
    }

    // For archive/delete: get jobs to process
    let jobs_to_clean: Vec<JobRecord> = if let Some(id) = job_id {
        vec![registry.get_job(id)?]
    } else if opts.all {
        if opts.include_archived {
            // Target archived jobs
            registry.list_archived_jobs()?
        } else if tags.is_empty() {
            registry.list_finished_jobs()?
        } else {
            registry
                .list_jobs_by_tags(tags, usize::MAX)?
                .into_iter()
                .filter(|j| {
                    matches!(
                        j.status,
                        JobStatus::Completed | JobStatus::Failed | JobStatus::Cancelled
                    )
                })
                .collect()
        }
    } else if let Some(duration_str) = older_than {
        let duration = parse_duration(duration_str)?;
        let older_jobs = if opts.include_archived {
            registry.list_archived_jobs_older_than(duration)?
        } else {
            registry.list_jobs_older_than(duration)?
        };
        // Filter by tags if provided
        if tags.is_empty() {
            older_jobs
        } else {
            older_jobs
                .into_iter()
                .filter(|j| tags.iter().all(|(k, v)| j.tags.get(k) == Some(v)))
                .collect()
        }
    } else {
        println!("Specify a job ID, --all, or --older-than");
        return Ok(());
    };

    // Apply --filter status filters
    let status_filters: Vec<JobStatus> = opts
        .status_filters
        .iter()
        .map(|f| f.parse())
        .collect::<Result<Vec<_>>>()?;
    let jobs_to_clean: Vec<JobRecord> = if status_filters.is_empty() {
        jobs_to_clean
    } else {
        jobs_to_clean
            .into_iter()
            .filter(|j| status_filters.contains(&j.status))
            .collect()
    };

    let action = if opts.delete { "delete" } else { "archive" };

    if jobs_to_clean.is_empty() && !opts.clean_workspace {
        let empty: Vec<JobRecord> = Vec::new();
        return opts.format.print(&empty, || {
            println!("No jobs to {action}.");
            Ok(())
        });
    }

    // Dry run: show what would be affected and exit
    if opts.dry_run {
        return opts.format.print(&jobs_to_clean, || {
            println!("Would {action} {} job(s):", jobs_to_clean.len());
            for job in &jobs_to_clean {
                println!(
                    "  {} ({}) - {}",
                    job.id,
                    style(&job.status).cyan(),
                    job.job_name
                );
            }
            Ok(())
        });
    }

    // Show jobs and confirm if multiple
    if opts.format.is_human()
        && !jobs_to_clean.is_empty()
        && (jobs_to_clean.len() > 1 || opts.all || older_than.is_some())
    {
        println!("Jobs to {action}:");
        for job in &jobs_to_clean {
            println!(
                "  {} ({}) - {}",
                job.id,
                style(&job.status).cyan(),
                job.job_name
            );
        }
        println!();
    }

    // Default mode: archive jobs
    if !opts.delete {
        let confirm_msg = format!("Archive {} job(s)?", jobs_to_clean.len());
        if opts.format.is_human() && !opts.skip_confirm && !confirm(&confirm_msg)? {
            println!("Cancelled.");
            return Ok(());
        }

        for job in &jobs_to_clean {
            registry.archive_job(&job.id)?;
            if opts.format.is_human() {
                println!("{} Archived job {}", style("").green(), job.id);
            }
        }

        return opts.format.print_json_only(&jobs_to_clean);
    }

    // --delete mode: permanently remove jobs
    if opts.format.is_human() && opts.clean_workspace {
        println!(
            "{}",
            style("WARNING: This will also delete the shared workspace!")
                .red()
                .bold()
        );
    }

    if opts.format.is_human() && !opts.skip_confirm && !confirm("Permanently delete?")? {
        println!("Cancelled.");
        return Ok(());
    }

    // Snapshot active jobs before deletions so workspace checks remain accurate
    // even if selected running jobs are removed from the registry.
    let active_jobs_snapshot = if opts.clean_workspace {
        Some(registry.list_active_jobs()?)
    } else {
        None
    };

    // Delete job directories
    for job in &jobs_to_clean {
        if opts.format.is_human() {
            print!("Deleting {}... ", job.id);
        }

        if job.remote_host == "local" {
            let project_path = PathBuf::from(&job.project_path);
            if let Err(e) = local::clean_local_job(&project_path, &job.id) {
                eprintln!("warning: could not delete job directory: {e}");
            }
        } else {
            let ssh = opts.ctx.ssh(&job.remote_host);
            let job_dir = job_path_from_workspace(&job.remote_path, &job.id);
            if let Err(e) = ssh.rm_rf(&job_dir).await {
                eprintln!("warning: could not delete job directory: {e}");
            }
        }

        registry.delete_job(&job.id)?;
        if opts.format.is_human() {
            println!("{}", style("done").green());
        }
    }

    // Clean workspaces if requested (only for remote jobs)
    if opts.clean_workspace {
        let active_jobs = active_jobs_snapshot
            .as_ref()
            .expect("snapshot exists when clean_workspace is enabled");
        let mut seen = HashSet::new();
        let mut cleaned_any = false;

        for job in &jobs_to_clean {
            if job.remote_host == "local" {
                continue;
            }

            let key = (job.remote_host.clone(), job.remote_path.clone());
            if !seen.insert(key.clone()) {
                continue;
            }

            let has_active = active_jobs
                .iter()
                .any(|j| j.remote_host == key.0 && j.remote_path == key.1);
            if has_active {
                eprintln!(
                    "{}",
                    style(format!(
                        "warning: skipping workspace '{}' on '{}' because it has active jobs",
                        key.1, key.0
                    ))
                    .yellow()
                );
                continue;
            }

            let ssh = opts.ctx.ssh(&key.0);
            print!("Deleting workspace on {}... ", key.0);
            if let Err(e) = ssh.rm_rf(&key.1).await {
                eprintln!("warning: could not delete workspace: {e}");
            } else {
                println!("{}", style("done").green());
                cleaned_any = true;
            }
        }

        if !cleaned_any && jobs_to_clean.iter().all(|j| j.remote_host == "local") {
            println!(
                "{}",
                style("Note: --workspace has no effect for local jobs.").yellow()
            );
        }
    }

    opts.format.print(&jobs_to_clean, || {
        if !jobs_to_clean.is_empty() {
            println!(
                "\n{} Deleted {} job(s)",
                style("").green(),
                jobs_to_clean.len()
            );
        }
        Ok(())
    })
}

/// Prompts the user for confirmation.
pub fn confirm(prompt: &str) -> Result<bool> {
    print!("{prompt} [y/N] ");
    std::io::stdout().flush()?;

    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;

    Ok(matches!(input.trim().to_lowercase().as_str(), "y" | "yes"))
}