cmCTestScriptHandler.cxx 32 KB

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