TestPuppetExecutor.py 13 KB

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