cmCTestScriptHandler.cxx 31 KB

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