Skip to main content

capsule/
config.rs

1/*
2* Copyright 2019 Comcast Cable Communications Management, LLC
3*
4* Licensed under the Apache License, Version 2.0 (the "License");
5* you may not use this file except in compliance with the License.
6* You may obtain a copy of the License at
7*
8* http://www.apache.org/licenses/LICENSE-2.0
9*
10* Unless required by applicable law or agreed to in writing, software
11* distributed under the License is distributed on an "AS IS" BASIS,
12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13* See the License for the specific language governing permissions and
14* limitations under the License.
15*
16* SPDX-License-Identifier: Apache-2.0
17*/
18
19//! Toml-based configuration for use with Capsule applications.
20//!
21//! # Example
22//!
23//! A configuration from our [`pktdump`] example:
24//! ```
25//! app_name = "pktdump"
26//! master_core = 0
27//! duration = 5
28//!
29//! [mempool]
30//!     capacity = 65535
31//!     cache_size = 256
32//!
33//! [[ports]]
34//!     name = "eth1"
35//!     device = "net_pcap0"
36//!     args = "rx_pcap=tcp4.pcap,tx_iface=lo"
37//!     cores = [0]
38//!
39//! [[ports]]
40//!     name = "eth2"
41//!     device = "net_pcap1"
42//!     args = "rx_pcap=tcp6.pcap,tx_iface=lo"
43//!     cores = [0]
44//! ```
45//!
46//! [`pktdump`]: https://github.com/capsule-rs/capsule/tree/master/examples/pktdump
47
48use crate::dpdk::CoreId;
49use crate::net::{Ipv4Cidr, Ipv6Cidr, MacAddr};
50use anyhow::Result;
51use clap::{clap_app, crate_version};
52use regex::Regex;
53use serde::{de, Deserialize, Deserializer};
54use std::fmt;
55use std::fs;
56use std::str::FromStr;
57use std::time::Duration;
58
59// make `CoreId` serde deserializable.
60impl<'de> Deserialize<'de> for CoreId {
61    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
62    where
63        D: Deserializer<'de>,
64    {
65        let i = usize::deserialize(deserializer)?;
66        Ok(CoreId::new(i))
67    }
68}
69
70// make `MacAddr` serde deserializable.
71impl<'de> Deserialize<'de> for MacAddr {
72    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
73    where
74        D: Deserializer<'de>,
75    {
76        let s = String::deserialize(deserializer)?;
77        MacAddr::from_str(&s).map_err(de::Error::custom)
78    }
79}
80
81// make `Ipv4Cidr` serde deserializable.
82impl<'de> Deserialize<'de> for Ipv4Cidr {
83    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
84    where
85        D: Deserializer<'de>,
86    {
87        let s = String::deserialize(deserializer)?;
88        Ipv4Cidr::from_str(&s).map_err(de::Error::custom)
89    }
90}
91
92// make `Ipv6Cidr` serde deserializable.
93impl<'de> Deserialize<'de> for Ipv6Cidr {
94    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
95    where
96        D: Deserializer<'de>,
97    {
98        let s = String::deserialize(deserializer)?;
99        Ipv6Cidr::from_str(&s).map_err(de::Error::custom)
100    }
101}
102
103/// Deserializes a duration from seconds expressed as `u64`.
104pub fn duration_from_secs<'de, D>(deserializer: D) -> Result<Duration, D::Error>
105where
106    D: Deserializer<'de>,
107{
108    let secs = u64::deserialize(deserializer)?;
109    Ok(Duration::from_secs(secs))
110}
111
112/// Deserializes an option of duration from seconds expressed as `u64`.
113pub fn duration_option_from_secs<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
114where
115    D: Deserializer<'de>,
116{
117    // for now this is the cleanest way to deserialize an option, till a better
118    // way is implemented, https://github.com/serde-rs/serde/issues/723
119    #[derive(Deserialize)]
120    struct Wrapper(#[serde(deserialize_with = "duration_from_secs")] Duration);
121
122    let option = Option::deserialize(deserializer)?.and_then(|Wrapper(dur)| {
123        if dur.as_secs() > 0 {
124            Some(dur)
125        } else {
126            None
127        }
128    });
129    Ok(option)
130}
131
132/// Runtime configuration settings.
133#[derive(Clone, Deserialize)]
134#[serde(deny_unknown_fields)]
135pub struct RuntimeConfig {
136    /// Application name. This must be unique if you want to run multiple
137    /// DPDK applications on the same system.
138    pub app_name: String,
139
140    /// Indicating whether the process is a secondary process. Secondary
141    /// process cannot initialize shared memory, but can attach to pre-
142    /// initialized shared memory by the primary process and create objects
143    /// in it. Defaults to `false`.
144    #[serde(default)]
145    pub secondary: bool,
146
147    /// Application group name. Use this to group primary and secondary
148    /// processes together in a multi-process setup; and allow them to share
149    /// the same memory regions. The default value is the `app_name`. Each
150    /// process works independently.
151    #[serde(default)]
152    pub app_group: Option<String>,
153
154    /// The identifier of the master core. This is the core the main thread
155    /// will run on.
156    pub master_core: CoreId,
157
158    /// Additional cores that are available to the application, and can be
159    /// used for running general tasks. Packet pipelines cannot be run on
160    /// these cores unless the core is also assigned to a port separately.
161    /// Defaults to empty list.
162    #[serde(default)]
163    pub cores: Vec<CoreId>,
164
165    /// Per mempool settings. On a system with multiple sockets, aka NUMA
166    /// nodes, one mempool will be allocated for each socket the apllication
167    /// uses.
168    #[serde(default)]
169    pub mempool: MempoolConfig,
170
171    /// The ports to use for the application. Must have at least one.
172    pub ports: Vec<PortConfig>,
173
174    /// Additional DPDK [`parameters`] to pass on for EAL initialization. When
175    /// set, the values are passed through as is without validation.
176    ///
177    /// [`parameters`]: https://doc.dpdk.org/guides/linux_gsg/linux_eal_parameters.html
178    #[serde(default)]
179    pub dpdk_args: Option<String>,
180
181    /// If set, the application will stop after the duration expires. Useful
182    /// for setting a timeout for integration tests.
183    #[serde(default, deserialize_with = "duration_option_from_secs")]
184    pub duration: Option<Duration>,
185}
186
187impl RuntimeConfig {
188    /// Returns all the cores assigned to the runtime.
189    pub(crate) fn all_cores(&self) -> Vec<CoreId> {
190        let mut cores = vec![];
191        cores.push(self.master_core);
192        cores.extend(self.cores.iter());
193
194        self.ports.iter().for_each(|port| {
195            cores.extend(port.cores.iter());
196        });
197
198        cores.sort();
199        cores.dedup();
200        cores
201    }
202
203    /// Extracts the EAL arguments from runtime settings.
204    pub(crate) fn to_eal_args(&self) -> Vec<String> {
205        let mut eal_args = vec![];
206
207        // adds the app name
208        eal_args.push(self.app_name.clone());
209
210        let proc_type = if self.secondary {
211            "secondary".to_owned()
212        } else {
213            "primary".to_owned()
214        };
215
216        // adds the proc type
217        eal_args.push("--proc-type".to_owned());
218        eal_args.push(proc_type);
219
220        // adds the mem file prefix
221        let prefix = self.app_group.as_ref().unwrap_or(&self.app_name);
222        eal_args.push("--file-prefix".to_owned());
223        eal_args.push(prefix.clone());
224
225        // adds all the ports
226        let pcie = Regex::new(r"^\d{4}:\d{2}:\d{2}\.\d$").unwrap();
227        self.ports.iter().for_each(|port| {
228            if pcie.is_match(port.device.as_str()) {
229                eal_args.push("--pci-whitelist".to_owned());
230                eal_args.push(port.device.clone());
231            } else {
232                let vdev = if let Some(args) = &port.args {
233                    format!("{},{}", port.device, args)
234                } else {
235                    port.device.clone()
236                };
237                eal_args.push("--vdev".to_owned());
238                eal_args.push(vdev);
239            }
240        });
241
242        // adds the master core
243        eal_args.push("--master-lcore".to_owned());
244        eal_args.push(self.master_core.raw().to_string());
245
246        // limits the EAL to only the master core. actual threads are
247        // managed by the runtime not the EAL.
248        eal_args.push("-l".to_owned());
249        eal_args.push(self.master_core.raw().to_string());
250
251        // adds additional DPDK args
252        if let Some(args) = &self.dpdk_args {
253            eal_args.extend(args.split_ascii_whitespace().map(str::to_owned));
254        }
255
256        eal_args
257    }
258
259    /// Returns the number of KNI enabled ports
260    pub(crate) fn num_knis(&self) -> usize {
261        self.ports.iter().filter(|p| p.kni).count()
262    }
263}
264
265impl fmt::Debug for RuntimeConfig {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        let mut d = f.debug_struct("runtime");
268        d.field("app_name", &self.app_name)
269            .field("secondary", &self.secondary)
270            .field(
271                "app_group",
272                self.app_group.as_ref().unwrap_or(&self.app_name),
273            )
274            .field("master_core", &self.master_core)
275            .field("cores", &self.cores)
276            .field("mempool", &self.mempool)
277            .field("ports", &self.ports);
278        if let Some(dpdk_args) = &self.dpdk_args {
279            d.field("dpdk_args", dpdk_args);
280        }
281        if let Some(duration) = &self.duration {
282            d.field("duration", duration);
283        }
284        d.finish()
285    }
286}
287
288/// Mempool configuration settings.
289#[derive(Clone, Deserialize)]
290pub struct MempoolConfig {
291    /// The maximum number of Mbufs the mempool can allocate. The optimum
292    /// size (in terms of memory usage) is when n is a power of two minus
293    /// one. Defaults to `65535` or `2 ^ 16 - 1`.
294    #[serde(default = "default_capacity")]
295    pub capacity: usize,
296
297    /// The size of the per core object cache. If cache_size is non-zero,
298    /// the library will try to limit the accesses to the common lockless
299    /// pool. The cache can be disabled if the argument is set to 0. Defaults
300    /// to `0`.
301    #[serde(default = "default_cache_size")]
302    pub cache_size: usize,
303}
304
305fn default_capacity() -> usize {
306    65535
307}
308
309fn default_cache_size() -> usize {
310    0
311}
312
313impl Default for MempoolConfig {
314    fn default() -> Self {
315        MempoolConfig {
316            capacity: default_capacity(),
317            cache_size: default_cache_size(),
318        }
319    }
320}
321
322impl fmt::Debug for MempoolConfig {
323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
324        f.debug_struct("mempool")
325            .field("capacity", &self.capacity)
326            .field("cache_size", &self.cache_size)
327            .finish()
328    }
329}
330
331/// Port configuration settings.
332#[derive(Clone, Deserialize)]
333pub struct PortConfig {
334    /// The application assigned logical name of the port.
335    ///
336    /// For applications with more than one port, this name can be used to
337    /// identifer the port.
338    pub name: String,
339
340    /// The device name of the port. It can be the following formats,
341    ///
342    ///   * PCIe address, for example `0000:02:00.0`
343    ///   * DPDK virtual device, for example `net_[pcap0|null0|tap0]`
344    pub device: String,
345
346    /// Additional arguments to configure a virtual device.
347    #[serde(default)]
348    pub args: Option<String>,
349
350    /// The cores assigned to the port for running the pipelines. The values
351    /// can overlap with the runtime cores.
352    pub cores: Vec<CoreId>,
353
354    /// The receive queue capacity. Defaults to `128`.
355    #[serde(default = "default_port_rxd")]
356    pub rxd: usize,
357
358    /// The transmit queue capacity. Defaults to `128`.
359    #[serde(default = "default_port_txd")]
360    pub txd: usize,
361
362    /// Whether promiscuous mode is enabled for this port. Defaults to `false`.
363    #[serde(default)]
364    pub promiscuous: bool,
365
366    /// Whether multicast packet reception is enabled for this port. Defaults
367    /// to `true`.
368    #[serde(default = "default_multicast_mode")]
369    pub multicast: bool,
370
371    /// Whether kernel NIC interface is enabled for this port. with KNI, this
372    /// port can exchange packets with the kernel networking stack. Defaults
373    /// to `false`.
374    #[serde(default)]
375    pub kni: bool,
376}
377
378fn default_port_rxd() -> usize {
379    128
380}
381
382fn default_port_txd() -> usize {
383    128
384}
385
386fn default_multicast_mode() -> bool {
387    true
388}
389
390impl fmt::Debug for PortConfig {
391    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
392        let mut d = f.debug_struct("port");
393        d.field("name", &self.name);
394        d.field("device", &self.device);
395        if let Some(args) = &self.args {
396            d.field("args", args);
397        }
398        d.field("cores", &self.cores)
399            .field("rxd", &self.rxd)
400            .field("txd", &self.txd)
401            .field("promiscuous", &self.promiscuous)
402            .field("multicast", &self.multicast)
403            .field("kni", &self.kni)
404            .finish()
405    }
406}
407
408/// Loads the app config from a TOML file.
409///
410/// # Example
411///
412/// ```
413/// home$ ./myapp -f config.toml
414/// ```
415pub fn load_config() -> Result<RuntimeConfig> {
416    let matches = clap_app!(capsule =>
417        (version: crate_version!())
418        (@arg file: -f --file +required +takes_value "configuration file")
419    )
420    .get_matches();
421
422    let path = matches.value_of("file").unwrap();
423    let content = fs::read_to_string(path)?;
424    toml::from_str(&content).map_err(|err| err.into())
425}
426
427#[cfg(test)]
428mod tests {
429    use super::*;
430
431    #[test]
432    fn config_defaults() {
433        const CONFIG: &str = r#"
434            app_name = "myapp"
435            master_core = 0
436
437            [[ports]]
438                name = "eth0"
439                device = "0000:00:01.0"
440                cores = [2, 3]
441        "#;
442
443        let config: RuntimeConfig = toml::from_str(CONFIG).unwrap();
444
445        assert_eq!(false, config.secondary);
446        assert_eq!(None, config.app_group);
447        assert!(config.cores.is_empty());
448        assert_eq!(None, config.dpdk_args);
449        assert_eq!(default_capacity(), config.mempool.capacity);
450        assert_eq!(default_cache_size(), config.mempool.cache_size);
451        assert_eq!(None, config.ports[0].args);
452        assert_eq!(default_port_rxd(), config.ports[0].rxd);
453        assert_eq!(default_port_txd(), config.ports[0].txd);
454        assert_eq!(false, config.ports[0].promiscuous);
455        assert_eq!(default_multicast_mode(), config.ports[0].multicast);
456        assert_eq!(false, config.ports[0].kni);
457    }
458
459    #[test]
460    fn config_to_eal_args() {
461        const CONFIG: &str = r#"
462            app_name = "myapp"
463            secondary = false
464            app_group = "mygroup"
465            master_core = 0
466            cores = [1]
467            dpdk_args = "-v --log-level eal:8"
468
469            [mempool]
470                capacity = 255
471                cache_size = 16
472
473            [[ports]]
474                name = "eth0"
475                device = "0000:00:01.0"
476                cores = [2, 3]
477                rxd = 32
478                txd = 32
479
480            [[ports]]
481                name = "eth1"
482                device = "net_pcap0"
483                args = "rx=lo,tx=lo"
484                cores = [0, 4]
485                rxd = 32
486                txd = 32
487        "#;
488
489        let config: RuntimeConfig = toml::from_str(CONFIG).unwrap();
490
491        assert_eq!(
492            &[
493                "myapp",
494                "--proc-type",
495                "primary",
496                "--file-prefix",
497                "mygroup",
498                "--pci-whitelist",
499                "0000:00:01.0",
500                "--vdev",
501                "net_pcap0,rx=lo,tx=lo",
502                "--master-lcore",
503                "0",
504                "-l",
505                "0",
506                "-v",
507                "--log-level",
508                "eal:8"
509            ],
510            config.to_eal_args().as_slice(),
511        )
512    }
513}