service.py 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from comar.service import *
  2. import os
  3. serviceType = "server"
  4. serviceDefault = "off"
  5. serviceDesc = _({"en": "OpenVPN",
  6. "tr": "OpenVPN"})
  7. OPENVPN = "/usr/sbin/openvpn"
  8. PIDDIR = "/run/openvpn"
  9. WORKDIR = "/etc/openvpn"
  10. PIDFILE = ""
  11. MSG_NOCONF = _({"en": "%s doesn't contain any OpenVPN configuration file." % WORKDIR,
  12. "tr": "%s herhangi bir OpenVPN yapılandırma dosyası içermiyor." % WORKDIR,
  13. })
  14. @synchronized
  15. def start():
  16. # Load tun
  17. os.system("modprobe -q tun")
  18. # Run startup script if defined
  19. if os.path.exists(os.path.join(WORKDIR, "openvpn-startup.sh")):
  20. os.system(os.path.join(WORKDIR, "openvpn-startup.sh"))
  21. configs = [_c for _c in os.listdir(WORKDIR) if _c.endswith(".conf")]
  22. if len(configs) > 0:
  23. # There's at least 1 OpenVPN configuration to start
  24. # Start every .conf in WORKDIR and run .sh if it exists
  25. for conf in configs:
  26. conf_name = conf.split(".conf")[0]
  27. sh_name = os.path.join(WORKDIR, "%s.sh" % conf_name)
  28. PIDFILE = os.path.join(PIDDIR, "%s.pid" % conf_name)
  29. if os.path.exists(sh_name):
  30. os.system(sh_name)
  31. # Clean stale pid files
  32. if os.path.exists(PIDFILE):
  33. os.unlink(PIDFILE)
  34. startService(command=OPENVPN,
  35. args="--daemon --writepid %s --config %s/%s --cd %s --script-security 2" % (PIDFILE, WORKDIR, conf, WORKDIR),
  36. pidfile=PIDFILE,
  37. donotify=True)
  38. # Reset PIDFILE. This is a hack for status() calls from startService() problems..
  39. PIDFILE = ""
  40. else:
  41. fail(MSG_NOCONF)
  42. @synchronized
  43. def stop():
  44. for pidf in [pid for pid in os.listdir(PIDDIR) if pid.endswith(".pid")]:
  45. stopService(pidfile="%s/%s" % (PIDDIR, pidf),
  46. donotify=True)
  47. try:
  48. os.unlink(os.path.join(PIDDIR, pidf))
  49. except OSError:
  50. pass
  51. # Run shutdown script if defined
  52. if os.path.exists(os.path.join(WORKDIR, "openvpn-shutdown.sh")):
  53. os.system(os.path.join(WORKDIR, "openvpn-shutdown.sh"))
  54. @synchronized
  55. def reload():
  56. import signal
  57. for pidf in [pid for pid in os.listdir(PIDDIR) if pid.endswith(".pid")]:
  58. stopService(pidfile="%s/%s" % (PIDDIR, pidf),
  59. signalno=signal.SIGHUP,
  60. donotify=True)
  61. def status():
  62. if PIDFILE:
  63. return isServiceRunning(pidfile=PIDFILE)
  64. else:
  65. state = False
  66. for pidf in [pid for pid in os.listdir(PIDDIR) if pid.endswith(".pid")]:
  67. PIDFILE = os.path.join(PIDDIR, pidf)
  68. state = state and isServiceRunning(pidfile=PIDFILE)
  69. return state