cmCTestSubmitHandler.cxx 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919
  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 <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(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(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. this->HasWarnings = false;
  113. this->HasErrors = false;
  114. this->HTTPProxyType = 0;
  115. this->LogFile = nullptr;
  116. }
  117. bool cmCTestSubmitHandler::SubmitUsingHTTP(
  118. const std::string& localprefix, const std::vector<std::string>& files,
  119. const std::string& remoteprefix, const std::string& url)
  120. {
  121. CURL* curl;
  122. FILE* ftpfile;
  123. char error_buffer[1024];
  124. // Set Content-Type to satisfy fussy modsecurity rules.
  125. struct curl_slist* headers =
  126. ::curl_slist_append(nullptr, "Content-Type: text/xml");
  127. // Add any additional headers that the user specified.
  128. for (std::string const& h : this->HttpHeaders) {
  129. cmCTestOptionalLog(this->CTest, DEBUG,
  130. " Add HTTP Header: \"" << h << "\"" << std::endl,
  131. this->Quiet);
  132. headers = ::curl_slist_append(headers, h.c_str());
  133. }
  134. cmCurlInitOnce();
  135. /* In windows, this will init the winsock stuff */
  136. ::curl_global_init(CURL_GLOBAL_ALL);
  137. cmCTestCurlOpts curlOpts(this->CTest);
  138. for (std::string const& file : files) {
  139. /* get a curl handle */
  140. curl = cm_curl_easy_init();
  141. if (curl) {
  142. cmCurlSetCAInfo(curl);
  143. if (curlOpts.TLSVersionOpt.has_value()) {
  144. cm::optional<std::string> tlsVersionStr =
  145. cmCurlPrintTLSVersion(*curlOpts.TLSVersionOpt);
  146. cmCTestOptionalLog(
  147. this->CTest, HANDLER_VERBOSE_OUTPUT,
  148. " Set CURLOPT_SSLVERSION to "
  149. << (tlsVersionStr ? *tlsVersionStr : "unknown value") << "\n",
  150. this->Quiet);
  151. curl_easy_setopt(curl, CURLOPT_SSLVERSION, *curlOpts.TLSVersionOpt);
  152. }
  153. if (curlOpts.TLSVerifyOpt.has_value()) {
  154. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  155. " Set CURLOPT_SSL_VERIFYPEER to "
  156. << (*curlOpts.TLSVerifyOpt ? "on" : "off")
  157. << "\n",
  158. this->Quiet);
  159. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER,
  160. *curlOpts.TLSVerifyOpt ? 1 : 0);
  161. }
  162. if (curlOpts.VerifyHostOff) {
  163. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  164. " Set CURLOPT_SSL_VERIFYHOST to off\n",
  165. this->Quiet);
  166. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  167. }
  168. // Using proxy
  169. if (this->HTTPProxyType > 0) {
  170. curl_easy_setopt(curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
  171. switch (this->HTTPProxyType) {
  172. case 2:
  173. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  174. break;
  175. case 3:
  176. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  177. break;
  178. default:
  179. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  180. if (!this->HTTPProxyAuth.empty()) {
  181. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD,
  182. this->HTTPProxyAuth.c_str());
  183. }
  184. }
  185. }
  186. if (this->CTest->ShouldUseHTTP10()) {
  187. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  188. }
  189. /* enable uploading */
  190. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  191. // if there is little to no activity for too long stop submitting
  192. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  193. auto submitInactivityTimeout = this->GetSubmitInactivityTimeout();
  194. if (submitInactivityTimeout != 0) {
  195. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME,
  196. submitInactivityTimeout);
  197. }
  198. ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  199. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  200. std::string local_file = file;
  201. bool initialize_cdash_buildid = false;
  202. if (!cmSystemTools::FileExists(local_file)) {
  203. local_file = cmStrCat(localprefix, "/", file);
  204. // If this file exists within the local Testing directory we assume
  205. // that it will be associated with the current build in CDash.
  206. initialize_cdash_buildid = true;
  207. }
  208. std::string remote_file =
  209. remoteprefix + cmSystemTools::GetFilenameName(file);
  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. cmCTestSubmitHandlerVectorOfChar chunk;
  290. cmCTestSubmitHandlerVectorOfChar 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(
  401. cmCTestSubmitHandlerVectorOfChar chunk)
  402. {
  403. std::string output;
  404. output.append(chunk.begin(), chunk.end());
  405. if (output.find("<cdash") != std::string::npos) {
  406. ResponseParser parser;
  407. parser.Parse(output.c_str());
  408. if (parser.Status != ResponseParser::STATUS_OK) {
  409. this->HasErrors = true;
  410. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  411. " Submission failed: " << parser.Message << std::endl);
  412. return;
  413. }
  414. this->CTest->SetBuildID(parser.BuildID);
  415. }
  416. output = cmSystemTools::UpperCase(output);
  417. if (output.find("WARNING") != std::string::npos) {
  418. this->HasWarnings = true;
  419. }
  420. if (output.find("ERROR") != std::string::npos) {
  421. this->HasErrors = true;
  422. }
  423. if (this->HasWarnings || this->HasErrors) {
  424. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  425. " Server Response:\n"
  426. << cm::string_view(chunk.data(), chunk.size()) << "\n");
  427. }
  428. }
  429. int cmCTestSubmitHandler::HandleCDashUploadFile(std::string const& file,
  430. std::string const& typeString)
  431. {
  432. if (file.empty()) {
  433. cmCTestLog(this->CTest, ERROR_MESSAGE, "Upload file not specified\n");
  434. return -1;
  435. }
  436. if (!cmSystemTools::FileExists(file)) {
  437. cmCTestLog(this->CTest, ERROR_MESSAGE,
  438. "Upload file not found: '" << file << "'\n");
  439. return -1;
  440. }
  441. cmCTestCurl curl(this->CTest);
  442. curl.SetQuiet(this->Quiet);
  443. auto submitInactivityTimeout = this->GetSubmitInactivityTimeout();
  444. if (submitInactivityTimeout != 0) {
  445. curl.SetTimeOutSeconds(submitInactivityTimeout);
  446. }
  447. curl.SetHttpHeaders(this->HttpHeaders);
  448. std::string url = this->CTest->GetSubmitURL();
  449. if (!cmHasLiteralPrefix(url, "http://") &&
  450. !cmHasLiteralPrefix(url, "https://")) {
  451. cmCTestLog(this->CTest, ERROR_MESSAGE,
  452. "Only http and https are supported for CDASH_UPLOAD\n");
  453. return -1;
  454. }
  455. std::string fields;
  456. std::string::size_type pos = url.find('?');
  457. if (pos != std::string::npos) {
  458. fields = url.substr(pos + 1);
  459. url.erase(pos);
  460. }
  461. bool internalTest = this->InternalTest;
  462. // Get RETRY_COUNT and RETRY_DELAY values if they were set.
  463. std::string retryDelayString = this->RetryDelay;
  464. std::string retryCountString = this->RetryCount;
  465. auto retryDelay = std::chrono::seconds(0);
  466. if (!retryDelayString.empty()) {
  467. unsigned long retryDelayValue = 0;
  468. if (!cmStrToULong(retryDelayString, &retryDelayValue)) {
  469. cmCTestLog(this->CTest, WARNING,
  470. "Invalid value for 'RETRY_DELAY' : " << retryDelayString
  471. << std::endl);
  472. } else {
  473. retryDelay = std::chrono::seconds(retryDelayValue);
  474. }
  475. }
  476. unsigned long retryCount = 0;
  477. if (!retryCountString.empty()) {
  478. if (!cmStrToULong(retryCountString, &retryCount)) {
  479. cmCTestLog(this->CTest, WARNING,
  480. "Invalid value for 'RETRY_DELAY' : " << retryCountString
  481. << std::endl);
  482. }
  483. }
  484. cmCryptoHash hasher(cmCryptoHash::AlgoMD5);
  485. std::string md5sum = hasher.HashFile(file);
  486. // 1. request the buildid and check to see if the file
  487. // has already been uploaded
  488. // TODO I added support for subproject. You would need to add
  489. // a "&subproject=subprojectname" to the first POST.
  490. cmValue subproject =
  491. this->CMake->GetState()->GetGlobalProperty("SubProject");
  492. // TODO: Encode values for a URL instead of trusting caller.
  493. std::ostringstream str;
  494. if (subproject) {
  495. str << "subproject=" << curl.Escape(*subproject) << "&";
  496. }
  497. auto timeNow =
  498. std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  499. str << "stamp=" << curl.Escape(this->CTest->GetCurrentTag()) << "-"
  500. << curl.Escape(this->CTest->GetTestGroupString()) << "&"
  501. << "model=" << curl.Escape(this->CTest->GetTestGroupString()) << "&"
  502. << "build="
  503. << curl.Escape(this->CTest->GetCTestConfiguration("BuildName")) << "&"
  504. << "site=" << curl.Escape(this->CTest->GetCTestConfiguration("Site"))
  505. << "&"
  506. << "group=" << curl.Escape(this->CTest->GetTestGroupString())
  507. << "&"
  508. // For now, we send both "track" and "group" to CDash in case we're
  509. // submitting to an older instance that still expects the prior
  510. // terminology.
  511. << "track=" << curl.Escape(this->CTest->GetTestGroupString()) << "&"
  512. << "starttime=" << timeNow << "&"
  513. << "endtime=" << timeNow << "&"
  514. << "datafilesmd5[0]=" << md5sum << "&"
  515. << "type=" << curl.Escape(typeString);
  516. if (!fields.empty()) {
  517. fields += '&';
  518. }
  519. fields += str.str();
  520. cmCTestOptionalLog(this->CTest, DEBUG,
  521. "fields: " << fields << "\nurl:" << url
  522. << "\nfile: " << file << "\n",
  523. this->Quiet);
  524. std::string response;
  525. bool requestSucceeded = curl.HttpRequest(url, fields, response);
  526. if (!internalTest && !requestSucceeded) {
  527. // If request failed, wait and retry.
  528. for (unsigned long i = 0; i < retryCount; i++) {
  529. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  530. " Request failed, waiting " << retryDelay.count()
  531. << " seconds...\n",
  532. this->Quiet);
  533. auto stop = std::chrono::steady_clock::now() + retryDelay;
  534. while (std::chrono::steady_clock::now() < stop) {
  535. cmSystemTools::Delay(100);
  536. }
  537. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  538. " Retry request: Attempt "
  539. << (i + 1) << " of " << retryCount << std::endl,
  540. this->Quiet);
  541. requestSucceeded = curl.HttpRequest(url, fields, response);
  542. if (requestSucceeded) {
  543. break;
  544. }
  545. }
  546. }
  547. if (!internalTest && !requestSucceeded) {
  548. cmCTestLog(this->CTest, ERROR_MESSAGE,
  549. "Error in HttpRequest\n"
  550. << response);
  551. return -1;
  552. }
  553. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  554. "Request upload response: [" << response << "]\n",
  555. this->Quiet);
  556. Json::Value json;
  557. Json::Reader reader;
  558. if (!internalTest && !reader.parse(response, json)) {
  559. cmCTestLog(this->CTest, ERROR_MESSAGE,
  560. "error parsing json string ["
  561. << response << "]\n"
  562. << reader.getFormattedErrorMessages() << "\n");
  563. return -1;
  564. }
  565. if (!internalTest && json["status"].asInt() != 0) {
  566. cmCTestLog(this->CTest, ERROR_MESSAGE,
  567. "Bad status returned from CDash: " << json["status"].asInt());
  568. return -1;
  569. }
  570. if (!internalTest) {
  571. if (json["datafilesmd5"].isArray()) {
  572. int datares = json["datafilesmd5"][0].asInt();
  573. if (datares == 1) {
  574. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  575. "File already exists on CDash, skip upload "
  576. << file << "\n",
  577. this->Quiet);
  578. return 0;
  579. }
  580. } else {
  581. cmCTestLog(this->CTest, ERROR_MESSAGE,
  582. "bad datafilesmd5 value in response " << response << "\n");
  583. return -1;
  584. }
  585. }
  586. std::string upload_as = cmSystemTools::GetFilenameName(file);
  587. std::ostringstream fstr;
  588. fstr << "type=" << curl.Escape(typeString) << "&"
  589. << "md5=" << md5sum << "&"
  590. << "filename=" << curl.Escape(upload_as) << "&"
  591. << "buildid=" << json["buildid"].asString();
  592. bool uploadSucceeded = false;
  593. if (!internalTest) {
  594. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  595. }
  596. if (!uploadSucceeded) {
  597. // If upload failed, wait and retry.
  598. for (unsigned long i = 0; i < retryCount; i++) {
  599. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  600. " Upload failed, waiting " << retryDelay.count()
  601. << " seconds...\n",
  602. this->Quiet);
  603. auto stop = std::chrono::steady_clock::now() + retryDelay;
  604. while (std::chrono::steady_clock::now() < stop) {
  605. cmSystemTools::Delay(100);
  606. }
  607. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  608. " Retry upload: Attempt "
  609. << (i + 1) << " of " << retryCount << std::endl,
  610. this->Quiet);
  611. if (!internalTest) {
  612. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  613. }
  614. if (uploadSucceeded) {
  615. break;
  616. }
  617. }
  618. }
  619. if (!uploadSucceeded) {
  620. cmCTestLog(this->CTest, ERROR_MESSAGE,
  621. "error uploading to CDash. " << file << " " << url << " "
  622. << fstr.str());
  623. return -1;
  624. }
  625. if (!reader.parse(response, json)) {
  626. cmCTestLog(this->CTest, ERROR_MESSAGE,
  627. "error parsing json string ["
  628. << response << "]\n"
  629. << reader.getFormattedErrorMessages() << "\n");
  630. return -1;
  631. }
  632. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  633. "Upload file response: [" << response << "]\n",
  634. this->Quiet);
  635. return 0;
  636. }
  637. int cmCTestSubmitHandler::ProcessHandler()
  638. {
  639. if (this->CDashUpload) {
  640. return this->HandleCDashUploadFile(this->CDashUploadFile,
  641. this->CDashUploadType);
  642. }
  643. const std::string& buildDirectory =
  644. this->CTest->GetCTestConfiguration("BuildDirectory");
  645. if (buildDirectory.empty()) {
  646. cmCTestLog(this->CTest, ERROR_MESSAGE,
  647. "Cannot find BuildDirectory key in the DartConfiguration.tcl"
  648. << std::endl);
  649. return -1;
  650. }
  651. if (char const* proxy = getenv("HTTP_PROXY")) {
  652. this->HTTPProxyType = 1;
  653. this->HTTPProxy = proxy;
  654. if (getenv("HTTP_PROXY_PORT")) {
  655. this->HTTPProxy += ":";
  656. this->HTTPProxy += getenv("HTTP_PROXY_PORT");
  657. }
  658. if (char const* proxy_type = getenv("HTTP_PROXY_TYPE")) {
  659. std::string type = proxy_type;
  660. // HTTP/SOCKS4/SOCKS5
  661. if (type == "HTTP") {
  662. this->HTTPProxyType = 1;
  663. } else if (type == "SOCKS4") {
  664. this->HTTPProxyType = 2;
  665. } else if (type == "SOCKS5") {
  666. this->HTTPProxyType = 3;
  667. }
  668. }
  669. if (getenv("HTTP_PROXY_USER")) {
  670. this->HTTPProxyAuth = getenv("HTTP_PROXY_USER");
  671. }
  672. if (getenv("HTTP_PROXY_PASSWD")) {
  673. this->HTTPProxyAuth += ":";
  674. this->HTTPProxyAuth += getenv("HTTP_PROXY_PASSWD");
  675. }
  676. }
  677. if (!this->HTTPProxy.empty()) {
  678. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  679. " Use HTTP Proxy: " << this->HTTPProxy << std::endl,
  680. this->Quiet);
  681. }
  682. cmGeneratedFileStream ofs;
  683. this->StartLogFile("Submit", ofs);
  684. std::vector<std::string> files;
  685. std::string prefix = this->GetSubmitResultsPrefix();
  686. if (!this->Files.empty()) {
  687. // Submit the explicitly selected files:
  688. cm::append(files, this->Files);
  689. }
  690. // Add to the list of files to submit from any selected, existing parts:
  691. //
  692. // TODO:
  693. // Check if test is enabled
  694. this->CTest->AddIfExists(cmCTest::PartUpdate, "Update.xml");
  695. this->CTest->AddIfExists(cmCTest::PartConfigure, "Configure.xml");
  696. this->CTest->AddIfExists(cmCTest::PartBuild, "Build.xml");
  697. this->CTest->AddIfExists(cmCTest::PartTest, "Test.xml");
  698. if (this->CTest->AddIfExists(cmCTest::PartCoverage, "Coverage.xml")) {
  699. std::vector<std::string> gfiles;
  700. std::string gpath =
  701. buildDirectory + "/Testing/" + this->CTest->GetCurrentTag();
  702. std::string::size_type glen = gpath.size() + 1;
  703. gpath = gpath + "/CoverageLog*";
  704. cmCTestOptionalLog(this->CTest, DEBUG,
  705. "Globbing for: " << gpath << std::endl, this->Quiet);
  706. if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) {
  707. for (std::string& gfile : gfiles) {
  708. gfile = gfile.substr(glen);
  709. cmCTestOptionalLog(this->CTest, DEBUG,
  710. "Glob file: " << gfile << std::endl, this->Quiet);
  711. this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile);
  712. }
  713. } else {
  714. cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl);
  715. }
  716. }
  717. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis.xml");
  718. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis-Test.xml");
  719. this->CTest->AddIfExists(cmCTest::PartMemCheck, "Purify.xml");
  720. this->CTest->AddIfExists(cmCTest::PartNotes, "Notes.xml");
  721. this->CTest->AddIfExists(cmCTest::PartUpload, "Upload.xml");
  722. // Query parts for files to submit.
  723. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  724. p = static_cast<cmCTest::Part>(p + 1)) {
  725. // Skip parts we are not submitting.
  726. if (!this->SubmitPart[p]) {
  727. continue;
  728. }
  729. // Submit files from this part.
  730. cm::append(files, this->CTest->GetSubmitFiles(p));
  731. }
  732. // Make sure files are unique, but preserve order.
  733. {
  734. // This endPos intermediate is needed to work around non-conformant C++11
  735. // standard libraries that have erase(iterator,iterator) instead of
  736. // erase(const_iterator,const_iterator).
  737. size_t endPos = cmRemoveDuplicates(files) - files.cbegin();
  738. files.erase(files.begin() + endPos, files.end());
  739. }
  740. // Submit Done.xml last
  741. if (this->SubmitPart[cmCTest::PartDone]) {
  742. files.emplace_back("Done.xml");
  743. }
  744. if (ofs) {
  745. ofs << "Upload files:" << std::endl;
  746. int cnt = 0;
  747. for (std::string const& file : files) {
  748. ofs << cnt << "\t" << file << std::endl;
  749. cnt++;
  750. }
  751. }
  752. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "Submit files\n",
  753. this->Quiet);
  754. const char* specificGroup = this->CTest->GetSpecificGroup();
  755. if (specificGroup) {
  756. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  757. " Send to group: " << specificGroup << std::endl,
  758. this->Quiet);
  759. }
  760. this->SetLogFile(&ofs);
  761. std::string url = this->CTest->GetSubmitURL();
  762. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  763. " SubmitURL: " << url << '\n', this->Quiet);
  764. if (!this->SubmitUsingHTTP(buildDirectory + "/Testing/" +
  765. this->CTest->GetCurrentTag(),
  766. files, prefix, url)) {
  767. cmCTestLog(this->CTest, ERROR_MESSAGE,
  768. " Problems when submitting via HTTP\n");
  769. ofs << " Problems when submitting via HTTP\n";
  770. return -1;
  771. }
  772. if (this->HasErrors) {
  773. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  774. " Errors occurred during submission.\n");
  775. ofs << " Errors occurred during submission.\n";
  776. } else {
  777. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  778. " Submission successful"
  779. << (this->HasWarnings ? ", with warnings." : "")
  780. << std::endl,
  781. this->Quiet);
  782. ofs << " Submission successful"
  783. << (this->HasWarnings ? ", with warnings." : "") << std::endl;
  784. }
  785. return 0;
  786. }
  787. std::string cmCTestSubmitHandler::GetSubmitResultsPrefix()
  788. {
  789. std::string buildname =
  790. cmCTest::SafeBuildIdField(this->CTest->GetCTestConfiguration("BuildName"));
  791. std::string name = this->CTest->GetCTestConfiguration("Site") + "___" +
  792. buildname + "___" + this->CTest->GetCurrentTag() + "-" +
  793. this->CTest->GetTestGroupString() + "___XML___";
  794. return name;
  795. }
  796. void cmCTestSubmitHandler::SelectParts(std::set<cmCTest::Part> const& parts)
  797. {
  798. // Check whether each part is selected.
  799. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  800. p = static_cast<cmCTest::Part>(p + 1)) {
  801. this->SubmitPart[p] = parts.find(p) != parts.end();
  802. }
  803. }
  804. int cmCTestSubmitHandler::GetSubmitInactivityTimeout()
  805. {
  806. int submitInactivityTimeout = SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT;
  807. std::string const& timeoutStr =
  808. this->CTest->GetCTestConfiguration("SubmitInactivityTimeout");
  809. if (!timeoutStr.empty()) {
  810. unsigned long timeout;
  811. if (cmStrToULong(timeoutStr, &timeout)) {
  812. submitInactivityTimeout = static_cast<int>(timeout);
  813. } else {
  814. cmCTestLog(this->CTest, ERROR_MESSAGE,
  815. "SubmitInactivityTimeout is invalid: "
  816. << cm::quoted(timeoutStr) << "."
  817. << " Using a default value of "
  818. << SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT << "." << std::endl);
  819. }
  820. }
  821. return submitInactivityTimeout;
  822. }
  823. void cmCTestSubmitHandler::SelectFiles(std::set<std::string> const& files)
  824. {
  825. this->Files.insert(files.begin(), files.end());
  826. }