1
0

cmCTestScriptHandler.cxx 31 KB

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