flume.py 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 glob
  17. import ambari_simplejson as json # simplejson is much faster comparing to Python 2.6 json module and has the same functions set.
  18. import os
  19. from resource_management import *
  20. from resource_management.libraries.functions.flume_agent_helper import is_flume_process_live
  21. from resource_management.libraries.functions.flume_agent_helper import find_expected_agent_names
  22. from resource_management.libraries.functions.flume_agent_helper import await_flume_process_termination
  23. from ambari_commons import OSConst
  24. from ambari_commons.os_family_impl import OsFamilyFuncImpl, OsFamilyImpl
  25. @OsFamilyFuncImpl(os_family=OSConst.WINSRV_FAMILY)
  26. def flume(action = None):
  27. import params
  28. from service_mapping import flume_win_service_name
  29. if action == 'config':
  30. ServiceConfig(flume_win_service_name,
  31. action="configure",
  32. start_type="manual")
  33. ServiceConfig(flume_win_service_name,
  34. action="change_user",
  35. username=params.flume_user,
  36. password = Script.get_password(params.flume_user))
  37. # remove previously defined meta's
  38. for n in find_expected_agent_names(params.flume_conf_dir):
  39. os.unlink(os.path.join(params.flume_conf_dir, n, 'ambari-meta.json'))
  40. flume_agents = {}
  41. if params.flume_conf_content is not None:
  42. flume_agents = build_flume_topology(params.flume_conf_content)
  43. for agent in flume_agents.keys():
  44. flume_agent_conf_dir = os.path.join(params.flume_conf_dir, agent)
  45. flume_agent_conf_file = os.path.join(flume_agent_conf_dir, 'flume.conf')
  46. flume_agent_meta_file = os.path.join(flume_agent_conf_dir, 'ambari-meta.json')
  47. flume_agent_log4j_file = os.path.join(flume_agent_conf_dir, 'log4j.properties')
  48. flume_agent_env_file = os.path.join(flume_agent_conf_dir, 'flume-env.ps1')
  49. Directory(flume_agent_conf_dir
  50. )
  51. PropertiesFile(flume_agent_conf_file,
  52. properties=flume_agents[agent])
  53. File(flume_agent_log4j_file,
  54. content=Template('log4j.properties.j2', agent_name = agent))
  55. File(flume_agent_meta_file,
  56. content = json.dumps(ambari_meta(agent, flume_agents[agent])))
  57. File(flume_agent_env_file,
  58. owner=params.flume_user,
  59. content=InlineTemplate(params.flume_env_sh_template)
  60. )
  61. if params.has_metric_collector:
  62. File(os.path.join(flume_agent_conf_dir, "flume-metrics2.properties"),
  63. owner=params.flume_user,
  64. content=Template("flume-metrics2.properties.j2")
  65. )
  66. @OsFamilyFuncImpl(os_family=OsFamilyImpl.DEFAULT)
  67. def flume(action = None):
  68. import params
  69. if action == 'config':
  70. # remove previously defined meta's
  71. for n in find_expected_agent_names(params.flume_conf_dir):
  72. File(os.path.join(params.flume_conf_dir, n, 'ambari-meta.json'),
  73. action = "delete",
  74. )
  75. Directory(params.flume_run_dir,
  76. )
  77. Directory(params.flume_conf_dir,
  78. recursive=True,
  79. owner=params.flume_user,
  80. )
  81. Directory(params.flume_log_dir, owner=params.flume_user)
  82. flume_agents = {}
  83. if params.flume_conf_content is not None:
  84. flume_agents = build_flume_topology(params.flume_conf_content)
  85. for agent in flume_agents.keys():
  86. flume_agent_conf_dir = os.path.join(params.flume_conf_dir, agent)
  87. flume_agent_conf_file = os.path.join(flume_agent_conf_dir, 'flume.conf')
  88. flume_agent_meta_file = os.path.join(flume_agent_conf_dir, 'ambari-meta.json')
  89. flume_agent_log4j_file = os.path.join(flume_agent_conf_dir, 'log4j.properties')
  90. flume_agent_env_file = os.path.join(flume_agent_conf_dir, 'flume-env.sh')
  91. Directory(flume_agent_conf_dir,
  92. owner=params.flume_user,
  93. )
  94. PropertiesFile(flume_agent_conf_file,
  95. properties=flume_agents[agent],
  96. owner=params.flume_user,
  97. mode = 0644)
  98. File(flume_agent_log4j_file,
  99. content=Template('log4j.properties.j2', agent_name = agent),
  100. owner=params.flume_user,
  101. mode = 0644)
  102. File(flume_agent_meta_file,
  103. content = json.dumps(ambari_meta(agent, flume_agents[agent])),
  104. owner=params.flume_user,
  105. mode = 0644)
  106. File(flume_agent_env_file,
  107. owner=params.flume_user,
  108. content=InlineTemplate(params.flume_env_sh_template)
  109. )
  110. if params.has_metric_collector:
  111. File(os.path.join(flume_agent_conf_dir, "flume-metrics2.properties"),
  112. owner=params.flume_user,
  113. content=Template("flume-metrics2.properties.j2")
  114. )
  115. elif action == 'start':
  116. # desired state for service should be STARTED
  117. if len(params.flume_command_targets) == 0:
  118. _set_desired_state('STARTED')
  119. # It is important to run this command as a background process.
  120. flume_base = as_user(format("{flume_bin} agent --name {{0}} --conf {{1}} --conf-file {{2}} {{3}} > {flume_log_dir}/{{4}}.out 2>&1"), params.flume_user, env={'JAVA_HOME': params.java_home}) + " &"
  121. for agent in cmd_target_names():
  122. flume_agent_conf_dir = params.flume_conf_dir + os.sep + agent
  123. flume_agent_conf_file = flume_agent_conf_dir + os.sep + "flume.conf"
  124. flume_agent_pid_file = params.flume_run_dir + os.sep + agent + ".pid"
  125. if not os.path.isfile(flume_agent_conf_file):
  126. continue
  127. if not is_flume_process_live(flume_agent_pid_file):
  128. # TODO someday make the ganglia ports configurable
  129. extra_args = ''
  130. if params.ganglia_server_host is not None:
  131. extra_args = '-Dflume.monitoring.type=ganglia -Dflume.monitoring.hosts={0}:{1}'
  132. extra_args = extra_args.format(params.ganglia_server_host, '8655')
  133. if params.has_metric_collector:
  134. extra_args = '-Dflume.monitoring.type=org.apache.hadoop.metrics2.sink.flume.FlumeTimelineMetricsSink ' \
  135. '-Dflume.monitoring.node={0}:{1}'
  136. extra_args = extra_args.format(params.metric_collector_host, params.metric_collector_port)
  137. flume_cmd = flume_base.format(agent, flume_agent_conf_dir,
  138. flume_agent_conf_file, extra_args, agent)
  139. Execute(flume_cmd,
  140. wait_for_finish=False,
  141. environment={'JAVA_HOME': params.java_home}
  142. )
  143. # sometimes startup spawns a couple of threads - so only the first line may count
  144. pid_cmd = as_sudo(('pgrep', '-o', '-u', params.flume_user, '-f', format('^{java_home}.*{agent}.*'))) + \
  145. " | " + as_sudo(('tee', flume_agent_pid_file)) + " && test ${PIPESTATUS[0]} -eq 0"
  146. Execute(pid_cmd,
  147. logoutput=True,
  148. tries=20,
  149. try_sleep=10)
  150. pass
  151. elif action == 'stop':
  152. # desired state for service should be INSTALLED
  153. if len(params.flume_command_targets) == 0:
  154. _set_desired_state('INSTALLED')
  155. pid_files = glob.glob(params.flume_run_dir + os.sep + "*.pid")
  156. if 0 == len(pid_files):
  157. return
  158. agent_names = cmd_target_names()
  159. for agent in agent_names:
  160. pid_file = format("{flume_run_dir}/{agent}.pid")
  161. if is_flume_process_live(pid_file):
  162. pid = shell.checked_call(("cat", pid_file), sudo=True)[1].strip()
  163. Execute(("kill", "-15", pid), sudo=True) # kill command has to be a tuple
  164. if not await_flume_process_termination(pid_file):
  165. raise Fail("Can't stop flume agent: {0}".format(agent))
  166. File(pid_file, action = 'delete')
  167. def ambari_meta(agent_name, agent_conf):
  168. res = {}
  169. sources = agent_conf[agent_name + '.sources'].split(' ')
  170. res['sources_count'] = len(sources)
  171. sinks = agent_conf[agent_name + '.sinks'].split(' ')
  172. res['sinks_count'] = len(sinks)
  173. channels = agent_conf[agent_name + '.channels'].split(' ')
  174. res['channels_count'] = len(channels)
  175. return res
  176. # define a map of dictionaries, where the key is agent name
  177. # and the dictionary is the name/value pair
  178. def build_flume_topology(content):
  179. result = {}
  180. agent_names = []
  181. for line in content.split('\n'):
  182. rline = line.strip()
  183. if 0 != len(rline) and not rline.startswith('#'):
  184. pair = rline.split('=')
  185. lhs = pair[0].strip()
  186. rhs = pair[1].strip()
  187. part0 = lhs.split('.')[0]
  188. if lhs.endswith(".sources"):
  189. agent_names.append(part0)
  190. if not result.has_key(part0):
  191. result[part0] = {}
  192. result[part0][lhs] = rhs
  193. # trim out non-agents
  194. for k in result.keys():
  195. if not k in agent_names:
  196. del result[k]
  197. return result
  198. def cmd_target_names():
  199. import params
  200. if len(params.flume_command_targets) > 0:
  201. return params.flume_command_targets
  202. else:
  203. return find_expected_agent_names(params.flume_conf_dir)
  204. def _set_desired_state(state):
  205. import params
  206. File(params.ambari_state_file,
  207. content = state,
  208. )
  209. def get_desired_state():
  210. import params
  211. from resource_management.core import sudo
  212. if os.path.exists(params.ambari_state_file):
  213. return sudo.read_file(params.ambari_state_file)
  214. else:
  215. return 'INSTALLED'