Skip to content

Instantly share code, notes, and snippets.

@fcwu
Created April 30, 2020 23:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fcwu/3e1571944c9c55e9443104f8b3a34395 to your computer and use it in GitHub Desktop.
Save fcwu/3e1571944c9c55e9443104f8b3a34395 to your computer and use it in GitHub Desktop.
go-systemd example
module example.com
replace github.com/coreos/go-systemd => github.com/coreos/go-systemd/v22 v22.0.0
go 1.13
require github.com/coreos/go-systemd v0.0.0-00010101000000-000000000000 // indirect
package main
import (
"fmt"
"log"
"time"
"github.com/coreos/go-systemd/dbus"
"github.com/coreos/go-systemd/journal"
)
const unitName = "nginx.service"
func main() {
conn, err := dbus.NewSystemConnection()
if err != nil {
log.Fatal(err.Error())
}
defer conn.Close()
// list unit's properties
properties, err := conn.GetUnitProperties(unitName)
if err != nil {
log.Fatal(err.Error())
}
for k, v := range properties {
fmt.Printf("%s: %v\n", k, v)
}
// send log
journal.Send("send to journald", journal.PriInfo, map[string]string{"SYSLOG_IDENTIFIER": "go-systemd"})
journal.Print(journal.PriInfo, "go-systemd: hello") // go-systemd will not show as SYSLOG_IDENTIFIER
statusChan, errChan := conn.SubscribeUnits(time.Second)
// it will list all units first
select {
case m := <-statusChan:
for k, v := range m {
fmt.Printf("event: %v: %v\n", k, *v)
}
case err := <-errChan:
fmt.Printf("error: %v\n", err.Error())
}
stop := make(chan struct{}, 0)
go func() {
time.Sleep(1 * time.Second)
fmt.Printf("disable [%s]\n", unitName)
conn.DisableUnitFiles([]string{unitName}, false)
time.Sleep(1 * time.Second)
fmt.Printf("enable [%s]\n", unitName)
conn.EnableUnitFiles([]string{unitName}, false, true)
time.Sleep(1 * time.Second)
resultChan := make(chan string)
// second args: replace, fail, isolate, ignore-dependencies, ignore-requirements
// result can be nil, possible value: done, canceled, timeout, failed, dependency, skipped.
jobID, err := conn.StopUnit(unitName, "replace", resultChan)
if err == nil {
fmt.Printf("stop [%s]: job ID=%d\n", unitName, jobID)
s := <-resultChan
fmt.Printf("stop result: %v\n", s)
} else {
fmt.Printf("failed to stop [%s]: %s\n", unitName, err.Error())
}
time.Sleep(1 * time.Second)
jobID, err = conn.StartUnit(unitName, "replace", resultChan)
if err == nil {
fmt.Printf("start [%s]: job ID=%d\n", unitName, jobID)
s := <-resultChan
fmt.Printf("start result: %v\n", s)
} else {
fmt.Printf("failed to start [%s]: %s\n", unitName, err.Error())
}
time.Sleep(1 * time.Second)
stop <- struct{}{}
}()
// wait done
Loop:
for {
select {
case m := <-statusChan:
for k, v := range m {
fmt.Printf("event: %v: %v\n", k, *v)
}
case err := <-errChan:
fmt.Printf("error: %v\n", err.Error())
break Loop
case <-stop:
break Loop
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment