zlayer-init-actions 0.12.0

Pre-start container lifecycle actions (TCP, HTTP, S3, commands)
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
//! Built-in init actions

use crate::error::{InitError, Result};
use std::collections::HashMap;
use std::time::Duration;
use tokio::process::Command;
use tokio::time::{sleep, timeout};

/// Wait for a TCP port to be open
pub struct WaitTcp {
    pub host: String,
    pub port: u16,
    pub timeout: Duration,
    pub interval: Duration,
}

impl WaitTcp {
    /// # Errors
    /// Returns `InitError::TcpFailed` if the connection times out.
    pub async fn execute(&self) -> Result<()> {
        let start = std::time::Instant::now();

        loop {
            if tokio::net::TcpStream::connect(&format!("{}:{}", self.host, self.port))
                .await
                .is_ok()
            {
                return Ok(());
            }

            if start.elapsed() >= self.timeout {
                return Err(InitError::TcpFailed {
                    host: self.host.clone(),
                    port: self.port,
                    reason: format!("timeout after {:?}", self.timeout),
                });
            }

            sleep(self.interval).await;
        }
    }
}

/// Wait for an HTTP endpoint to respond
pub struct WaitHttp {
    pub url: String,
    pub expect_status: Option<u16>,
    pub timeout: Duration,
    pub interval: Duration,
}

impl WaitHttp {
    /// # Errors
    /// Returns `InitError::HttpFailed` if the request times out or the expected status is not received.
    pub async fn execute(&self) -> Result<()> {
        let start = std::time::Instant::now();
        let client = reqwest::Client::builder()
            .timeout(Duration::from_secs(5))
            .build()
            .map_err(|e| InitError::HttpFailed {
                url: self.url.clone(),
                reason: format!("failed to create client: {e}"),
            })?;

        loop {
            let response = client.get(&self.url).send().await;

            if let Ok(resp) = response {
                let status = resp.status().as_u16();

                if let Some(expected) = self.expect_status {
                    if status == expected {
                        return Ok(());
                    }
                } else if (200..300).contains(&status) {
                    return Ok(());
                }
            }

            if start.elapsed() >= self.timeout {
                return Err(InitError::HttpFailed {
                    url: self.url.clone(),
                    reason: format!("timeout after {:?}", self.timeout),
                });
            }

            sleep(self.interval).await;
        }
    }
}

/// Run a shell command
pub struct RunCommand {
    pub command: String,
    pub timeout: Duration,
}

#[cfg(unix)]
fn build_shell_command(cmd: &str) -> Command {
    let mut c = Command::new("sh");
    c.arg("-c").arg(cmd);
    c
}

#[cfg(windows)]
fn build_shell_command(cmd: &str) -> Command {
    let mut c = Command::new("cmd");
    c.arg("/C").arg(cmd);
    c
}

impl RunCommand {
    /// # Errors
    /// Returns an error if the command fails, exits non-zero, or times out.
    pub async fn execute(&self) -> Result<()> {
        match timeout(self.timeout, build_shell_command(&self.command).output()).await {
            Ok(Ok(output)) => {
                if output.status.success() {
                    Ok(())
                } else {
                    Err(InitError::CommandFailed {
                        command: self.command.clone(),
                        code: output.status.code().unwrap_or(-1),
                        stdout: String::from_utf8_lossy(&output.stdout).to_string(),
                        stderr: String::from_utf8_lossy(&output.stderr).to_string(),
                    })
                }
            }
            Ok(Err(_)) => Err(InitError::CommandFailed {
                command: self.command.clone(),
                code: -1,
                stdout: String::new(),
                stderr: "timeout".to_string(),
            }),
            Err(_) => Err(InitError::Timeout {
                timeout: self.timeout,
            }),
        }
    }
}

/// Push files to S3 from a local path
#[cfg(feature = "s3")]
pub struct S3Push {
    /// Local source path (file or directory)
    pub source: String,
    /// S3 bucket name
    pub bucket: String,
    /// S3 key prefix
    pub key: String,
    /// Custom S3 endpoint (for S3-compatible services)
    pub endpoint: Option<String>,
    /// Region
    pub region: Option<String>,
    /// Upload timeout
    pub timeout: Duration,
}

#[cfg(feature = "s3")]
impl S3Push {
    /// Execute the S3 push action, uploading files to the configured bucket.
    ///
    /// # Errors
    ///
    /// Returns an error if the AWS SDK configuration fails, the S3 client
    /// cannot be created, or any file upload fails.
    pub async fn execute(&self) -> Result<()> {
        use aws_sdk_s3::Client;

        // Build AWS config
        let mut config_loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
        if let Some(ref region) = self.region {
            config_loader = config_loader.region(aws_config::Region::new(region.clone()));
        }
        let sdk_config = config_loader.load().await;

        // Build S3 client
        let mut s3_config = aws_sdk_s3::config::Builder::from(&sdk_config);
        if let Some(ref endpoint) = self.endpoint {
            s3_config = s3_config.endpoint_url(endpoint).force_path_style(true);
        }
        let client = Client::from_conf(s3_config.build());

        let source_path = std::path::Path::new(&self.source);

        if source_path.is_file() {
            // Upload single file
            self.upload_file(&client, source_path, &self.key).await?;
        } else if source_path.is_dir() {
            // Upload directory recursively
            self.upload_directory(&client, source_path, &self.key)
                .await?;
        } else {
            return Err(InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: self.key.clone(),
                reason: format!("source path '{}' does not exist", self.source),
            });
        }

        Ok(())
    }

    #[cfg(feature = "s3")]
    async fn upload_file(
        &self,
        client: &aws_sdk_s3::Client,
        path: &std::path::Path,
        key: &str,
    ) -> Result<()> {
        use aws_sdk_s3::primitives::ByteStream;

        tracing::info!(
            bucket = %self.bucket,
            key = %key,
            source = %path.display(),
            "pushing file to S3"
        );

        let data = tokio::fs::read(path)
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: key.to_string(),
                reason: format!("failed to read file: {e}"),
            })?;

        tokio::time::timeout(
            self.timeout,
            client
                .put_object()
                .bucket(&self.bucket)
                .key(key)
                .body(ByteStream::from(data))
                .content_type("application/octet-stream")
                .send(),
        )
        .await
        .map_err(|_| InitError::Timeout {
            timeout: self.timeout,
        })?
        .map_err(|e| InitError::S3Failed {
            bucket: self.bucket.clone(),
            key: key.to_string(),
            reason: format!("put_object failed: {e}"),
        })?;

        tracing::info!(bucket = %self.bucket, key = %key, "S3 push complete");
        Ok(())
    }

    #[cfg(feature = "s3")]
    async fn upload_directory(
        &self,
        client: &aws_sdk_s3::Client,
        dir: &std::path::Path,
        prefix: &str,
    ) -> Result<()> {
        let mut entries = tokio::fs::read_dir(dir)
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: prefix.to_string(),
                reason: format!("failed to read directory: {e}"),
            })?;

        while let Some(entry) = entries
            .next_entry()
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: prefix.to_string(),
                reason: format!("failed to read directory entry: {e}"),
            })?
        {
            let path = entry.path();
            let file_name = entry.file_name();
            let key = format!(
                "{}/{}",
                prefix.trim_end_matches('/'),
                file_name.to_string_lossy()
            );

            if path.is_file() {
                self.upload_file(client, &path, &key).await?;
            } else if path.is_dir() {
                // Use Box::pin for recursive async
                Box::pin(self.upload_directory(client, &path, &key)).await?;
            }
        }

        Ok(())
    }
}

/// Pull files from S3 to a local path
#[cfg(feature = "s3")]
pub struct S3Pull {
    /// S3 bucket name
    pub bucket: String,
    /// S3 key or prefix to download
    pub key: String,
    /// Local destination path
    pub destination: String,
    /// Custom S3 endpoint (for S3-compatible services)
    pub endpoint: Option<String>,
    /// Region
    pub region: Option<String>,
    /// Download timeout
    pub timeout: Duration,
}

#[cfg(feature = "s3")]
impl S3Pull {
    /// Execute the S3 pull action, downloading files from the configured bucket.
    ///
    /// # Errors
    ///
    /// Returns an error if the AWS SDK configuration fails, the S3 client
    /// cannot be created, or any file download fails.
    pub async fn execute(&self) -> Result<()> {
        use aws_sdk_s3::Client;
        use tokio::io::AsyncWriteExt;

        // Build AWS config
        let mut config_loader = aws_config::defaults(aws_config::BehaviorVersion::latest());
        if let Some(ref region) = self.region {
            config_loader = config_loader.region(aws_config::Region::new(region.clone()));
        }
        let sdk_config = config_loader.load().await;

        // Build S3 client
        let mut s3_config = aws_sdk_s3::config::Builder::from(&sdk_config);
        if let Some(ref endpoint) = self.endpoint {
            s3_config = s3_config.endpoint_url(endpoint).force_path_style(true);
        }
        let client = Client::from_conf(s3_config.build());

        tracing::info!(
            bucket = %self.bucket,
            key = %self.key,
            destination = %self.destination,
            "pulling from S3"
        );

        // Get object from S3
        let result = tokio::time::timeout(
            self.timeout,
            client
                .get_object()
                .bucket(&self.bucket)
                .key(&self.key)
                .send(),
        )
        .await
        .map_err(|_| InitError::Timeout {
            timeout: self.timeout,
        })?
        .map_err(|e| InitError::S3Failed {
            bucket: self.bucket.clone(),
            key: self.key.clone(),
            reason: format!("get_object failed: {e}"),
        })?;

        // Read body
        let data = result
            .body
            .collect()
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: self.key.clone(),
                reason: format!("failed to read body: {e}"),
            })?
            .into_bytes();

        // Write to destination
        let dest_path = std::path::Path::new(&self.destination);
        if let Some(parent) = dest_path.parent() {
            tokio::fs::create_dir_all(parent)
                .await
                .map_err(|e| InitError::S3Failed {
                    bucket: self.bucket.clone(),
                    key: self.key.clone(),
                    reason: format!("failed to create destination directory: {e}"),
                })?;
        }

        let mut file = tokio::fs::File::create(&self.destination)
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: self.key.clone(),
                reason: format!("failed to create file: {e}"),
            })?;

        file.write_all(&data)
            .await
            .map_err(|e| InitError::S3Failed {
                bucket: self.bucket.clone(),
                key: self.key.clone(),
                reason: format!("failed to write file: {e}"),
            })?;

        tracing::info!(
            bucket = %self.bucket,
            key = %self.key,
            bytes = data.len(),
            "S3 pull complete"
        );

        Ok(())
    }
}

/// Create an init action from the spec
///
/// # Errors
/// Returns `InitError::InvalidParams` if required parameters are missing or invalid,
/// or `InitError::UnknownAction` if the action type is not recognized.
#[allow(clippy::too_many_lines, clippy::implicit_hasher)]
pub fn from_spec(
    action: &str,
    params: &HashMap<String, serde_json::Value>,
    _default_timeout: Duration,
) -> Result<InitAction> {
    match action {
        "init.wait_tcp" => {
            let host = params
                .get("host")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'host' parameter".to_string(),
                })?
                .to_string();

            #[allow(clippy::cast_possible_truncation)]
            let port = params
                .get("port")
                .and_then(serde_json::Value::as_u64)
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing or invalid 'port' parameter".to_string(),
                })? as u16;

            let timeout_secs = params
                .get("timeout")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(30);

            Ok(InitAction::WaitTcp(WaitTcp {
                host,
                port,
                timeout: Duration::from_secs(timeout_secs),
                interval: Duration::from_secs(2),
            }))
        }

        "init.wait_http" => {
            let url = params
                .get("url")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'url' parameter".to_string(),
                })?
                .to_string();

            #[allow(clippy::cast_possible_truncation)]
            let expect_status = params
                .get("expect_status")
                .and_then(serde_json::Value::as_u64)
                .map(|v| v as u16);

            let timeout_secs = params
                .get("timeout")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(30);

            Ok(InitAction::WaitHttp(WaitHttp {
                url,
                expect_status,
                timeout: Duration::from_secs(timeout_secs),
                interval: Duration::from_secs(2),
            }))
        }

        "init.run" => {
            let command = params
                .get("command")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'command' parameter".to_string(),
                })?
                .to_string();

            let timeout_secs = params
                .get("timeout")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(300);

            Ok(InitAction::Run(RunCommand {
                command,
                timeout: Duration::from_secs(timeout_secs),
            }))
        }

        #[cfg(feature = "s3")]
        "init.s3_push" => {
            let source = params
                .get("source")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'source' parameter".to_string(),
                })?
                .to_string();

            let bucket = params
                .get("bucket")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'bucket' parameter".to_string(),
                })?
                .to_string();

            let key = params
                .get("key")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'key' parameter".to_string(),
                })?
                .to_string();

            let endpoint = params
                .get("endpoint")
                .and_then(|v| v.as_str())
                .map(String::from);
            let region = params
                .get("region")
                .and_then(|v| v.as_str())
                .map(String::from);
            let timeout_secs = params
                .get("timeout")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(300);

            Ok(InitAction::S3Push(S3Push {
                source,
                bucket,
                key,
                endpoint,
                region,
                timeout: Duration::from_secs(timeout_secs),
            }))
        }

        #[cfg(feature = "s3")]
        "init.s3_pull" => {
            let bucket = params
                .get("bucket")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'bucket' parameter".to_string(),
                })?
                .to_string();

            let key = params
                .get("key")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'key' parameter".to_string(),
                })?
                .to_string();

            let destination = params
                .get("destination")
                .and_then(|v| v.as_str())
                .ok_or_else(|| InitError::InvalidParams {
                    action: action.to_string(),
                    reason: "missing 'destination' parameter".to_string(),
                })?
                .to_string();

            let endpoint = params
                .get("endpoint")
                .and_then(|v| v.as_str())
                .map(String::from);
            let region = params
                .get("region")
                .and_then(|v| v.as_str())
                .map(String::from);
            let timeout_secs = params
                .get("timeout")
                .and_then(serde_json::Value::as_u64)
                .unwrap_or(300);

            Ok(InitAction::S3Pull(S3Pull {
                bucket,
                key,
                destination,
                endpoint,
                region,
                timeout: Duration::from_secs(timeout_secs),
            }))
        }

        _ => Err(InitError::UnknownAction(action.to_string())),
    }
}

/// Enum of all init actions
pub enum InitAction {
    WaitTcp(WaitTcp),
    WaitHttp(WaitHttp),
    Run(RunCommand),
    #[cfg(feature = "s3")]
    S3Push(S3Push),
    #[cfg(feature = "s3")]
    S3Pull(S3Pull),
}

impl InitAction {
    /// # Errors
    /// Returns an error if the underlying action fails.
    pub async fn execute(&self) -> Result<()> {
        match self {
            InitAction::WaitTcp(a) => a.execute().await,
            InitAction::WaitHttp(a) => a.execute().await,
            InitAction::Run(a) => a.execute().await,
            #[cfg(feature = "s3")]
            InitAction::S3Push(a) => a.execute().await,
            #[cfg(feature = "s3")]
            InitAction::S3Pull(a) => a.execute().await,
        }
    }
}

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

    #[tokio::test]
    async fn test_run_command_success() {
        let action = RunCommand {
            command: "echo hello".to_string(),
            timeout: Duration::from_secs(5),
        };
        action.execute().await.unwrap();
    }

    #[tokio::test]
    async fn test_run_command_failure() {
        let action = RunCommand {
            command: "exit 1".to_string(),
            timeout: Duration::from_secs(5),
        };
        let result = action.execute().await;
        assert!(result.is_err());
    }

    #[test]
    fn test_from_spec_wait_tcp() {
        let mut params = HashMap::new();
        params.insert("host".to_string(), serde_json::json!("localhost"));
        params.insert("port".to_string(), serde_json::json!(8080));

        let action = from_spec("init.wait_tcp", &params, Duration::from_secs(30)).unwrap();
        match action {
            InitAction::WaitTcp(_) => {}
            _ => panic!("Expected WaitTcp action"),
        }
    }

    #[test]
    fn test_from_spec_unknown() {
        let params = HashMap::new();
        let result = from_spec("unknown.action", &params, Duration::from_secs(30));
        assert!(result.is_err());
    }
}