cmCTestSubmitHandler.cxx 34 KB

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