rscni 0.1.0

CNI plugin library for Rust
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
use std::io::Write;

use crate::{
    error::Error,
    types::{Args, CNIResult, Cmd},
    util::{Env, Io, OsEnv, StdIo},
    version::PluginInfo,
};

/// The core trait for implementing a CNI plugin.
///
/// Implement this trait to define the behavior of your CNI plugin for the
/// ADD, DEL, and CHECK operations as specified by the CNI specification.
///
/// # CNI Operations
///
/// - **ADD**: Called when a container is created. Set up the network interface.
/// - **DEL**: Called when a container is deleted. Clean up the network interface.
/// - **CHECK**: Called to verify that the network configuration is as expected.
///
/// # Example
///
/// ```rust
/// use rscni::{cni::Cni, error::Error, types::{Args, CNIResult}};
///
/// struct MyPlugin;
///
/// impl Cni for MyPlugin {
///     fn add(&self, args: Args) -> Result<CNIResult, Error> {
///         // Network setup logic
///         Ok(CNIResult::default())
///     }
///
///     fn del(&self, args: Args) -> Result<CNIResult, Error> {
///         // Network cleanup logic
///         Ok(CNIResult::default())
///     }
///
///     fn check(&self, args: Args) -> Result<CNIResult, Error> {
///         // Network verification logic
///         Ok(CNIResult::default())
///     }
/// }
/// ```
pub trait Cni {
    /// Executes the ADD command for the CNI plugin.
    /// <https://github.com/containernetworking/cni/blob/v1.1.0/SPEC.md#add-add-container-to-network-or-apply-modifications>
    ///
    /// This method is called when a container is created and needs network connectivity.
    /// It should set up the network interface, assign IP addresses, configure routes, etc.
    ///
    /// # Arguments
    ///
    /// * `args` - Contains all CNI parameters including container ID, network namespace,
    ///   interface name, and network configuration from stdin.
    ///
    /// # Returns
    ///
    /// Returns a [`CNIResult`](../types/struct.CNIResult.html) containing the network configuration
    /// that was created (interfaces, IPs, routes, DNS).
    ///
    /// # Errors
    ///
    /// Returns an error if the ADD operation fails.
    fn add(&self, args: Args) -> Result<CNIResult, Error>;

    /// Executes the DEL command for the CNI plugin.
    /// <https://github.com/containernetworking/cni/blob/v1.1.0/SPEC.md#del-remove-container-from-network-or-un-apply-modifications>
    ///
    /// This method is called when a container is being deleted and should clean up
    /// all network resources that were created during the ADD operation.
    ///
    /// # Arguments
    ///
    /// * `args` - Contains all CNI parameters needed to identify and clean up the network.
    ///
    /// # Returns
    ///
    /// Returns an empty [`CNIResult`](../types/struct.CNIResult.html) on success.
    ///
    /// # Errors
    ///
    /// Returns an error if the DEL operation fails.
    fn del(&self, args: Args) -> Result<CNIResult, Error>;

    /// Executes the CHECK command for the CNI plugin.
    /// <https://github.com/containernetworking/cni/blob/v1.1.0/SPEC.md#check-check-containers-networking-is-as-expected>
    ///
    /// This method verifies that the network configuration is still correct and matches
    /// what was configured during ADD.
    ///
    /// # Arguments
    ///
    /// * `args` - Contains all CNI parameters and the previous result to check against.
    ///
    /// # Returns
    ///
    /// Returns an empty [`CNIResult`](../types/struct.CNIResult.html) on success.
    ///
    /// # Errors
    ///
    /// Returns an error if the CHECK operation fails.
    fn check(&self, args: Args) -> Result<CNIResult, Error>;
}

/// The main entry point for a CNI plugin.
///
/// `Plugin` handles all the CNI protocol details including:
/// - Reading CNI environment variables
/// - Parsing network configuration from stdin
/// - Version negotiation
/// - Routing commands (ADD/DEL/CHECK/VERSION) to the appropriate handler
/// - Writing results to stdout
///
/// # Example
///
/// ```rust,no_run
/// # use rscni::{cni::{Cni, Plugin}, error::Error, types::{Args, CNIResult}};
/// #
/// # struct MyPlugin;
/// # impl Cni for MyPlugin {
/// #     fn add(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
/// #     fn del(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
/// #     fn check(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
/// # }
/// #
/// let plugin = Plugin::default().msg("MyPlugin v1.0.0");
/// let my_plugin = MyPlugin;
/// plugin.run(&my_plugin).expect("Failed to run plugin");
/// ```
#[derive(Debug, Default)]
pub struct Plugin {
    info: PluginInfo,
    msg: Option<String>,
}

impl Plugin {
    /// Creates a new `Plugin` with custom CNI version support.
    ///
    /// # Arguments
    ///
    /// * `ver` - The primary CNI version this plugin uses (e.g., "1.1.0")
    /// * `versions` - List of all CNI versions this plugin supports
    ///
    /// # Example
    ///
    /// ```rust
    /// use rscni::cni::Plugin;
    ///
    /// let plugin = Plugin::new(
    ///     "1.1.0",
    ///     vec!["1.0.0".to_string(), "1.1.0".to_string()]
    /// );
    /// ```
    #[must_use]
    pub fn new(ver: &str, versions: Vec<String>) -> Self {
        Self {
            info: PluginInfo::new(ver, versions),
            msg: None,
        }
    }

    /// Sets an optional message to display with version information.
    ///
    /// This message is shown when the plugin is called with the VERSION command.
    ///
    /// # Arguments
    ///
    /// * `msg` - A description or version string for your plugin
    ///
    /// # Example
    ///
    /// ```rust
    /// use rscni::cni::Plugin;
    ///
    /// let plugin = Plugin::default()
    ///     .msg("MyPlugin v1.0.0 - CNI plugin");
    /// ```
    #[must_use]
    pub fn msg(mut self, msg: &str) -> Self {
        self.msg = Some(msg.to_string());
        self
    }

    /// Runs the CNI plugin by processing the CNI command and executing the appropriate operation.
    ///
    /// This method:
    /// 1. Reads the `CNI_COMMAND` environment variable
    /// 2. Routes to ADD/DEL/CHECK/VERSION based on the command
    /// 3. Calls the appropriate method on your `Cni` implementation
    /// 4. Writes the result to stdout in JSON format
    ///
    /// # Arguments
    ///
    /// * `cni` - A reference to your `Cni` trait implementation
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if any step fails.
    ///
    /// # Errors
    ///
    /// This method can return errors for various reasons:
    /// - Missing or invalid CNI environment variables
    /// - Invalid network configuration on stdin
    /// - CNI version mismatch
    /// - Errors from your `Cni` implementation
    /// - I/O errors writing to stdout
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// # use rscni::{cni::{Cni, Plugin}, error::Error, types::{Args, CNIResult}};
    /// #
    /// # struct MyPlugin;
    /// # impl Cni for MyPlugin {
    /// #     fn add(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
    /// #     fn del(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
    /// #     fn check(&self, args: Args) -> Result<CNIResult, Error> { Ok(CNIResult::default()) }
    /// # }
    /// #
    /// let plugin = Plugin::default();
    /// let my_plugin = MyPlugin;
    ///
    /// if let Err(e) = plugin.run(&my_plugin) {
    ///     eprintln!("CNI plugin failed: {}", e);
    ///     std::process::exit(1);
    /// }
    /// ```
    pub fn run<T: Cni>(&self, cni: &T) -> Result<(), Error> {
        let res = self.inner_run::<T, OsEnv, StdIo>(cni)?;

        StdIo::io_out()
            .write_all(res.as_bytes())
            .map_err(|e| Error::IOFailure(e.to_string()))
    }

    fn inner_run<C: Cni, E: Env, I: Io>(&self, cni: &C) -> Result<String, Error> {
        let cmd = Cmd::get_from_env::<E>()?;

        match cmd {
            Cmd::Add => {
                let args = Args::build::<E, I>()?;
                if let Some(conf) = &args.config {
                    self.info.validate(&conf.cni_version)?;
                }
                let res = cni.add(args)?;
                serde_json::to_string(&res).map_err(|e| Error::FailedToDecode(e.to_string()))
            }
            Cmd::Del => {
                let args = Args::build::<E, I>()?;
                if let Some(conf) = &args.config {
                    self.info.validate(&conf.cni_version)?;
                }
                let res = cni.del(args)?;
                serde_json::to_string(&res).map_err(|e| Error::FailedToDecode(e.to_string()))
            }
            Cmd::Check => {
                let args = Args::build::<E, I>()?;
                if let Some(conf) = &args.config {
                    self.info.validate(&conf.cni_version)?;
                }
                let res = cni.check(args)?;
                serde_json::to_string(&res).map_err(|e| Error::FailedToDecode(e.to_string()))
            }
            Cmd::Version => self.info.version(),
            Cmd::UnSet => Ok(self.info.about(self.msg.clone())),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{Dns, Interface, IpConfig, NetConf, Route};
    use rstest::rstest;
    use std::cell::RefCell;
    use std::collections::HashMap;
    use std::io::{Cursor, Read, Write};
    use std::str::FromStr;

    // Thread-local storage for mock environment variables
    thread_local! {
        static MOCK_ENV: RefCell<HashMap<String, String>> = RefCell::new(HashMap::new());
    }

    // Mock Env implementation
    struct MockEnv;

    impl Env for MockEnv {
        fn get<T>(name: &str) -> Result<T, Error>
        where
            T: FromStr,
            T::Err: std::error::Error + 'static,
        {
            MOCK_ENV.with(|env| {
                env.borrow()
                    .get(name)
                    .ok_or_else(|| Error::InvalidEnvValue(format!("env var not found: {}", name)))
                    .and_then(|v| {
                        v.parse::<T>()
                            .map_err(|e| Error::InvalidEnvValue(e.to_string()))
                    })
            })
        }
    }

    // Thread-local storage for mock I/O
    thread_local! {
        static MOCK_INPUT: RefCell<Vec<u8>> = RefCell::new(Vec::new());
    }

    struct MockIo;

    impl Io for MockIo {
        fn io_in() -> impl Read {
            MOCK_INPUT.with(|input| {
                let data = input.borrow().clone();
                Cursor::new(data)
            })
        }

        fn io_out() -> impl Write {
            Vec::new()
        }

        fn io_err() -> impl Write {
            Vec::new()
        }
    }

    // Helper function to set mock environment variable
    fn set_mock_env(key: &str, value: &str) {
        MOCK_ENV.with(|env| {
            env.borrow_mut().insert(key.to_string(), value.to_string());
        });
    }

    // Helper function to set mock input
    fn set_mock_input(data: &str) {
        MOCK_INPUT.with(|input| {
            *input.borrow_mut() = data.as_bytes().to_vec();
        });
    }

    // Helper function to clear mock environment
    fn clear_mock_env() {
        MOCK_ENV.with(|env| {
            env.borrow_mut().clear();
        });
    }

    // Helper function to clear mock input
    fn clear_mock_input() {
        MOCK_INPUT.with(|input| {
            input.borrow_mut().clear();
        });
    }

    // Mock Cni implementation
    struct MockCni;

    impl Cni for MockCni {
        fn add(&self, _args: Args) -> Result<CNIResult, Error> {
            Ok(CNIResult {
                interfaces: vec![Interface {
                    name: "eth0".to_string(),
                    mac: "00:11:22:33:44:55".to_string(),
                    sandbox: Some("/var/run/netns/test".to_string()),
                }],
                ips: vec![IpConfig {
                    interface: Some(0),
                    address: "10.1.0.5/16".to_string(),
                    gateway: Some("10.1.0.1".to_string()),
                }],
                routes: vec![Route {
                    dst: "0.0.0.0/0".to_string(),
                    gw: Some("10.1.0.1".to_string()),
                    mtu: None,
                    advmss: None,
                }],
                dns: Some(Dns {
                    nameservers: vec!["10.1.0.1".to_string()],
                    domain: None,
                    search: None,
                    options: None,
                }),
            })
        }

        fn del(&self, _args: Args) -> Result<CNIResult, Error> {
            Ok(CNIResult::default())
        }

        fn check(&self, _args: Args) -> Result<CNIResult, Error> {
            Ok(CNIResult::default())
        }
    }

    #[rstest]
    #[case("ADD")]
    #[case("DEL")]
    #[case("CHECK")]
    fn test_plugin_inner_run_commands(#[case] command: &str) {
        clear_mock_env();
        clear_mock_input();

        set_mock_env("CNI_COMMAND", command);
        set_mock_env("CNI_CONTAINERID", "test-container");
        set_mock_env("CNI_NETNS", "/var/run/netns/test");
        set_mock_env("CNI_IFNAME", "eth0");
        set_mock_env("CNI_PATH", "/opt/cni/bin");
        set_mock_env("CNI_ARGS", "");

        let config = NetConf {
            cni_version: "1.0.0".to_string(),
            name: "test-network".to_string(),
            r#type: "test".to_string(),
            ..Default::default()
        };
        set_mock_input(&serde_json::to_string(&config).unwrap());

        let plugin = Plugin::default();
        let mock_cni = MockCni;

        let result = plugin.inner_run::<MockCni, MockEnv, MockIo>(&mock_cni);
        assert!(result.is_ok(), "Command {} should succeed", command);

        let json_output = result.unwrap();
        assert!(!json_output.is_empty());
    }

    #[test]
    fn test_plugin_inner_run_version() {
        clear_mock_env();
        set_mock_env("CNI_COMMAND", "VERSION");

        let plugin = Plugin::default();
        let mock_cni = MockCni;

        let result = plugin.inner_run::<MockCni, MockEnv, MockIo>(&mock_cni);
        assert!(result.is_ok());

        let json_output = result.unwrap();
        assert!(json_output.contains("cniVersion"));
        assert!(json_output.contains("supportedVersions"));
    }

    #[test]
    fn test_plugin_inner_run_unset() {
        clear_mock_env();
        set_mock_env("CNI_COMMAND", "");

        let plugin = Plugin::default().msg("Test Plugin v1.0.0");
        let mock_cni = MockCni;

        let result = plugin.inner_run::<MockCni, MockEnv, MockIo>(&mock_cni);
        assert!(result.is_ok());

        let output = result.unwrap();
        assert!(output.contains("Test Plugin v1.0.0"));
    }

    #[test]
    fn test_plugin_inner_run_version_mismatch() {
        clear_mock_env();
        clear_mock_input();

        set_mock_env("CNI_COMMAND", "ADD");
        set_mock_env("CNI_CONTAINERID", "test-container");
        set_mock_env("CNI_NETNS", "/var/run/netns/test");
        set_mock_env("CNI_IFNAME", "eth0");
        set_mock_env("CNI_PATH", "/opt/cni/bin");
        set_mock_env("CNI_ARGS", "");

        // Plugin supports 1.0.0, but config specifies 0.4.0
        let config = NetConf {
            cni_version: "0.4.0".to_string(),
            name: "test-network".to_string(),
            r#type: "test".to_string(),
            ..Default::default()
        };
        set_mock_input(&serde_json::to_string(&config).unwrap());

        let plugin = Plugin::new("1.0.0", vec!["1.0.0".to_string()]);
        let mock_cni = MockCni;

        let result = plugin.inner_run::<MockCni, MockEnv, MockIo>(&mock_cni);
        assert!(result.is_err());
        if let Err(Error::IncompatibleVersion(_)) = result {
            // Expected error
        } else {
            panic!("Expected IncompatibleVersion error");
        }
    }
}