cmCTestScriptHandler.cxx 30 KB

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