~whynothugo/systemd-lock-handler

df860d0d8b736d131e63723b6e28f78e76980d95 — Hugo Osvaldo Barrera 2 months ago bfb186c
Inhibit sleeping to ensure we have time to react

This is still imperfect; see linked article for additional upcoming
changes in v3.0.0.
2 files changed, 22 insertions(+), 0 deletions(-)

M README.md
M main.go
M README.md => README.md +9 -0
@@ 111,6 111,15 @@ This will happen _before_ the system is suspended.
Changelog
---------

## 2.4.0

- Sleeping will be now inhibited when `systemd-lock-handler` starts. This
  ensure that there is enough time to react before the system actually goes to
  sleep. See [this article] for some background on how this all works and
  upcoming changes.

[this article]: https://whynothugo.nl/journal/2022/10/26/systemd-locking-and-sleeping/

## 2.3.0

- `sleep.target` now requires `lock.target` itself. So for any services that

M main.go => main.go +13 -0
@@ 9,6 9,7 @@ import (

	"github.com/coreos/go-systemd/v22/daemon"
	systemd "github.com/coreos/go-systemd/v22/dbus"
	"github.com/coreos/go-systemd/v22/login1"
	"github.com/godbus/dbus/v5"
)



@@ 45,9 46,19 @@ func ListenForSleep() {
	}

	c := make(chan *dbus.Signal, 10)
	logind, err := login1.New()
	if err != nil {
		log.Fatalln("Failed to connect to logind")
	}

	go func() {
		for {
			// We need to inhibit sleeping so we have time to execute our actions before the system sleeps.
			lock, err := logind.Inhibit("sleep", "systemd-lock-handler", "Start pre-sleep target", "delay")
			if err != nil {
				log.Fatalln("Failed to grab sleep inhibitor lock", err)
			}
			log.Println("Got lock on sleep inhibitor")
			<-c
			log.Println("The system is going to sleep")



@@ 55,6 66,8 @@ func ListenForSleep() {
			if err != nil {
				log.Println("Error starting sleep.target:", err)
			}
			// Uninhibit sleeping. I.e.: let the system actually go to sleep.
			lock.Close()
		}
	}()