cmCTestScriptHandler.cxx 30 KB

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