cmCTestScriptHandler.cxx 31 KB

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