libcgroup_rs 0.1.0

C FFI libcgroup
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
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
//!
//! ### 2.Group Manipulation API
//!
//! URL: [Group Manipulation API](http://libcg.sourceforge.net/html/group__group__groups.html)
//!
//! Functions:
//!    - cgroup_new_cgroup
//!    - cgroup_add_controller
//!    - cgroup_get_controller
//!    - cgroup_free
//!    - cgroup_free_controllers
//!    - cgroup_create_cgroup
//!    - cgroup_create_cgroup_from_parent
//!    - cgroup_modify_cgroup
//!    - cgroup_delete_cgroup
//!    - cgroup_delete_cgroup_ext
//!    - cgroup_get_cgroup
//!    - cgroup_copy_cgroup
//!    - cgroup_compare_cgroup
//!    - cgroup_compare_controllers
//!    - cgroup_set_uid_gid
//!    - cgroup_get_uid_gid
//!    - cgroup_add_value_*
//!    - cgroup_get_value_*
//!    - cgroup_set_value_*
//!    - cgroup_get_value_name_count
//!    - cgroup_get_value_name
//!
//! Usage(Create):
//! ```
//! use libcgroup_rs::initialization::CGroupInitializer;
//! use libcgroup_rs::manipulation::CGroupBuilder;
//! use libcgroup_rs::error::{cg_get_error, C_EC_GROUP_NOT_ALLOWED};
//!
//! fn main()->Result<(),Box<dyn std::error::Error>>{
//!     CGroupInitializer::init()?;
//!     let container_name = "foo";
//!     let cg = CGroupBuilder::new(container_name)?;
//!     println!("Source CG = {:?}",cg);
//!
//!     // append controller
//!     println!("Add Controller = {:?}",cg.add_controller("cpu")?);
//!     println!("Get Controller = {:?}",cg.get_controller("cpu")?);
//!
//!     //only root
//!     match cg.create(0) {
//!         Ok(_) => (),
//!         Err(e) if e.kind().eq(&cg_get_error(C_EC_GROUP_NOT_ALLOWED).kind()) =>{
//!             println!("Only root! = use sudo ?");
//!             return Ok(());
//!         }
//!         Err(e) => return Err(Box::new(e))
//!     }
//!     Ok(())
//! }
//! ```
//!
//! Usage(Create with params):
//! ```
//! use libcgroup_rs::initialization::CGroupInitializer;
//! use libcgroup_rs::manipulation::CGroupBuilder;
//! use libcgroup_rs::error::{cg_get_error, C_EC_GROUP_NOT_ALLOWED};
//!
//! fn main()->Result<(),Box<dyn std::error::Error>>{
//!     CGroupInitializer::init()?;
//!
//!     let container_name = "foo";
//!     let container = CGroupBuilder::new(container_name)?;
//!     println!("Container = {:?}",container);
//!
//!     let ctrl = container.add_controller("cpu")?;
//!     println!("Controller = {:?}",ctrl);
//!
//!     // cfg = /cgroups/foo/cpu/cfs_quota_us
//!     ctrl.add_u64("cpu.cfs_quota_us",50000)?;
//!
//!     // cfg = /cgroups/foo/cpu/cfs_period_us
//!     ctrl.add_u64("cpu.cfs_period_us",100000)?;
//!
//!     // create
//!     container.create(0)?;
//!
//!     Ok(())
//! }
//! ```
//!

use crate::prelude::*;
use crate::error::*;
use log::{info,error};


#[derive(Debug)]
pub struct CGroupControllerBuilder{
    name: String,
    c_groups:*mut cgroup,
    c_groups_ctrl: *mut cgroup_controller,
}


#[derive(Debug)]
pub struct CGroupBuilder<'a>{
    name: &'a str,
    c_groups: *mut cgroup,
}



impl<'a> CGroupBuilder<'a>{


    pub fn new(name:&'a str)->Result<Self,std::io::Error>{
        let mut cg = Self{
            name,
            c_groups:std::ptr::null_mut(),
        };
        cg.c_groups = unsafe {
            let c_name = std::ffi::CString::new(cg.name)?;
            cgroup_new_cgroup(c_name.as_ptr())
        };

        if cg.c_groups.is_null() {
            return Err(cg_get_error(C_EC_GROUP_NOT_CREATED))
        }
        Ok(cg)
    }

    pub fn is_null(&self)->bool{
        self.c_groups.is_null()
    }

    pub fn add_controller(&self, ctrl_name: &str) ->Result<CGroupControllerBuilder, std::io::Error> {
        unsafe {
            let c_ctrl_name = std::ffi::CString::new(ctrl_name)?;
            let c_ctrl_ptr = cgroup_add_controller(self.c_groups,c_ctrl_name.as_ptr());
            info!("CGroupBuilder::add_controller[return pointer] = {:?}",c_ctrl_ptr);
            if c_ctrl_ptr.is_null() {
                return Err(cg_get_error(C_EC_CONTROLLER_CREATE_FAILED))
            }
            return Ok(CGroupControllerBuilder::new(String::from(ctrl_name),self.c_groups,c_ctrl_ptr));
        }
    }

    pub fn get_controller(&self, ctrl_name: &str) ->Result<CGroupControllerBuilder, std::io::Error>{
        unsafe {
            let c_ctrl_name = std::ffi::CString::new(ctrl_name)?;
            let c_ctrl_ptr = cgroup_get_controller(self.c_groups,c_ctrl_name.as_ptr());
            info!("CGroupBuilder::get_controller[return pointer] = {:?}",c_ctrl_ptr);
            if c_ctrl_ptr.is_null() {
                return Err(cg_get_error(C_EC_CONTROLLER_CREATE_FAILED))
            }
            return Ok(CGroupControllerBuilder::new(String::from(ctrl_name),self.c_groups,c_ctrl_ptr));
        }
    }

    pub fn free(&self){
        unsafe {
            if !self.c_groups.is_null() {
                let c_point = self.c_groups as *const cgroup;
                info!("CGroupBuilder::free[return point] = {:?}",c_point);
                cgroup_free(&c_point  as *const *const cgroup);
            }
        }
    }

    pub fn free_controllers(&self){
        unsafe {
            if !self.c_groups.is_null() {
                let c_point = self.c_groups;
                info!("CGroupBuilder::free_controllers[return point] = {:?}",c_point);
                cgroup_free_controllers(c_point);
            }
        }
    }

    pub fn create(&self,ignore_ownership:i32)->Result<(),std::io::Error>{
        unsafe {
            let c_ignore_ownership = libc::c_int::from(ignore_ownership);
            let ret = cgroup_create_cgroup(self.c_groups,c_ignore_ownership);
            info!("CGroupBuilder::create[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn create_from_parent(&self,ignore_ownership:i32)->Result<(),std::io::Error>{
        unsafe {
            let c_ignore_ownership = libc::c_int::from(ignore_ownership);
            let ret = cgroup_create_cgroup_from_parent(self.c_groups,c_ignore_ownership);
            info!("CGroupBuilder::create_from_parent[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn modify(&self)->Result<(),std::io::Error>{
        unsafe {
            let ret = cgroup_modify_cgroup(self.c_groups);
            info!("CGroupBuilder::modify[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }

        Ok(())
    }

    pub fn delete(&self,ignore_migration:i32)->Result<(),std::io::Error>{
        unsafe {
            let c_ignore_migration = libc::c_int::from(ignore_migration);
            let ret = cgroup_delete_cgroup(self.c_groups,c_ignore_migration);
            info!("CGroupBuilder::delete[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn delete_ext(&self,flags:i32)->Result<(),std::io::Error>{
        unsafe {
            let c_flags = libc::c_int::from(flags);
            let ret = cgroup_delete_cgroup_ext(self.c_groups,c_flags);
            info!("CGroupBuilder::delete_ext[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn set_uid_pid(&self,
                       tasks_uid:u32,
                       tasks_gid:u32,
                       ctrl_uid:u32,
                       ctrl_gid:u32
    )->Result<(),std::io::Error>{
        unsafe {
            let c_tasks_uid = libc::uid_t::from(tasks_uid);
            let c_tasks_gid = libc::uid_t::from(tasks_gid);
            let c_ctrl_uid = libc::uid_t::from(ctrl_uid);
            let c_ctrl_gid = libc::uid_t::from(ctrl_gid);
            let ret = cgroup_set_uid_gid(
                self.c_groups,
                c_tasks_uid,
                c_tasks_gid,
                c_ctrl_uid,
                c_ctrl_gid
            );

            info!("CGroupBuilder::set_uid_pid[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }


    pub fn get_uid_pid(&self)->Result<(u32,u32,u32,u32),std::io::Error>{
        unsafe {
            let c_tasks_uid = libc::uid_t::from(0u32);
            let c_tasks_gid = libc::uid_t::from(0u32);
            let c_ctrl_uid = libc::uid_t::from(0u32);
            let c_ctrl_gid = libc::uid_t::from(0u32);
            let ret = cgroup_get_uid_gid(
                self.c_groups,
                &c_tasks_uid,
                &c_tasks_gid,
                &c_ctrl_uid,
                &c_ctrl_gid
            );

            info!("CGroupBuilder::get_uid_pid[return code] = {}",ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }

            Ok((
                c_tasks_uid as u32,
                c_tasks_gid as u32,
                c_ctrl_uid as u32,
                c_ctrl_gid as u32,
            ))
        }
    }



    pub fn attach_task(&self)->Result<(),std::io::Error>{
        unsafe {
            let ret = cgroup_attach_task(self.c_groups);
            info!("CGroupBuilder::attach_task[return code] = {}",ret);
        }

        Ok(())
    }

    pub fn attach_task_pid(&self,pid:i32)->Result<(),std::io::Error>{
        unsafe {
            let c_pid = libc::pid_t::from(pid);
            let ret = cgroup_attach_task_pid(self.c_groups,c_pid);
            info!("CGroupBuilder::attach_task_pid[return code] = {}",ret);
        }
        Ok(())
    }

    pub fn attach_task_shell(&self)->Result<(),std::io::Error>{

        unsafe {
            let pid = libc::fork();
            if pid < 0 {
                return Err(std::io::Error::new(std::io::ErrorKind::Other,"Failed by fork"))
            }else if pid == 0 {
                let pid = libc::getpid();
                self.attach_task_pid(pid)?;

                let c_exec_app = std::ffi::CString::new("/bin/sh")?;
                let ret = libc::execl(c_exec_app.as_ptr(),std::ptr::null());
                if ret != C_GROUP_SUCCESS {
                    return Err(std::io::Error::new(
                       std::io::Error::from_raw_os_error(ret).kind(),
                        "Failed by Attach CGroup Shell"
                    ));
                }

            }else {
                let pid = libc::getpid();
                let mut status = libc::c_int::from(0 as i32);
                let ppid = libc::wait(&mut status);
                info!("Fork Parent = {}",pid);
                info!("Fork Child = {}",ppid);
                if status != C_GROUP_SUCCESS {
                    return Err(std::io::Error::from_raw_os_error(status));
                }
            }
        }
        Ok(())
    }
}

impl CGroupControllerBuilder {
    pub fn new(name: String, c_groups: *mut cgroup, c_groups_ctrl: *mut cgroup_controller) -> Self {
        Self { name, c_groups, c_groups_ctrl }
    }

    pub fn is_null(&self) -> bool {
        self.c_groups_ctrl.is_null()
    }

    pub fn add_str(&self, name: &str, value: &str) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = std::ffi::CString::new(value)?;
            let ret = cgroup_add_value_string(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value.as_ptr());

            info!("CGroupControllerBuilder::add_str[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn add_i64(&self, name: &str, value: i64) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = libc::c_longlong::from(value);
            let ret = cgroup_add_value_int64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value
            );
            info!("CGroupControllerBuilder::add_i64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn add_u64(&self, name: &str, value: u64) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = libc::c_ulonglong::from(value);
            let ret = cgroup_add_value_uint64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value
            );
            info!("CGroupControllerBuilder::add_u64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn add_bool(&self, name: &str, value: bool) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let ret = cgroup_add_value_bool(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                value
            );
            info!("CGroupControllerBuilder::add_bool[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }


    pub fn set_str(&self, name: &str, value: &str) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = std::ffi::CString::new(value)?;
            let ret = cgroup_set_value_string(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value.as_ptr());

            info!("CGroupControllerBuilder::set_str[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn set_i64(&self, name: &str, value: i64) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = libc::c_longlong::from(value);
            let ret = cgroup_set_value_int64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value
            );
            info!("CGroupControllerBuilder::set_i64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn set_u64(&self, name: &str, value: u64) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = libc::c_ulonglong::from(value);
            let ret = cgroup_set_value_uint64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                c_value
            );
            info!("CGroupControllerBuilder::set_u64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn set_bool(&self, name: &str, value: bool) -> Result<(), std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let ret = cgroup_set_value_bool(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                value
            );
            info!("CGroupControllerBuilder::set_bool[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
        }
        Ok(())
    }

    pub fn get_str(&self, name: &str) -> Result<String, std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let c_value = std::ptr::null();
            let ret = cgroup_get_value_string(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                &c_value as *const *const libc::c_char
            );

            info!("CGroupControllerBuilder::get_str[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
            Ok(std::ffi::CStr::from_ptr(c_value)
                .to_string_lossy()
                .to_owned()
                .to_string())
        }
    }

    pub fn get_i64(&self, name: &str) -> Result<i64, std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let mut c_value = libc::c_longlong::from(0 as i64);
            let ret = cgroup_get_value_int64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                &mut c_value
            );
            info!("CGroupControllerBuilder::get_i64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
            Ok(c_value as i64)
        }
    }

    pub fn get_u64(&self, name: &str) -> Result<u64, std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let mut c_value = libc::c_ulonglong::from(0 as u64);
            let ret = cgroup_get_value_uint64(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                &mut c_value
            );
            info!("CGroupControllerBuilder::get_u64[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
            Ok(c_value as u64)
        }
    }

    pub fn get_bool(&self, name: &str) -> Result<bool, std::io::Error> {
        unsafe {
            let c_name = std::ffi::CString::new(name)?;
            let mut c_value = false;
            let ret = cgroup_get_value_bool(
                self.c_groups_ctrl,
                c_name.as_ptr(),
                &mut c_value
            );
            info!("CGroupControllerBuilder::get_bool[return code] = {}", ret);
            if ret != C_GROUP_SUCCESS {
                return Err(cg_get_error(ret));
            }
            Ok(c_value as bool)
        }
    }

}


impl<'a> Clone for CGroupBuilder<'a>{

    fn clone(&self) -> Self {
        unsafe {
            match Self::new(self.name.clone()) {
                Ok(mut clone) => {
                    let c_sdt :*mut cgroup = clone.c_groups;
                    let ret = cgroup_copy_cgroup(self.c_groups,c_sdt);
                    info!("CGroupBuilder::clone[return code] = {}",ret);
                    if ret == C_GROUP_SUCCESS {
                        clone.c_groups = c_sdt;
                    }
                    clone
                }
                Err(e) => {
                    error!("CGroupBuilder::clone[error msg] = {:?}",e);
                    Self{name:self.name,c_groups:std::ptr::null_mut()}
                }
            }
        }
    }

    fn clone_from(&mut self, source: &Self) {
        unsafe {
            let c_sdt :*mut cgroup = source.c_groups;
            let ret = cgroup_copy_cgroup(c_sdt,self.c_groups);
            info!("CGroupBuilder::clone_from[return code] = {}",ret);
            if ret == C_GROUP_SUCCESS {
                self.c_groups = c_sdt;
            }
        }
    }
}


impl<'a> PartialEq for CGroupBuilder<'a>{
    fn eq(&self, other: &Self) -> bool {
        unsafe {
            let ret = cgroup_compare_cgroup(self.c_groups,other.c_groups);
            info!("CGroupBuilder::eq[return code] = {}",ret);
            if ret == C_GROUP_SUCCESS {
                return true;
            }
        }
        false
    }
}


impl PartialEq for CGroupControllerBuilder{
    fn eq(&self, other: &Self) -> bool {
        unsafe {
            let ret = cgroup_compare_controllers(self.c_groups_ctrl,other.c_groups_ctrl);
            info!("CGroupControllerBuilder::eq[return code] = {}",ret);
            if ret == C_GROUP_SUCCESS {
                return true;
            }
        }
        false
    }
}