TestCheckHost.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  1. # !/usr/bin/env python
  2. '''
  3. Licensed to the Apache Software Foundation (ASF) under one
  4. or more contributor license agreements. See the NOTICE file
  5. distributed with this work for additional information
  6. regarding copyright ownership. The ASF licenses this file
  7. to you under the Apache License, Version 2.0 (the
  8. "License"); you may not use this file except in compliance
  9. with the License. You may obtain a copy of the License at
  10. http://www.apache.org/licenses/LICENSE-2.0
  11. Unless required by applicable law or agreed to in writing, software
  12. distributed under the License is distributed on an "AS IS" BASIS,
  13. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. See the License for the specific language governing permissions and
  15. limitations under the License.
  16. '''
  17. from stacks.utils.RMFTestCase import *
  18. import json
  19. import os
  20. import socket
  21. import subprocess
  22. from ambari_commons import inet_utils, OSCheck
  23. from resource_management import Script, ConfigDictionary
  24. from mock.mock import patch
  25. from mock.mock import MagicMock
  26. from unittest import TestCase
  27. from check_host import CheckHost
  28. from only_for_platform import only_for_platform, get_platform, PLATFORM_LINUX, PLATFORM_WINDOWS
  29. from ambari_agent.HostCheckReportFileHandler import HostCheckReportFileHandler
  30. if get_platform() != PLATFORM_WINDOWS:
  31. os_distro_value = ('Suse','11','Final')
  32. else:
  33. os_distro_value = ('win2012serverr2','6.3','WindowsServer')
  34. @patch.object(HostCheckReportFileHandler, "writeHostChecksCustomActionsFile", new=MagicMock())
  35. @patch.object(HostCheckReportFileHandler, "resolve_ambari_config", new=MagicMock())
  36. class TestCheckHost(TestCase):
  37. current_dir = os.path.dirname(os.path.realpath(__file__))
  38. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  39. @patch("os.path.isfile")
  40. @patch.object(Script, 'get_config')
  41. @patch.object(Script, 'get_tmp_dir')
  42. @patch("resource_management.libraries.script.Script.put_structured_out")
  43. def testJavaHomeAvailableCheck(self, structured_out_mock, get_tmp_dir_mock, mock_config, os_isfile_mock):
  44. # test, java home exists
  45. os_isfile_mock.return_value = True
  46. get_tmp_dir_mock.return_value = "/tmp"
  47. mock_config.return_value = {"commandParams" : {"check_execute_list" : "java_home_check",
  48. "java_home" : "test_java_home"}}
  49. checkHost = CheckHost()
  50. checkHost.actionexecute(None)
  51. self.assertEquals(structured_out_mock.call_args[0][0], {'java_home_check': {'message': 'Java home exists!',
  52. 'exit_code': 0}})
  53. # test, java home doesn't exist
  54. os_isfile_mock.reset_mock()
  55. os_isfile_mock.return_value = False
  56. checkHost.actionexecute(None)
  57. self.assertEquals(structured_out_mock.call_args[0][0], {'java_home_check': {"message": "Java home doesn't exist!",
  58. "exit_code" : 1}})
  59. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  60. @patch.object(Script, 'get_config')
  61. @patch.object(Script, 'get_tmp_dir')
  62. @patch("check_host.download_file")
  63. @patch("resource_management.libraries.script.Script.put_structured_out")
  64. @patch("check_host.format")
  65. @patch("os.path.isfile")
  66. @patch("resource_management.core.shell.call")
  67. def testDBConnectionCheck(self, shell_call_mock, isfile_mock, format_mock, structured_out_mock, download_file_mock, get_tmp_dir_mock, mock_config):
  68. # test, download DBConnectionVerification.jar failed
  69. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  70. "java_home" : "test_java_home",
  71. "ambari_server_host" : "test_host",
  72. "jdk_location" : "test_jdk_location",
  73. "db_name" : "mysql",
  74. "db_connection_url" : "test_db_connection_url",
  75. "user_name" : "test_user_name",
  76. "user_passwd" : "test_user_passwd",
  77. "jdk_name" : "test_jdk_name"},
  78. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  79. get_tmp_dir_mock.return_value = "/tmp"
  80. download_file_mock.side_effect = Exception("test exception")
  81. isfile_mock.return_value = True
  82. checkHost = CheckHost()
  83. checkHost.actionexecute(None)
  84. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Error downloading ' \
  85. 'DBConnectionVerification.jar from Ambari Server resources. Check network access to Ambari ' \
  86. 'Server.\ntest exception', 'exit_code': 1}})
  87. # test, download jdbc driver failed
  88. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  89. "java_home" : "test_java_home",
  90. "ambari_server_host" : "test_host",
  91. "jdk_location" : "test_jdk_location",
  92. "db_name" : "oracle",
  93. "db_connection_url" : "test_db_connection_url",
  94. "user_name" : "test_user_name",
  95. "user_passwd" : "test_user_passwd",
  96. "jdk_name" : "test_jdk_name"},
  97. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  98. format_mock.reset_mock()
  99. download_file_mock.reset_mock()
  100. p = MagicMock()
  101. download_file_mock.side_effect = [p, Exception("test exception")]
  102. checkHost.actionexecute(None)
  103. self.assertEquals(format_mock.call_args[0][0], 'Error: Ambari Server cannot download the database JDBC driver '
  104. 'and is unable to test the database connection. You must run ambari-server setup '
  105. '--jdbc-db={db_name} --jdbc-driver=/path/to/your/{db_name}/driver.jar on the Ambari '
  106. 'Server host to make the JDBC driver available for download and to enable testing '
  107. 'the database connection.\n')
  108. self.assertEquals(structured_out_mock.call_args[0][0]['db_connection_check']['exit_code'], 1)
  109. # test, no connection to remote db
  110. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  111. "java_home" : "test_java_home",
  112. "ambari_server_host" : "test_host",
  113. "jdk_location" : "test_jdk_location",
  114. "db_name" : "postgres",
  115. "db_connection_url" : "test_db_connection_url",
  116. "user_name" : "test_user_name",
  117. "user_passwd" : "test_user_passwd",
  118. "jdk_name" : "test_jdk_name"},
  119. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  120. format_mock.reset_mock()
  121. download_file_mock.reset_mock()
  122. download_file_mock.side_effect = [p, p]
  123. shell_call_mock.return_value = (1, "test message")
  124. checkHost.actionexecute(None)
  125. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'test message',
  126. 'exit_code': 1}})
  127. self.assertEquals(format_mock.call_args[0][0],'{java_exec} -cp '\
  128. '{check_db_connection_path}{class_path_delimiter}{jdbc_path} -Djava.library.path={agent_cache_dir} '\
  129. 'org.apache.ambari.server.DBConnectionVerification \"{db_connection_url}\" '\
  130. '{user_name} {user_passwd!p} {jdbc_driver}')
  131. # test, db connection success
  132. download_file_mock.reset_mock()
  133. download_file_mock.side_effect = [p, p]
  134. shell_call_mock.return_value = (0, "test message")
  135. checkHost.actionexecute(None)
  136. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check':
  137. {'message': 'DB connection check completed successfully!', 'exit_code': 0}})
  138. #test jdk_name and java home are not available
  139. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  140. "java_home" : "test_java_home",
  141. "ambari_server_host" : "test_host",
  142. "jdk_location" : "test_jdk_location",
  143. "db_connection_url" : "test_db_connection_url",
  144. "user_name" : "test_user_name",
  145. "user_passwd" : "test_user_passwd",
  146. "db_name" : "postgres"},
  147. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  148. isfile_mock.return_value = False
  149. checkHost.actionexecute(None)
  150. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Custom java is not ' \
  151. 'available on host. Please install it. Java home should be the same as on server. \n', 'exit_code': 1}})
  152. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  153. @patch("socket.gethostbyname")
  154. @patch.object(Script, 'get_config')
  155. @patch.object(Script, 'get_tmp_dir')
  156. @patch("resource_management.libraries.script.Script.put_structured_out")
  157. def testHostResolution(self, structured_out_mock, get_tmp_dir_mock, mock_config, mock_socket):
  158. mock_socket.return_value = "192.168.1.1"
  159. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "check_host_ip_addresses.json")
  160. with open(jsonFilePath, "r") as jsonFile:
  161. jsonPayload = json.load(jsonFile)
  162. mock_config.return_value = ConfigDictionary(jsonPayload)
  163. get_tmp_dir_mock.return_value = "/tmp"
  164. checkHost = CheckHost()
  165. checkHost.actionexecute(None)
  166. # ensure the correct function was called
  167. self.assertTrue(structured_out_mock.called)
  168. structured_out_mock.assert_called_with({'host_resolution_check':
  169. {'failures': [],
  170. 'message': 'All hosts resolved to an IP address.',
  171. 'failed_count': 0,
  172. 'success_count': 5,
  173. 'exit_code': 0}})
  174. # try it now with errors
  175. mock_socket.side_effect = socket.error
  176. checkHost.actionexecute(None)
  177. structured_out_mock.assert_called_with({'host_resolution_check':
  178. {'failures': [
  179. {'cause': (), 'host': u'c6401.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  180. {'cause': (), 'host': u'c6402.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  181. {'cause': (), 'host': u'c6403.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  182. {'cause': (), 'host': u'foobar', 'type': 'FORWARD_LOOKUP'},
  183. {'cause': (), 'host': u'!!!', 'type': 'FORWARD_LOOKUP'}],
  184. 'message': 'There were 5 host(s) that could not resolve to an IP address.',
  185. 'failed_count': 5, 'success_count': 0, 'exit_code': 0}})
  186. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  187. @patch.object(Script, 'get_config')
  188. @patch.object(Script, 'get_tmp_dir')
  189. @patch("resource_management.libraries.script.Script.put_structured_out")
  190. def testInvalidCheck(self, structured_out_mock, get_tmp_dir_mock, mock_config):
  191. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "invalid_check.json")
  192. with open(jsonFilePath, "r") as jsonFile:
  193. jsonPayload = json.load(jsonFile)
  194. mock_config.return_value = ConfigDictionary(jsonPayload)
  195. get_tmp_dir_mock.return_value = "tmp"
  196. checkHost = CheckHost()
  197. checkHost.actionexecute(None)
  198. # ensure the correct function was called
  199. self.assertTrue(structured_out_mock.called)
  200. structured_out_mock.assert_called_with({})
  201. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  202. @patch("platform.system")
  203. @patch.object(Script, 'get_config')
  204. @patch.object(Script, 'get_tmp_dir')
  205. @patch('resource_management.libraries.script.Script.put_structured_out')
  206. @patch('ambari_agent.HostInfo.HostInfoLinux.javaProcs')
  207. @patch('ambari_agent.HostInfo.HostInfoLinux.checkLiveServices')
  208. @patch('ambari_agent.HostInfo.HostInfoLinux.getUMask')
  209. @patch('ambari_agent.HostInfo.HostInfoLinux.getTransparentHugePage')
  210. @patch('ambari_agent.HostInfo.HostInfoLinux.checkFirewall')
  211. @patch('ambari_agent.HostInfo.HostInfoLinux.checkReverseLookup')
  212. @patch('time.time')
  213. def testLastAgentEnv(self, time_mock, checkReverseLookup_mock, checkFirewall_mock, getTransparentHugePage_mock,
  214. getUMask_mock, checkLiveServices_mock, javaProcs_mock, put_structured_out_mock,
  215. get_tmp_dir_mock, get_config_mock, systemmock):
  216. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "check_last_agent_env.json")
  217. with open(jsonFilePath, "r") as jsonFile:
  218. jsonPayload = json.load(jsonFile)
  219. get_config_mock.return_value = ConfigDictionary(jsonPayload)
  220. get_tmp_dir_mock.return_value = "/tmp"
  221. checkHost = CheckHost()
  222. checkHost.actionexecute(None)
  223. # ensure the correct function was called
  224. self.assertTrue(time_mock.called)
  225. self.assertTrue(checkReverseLookup_mock.called)
  226. self.assertTrue(checkFirewall_mock.called)
  227. self.assertTrue(getTransparentHugePage_mock.called)
  228. self.assertTrue(getUMask_mock.called)
  229. self.assertTrue(checkLiveServices_mock.called)
  230. self.assertTrue(javaProcs_mock.called)
  231. self.assertTrue(put_structured_out_mock.called)
  232. # ensure the correct keys are in the result map
  233. last_agent_env_check_result = put_structured_out_mock.call_args[0][0]
  234. self.assertTrue('last_agent_env_check' in last_agent_env_check_result)
  235. self.assertTrue('hostHealth' in last_agent_env_check_result['last_agent_env_check'])
  236. self.assertTrue('firewallRunning' in last_agent_env_check_result['last_agent_env_check'])
  237. self.assertTrue('firewallName' in last_agent_env_check_result['last_agent_env_check'])
  238. self.assertTrue('reverseLookup' in last_agent_env_check_result['last_agent_env_check'])
  239. self.assertTrue('alternatives' in last_agent_env_check_result['last_agent_env_check'])
  240. self.assertTrue('umask' in last_agent_env_check_result['last_agent_env_check'])
  241. self.assertTrue('stackFoldersAndFiles' in last_agent_env_check_result['last_agent_env_check'])
  242. self.assertTrue('existingUsers' in last_agent_env_check_result['last_agent_env_check'])
  243. # try it now with errors
  244. javaProcs_mock.side_effect = Exception("test exception")
  245. checkHost.actionexecute(None)
  246. #ensure the correct response is returned
  247. put_structured_out_mock.assert_called_with({'last_agent_env_check': {'message': 'test exception', 'exit_code': 1}})