cmCTestSubmitHandler.cxx 32 KB

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