libcgroups 0.6.0

Library for cgroup
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
#[derive(Clone)]
pub struct ProgramInfo {
    pub id: u32,
    pub fd: i32,
}

#[derive(thiserror::Error, Debug)]
pub enum BpfError {
    #[error(transparent)]
    Errno(#[from] errno::Errno),
    #[error("Failed to increase rlimit")]
    FailedToIncreaseRLimit,
}

#[cfg_attr(test, automock)]
pub mod prog {
    use std::os::unix::io::RawFd;
    use std::ptr;

    use libbpf_sys::{BPF_CGROUP_DEVICE, BPF_F_ALLOW_MULTI, BPF_PROG_TYPE_CGROUP_DEVICE, bpf_insn};
    #[cfg(not(test))]
    use libbpf_sys::{
        bpf_prog_attach, bpf_prog_detach2, bpf_prog_get_fd_by_id, bpf_prog_load, bpf_prog_query,
    };
    #[cfg(not(test))]
    use libc::setrlimit;
    use libc::{ENOSPC, RLIMIT_MEMLOCK, rlimit};

    use super::ProgramInfo;
    // TODO: consider use of #[mockall_double]
    #[cfg(test)]
    use crate::v2::devices::mocks::mock_libbpf_sys::{
        bpf_prog_attach, bpf_prog_detach2, bpf_prog_get_fd_by_id, bpf_prog_load, bpf_prog_query,
    };
    // mocks
    // TODO: consider use of #[mockall_double]
    #[cfg(test)]
    use crate::v2::devices::mocks::mock_libc::setrlimit;

    pub fn load(license: &str, insns: &[u8]) -> Result<RawFd, super::BpfError> {
        let insns_cnt = insns.len() / std::mem::size_of::<bpf_insn>();
        let insns = insns as *const _ as *const bpf_insn;
        let mut opts = libbpf_sys::bpf_prog_load_opts {
            sz: std::mem::size_of::<libbpf_sys::bpf_prog_load_opts>() as libbpf_sys::size_t,
            kern_version: 0,
            log_buf: ptr::null_mut::<::std::os::raw::c_char>(),
            log_size: 0,
            ..Default::default()
        };
        #[allow(unused_unsafe)]
        let prog_fd = unsafe {
            bpf_prog_load(
                BPF_PROG_TYPE_CGROUP_DEVICE,
                ptr::null::<::std::os::raw::c_char>(),
                license as *const _ as *const ::std::os::raw::c_char,
                insns,
                insns_cnt as u64,
                &mut opts as *mut libbpf_sys::bpf_prog_load_opts,
            )
        };

        if prog_fd < 0 {
            return Err(errno::errno().into());
        }
        Ok(prog_fd)
    }

    /// Given a fd for a cgroup, collect the programs associated with it
    pub fn query(cgroup_fd: RawFd) -> Result<Vec<ProgramInfo>, super::BpfError> {
        let mut prog_ids: Vec<u32> = vec![0_u32; 64];
        let mut attach_flags = 0_u32;
        for _ in 0..10 {
            let mut prog_cnt = prog_ids.len() as u32;
            #[allow(unused_unsafe)]
            let ret = unsafe {
                // collect ids for bpf programs
                bpf_prog_query(
                    cgroup_fd,
                    BPF_CGROUP_DEVICE,
                    0,
                    &mut attach_flags,
                    &prog_ids[0] as *const u32 as *mut u32,
                    &mut prog_cnt,
                )
            };
            if ret != 0 {
                let err = errno::errno();
                if err.0 == ENOSPC {
                    assert!(prog_cnt as usize > prog_ids.len());

                    // allocate more space and try again
                    prog_ids.resize(prog_cnt as usize, 0);
                    continue;
                }

                return Err(err.into());
            }

            prog_ids.resize(prog_cnt as usize, 0);
            break;
        }

        let mut prog_fds = Vec::with_capacity(prog_ids.len());
        for prog_id in &prog_ids {
            // collect fds for programs by getting their ids
            #[allow(unused_unsafe)]
            let prog_fd = unsafe { bpf_prog_get_fd_by_id(*prog_id) };
            if prog_fd < 0 {
                tracing::debug!("bpf_prog_get_fd_by_id failed: {}", errno::errno());
                continue;
            }
            prog_fds.push(ProgramInfo {
                id: *prog_id,
                fd: prog_fd,
            });
        }
        Ok(prog_fds)
    }

    pub fn detach2(prog_fd: RawFd, cgroup_fd: RawFd) -> Result<(), super::BpfError> {
        #[allow(unused_unsafe)]
        let ret = unsafe { bpf_prog_detach2(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE) };
        if ret != 0 {
            return Err(errno::errno().into());
        }
        Ok(())
    }

    pub fn attach(prog_fd: RawFd, cgroup_fd: RawFd) -> Result<(), super::BpfError> {
        #[allow(unused_unsafe)]
        let ret =
            unsafe { bpf_prog_attach(prog_fd, cgroup_fd, BPF_CGROUP_DEVICE, BPF_F_ALLOW_MULTI) };

        if ret != 0 {
            return Err(errno::errno().into());
        }
        Ok(())
    }

    pub fn bump_memlock_rlimit() -> Result<(), super::BpfError> {
        let rlimit = rlimit {
            rlim_cur: 128 << 20,
            rlim_max: 128 << 20,
        };

        #[allow(unused_unsafe)]
        if unsafe { setrlimit(RLIMIT_MEMLOCK, &rlimit) } != 0 {
            return Err(super::BpfError::FailedToIncreaseRLimit);
        }

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use errno::{Errno, set_errno};
    use libc::{ENOSPC, ENOSYS};
    use serial_test::serial;

    use super::prog;
    use crate::v2::devices::mocks::{mock_libbpf_sys, mock_libc};

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_load() {
        // eBPF uses 64-bit instructions
        let instruction_zero: &[u8] = &[0x0, 0x0, 0x0, 0x0];
        let instruction_one: &[u8] = &[0xF, 0xF, 0xF, 0xF];

        // arrange
        let license = "Apache";
        let instructions = [instruction_zero, instruction_one].concat();
        let load = mock_libbpf_sys::bpf_prog_load_context();

        // expect
        load.expect().once().returning(|_, _, _, _, _, _| 32);

        // act
        let fd = prog::load(license, &instructions).expect("successfully calls load");

        // assert
        assert_eq!(fd, 32);
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_attach() {
        // arrange
        let attach = mock_libbpf_sys::bpf_prog_attach_context();

        // expect
        attach.expect().once().returning(|_, _, _, _| 0);

        // act
        let r = prog::attach(0, 0);

        // assert
        assert!(r.is_ok());
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_load_error() {
        // eBPF uses 64-bit instructions
        let instruction_zero: &[u8] = &[0x0, 0x0, 0x0, 0x0];
        let instruction_one: &[u8] = &[0xF, 0xF, 0xF, 0xF];

        // arrange
        let license = "Apache";
        let instructions = [instruction_zero, instruction_one].concat();
        let load = mock_libbpf_sys::bpf_prog_load_context();

        // expect
        load.expect().once().returning(|_, _, _, _, _, _| -1);

        // act
        let error_result = prog::load(license, &instructions);

        // assert
        assert!(error_result.is_err());
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_query() {
        // arrange
        let query = mock_libbpf_sys::bpf_prog_query_context();
        let get_fd_by_id = mock_libbpf_sys::bpf_prog_get_fd_by_id_context();

        // expect
        query.expect().once().returning(
            |_target_fd: std::os::raw::c_int,
             _type_: libbpf_sys::bpf_attach_type,
             _query_flags: libbpf_sys::__u32,
             _attach_flags: *mut libbpf_sys::__u32,
             prog_ids: *mut libbpf_sys::__u32,
             prog_cnt: *mut libbpf_sys::__u32|
             -> ::std::os::raw::c_int {
                // deref the ptr and fill it with some "ids"
                // also set the prog_cnt to 4
                set_errno(Errno(0));
                unsafe {
                    *prog_cnt = 4;
                    let id_array = std::slice::from_raw_parts_mut(prog_ids, 4_usize);
                    id_array[0] = 1;
                    id_array[1] = 2;
                    id_array[2] = 3;
                    id_array[3] = 4;
                }
                0
            },
        );
        get_fd_by_id.expect().times(4).returning(|fd| {
            // return the same fd if it's not 0
            if fd > 0 {
                return fd as std::os::raw::c_int;
            }
            -1
        });

        // act
        let info = prog::query(0).expect("Able to successfully query");

        // assert
        assert_eq!(info.first().unwrap().id, 1);
        assert_eq!(info.len(), 4);
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_query_recoverable_error() {
        // arrange
        let query = mock_libbpf_sys::bpf_prog_query_context();
        let get_fd_by_id = mock_libbpf_sys::bpf_prog_get_fd_by_id_context();

        // expect
        query.expect().times(2).returning(
            |_target_fd: std::os::raw::c_int,
             _type_: libbpf_sys::bpf_attach_type,
             _query_flags: libbpf_sys::__u32,
             _attach_flags: *mut libbpf_sys::__u32,
             prog_ids: *mut libbpf_sys::__u32,
             prog_cnt: *mut libbpf_sys::__u32|
             -> ::std::os::raw::c_int {
                unsafe {
                    if *prog_cnt == 64 {
                        set_errno(Errno(ENOSPC));
                        *prog_cnt = 128;
                        return 1;
                    }
                    let id_array = std::slice::from_raw_parts_mut(prog_ids, 128_usize);
                    for (i, item) in id_array.iter_mut().enumerate() {
                        *item = (i + 1) as u32;
                    }
                }
                0
            },
        );
        get_fd_by_id.expect().times(128).returning(|fd| {
            // return the same fd if it's not 0
            if fd > 0 {
                return fd as std::os::raw::c_int;
            }
            -1
        });

        // act
        let info = prog::query(0).expect("Able to successfully query");

        // assert
        assert_eq!(info.first().unwrap().id, 1);
        assert_eq!(info.len(), 128);
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_query_other_error() {
        // arrange
        let query = mock_libbpf_sys::bpf_prog_query_context();
        let get_fd_by_id = mock_libbpf_sys::bpf_prog_get_fd_by_id_context();

        // expect
        query.expect().times(1).returning(
            |_target_fd: std::os::raw::c_int,
             _type_: libbpf_sys::bpf_attach_type,
             _query_flags: libbpf_sys::__u32,
             _attach_flags: *mut libbpf_sys::__u32,
             _prog_ids: *mut libbpf_sys::__u32,
             _prog_cnt: *mut libbpf_sys::__u32|
             -> ::std::os::raw::c_int {
                set_errno(Errno(ENOSYS));
                1
            },
        );
        get_fd_by_id.expect().never();

        // act
        let error = prog::query(0);

        // assert
        assert!(error.is_err());
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_detach2() {
        // arrange
        let detach2 = mock_libbpf_sys::bpf_prog_detach2_context();

        // expect
        detach2.expect().once().returning(|_, _, _| 0);

        // act
        let r = prog::detach2(0, 0);

        // assert
        assert!(r.is_ok());
    }

    #[test]
    #[serial(libbpf_sys)] // mock contexts are shared
    fn test_bpf_detach2_error() {
        // arrange
        let detach2 = mock_libbpf_sys::bpf_prog_detach2_context();

        // expect
        detach2.expect().once().returning(|_, _, _| 1);

        // act
        let r = prog::detach2(0, 0);

        // assert
        assert!(r.is_err());
    }

    #[test]
    #[serial(libc)] // mock contexts are shared
    fn test_bump_memlock_rlimit() {
        // arrange
        let setrlimit = mock_libc::setrlimit_context();

        // expect
        setrlimit.expect().once().returning(|_, _| 0);

        // act
        let r = prog::bump_memlock_rlimit();

        // assert
        assert!(r.is_ok());
    }

    #[test]
    #[serial(libc)] // mock contexts are shared
    fn test_bump_memlock_rlimit_error() {
        // arrange
        let setrlimit = mock_libc::setrlimit_context();

        // expect
        setrlimit.expect().once().returning(|_, _| 1);

        // act
        let r = prog::bump_memlock_rlimit();

        // assert
        assert!(r.is_err());
    }
}