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