cmCTestScriptHandler.cxx 31 KB

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