blob: 043ef00c8bcc75f0ef093a30540e1f92aa811515 [file] [log] [blame]
// 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"
"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 && output != "inactive" {
return false, err
} else 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
}