TestCheckHost.py 19 KB

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