2022-09-05 03:06:08 -04:00
|
|
|
/*
|
|
|
|
Copyright (c) Edgeless Systems GmbH
|
|
|
|
|
|
|
|
SPDX-License-Identifier: AGPL-3.0-only
|
|
|
|
*/
|
|
|
|
|
2022-03-22 11:03:15 -04:00
|
|
|
package k8sapi
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/coreos/go-systemd/v22/dbus"
|
|
|
|
)
|
|
|
|
|
2022-05-19 11:18:22 -04:00
|
|
|
func restartSystemdUnit(ctx context.Context, unit string) error {
|
2022-03-22 11:03:15 -04:00
|
|
|
conn, err := dbus.NewSystemdConnectionContext(ctx)
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("establishing systemd connection: %w", err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
restartChan := make(chan string)
|
|
|
|
if _, err := conn.RestartUnitContext(ctx, unit, "replace", restartChan); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("restarting systemd unit %q: %w", unit, err)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for the restart to finish and actually check if it was
|
|
|
|
// successful or not.
|
|
|
|
result := <-restartChan
|
|
|
|
|
|
|
|
switch result {
|
|
|
|
case "done":
|
|
|
|
return nil
|
|
|
|
|
|
|
|
default:
|
2022-05-19 11:18:22 -04:00
|
|
|
return fmt.Errorf("restarting systemd unit %q failed: expected %v but received %v", unit, "done", result)
|
2022-03-22 11:03:15 -04:00
|
|
|
}
|
|
|
|
}
|
2022-05-19 11:18:22 -04:00
|
|
|
|
|
|
|
func startSystemdUnit(ctx context.Context, unit string) error {
|
|
|
|
conn, err := dbus.NewSystemdConnectionContext(ctx)
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("establishing systemd connection: %w", err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
startChan := make(chan string)
|
|
|
|
if _, err := conn.StartUnitContext(ctx, unit, "replace", startChan); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("starting systemd unit %q: %w", unit, err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for the enable to finish and actually check if it was
|
|
|
|
// successful or not.
|
|
|
|
result := <-startChan
|
|
|
|
|
|
|
|
switch result {
|
|
|
|
case "done":
|
|
|
|
return nil
|
|
|
|
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("starting systemd unit %q failed: expected %v but received %v", unit, "done", result)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func enableSystemdUnit(ctx context.Context, unitPath string) error {
|
|
|
|
conn, err := dbus.NewSystemdConnectionContext(ctx)
|
|
|
|
if err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("establishing systemd connection: %w", err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
if _, _, err := conn.EnableUnitFilesContext(ctx, []string{unitPath}, true, true); err != nil {
|
2022-06-09 10:04:30 -04:00
|
|
|
return fmt.Errorf("enabling systemd unit %q: %w", unitPath, err)
|
2022-05-19 11:18:22 -04:00
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|