rash_core 2.20.0

Declarative shell scripting using Rust native bindings
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
/// ANCHOR: module
/// # dpkg_selections
///
/// Manage Debian package selections (hold/unhold packages).
///
/// ## Description
///
/// This module manages dpkg selections for Debian packages. It allows you to
/// set packages to be held, unheld, installed, deinstalled, or purged.
/// This is useful for preventing automatic package updates, locking package
/// versions, or managing package states during system configuration.
///
/// ## Attributes
///
/// ```yaml
/// check_mode:
///   support: full
/// ```
/// ANCHOR_END: module
/// ANCHOR: examples
/// ## Example
///
/// ```yaml
/// - name: Hold nginx package to prevent updates
///   dpkg_selections:
///     name: nginx
///     selection: hold
///
/// - name: Hold multiple packages
///   dpkg_selections:
///     name:
///       - nginx
///       - docker-ce
///       - kernel-package
///     selection: hold
///
/// - name: Unhold a package to allow updates
///   dpkg_selections:
///     name: nginx
///     selection: install
///
/// - name: Query current package selections
///   dpkg_selections:
///     name: nginx
///   register: nginx_status
///
/// - name: Mark package for removal
///   dpkg_selections:
///     name: old-package
///     selection: deinstall
/// ```
/// ANCHOR_END: examples
use crate::context::GlobalParams;
use crate::error::{Error, ErrorKind, Result};
use crate::logger;
use crate::modules::{Module, ModuleResult, parse_params};

#[cfg(feature = "docs")]
use rash_derive::DocJsonSchema;

use minijinja::Value;
#[cfg(feature = "docs")]
use schemars::{JsonSchema, Schema};
use serde::Deserialize;
use serde_norway::Value as YamlValue;
use serde_norway::value;
use serde_with::{OneOrMany, serde_as};
use std::path::PathBuf;
use std::process::Command;

fn default_executable() -> Option<String> {
    Some("dpkg".to_owned())
}

#[derive(Clone, Debug, Default, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(JsonSchema))]
#[serde(rename_all = "lowercase")]
pub enum Selection {
    Install,
    Hold,
    Deinstall,
    Purge,
    #[default]
    Unhold,
}

impl Selection {
    fn as_str(&self) -> &'static str {
        match self {
            Selection::Install => "install",
            Selection::Hold => "hold",
            Selection::Deinstall => "deinstall",
            Selection::Purge => "purge",
            Selection::Unhold => "install",
        }
    }
}

#[serde_as]
#[derive(Debug, PartialEq, Deserialize)]
#[cfg_attr(feature = "docs", derive(JsonSchema, DocJsonSchema))]
#[serde(deny_unknown_fields)]
pub struct Params {
    /// Path of the binary to use.
    /// **[default: `"dpkg"`]**
    #[serde(default = "default_executable")]
    executable: Option<String>,
    /// Name or list of names of packages.
    #[serde_as(deserialize_as = "OneOrMany<_>")]
    #[serde(default)]
    pub name: Vec<String>,
    /// The selection state to set. Valid values: `install`, `hold`, `deinstall`, `purge`.
    /// Using `unhold` is equivalent to `install`.
    /// **[default: `"install"`]**
    pub selection: Option<Selection>,
}

struct DpkgClient {
    executable: PathBuf,
    check_mode: bool,
}

impl DpkgClient {
    pub fn new(params: &Params, check_mode: bool) -> Result<Self> {
        Ok(DpkgClient {
            executable: PathBuf::from(params.executable.as_ref().unwrap()),
            check_mode,
        })
    }

    fn get_current_selection(&self, package: &str) -> Result<Option<String>> {
        let output = Command::new(&self.executable)
            .arg("--get-selections")
            .arg(package)
            .output()
            .map_err(|e| {
                Error::new(
                    ErrorKind::SubprocessFail,
                    format!(
                        "Failed to execute {} --get-selections: {}",
                        self.executable.display(),
                        e
                    ),
                )
            })?;

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

        if trimmed.is_empty() || !output.status.success() {
            return Ok(None);
        }

        let parts: Vec<&str> = trimmed.split_whitespace().collect();
        if parts.len() >= 2 && parts[0] == package {
            Ok(Some(parts[1].to_string()))
        } else {
            Ok(None)
        }
    }

    fn set_selection(&self, package: &str, selection: &str) -> Result<()> {
        if self.check_mode {
            return Ok(());
        }

        let input = format!("{} {}", package, selection);

        let child = Command::new(&self.executable)
            .arg("--set-selections")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .spawn()
            .map_err(|e| {
                Error::new(
                    ErrorKind::SubprocessFail,
                    format!(
                        "Failed to execute {} --set-selections: {}",
                        self.executable.display(),
                        e
                    ),
                )
            })?;

        if let Some(mut stdin) = child.stdin.as_ref() {
            use std::io::Write;
            writeln!(stdin, "{}", input).map_err(|e| {
                Error::new(
                    ErrorKind::SubprocessFail,
                    format!(
                        "Failed to write to {} --set-selections: {}",
                        self.executable.display(),
                        e
                    ),
                )
            })?;
        }

        let output = child.wait_with_output().map_err(|e| {
            Error::new(
                ErrorKind::SubprocessFail,
                format!(
                    "Failed to wait for {} --set-selections: {}",
                    self.executable.display(),
                    e
                ),
            )
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(Error::new(
                ErrorKind::SubprocessFail,
                format!(
                    "{} --set-selections failed: {}",
                    self.executable.display(),
                    stderr
                ),
            ));
        }

        Ok(())
    }
}

fn dpkg_selections_impl(params: Params, check_mode: bool) -> Result<ModuleResult> {
    if params.name.is_empty() {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "name parameter is required",
        ));
    }

    let packages: Vec<&str> = params.name.iter().map(|s| s.trim()).collect();

    for pkg in &packages {
        if pkg.is_empty() {
            return Err(Error::new(
                ErrorKind::InvalidData,
                "package name cannot be empty",
            ));
        }
    }

    let client = DpkgClient::new(&params, check_mode)?;
    let selection = params.selection.unwrap_or_default();
    let selection_str = selection.as_str();

    let mut changed_packages: Vec<String> = Vec::new();
    let mut unchanged_packages: Vec<String> = Vec::new();
    let mut current_selections: Vec<(String, String)> = Vec::new();

    for package in &packages {
        let current = client.get_current_selection(package)?;

        current_selections.push((
            package.to_string(),
            current.clone().unwrap_or_else(|| "unknown".to_string()),
        ));

        if let Some(ref current_sel) = current
            && current_sel == selection_str
        {
            unchanged_packages.push(package.to_string());
            continue;
        }

        changed_packages.push(package.to_string());

        client.set_selection(package, selection_str)?;
    }

    let changed = !changed_packages.is_empty();

    if changed {
        logger::add(&changed_packages);
    }

    let extra = Some(value::to_value(json!({
        "packages": packages.iter().map(|s| s.to_string()).collect::<Vec<String>>(),
        "selection": selection_str,
        "changed_packages": changed_packages,
        "unchanged_packages": unchanged_packages,
        "current_selections": current_selections,
    }))?);

    Ok(ModuleResult {
        changed,
        output: None,
        extra,
    })
}

#[derive(Debug)]
pub struct DpkgSelections;

impl Module for DpkgSelections {
    fn get_name(&self) -> &str {
        "dpkg_selections"
    }

    fn exec(
        &self,
        _global_params: &GlobalParams,
        optional_params: YamlValue,
        _vars: &Value,
        check_mode: bool,
    ) -> Result<(ModuleResult, Option<Value>)> {
        let params: Params = parse_params(optional_params)?;
        Ok((dpkg_selections_impl(params, check_mode)?, None))
    }

    fn force_string_on_params(&self) -> bool {
        false
    }

    #[cfg(feature = "docs")]
    fn get_json_schema(&self) -> Option<Schema> {
        Some(Params::get_json_schema())
    }
}

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

    #[test]
    fn test_parse_params_single_package() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: nginx
            selection: hold
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.name, vec!["nginx".to_string()]);
        assert_eq!(params.selection, Some(Selection::Hold));
    }

    #[test]
    fn test_parse_params_multiple_packages() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name:
              - nginx
              - docker-ce
            selection: hold
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(
            params.name,
            vec!["nginx".to_string(), "docker-ce".to_string()]
        );
        assert_eq!(params.selection, Some(Selection::Hold));
    }

    #[test]
    fn test_parse_params_no_selection() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: nginx
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.name, vec!["nginx".to_string()]);
        assert_eq!(params.selection, None);
    }

    #[test]
    fn test_parse_params_install() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: nginx
            selection: install
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.selection, Some(Selection::Install));
    }

    #[test]
    fn test_parse_params_deinstall() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: old-package
            selection: deinstall
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.selection, Some(Selection::Deinstall));
    }

    #[test]
    fn test_parse_params_purge() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: old-package
            selection: purge
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.selection, Some(Selection::Purge));
    }

    #[test]
    fn test_parse_params_unhold() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: nginx
            selection: unhold
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.selection, Some(Selection::Unhold));
    }

    #[test]
    fn test_parse_params_unknown_field() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: nginx
            unknown: field
            "#,
        )
        .unwrap();
        let error = parse_params::<Params>(yaml).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn test_selection_as_str() {
        assert_eq!(Selection::Install.as_str(), "install");
        assert_eq!(Selection::Hold.as_str(), "hold");
        assert_eq!(Selection::Deinstall.as_str(), "deinstall");
        assert_eq!(Selection::Purge.as_str(), "purge");
        assert_eq!(Selection::Unhold.as_str(), "install");
    }

    #[test]
    fn test_parse_params_empty_name() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            name: []
            selection: hold
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert!(params.name.is_empty());
    }

    #[test]
    fn test_parse_params_executable() {
        let yaml: YamlValue = serde_norway::from_str(
            r#"
            executable: /usr/bin/dpkg
            name: nginx
            selection: hold
            "#,
        )
        .unwrap();
        let params: Params = parse_params(yaml).unwrap();
        assert_eq!(params.executable, Some("/usr/bin/dpkg".to_string()));
        assert_eq!(params.name, vec!["nginx".to_string()]);
        assert_eq!(params.selection, Some(Selection::Hold));
    }
}