service_wrapper.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  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 ConfigParser
  17. import os
  18. import optparse
  19. import sys
  20. import win32serviceutil
  21. import win32api
  22. import win32event
  23. import win32service
  24. from ambari_commons.ambari_service import AmbariService, ENV_PYTHON_PATH
  25. from ambari_commons.exceptions import *
  26. from ambari_commons.logging_utils import *
  27. from ambari_commons.os_windows import WinServiceController
  28. from ambari_commons.os_utils import find_in_path
  29. from ambari_agent.AmbariConfig import AmbariConfig, updateConfigServerHostname
  30. from ambari_agent.HeartbeatHandlers import HeartbeatStopHandlers
  31. AMBARI_VERSION_VAR = "AMBARI_VERSION_VAR"
  32. SETUP_ACTION = "setup"
  33. START_ACTION = "start"
  34. STOP_ACTION = "stop"
  35. RESET_ACTION = "reset"
  36. STATUS_ACTION = "status"
  37. DEBUG_ACTION = "debug"
  38. def parse_options():
  39. # parse env cmd
  40. with open(os.path.join(os.getcwd(), "ambari-env.cmd"), "r") as env_cmd:
  41. content = env_cmd.readlines()
  42. for line in content:
  43. if line.startswith("set"):
  44. name, value = line[4:].split("=")
  45. os.environ[name] = value.rstrip()
  46. # checking env variables, and fallback to working dir if no env var was founded
  47. if not os.environ.has_key("AMBARI_AGENT_CONF_DIR"):
  48. os.environ["AMBARI_AGENT_CONF_DIR"] = os.getcwd()
  49. if not os.environ.has_key("AMBARI_AGENT_LOG_DIR"):
  50. os.environ["AMBARI_AGENT_LOG_DIR"] = os.path.join("\\", "var", "log", "ambari-agent")
  51. if not os.path.exists(os.environ["AMBARI_AGENT_LOG_DIR"]):
  52. os.makedirs(os.environ["AMBARI_AGENT_LOG_DIR"])
  53. if not os.environ.has_key("PYTHON_EXE"):
  54. os.environ["PYTHON_EXE"] = find_in_path("python.exe")
  55. class AmbariAgentService(AmbariService):
  56. AmbariService._svc_name_ = "Ambari Agent"
  57. AmbariService._svc_display_name_ = "Ambari Agent"
  58. AmbariService._svc_description_ = "Ambari Agent"
  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. #
  97. # Configures the Ambari Agent settings and registers the Windows service.
  98. #
  99. def setup(options):
  100. config = AmbariConfig()
  101. # TODO AMBARI-18733, need to read home_dir to get correct config file.
  102. configFile = config.getConfigFile()
  103. updateConfigServerHostname(configFile, options.host_name)
  104. AmbariAgentService.set_ctrl_c_handler(ctrlHandler)
  105. AmbariAgentService.Install()
  106. #
  107. # Starts the Ambari Agent as a service.
  108. # Start the Agent in normal mode, as a Windows service. If the Ambari Agent is
  109. # not registered as a service, the function fails. By default, only one instance of the service can
  110. # possibly run.
  111. #
  112. def svcstart(options):
  113. (ret, msg) = AmbariAgentService.Start(15)
  114. if 0 != ret:
  115. options.exit_message = msg
  116. pass
  117. #
  118. # Stops the Ambari Agent.
  119. #
  120. def svcstop(options):
  121. (ret, msg) = AmbariAgentService.Stop()
  122. if 0 != ret:
  123. options.exit_message = msg
  124. #
  125. # The Ambari Agent status.
  126. #
  127. def svcstatus(options):
  128. options.exit_message = None
  129. statusStr = AmbariAgentService.QueryStatus()
  130. print "Ambari Agent is " + statusStr
  131. def svcdebug(options):
  132. sys.frozen = 'windows_exe' # Fake py2exe so we can debug
  133. AmbariAgentService.set_ctrl_c_handler(ctrlHandler)
  134. win32serviceutil.HandleCommandLine(AmbariAgentService, options)
  135. def init_options_parser():
  136. parser = optparse.OptionParser(usage="usage: %prog action [options]", )
  137. parser.add_option('-r', '--hostname', dest="host_name", default="localhost",
  138. help="Use specified Ambari server host for registration.")
  139. parser.add_option('-j', '--java-home', dest="java_home", default=None,
  140. help="Use specified java_home. Must be valid on all hosts")
  141. parser.add_option("-v", "--verbose",
  142. action="store_true", dest="verbose", default=False,
  143. help="Print verbose status messages")
  144. parser.add_option("-s", "--silent",
  145. action="store_true", dest="silent", default=False,
  146. help="Silently accepts default prompt values")
  147. parser.add_option('--jdbc-driver', default=None,
  148. help="Specifies the path to the JDBC driver JAR file for the " \
  149. "database type specified with the --jdbc-db option. Used only with --jdbc-db option.",
  150. dest="jdbc_driver")
  151. return parser
  152. #
  153. # Main.
  154. #
  155. def agent_main():
  156. parser = init_options_parser()
  157. (options, args) = parser.parse_args()
  158. options.warnings = []
  159. if len(args) == 0:
  160. print parser.print_help()
  161. parser.error("No action entered")
  162. action = args[0]
  163. possible_args_numbers = [1]
  164. matches = 0
  165. for args_number_required in possible_args_numbers:
  166. matches += int(len(args) == args_number_required)
  167. if matches == 0:
  168. print parser.print_help()
  169. possible_args = ' or '.join(str(x) for x in possible_args_numbers)
  170. parser.error("Invalid number of arguments. Entered: " + str(len(args)) + ", required: " + possible_args)
  171. options.exit_message = "Ambari Agent '%s' completed successfully." % action
  172. try:
  173. if action == SETUP_ACTION:
  174. setup(options)
  175. elif action == START_ACTION:
  176. svcstart(options)
  177. elif action == DEBUG_ACTION:
  178. svcdebug(options)
  179. elif action == STOP_ACTION:
  180. svcstop(options)
  181. elif action == STATUS_ACTION:
  182. svcstatus(options)
  183. else:
  184. parser.error("Invalid action")
  185. if options.warnings:
  186. for warning in options.warnings:
  187. print_warning_msg(warning)
  188. pass
  189. options.exit_message = "Ambari Agent '%s' completed with warnings." % action
  190. pass
  191. except FatalException as e:
  192. if e.reason is not None:
  193. print_error_msg("Exiting with exit code {0}. \nREASON: {1}".format(e.code, e.reason))
  194. sys.exit(e.code)
  195. except NonFatalException as e:
  196. options.exit_message = "Ambari Agent '%s' completed with warnings." % action
  197. if e.reason is not None:
  198. print_warning_msg(e.reason)
  199. if options.exit_message is not None:
  200. print options.exit_message
  201. if __name__ == '__main__':
  202. try:
  203. agent_main()
  204. except (KeyboardInterrupt, EOFError):
  205. print("\nAborting ... Keyboard Interrupt.")
  206. sys.exit(1)