cmCTestScriptHandler.cxx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmCTestScriptHandler.h"
  4. #include <chrono>
  5. #include <cstdlib>
  6. #include <functional>
  7. #include <map>
  8. #include <sstream>
  9. #include <utility>
  10. #include <cm/memory>
  11. #include <cm3p/uv.h>
  12. #include "cmCTest.h"
  13. #include "cmCTestBuildCommand.h"
  14. #include "cmCTestConfigureCommand.h"
  15. #include "cmCTestCoverageCommand.h"
  16. #include "cmCTestEmptyBinaryDirectoryCommand.h"
  17. #include "cmCTestMemCheckCommand.h"
  18. #include "cmCTestReadCustomFilesCommand.h"
  19. #include "cmCTestRunScriptCommand.h"
  20. #include "cmCTestSleepCommand.h"
  21. #include "cmCTestStartCommand.h"
  22. #include "cmCTestSubmitCommand.h"
  23. #include "cmCTestTestCommand.h"
  24. #include "cmCTestUpdateCommand.h"
  25. #include "cmCTestUploadCommand.h"
  26. #include "cmDuration.h"
  27. #include "cmGlobalGenerator.h"
  28. #include "cmMakefile.h"
  29. #include "cmState.h"
  30. #include "cmStateDirectory.h"
  31. #include "cmStateSnapshot.h"
  32. #include "cmSystemTools.h"
  33. #include "cmUVHandlePtr.h"
  34. #include "cmUVProcessChain.h"
  35. #include "cmake.h"
  36. cmCTestScriptHandler::cmCTestScriptHandler(cmCTest* ctest)
  37. : CTest(ctest)
  38. {
  39. }
  40. cmCTestScriptHandler::~cmCTestScriptHandler() = default;
  41. // just adds an argument to the vector
  42. void cmCTestScriptHandler::AddConfigurationScript(std::string const& script,
  43. bool pscope)
  44. {
  45. this->ConfigurationScripts.emplace_back(script);
  46. this->ScriptProcessScope.push_back(pscope);
  47. }
  48. // the generic entry point for handling scripts, this routine will run all
  49. // the scripts provides a -S arguments
  50. int cmCTestScriptHandler::ProcessHandler()
  51. {
  52. int res = 0;
  53. for (size_t i = 0; i < this->ConfigurationScripts.size(); ++i) {
  54. // for each script run it
  55. res |= this->RunConfigurationScript(this->ConfigurationScripts[i],
  56. this->ScriptProcessScope[i]);
  57. }
  58. return res;
  59. }
  60. void cmCTestScriptHandler::UpdateElapsedTime()
  61. {
  62. if (this->Makefile) {
  63. // set the current elapsed time
  64. auto itime = cmDurationTo<unsigned int>(this->CTest->GetElapsedTime());
  65. auto timeString = std::to_string(itime);
  66. this->Makefile->AddDefinition("CTEST_ELAPSED_TIME", timeString);
  67. }
  68. }
  69. int cmCTestScriptHandler::ExecuteScript(std::string const& total_script_arg)
  70. {
  71. // execute the script passing in the arguments to the script as well as the
  72. // arguments from this invocation of cmake
  73. std::vector<std::string> argv;
  74. argv.push_back(cmSystemTools::GetCTestCommand());
  75. argv.push_back("-SR");
  76. argv.push_back(total_script_arg);
  77. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  78. "Executable for CTest is: " << cmSystemTools::GetCTestCommand()
  79. << "\n");
  80. // now pass through all the other arguments
  81. std::vector<std::string>& initArgs =
  82. this->CTest->GetInitialCommandLineArguments();
  83. //*** need to make sure this does not have the current script ***
  84. for (size_t i = 1; i < initArgs.size(); ++i) {
  85. // in a nested subprocess, skip the parent's `-SR <path>` arguments.
  86. if (initArgs[i] == "-SR") {
  87. i++; // <path>
  88. } else {
  89. argv.push_back(initArgs[i]);
  90. }
  91. }
  92. // Now create process object
  93. cmUVProcessChainBuilder builder;
  94. builder.AddCommand(argv)
  95. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  96. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  97. auto process = builder.Start();
  98. cm::uv_pipe_ptr outPipe;
  99. outPipe.init(process.GetLoop(), 0);
  100. uv_pipe_open(outPipe, process.OutputStream());
  101. cm::uv_pipe_ptr errPipe;
  102. errPipe.init(process.GetLoop(), 0);
  103. uv_pipe_open(errPipe, process.ErrorStream());
  104. std::vector<char> out;
  105. std::vector<char> err;
  106. std::string line;
  107. auto pipe =
  108. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  109. std::chrono::seconds(100), out, err);
  110. while (pipe != cmSystemTools::WaitForLineResult::None) {
  111. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  112. "Output: " << line << "\n");
  113. if (pipe == cmSystemTools::WaitForLineResult::STDERR) {
  114. cmCTestLog(this->CTest, ERROR_MESSAGE, line << "\n");
  115. } else if (pipe == cmSystemTools::WaitForLineResult::STDOUT) {
  116. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, line << "\n");
  117. }
  118. pipe =
  119. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  120. std::chrono::seconds(100), out, err);
  121. }
  122. // Properly handle output of the build command
  123. process.Wait();
  124. auto const& status = process.GetStatus(0);
  125. auto result = status.GetException();
  126. int retVal = 0;
  127. bool failed = false;
  128. switch (result.first) {
  129. case cmUVProcessChain::ExceptionCode::None:
  130. retVal = static_cast<int>(status.ExitStatus);
  131. break;
  132. case cmUVProcessChain::ExceptionCode::Spawn:
  133. cmCTestLog(this->CTest, ERROR_MESSAGE,
  134. "\tError executing ctest: " << result.second << std::endl);
  135. failed = true;
  136. break;
  137. default:
  138. retVal = status.TermSignal;
  139. cmCTestLog(this->CTest, ERROR_MESSAGE,
  140. "\tThere was an exception: " << result.second << " " << retVal
  141. << std::endl);
  142. failed = true;
  143. }
  144. if (failed) {
  145. std::ostringstream message;
  146. message << "Error running command: [";
  147. message << static_cast<int>(result.first) << "] ";
  148. for (std::string const& arg : argv) {
  149. message << arg << " ";
  150. }
  151. cmCTestLog(this->CTest, ERROR_MESSAGE, message.str() << std::endl);
  152. return -1;
  153. }
  154. return retVal;
  155. }
  156. void cmCTestScriptHandler::CreateCMake()
  157. {
  158. // create a cmake instance to read the configuration script
  159. this->CMake = cm::make_unique<cmake>(cmState::Role::CTest);
  160. this->CMake->GetCurrentSnapshot().SetDefaultDefinitions();
  161. this->CMake->AddCMakePaths();
  162. this->GlobalGenerator =
  163. cm::make_unique<cmGlobalGenerator>(this->CMake.get());
  164. cmStateSnapshot snapshot = this->CMake->GetCurrentSnapshot();
  165. std::string cwd = cmSystemTools::GetLogicalWorkingDirectory();
  166. snapshot.GetDirectory().SetCurrentSource(cwd);
  167. snapshot.GetDirectory().SetCurrentBinary(cwd);
  168. this->Makefile =
  169. cm::make_unique<cmMakefile>(this->GlobalGenerator.get(), snapshot);
  170. if (this->ParentMakefile) {
  171. this->Makefile->SetRecursionDepth(
  172. this->ParentMakefile->GetRecursionDepth());
  173. }
  174. this->CMake->SetProgressCallback(
  175. [this](std::string const& m, float /*unused*/) {
  176. if (!m.empty()) {
  177. cmCTestLog(this->CTest, HANDLER_OUTPUT, "-- " << m << std::endl);
  178. }
  179. });
  180. cmState* state = this->CMake->GetState();
  181. state->AddBuiltinCommand("ctest_build", cmCTestBuildCommand(this->CTest));
  182. state->AddBuiltinCommand("ctest_configure",
  183. cmCTestConfigureCommand(this->CTest));
  184. state->AddBuiltinCommand("ctest_coverage",
  185. cmCTestCoverageCommand(this->CTest));
  186. state->AddBuiltinCommand("ctest_empty_binary_directory",
  187. cmCTestEmptyBinaryDirectoryCommand);
  188. state->AddBuiltinCommand("ctest_memcheck",
  189. cmCTestMemCheckCommand(this->CTest));
  190. state->AddBuiltinCommand("ctest_read_custom_files",
  191. cmCTestReadCustomFilesCommand(this->CTest));
  192. state->AddBuiltinCommand("ctest_run_script",
  193. cmCTestRunScriptCommand(this->CTest));
  194. state->AddBuiltinCommand("ctest_sleep", cmCTestSleepCommand);
  195. state->AddBuiltinCommand("ctest_start", cmCTestStartCommand(this->CTest));
  196. state->AddBuiltinCommand("ctest_submit", cmCTestSubmitCommand(this->CTest));
  197. state->AddBuiltinCommand("ctest_test", cmCTestTestCommand(this->CTest));
  198. state->AddBuiltinCommand("ctest_update", cmCTestUpdateCommand(this->CTest));
  199. state->AddBuiltinCommand("ctest_upload", cmCTestUploadCommand(this->CTest));
  200. }
  201. // this sets up some variables for the script to use, creates the required
  202. // cmake instance and generators, and then reads in the script
  203. int cmCTestScriptHandler::ReadInScript(std::string const& total_script_arg)
  204. {
  205. // Reset the error flag so that the script is read in no matter what
  206. cmSystemTools::ResetErrorOccurredFlag();
  207. // if the argument has a , in it then it needs to be broken into the fist
  208. // argument (which is the script) and the second argument which will be
  209. // passed into the scripts as S_ARG
  210. std::string script;
  211. std::string script_arg;
  212. std::string::size_type const comma_pos = total_script_arg.find(',');
  213. if (comma_pos != std::string::npos) {
  214. script = total_script_arg.substr(0, comma_pos);
  215. script_arg = total_script_arg.substr(comma_pos + 1);
  216. } else {
  217. script = total_script_arg;
  218. }
  219. // make sure the file exists
  220. if (!cmSystemTools::FileExists(script)) {
  221. cmSystemTools::Error("Cannot find file: " + script);
  222. return 1;
  223. }
  224. // read in the list file to fill the cache
  225. // create a cmake instance to read the configuration script
  226. this->CreateCMake();
  227. // set a variable with the path to the current script
  228. this->Makefile->AddDefinition("CTEST_SCRIPT_DIRECTORY",
  229. cmSystemTools::GetFilenamePath(script));
  230. this->Makefile->AddDefinition("CTEST_SCRIPT_NAME",
  231. cmSystemTools::GetFilenameName(script));
  232. this->Makefile->AddDefinition("CTEST_EXECUTABLE_NAME",
  233. cmSystemTools::GetCTestCommand());
  234. this->Makefile->AddDefinition("CMAKE_EXECUTABLE_NAME",
  235. cmSystemTools::GetCMakeCommand());
  236. this->UpdateElapsedTime();
  237. // set the CTEST_CONFIGURATION_TYPE variable to the current value of the
  238. // the -C argument on the command line.
  239. if (!this->CTest->GetConfigType().empty()) {
  240. this->Makefile->AddDefinition("CTEST_CONFIGURATION_TYPE",
  241. this->CTest->GetConfigType());
  242. }
  243. // add the script arg if defined
  244. if (!script_arg.empty()) {
  245. this->Makefile->AddDefinition("CTEST_SCRIPT_ARG", script_arg);
  246. }
  247. // set a callback function to update the elapsed time
  248. this->Makefile->OnExecuteCommand([this] { this->UpdateElapsedTime(); });
  249. /* Execute CTestScriptMode.cmake, which loads CMakeDetermineSystem and
  250. CMakeSystemSpecificInformation, so
  251. that variables like CMAKE_SYSTEM and also the search paths for libraries,
  252. header and executables are set correctly and can be used. Makes new-style
  253. ctest scripting easier. */
  254. std::string systemFile =
  255. this->Makefile->GetModulesFile("CTestScriptMode.cmake");
  256. if (!this->Makefile->ReadListFile(systemFile) ||
  257. cmSystemTools::GetErrorOccurredFlag()) {
  258. cmCTestLog(this->CTest, ERROR_MESSAGE,
  259. "Error in read:" << systemFile << "\n");
  260. return -1;
  261. }
  262. // Add definitions of variables passed in on the command line:
  263. std::map<std::string, std::string> const& defs =
  264. this->CTest->GetDefinitions();
  265. for (auto const& d : defs) {
  266. this->Makefile->AddDefinition(d.first, d.second);
  267. }
  268. int res = 0;
  269. // finally read in the script
  270. if (!this->Makefile->ReadListFile(script) ||
  271. cmSystemTools::GetErrorOccurredFlag()) {
  272. // Reset the error flag so that it can run more than
  273. // one script with an error when you use ctest_run_script.
  274. cmSystemTools::ResetErrorOccurredFlag();
  275. res = -1;
  276. }
  277. return this->CMake->HasScriptModeExitCode()
  278. ? this->CMake->GetScriptModeExitCode()
  279. : res;
  280. }
  281. // run a specific script
  282. int cmCTestScriptHandler::RunConfigurationScript(
  283. std::string const& total_script_arg, bool pscope)
  284. {
  285. #ifndef CMAKE_BOOTSTRAP
  286. cmSystemTools::SaveRestoreEnvironment sre;
  287. #endif
  288. int result;
  289. // read in the script
  290. if (pscope) {
  291. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  292. "Reading Script: " << total_script_arg << std::endl);
  293. result = this->ReadInScript(total_script_arg);
  294. } else {
  295. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  296. "Executing Script: " << total_script_arg << std::endl);
  297. result = this->ExecuteScript(total_script_arg);
  298. }
  299. return result;
  300. }
  301. bool cmCTestScriptHandler::RunScript(cmCTest* ctest, cmMakefile* mf,
  302. std::string const& sname, bool InProcess,
  303. int* returnValue)
  304. {
  305. auto sh = cm::make_unique<cmCTestScriptHandler>(ctest);
  306. sh->ParentMakefile = mf;
  307. sh->AddConfigurationScript(sname, InProcess);
  308. int res = sh->ProcessHandler();
  309. if (returnValue) {
  310. *returnValue = res;
  311. }
  312. return true;
  313. }