TestPuppetExecutor.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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 unittest import TestCase
  18. from PuppetExecutor import PuppetExecutor
  19. from RepoInstaller import RepoInstaller
  20. from Grep import Grep
  21. from pprint import pformat
  22. import socket, threading, tempfile
  23. import os, time
  24. import sys
  25. import json
  26. from AmbariConfig import AmbariConfig
  27. from mock.mock import patch, MagicMock, call
  28. from threading import Thread
  29. from shell import shellRunner
  30. import manifestGenerator
  31. class TestPuppetExecutor(TestCase):
  32. def test_build(self):
  33. puppetexecutor = PuppetExecutor("/tmp", "/x", "/y", "/z", AmbariConfig().getConfig())
  34. command = puppetexecutor.puppetCommand("site.pp")
  35. self.assertEquals("puppet", command[0], "puppet binary wrong")
  36. self.assertEquals("apply", command[1], "local apply called")
  37. self.assertEquals("--confdir=/tmp", command[2],"conf dir tmp")
  38. self.assertEquals("--detailed-exitcodes", command[3], "make sure output \
  39. correct")
  40. @patch.object(shellRunner,'run')
  41. def test_isJavaAvailable(self, cmdrun_mock):
  42. puppetInstance = PuppetExecutor("/tmp", "/x", "/y", '/tmpdir',
  43. AmbariConfig().getConfig())
  44. command = {'configurations':{'global':{'java64_home':'/usr/jdk/jdk123'}}}
  45. cmdrun_mock.return_value = {'exitCode': 1, 'output': 'Command not found', 'error': ''}
  46. self.assertEquals(puppetInstance.isJavaAvailable(command), False)
  47. cmdrun_mock.return_value = {'exitCode': 0, 'output': 'OK', 'error': ''}
  48. self.assertEquals(puppetInstance.isJavaAvailable(command), True)
  49. @patch.object(manifestGenerator, 'generateManifest')
  50. @patch.object(PuppetExecutor, 'isJavaAvailable')
  51. @patch.object(PuppetExecutor, 'runPuppetFile')
  52. def test_run_command(self, runPuppetFileMock, isJavaAvailableMock, generateManifestMock):
  53. tmpdir = tempfile.gettempdir()
  54. puppetInstance = PuppetExecutor("/tmp", "/x", "/y", tmpdir, AmbariConfig().getConfig())
  55. jsonFile = open('../../main/python/ambari_agent/test.json', 'r')
  56. jsonStr = jsonFile.read()
  57. parsedJson = json.loads(jsonStr)
  58. parsedJson["taskId"] = 1
  59. def side_effect1(puppetFile, result, puppetEnv, tmpoutfile, tmperrfile):
  60. result["exitcode"] = 0
  61. runPuppetFileMock.side_effect = side_effect1
  62. generateManifestMock.return_value = ''
  63. puppetInstance.reposInstalled = False
  64. isJavaAvailableMock.return_value = True
  65. res = puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  66. self.assertEquals(res["exitcode"], 0)
  67. self.assertTrue(puppetInstance.reposInstalled)
  68. def side_effect2(puppetFile, result, puppetEnv, tmpoutfile, tmperrfile):
  69. result["exitcode"] = 999
  70. runPuppetFileMock.side_effect = side_effect2
  71. puppetInstance.reposInstalled = False
  72. isJavaAvailableMock.return_value = True
  73. res = puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  74. self.assertEquals(res["exitcode"], 999)
  75. self.assertFalse(puppetInstance.reposInstalled)
  76. generateManifestMock.return_value = 'error during manifest generation'
  77. res = puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  78. self.assertTrue(generateManifestMock.called)
  79. self.assertEquals(res["exitcode"], 1)
  80. generateManifestMock.return_value = ''
  81. def side_effect2(puppetFile, result, puppetEnv, tmpoutfile, tmperrfile):
  82. result["exitcode"] = 0
  83. runPuppetFileMock.side_effect = side_effect2
  84. puppetInstance.reposInstalled = False
  85. isJavaAvailableMock.return_value = False
  86. parsedJson['roleCommand'] = "START"
  87. parsedJson['hostLevelParams'] = {'java_home':'/usr/jdk/jdk123'}
  88. res = puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  89. JAVANOTVALID_MSG = "Cannot access JDK! Make sure you have permission to execute {0}/bin/java"
  90. errMsg = JAVANOTVALID_MSG.format('/usr/jdk/jdk123')
  91. self.assertEquals(res["exitcode"], 1)
  92. self.assertEquals(res["stderr"], errMsg)
  93. self.assertFalse(puppetInstance.reposInstalled)
  94. parsedJson['hostLevelParams'] = {'random':{'name1':'value2'}}
  95. res = puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  96. self.assertEquals(res["exitcode"], 1)
  97. self.assertEquals(res["stderr"], "Cannot access JDK! Make sure java_home is specified in hostLevelParams")
  98. @patch.object(PuppetExecutor, 'isJavaAvailable')
  99. @patch.object(RepoInstaller, 'generate_repo_manifests')
  100. @patch.object(PuppetExecutor, 'runPuppetFile')
  101. def test_overwrite_repos(self, runPuppetFileMock, generateRepoManifestMock, isJavaAvailableMock):
  102. tmpdir = tempfile.gettempdir()
  103. puppetInstance = PuppetExecutor("/tmp", "/x", "/y", tmpdir, AmbariConfig().getConfig())
  104. jsonFile = open('../../main/python/ambari_agent/test.json', 'r')
  105. jsonStr = jsonFile.read()
  106. parsedJson = json.loads(jsonStr)
  107. parsedJson["taskId"] = 77
  108. parsedJson['roleCommand'] = "START"
  109. def side_effect(puppetFile, result, puppetEnv, tmpoutfile, tmperrfile):
  110. result["exitcode"] = 0
  111. runPuppetFileMock.side_effect = side_effect
  112. isJavaAvailableMock.return_value = True
  113. #If ambari-agent has been just started and no any commands were executed by
  114. # PuppetExecutor.runCommand, then no repo files were updated by
  115. # RepoInstaller.generate_repo_manifests
  116. self.assertEquals(0, generateRepoManifestMock.call_count)
  117. self.assertFalse(puppetInstance.reposInstalled)
  118. # After executing of the first command, RepoInstaller.generate_repo_manifests
  119. # generates a .pp file for updating repo files
  120. puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  121. self.assertTrue(puppetInstance.reposInstalled)
  122. self.assertEquals(1, generateRepoManifestMock.call_count)
  123. isJavaAvailableMock.assert_called_with("java64_home")
  124. # After executing of the next commands, repo manifest aren't generated again
  125. puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  126. self.assertTrue(puppetInstance.reposInstalled)
  127. self.assertEquals(1, generateRepoManifestMock.call_count)
  128. puppetInstance.runCommand(parsedJson, tmpdir + '/out.txt', tmpdir + '/err.txt')
  129. self.assertTrue(puppetInstance.reposInstalled)
  130. self.assertEquals(1, generateRepoManifestMock.call_count)
  131. @patch("os.path.exists")
  132. def test_configure_environ(self, osPathExistsMock):
  133. config = AmbariConfig().getConfig()
  134. tmpdir = tempfile.gettempdir()
  135. puppetInstance = PuppetExecutor("/tmp", "/x", "/y", tmpdir, config)
  136. environ = puppetInstance.configureEnviron({})
  137. self.assertEquals(environ, {})
  138. config.set('puppet','ruby_home',"test/ruby_home")
  139. puppetInstance = PuppetExecutor("/tmp", "/x", "/y", tmpdir, config)
  140. osPathExistsMock.return_value = True
  141. environ = puppetInstance.configureEnviron({"PATH" : "test_path"})
  142. self.assertEquals(environ["PATH"], "test/ruby_home/bin:test_path")
  143. self.assertEquals(environ["MY_RUBY_HOME"], "test/ruby_home")
  144. def test_condense_bad2(self):
  145. puppetexecutor = PuppetExecutor("/tmp", "/x", "/y", "/z", AmbariConfig().getConfig())
  146. grep = Grep()
  147. puppetexecutor.grep = grep
  148. grep.ERROR_LAST_LINES_BEFORE = 2
  149. grep.ERROR_LAST_LINES_AFTER = 3
  150. string_err = open('ambari_agent' + os.sep + 'dummy_puppet_output_error2.txt', 'r').read().replace("\n", os.linesep)
  151. result = puppetexecutor.condenseOutput(string_err, '', 1)
  152. stripped_string = string_err.strip()
  153. lines = stripped_string.splitlines(True)
  154. d = lines[1:6]
  155. d = grep.cleanByTemplate("".join(d).strip(), "warning").splitlines(True)
  156. result_check = True
  157. for l in d:
  158. result_check &= grep.filterMarkup(l) in result
  159. self.assertEquals(result_check, True, "Failed to condence fail log")
  160. self.assertEquals(('warning' in result.lower()), False, "Failed to condence fail log")
  161. self.assertEquals(len(result.splitlines(True)), 5, "Failed to condence fail log")
  162. def test_condense_bad3(self):
  163. puppetexecutor = PuppetExecutor("/tmp", "/x", "/y", "/z", AmbariConfig().getConfig())
  164. grep = Grep()
  165. puppetexecutor.grep = grep
  166. string_err = open('ambari_agent' + os.sep + 'dummy_puppet_output_error3.txt', 'r').read().replace("\n", os.linesep)
  167. result = puppetexecutor.condenseOutput(string_err, '', 1)
  168. stripped_string = string_err.strip()
  169. lines = stripped_string.splitlines(True)
  170. #sys.stderr.write(result)
  171. d = lines[0:31]
  172. d = grep.cleanByTemplate("".join(d).strip(), "warning").splitlines(True)
  173. result_check = True
  174. for l in d:
  175. result_check &= grep.filterMarkup(l) in result
  176. self.assertEquals(result_check, True, "Failed to condence fail log")
  177. self.assertEquals(('warning' in result.lower()), False, "Failed to condence fail log")
  178. self.assertEquals(len(result.splitlines(True)), 19, "Failed to condence fail log")
  179. def test_condense_good(self):
  180. puppetexecutor = PuppetExecutor("/tmp", "/x", "/y", "/z", AmbariConfig().getConfig())
  181. grep = Grep()
  182. puppetexecutor.grep = grep
  183. grep.OUTPUT_LAST_LINES = 2
  184. string_good = open('ambari_agent' + os.sep + 'dummy_puppet_output_good.txt', 'r').read().replace("\n", os.linesep)
  185. result = puppetexecutor.condenseOutput(string_good, PuppetExecutor.NO_ERROR, 0)
  186. stripped_string = string_good.strip()
  187. lines = stripped_string.splitlines(True)
  188. result_check = lines[45].strip() in result and lines[46].strip() in result
  189. self.assertEquals(result_check, True, "Failed to condence output log")
  190. self.assertEquals(len(result.splitlines(True)), 2, "Failed to condence output log")
  191. @patch("shell.kill_process_with_children")
  192. def test_watchdog_1(self, kill_process_with_children_mock):
  193. """
  194. Tests whether watchdog works
  195. """
  196. subproc_mock = self.Subprocess_mockup()
  197. config = AmbariConfig().getConfig()
  198. config.set('puppet','timeout_seconds',"0.1")
  199. executor_mock = self.PuppetExecutor_mock("/home/centos/ambari_repo_info/ambari-agent/src/main/puppet/",
  200. "/usr/",
  201. "/root/workspace/puppet-install/facter-1.6.10/",
  202. "/tmp", config, subproc_mock)
  203. _, tmpoutfile = tempfile.mkstemp()
  204. _, tmperrfile = tempfile.mkstemp()
  205. result = { }
  206. puppetEnv = { "RUBYLIB" : ""}
  207. kill_process_with_children_mock.side_effect = lambda pid : subproc_mock.terminate()
  208. subproc_mock.returncode = None
  209. thread = Thread(target = executor_mock.runPuppetFile, args = ("fake_puppetFile", result, puppetEnv, tmpoutfile, tmperrfile))
  210. thread.start()
  211. time.sleep(0.1)
  212. subproc_mock.finished_event.wait()
  213. self.assertEquals(subproc_mock.was_terminated, True, "Subprocess should be terminated due to timeout")
  214. def test_watchdog_2(self):
  215. """
  216. Tries to catch false positive watchdog invocations
  217. """
  218. subproc_mock = self.Subprocess_mockup()
  219. config = AmbariConfig().getConfig()
  220. config.set('puppet','timeout_seconds',"5")
  221. executor_mock = self.PuppetExecutor_mock("/home/centos/ambari_repo_info/ambari-agent/src/main/puppet/",
  222. "/usr/",
  223. "/root/workspace/puppet-install/facter-1.6.10/",
  224. "/tmp", config, subproc_mock)
  225. _, tmpoutfile = tempfile.mkstemp()
  226. _, tmperrfile = tempfile.mkstemp()
  227. result = { }
  228. puppetEnv = { "RUBYLIB" : ""}
  229. subproc_mock.returncode = 0
  230. thread = Thread(target = executor_mock.runPuppetFile, args = ("fake_puppetFile",
  231. result, puppetEnv, tmpoutfile, tmperrfile))
  232. thread.start()
  233. time.sleep(0.1)
  234. subproc_mock.should_finish_event.set()
  235. subproc_mock.finished_event.wait()
  236. self.assertEquals(subproc_mock.was_terminated, False, "Subprocess should not be terminated before timeout")
  237. self.assertEquals(subproc_mock.returncode, 0, "Subprocess should not be terminated before timeout")
  238. class PuppetExecutor_mock(PuppetExecutor):
  239. def __init__(self, puppetModule, puppetInstall, facterInstall, tmpDir, config, subprocess_mockup):
  240. self.subprocess_mockup = subprocess_mockup
  241. PuppetExecutor.__init__(self, puppetModule, puppetInstall, facterInstall, tmpDir, config)
  242. pass
  243. def lauch_puppet_subprocess(self, puppetcommand, tmpout, tmperr, puppetEnv):
  244. self.subprocess_mockup.tmpout = tmpout
  245. self.subprocess_mockup.tmperr = tmperr
  246. return self.subprocess_mockup
  247. def runShellKillPgrp(self, puppet):
  248. puppet.terminate() # note: In real code, subprocess.terminate() is not called
  249. pass
  250. class Subprocess_mockup():
  251. returncode = 0
  252. started_event = threading.Event()
  253. should_finish_event = threading.Event()
  254. finished_event = threading.Event()
  255. was_terminated = False
  256. tmpout = None
  257. tmperr = None
  258. pid=-1
  259. def communicate(self):
  260. self.started_event.set()
  261. self.tmpout.write("Dummy output")
  262. self.tmpout.flush()
  263. self.tmperr.write("Dummy err")
  264. self.tmperr.flush()
  265. self.should_finish_event.wait()
  266. self.finished_event.set()
  267. pass
  268. def terminate(self):
  269. self.was_terminated = True
  270. self.returncode = 17
  271. self.should_finish_event.set()