sysv.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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. SysVServiceManager IServiceManager = &SSysVServiceManager{}
  21. )
  22. type SSysVServiceManager struct {
  23. }
  24. func (manager *SSysVServiceManager) Detect() bool {
  25. return procutils.NewCommand("chkconfig", "--version").Run() == nil
  26. }
  27. func (manager *SSysVServiceManager) Start(srvname string) error {
  28. return procutils.NewCommand("service", srvname, "restart").Run()
  29. }
  30. func (manager *SSysVServiceManager) Enable(srvname string) error {
  31. return procutils.NewCommand("chkconfig", srvname, "on").Run()
  32. }
  33. func (manager *SSysVServiceManager) Stop(srvname string) error {
  34. return procutils.NewCommand("service", srvname, "stop").Run()
  35. }
  36. func (manager *SSysVServiceManager) Disable(srvname string) error {
  37. return procutils.NewCommand("chkconfig", srvname, "off").Run()
  38. }
  39. func (manager *SSysVServiceManager) GetStatus(srvname string) SServiceStatus {
  40. res, _ := procutils.NewCommand("chkconfig", "--list", srvname).Output()
  41. res2, _ := procutils.NewCommand("service", srvname, "status").Output()
  42. return parseSysvStatus(string(res), string(res2), srvname)
  43. }
  44. func parseSysvStatus(res string, res2 string, srvname string) SServiceStatus {
  45. var ret SServiceStatus
  46. lines := strings.Split(res, "\n")
  47. for _, line := range lines {
  48. parts := strings.Split(strings.TrimSpace(line), "\t")
  49. for i := 1; i < len(parts); i++ {
  50. part := parts[i]
  51. part = strings.TrimSpace(part)
  52. if strings.HasSuffix(part, ":on") {
  53. ret.Enabled = true
  54. break
  55. }
  56. }
  57. if len(parts) > 1 && strings.TrimSpace(parts[0]) == srvname {
  58. ret.Loaded = true
  59. if strings.Index(res2, "running") > 0 {
  60. ret.Active = true
  61. }
  62. break
  63. }
  64. }
  65. return ret
  66. }