Skip to content

Instantly share code, notes, and snippets.

@bobbypage
Last active July 20, 2022 21:55
Show Gist options
  • Save bobbypage/13ca9e1e8aee728dc2c7e0e1fd9b59ea to your computer and use it in GitHub Desktop.
Save bobbypage/13ca9e1e8aee728dc2c7e0e1fd9b59ea to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"os"
"time"
"github.com/godbus/dbus/v5"
)
func simulateWorkload() {
// Got signal, sleep a bit then exit
fmt.Println("Preparing to shutdown")
for i := 0; i < 20; i = i + 1 {
fmt.Printf(".")
time.Sleep(time.Second)
}
fmt.Println("")
fmt.Println("All saved, exiting")
os.Exit(0)
}
// need to tweak InhibitDelayMaxSec= in /etc/systemd/logind.conf
func inhibit() error {
conn, err := dbus.SystemBus()
if err != nil {
return err
}
defer conn.Close()
var fd int
obj := conn.Object("org.freedesktop.login1", "/org/freedesktop/login1")
what := "shutdown"
who := "test-app"
why := "because"
mode := "delay"
call := obj.Call("org.freedesktop.login1.Manager.Inhibit", 0, what, who, why, mode)
if call.Err != nil {
return call.Err
}
err = call.Store(&fd)
f := os.NewFile(uintptr(fd), "inhibit fd")
defer f.Close()
err = conn.AddMatchSignal(
dbus.WithMatchInterface("org.freedesktop.login1.Manager"),
dbus.WithMatchMember("PrepareForShutdown"),
dbus.WithMatchObjectPath("/org/freedesktop/login1"),
)
if err != nil {
return err
}
c := make(chan *dbus.Signal, 1)
conn.Signal(c)
for v := range c {
r, _ := v.Body[0].(bool)
if r {
go simulateWorkload()
}
}
return nil
}
func main() {
err := inhibit()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to inhibit:", err)
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment