| // Copyright 2021 Google LLC | |
| // | |
| // Licensed under the Apache License, Version 2.0 (the "License"); | |
| // you may not use this file except in compliance with the License. | |
| // You may obtain a copy of the License at | |
| // | |
| // http://www.apache.org/licenses/LICENSE-2.0 | |
| // | |
| // Unless required by applicable law or agreed to in writing, software | |
| // distributed under the License is distributed on an "AS IS" BASIS, | |
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| // See the License for the specific language governing permissions and | |
| // limitations under the License. | |
| package systemd | |
| import ( | |
| "bytes" | |
| "fmt" | |
| "os/exec" | |
| "policy-manager/pkg/sysapi" | |
| "strings" | |
| ) | |
| // SystemdClient implements the SystemdClient interface. | |
| type SystemdClient struct { | |
| // systemctlCmd is a string to pass appropriate command. | |
| systemctlCmd string | |
| } | |
| // NewSystemdClient returns a new SystemdClient. | |
| func NewSystemdClient(systemctlCmd string) *SystemdClient { | |
| return &SystemdClient{systemctlCmd} | |
| } | |
| func (systemd *SystemdClient) IsUnitActiveRunning(name string) (bool, error) { | |
| cmd := exec.Command(systemd.systemctlCmd, "is-active", name) | |
| var stdout bytes.Buffer | |
| cmd.Stdout = &stdout | |
| err := cmd.Run() | |
| output := strings.TrimSpace(string(stdout.Bytes())) | |
| if err != nil { | |
| if exitError, ok := err.(*exec.ExitError); ok { | |
| code := exitError.ExitCode() | |
| if code == 3 || code == 4 { | |
| return false, nil | |
| } | |
| } | |
| return false, err | |
| } | |
| if output == "active" { | |
| return true, nil | |
| } | |
| return false, nil | |
| } | |
| func (systemd *SystemdClient) StartUnit(name string) error { | |
| _, _, err := sysapi.RunCommand(systemd.systemctlCmd, "start", name) | |
| return err | |
| } | |
| func (systemd *SystemdClient) StopUnit(name string) error { | |
| _, _, err := sysapi.RunCommand(systemd.systemctlCmd, "stop", name) | |
| return err | |
| } | |
| // ServiceExists checks if a systemd service exists (is loaded). | |
| func (systemd *SystemdClient) ServiceExists(name string) (bool, error) { | |
| stdout, _, err := sysapi.RunCommand(systemd.systemctlCmd, "show", name, "-p", "LoadState") | |
| if err != nil { | |
| return false, err | |
| } | |
| output := strings.TrimSpace(string(stdout)) | |
| if !strings.HasPrefix(output, "LoadState=") { | |
| return false, fmt.Errorf("unexpected output from systemctl show: %q", output) | |
| } | |
| return !strings.Contains(output, "LoadState=not-found"), nil | |
| } |