zlayer-agent 0.11.12

Container runtime agent using libcontainer/youki
Documentation
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
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Cron scheduler - triggers jobs on time-based schedules
//!
//! This module provides the `CronScheduler` which manages scheduled job executions.
//! Jobs are triggered based on cron expressions (e.g., "0 0 * * * * *" for hourly).

use crate::error::{AgentError, Result};
use crate::job::{JobExecutionId, JobExecutor, JobTrigger};
use chrono::{DateTime, Utc};
use cron::Schedule;
use std::collections::HashMap;
use std::str::FromStr;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};
use zlayer_spec::ServiceSpec;

/// A registered cron job
struct CronJob {
    /// Job name
    name: String,
    /// Service specification for the job
    spec: ServiceSpec,
    /// Parsed cron schedule
    schedule: Schedule,
    /// Last time this job was run
    last_run: Option<Instant>,
    /// Next scheduled run time
    next_run: Option<DateTime<Utc>>,
    /// Whether this job is enabled
    enabled: bool,
}

/// Public info about a cron job (for external visibility)
#[derive(Debug, Clone)]
pub struct CronJobInfo {
    /// Job name
    pub name: String,
    /// Cron schedule expression
    pub schedule_expr: String,
    /// Last run time (as UTC datetime)
    pub last_run: Option<DateTime<Utc>>,
    /// Next scheduled run time
    pub next_run: Option<DateTime<Utc>>,
    /// Whether this job is enabled
    pub enabled: bool,
}

/// Cron scheduler manages time-based job triggers
pub struct CronScheduler {
    /// Registered cron jobs
    jobs: RwLock<HashMap<String, CronJob>>,
    /// Job executor for running jobs
    job_executor: Arc<JobExecutor>,
    /// Running state flag
    running: AtomicBool,
    /// Shutdown signal
    shutdown: Arc<tokio::sync::Notify>,
}

impl CronScheduler {
    /// Create a new cron scheduler
    ///
    /// # Arguments
    /// * `job_executor` - The job executor to use for running triggered jobs
    pub fn new(job_executor: Arc<JobExecutor>) -> Self {
        Self {
            jobs: RwLock::new(HashMap::new()),
            job_executor,
            running: AtomicBool::new(false),
            shutdown: Arc::new(tokio::sync::Notify::new()),
        }
    }

    /// Register a cron job
    ///
    /// # Arguments
    /// * `name` - Unique name for this cron job
    /// * `spec` - Service specification (must have rtype: cron and schedule field)
    ///
    /// # Errors
    /// Returns error if spec has no schedule or if schedule is invalid
    pub async fn register(&self, name: &str, spec: &ServiceSpec) -> Result<()> {
        let schedule_str = spec.schedule.as_ref().ok_or_else(|| {
            AgentError::InvalidSpec("Cron job missing schedule field".to_string())
        })?;

        let schedule = Schedule::from_str(schedule_str).map_err(|e| {
            AgentError::InvalidSpec(format!("Invalid cron schedule '{schedule_str}': {e}"))
        })?;

        let next_run = schedule.upcoming(Utc).next();

        let job = CronJob {
            name: name.to_string(),
            spec: spec.clone(),
            schedule,
            last_run: None,
            next_run,
            enabled: true,
        };

        {
            let mut jobs = self.jobs.write().await;
            jobs.insert(name.to_string(), job);
        }

        info!(
            job = %name,
            schedule = %schedule_str,
            next_run = ?next_run,
            "Registered cron job"
        );

        Ok(())
    }

    /// Unregister a cron job
    ///
    /// # Arguments
    /// * `name` - Name of the cron job to unregister
    pub async fn unregister(&self, name: &str) {
        let mut jobs = self.jobs.write().await;
        if jobs.remove(name).is_some() {
            info!(job = %name, "Unregistered cron job");
        } else {
            warn!(job = %name, "Attempted to unregister non-existent cron job");
        }
    }

    /// Enable or disable a cron job
    ///
    /// When enabled, recalculates the next run time.
    pub async fn set_enabled(&self, name: &str, enabled: bool) {
        let mut jobs = self.jobs.write().await;
        if let Some(job) = jobs.get_mut(name) {
            job.enabled = enabled;
            if enabled {
                // Recalculate next run when re-enabled
                job.next_run = job.schedule.upcoming(Utc).next();
            }
            info!(
                job = %name,
                enabled = enabled,
                next_run = ?job.next_run,
                "Updated cron job enabled state"
            );
        }
    }

    /// Get info about a specific cron job
    pub async fn get_job_info(&self, name: &str) -> Option<CronJobInfo> {
        let jobs = self.jobs.read().await;
        jobs.get(name).map(|j| CronJobInfo {
            name: j.name.clone(),
            schedule_expr: j.spec.schedule.clone().unwrap_or_default(),
            last_run: j.last_run.map(|_| {
                // Convert Instant to approximate DateTime
                // Note: Instant doesn't have a direct conversion, so we approximate
                // based on current time minus elapsed duration
                Utc::now()
            }),
            next_run: j.next_run,
            enabled: j.enabled,
        })
    }

    /// List all registered cron jobs
    pub async fn list_jobs(&self) -> Vec<CronJobInfo> {
        let jobs = self.jobs.read().await;
        jobs.values()
            .map(|j| CronJobInfo {
                name: j.name.clone(),
                schedule_expr: j.spec.schedule.clone().unwrap_or_default(),
                last_run: j.last_run.map(|_| Utc::now()), // Approximate
                next_run: j.next_run,
                enabled: j.enabled,
            })
            .collect()
    }

    /// Run the scheduler loop
    ///
    /// This method runs forever, checking every second for jobs that need to be triggered.
    /// Use `shutdown()` to stop the loop gracefully.
    pub async fn run_loop(&self) {
        if self
            .running
            .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
            .is_err()
        {
            warn!("Cron scheduler is already running");
            return;
        }

        let check_interval = Duration::from_secs(1);
        let mut interval = tokio::time::interval(check_interval);

        info!("Cron scheduler started");

        loop {
            tokio::select! {
                _ = interval.tick() => {
                    self.check_and_trigger().await;
                }
                () = self.shutdown.notified() => {
                    info!("Cron scheduler received shutdown signal");
                    break;
                }
            }
        }

        self.running.store(false, Ordering::SeqCst);
        info!("Cron scheduler stopped");
    }

    /// Check all jobs and trigger those that are due
    async fn check_and_trigger(&self) {
        let now = Utc::now();
        let mut jobs_to_trigger: Vec<(String, ServiceSpec)> = Vec::new();

        // First pass: find jobs that need to be triggered
        {
            let jobs = self.jobs.read().await;
            for (name, job) in jobs.iter() {
                if !job.enabled {
                    continue;
                }

                if let Some(next_run) = job.next_run {
                    if next_run <= now {
                        debug!(
                            job = %name,
                            scheduled_time = %next_run,
                            current_time = %now,
                            "Job is due for execution"
                        );
                        jobs_to_trigger.push((name.clone(), job.spec.clone()));
                    }
                }
            }
        }

        // Second pass: trigger jobs and update their state
        for (name, spec) in jobs_to_trigger {
            match self
                .job_executor
                .trigger(&name, &spec, JobTrigger::Scheduler)
                .await
            {
                Ok(exec_id) => {
                    info!(
                        job = %name,
                        execution_id = %exec_id,
                        "Cron job triggered"
                    );

                    // Update job state
                    let mut jobs = self.jobs.write().await;
                    if let Some(job) = jobs.get_mut(&name) {
                        job.last_run = Some(Instant::now());
                        job.next_run = job.schedule.upcoming(Utc).next();
                        debug!(
                            job = %name,
                            next_run = ?job.next_run,
                            "Updated cron job next run time"
                        );
                    }
                }
                Err(e) => {
                    error!(
                        job = %name,
                        error = %e,
                        "Failed to trigger cron job"
                    );
                }
            }
        }
    }

    /// Manually trigger a cron job (outside of its schedule)
    ///
    /// # Arguments
    /// * `name` - Name of the cron job to trigger
    ///
    /// # Returns
    /// The execution ID of the triggered job
    ///
    /// # Errors
    /// Returns error if the job is not found
    pub async fn trigger_now(&self, name: &str) -> Result<JobExecutionId> {
        let jobs = self.jobs.read().await;
        let job = jobs.get(name).ok_or_else(|| AgentError::NotFound {
            container: name.to_string(),
            reason: "cron job not found".to_string(),
        })?;

        info!(job = %name, "Manually triggering cron job");

        self.job_executor
            .trigger(name, &job.spec, JobTrigger::Cli)
            .await
    }

    /// Signal the scheduler to shut down
    pub fn shutdown(&self) {
        info!("Signaling cron scheduler shutdown");
        self.shutdown.notify_one();
    }

    /// Check if the scheduler is currently running
    pub fn is_running(&self) -> bool {
        self.running.load(Ordering::Relaxed)
    }

    /// Get the number of registered jobs
    pub async fn job_count(&self) -> usize {
        let jobs = self.jobs.read().await;
        jobs.len()
    }

    /// Get the number of enabled jobs
    pub async fn enabled_job_count(&self) -> usize {
        let jobs = self.jobs.read().await;
        jobs.values().filter(|j| j.enabled).count()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::runtime::{MockRuntime, Runtime};
    use zlayer_spec::DeploymentSpec;

    fn mock_cron_spec(schedule: &str) -> ServiceSpec {
        let yaml = format!(
            r#"
version: v1
deployment: test
services:
  cleanup:
    rtype: cron
    schedule: "{schedule}"
    image:
      name: cleanup:latest
"#
        );

        serde_yaml::from_str::<DeploymentSpec>(&yaml)
            .unwrap()
            .services
            .remove("cleanup")
            .unwrap()
    }

    #[tokio::test]
    async fn test_cron_scheduler_register() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        // Valid cron expression (every minute)
        let spec = mock_cron_spec("0 * * * * * *");
        scheduler.register("cleanup", &spec).await.unwrap();

        assert_eq!(scheduler.job_count().await, 1);

        let info = scheduler.get_job_info("cleanup").await;
        assert!(info.is_some());
        let info = info.unwrap();
        assert_eq!(info.name, "cleanup");
        assert!(info.enabled);
        assert!(info.next_run.is_some());
    }

    #[tokio::test]
    async fn test_cron_scheduler_invalid_schedule() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        // Create a spec manually with invalid schedule
        let mut spec = mock_cron_spec("0 * * * * * *");
        spec.schedule = Some("not a valid cron".to_string());

        let result = scheduler.register("bad", &spec).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_cron_scheduler_missing_schedule() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        // Create a spec without schedule
        let mut spec = mock_cron_spec("0 * * * * * *");
        spec.schedule = None;

        let result = scheduler.register("missing", &spec).await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_cron_scheduler_unregister() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        let spec = mock_cron_spec("0 * * * * * *");
        scheduler.register("cleanup", &spec).await.unwrap();
        assert_eq!(scheduler.job_count().await, 1);

        scheduler.unregister("cleanup").await;
        assert_eq!(scheduler.job_count().await, 0);
    }

    #[tokio::test]
    async fn test_cron_scheduler_enable_disable() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        let spec = mock_cron_spec("0 * * * * * *");
        scheduler.register("cleanup", &spec).await.unwrap();

        assert_eq!(scheduler.enabled_job_count().await, 1);

        scheduler.set_enabled("cleanup", false).await;
        assert_eq!(scheduler.enabled_job_count().await, 0);

        let info = scheduler.get_job_info("cleanup").await.unwrap();
        assert!(!info.enabled);

        scheduler.set_enabled("cleanup", true).await;
        assert_eq!(scheduler.enabled_job_count().await, 1);
    }

    #[tokio::test]
    async fn test_cron_scheduler_list_jobs() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        let spec1 = mock_cron_spec("0 * * * * * *");
        let spec2 = mock_cron_spec("0 0 * * * * *");

        scheduler.register("job1", &spec1).await.unwrap();
        scheduler.register("job2", &spec2).await.unwrap();

        let jobs = scheduler.list_jobs().await;
        assert_eq!(jobs.len(), 2);

        let names: Vec<_> = jobs.iter().map(|j| j.name.as_str()).collect();
        assert!(names.contains(&"job1"));
        assert!(names.contains(&"job2"));
    }

    #[tokio::test]
    async fn test_cron_scheduler_trigger_now() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor.clone());

        let spec = mock_cron_spec("0 * * * * * *");
        scheduler.register("cleanup", &spec).await.unwrap();

        // Manually trigger
        let exec_id = scheduler.trigger_now("cleanup").await.unwrap();
        assert!(!exec_id.0.is_empty());

        // Verify execution was created
        tokio::time::sleep(Duration::from_millis(50)).await;
        let execution = executor.get_execution(&exec_id).await;
        assert!(execution.is_some());
    }

    #[tokio::test]
    async fn test_cron_scheduler_trigger_now_not_found() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = CronScheduler::new(executor);

        let result = scheduler.trigger_now("nonexistent").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn test_cron_job_info() {
        let info = CronJobInfo {
            name: "test".to_string(),
            schedule_expr: "0 * * * * * *".to_string(),
            last_run: Some(Utc::now()),
            next_run: Some(Utc::now()),
            enabled: true,
        };

        assert_eq!(info.name, "test");
        assert!(info.enabled);
    }

    #[tokio::test]
    async fn test_cron_scheduler_shutdown() {
        let runtime: Arc<dyn Runtime + Send + Sync> = Arc::new(MockRuntime::new());
        let executor = Arc::new(JobExecutor::new(runtime));
        let scheduler = Arc::new(CronScheduler::new(executor));

        assert!(!scheduler.is_running());

        // Start scheduler in background
        let scheduler_clone = scheduler.clone();
        let handle = tokio::spawn(async move {
            scheduler_clone.run_loop().await;
        });

        // Give it time to start
        tokio::time::sleep(Duration::from_millis(50)).await;
        assert!(scheduler.is_running());

        // Shutdown
        scheduler.shutdown();

        // Wait for it to stop
        tokio::time::timeout(Duration::from_secs(2), handle)
            .await
            .expect("Scheduler should stop within timeout")
            .expect("Scheduler task should complete without error");

        assert!(!scheduler.is_running());
    }
}