TestCheckHost.py 14 KB

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