cmCTestScriptHandler.cxx 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file Copyright.txt or https://cmake.org/licensing for details. */
  3. #include "cmCTestScriptHandler.h"
  4. #include <cstdio>
  5. #include <cstdlib>
  6. #include <map>
  7. #include <ratio>
  8. #include <sstream>
  9. #include <utility>
  10. #include <cm/memory>
  11. #include <cm3p/uv.h>
  12. #include "cmsys/Directory.hxx"
  13. #include "cmCTest.h"
  14. #include "cmCTestBuildCommand.h"
  15. #include "cmCTestCommand.h"
  16. #include "cmCTestConfigureCommand.h"
  17. #include "cmCTestCoverageCommand.h"
  18. #include "cmCTestEmptyBinaryDirectoryCommand.h"
  19. #include "cmCTestMemCheckCommand.h"
  20. #include "cmCTestReadCustomFilesCommand.h"
  21. #include "cmCTestRunScriptCommand.h"
  22. #include "cmCTestSleepCommand.h"
  23. #include "cmCTestStartCommand.h"
  24. #include "cmCTestSubmitCommand.h"
  25. #include "cmCTestTestCommand.h"
  26. #include "cmCTestUpdateCommand.h"
  27. #include "cmCTestUploadCommand.h"
  28. #include "cmCommand.h"
  29. #include "cmDuration.h"
  30. #include "cmGeneratedFileStream.h"
  31. #include "cmGlobalGenerator.h"
  32. #include "cmList.h"
  33. #include "cmMakefile.h"
  34. #include "cmState.h"
  35. #include "cmStateDirectory.h"
  36. #include "cmStateSnapshot.h"
  37. #include "cmStringAlgorithms.h"
  38. #include "cmSystemTools.h"
  39. #include "cmUVHandlePtr.h"
  40. #include "cmUVProcessChain.h"
  41. #include "cmValue.h"
  42. #include "cmake.h"
  43. #ifdef _WIN32
  44. # include <windows.h>
  45. #else
  46. # include <unistd.h>
  47. #endif
  48. cmCTestScriptHandler::cmCTestScriptHandler() = default;
  49. void cmCTestScriptHandler::Initialize()
  50. {
  51. this->Superclass::Initialize();
  52. this->Backup = false;
  53. this->EmptyBinDir = false;
  54. this->EmptyBinDirOnce = false;
  55. this->SourceDir.clear();
  56. this->BinaryDir.clear();
  57. this->BackupSourceDir.clear();
  58. this->BackupBinaryDir.clear();
  59. this->CTestRoot.clear();
  60. this->CVSCheckOut.clear();
  61. this->CTestCmd.clear();
  62. this->UpdateCmd.clear();
  63. this->CTestEnv.clear();
  64. this->InitialCache.clear();
  65. this->CMakeCmd.clear();
  66. this->CMOutFile.clear();
  67. this->ExtraUpdates.clear();
  68. this->MinimumInterval = 20 * 60;
  69. this->ContinuousDuration = -1;
  70. // what time in seconds did this script start running
  71. this->ScriptStartTime = std::chrono::steady_clock::time_point();
  72. this->Makefile.reset();
  73. this->ParentMakefile = nullptr;
  74. this->GlobalGenerator.reset();
  75. this->CMake.reset();
  76. }
  77. cmCTestScriptHandler::~cmCTestScriptHandler() = default;
  78. // just adds an argument to the vector
  79. void cmCTestScriptHandler::AddConfigurationScript(const std::string& script,
  80. bool pscope)
  81. {
  82. this->ConfigurationScripts.emplace_back(script);
  83. this->ScriptProcessScope.push_back(pscope);
  84. }
  85. // the generic entry point for handling scripts, this routine will run all
  86. // the scripts provides a -S arguments
  87. int cmCTestScriptHandler::ProcessHandler()
  88. {
  89. int res = 0;
  90. for (size_t i = 0; i < this->ConfigurationScripts.size(); ++i) {
  91. // for each script run it
  92. res |= this->RunConfigurationScript(
  93. cmSystemTools::CollapseFullPath(this->ConfigurationScripts[i]),
  94. this->ScriptProcessScope[i]);
  95. }
  96. if (res) {
  97. return -1;
  98. }
  99. return 0;
  100. }
  101. void cmCTestScriptHandler::UpdateElapsedTime()
  102. {
  103. if (this->Makefile) {
  104. // set the current elapsed time
  105. auto itime = cmDurationTo<unsigned int>(std::chrono::steady_clock::now() -
  106. this->ScriptStartTime);
  107. auto timeString = std::to_string(itime);
  108. this->Makefile->AddDefinition("CTEST_ELAPSED_TIME", timeString);
  109. }
  110. }
  111. void cmCTestScriptHandler::AddCTestCommand(
  112. std::string const& name, std::unique_ptr<cmCTestCommand> command)
  113. {
  114. command->CTest = this->CTest;
  115. command->CTestScriptHandler = this;
  116. this->CMake->GetState()->AddBuiltinCommand(name, std::move(command));
  117. }
  118. int cmCTestScriptHandler::ExecuteScript(const std::string& total_script_arg)
  119. {
  120. // execute the script passing in the arguments to the script as well as the
  121. // arguments from this invocation of cmake
  122. std::vector<const char*> argv;
  123. argv.push_back(cmSystemTools::GetCTestCommand().c_str());
  124. argv.push_back("-SR");
  125. argv.push_back(total_script_arg.c_str());
  126. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  127. "Executable for CTest is: " << cmSystemTools::GetCTestCommand()
  128. << "\n");
  129. // now pass through all the other arguments
  130. std::vector<std::string>& initArgs =
  131. this->CTest->GetInitialCommandLineArguments();
  132. // Now create process object
  133. cmUVProcessChainBuilder builder;
  134. builder.AddCommand(initArgs)
  135. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_OUTPUT)
  136. .SetBuiltinStream(cmUVProcessChainBuilder::Stream_ERROR);
  137. auto process = builder.Start();
  138. cm::uv_pipe_ptr outPipe;
  139. outPipe.init(process.GetLoop(), 0);
  140. uv_pipe_open(outPipe, process.OutputStream());
  141. cm::uv_pipe_ptr errPipe;
  142. errPipe.init(process.GetLoop(), 0);
  143. uv_pipe_open(errPipe, process.ErrorStream());
  144. std::vector<char> out;
  145. std::vector<char> err;
  146. std::string line;
  147. auto pipe =
  148. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  149. std::chrono::seconds(100), out, err);
  150. while (pipe != cmSystemTools::WaitForLineResult::None) {
  151. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  152. "Output: " << line << "\n");
  153. if (pipe == cmSystemTools::WaitForLineResult::STDERR) {
  154. cmCTestLog(this->CTest, ERROR_MESSAGE, line << "\n");
  155. } else if (pipe == cmSystemTools::WaitForLineResult::STDOUT) {
  156. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT, line << "\n");
  157. }
  158. pipe =
  159. cmSystemTools::WaitForLine(&process.GetLoop(), outPipe, errPipe, line,
  160. std::chrono::seconds(100), out, err);
  161. }
  162. // Properly handle output of the build command
  163. process.Wait();
  164. auto const& status = process.GetStatus(0);
  165. auto result = status.GetException();
  166. int retVal = 0;
  167. bool failed = false;
  168. switch (result.first) {
  169. case cmUVProcessChain::ExceptionCode::None:
  170. retVal = static_cast<int>(status.ExitStatus);
  171. break;
  172. case cmUVProcessChain::ExceptionCode::Spawn:
  173. cmCTestLog(this->CTest, ERROR_MESSAGE,
  174. "\tError executing ctest: " << result.second << std::endl);
  175. failed = true;
  176. break;
  177. default:
  178. retVal = status.TermSignal;
  179. cmCTestLog(this->CTest, ERROR_MESSAGE,
  180. "\tThere was an exception: " << result.second << " " << retVal
  181. << std::endl);
  182. failed = true;
  183. }
  184. if (failed) {
  185. std::ostringstream message;
  186. message << "Error running command: [";
  187. message << static_cast<int>(result.first) << "] ";
  188. for (const char* arg : argv) {
  189. if (arg) {
  190. message << arg << " ";
  191. }
  192. }
  193. cmCTestLog(this->CTest, ERROR_MESSAGE,
  194. message.str() << argv[0] << std::endl);
  195. return -1;
  196. }
  197. return retVal;
  198. }
  199. void cmCTestScriptHandler::CreateCMake()
  200. {
  201. // create a cmake instance to read the configuration script
  202. this->CMake = cm::make_unique<cmake>(cmake::RoleScript, cmState::CTest);
  203. this->CMake->SetHomeDirectory("");
  204. this->CMake->SetHomeOutputDirectory("");
  205. this->CMake->GetCurrentSnapshot().SetDefaultDefinitions();
  206. this->CMake->AddCMakePaths();
  207. this->GlobalGenerator =
  208. cm::make_unique<cmGlobalGenerator>(this->CMake.get());
  209. cmStateSnapshot snapshot = this->CMake->GetCurrentSnapshot();
  210. std::string cwd = cmSystemTools::GetCurrentWorkingDirectory();
  211. snapshot.GetDirectory().SetCurrentSource(cwd);
  212. snapshot.GetDirectory().SetCurrentBinary(cwd);
  213. this->Makefile =
  214. cm::make_unique<cmMakefile>(this->GlobalGenerator.get(), snapshot);
  215. if (this->ParentMakefile) {
  216. this->Makefile->SetRecursionDepth(
  217. this->ParentMakefile->GetRecursionDepth());
  218. }
  219. this->CMake->SetProgressCallback(
  220. [this](const std::string& m, float /*unused*/) {
  221. if (!m.empty()) {
  222. cmCTestLog(this->CTest, HANDLER_OUTPUT, "-- " << m << std::endl);
  223. }
  224. });
  225. this->AddCTestCommand("ctest_build", cm::make_unique<cmCTestBuildCommand>());
  226. this->AddCTestCommand("ctest_configure",
  227. cm::make_unique<cmCTestConfigureCommand>());
  228. this->AddCTestCommand("ctest_coverage",
  229. cm::make_unique<cmCTestCoverageCommand>());
  230. this->AddCTestCommand("ctest_empty_binary_directory",
  231. cm::make_unique<cmCTestEmptyBinaryDirectoryCommand>());
  232. this->AddCTestCommand("ctest_memcheck",
  233. cm::make_unique<cmCTestMemCheckCommand>());
  234. this->AddCTestCommand("ctest_read_custom_files",
  235. cm::make_unique<cmCTestReadCustomFilesCommand>());
  236. this->AddCTestCommand("ctest_run_script",
  237. cm::make_unique<cmCTestRunScriptCommand>());
  238. this->AddCTestCommand("ctest_sleep", cm::make_unique<cmCTestSleepCommand>());
  239. this->AddCTestCommand("ctest_start", cm::make_unique<cmCTestStartCommand>());
  240. this->AddCTestCommand("ctest_submit",
  241. cm::make_unique<cmCTestSubmitCommand>());
  242. this->AddCTestCommand("ctest_test", cm::make_unique<cmCTestTestCommand>());
  243. this->AddCTestCommand("ctest_update",
  244. cm::make_unique<cmCTestUpdateCommand>());
  245. this->AddCTestCommand("ctest_upload",
  246. cm::make_unique<cmCTestUploadCommand>());
  247. }
  248. // this sets up some variables for the script to use, creates the required
  249. // cmake instance and generators, and then reads in the script
  250. int cmCTestScriptHandler::ReadInScript(const std::string& total_script_arg)
  251. {
  252. // Reset the error flag so that the script is read in no matter what
  253. cmSystemTools::ResetErrorOccurredFlag();
  254. // if the argument has a , in it then it needs to be broken into the fist
  255. // argument (which is the script) and the second argument which will be
  256. // passed into the scripts as S_ARG
  257. std::string script;
  258. std::string script_arg;
  259. const std::string::size_type comma_pos = total_script_arg.find(',');
  260. if (comma_pos != std::string::npos) {
  261. script = total_script_arg.substr(0, comma_pos);
  262. script_arg = total_script_arg.substr(comma_pos + 1);
  263. } else {
  264. script = total_script_arg;
  265. }
  266. // make sure the file exists
  267. if (!cmSystemTools::FileExists(script)) {
  268. cmSystemTools::Error("Cannot find file: " + script);
  269. return 1;
  270. }
  271. // read in the list file to fill the cache
  272. // create a cmake instance to read the configuration script
  273. this->CreateCMake();
  274. // set a variable with the path to the current script
  275. this->Makefile->AddDefinition("CTEST_SCRIPT_DIRECTORY",
  276. cmSystemTools::GetFilenamePath(script));
  277. this->Makefile->AddDefinition("CTEST_SCRIPT_NAME",
  278. cmSystemTools::GetFilenameName(script));
  279. this->Makefile->AddDefinition("CTEST_EXECUTABLE_NAME",
  280. cmSystemTools::GetCTestCommand());
  281. this->Makefile->AddDefinition("CMAKE_EXECUTABLE_NAME",
  282. cmSystemTools::GetCMakeCommand());
  283. this->Makefile->AddDefinitionBool("CTEST_RUN_CURRENT_SCRIPT", true);
  284. this->SetRunCurrentScript(true);
  285. this->UpdateElapsedTime();
  286. // set the CTEST_CONFIGURATION_TYPE variable to the current value of the
  287. // the -C argument on the command line.
  288. if (!this->CTest->GetConfigType().empty()) {
  289. this->Makefile->AddDefinition("CTEST_CONFIGURATION_TYPE",
  290. this->CTest->GetConfigType());
  291. }
  292. // add the script arg if defined
  293. if (!script_arg.empty()) {
  294. this->Makefile->AddDefinition("CTEST_SCRIPT_ARG", script_arg);
  295. }
  296. // set a callback function to update the elapsed time
  297. this->Makefile->OnExecuteCommand([this] { this->UpdateElapsedTime(); });
  298. /* Execute CTestScriptMode.cmake, which loads CMakeDetermineSystem and
  299. CMakeSystemSpecificInformation, so
  300. that variables like CMAKE_SYSTEM and also the search paths for libraries,
  301. header and executables are set correctly and can be used. Makes new-style
  302. ctest scripting easier. */
  303. std::string systemFile =
  304. this->Makefile->GetModulesFile("CTestScriptMode.cmake");
  305. if (!this->Makefile->ReadListFile(systemFile) ||
  306. cmSystemTools::GetErrorOccurredFlag()) {
  307. cmCTestLog(this->CTest, ERROR_MESSAGE,
  308. "Error in read:" << systemFile << "\n");
  309. return 2;
  310. }
  311. // Add definitions of variables passed in on the command line:
  312. const std::map<std::string, std::string>& defs =
  313. this->CTest->GetDefinitions();
  314. for (auto const& d : defs) {
  315. this->Makefile->AddDefinition(d.first, d.second);
  316. }
  317. // finally read in the script
  318. if (!this->Makefile->ReadListFile(script) ||
  319. cmSystemTools::GetErrorOccurredFlag()) {
  320. // Reset the error flag so that it can run more than
  321. // one script with an error when you use ctest_run_script.
  322. cmSystemTools::ResetErrorOccurredFlag();
  323. return 2;
  324. }
  325. return 0;
  326. }
  327. // extract variables from the script to set ivars
  328. int cmCTestScriptHandler::ExtractVariables()
  329. {
  330. // Temporary variables
  331. cmValue minInterval;
  332. cmValue contDuration;
  333. this->SourceDir =
  334. this->Makefile->GetSafeDefinition("CTEST_SOURCE_DIRECTORY");
  335. this->BinaryDir =
  336. this->Makefile->GetSafeDefinition("CTEST_BINARY_DIRECTORY");
  337. // add in translations for src and bin
  338. cmSystemTools::AddKeepPath(this->SourceDir);
  339. cmSystemTools::AddKeepPath(this->BinaryDir);
  340. this->CTestCmd = this->Makefile->GetSafeDefinition("CTEST_COMMAND");
  341. this->CVSCheckOut = this->Makefile->GetSafeDefinition("CTEST_CVS_CHECKOUT");
  342. this->CTestRoot = this->Makefile->GetSafeDefinition("CTEST_DASHBOARD_ROOT");
  343. this->UpdateCmd = this->Makefile->GetSafeDefinition("CTEST_UPDATE_COMMAND");
  344. if (this->UpdateCmd.empty()) {
  345. this->UpdateCmd = this->Makefile->GetSafeDefinition("CTEST_CVS_COMMAND");
  346. }
  347. this->CTestEnv = this->Makefile->GetSafeDefinition("CTEST_ENVIRONMENT");
  348. this->InitialCache =
  349. this->Makefile->GetSafeDefinition("CTEST_INITIAL_CACHE");
  350. this->CMakeCmd = this->Makefile->GetSafeDefinition("CTEST_CMAKE_COMMAND");
  351. this->CMOutFile =
  352. this->Makefile->GetSafeDefinition("CTEST_CMAKE_OUTPUT_FILE_NAME");
  353. this->Backup = this->Makefile->IsOn("CTEST_BACKUP_AND_RESTORE");
  354. this->EmptyBinDir =
  355. this->Makefile->IsOn("CTEST_START_WITH_EMPTY_BINARY_DIRECTORY");
  356. this->EmptyBinDirOnce =
  357. this->Makefile->IsOn("CTEST_START_WITH_EMPTY_BINARY_DIRECTORY_ONCE");
  358. minInterval =
  359. this->Makefile->GetDefinition("CTEST_CONTINUOUS_MINIMUM_INTERVAL");
  360. contDuration = this->Makefile->GetDefinition("CTEST_CONTINUOUS_DURATION");
  361. char updateVar[40];
  362. int i;
  363. for (i = 1; i < 10; ++i) {
  364. snprintf(updateVar, sizeof(updateVar), "CTEST_EXTRA_UPDATES_%i", i);
  365. cmValue updateVal = this->Makefile->GetDefinition(updateVar);
  366. if (updateVal) {
  367. if (this->UpdateCmd.empty()) {
  368. cmSystemTools::Error(
  369. std::string(updateVar) +
  370. " specified without specifying CTEST_CVS_COMMAND.");
  371. return 12;
  372. }
  373. this->ExtraUpdates.emplace_back(*updateVal);
  374. }
  375. }
  376. // in order to backup and restore we also must have the cvs root
  377. if (this->Backup && this->CVSCheckOut.empty()) {
  378. cmSystemTools::Error(
  379. "Backup was requested without specifying CTEST_CVS_CHECKOUT.");
  380. return 3;
  381. }
  382. // make sure the required info is here
  383. if (this->SourceDir.empty() || this->BinaryDir.empty() ||
  384. this->CTestCmd.empty()) {
  385. std::string msg =
  386. cmStrCat("CTEST_SOURCE_DIRECTORY = ",
  387. (!this->SourceDir.empty()) ? this->SourceDir.c_str() : "(Null)",
  388. "\nCTEST_BINARY_DIRECTORY = ",
  389. (!this->BinaryDir.empty()) ? this->BinaryDir.c_str() : "(Null)",
  390. "\nCTEST_COMMAND = ",
  391. (!this->CTestCmd.empty()) ? this->CTestCmd.c_str() : "(Null)");
  392. cmSystemTools::Error(
  393. "Some required settings in the configuration file were missing:\n" +
  394. msg);
  395. return 4;
  396. }
  397. // if the dashboard root isn't specified then we can compute it from the
  398. // this->SourceDir
  399. if (this->CTestRoot.empty()) {
  400. this->CTestRoot = cmSystemTools::GetFilenamePath(this->SourceDir);
  401. }
  402. // the script may override the minimum continuous interval
  403. if (minInterval) {
  404. this->MinimumInterval = 60 * atof(minInterval->c_str());
  405. }
  406. if (contDuration) {
  407. this->ContinuousDuration = 60.0 * atof(contDuration->c_str());
  408. }
  409. this->UpdateElapsedTime();
  410. return 0;
  411. }
  412. void cmCTestScriptHandler::SleepInSeconds(unsigned int secondsToWait)
  413. {
  414. #if defined(_WIN32)
  415. Sleep(1000 * secondsToWait);
  416. #else
  417. sleep(secondsToWait);
  418. #endif
  419. }
  420. // run a specific script
  421. int cmCTestScriptHandler::RunConfigurationScript(
  422. const std::string& total_script_arg, bool pscope)
  423. {
  424. #ifndef CMAKE_BOOTSTRAP
  425. cmSystemTools::SaveRestoreEnvironment sre;
  426. #endif
  427. int result;
  428. this->ScriptStartTime = std::chrono::steady_clock::now();
  429. // read in the script
  430. if (pscope) {
  431. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  432. "Reading Script: " << total_script_arg << std::endl);
  433. result = this->ReadInScript(total_script_arg);
  434. } else {
  435. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  436. "Executing Script: " << total_script_arg << std::endl);
  437. result = this->ExecuteScript(total_script_arg);
  438. }
  439. if (result) {
  440. return result;
  441. }
  442. // only run the current script if we should
  443. if (this->Makefile && this->Makefile->IsOn("CTEST_RUN_CURRENT_SCRIPT") &&
  444. this->ShouldRunCurrentScript) {
  445. return this->RunCurrentScript();
  446. }
  447. return result;
  448. }
  449. int cmCTestScriptHandler::RunCurrentScript()
  450. {
  451. int result;
  452. // do not run twice
  453. this->SetRunCurrentScript(false);
  454. // no popup widows
  455. cmSystemTools::SetRunCommandHideConsole(true);
  456. // extract the vars from the cache and store in ivars
  457. result = this->ExtractVariables();
  458. if (result) {
  459. return result;
  460. }
  461. // set any environment variables
  462. if (!this->CTestEnv.empty()) {
  463. cmList envArgs{ this->CTestEnv };
  464. cmSystemTools::AppendEnv(envArgs);
  465. }
  466. // now that we have done most of the error checking finally run the
  467. // dashboard, we may be asked to repeatedly run this dashboard, such as
  468. // for a continuous, do we need to run it more than once?
  469. if (this->ContinuousDuration >= 0) {
  470. this->UpdateElapsedTime();
  471. auto ending_time =
  472. std::chrono::steady_clock::now() + cmDuration(this->ContinuousDuration);
  473. if (this->EmptyBinDirOnce) {
  474. this->EmptyBinDir = true;
  475. }
  476. do {
  477. auto startOfInterval = std::chrono::steady_clock::now();
  478. result = this->RunConfigurationDashboard();
  479. auto interval = std::chrono::steady_clock::now() - startOfInterval;
  480. auto minimumInterval = cmDuration(this->MinimumInterval);
  481. if (interval < minimumInterval) {
  482. auto sleepTime =
  483. cmDurationTo<unsigned int>(minimumInterval - interval);
  484. this->SleepInSeconds(sleepTime);
  485. }
  486. if (this->EmptyBinDirOnce) {
  487. this->EmptyBinDir = false;
  488. }
  489. } while (std::chrono::steady_clock::now() < ending_time);
  490. }
  491. // otherwise just run it once
  492. else {
  493. result = this->RunConfigurationDashboard();
  494. }
  495. return result;
  496. }
  497. int cmCTestScriptHandler::CheckOutSourceDir()
  498. {
  499. std::string command;
  500. std::string output;
  501. int retVal;
  502. bool res;
  503. if (!cmSystemTools::FileExists(this->SourceDir) &&
  504. !this->CVSCheckOut.empty()) {
  505. // we must now checkout the src dir
  506. output.clear();
  507. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  508. "Run cvs: " << this->CVSCheckOut << std::endl);
  509. res = cmSystemTools::RunSingleCommand(
  510. this->CVSCheckOut, &output, &output, &retVal, this->CTestRoot.c_str(),
  511. this->HandlerVerbose, cmDuration::zero() /*this->TimeOut*/);
  512. if (!res || retVal != 0) {
  513. cmSystemTools::Error("Unable to perform cvs checkout:\n" + output);
  514. return 6;
  515. }
  516. }
  517. return 0;
  518. }
  519. int cmCTestScriptHandler::BackupDirectories()
  520. {
  521. int retVal;
  522. // compute the backup names
  523. this->BackupSourceDir = cmStrCat(this->SourceDir, "_CMakeBackup");
  524. this->BackupBinaryDir = cmStrCat(this->BinaryDir, "_CMakeBackup");
  525. // backup the binary and src directories if requested
  526. if (this->Backup) {
  527. // if for some reason those directories exist then first delete them
  528. if (cmSystemTools::FileExists(this->BackupSourceDir)) {
  529. cmSystemTools::RemoveADirectory(this->BackupSourceDir);
  530. }
  531. if (cmSystemTools::FileExists(this->BackupBinaryDir)) {
  532. cmSystemTools::RemoveADirectory(this->BackupBinaryDir);
  533. }
  534. // first rename the src and binary directories
  535. rename(this->SourceDir.c_str(), this->BackupSourceDir.c_str());
  536. rename(this->BinaryDir.c_str(), this->BackupBinaryDir.c_str());
  537. // we must now checkout the src dir
  538. retVal = this->CheckOutSourceDir();
  539. if (retVal) {
  540. this->RestoreBackupDirectories();
  541. return retVal;
  542. }
  543. }
  544. return 0;
  545. }
  546. int cmCTestScriptHandler::PerformExtraUpdates()
  547. {
  548. std::string command;
  549. std::string output;
  550. int retVal;
  551. bool res;
  552. // do an initial cvs update as required
  553. command = this->UpdateCmd;
  554. for (std::string const& eu : this->ExtraUpdates) {
  555. cmList cvsArgs{ eu };
  556. if (cvsArgs.size() == 2) {
  557. std::string fullCommand = cmStrCat(command, " update ", cvsArgs[1]);
  558. output.clear();
  559. retVal = 0;
  560. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  561. "Run Update: " << fullCommand << std::endl);
  562. res = cmSystemTools::RunSingleCommand(
  563. fullCommand, &output, &output, &retVal, cvsArgs[0].c_str(),
  564. this->HandlerVerbose, cmDuration::zero() /*this->TimeOut*/);
  565. if (!res || retVal != 0) {
  566. cmSystemTools::Error(cmStrCat("Unable to perform extra updates:\n", eu,
  567. "\nWith output:\n", output));
  568. return 0;
  569. }
  570. }
  571. }
  572. return 0;
  573. }
  574. // run a single dashboard entry
  575. int cmCTestScriptHandler::RunConfigurationDashboard()
  576. {
  577. // local variables
  578. std::string command;
  579. std::string output;
  580. int retVal;
  581. bool res;
  582. // make sure the src directory is there, if it isn't then we might be able
  583. // to check it out from cvs
  584. retVal = this->CheckOutSourceDir();
  585. if (retVal) {
  586. return retVal;
  587. }
  588. // backup the dirs if requested
  589. retVal = this->BackupDirectories();
  590. if (retVal) {
  591. return retVal;
  592. }
  593. // clear the binary directory?
  594. if (this->EmptyBinDir) {
  595. if (!cmCTestScriptHandler::EmptyBinaryDirectory(this->BinaryDir)) {
  596. cmCTestLog(this->CTest, ERROR_MESSAGE,
  597. "Problem removing the binary directory" << std::endl);
  598. }
  599. }
  600. // make sure the binary directory exists if it isn't the srcdir
  601. if (!cmSystemTools::FileExists(this->BinaryDir) &&
  602. this->SourceDir != this->BinaryDir) {
  603. if (!cmSystemTools::MakeDirectory(this->BinaryDir)) {
  604. cmSystemTools::Error("Unable to create the binary directory:\n" +
  605. this->BinaryDir);
  606. this->RestoreBackupDirectories();
  607. return 7;
  608. }
  609. }
  610. // if the binary directory and the source directory are the same,
  611. // and we are starting with an empty binary directory, then that means
  612. // we must check out the source tree
  613. if (this->EmptyBinDir && this->SourceDir == this->BinaryDir) {
  614. // make sure we have the required info
  615. if (this->CVSCheckOut.empty()) {
  616. cmSystemTools::Error(
  617. "You have specified the source and binary "
  618. "directories to be the same (an in source build). You have also "
  619. "specified that the binary directory is to be erased. This means "
  620. "that the source will have to be checked out from CVS. But you have "
  621. "not specified CTEST_CVS_CHECKOUT");
  622. return 8;
  623. }
  624. // we must now checkout the src dir
  625. retVal = this->CheckOutSourceDir();
  626. if (retVal) {
  627. this->RestoreBackupDirectories();
  628. return retVal;
  629. }
  630. }
  631. // backup the dirs if requested
  632. retVal = this->PerformExtraUpdates();
  633. if (retVal) {
  634. return retVal;
  635. }
  636. // put the initial cache into the bin dir
  637. if (!this->InitialCache.empty()) {
  638. if (!cmCTestScriptHandler::WriteInitialCache(this->BinaryDir,
  639. this->InitialCache)) {
  640. this->RestoreBackupDirectories();
  641. return 9;
  642. }
  643. }
  644. // do an initial cmake to setup the DartConfig file
  645. int cmakeFailed = 0;
  646. std::string cmakeFailedOuput;
  647. if (!this->CMakeCmd.empty()) {
  648. command = cmStrCat(this->CMakeCmd, " \"", this->SourceDir);
  649. output.clear();
  650. command += "\"";
  651. retVal = 0;
  652. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  653. "Run cmake command: " << command << std::endl);
  654. res = cmSystemTools::RunSingleCommand(
  655. command, &output, &output, &retVal, this->BinaryDir.c_str(),
  656. this->HandlerVerbose, cmDuration::zero() /*this->TimeOut*/);
  657. if (!this->CMOutFile.empty()) {
  658. std::string cmakeOutputFile = this->CMOutFile;
  659. if (!cmSystemTools::FileIsFullPath(cmakeOutputFile)) {
  660. cmakeOutputFile = this->BinaryDir + "/" + cmakeOutputFile;
  661. }
  662. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  663. "Write CMake output to file: " << cmakeOutputFile
  664. << std::endl);
  665. cmGeneratedFileStream fout(cmakeOutputFile);
  666. if (fout) {
  667. fout << output.c_str();
  668. } else {
  669. cmCTestLog(this->CTest, ERROR_MESSAGE,
  670. "Cannot open CMake output file: "
  671. << cmakeOutputFile << " for writing" << std::endl);
  672. }
  673. }
  674. if (!res || retVal != 0) {
  675. // even if this fails continue to the next step
  676. cmakeFailed = 1;
  677. cmakeFailedOuput = output;
  678. }
  679. }
  680. // run ctest, it may be more than one command in here
  681. cmList ctestCommands{ this->CTestCmd };
  682. // for each variable/argument do a putenv
  683. for (std::string const& ctestCommand : ctestCommands) {
  684. command = ctestCommand;
  685. output.clear();
  686. retVal = 0;
  687. cmCTestLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  688. "Run ctest command: " << command << std::endl);
  689. res = cmSystemTools::RunSingleCommand(
  690. command, &output, &output, &retVal, this->BinaryDir.c_str(),
  691. this->HandlerVerbose, cmDuration::zero() /*this->TimeOut*/);
  692. // did something critical fail in ctest
  693. if (!res || cmakeFailed || retVal & cmCTest::BUILD_ERRORS) {
  694. this->RestoreBackupDirectories();
  695. if (cmakeFailed) {
  696. cmCTestLog(this->CTest, ERROR_MESSAGE,
  697. "Unable to run cmake:" << std::endl
  698. << cmakeFailedOuput << std::endl);
  699. return 10;
  700. }
  701. cmCTestLog(this->CTest, ERROR_MESSAGE,
  702. "Unable to run ctest:" << std::endl
  703. << "command: " << command << std::endl
  704. << "output: " << output << std::endl);
  705. if (!res) {
  706. return 11;
  707. }
  708. return retVal * 100;
  709. }
  710. }
  711. // if all was successful, delete the backup dirs to free up disk space
  712. if (this->Backup) {
  713. cmSystemTools::RemoveADirectory(this->BackupSourceDir);
  714. cmSystemTools::RemoveADirectory(this->BackupBinaryDir);
  715. }
  716. return 0;
  717. }
  718. bool cmCTestScriptHandler::WriteInitialCache(const std::string& directory,
  719. const std::string& text)
  720. {
  721. std::string cacheFile = cmStrCat(directory, "/CMakeCache.txt");
  722. cmGeneratedFileStream fout(cacheFile);
  723. if (!fout) {
  724. return false;
  725. }
  726. fout.write(text.data(), text.size());
  727. // Make sure the operating system has finished writing the file
  728. // before closing it. This will ensure the file is finished before
  729. // the check below.
  730. fout.flush();
  731. fout.close();
  732. return true;
  733. }
  734. void cmCTestScriptHandler::RestoreBackupDirectories()
  735. {
  736. // if we backed up the dirs and the build failed, then restore
  737. // the backed up dirs
  738. if (this->Backup) {
  739. // if for some reason those directories exist then first delete them
  740. if (cmSystemTools::FileExists(this->SourceDir)) {
  741. cmSystemTools::RemoveADirectory(this->SourceDir);
  742. }
  743. if (cmSystemTools::FileExists(this->BinaryDir)) {
  744. cmSystemTools::RemoveADirectory(this->BinaryDir);
  745. }
  746. // rename the src and binary directories
  747. rename(this->BackupSourceDir.c_str(), this->SourceDir.c_str());
  748. rename(this->BackupBinaryDir.c_str(), this->BinaryDir.c_str());
  749. }
  750. }
  751. bool cmCTestScriptHandler::RunScript(cmCTest* ctest, cmMakefile* mf,
  752. const std::string& sname, bool InProcess,
  753. int* returnValue)
  754. {
  755. auto sh = cm::make_unique<cmCTestScriptHandler>();
  756. sh->SetCTestInstance(ctest);
  757. sh->ParentMakefile = mf;
  758. sh->AddConfigurationScript(sname, InProcess);
  759. int res = sh->ProcessHandler();
  760. if (returnValue) {
  761. *returnValue = res;
  762. }
  763. return true;
  764. }
  765. bool cmCTestScriptHandler::EmptyBinaryDirectory(const std::string& sname)
  766. {
  767. // try to avoid deleting root
  768. if (sname.size() < 2) {
  769. return false;
  770. }
  771. // consider non existing target directory a success
  772. if (!cmSystemTools::FileExists(sname)) {
  773. return true;
  774. }
  775. // try to avoid deleting directories that we shouldn't
  776. std::string check = cmStrCat(sname, "/CMakeCache.txt");
  777. if (!cmSystemTools::FileExists(check)) {
  778. return false;
  779. }
  780. for (int i = 0; i < 5; ++i) {
  781. if (TryToRemoveBinaryDirectoryOnce(sname)) {
  782. return true;
  783. }
  784. cmSystemTools::Delay(100);
  785. }
  786. return false;
  787. }
  788. bool cmCTestScriptHandler::TryToRemoveBinaryDirectoryOnce(
  789. const std::string& directoryPath)
  790. {
  791. cmsys::Directory directory;
  792. directory.Load(directoryPath);
  793. for (unsigned long i = 0; i < directory.GetNumberOfFiles(); ++i) {
  794. std::string path = directory.GetFile(i);
  795. if (path == "." || path == ".." || path == "CMakeCache.txt") {
  796. continue;
  797. }
  798. std::string fullPath = cmStrCat(directoryPath, "/", path);
  799. bool isDirectory = cmSystemTools::FileIsDirectory(fullPath) &&
  800. !cmSystemTools::FileIsSymlink(fullPath);
  801. if (isDirectory) {
  802. if (!cmSystemTools::RemoveADirectory(fullPath)) {
  803. return false;
  804. }
  805. } else {
  806. if (!cmSystemTools::RemoveFile(fullPath)) {
  807. return false;
  808. }
  809. }
  810. }
  811. return static_cast<bool>(cmSystemTools::RemoveADirectory(directoryPath));
  812. }
  813. cmDuration cmCTestScriptHandler::GetRemainingTimeAllowed()
  814. {
  815. if (!this->Makefile) {
  816. return cmCTest::MaxDuration();
  817. }
  818. cmValue timelimitS = this->Makefile->GetDefinition("CTEST_TIME_LIMIT");
  819. if (!timelimitS) {
  820. return cmCTest::MaxDuration();
  821. }
  822. auto timelimit = cmDuration(atof(timelimitS->c_str()));
  823. auto duration = std::chrono::duration_cast<cmDuration>(
  824. std::chrono::steady_clock::now() - this->ScriptStartTime);
  825. return (timelimit - duration);
  826. }
  827. void cmCTestScriptHandler::SetRunCurrentScript(bool value)
  828. {
  829. this->ShouldRunCurrentScript = value;
  830. }