Giter Club home page Giter Club logo

systemctl's Introduction

systemctl

Small rust crate to interact with systemd units

crates.io License License crates.io
Rust crates.io

Features

  • serde: Enable to make structs in this crate De-/Serializable

Limitations

Currently SystemD Version <245 are not supported as unit-file-list changed from two column to three column setup. See: SystemD Changelog

Environment

SYSTEMCTL_PATH custom env. variable describes the absolute location path of systemctl binary, by default this crate uses /usr/bin/systemctl, but that can be customized:

SYSTEMCTL_PATH=/home/$me/bin/systemctl cargo build

Unit / service operation

Nominal service operations:

systemctl::stop("systemd-journald.service")
    .unwrap();
systemctl::restart("systemd-journald.service")
    .unwrap();

if let Ok(true) = systemctl::exists("ntpd") {
    let is_active = systemctl::is_active("ntpd")
        .unwrap();
}

Service enumeration

use systemctl;
// list all units
systemctl::list_units(None, None, None);

// list all services 
// by adding a --type filter
systemctl::list_units(Some("service"), None, None);

// list all services currently `enabled` 
// by adding a --state filter
systemctl::list_units(Some("service"), Some("enabled"), None);

// list all services starting with cron
systemctl::list_units(Some("service"), None, Some("cron*"));

Unit structure

Use the unit structure for more information

let unit = systemctl::Unit::from_systemctl("sshd")
    .unwrap();
unit.restart().unwrap();
println!("active: {}", unit.active);
println!("preset: {}", unit.preset);

if let Some(docs) = unit.docs { // doc pages available
    for doc in docs {
        if let Some(page) = doc.as_man() {
            // `man` page exists 
        }
        if let Some(url) = doc.as_url() {
            // `url` is indicated
        }
    }
}

println!("auto_start (enabled): {}", unit.auto_start);
println!("config script : {}", unit.script);
println!("pid: {}", unit.pid);
println!("Running task(s): {}", unit.tasks.unwrap());
println!("Memory consumption: {}", unit.memory.unwrap());

TODO

  • parse all known attributes in from_systemctl

systemctl's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

systemctl's Issues

list_disabled_services , list_enabled_services not working

let services = vec!["sshd","podman"];
let disabled_services =  match systemctl::list_disabled_services(){
        Ok(list) => list,
        Err(_) => bail!("Unable to fetch list of disabled services")
    };
    println!("disabled services : {:?}",disabled_services);
    for service in &services {
        if disabled_services.contains(&service.to_string()) {
            service_not_ok.push(service);
            log::warn!("service: {service} is disabled");
            continue;
        }
        println!("{service}: {}",systemctl::Unit::from_systemctl(service).unwrap().preset);
        match systemctl::Unit::from_systemctl(service) {
            Ok(service_details) => {
                if !service_details.active {
                    log::warn!("service: {service} is not running"); 
                    unforced_error=true;
                }
            },
            Err(err) => log::error!("Error fetching {service} status: {err}"),
        }   
    }

output is :

disabled services : []
sshd: true
podman: false
 WARN  greenboot > service: podman is not running

The disabled service list in empty where I expected podman to be present.

As

[sayan@ibm-p8-kvm-03-guest-02 ~]$ systemctl list-unit-files | grep podman
podman-auto-update.service                                                          disabled        disabled
podman-clean-transient.service                                                      disabled        disabled
[email protected]                                                                disabled        disabled
podman-restart.service                                                              disabled        disabled
podman.service                                                                      disabled        disabled
podman.socket                                                                       disabled        disabled
podman-auto-update.timer                                                            disabled        disabled

"list_units" not working correctely

So i was trying to get a list of all units as in the doc's, but it doesn't work because returns a empty vector
fn test_status() { let units = systemctl::list_units(None, None); // all units let is_ok = units.is_ok(); println!("{}", is_ok); let new_units = units.unwrap(); println!("{}", new_units.len()); }
output
true 0
Test in the terminal
systemctl list-units | wc -l 199
I'm i doing something wrong or is something broken

"index out of bounds: the len is 2 but the index is 2" on older systemctl

Hi,

I'm using this crate on a device running Linux (Yocto Dunfel), which run systemctl 244.
Where "systemctl list-unit-files" gives me:

UNIT FILE                              STATE          
-.mount                                generated      
boot.mount                             generated      
data.mount                             generated      
dev-hugepages.mount                    static         
dev-mqueue.mount                       static         
sys-fs-fuse-connections.mount          static         
sys-kernel-config.mount                static         
sys-kernel-debug.mount                 static         
tmp.mount                              static         
var-volatile.mount                     generated      
systemd-ask-password-console.path      static         
systemd-ask-password-wall.path         static         
alsa-restore.service                   static         
alsa-state.service                     static         
apmd.service                           static         
[email protected]                        enabled             
bluetooth.service                      enabled        
[email protected]                      static         
busybox-klogd.service                  enabled        
busybox-syslog.service                 enabled        
console-getty.service                  disabled       
[email protected]               static         
containerd.service                     disabled       
crond.service                          enabled        
dbus-org.bluez.service                 enabled        
dbus-org.freedesktop.hostname1.service static         
dbus-org.freedesktop.locale1.service   static         
dbus-org.freedesktop.login1.service    static         
dbus-org.freedesktop.network1.service  enabled        
dbus-org.freedesktop.resolve1.service  enabled        
dbus-org.freedesktop.timedate1.service static         
dbus-org.freedesktop.timesync1.service enabled        
dbus.service                           static         
debug-shell.service                    disabled  

I.e. the third column "VENDOR PRESET" doesn't exist.

So when I run e.g. "systemctl::exists" in my code it panics.

It looks lite this line is the culprit.

Does not work on Arch linux

I am importing using use systemctl::*; and running the following code:

let services = list_units(None, None).unwrap();
println!("Services: {:?}", services);

and I get
Services: [] no matter what I do.

I validated that systemctl is in /usr/bin/systemctl and when I run the actual commands locally I do not have any problems. Am I missing something obvious here?

parse failed

if parsed.len() == 2 {

Use systemctl list-unit-files for systemctl version systemd 245 (245.4-4ubuntu3.17), output the following result

1666153389660

Judging by the number of columns is unreasonable.

list_units function is private

Hi, thanks for making this library! I think it's really useful to have a simple Rust library for working with systemd.

I tried following the "Service enumeration" example in the README, but it fails because list_units() is not public:

error[E0603]: function `list_units` is private
  --> src/main.rs:6:28
   |
6  |     let units = systemctl::list_units(None, None);
   |                            ^^^^^^^^^^ private function

feasibility of not depending on the systemctl

Ideally, for cases like these, it would be possible to manage systemd through a library instead of systemctl.
A reasonable question is, for the feature-set of this library, what would be involved in implementing the systemctl features in rust?

Package does not work on Ubuntu 18.04

Hiya!

This package works great for 20.04 onwards. On 18.04 (and before?) however, the systemctl binary is in a different location: /bin/systemctl.

After examining the code base, I spotted the SYSTEMCTL_PATH environment variable that can be set. I have tried to set the variable in a multitude of ways from my application, but the variable does not seem to take effect. I verified this by cloning and using a local copy of this library.

Ways I've tried:

  • SYSTEMCTL_PATH=/bin/systemctl cargo r -- status
  • export SYSTEMCTL_PATH=/bin/systemctl && cargo r -- status
  • In my app using temp_var:
temp_env::with_var("SYSTEMCTL_PATH", Some("/bin/systemctl"), || {
    systemctl::exists(SERVICE_NAME)
})?;
  • in my app using env::set_var:
env::set_var(key, "/bin/systemctl")
systemctl::exists(SERVICE_NAME)

In all cases, default_env! uses the default path.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.