1
0

cmCTestScriptHandler.cxx 31 KB

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