cmCTestScriptHandler.cxx 30 KB

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