cmCTestScriptHandler.cxx 31 KB

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