Created
July 6, 2020 19:43
-
-
Save giuseppe/9be2b3b4de7f6971d7a358c1c6c7224b to your computer and use it in GitHub Desktop.
systemd inhibit PoC
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module inhibit | |
go 1.13 | |
require ( | |
github.com/godbus/dbus/v5 v5.0.3 | |
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:sleep" | |
who := "kubelet" | |
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