File: main.rs

package info (click to toggle)
netconsd 0.4.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 344 kB
  • sloc: ansic: 2,650; cpp: 111; python: 107; makefile: 98
file content (197 lines) | stat: -rw-r--r-- 5,268 bytes parent folder | download
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
/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree.
 */

use anyhow::bail;
use anyhow::Error;
use clap::Parser;
use libc::in6_addr;
use libc::sigaction;
use libc::sigaddset;
use libc::sigemptyset;
use libc::sigprocmask;
use libc::sigset_t;
use libc::sigwait;
use libc::sockaddr_in6;
use libc::strsignal;
use libc::AF_INET6;
use libc::SA_NODEFER;
use libc::SIGHUP;
use libc::SIGINT;
use libc::SIGPIPE;
use libc::SIGTERM;
use libc::SIGUSR1;
use libc::SIG_BLOCK;
use libc::SIG_IGN;

extern "C" {
    fn register_output_module(path: *const c_char, nr_workers: c_int);
    fn create_threads(params: &netconsd_params) -> *const c_void;
    fn destroy_threads(ctl: *const c_void);
    fn destroy_output_modules();
}

#[repr(C)]
#[derive(Copy, Clone)]
pub struct netconsd_params {
    pub nr_workers: c_int,
    pub nr_listeners: c_int,
    pub mmsg_batch: c_int,
    pub gc_int_ms: c_uint,
    pub gc_age_ms: c_uint,
    pub listen_addr: sockaddr_in6,
}

#[derive(Debug)]
struct GcParams {
    age: u32,
    interval: u32,
}

impl FromStr for GcParams {
    type Err = Error;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let split: Vec<&str> = s.split("/").collect();
        if split.len() != 2 {
            bail!("Wrong GC format, it should be <age>/<interval>");
        }
        let age = match split[0].parse::<u32>() {
            Ok(x) => x,
            Err(_) => bail!("Could not parse age, it should be an unsigned 32bits integer."),
        };

        let interval = match split[1].parse::<u32>() {
            Ok(x) => x,
            Err(_) => bail!("Could not parse interval, it should be an unsigned 32bits integer."),
        };

        if age < interval {
            bail!("GC age should >= GC interval");
        }
        Ok(GcParams { age, interval })
    }
}

#[derive(Parser, Debug)]
struct CliArgs {
    /// Number of worker threads
    #[clap(short, long)]
    workers: Option<u16>,

    /// Number of listener threads
    #[clap(short, long)]
    listeners: Option<u16>,

    /// Message batch size
    #[clap(short, long)]
    batch: Option<u16>,

    /// UDP listen IPV6 address
    #[clap(short, long)]
    address: Option<Ipv6Addr>,

    /// UDP listen port
    #[clap(short = 'u', long)]
    port: Option<u16>,

    /// Garbage collector interval/age in ms
    #[clap(short, long)]
    gc: Option<GcParams>,

    /// Dynamic modules to load
    #[clap()]
    modules: Vec<String>,
}

/*
 * This exists to kick the blocking recvmmsg() call in the listener threads, so
 * they get -EINTR, notice the stop flag, and terminate.
 *
 * See also: stop_and_wait_for_listeners() in threads.c
 */
fn interrupter_handler(_sig: c_int) {
    return;
}

unsafe fn init_sighandlers() {
    let ignorer: sigaction = sigaction {
        sa_sigaction: SIG_IGN,
        sa_mask: MaybeUninit::zeroed().assume_init(),
        sa_flags: 0,
        sa_restorer: None,
    };
    let interrupter = sigaction {
        sa_sigaction: interrupter_handler as usize,
        sa_mask: MaybeUninit::zeroed().assume_init(),
        sa_flags: SA_NODEFER,
        sa_restorer: None,
    };

    sigaction(SIGUSR1, &interrupter, std::ptr::null_mut::<sigaction>());
    sigaction(SIGPIPE, &ignorer, std::ptr::null_mut::<sigaction>());
}

/*
 * Initialize the set of signals for which we try to terminate gracefully.
 */
unsafe fn init_sigset(set: &mut sigset_t) {
    sigemptyset(set);
    sigaddset(set, SIGTERM);
    sigaddset(set, SIGINT);
    sigaddset(set, SIGHUP);
}

fn get_netconsd_params(cli_args: &CliArgs) -> netconsd_params {
    netconsd_params {
        nr_workers: cli_args.workers.unwrap_or(2).into(),
        nr_listeners: cli_args.listeners.unwrap_or(1).into(),
        mmsg_batch: cli_args.batch.unwrap_or(512).into(),
        gc_int_ms: cli_args.gc.as_ref().map(|gc| gc.interval).unwrap_or(0),
        gc_age_ms: cli_args.gc.as_ref().map(|gc| gc.age).unwrap_or(0),
        listen_addr: sockaddr_in6 {
            sin6_family: AF_INET6 as u16,
            sin6_port: cli_args.port.unwrap_or(1514).to_be(),
            sin6_flowinfo: 0,
            sin6_addr: in6_addr {
                s6_addr: cli_args
                    .address
                    .map(|x| x.octets().clone())
                    .unwrap_or_else(|| [0u8; 16]),
            },
            sin6_scope_id: 0,
        },
    }
}

fn main() {
    let cli_args = CliArgs::parse();
    let params = get_netconsd_params(&cli_args);

    unsafe {
        for module in cli_args.modules.iter() {
            let path = CString::new(module.as_str()).unwrap();
            register_output_module(path.as_ptr(), params.nr_workers);
        }

        init_sighandlers();
        let mut set: sigset_t = MaybeUninit::zeroed().assume_init();
        init_sigset(&mut set);
        sigprocmask(SIG_BLOCK, &set, std::ptr::null_mut::<sigset_t>());

        let mut num: c_int = 0;
        let ctl = create_threads(&params);
        sigwait(&set, &mut num);

        println!(
            "Signal: '{:?}', terminating",
            CStr::from_ptr(strsignal(num))
        );

        destroy_threads(ctl);
        destroy_output_modules();
    };
}