cmCTestSubmitHandler.cxx 32 KB

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