service_wrapper.py 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. '''
  2. Licensed to the Apache Software Foundation (ASF) under one
  3. or more contributor license agreements. See the NOTICE file
  4. distributed with this work for additional information
  5. regarding copyright ownership. The ASF licenses this file
  6. to you under the Apache License, Version 2.0 (the
  7. "License"); you may not use this file except in compliance
  8. with the License. You may obtain a copy of the License at
  9. http://www.apache.org/licenses/LICENSE-2.0
  10. Unless required by applicable law or agreed to in writing, software
  11. distributed under the License is distributed on an "AS IS" BASIS,
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. See the License for the specific language governing permissions and
  14. limitations under the License.
  15. '''
  16. import os
  17. import optparse
  18. import sys
  19. import win32serviceutil
  20. import win32api
  21. import win32event
  22. import win32service
  23. from ambari_commons.ambari_service import AmbariService, ENV_PYTHON_PATH
  24. from ambari_commons.exceptions import *
  25. from ambari_commons.logging_utils import *
  26. from ambari_commons.os_windows import WinServiceController
  27. from ambari_commons.os_utils import find_in_path
  28. from ambari_agent.AmbariConfig import AmbariConfig
  29. from ambari_agent.HeartbeatHandlers import HeartbeatStopHandlers
  30. AMBARI_VERSION_VAR = "AMBARI_VERSION_VAR"
  31. SETUP_ACTION = "setup"
  32. START_ACTION = "start"
  33. STOP_ACTION = "stop"
  34. RESET_ACTION = "reset"
  35. STATUS_ACTION = "status"
  36. DEBUG_ACTION = "debug"
  37. def parse_options():
  38. # parse env cmd
  39. with open(os.path.join(os.getcwd(), "ambari-env.cmd"), "r") as env_cmd:
  40. content = env_cmd.readlines()
  41. for line in content:
  42. if line.startswith("set"):
  43. name, value = line[4:].split("=")
  44. os.environ[name] = value.rstrip()
  45. # checking env variables, and fallback to working dir if no env var was founded
  46. if not os.environ.has_key("AMBARI_AGENT_CONF_DIR"):
  47. os.environ["AMBARI_AGENT_CONF_DIR"] = os.getcwd()
  48. if not os.environ.has_key("AMBARI_AGENT_LOG_DIR"):
  49. os.environ["AMBARI_AGENT_LOG_DIR"] = os.path.join("\\", "var", "log", "ambari-agent")
  50. if not os.path.exists(os.environ["AMBARI_AGENT_LOG_DIR"]):
  51. os.makedirs(os.environ["AMBARI_AGENT_LOG_DIR"])
  52. if not os.environ.has_key("PYTHON_EXE"):
  53. os.environ["PYTHON_EXE"] = find_in_path("python.exe")
  54. class AmbariAgentService(AmbariService):
  55. AmbariService._svc_name_ = "Ambari Agent"
  56. AmbariService._svc_display_name_ = "Ambari Agent"
  57. AmbariService._svc_description_ = "Ambari Agent"
  58. AmbariService._AdjustServiceVersion()
  59. heartbeat_stop_handler = None
  60. # Adds the necessary script dir to the Python's modules path
  61. def _adjustPythonPath(self, current_dir):
  62. iPos = 0
  63. python_path = os.path.join(current_dir, "sbin")
  64. sys.path.insert(iPos, python_path)
  65. # Add the alerts and apscheduler subdirs to the path, for the imports to work correctly without
  66. # having to modify the files in these 2 subdirectories
  67. agent_path = os.path.join(current_dir, "sbin", "ambari_agent")
  68. iPos += 1
  69. sys.path.insert(iPos, agent_path)
  70. for subdir in os.listdir(agent_path):
  71. full_subdir = os.path.join(agent_path, subdir)
  72. iPos += 1
  73. sys.path.insert(iPos, full_subdir)
  74. def SvcDoRun(self):
  75. parse_options()
  76. self.redirect_output_streams()
  77. # Soft dependency on the Windows Time service
  78. ensure_time_service_is_started()
  79. self.heartbeat_stop_handler = HeartbeatStopHandlers(AmbariAgentService._heventSvcStop)
  80. self.ReportServiceStatus(win32service.SERVICE_RUNNING)
  81. from ambari_agent import main
  82. main.main(self.heartbeat_stop_handler)
  83. def _InitOptionsParser(self):
  84. return init_options_parser()
  85. def redirect_output_streams(self):
  86. self._RedirectOutputStreamsToFile(AmbariConfig.getOutFile())
  87. pass
  88. def ensure_time_service_is_started():
  89. ret = WinServiceController.EnsureServiceIsStarted("W32Time")
  90. if 0 != ret:
  91. raise FatalException(-1, "Error starting Windows Time service: " + str(ret))
  92. pass
  93. def ctrlHandler(ctrlType):
  94. AmbariAgentService.DefCtrlCHandler()
  95. return True
  96. def svcsetup():
  97. AmbariAgentService.set_ctrl_c_handler(ctrlHandler)
  98. AmbariAgentService.Install()
  99. pass
  100. #
  101. # Starts the Ambari Agent as a service.
  102. # Start the Agent in normal mode, as a Windows service. If the Ambari Agent is
  103. # not registered as a service, the function fails. By default, only one instance of the service can
  104. # possibly run.
  105. #
  106. def svcstart(options):
  107. if 0 != AmbariAgentService.Start(15):
  108. options.exit_message = None
  109. pass
  110. #
  111. # Stops the Ambari Agent.
  112. #
  113. def svcstop(options):
  114. if 0 != AmbariAgentService.Stop():
  115. options.exit_message = None
  116. #
  117. # The Ambari Agent status.
  118. #
  119. def svcstatus(options):
  120. options.exit_message = None
  121. statusStr = AmbariAgentService.QueryStatus()
  122. print "Ambari Agent is " + statusStr
  123. def svcdebug(options):
  124. sys.frozen = 'windows_exe' # Fake py2exe so we can debug
  125. AmbariAgentService.set_ctrl_c_handler(ctrlHandler)
  126. win32serviceutil.HandleCommandLine(AmbariAgentService, options)
  127. def init_options_parser():
  128. parser = optparse.OptionParser(usage="usage: %prog action [options]", )
  129. parser.add_option('-r', '--hostname', dest="host_name", default="localhost",
  130. help="Use specified Ambari server host for registration.")
  131. parser.add_option('-j', '--java-home', dest="java_home", default=None,
  132. help="Use specified java_home. Must be valid on all hosts")
  133. parser.add_option("-v", "--verbose",
  134. action="store_true", dest="verbose", default=False,
  135. help="Print verbose status messages")
  136. parser.add_option("-s", "--silent",
  137. action="store_true", dest="silent", default=False,
  138. help="Silently accepts default prompt values")
  139. parser.add_option('--jdbc-driver', default=None,
  140. help="Specifies the path to the JDBC driver JAR file for the " \
  141. "database type specified with the --jdbc-db option. Used only with --jdbc-db option.",
  142. dest="jdbc_driver")
  143. return parser
  144. #
  145. # Main.
  146. #
  147. def agent_main():
  148. parser = init_options_parser()
  149. (options, args) = parser.parse_args()
  150. options.warnings = []
  151. if len(args) == 0:
  152. print parser.print_help()
  153. parser.error("No action entered")
  154. action = args[0]
  155. possible_args_numbers = [1]
  156. matches = 0
  157. for args_number_required in possible_args_numbers:
  158. matches += int(len(args) == args_number_required)
  159. if matches == 0:
  160. print parser.print_help()
  161. possible_args = ' or '.join(str(x) for x in possible_args_numbers)
  162. parser.error("Invalid number of arguments. Entered: " + str(len(args)) + ", required: " + possible_args)
  163. options.exit_message = "Ambari Agent '%s' completed successfully." % action
  164. try:
  165. if action == SETUP_ACTION:
  166. #TODO Insert setup(options) here upon need
  167. svcsetup()
  168. elif action == START_ACTION:
  169. svcstart(options)
  170. elif action == DEBUG_ACTION:
  171. svcdebug(options)
  172. elif action == STOP_ACTION:
  173. svcstop(options)
  174. elif action == STATUS_ACTION:
  175. svcstatus(options)
  176. else:
  177. parser.error("Invalid action")
  178. if options.warnings:
  179. for warning in options.warnings:
  180. print_warning_msg(warning)
  181. pass
  182. options.exit_message = "Ambari Agent '%s' completed with warnings." % action
  183. pass
  184. except FatalException as e:
  185. if e.reason is not None:
  186. print_error_msg("Exiting with exit code {0}. \nREASON: {1}".format(e.code, e.reason))
  187. sys.exit(e.code)
  188. except NonFatalException as e:
  189. options.exit_message = "Ambari Agent '%s' completed with warnings." % action
  190. if e.reason is not None:
  191. print_warning_msg(e.reason)
  192. if options.exit_message is not None:
  193. print options.exit_message
  194. if __name__ == '__main__':
  195. try:
  196. agent_main()
  197. except (KeyboardInterrupt, EOFError):
  198. print("\nAborting ... Keyboard Interrupt.")
  199. sys.exit(1)