From 97453276a8c9dc9e9087fcc2b669a436ab65a7af Mon Sep 17 00:00:00 2001 From: Tycho Andersen Date: Wed, 19 Jul 2023 11:39:42 -0600 Subject: [PATCH] add CancelJob() We'd like to be able to cancel jobs using this API, so add a wrapper for it. Signed-off-by: Tycho Andersen --- dbus/methods.go | 5 +++++ dbus/methods_test.go | 35 +++++++++++++++++++++++++++++++++++ fixtures/cancelme.service | 6 ++++++ 3 files changed, 46 insertions(+) create mode 100644 fixtures/cancelme.service diff --git a/dbus/methods.go b/dbus/methods.go index 074148cb..21ad9792 100644 --- a/dbus/methods.go +++ b/dbus/methods.go @@ -852,6 +852,11 @@ func (c *Conn) listJobsInternal(ctx context.Context) ([]JobStatus, error) { return status, nil } +// Cancel the specified job ID. +func (c *Conn) CancelJobContext(ctx context.Context, id uint32) error { + return c.sysobj.CallWithContext(ctx, "org.freedesktop.systemd1.Manager.CancelJob", 0, id).Store() +} + // Freeze the cgroup associated with the unit. // Note that FreezeUnit and ThawUnit are only supported on systems running with cgroup v2. func (c *Conn) FreezeUnit(ctx context.Context, unit string) error { diff --git a/dbus/methods_test.go b/dbus/methods_test.go index 30cc1324..27c20bc6 100644 --- a/dbus/methods_test.go +++ b/dbus/methods_test.go @@ -1689,3 +1689,38 @@ func TestFreezer(t *testing.T) { runStopUnit(t, conn, TrUnitProp{target, nil}) } + +func TestCancel(t *testing.T) { + target := "cancelme.service" + conn := setupConn(t) + defer conn.Close() + + setupUnit(target, conn, t) + linkUnit(target, conn, t) + + reschan := make(chan string) + _, err := conn.StartUnit(target, "replace", reschan) + if err != nil { + t.Fatal(err) + } + + ctx := context.Background() + units, err := conn.ListUnitsByNamesContext(ctx, []string{target}) + if err != nil { + t.Fatal("couldn't list units ", err) + } + + if err := conn.CancelJobContext(ctx, units[0].JobId); err != nil { + t.Fatal("couldn't cancel job ", err) + } + + units, err = conn.ListUnitsByNamesContext(ctx, []string{target}) + if err != nil { + t.Fatal("couldn't list units after cancel ", err) + } + + job := <-reschan + if job != "canceled" { + t.Fatal("Job is not canceled:", job) + } +} diff --git a/fixtures/cancelme.service b/fixtures/cancelme.service new file mode 100644 index 00000000..77ab3835 --- /dev/null +++ b/fixtures/cancelme.service @@ -0,0 +1,6 @@ +[Unit] +Description=cancel unit test + +[Service] +ExecStartPre=/bin/sleep 400 +ExecStart=/bin/sleep 400