Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

dbus: add GetUnitFileState method #350

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions dbus/methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -830,3 +830,18 @@ func (c *Conn) listJobsInternal(ctx context.Context) ([]JobStatus, error) {

return status, nil
}

// GetUnitFileStateContext returns UnitFileState
func (c *Conn) GetUnitFileStateContext(ctx context.Context, name string) (string, error) {
var prop dbus.Variant
obj := c.sysconn.Object("org.freedesktop.systemd1", "/org/freedesktop/systemd1")
err := obj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.GetUnitFileState", 0, name).Store(&prop)
if err != nil {
return "", err
}
state, ok := prop.Value().(string)
if !ok {
return "", fmt.Errorf("failed to cast UnitFileState prop to string")
}
return state, nil
}
26 changes: 26 additions & 0 deletions dbus/methods_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@
package dbus

import (
"context"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"reflect"
"strings"
"syscall"
"testing"
"time"
Expand Down Expand Up @@ -1600,3 +1602,27 @@ func TestUnitName(t *testing.T) {
}
}
}

// TestGetUnitFileState reads the `systemd-udevd.service` which should exist on all systemd
// systems and ensures that UnitFileState property is valid.
func TestGetUnitFileState(t *testing.T) {
conn := setupConn(t)
defer conn.Close()
service := "systemd-udevd.service"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This may not exist in the testing environment. It would be good to set up a dedicated temporary service unit instead.

got, err := conn.GetUnitFileStateContext(context.Background(), service)
if err != nil {
t.Fatal(err)
}
ok := false
// valid UnitFileState values
validUnitFileStates := []string{"enabled", "disabled", "static", "bad"}
for _, v := range validUnitFileStates {
if got == v {
ok = true
break
}
}
if !ok {
t.Errorf("invalid UnitFileState returned from GetUnitFileState(%s): got %s, want one of [%s]", service, got, strings.Join(validUnitFileStates, ", "))
}
}