TestCheckHost.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. from only_for_platform import get_platform, not_for_platform, only_for_platform, os_distro_value, PLATFORM_LINUX, PLATFORM_WINDOWS
  31. @patch.object(HostCheckReportFileHandler, "writeHostChecksCustomActionsFile", new=MagicMock())
  32. @patch.object(HostCheckReportFileHandler, "resolve_ambari_config", new=MagicMock())
  33. class TestCheckHost(TestCase):
  34. current_dir = os.path.dirname(os.path.realpath(__file__))
  35. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  36. @patch("os.path.isfile")
  37. @patch.object(Script, 'get_config')
  38. @patch.object(Script, 'get_tmp_dir')
  39. @patch("resource_management.libraries.script.Script.put_structured_out")
  40. def testJavaHomeAvailableCheck(self, structured_out_mock, get_tmp_dir_mock, mock_config, os_isfile_mock):
  41. # test, java home exists
  42. os_isfile_mock.return_value = True
  43. get_tmp_dir_mock.return_value = "/tmp"
  44. mock_config.return_value = {"commandParams" : {"check_execute_list" : "java_home_check",
  45. "java_home" : "test_java_home"}}
  46. checkHost = CheckHost()
  47. checkHost.actionexecute(None)
  48. self.assertEquals(structured_out_mock.call_args[0][0], {'java_home_check': {'message': 'Java home exists!',
  49. 'exit_code': 0}})
  50. # test, java home doesn't exist
  51. os_isfile_mock.reset_mock()
  52. os_isfile_mock.return_value = False
  53. checkHost.actionexecute(None)
  54. self.assertEquals(structured_out_mock.call_args[0][0], {'java_home_check': {"message": "Java home doesn't exist!",
  55. "exit_code" : 1}})
  56. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  57. @patch.object(Script, 'get_config')
  58. @patch.object(Script, 'get_tmp_dir')
  59. @patch("check_host.download_file")
  60. @patch("resource_management.libraries.script.Script.put_structured_out")
  61. @patch("check_host.format")
  62. @patch("os.path.isfile")
  63. @patch("resource_management.core.shell.call")
  64. def testDBConnectionCheck(self, shell_call_mock, isfile_mock, format_mock, structured_out_mock, download_file_mock, get_tmp_dir_mock, mock_config):
  65. # test, download DBConnectionVerification.jar failed
  66. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  67. "java_home" : "test_java_home",
  68. "ambari_server_host" : "test_host",
  69. "jdk_location" : "test_jdk_location",
  70. "db_name" : "mysql",
  71. "db_connection_url" : "test_db_connection_url",
  72. "user_name" : "test_user_name",
  73. "user_passwd" : "test_user_passwd",
  74. "jdk_name" : "test_jdk_name"},
  75. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  76. get_tmp_dir_mock.return_value = "/tmp"
  77. download_file_mock.side_effect = Exception("test exception")
  78. isfile_mock.return_value = True
  79. checkHost = CheckHost()
  80. checkHost.actionexecute(None)
  81. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Error downloading ' \
  82. 'DBConnectionVerification.jar from Ambari Server resources. Check network access to Ambari ' \
  83. 'Server.\ntest exception', 'exit_code': 1}})
  84. # test, download jdbc driver failed
  85. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  86. "java_home" : "test_java_home",
  87. "ambari_server_host" : "test_host",
  88. "jdk_location" : "test_jdk_location",
  89. "db_name" : "oracle",
  90. "db_connection_url" : "test_db_connection_url",
  91. "user_name" : "test_user_name",
  92. "user_passwd" : "test_user_passwd",
  93. "jdk_name" : "test_jdk_name"},
  94. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  95. format_mock.reset_mock()
  96. download_file_mock.reset_mock()
  97. p = MagicMock()
  98. download_file_mock.side_effect = [p, Exception("test exception")]
  99. checkHost.actionexecute(None)
  100. self.assertEquals(format_mock.call_args[0][0], 'Error: Ambari Server cannot download the database JDBC driver '
  101. 'and is unable to test the database connection. You must run ambari-server setup '
  102. '--jdbc-db={db_name} --jdbc-driver=/path/to/your/{db_name}/driver.jar on the Ambari '
  103. 'Server host to make the JDBC driver available for download and to enable testing '
  104. 'the database connection.\n')
  105. self.assertEquals(structured_out_mock.call_args[0][0]['db_connection_check']['exit_code'], 1)
  106. # test, no connection to remote db
  107. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  108. "java_home" : "test_java_home",
  109. "ambari_server_host" : "test_host",
  110. "jdk_location" : "test_jdk_location",
  111. "db_name" : "postgres",
  112. "db_connection_url" : "test_db_connection_url",
  113. "user_name" : "test_user_name",
  114. "user_passwd" : "test_user_passwd",
  115. "jdk_name" : "test_jdk_name"},
  116. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  117. format_mock.reset_mock()
  118. download_file_mock.reset_mock()
  119. download_file_mock.side_effect = [p, p]
  120. shell_call_mock.return_value = (1, "test message")
  121. checkHost.actionexecute(None)
  122. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'test message',
  123. 'exit_code': 1}})
  124. self.assertEquals(format_mock.call_args[0][0],'{java_exec} -cp '\
  125. '{check_db_connection_path}{class_path_delimiter}{jdbc_path} -Djava.library.path={agent_cache_dir} '\
  126. 'org.apache.ambari.server.DBConnectionVerification \"{db_connection_url}\" '\
  127. '{user_name} {user_passwd!p} {jdbc_driver}')
  128. # test, db connection success
  129. download_file_mock.reset_mock()
  130. download_file_mock.side_effect = [p, p]
  131. shell_call_mock.return_value = (0, "test message")
  132. checkHost.actionexecute(None)
  133. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check':
  134. {'message': 'DB connection check completed successfully!', 'exit_code': 0}})
  135. #test jdk_name and java home are not available
  136. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  137. "java_home" : "test_java_home",
  138. "ambari_server_host" : "test_host",
  139. "jdk_location" : "test_jdk_location",
  140. "db_connection_url" : "test_db_connection_url",
  141. "user_name" : "test_user_name",
  142. "user_passwd" : "test_user_passwd",
  143. "db_name" : "postgres"},
  144. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  145. isfile_mock.return_value = False
  146. checkHost.actionexecute(None)
  147. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Custom java is not ' \
  148. 'available on host. Please install it. Java home should be the same as on server. \n', 'exit_code': 1}})
  149. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  150. @patch("socket.gethostbyname")
  151. @patch.object(Script, 'get_config')
  152. @patch.object(Script, 'get_tmp_dir')
  153. @patch("resource_management.libraries.script.Script.put_structured_out")
  154. def testHostResolution(self, structured_out_mock, get_tmp_dir_mock, mock_config, mock_socket):
  155. mock_socket.return_value = "192.168.1.1"
  156. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "check_host_ip_addresses.json")
  157. with open(jsonFilePath, "r") as jsonFile:
  158. jsonPayload = json.load(jsonFile)
  159. mock_config.return_value = ConfigDictionary(jsonPayload)
  160. get_tmp_dir_mock.return_value = "/tmp"
  161. checkHost = CheckHost()
  162. checkHost.actionexecute(None)
  163. # ensure the correct function was called
  164. self.assertTrue(structured_out_mock.called)
  165. structured_out_mock.assert_called_with({'host_resolution_check':
  166. {'failures': [],
  167. 'message': 'All hosts resolved to an IP address.',
  168. 'failed_count': 0,
  169. 'success_count': 5,
  170. 'exit_code': 0}})
  171. # try it now with errors
  172. mock_socket.side_effect = socket.error
  173. checkHost.actionexecute(None)
  174. structured_out_mock.assert_called_with({'host_resolution_check':
  175. {'failures': [
  176. {'cause': (), 'host': u'c6401.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  177. {'cause': (), 'host': u'c6402.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  178. {'cause': (), 'host': u'c6403.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  179. {'cause': (), 'host': u'foobar', 'type': 'FORWARD_LOOKUP'},
  180. {'cause': (), 'host': u'!!!', 'type': 'FORWARD_LOOKUP'}],
  181. 'message': 'There were 5 host(s) that could not resolve to an IP address.',
  182. 'failed_count': 5, 'success_count': 0, 'exit_code': 0}})
  183. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  184. @patch.object(Script, 'get_config')
  185. @patch.object(Script, 'get_tmp_dir')
  186. @patch("resource_management.libraries.script.Script.put_structured_out")
  187. def testInvalidCheck(self, structured_out_mock, get_tmp_dir_mock, mock_config):
  188. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "invalid_check.json")
  189. with open(jsonFilePath, "r") as jsonFile:
  190. jsonPayload = json.load(jsonFile)
  191. mock_config.return_value = ConfigDictionary(jsonPayload)
  192. get_tmp_dir_mock.return_value = "tmp"
  193. checkHost = CheckHost()
  194. checkHost.actionexecute(None)
  195. # ensure the correct function was called
  196. self.assertTrue(structured_out_mock.called)
  197. structured_out_mock.assert_called_with({})
  198. @patch.object(OSCheck, "os_distribution", new = MagicMock(return_value = os_distro_value))
  199. @patch("platform.system")
  200. @patch.object(Script, 'get_config')
  201. @patch.object(Script, 'get_tmp_dir')
  202. @patch('resource_management.libraries.script.Script.put_structured_out')
  203. @patch('ambari_agent.HostInfo.HostInfoLinux.javaProcs')
  204. @patch('ambari_agent.HostInfo.HostInfoLinux.checkLiveServices')
  205. @patch('ambari_agent.HostInfo.HostInfoLinux.getUMask')
  206. @patch('ambari_agent.HostInfo.HostInfoLinux.getTransparentHugePage')
  207. @patch('ambari_agent.HostInfo.HostInfoLinux.checkFirewall')
  208. @patch('ambari_agent.HostInfo.HostInfoLinux.checkReverseLookup')
  209. @patch('time.time')
  210. def testLastAgentEnv(self, time_mock, checkReverseLookup_mock, checkFirewall_mock, getTransparentHugePage_mock,
  211. getUMask_mock, checkLiveServices_mock, javaProcs_mock, put_structured_out_mock,
  212. get_tmp_dir_mock, get_config_mock, systemmock):
  213. jsonFilePath = os.path.join(TestCheckHost.current_dir+"/../../resources/custom_actions", "check_last_agent_env.json")
  214. with open(jsonFilePath, "r") as jsonFile:
  215. jsonPayload = json.load(jsonFile)
  216. get_config_mock.return_value = ConfigDictionary(jsonPayload)
  217. get_tmp_dir_mock.return_value = "/tmp"
  218. checkHost = CheckHost()
  219. checkHost.actionexecute(None)
  220. # ensure the correct function was called
  221. self.assertTrue(time_mock.called)
  222. self.assertTrue(checkReverseLookup_mock.called)
  223. self.assertTrue(checkFirewall_mock.called)
  224. self.assertTrue(getTransparentHugePage_mock.called)
  225. self.assertTrue(getUMask_mock.called)
  226. self.assertTrue(checkLiveServices_mock.called)
  227. self.assertTrue(javaProcs_mock.called)
  228. self.assertTrue(put_structured_out_mock.called)
  229. # ensure the correct keys are in the result map
  230. last_agent_env_check_result = put_structured_out_mock.call_args[0][0]
  231. self.assertTrue('last_agent_env_check' in last_agent_env_check_result)
  232. self.assertTrue('hostHealth' in last_agent_env_check_result['last_agent_env_check'])
  233. self.assertTrue('firewallRunning' in last_agent_env_check_result['last_agent_env_check'])
  234. self.assertTrue('firewallName' in last_agent_env_check_result['last_agent_env_check'])
  235. self.assertTrue('reverseLookup' in last_agent_env_check_result['last_agent_env_check'])
  236. self.assertTrue('alternatives' in last_agent_env_check_result['last_agent_env_check'])
  237. self.assertTrue('umask' in last_agent_env_check_result['last_agent_env_check'])
  238. self.assertTrue('stackFoldersAndFiles' in last_agent_env_check_result['last_agent_env_check'])
  239. self.assertTrue('existingUsers' in last_agent_env_check_result['last_agent_env_check'])
  240. # try it now with errors
  241. javaProcs_mock.side_effect = Exception("test exception")
  242. checkHost.actionexecute(None)
  243. #ensure the correct response is returned
  244. put_structured_out_mock.assert_called_with({'last_agent_env_check': {'message': 'test exception', 'exit_code': 1}})
  245. @patch("resource_management.libraries.script.Script.put_structured_out")
  246. @patch.object(Script, 'get_tmp_dir')
  247. @patch.object(Script, 'get_config')
  248. @patch("os.path.isfile")
  249. @patch('__builtin__.open')
  250. def testTransparentHugePage(self, open_mock, os_path_isfile_mock, mock_config, get_tmp_dir_mock, structured_out_mock):
  251. context_manager_mock = MagicMock()
  252. open_mock.return_value = context_manager_mock
  253. file_mock = MagicMock()
  254. file_mock.read.return_value = "[never] always"
  255. enter_mock = MagicMock()
  256. enter_mock.return_value = file_mock
  257. enter_mock = MagicMock()
  258. enter_mock.return_value = file_mock
  259. exit_mock = MagicMock()
  260. setattr( context_manager_mock, '__enter__', enter_mock )
  261. setattr( context_manager_mock, '__exit__', exit_mock )
  262. os_path_isfile_mock.return_value = True
  263. get_tmp_dir_mock.return_value = "/tmp"
  264. mock_config.return_value = {"commandParams" : {"check_execute_list" : "transparentHugePage"}}
  265. checkHost = CheckHost()
  266. checkHost.actionexecute(None)
  267. self.assertEquals(structured_out_mock.call_args[0][0], {'transparentHugePage' : {'message': 'never', 'exit_code': 0}})
  268. # case 2, file not exists
  269. os_path_isfile_mock.return_value = False
  270. checkHost.actionexecute(None)
  271. self.assertEquals(structured_out_mock.call_args[0][0], {'transparentHugePage' : {'message': '', 'exit_code': 0}})