cmCTestScriptHandler.cxx 31 KB

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