systemd.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package system_service
  15. import (
  16. "strings"
  17. "yunion.io/x/onecloud/pkg/util/procutils"
  18. )
  19. var (
  20. SystemdServiceManager IServiceManager = &SSystemdServiceManager{}
  21. )
  22. type SSystemdServiceManager struct {
  23. }
  24. func systemctl(args ...string) *procutils.Command {
  25. return procutils.NewRemoteCommandAsFarAsPossible("systemctl", args...)
  26. }
  27. func (manager *SSystemdServiceManager) Detect() bool {
  28. return systemctl("--version").Run() == nil
  29. }
  30. func (manager *SSystemdServiceManager) Start(srvname string) error {
  31. return systemctl("restart", srvname).Run()
  32. }
  33. func (manager *SSystemdServiceManager) Enable(srvname string) error {
  34. return systemctl("enable", srvname).Run()
  35. }
  36. func (manager *SSystemdServiceManager) Stop(srvname string) error {
  37. return systemctl("stop", srvname).Run()
  38. }
  39. func (manager *SSystemdServiceManager) Disable(srvname string) error {
  40. return systemctl("disable", srvname).Run()
  41. }
  42. func (manager *SSystemdServiceManager) GetStatus(srvname string) SServiceStatus {
  43. res, _ := systemctl("status", srvname).Output()
  44. res2, _ := systemctl("is-enabled", srvname).Output()
  45. return parseSystemdStatus(string(res), string(res2), srvname)
  46. }
  47. func parseSystemdStatus(res string, res2 string, srvname string) SServiceStatus {
  48. var ret SServiceStatus
  49. lines := strings.Split(res, "\n")
  50. for _, line := range lines {
  51. line = strings.TrimSpace(line)
  52. if strings.HasPrefix(line, "Loaded:") {
  53. parts := strings.Split(line, " ")
  54. if len(parts) > 1 && parts[1] == "loaded" {
  55. ret.Loaded = true
  56. }
  57. } else if strings.HasPrefix(line, "Active:") {
  58. parts := strings.Split(line, " ")
  59. if len(parts) > 1 && parts[1] == "active" {
  60. ret.Active = true
  61. }
  62. }
  63. }
  64. lines2 := strings.Split(res2, "\n")
  65. for _, line := range lines2 {
  66. switch line {
  67. case "enabled", "enabled-runtime":
  68. ret.Enabled = true
  69. break
  70. }
  71. }
  72. return ret
  73. }