| 1 |
// Package systemctl implements a subset of systemctl operations. |
| 2 |
package systemctl |
| 3 |
|
| 4 |
import ( |
| 5 |
"context" |
| 6 |
"fmt" |
| 7 |
"log" |
| 8 |
|
| 9 |
"github.com/coreos/go-systemd/v22/dbus" |
| 10 |
) |
| 11 |
|
| 12 |
// Systemd is an interface to connect to host systemd with selected functions. |
| 13 |
type Systemd interface { |
| 14 |
Start(string) error |
| 15 |
Stop(string) error |
| 16 |
IsActive(context.Context, string) (string, error) |
| 17 |
Close() |
| 18 |
} |
| 19 |
|
| 20 |
// Systemctl is a wrap around of dbus.Conn and implements the Systemd interface. |
| 21 |
type Systemctl struct { |
| 22 |
dbus *dbus.Conn |
| 23 |
} |
| 24 |
|
| 25 |
var _ Systemd = (*Systemctl)(nil) |
| 26 |
|
| 27 |
// New connects to systemd over dbus. |
| 28 |
func New() (*Systemctl, error) { |
| 29 |
conn, err := dbus.NewWithContext(context.Background()) |
| 30 |
if err != nil { |
| 31 |
return nil, err |
| 32 |
} |
| 33 |
return &Systemctl{dbus: conn}, nil |
| 34 |
} |
| 35 |
|
| 36 |
// Start is the equivalent of `systemctl start $unit`. |
| 37 |
func (s *Systemctl) Start(unit string) error { |
| 38 |
return runSystemdCmd(s.dbus.StartUnitContext, "start", unit) |
| 39 |
} |
| 40 |
|
| 41 |
// Stop is the equivalent of `systemctl stop $unit`. |
| 42 |
func (s *Systemctl) Stop(unit string) error { |
| 43 |
return runSystemdCmd(s.dbus.StopUnitContext, "stop", unit) |
| 44 |
} |
| 45 |
|
| 46 |
// IsActive is the equivalent of `systemctl is-active $unit`. |
| 47 |
// The status can be "active", "activating", "deactivating", "inactive" or "failed". |
| 48 |
func (s *Systemctl) IsActive(ctx context.Context, unit string) (string, error) { |
| 49 |
status, err := s.dbus.ListUnitsByNamesContext(ctx, []string{unit}) |
| 50 |
if err != nil { |
| 51 |
return "", err |
| 52 |
} |
| 53 |
if len(status) != 1 { |
| 54 |
return "", fmt.Errorf("want 1 unit from ListUnitsByNames, got %d", len(status)) |
| 55 |
} |
| 56 |
return status[0].ActiveState, nil |
| 57 |
} |
| 58 |
|
| 59 |
// Close disconnects from dbus. |
| 60 |
func (s *Systemctl) Close() { s.dbus.Close() } |
| 61 |
|
| 62 |
func runSystemdCmd(cmdFunc func(context.Context, string, string, chan<- string) (int, error), cmd string, unit string) error { |
| 63 |
progress := make(chan string, 1) |
| 64 |
|
| 65 |
// Run systemd command in "replace" mode to start the unit and its dependencies, |
| 66 |
// possibly replacing already queued jobs that conflict with this. |
| 67 |
if _, err := cmdFunc(context.Background(), unit, "replace", progress); err != nil { |
| 68 |
return fmt.Errorf("failed to run systemctl [%s] for unit [%s]: %v", cmd, unit, err) |
| 69 |
} |
| 70 |
|
| 71 |
if result := <-progress; result != "done" { |
| 72 |
return fmt.Errorf("systemctl [%s] result was [%s], want done", cmd, result) |
| 73 |
} |
| 74 |
|
| 75 |
log.Printf("Finished up systemctl [%s] for unit [%s]", cmd, unit) |
| 76 |
return nil |
| 77 |
} |