service_wrapper.py 7.4 KB

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