cmCTestSubmitHandler.cxx 32 KB

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