pipeline-service 2.1.0

Pipeline execution service for roxid
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
// Container Runner
// Executes jobs inside Docker containers

use crate::parser::models::{
    ContainerRef, ContainerSpec, Job, JobResult, JobStatus, Step, StepResult, StepStatus,
};

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use thiserror::Error;

/// Errors that can occur with container execution
#[derive(Debug, Error)]
pub enum ContainerError {
    #[error("Docker is not available: {0}")]
    DockerNotAvailable(String),

    #[error("Failed to pull image: {0}")]
    PullFailed(String),

    #[error("Failed to create container: {0}")]
    CreateFailed(String),

    #[error("Failed to start container: {0}")]
    StartFailed(String),

    #[error("Container execution failed: {0}")]
    ExecutionFailed(String),

    #[error("Failed to stop container: {0}")]
    StopFailed(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),
}

/// Configuration for container execution
#[derive(Debug, Clone)]
pub struct ContainerConfig {
    /// Docker socket path (default: /var/run/docker.sock on Unix)
    pub docker_socket: Option<PathBuf>,
    /// Whether to pull images before running
    pub pull_policy: ImagePullPolicy,
    /// Default timeout for container operations
    pub timeout: Duration,
    /// Whether to remove containers after execution
    pub auto_remove: bool,
}

impl Default for ContainerConfig {
    fn default() -> Self {
        Self {
            docker_socket: None,
            pull_policy: ImagePullPolicy::IfNotPresent,
            timeout: Duration::from_secs(3600),
            auto_remove: true,
        }
    }
}

/// Image pull policy
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImagePullPolicy {
    /// Always pull the image
    Always,
    /// Pull only if not present locally
    IfNotPresent,
    /// Never pull (must be present locally)
    Never,
}

/// Handle to a running container
#[derive(Debug)]
pub struct ContainerHandle {
    /// Container ID
    pub id: String,
    /// Container name
    pub name: String,
    /// Image used
    pub image: String,
}

/// Handle to service containers
#[derive(Debug)]
pub struct ServiceHandles {
    /// Service name to container handle mapping
    pub services: HashMap<String, ContainerHandle>,
}

/// Container runner for Docker-based execution
pub struct ContainerRunner {
    config: ContainerConfig,
}

impl ContainerRunner {
    /// Create a new container runner with default configuration
    pub fn new() -> Self {
        Self {
            config: ContainerConfig::default(),
        }
    }

    /// Create a container runner with custom configuration
    pub fn with_config(config: ContainerConfig) -> Self {
        Self { config }
    }

    /// Check if Docker is available
    pub async fn is_available(&self) -> bool {
        // Try to run `docker version`
        let output = tokio::process::Command::new("docker")
            .arg("version")
            .arg("--format")
            .arg("{{.Server.Version}}")
            .output()
            .await;

        output.map(|o| o.status.success()).unwrap_or(false)
    }

    /// Run a job inside a container
    pub async fn run_job_in_container(
        &self,
        job: &Job,
        container: &ContainerRef,
        env: &HashMap<String, String>,
        working_dir: &Path,
    ) -> Result<JobResult, ContainerError> {
        let start = Instant::now();
        let job_name = job.identifier().unwrap_or("job").to_string();

        // Parse container spec
        let container_spec = self.parse_container_ref(container)?;

        // Pull image if needed
        self.pull_image_if_needed(&container_spec.image).await?;

        // Create and start the container
        let container_handle = self
            .create_container(&job_name, &container_spec, env, working_dir)
            .await?;

        // Execute steps inside the container
        let mut step_results = Vec::new();
        let mut job_status = JobStatus::Succeeded;

        for step in &job.steps {
            let result = self
                .run_step_in_container(&container_handle, step, env, working_dir)
                .await;

            if result.status == StepStatus::Failed {
                job_status = JobStatus::Failed;
            } else if result.status == StepStatus::SucceededWithIssues
                && job_status == JobStatus::Succeeded
            {
                job_status = JobStatus::SucceededWithIssues;
            }

            step_results.push(result);

            if job_status == JobStatus::Failed && !job.continue_on_error {
                break;
            }
        }

        // Clean up container
        self.stop_container(&container_handle).await?;

        Ok(JobResult {
            job_name,
            display_name: job.display_name.clone(),
            status: job_status,
            steps: step_results,
            duration: start.elapsed(),
            outputs: HashMap::new(),
        })
    }

    /// Start service containers for a job
    pub async fn start_service_containers(
        &self,
        services: &HashMap<String, ContainerRef>,
        env: &HashMap<String, String>,
        working_dir: &Path,
    ) -> Result<ServiceHandles, ContainerError> {
        let mut handles = HashMap::new();

        for (service_name, container_ref) in services {
            let container_spec = self.parse_container_ref(container_ref)?;

            // Pull image if needed
            self.pull_image_if_needed(&container_spec.image).await?;

            // Create service container
            let handle = self
                .create_service_container(service_name, &container_spec, env, working_dir)
                .await?;

            handles.insert(service_name.clone(), handle);
        }

        Ok(ServiceHandles { services: handles })
    }

    /// Stop service containers
    pub async fn stop_service_containers(
        &self,
        handles: ServiceHandles,
    ) -> Result<(), ContainerError> {
        for (_, handle) in handles.services {
            self.stop_container(&handle).await?;
        }
        Ok(())
    }

    /// Parse a container reference into a spec
    fn parse_container_ref(
        &self,
        container: &ContainerRef,
    ) -> Result<ContainerSpec, ContainerError> {
        match container {
            ContainerRef::Image(image) => Ok(ContainerSpec {
                image: image.clone(),
                endpoint: None,
                env: HashMap::new(),
                ports: Vec::new(),
                volumes: Vec::new(),
                options: None,
                map_docker_socket: None,
                mount_read_only: None,
            }),
            ContainerRef::Spec(spec) => Ok(spec.clone()),
        }
    }

    /// Pull an image if needed based on pull policy
    async fn pull_image_if_needed(&self, image: &str) -> Result<(), ContainerError> {
        match self.config.pull_policy {
            ImagePullPolicy::Never => Ok(()),
            ImagePullPolicy::Always => self.pull_image(image).await,
            ImagePullPolicy::IfNotPresent => {
                // Check if image exists locally
                let output = tokio::process::Command::new("docker")
                    .args(["image", "inspect", image])
                    .output()
                    .await
                    .map_err(|e| ContainerError::DockerNotAvailable(e.to_string()))?;

                if !output.status.success() {
                    self.pull_image(image).await
                } else {
                    Ok(())
                }
            }
        }
    }

    /// Pull a Docker image
    async fn pull_image(&self, image: &str) -> Result<(), ContainerError> {
        let output = tokio::process::Command::new("docker")
            .args(["pull", image])
            .output()
            .await
            .map_err(|e| ContainerError::DockerNotAvailable(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(ContainerError::PullFailed(format!(
                "Failed to pull {}: {}",
                image, stderr
            )));
        }

        Ok(())
    }

    /// Create a container for job execution
    async fn create_container(
        &self,
        name: &str,
        spec: &ContainerSpec,
        env: &HashMap<String, String>,
        working_dir: &Path,
    ) -> Result<ContainerHandle, ContainerError> {
        let container_name = format!("roxid-{}-{}", name, uuid_v4_simple());

        let mut args = vec![
            "create".to_string(),
            "--name".to_string(),
            container_name.clone(),
            "-w".to_string(),
            "/workspace".to_string(),
            "-v".to_string(),
            format!("{}:/workspace", working_dir.display()),
        ];

        // Add environment variables
        for (key, value) in env {
            args.push("-e".to_string());
            args.push(format!("{}={}", key, value));
        }

        // Add container-specific env
        for (key, value) in &spec.env {
            args.push("-e".to_string());
            args.push(format!("{}={}", key, value));
        }

        // Add volumes
        for volume in &spec.volumes {
            args.push("-v".to_string());
            args.push(volume.clone());
        }

        // Add ports
        for port in &spec.ports {
            args.push("-p".to_string());
            args.push(port.clone());
        }

        // Add Docker socket if requested
        if spec.map_docker_socket.unwrap_or(false) {
            args.push("-v".to_string());
            args.push("/var/run/docker.sock:/var/run/docker.sock".to_string());
        }

        // Add any additional options
        if let Some(options) = &spec.options {
            // Parse options string (space-separated Docker flags)
            for opt in options.split_whitespace() {
                args.push(opt.to_string());
            }
        }

        // Add the image
        args.push(spec.image.clone());

        // Keep container running with tail
        args.push("tail".to_string());
        args.push("-f".to_string());
        args.push("/dev/null".to_string());

        let output = tokio::process::Command::new("docker")
            .args(&args)
            .output()
            .await
            .map_err(|e| ContainerError::DockerNotAvailable(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(ContainerError::CreateFailed(stderr.to_string()));
        }

        let container_id = String::from_utf8_lossy(&output.stdout).trim().to_string();

        // Start the container
        let start_output = tokio::process::Command::new("docker")
            .args(["start", &container_name])
            .output()
            .await
            .map_err(|e| ContainerError::DockerNotAvailable(e.to_string()))?;

        if !start_output.status.success() {
            let stderr = String::from_utf8_lossy(&start_output.stderr);
            return Err(ContainerError::StartFailed(stderr.to_string()));
        }

        Ok(ContainerHandle {
            id: container_id,
            name: container_name,
            image: spec.image.clone(),
        })
    }

    /// Create a service container
    async fn create_service_container(
        &self,
        service_name: &str,
        spec: &ContainerSpec,
        env: &HashMap<String, String>,
        _working_dir: &Path,
    ) -> Result<ContainerHandle, ContainerError> {
        let container_name = format!("roxid-svc-{}-{}", service_name, uuid_v4_simple());

        let mut args = vec![
            "run".to_string(),
            "-d".to_string(),
            "--name".to_string(),
            container_name.clone(),
        ];

        // Add environment variables
        for (key, value) in env {
            args.push("-e".to_string());
            args.push(format!("{}={}", key, value));
        }

        for (key, value) in &spec.env {
            args.push("-e".to_string());
            args.push(format!("{}={}", key, value));
        }

        // Add ports
        for port in &spec.ports {
            args.push("-p".to_string());
            args.push(port.clone());
        }

        // Add volumes
        for volume in &spec.volumes {
            args.push("-v".to_string());
            args.push(volume.clone());
        }

        // Add the image
        args.push(spec.image.clone());

        let output = tokio::process::Command::new("docker")
            .args(&args)
            .output()
            .await
            .map_err(|e| ContainerError::DockerNotAvailable(e.to_string()))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(ContainerError::CreateFailed(stderr.to_string()));
        }

        let container_id = String::from_utf8_lossy(&output.stdout).trim().to_string();

        Ok(ContainerHandle {
            id: container_id,
            name: container_name,
            image: spec.image.clone(),
        })
    }

    /// Run a step inside a container
    async fn run_step_in_container(
        &self,
        container: &ContainerHandle,
        step: &Step,
        _env: &HashMap<String, String>,
        _working_dir: &Path,
    ) -> StepResult {
        let start = Instant::now();
        let step_name = step.name.clone();

        // For now, we only support script steps in containers
        let script = match &step.action {
            crate::parser::models::StepAction::Script(s) => &s.script,
            crate::parser::models::StepAction::Bash(s) => &s.bash,
            crate::parser::models::StepAction::Pwsh(s) => &s.pwsh,
            crate::parser::models::StepAction::PowerShell(s) => &s.powershell,
            _ => {
                return StepResult {
                    step_name,
                    display_name: step.display_name.clone(),
                    status: StepStatus::Skipped,
                    output: "Step type not supported in container".to_string(),
                    error: None,
                    duration: start.elapsed(),
                    exit_code: None,
                    outputs: HashMap::new(),
                };
            }
        };

        // Execute the script in the container
        let output = tokio::process::Command::new("docker")
            .args([
                "exec",
                "-w",
                "/workspace",
                &container.name,
                "sh",
                "-c",
                script,
            ])
            .output()
            .await;

        match output {
            Ok(output) => {
                let stdout = String::from_utf8_lossy(&output.stdout).to_string();
                let stderr = String::from_utf8_lossy(&output.stderr).to_string();

                let status = if output.status.success() {
                    StepStatus::Succeeded
                } else {
                    StepStatus::Failed
                };

                StepResult {
                    step_name,
                    display_name: step.display_name.clone(),
                    status,
                    output: stdout,
                    error: if stderr.is_empty() {
                        None
                    } else {
                        Some(stderr)
                    },
                    duration: start.elapsed(),
                    exit_code: output.status.code(),
                    outputs: HashMap::new(),
                }
            }
            Err(e) => StepResult {
                step_name,
                display_name: step.display_name.clone(),
                status: StepStatus::Failed,
                output: String::new(),
                error: Some(format!("Failed to execute in container: {}", e)),
                duration: start.elapsed(),
                exit_code: None,
                outputs: HashMap::new(),
            },
        }
    }

    /// Stop and remove a container
    async fn stop_container(&self, handle: &ContainerHandle) -> Result<(), ContainerError> {
        // Stop the container
        let _ = tokio::process::Command::new("docker")
            .args(["stop", &handle.name])
            .output()
            .await;

        // Remove the container if auto_remove is enabled
        if self.config.auto_remove {
            let _ = tokio::process::Command::new("docker")
                .args(["rm", "-f", &handle.name])
                .output()
                .await;
        }

        Ok(())
    }
}

impl Default for ContainerRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// Generate a simple UUID-like string (8 chars)
fn uuid_v4_simple() -> String {
    use std::time::{SystemTime, UNIX_EPOCH};
    let duration = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default();
    let nanos = duration.as_nanos();
    format!("{:08x}", (nanos as u32) ^ std::process::id())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_container_ref_image() {
        let runner = ContainerRunner::new();
        let container = ContainerRef::Image("ubuntu:22.04".to_string());
        let spec = runner.parse_container_ref(&container).unwrap();

        assert_eq!(spec.image, "ubuntu:22.04");
        assert!(spec.env.is_empty());
    }

    #[test]
    fn test_parse_container_ref_spec() {
        let runner = ContainerRunner::new();
        let mut env = HashMap::new();
        env.insert("MY_VAR".to_string(), "value".to_string());

        let container = ContainerRef::Spec(ContainerSpec {
            image: "node:18".to_string(),
            endpoint: None,
            env,
            ports: vec!["3000:3000".to_string()],
            volumes: vec!["/data:/data".to_string()],
            options: None,
            map_docker_socket: Some(true),
            mount_read_only: None,
        });

        let spec = runner.parse_container_ref(&container).unwrap();

        assert_eq!(spec.image, "node:18");
        assert_eq!(spec.env.get("MY_VAR"), Some(&"value".to_string()));
        assert!(spec.map_docker_socket.unwrap_or(false));
    }

    #[test]
    fn test_uuid_v4_simple() {
        let id1 = uuid_v4_simple();
        let id2 = uuid_v4_simple();

        assert_eq!(id1.len(), 8);
        // IDs generated in quick succession might be the same,
        // but they should be valid hex strings
        assert!(id1.chars().all(|c| c.is_ascii_hexdigit()));
        assert!(id2.chars().all(|c| c.is_ascii_hexdigit()));
    }

    #[tokio::test]
    async fn test_docker_availability_check() {
        let runner = ContainerRunner::new();
        // This test just verifies the check doesn't panic
        let _ = runner.is_available().await;
    }
}