TestCheckHost.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294
  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. if get_platform() != PLATFORM_WINDOWS:
  30. os_distro_value = ('Suse','11','Final')
  31. else:
  32. os_distro_value = ('win2012serverr2','6.3','WindowsServer')
  33. class TestCheckHost(TestCase):
  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(os_isfile_mock.call_args[0][0], 'test_java_home/bin/java')
  47. self.assertEquals(structured_out_mock.call_args[0][0], {'java_home_check': {'message': 'Java home exists!',
  48. 'exit_code': 0}})
  49. # test, java home doesn't exist
  50. os_isfile_mock.reset_mock()
  51. os_isfile_mock.return_value = False
  52. checkHost.actionexecute(None)
  53. self.assertEquals(os_isfile_mock.call_args[0][0], 'test_java_home/bin/java')
  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(Script, 'get_config')
  57. @patch.object(Script, 'get_tmp_dir')
  58. @patch("check_host.download_file")
  59. @patch("resource_management.libraries.script.Script.put_structured_out")
  60. @patch("subprocess.Popen")
  61. @patch("check_host.format")
  62. @patch("os.path.isfile")
  63. def testDBConnectionCheck(self, isfile_mock, format_mock, popenMock, structured_out_mock, download_file_mock, get_tmp_dir_mock, mock_config):
  64. # test, download DBConnectionVerification.jar failed
  65. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  66. "java_home" : "test_java_home",
  67. "ambari_server_host" : "test_host",
  68. "jdk_location" : "test_jdk_location",
  69. "db_name" : "mysql",
  70. "db_connection_url" : "test_db_connection_url",
  71. "user_name" : "test_user_name",
  72. "user_passwd" : "test_user_passwd",
  73. "jdk_name" : "test_jdk_name"},
  74. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  75. get_tmp_dir_mock.return_value = "/tmp"
  76. download_file_mock.side_effect = Exception("test exception")
  77. isfile_mock.return_value = True
  78. checkHost = CheckHost()
  79. checkHost.actionexecute(None)
  80. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Error downloading ' \
  81. 'DBConnectionVerification.jar from Ambari Server resources. Check network access to Ambari ' \
  82. 'Server.\ntest exception', 'exit_code': 1}})
  83. # test, download jdbc driver failed
  84. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  85. "java_home" : "test_java_home",
  86. "ambari_server_host" : "test_host",
  87. "jdk_location" : "test_jdk_location",
  88. "db_name" : "oracle",
  89. "db_connection_url" : "test_db_connection_url",
  90. "user_name" : "test_user_name",
  91. "user_passwd" : "test_user_passwd",
  92. "jdk_name" : "test_jdk_name"},
  93. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  94. format_mock.reset_mock()
  95. download_file_mock.reset_mock()
  96. p = MagicMock()
  97. download_file_mock.side_effect = [p, Exception("test exception")]
  98. checkHost.actionexecute(None)
  99. self.assertEquals(format_mock.call_args[0][0], 'Error: Ambari Server cannot download the database JDBC driver '
  100. 'and is unable to test the database connection. You must run ambari-server setup '
  101. '--jdbc-db={db_name} --jdbc-driver=/path/to/your/{db_name}/driver.jar on the Ambari '
  102. 'Server host to make the JDBC driver available for download and to enable testing '
  103. 'the database connection.\n')
  104. self.assertEquals(structured_out_mock.call_args[0][0]['db_connection_check']['exit_code'], 1)
  105. # test, no connection to remote db
  106. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  107. "java_home" : "test_java_home",
  108. "ambari_server_host" : "test_host",
  109. "jdk_location" : "test_jdk_location",
  110. "db_name" : "postgres",
  111. "db_connection_url" : "test_db_connection_url",
  112. "user_name" : "test_user_name",
  113. "user_passwd" : "test_user_passwd",
  114. "jdk_name" : "test_jdk_name"},
  115. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  116. format_mock.reset_mock()
  117. download_file_mock.reset_mock()
  118. download_file_mock.side_effect = [p, p]
  119. s = MagicMock()
  120. s.communicate.return_value = ("test message", "")
  121. s.returncode = 1
  122. popenMock.return_value = s
  123. checkHost.actionexecute(None)
  124. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'test message',
  125. 'exit_code': 1}})
  126. self.assertEquals(format_mock.call_args[0][0],'{java_exec} -cp '\
  127. '{check_db_connection_path}{class_path_delimiter}{jdbc_path} -Djava.library.path={agent_cache_dir} '\
  128. 'org.apache.ambari.server.DBConnectionVerification \"{db_connection_url}\" '\
  129. '{user_name} {user_passwd!p} {jdbc_driver}')
  130. # test, db connection success
  131. download_file_mock.reset_mock()
  132. download_file_mock.side_effect = [p, p]
  133. s.returncode = 0
  134. checkHost.actionexecute(None)
  135. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check':
  136. {'message': 'DB connection check completed successfully!', 'exit_code': 0}})
  137. #test jdk_name and java home are not available
  138. mock_config.return_value = {"commandParams" : {"check_execute_list" : "db_connection_check",
  139. "java_home" : "test_java_home",
  140. "ambari_server_host" : "test_host",
  141. "jdk_location" : "test_jdk_location",
  142. "db_connection_url" : "test_db_connection_url",
  143. "user_name" : "test_user_name",
  144. "user_passwd" : "test_user_passwd",
  145. "db_name" : "postgres"},
  146. "hostLevelParams": { "agentCacheDir": "/nonexistent_tmp" }}
  147. isfile_mock.return_value = False
  148. checkHost.actionexecute(None)
  149. self.assertEquals(structured_out_mock.call_args[0][0], {'db_connection_check': {'message': 'Custom java is not ' \
  150. 'available on host. Please install it. Java home should be the same as on server. \n', 'exit_code': 1}})
  151. @patch("socket.gethostbyname")
  152. @patch.object(Script, 'get_config')
  153. @patch.object(Script, 'get_tmp_dir')
  154. @patch("resource_management.libraries.script.Script.put_structured_out")
  155. def testHostResolution(self, structured_out_mock, get_tmp_dir_mock, mock_config, mock_socket):
  156. mock_socket.return_value = "192.168.1.1"
  157. jsonFilePath = os.path.join("../resources/custom_actions", "check_host_ip_addresses.json")
  158. with open(jsonFilePath, "r") as jsonFile:
  159. jsonPayload = json.load(jsonFile)
  160. mock_config.return_value = ConfigDictionary(jsonPayload)
  161. get_tmp_dir_mock.return_value = "/tmp"
  162. checkHost = CheckHost()
  163. checkHost.actionexecute(None)
  164. # ensure the correct function was called
  165. self.assertTrue(structured_out_mock.called)
  166. structured_out_mock.assert_called_with({'host_resolution_check':
  167. {'failures': [],
  168. 'message': 'All hosts resolved to an IP address.',
  169. 'failed_count': 0,
  170. 'success_count': 5,
  171. 'exit_code': 0}})
  172. # try it now with errors
  173. mock_socket.side_effect = socket.error
  174. checkHost.actionexecute(None)
  175. structured_out_mock.assert_called_with({'host_resolution_check':
  176. {'failures': [
  177. {'cause': (), 'host': u'c6401.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  178. {'cause': (), 'host': u'c6402.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  179. {'cause': (), 'host': u'c6403.ambari.apache.org', 'type': 'FORWARD_LOOKUP'},
  180. {'cause': (), 'host': u'foobar', 'type': 'FORWARD_LOOKUP'},
  181. {'cause': (), 'host': u'!!!', 'type': 'FORWARD_LOOKUP'}],
  182. 'message': 'There were 5 host(s) that could not resolve to an IP address.',
  183. 'failed_count': 5, 'success_count': 0, 'exit_code': 0}})
  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("../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.checkIptables')
  208. @patch('ambari_agent.HostInfo.HostInfoLinux.checkReverseLookup')
  209. @patch('time.time')
  210. def testLastAgentEnv(self, time_mock, checkReverseLookup_mock, checkIptables_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("../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(checkIptables_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('iptablesIsRunning' in last_agent_env_check_result['last_agent_env_check'])
  234. self.assertTrue('reverseLookup' in last_agent_env_check_result['last_agent_env_check'])
  235. self.assertTrue('alternatives' in last_agent_env_check_result['last_agent_env_check'])
  236. self.assertTrue('umask' in last_agent_env_check_result['last_agent_env_check'])
  237. self.assertTrue('stackFoldersAndFiles' in last_agent_env_check_result['last_agent_env_check'])
  238. self.assertTrue('existingRepos' in last_agent_env_check_result['last_agent_env_check'])
  239. self.assertTrue('installedPackages' in last_agent_env_check_result['last_agent_env_check'])
  240. self.assertTrue('existingUsers' in last_agent_env_check_result['last_agent_env_check'])
  241. # try it now with errors
  242. javaProcs_mock.side_effect = Exception("test exception")
  243. checkHost.actionexecute(None)
  244. #ensure the correct response is returned
  245. put_structured_out_mock.assert_called_with({'last_agent_env_check': {'message': 'test exception', 'exit_code': 1}})