cmCTestSubmitHandler.cxx 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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 "cmCTestSubmitHandler.h"
  4. #include <chrono>
  5. #include <cstdio>
  6. #include <cstdlib>
  7. #include <sstream>
  8. #include <cm/iomanip>
  9. #include <cm/optional>
  10. #include <cmext/algorithm>
  11. #include <cm3p/curl/curl.h>
  12. #include <cm3p/json/reader.h>
  13. #include <cm3p/json/value.h>
  14. #include "cmAlgorithms.h"
  15. #include "cmCTest.h"
  16. #include "cmCTestCurl.h"
  17. #include "cmCTestScriptHandler.h"
  18. #include "cmCryptoHash.h"
  19. #include "cmCurl.h"
  20. #include "cmDuration.h"
  21. #include "cmGeneratedFileStream.h"
  22. #include "cmState.h"
  23. #include "cmStringAlgorithms.h"
  24. #include "cmSystemTools.h"
  25. #include "cmValue.h"
  26. #include "cmXMLParser.h"
  27. #include "cmake.h"
  28. #define SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT 120
  29. using cmCTestSubmitHandlerVectorOfChar = std::vector<char>;
  30. class cmCTestSubmitHandler::ResponseParser : public cmXMLParser
  31. {
  32. public:
  33. enum StatusType
  34. {
  35. STATUS_OK,
  36. STATUS_WARNING,
  37. STATUS_ERROR
  38. };
  39. StatusType Status = STATUS_OK;
  40. std::string Filename;
  41. std::string MD5;
  42. std::string Message;
  43. std::string BuildID;
  44. private:
  45. std::vector<char> CurrentValue;
  46. std::string GetCurrentValue()
  47. {
  48. std::string val;
  49. if (!this->CurrentValue.empty()) {
  50. val.assign(this->CurrentValue.data(), this->CurrentValue.size());
  51. }
  52. return val;
  53. }
  54. void StartElement(const std::string& /*name*/,
  55. const char** /*atts*/) override
  56. {
  57. this->CurrentValue.clear();
  58. }
  59. void CharacterDataHandler(const char* data, int length) override
  60. {
  61. cm::append(this->CurrentValue, data, data + length);
  62. }
  63. void EndElement(const std::string& name) override
  64. {
  65. if (name == "status") {
  66. std::string status = cmSystemTools::UpperCase(this->GetCurrentValue());
  67. if (status == "OK" || status == "SUCCESS") {
  68. this->Status = STATUS_OK;
  69. } else if (status == "WARNING") {
  70. this->Status = STATUS_WARNING;
  71. } else {
  72. this->Status = STATUS_ERROR;
  73. }
  74. } else if (name == "filename") {
  75. this->Filename = this->GetCurrentValue();
  76. } else if (name == "md5") {
  77. this->MD5 = this->GetCurrentValue();
  78. } else if (name == "message") {
  79. this->Message = this->GetCurrentValue();
  80. } else if (name == "buildId") {
  81. this->BuildID = this->GetCurrentValue();
  82. }
  83. }
  84. };
  85. static size_t cmCTestSubmitHandlerWriteMemoryCallback(void* ptr, size_t size,
  86. size_t nmemb, void* data)
  87. {
  88. int realsize = static_cast<int>(size * nmemb);
  89. const char* chPtr = static_cast<char*>(ptr);
  90. cm::append(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  91. chPtr + realsize);
  92. return realsize;
  93. }
  94. static size_t cmCTestSubmitHandlerCurlDebugCallback(CURL* /*unused*/,
  95. curl_infotype /*unused*/,
  96. char* chPtr, size_t size,
  97. void* data)
  98. {
  99. cm::append(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  100. chPtr + size);
  101. return 0;
  102. }
  103. cmCTestSubmitHandler::cmCTestSubmitHandler()
  104. {
  105. this->Initialize();
  106. }
  107. void cmCTestSubmitHandler::Initialize()
  108. {
  109. // We submit all available parts by default.
  110. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  111. p = static_cast<cmCTest::Part>(p + 1)) {
  112. this->SubmitPart[p] = true;
  113. }
  114. this->HasWarnings = false;
  115. this->HasErrors = false;
  116. this->Superclass::Initialize();
  117. this->HTTPProxy.clear();
  118. this->HTTPProxyType = 0;
  119. this->HTTPProxyAuth.clear();
  120. this->LogFile = nullptr;
  121. this->Files.clear();
  122. }
  123. int cmCTestSubmitHandler::ProcessCommandLineArguments(
  124. const std::string& currentArg, size_t& idx,
  125. const std::vector<std::string>& allArgs, bool& validArg)
  126. {
  127. if (cmHasLiteralPrefix(currentArg, "--http-header") &&
  128. idx < allArgs.size() - 1) {
  129. ++idx;
  130. this->HttpHeaders.push_back(allArgs[idx]);
  131. this->CommandLineHttpHeaders.push_back(allArgs[idx]);
  132. validArg = true;
  133. }
  134. return 1;
  135. }
  136. bool cmCTestSubmitHandler::SubmitUsingHTTP(
  137. const std::string& localprefix, const std::vector<std::string>& files,
  138. const std::string& remoteprefix, const std::string& url)
  139. {
  140. CURL* curl;
  141. FILE* ftpfile;
  142. char error_buffer[1024];
  143. // Set Content-Type to satisfy fussy modsecurity rules.
  144. struct curl_slist* headers =
  145. ::curl_slist_append(nullptr, "Content-Type: text/xml");
  146. // Add any additional headers that the user specified.
  147. for (std::string const& h : this->HttpHeaders) {
  148. cmCTestOptionalLog(this->CTest, DEBUG,
  149. " Add HTTP Header: \"" << h << "\"" << std::endl,
  150. this->Quiet);
  151. headers = ::curl_slist_append(headers, h.c_str());
  152. }
  153. cmCurlInitOnce();
  154. /* In windows, this will init the winsock stuff */
  155. ::curl_global_init(CURL_GLOBAL_ALL);
  156. cmCTestCurlOpts curlOpts(this->CTest);
  157. for (std::string const& file : files) {
  158. /* get a curl handle */
  159. curl = curl_easy_init();
  160. if (curl) {
  161. cmCurlSetCAInfo(curl);
  162. if (curlOpts.TLSVersionOpt) {
  163. cm::optional<std::string> tlsVersionStr =
  164. cmCurlPrintTLSVersion(*curlOpts.TLSVersionOpt);
  165. cmCTestOptionalLog(
  166. this->CTest, HANDLER_VERBOSE_OUTPUT,
  167. " Set CURLOPT_SSLVERSION to "
  168. << (tlsVersionStr ? *tlsVersionStr : "unknown value") << "\n",
  169. this->Quiet);
  170. curl_easy_setopt(curl, CURLOPT_SSLVERSION, *curlOpts.TLSVersionOpt);
  171. }
  172. if (curlOpts.TLSVerifyOpt) {
  173. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  174. " Set CURLOPT_SSL_VERIFYPEER to "
  175. << (*curlOpts.TLSVerifyOpt ? "on" : "off")
  176. << "\n",
  177. this->Quiet);
  178. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER,
  179. *curlOpts.TLSVerifyOpt ? 1 : 0);
  180. }
  181. if (curlOpts.VerifyHostOff) {
  182. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  183. " Set CURLOPT_SSL_VERIFYHOST to off\n",
  184. this->Quiet);
  185. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  186. }
  187. // Using proxy
  188. if (this->HTTPProxyType > 0) {
  189. curl_easy_setopt(curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
  190. switch (this->HTTPProxyType) {
  191. case 2:
  192. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  193. break;
  194. case 3:
  195. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  196. break;
  197. default:
  198. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  199. if (!this->HTTPProxyAuth.empty()) {
  200. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD,
  201. this->HTTPProxyAuth.c_str());
  202. }
  203. }
  204. }
  205. if (this->CTest->ShouldUseHTTP10()) {
  206. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  207. }
  208. /* enable uploading */
  209. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  210. // if there is little to no activity for too long stop submitting
  211. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  212. auto submitInactivityTimeout = this->GetSubmitInactivityTimeout();
  213. if (submitInactivityTimeout != 0) {
  214. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME,
  215. submitInactivityTimeout);
  216. }
  217. ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  218. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  219. std::string local_file = file;
  220. bool initialize_cdash_buildid = false;
  221. if (!cmSystemTools::FileExists(local_file)) {
  222. local_file = cmStrCat(localprefix, "/", file);
  223. // If this file exists within the local Testing directory we assume
  224. // that it will be associated with the current build in CDash.
  225. initialize_cdash_buildid = true;
  226. }
  227. std::string remote_file =
  228. remoteprefix + cmSystemTools::GetFilenameName(file);
  229. *this->LogFile << "\tUpload file: " << local_file << " to "
  230. << remote_file << std::endl;
  231. std::string ofile = cmSystemTools::EncodeURL(remote_file);
  232. std::string upload_as =
  233. cmStrCat(url, ((url.find('?') == std::string::npos) ? '?' : '&'),
  234. "FileName=", ofile);
  235. if (initialize_cdash_buildid) {
  236. // Provide extra arguments to CDash so that it can initialize and
  237. // return a buildid.
  238. cmCTestCurl ctest_curl(this->CTest);
  239. upload_as += "&build=";
  240. upload_as +=
  241. ctest_curl.Escape(this->CTest->GetCTestConfiguration("BuildName"));
  242. upload_as += "&site=";
  243. upload_as +=
  244. ctest_curl.Escape(this->CTest->GetCTestConfiguration("Site"));
  245. upload_as += "&stamp=";
  246. upload_as += ctest_curl.Escape(this->CTest->GetCurrentTag());
  247. upload_as += "-";
  248. upload_as += ctest_curl.Escape(this->CTest->GetTestModelString());
  249. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  250. cmake* cm = ch->GetCMake();
  251. if (cm) {
  252. cmValue subproject = cm->GetState()->GetGlobalProperty("SubProject");
  253. if (subproject) {
  254. upload_as += "&subproject=";
  255. upload_as += ctest_curl.Escape(*subproject);
  256. }
  257. }
  258. }
  259. // Generate Done.xml right before it is submitted.
  260. // The reason for this is two-fold:
  261. // 1) It must be generated after some other part has been submitted
  262. // so we have a buildId to refer to in its contents.
  263. // 2) By generating Done.xml here its timestamp will be as late as
  264. // possible. This gives us a more accurate record of how long the
  265. // entire build took to complete.
  266. if (file == "Done.xml") {
  267. this->CTest->GenerateDoneFile();
  268. }
  269. upload_as += "&MD5=";
  270. if (this->GetOption("InternalTest").IsOn()) {
  271. upload_as += "ffffffffffffffffffffffffffffffff";
  272. } else {
  273. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  274. upload_as += hasher.HashFile(local_file);
  275. }
  276. if (!cmSystemTools::FileExists(local_file)) {
  277. cmCTestLog(this->CTest, ERROR_MESSAGE,
  278. " Cannot find file: " << local_file << std::endl);
  279. ::curl_easy_cleanup(curl);
  280. ::curl_slist_free_all(headers);
  281. ::curl_global_cleanup();
  282. return false;
  283. }
  284. unsigned long filelen = cmSystemTools::FileLength(local_file);
  285. ftpfile = cmsys::SystemTools::Fopen(local_file, "rb");
  286. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  287. " Upload file: " << local_file << " to "
  288. << upload_as << " Size: "
  289. << filelen << std::endl,
  290. this->Quiet);
  291. // specify target
  292. ::curl_easy_setopt(curl, CURLOPT_URL, upload_as.c_str());
  293. // follow redirects
  294. ::curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1);
  295. // CURLAUTH_BASIC is default, and here we allow additional methods,
  296. // including more secure ones
  297. ::curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  298. // now specify which file to upload
  299. ::curl_easy_setopt(curl, CURLOPT_INFILE, ftpfile);
  300. // and give the size of the upload (optional)
  301. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(filelen));
  302. // and give curl the buffer for errors
  303. ::curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &error_buffer);
  304. // specify handler for output
  305. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  306. cmCTestSubmitHandlerWriteMemoryCallback);
  307. ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  308. cmCTestSubmitHandlerCurlDebugCallback);
  309. /* we pass our 'chunk' struct to the callback function */
  310. cmCTestSubmitHandlerVectorOfChar chunk;
  311. cmCTestSubmitHandlerVectorOfChar chunkDebug;
  312. ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk);
  313. ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  314. // Now run off and do what you've been told!
  315. ::curl_easy_perform(curl);
  316. if (!chunk.empty()) {
  317. cmCTestOptionalLog(this->CTest, DEBUG,
  318. "CURL output: ["
  319. << cmCTestLogWrite(chunk.data(), chunk.size())
  320. << "]" << std::endl,
  321. this->Quiet);
  322. this->ParseResponse(chunk);
  323. }
  324. if (!chunkDebug.empty()) {
  325. cmCTestOptionalLog(
  326. this->CTest, DEBUG,
  327. "CURL debug output: ["
  328. << cmCTestLogWrite(chunkDebug.data(), chunkDebug.size()) << "]"
  329. << std::endl,
  330. this->Quiet);
  331. }
  332. // If curl failed for any reason, or checksum fails, wait and retry
  333. //
  334. long response_code;
  335. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  336. bool successful_submission = response_code == 200;
  337. if (!successful_submission || this->HasErrors) {
  338. std::string retryDelay = *this->GetOption("RetryDelay");
  339. std::string retryCount = *this->GetOption("RetryCount");
  340. auto delay = cmDuration(
  341. retryDelay.empty()
  342. ? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryDelay")
  343. .c_str())
  344. : atoi(retryDelay.c_str()));
  345. int count = retryCount.empty()
  346. ? atoi(this->CTest->GetCTestConfiguration("CTestSubmitRetryCount")
  347. .c_str())
  348. : atoi(retryCount.c_str());
  349. for (int i = 0; i < count; i++) {
  350. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  351. " Submit failed, waiting " << delay.count()
  352. << " seconds...\n",
  353. this->Quiet);
  354. auto stop = std::chrono::steady_clock::now() + delay;
  355. while (std::chrono::steady_clock::now() < stop) {
  356. cmSystemTools::Delay(100);
  357. }
  358. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  359. " Retry submission: Attempt "
  360. << (i + 1) << " of " << count << std::endl,
  361. this->Quiet);
  362. ::fclose(ftpfile);
  363. ftpfile = cmsys::SystemTools::Fopen(local_file, "rb");
  364. ::curl_easy_setopt(curl, CURLOPT_INFILE, ftpfile);
  365. chunk.clear();
  366. chunkDebug.clear();
  367. this->HasErrors = false;
  368. ::curl_easy_perform(curl);
  369. if (!chunk.empty()) {
  370. cmCTestOptionalLog(this->CTest, DEBUG,
  371. "CURL output: ["
  372. << cmCTestLogWrite(chunk.data(), chunk.size())
  373. << "]" << std::endl,
  374. this->Quiet);
  375. this->ParseResponse(chunk);
  376. }
  377. curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
  378. if (response_code == 200 && !this->HasErrors) {
  379. successful_submission = true;
  380. break;
  381. }
  382. }
  383. }
  384. fclose(ftpfile);
  385. if (!successful_submission) {
  386. cmCTestLog(this->CTest, ERROR_MESSAGE,
  387. " Error when uploading file: " << local_file
  388. << std::endl);
  389. cmCTestLog(this->CTest, ERROR_MESSAGE,
  390. " Error message was: " << error_buffer << std::endl);
  391. *this->LogFile << " Error when uploading file: " << local_file
  392. << std::endl
  393. << " Error message was: " << error_buffer
  394. << std::endl;
  395. // avoid deref of begin for zero size array
  396. if (!chunk.empty()) {
  397. *this->LogFile << " Curl output was: "
  398. << cmCTestLogWrite(chunk.data(), chunk.size())
  399. << std::endl;
  400. cmCTestLog(this->CTest, ERROR_MESSAGE,
  401. "CURL output: ["
  402. << cmCTestLogWrite(chunk.data(), chunk.size()) << "]"
  403. << std::endl);
  404. }
  405. ::curl_easy_cleanup(curl);
  406. ::curl_slist_free_all(headers);
  407. ::curl_global_cleanup();
  408. return false;
  409. }
  410. // always cleanup
  411. ::curl_easy_cleanup(curl);
  412. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  413. " Uploaded: " + local_file << std::endl,
  414. this->Quiet);
  415. }
  416. }
  417. ::curl_slist_free_all(headers);
  418. ::curl_global_cleanup();
  419. return true;
  420. }
  421. void cmCTestSubmitHandler::ParseResponse(
  422. cmCTestSubmitHandlerVectorOfChar chunk)
  423. {
  424. std::string output;
  425. output.append(chunk.begin(), chunk.end());
  426. if (output.find("<cdash") != std::string::npos) {
  427. ResponseParser parser;
  428. parser.Parse(output.c_str());
  429. if (parser.Status != ResponseParser::STATUS_OK) {
  430. this->HasErrors = true;
  431. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  432. " Submission failed: " << parser.Message << std::endl);
  433. return;
  434. }
  435. this->CTest->SetBuildID(parser.BuildID);
  436. }
  437. output = cmSystemTools::UpperCase(output);
  438. if (output.find("WARNING") != std::string::npos) {
  439. this->HasWarnings = true;
  440. }
  441. if (output.find("ERROR") != std::string::npos) {
  442. this->HasErrors = true;
  443. }
  444. if (this->HasWarnings || this->HasErrors) {
  445. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  446. " Server Response:\n"
  447. << cmCTestLogWrite(chunk.data(), chunk.size()) << "\n");
  448. }
  449. }
  450. int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
  451. std::string const& typeString)
  452. {
  453. if (file.empty()) {
  454. cmCTestLog(this->CTest, ERROR_MESSAGE, "Upload file not specified\n");
  455. return -1;
  456. }
  457. if (!cmSystemTools::FileExists(file)) {
  458. cmCTestLog(this->CTest, ERROR_MESSAGE,
  459. "Upload file not found: '" << file << "'\n");
  460. return -1;
  461. }
  462. cmCTestCurl curl(this->CTest);
  463. curl.SetQuiet(this->Quiet);
  464. auto submitInactivityTimeout = this->GetSubmitInactivityTimeout();
  465. if (submitInactivityTimeout != 0) {
  466. curl.SetTimeOutSeconds(submitInactivityTimeout);
  467. }
  468. curl.SetHttpHeaders(this->HttpHeaders);
  469. std::string url = this->CTest->GetSubmitURL();
  470. if (!cmHasLiteralPrefix(url, "http://") &&
  471. !cmHasLiteralPrefix(url, "https://")) {
  472. cmCTestLog(this->CTest, ERROR_MESSAGE,
  473. "Only http and https are supported for CDASH_UPLOAD\n");
  474. return -1;
  475. }
  476. std::string fields;
  477. std::string::size_type pos = url.find('?');
  478. if (pos != std::string::npos) {
  479. fields = url.substr(pos + 1);
  480. url.erase(pos);
  481. }
  482. bool internalTest = this->GetOption("InternalTest").IsOn();
  483. // Get RETRY_COUNT and RETRY_DELAY values if they were set.
  484. std::string retryDelayString = *this->GetOption("RetryDelay");
  485. std::string retryCountString = *this->GetOption("RetryCount");
  486. auto retryDelay = std::chrono::seconds(0);
  487. if (!retryDelayString.empty()) {
  488. unsigned long retryDelayValue = 0;
  489. if (!cmStrToULong(retryDelayString, &retryDelayValue)) {
  490. cmCTestLog(this->CTest, WARNING,
  491. "Invalid value for 'RETRY_DELAY' : " << retryDelayString
  492. << std::endl);
  493. } else {
  494. retryDelay = std::chrono::seconds(retryDelayValue);
  495. }
  496. }
  497. unsigned long retryCount = 0;
  498. if (!retryCountString.empty()) {
  499. if (!cmStrToULong(retryCountString, &retryCount)) {
  500. cmCTestLog(this->CTest, WARNING,
  501. "Invalid value for 'RETRY_DELAY' : " << retryCountString
  502. << std::endl);
  503. }
  504. }
  505. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  506. std::string md5sum = hasher.HashFile(file);
  507. // 1. request the buildid and check to see if the file
  508. // has already been uploaded
  509. // TODO I added support for subproject. You would need to add
  510. // a "&subproject=subprojectname" to the first POST.
  511. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  512. cmake* cm = ch->GetCMake();
  513. cmValue subproject = cm->GetState()->GetGlobalProperty("SubProject");
  514. // TODO: Encode values for a URL instead of trusting caller.
  515. std::ostringstream str;
  516. if (subproject) {
  517. str << "subproject=" << curl.Escape(*subproject) << "&";
  518. }
  519. auto timeNow =
  520. std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  521. str << "stamp=" << curl.Escape(this->CTest->GetCurrentTag()) << "-"
  522. << curl.Escape(this->CTest->GetTestModelString()) << "&"
  523. << "model=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  524. << "build="
  525. << curl.Escape(this->CTest->GetCTestConfiguration("BuildName")) << "&"
  526. << "site=" << curl.Escape(this->CTest->GetCTestConfiguration("Site"))
  527. << "&"
  528. << "group=" << curl.Escape(this->CTest->GetTestModelString())
  529. << "&"
  530. // For now, we send both "track" and "group" to CDash in case we're
  531. // submitting to an older instance that still expects the prior
  532. // terminology.
  533. << "track=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  534. << "starttime=" << timeNow << "&"
  535. << "endtime=" << timeNow << "&"
  536. << "datafilesmd5[0]=" << md5sum << "&"
  537. << "type=" << curl.Escape(typeString);
  538. if (!fields.empty()) {
  539. fields += '&';
  540. }
  541. fields += str.str();
  542. cmCTestOptionalLog(this->CTest, DEBUG,
  543. "fields: " << fields << "\nurl:" << url
  544. << "\nfile: " << file << "\n",
  545. this->Quiet);
  546. std::string response;
  547. bool requestSucceeded = curl.HttpRequest(url, fields, response);
  548. if (!internalTest && !requestSucceeded) {
  549. // If request failed, wait and retry.
  550. for (unsigned long i = 0; i < retryCount; i++) {
  551. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  552. " Request failed, waiting " << retryDelay.count()
  553. << " seconds...\n",
  554. this->Quiet);
  555. auto stop = std::chrono::steady_clock::now() + retryDelay;
  556. while (std::chrono::steady_clock::now() < stop) {
  557. cmSystemTools::Delay(100);
  558. }
  559. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  560. " Retry request: Attempt "
  561. << (i + 1) << " of " << retryCount << std::endl,
  562. this->Quiet);
  563. requestSucceeded = curl.HttpRequest(url, fields, response);
  564. if (requestSucceeded) {
  565. break;
  566. }
  567. }
  568. }
  569. if (!internalTest && !requestSucceeded) {
  570. cmCTestLog(this->CTest, ERROR_MESSAGE,
  571. "Error in HttpRequest\n"
  572. << response);
  573. return -1;
  574. }
  575. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  576. "Request upload response: [" << response << "]\n",
  577. this->Quiet);
  578. Json::Value json;
  579. Json::Reader reader;
  580. if (!internalTest && !reader.parse(response, json)) {
  581. cmCTestLog(this->CTest, ERROR_MESSAGE,
  582. "error parsing json string ["
  583. << response << "]\n"
  584. << reader.getFormattedErrorMessages() << "\n");
  585. return -1;
  586. }
  587. if (!internalTest && json["status"].asInt() != 0) {
  588. cmCTestLog(this->CTest, ERROR_MESSAGE,
  589. "Bad status returned from CDash: " << json["status"].asInt());
  590. return -1;
  591. }
  592. if (!internalTest) {
  593. if (json["datafilesmd5"].isArray()) {
  594. int datares = json["datafilesmd5"][0].asInt();
  595. if (datares == 1) {
  596. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  597. "File already exists on CDash, skip upload "
  598. << file << "\n",
  599. this->Quiet);
  600. return 0;
  601. }
  602. } else {
  603. cmCTestLog(this->CTest, ERROR_MESSAGE,
  604. "bad datafilesmd5 value in response " << response << "\n");
  605. return -1;
  606. }
  607. }
  608. std::string upload_as = cmSystemTools::GetFilenameName(file);
  609. std::ostringstream fstr;
  610. fstr << "type=" << curl.Escape(typeString) << "&"
  611. << "md5=" << md5sum << "&"
  612. << "filename=" << curl.Escape(upload_as) << "&"
  613. << "buildid=" << json["buildid"].asString();
  614. bool uploadSucceeded = false;
  615. if (!internalTest) {
  616. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  617. }
  618. if (!uploadSucceeded) {
  619. // If upload failed, wait and retry.
  620. for (unsigned long i = 0; i < retryCount; i++) {
  621. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  622. " Upload failed, waiting " << retryDelay.count()
  623. << " seconds...\n",
  624. this->Quiet);
  625. auto stop = std::chrono::steady_clock::now() + retryDelay;
  626. while (std::chrono::steady_clock::now() < stop) {
  627. cmSystemTools::Delay(100);
  628. }
  629. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  630. " Retry upload: Attempt "
  631. << (i + 1) << " of " << retryCount << std::endl,
  632. this->Quiet);
  633. if (!internalTest) {
  634. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  635. }
  636. if (uploadSucceeded) {
  637. break;
  638. }
  639. }
  640. }
  641. if (!uploadSucceeded) {
  642. cmCTestLog(this->CTest, ERROR_MESSAGE,
  643. "error uploading to CDash. " << file << " " << url << " "
  644. << fstr.str());
  645. return -1;
  646. }
  647. if (!reader.parse(response, json)) {
  648. cmCTestLog(this->CTest, ERROR_MESSAGE,
  649. "error parsing json string ["
  650. << response << "]\n"
  651. << reader.getFormattedErrorMessages() << "\n");
  652. return -1;
  653. }
  654. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  655. "Upload file response: [" << response << "]\n",
  656. this->Quiet);
  657. return 0;
  658. }
  659. int cmCTestSubmitHandler::ProcessHandler()
  660. {
  661. cmValue cdashUploadFile = this->GetOption("CDashUploadFile");
  662. cmValue cdashUploadType = this->GetOption("CDashUploadType");
  663. if (cdashUploadFile && cdashUploadType) {
  664. return this->HandleCDashUploadFile(*cdashUploadFile, *cdashUploadType);
  665. }
  666. const std::string& buildDirectory =
  667. this->CTest->GetCTestConfiguration("BuildDirectory");
  668. if (buildDirectory.empty()) {
  669. cmCTestLog(this->CTest, ERROR_MESSAGE,
  670. "Cannot find BuildDirectory key in the DartConfiguration.tcl"
  671. << std::endl);
  672. return -1;
  673. }
  674. if (char const* proxy = getenv("HTTP_PROXY")) {
  675. this->HTTPProxyType = 1;
  676. this->HTTPProxy = proxy;
  677. if (getenv("HTTP_PROXY_PORT")) {
  678. this->HTTPProxy += ":";
  679. this->HTTPProxy += getenv("HTTP_PROXY_PORT");
  680. }
  681. if (char const* proxy_type = getenv("HTTP_PROXY_TYPE")) {
  682. std::string type = proxy_type;
  683. // HTTP/SOCKS4/SOCKS5
  684. if (type == "HTTP") {
  685. this->HTTPProxyType = 1;
  686. } else if (type == "SOCKS4") {
  687. this->HTTPProxyType = 2;
  688. } else if (type == "SOCKS5") {
  689. this->HTTPProxyType = 3;
  690. }
  691. }
  692. if (getenv("HTTP_PROXY_USER")) {
  693. this->HTTPProxyAuth = getenv("HTTP_PROXY_USER");
  694. }
  695. if (getenv("HTTP_PROXY_PASSWD")) {
  696. this->HTTPProxyAuth += ":";
  697. this->HTTPProxyAuth += getenv("HTTP_PROXY_PASSWD");
  698. }
  699. }
  700. if (!this->HTTPProxy.empty()) {
  701. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  702. " Use HTTP Proxy: " << this->HTTPProxy << std::endl,
  703. this->Quiet);
  704. }
  705. cmGeneratedFileStream ofs;
  706. this->StartLogFile("Submit", ofs);
  707. std::vector<std::string> files;
  708. std::string prefix = this->GetSubmitResultsPrefix();
  709. if (!this->Files.empty()) {
  710. // Submit the explicitly selected files:
  711. cm::append(files, this->Files);
  712. }
  713. // Add to the list of files to submit from any selected, existing parts:
  714. //
  715. // TODO:
  716. // Check if test is enabled
  717. this->CTest->AddIfExists(cmCTest::PartUpdate, "Update.xml");
  718. this->CTest->AddIfExists(cmCTest::PartConfigure, "Configure.xml");
  719. this->CTest->AddIfExists(cmCTest::PartBuild, "Build.xml");
  720. this->CTest->AddIfExists(cmCTest::PartTest, "Test.xml");
  721. if (this->CTest->AddIfExists(cmCTest::PartCoverage, "Coverage.xml")) {
  722. std::vector<std::string> gfiles;
  723. std::string gpath =
  724. buildDirectory + "/Testing/" + this->CTest->GetCurrentTag();
  725. std::string::size_type glen = gpath.size() + 1;
  726. gpath = gpath + "/CoverageLog*";
  727. cmCTestOptionalLog(this->CTest, DEBUG,
  728. "Globbing for: " << gpath << std::endl, this->Quiet);
  729. if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) {
  730. for (std::string& gfile : gfiles) {
  731. gfile = gfile.substr(glen);
  732. cmCTestOptionalLog(this->CTest, DEBUG,
  733. "Glob file: " << gfile << std::endl, this->Quiet);
  734. this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile);
  735. }
  736. } else {
  737. cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl);
  738. }
  739. }
  740. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis.xml");
  741. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis-Test.xml");
  742. this->CTest->AddIfExists(cmCTest::PartMemCheck, "Purify.xml");
  743. this->CTest->AddIfExists(cmCTest::PartNotes, "Notes.xml");
  744. this->CTest->AddIfExists(cmCTest::PartUpload, "Upload.xml");
  745. // Query parts for files to submit.
  746. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  747. p = static_cast<cmCTest::Part>(p + 1)) {
  748. // Skip parts we are not submitting.
  749. if (!this->SubmitPart[p]) {
  750. continue;
  751. }
  752. // Submit files from this part.
  753. cm::append(files, this->CTest->GetSubmitFiles(p));
  754. }
  755. // Make sure files are unique, but preserve order.
  756. {
  757. // This endPos intermediate is needed to work around non-conformant C++11
  758. // standard libraries that have erase(iterator,iterator) instead of
  759. // erase(const_iterator,const_iterator).
  760. size_t endPos = cmRemoveDuplicates(files) - files.cbegin();
  761. files.erase(files.begin() + endPos, files.end());
  762. }
  763. // Submit Done.xml last
  764. if (this->SubmitPart[cmCTest::PartDone]) {
  765. files.emplace_back("Done.xml");
  766. }
  767. if (ofs) {
  768. ofs << "Upload files:" << std::endl;
  769. int cnt = 0;
  770. for (std::string const& file : files) {
  771. ofs << cnt << "\t" << file << std::endl;
  772. cnt++;
  773. }
  774. }
  775. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "Submit files\n",
  776. this->Quiet);
  777. const char* specificGroup = this->CTest->GetSpecificGroup();
  778. if (specificGroup) {
  779. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  780. " Send to group: " << specificGroup << std::endl,
  781. this->Quiet);
  782. }
  783. this->SetLogFile(&ofs);
  784. std::string url = this->CTest->GetSubmitURL();
  785. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  786. " SubmitURL: " << url << '\n', this->Quiet);
  787. if (!this->SubmitUsingHTTP(buildDirectory + "/Testing/" +
  788. this->CTest->GetCurrentTag(),
  789. files, prefix, url)) {
  790. cmCTestLog(this->CTest, ERROR_MESSAGE,
  791. " Problems when submitting via HTTP\n");
  792. ofs << " Problems when submitting via HTTP\n";
  793. return -1;
  794. }
  795. if (this->HasErrors) {
  796. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  797. " Errors occurred during submission.\n");
  798. ofs << " Errors occurred during submission.\n";
  799. } else {
  800. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  801. " Submission successful"
  802. << (this->HasWarnings ? ", with warnings." : "")
  803. << std::endl,
  804. this->Quiet);
  805. ofs << " Submission successful"
  806. << (this->HasWarnings ? ", with warnings." : "") << std::endl;
  807. }
  808. return 0;
  809. }
  810. std::string cmCTestSubmitHandler::GetSubmitResultsPrefix()
  811. {
  812. std::string buildname =
  813. cmCTest::SafeBuildIdField(this->CTest->GetCTestConfiguration("BuildName"));
  814. std::string name = this->CTest->GetCTestConfiguration("Site") + "___" +
  815. buildname + "___" + this->CTest->GetCurrentTag() + "-" +
  816. this->CTest->GetTestModelString() + "___XML___";
  817. return name;
  818. }
  819. void cmCTestSubmitHandler::SelectParts(std::set<cmCTest::Part> const& parts)
  820. {
  821. // Check whether each part is selected.
  822. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  823. p = static_cast<cmCTest::Part>(p + 1)) {
  824. this->SubmitPart[p] = parts.find(p) != parts.end();
  825. }
  826. }
  827. int cmCTestSubmitHandler::GetSubmitInactivityTimeout()
  828. {
  829. int submitInactivityTimeout = SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT;
  830. std::string const& timeoutStr =
  831. this->CTest->GetCTestConfiguration("SubmitInactivityTimeout");
  832. if (!timeoutStr.empty()) {
  833. unsigned long timeout;
  834. if (cmStrToULong(timeoutStr, &timeout)) {
  835. submitInactivityTimeout = static_cast<int>(timeout);
  836. } else {
  837. cmCTestLog(this->CTest, ERROR_MESSAGE,
  838. "SubmitInactivityTimeout is invalid: "
  839. << cm::quoted(timeoutStr) << "."
  840. << " Using a default value of "
  841. << SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT << "." << std::endl);
  842. }
  843. }
  844. return submitInactivityTimeout;
  845. }
  846. void cmCTestSubmitHandler::SelectFiles(std::set<std::string> const& files)
  847. {
  848. this->Files.insert(files.begin(), files.end());
  849. }