procmontap.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. # -*- test-case-name: twisted.runner.test.test_procmontap -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. Support for creating a service which runs a process monitor.
  6. """
  7. from typing import List, Sequence
  8. from twisted.python import usage
  9. from twisted.runner.procmon import ProcessMonitor
  10. class Options(usage.Options):
  11. """
  12. Define the options accepted by the I{twistd procmon} plugin.
  13. """
  14. synopsis = "[procmon options] commandline"
  15. optParameters = [
  16. [
  17. "threshold",
  18. "t",
  19. 1,
  20. "How long a process has to live "
  21. "before the death is considered instant, in seconds.",
  22. float,
  23. ],
  24. [
  25. "killtime",
  26. "k",
  27. 5,
  28. "How long a process being killed "
  29. "has to get its affairs in order before it gets killed "
  30. "with an unmaskable signal.",
  31. float,
  32. ],
  33. [
  34. "minrestartdelay",
  35. "m",
  36. 1,
  37. "The minimum time (in "
  38. "seconds) to wait before attempting to restart a "
  39. "process",
  40. float,
  41. ],
  42. [
  43. "maxrestartdelay",
  44. "M",
  45. 3600,
  46. "The maximum time (in "
  47. "seconds) to wait before attempting to restart a "
  48. "process",
  49. float,
  50. ],
  51. ]
  52. optFlags: List[Sequence[str]] = []
  53. longdesc = """\
  54. procmon runs processes, monitors their progress, and restarts them when they
  55. die.
  56. procmon will not attempt to restart a process that appears to die instantly;
  57. with each "instant" death (less than 1 second, by default), it will delay
  58. approximately twice as long before restarting it. A successful run will reset
  59. the counter.
  60. Eg twistd procmon sleep 10"""
  61. def parseArgs(self, *args: str) -> None:
  62. """
  63. Grab the command line that is going to be started and monitored
  64. """
  65. self["args"] = args
  66. def postOptions(self) -> None:
  67. """
  68. Check for dependencies.
  69. """
  70. if len(self["args"]) < 1:
  71. raise usage.UsageError("Please specify a process commandline")
  72. def makeService(config: Options) -> ProcessMonitor:
  73. s = ProcessMonitor()
  74. s.threshold = config["threshold"]
  75. s.killTime = config["killtime"]
  76. s.minRestartDelay = config["minrestartdelay"]
  77. s.maxRestartDelay = config["maxrestartdelay"]
  78. s.addProcess(" ".join(config["args"]), config["args"])
  79. return s