cmCTestScriptHandler.cxx 32 KB

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