cmCTestSubmitHandler.cxx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904
  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 <cmext/algorithm>
  9. #include "cm_curl.h"
  10. #include "cm_jsoncpp_reader.h"
  11. #include "cm_jsoncpp_value.h"
  12. #include "cmAlgorithms.h"
  13. #include "cmCTest.h"
  14. #include "cmCTestCurl.h"
  15. #include "cmCTestScriptHandler.h"
  16. #include "cmCryptoHash.h"
  17. #include "cmCurl.h"
  18. #include "cmDuration.h"
  19. #include "cmGeneratedFileStream.h"
  20. #include "cmState.h"
  21. #include "cmStringAlgorithms.h"
  22. #include "cmSystemTools.h"
  23. #include "cmXMLParser.h"
  24. #include "cmake.h"
  25. #define SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT 120
  26. using cmCTestSubmitHandlerVectorOfChar = std::vector<char>;
  27. class cmCTestSubmitHandler::ResponseParser : public cmXMLParser
  28. {
  29. public:
  30. enum StatusType
  31. {
  32. STATUS_OK,
  33. STATUS_WARNING,
  34. STATUS_ERROR
  35. };
  36. StatusType Status = STATUS_OK;
  37. std::string Filename;
  38. std::string MD5;
  39. std::string Message;
  40. std::string BuildID;
  41. private:
  42. std::vector<char> CurrentValue;
  43. std::string GetCurrentValue()
  44. {
  45. std::string val;
  46. if (!this->CurrentValue.empty()) {
  47. val.assign(&this->CurrentValue[0], this->CurrentValue.size());
  48. }
  49. return val;
  50. }
  51. void StartElement(const std::string& /*name*/,
  52. const char** /*atts*/) override
  53. {
  54. this->CurrentValue.clear();
  55. }
  56. void CharacterDataHandler(const char* data, int length) override
  57. {
  58. cm::append(this->CurrentValue, data, data + length);
  59. }
  60. void EndElement(const std::string& name) override
  61. {
  62. if (name == "status") {
  63. std::string status = cmSystemTools::UpperCase(this->GetCurrentValue());
  64. if (status == "OK" || status == "SUCCESS") {
  65. this->Status = STATUS_OK;
  66. } else if (status == "WARNING") {
  67. this->Status = STATUS_WARNING;
  68. } else {
  69. this->Status = STATUS_ERROR;
  70. }
  71. } else if (name == "filename") {
  72. this->Filename = this->GetCurrentValue();
  73. } else if (name == "md5") {
  74. this->MD5 = this->GetCurrentValue();
  75. } else if (name == "message") {
  76. this->Message = this->GetCurrentValue();
  77. } else if (name == "buildId") {
  78. this->BuildID = this->GetCurrentValue();
  79. }
  80. }
  81. };
  82. static size_t cmCTestSubmitHandlerWriteMemoryCallback(void* ptr, size_t size,
  83. size_t nmemb, void* data)
  84. {
  85. int realsize = static_cast<int>(size * nmemb);
  86. const char* chPtr = static_cast<char*>(ptr);
  87. cm::append(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  88. chPtr + realsize);
  89. return realsize;
  90. }
  91. static size_t cmCTestSubmitHandlerCurlDebugCallback(CURL* /*unused*/,
  92. curl_infotype /*unused*/,
  93. char* chPtr, size_t size,
  94. void* data)
  95. {
  96. cm::append(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  97. chPtr + size);
  98. return 0;
  99. }
  100. cmCTestSubmitHandler::cmCTestSubmitHandler()
  101. {
  102. this->Initialize();
  103. }
  104. void cmCTestSubmitHandler::Initialize()
  105. {
  106. // We submit all available parts by default.
  107. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  108. p = cmCTest::Part(p + 1)) {
  109. this->SubmitPart[p] = true;
  110. }
  111. this->HasWarnings = false;
  112. this->HasErrors = false;
  113. this->Superclass::Initialize();
  114. this->HTTPProxy.clear();
  115. this->HTTPProxyType = 0;
  116. this->HTTPProxyAuth.clear();
  117. this->LogFile = nullptr;
  118. this->Files.clear();
  119. }
  120. bool cmCTestSubmitHandler::SubmitUsingHTTP(
  121. const std::string& localprefix, const std::vector<std::string>& files,
  122. const std::string& remoteprefix, const std::string& url)
  123. {
  124. CURL* curl;
  125. CURLcode res;
  126. FILE* ftpfile;
  127. char error_buffer[1024];
  128. // Set Content-Type to satisfy fussy modsecurity rules.
  129. struct curl_slist* headers =
  130. ::curl_slist_append(nullptr, "Content-Type: text/xml");
  131. // Add any additional headers that the user specified.
  132. for (std::string const& h : this->HttpHeaders) {
  133. cmCTestOptionalLog(this->CTest, DEBUG,
  134. " Add HTTP Header: \"" << h << "\"" << std::endl,
  135. this->Quiet);
  136. headers = ::curl_slist_append(headers, h.c_str());
  137. }
  138. /* In windows, this will init the winsock stuff */
  139. ::curl_global_init(CURL_GLOBAL_ALL);
  140. std::string curlopt(this->CTest->GetCTestConfiguration("CurlOptions"));
  141. std::vector<std::string> args = cmExpandedList(curlopt);
  142. bool verifyPeerOff = false;
  143. bool verifyHostOff = false;
  144. for (std::string const& arg : args) {
  145. if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") {
  146. verifyPeerOff = true;
  147. }
  148. if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") {
  149. verifyHostOff = true;
  150. }
  151. }
  152. for (std::string const& file : files) {
  153. /* get a curl handle */
  154. curl = curl_easy_init();
  155. if (curl) {
  156. cmCurlSetCAInfo(curl);
  157. if (verifyPeerOff) {
  158. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  159. " Set CURLOPT_SSL_VERIFYPEER to off\n",
  160. this->Quiet);
  161. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  162. }
  163. if (verifyHostOff) {
  164. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  165. " Set CURLOPT_SSL_VERIFYHOST to off\n",
  166. this->Quiet);
  167. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  168. }
  169. // Using proxy
  170. if (this->HTTPProxyType > 0) {
  171. curl_easy_setopt(curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
  172. switch (this->HTTPProxyType) {
  173. case 2:
  174. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  175. break;
  176. case 3:
  177. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  178. break;
  179. default:
  180. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  181. if (!this->HTTPProxyAuth.empty()) {
  182. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD,
  183. this->HTTPProxyAuth.c_str());
  184. }
  185. }
  186. }
  187. if (this->CTest->ShouldUseHTTP10()) {
  188. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  189. }
  190. // enable HTTP ERROR parsing
  191. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  192. /* enable uploading */
  193. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  194. // if there is little to no activity for too long stop submitting
  195. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  196. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME,
  197. SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT);
  198. /* HTTP PUT please */
  199. ::curl_easy_setopt(curl, CURLOPT_PUT, 1);
  200. ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  201. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  202. std::string local_file = file;
  203. bool initialize_cdash_buildid = false;
  204. if (!cmSystemTools::FileExists(local_file)) {
  205. local_file = cmStrCat(localprefix, "/", file);
  206. // If this file exists within the local Testing directory we assume
  207. // that it will be associated with the current build in CDash.
  208. initialize_cdash_buildid = true;
  209. }
  210. std::string remote_file =
  211. remoteprefix + cmSystemTools::GetFilenameName(file);
  212. *this->LogFile << "\tUpload file: " << local_file << " to "
  213. << remote_file << std::endl;
  214. std::string ofile = cmSystemTools::EncodeURL(remote_file);
  215. std::string upload_as =
  216. cmStrCat(url, ((url.find('?') == std::string::npos) ? '?' : '&'),
  217. "FileName=", ofile);
  218. if (initialize_cdash_buildid) {
  219. // Provide extra arguments to CDash so that it can initialize and
  220. // return a buildid.
  221. cmCTestCurl ctest_curl(this->CTest);
  222. upload_as += "&build=";
  223. upload_as +=
  224. ctest_curl.Escape(this->CTest->GetCTestConfiguration("BuildName"));
  225. upload_as += "&site=";
  226. upload_as +=
  227. ctest_curl.Escape(this->CTest->GetCTestConfiguration("Site"));
  228. upload_as += "&stamp=";
  229. upload_as += ctest_curl.Escape(this->CTest->GetCurrentTag());
  230. upload_as += "-";
  231. upload_as += ctest_curl.Escape(this->CTest->GetTestModelString());
  232. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  233. cmake* cm = ch->GetCMake();
  234. if (cm) {
  235. cmProp subproject = cm->GetState()->GetGlobalProperty("SubProject");
  236. if (subproject) {
  237. upload_as += "&subproject=";
  238. upload_as += ctest_curl.Escape(*subproject);
  239. }
  240. }
  241. }
  242. // Generate Done.xml right before it is submitted.
  243. // The reason for this is two-fold:
  244. // 1) It must be generated after some other part has been submitted
  245. // so we have a buildId to refer to in its contents.
  246. // 2) By generating Done.xml here its timestamp will be as late as
  247. // possible. This gives us a more accurate record of how long the
  248. // entire build took to complete.
  249. if (file == "Done.xml") {
  250. this->CTest->GenerateDoneFile();
  251. }
  252. upload_as += "&MD5=";
  253. if (cmIsOn(this->GetOption("InternalTest"))) {
  254. upload_as += "bad_md5sum";
  255. } else {
  256. upload_as +=
  257. cmSystemTools::ComputeFileHash(local_file, cmCryptoHash::AlgoMD5);
  258. }
  259. if (!cmSystemTools::FileExists(local_file)) {
  260. cmCTestLog(this->CTest, ERROR_MESSAGE,
  261. " Cannot find file: " << local_file << std::endl);
  262. ::curl_easy_cleanup(curl);
  263. ::curl_slist_free_all(headers);
  264. ::curl_global_cleanup();
  265. return false;
  266. }
  267. unsigned long filelen = cmSystemTools::FileLength(local_file);
  268. ftpfile = cmsys::SystemTools::Fopen(local_file, "rb");
  269. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  270. " Upload file: " << local_file << " to "
  271. << upload_as << " Size: "
  272. << filelen << std::endl,
  273. this->Quiet);
  274. // specify target
  275. ::curl_easy_setopt(curl, CURLOPT_URL, upload_as.c_str());
  276. // CURLAUTH_BASIC is default, and here we allow additional methods,
  277. // including more secure ones
  278. ::curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
  279. // now specify which file to upload
  280. ::curl_easy_setopt(curl, CURLOPT_INFILE, ftpfile);
  281. // and give the size of the upload (optional)
  282. ::curl_easy_setopt(curl, CURLOPT_INFILESIZE, static_cast<long>(filelen));
  283. // and give curl the buffer for errors
  284. ::curl_easy_setopt(curl, CURLOPT_ERRORBUFFER, &error_buffer);
  285. // specify handler for output
  286. ::curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION,
  287. cmCTestSubmitHandlerWriteMemoryCallback);
  288. ::curl_easy_setopt(curl, CURLOPT_DEBUGFUNCTION,
  289. cmCTestSubmitHandlerCurlDebugCallback);
  290. /* we pass our 'chunk' struct to the callback function */
  291. cmCTestSubmitHandlerVectorOfChar chunk;
  292. cmCTestSubmitHandlerVectorOfChar chunkDebug;
  293. ::curl_easy_setopt(curl, CURLOPT_FILE, &chunk);
  294. ::curl_easy_setopt(curl, CURLOPT_DEBUGDATA, &chunkDebug);
  295. // Now run off and do what you've been told!
  296. res = ::curl_easy_perform(curl);
  297. if (!chunk.empty()) {
  298. cmCTestOptionalLog(this->CTest, DEBUG,
  299. "CURL output: ["
  300. << cmCTestLogWrite(chunk.data(), chunk.size())
  301. << "]" << std::endl,
  302. this->Quiet);
  303. this->ParseResponse(chunk);
  304. }
  305. if (!chunkDebug.empty()) {
  306. cmCTestOptionalLog(
  307. this->CTest, DEBUG,
  308. "CURL debug output: ["
  309. << cmCTestLogWrite(chunkDebug.data(), chunkDebug.size()) << "]"
  310. << std::endl,
  311. this->Quiet);
  312. }
  313. // If curl failed for any reason, or checksum fails, wait and retry
  314. //
  315. if (res != CURLE_OK || this->HasErrors) {
  316. std::string retryDelay = this->GetOption("RetryDelay") == nullptr
  317. ? ""
  318. : this->GetOption("RetryDelay");
  319. std::string retryCount = this->GetOption("RetryCount") == nullptr
  320. ? ""
  321. : 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. std::vector<std::string> args = cmExpandedList(curlopt);
  446. curl.SetCurlOptions(args);
  447. curl.SetTimeOutSeconds(SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT);
  448. curl.SetHttpHeaders(this->HttpHeaders);
  449. std::string url = this->CTest->GetSubmitURL();
  450. std::string fields;
  451. std::string::size_type pos = url.find('?');
  452. if (pos != std::string::npos) {
  453. fields = url.substr(pos + 1);
  454. url = url.substr(0, pos);
  455. }
  456. if (!cmHasLiteralPrefix(url, "http://") &&
  457. !cmHasLiteralPrefix(url, "https://")) {
  458. cmCTestLog(this->CTest, ERROR_MESSAGE,
  459. "Only http and https are supported for CDASH_UPLOAD\n");
  460. return -1;
  461. }
  462. bool internalTest = cmIsOn(this->GetOption("InternalTest"));
  463. // Get RETRY_COUNT and RETRY_DELAY values if they were set.
  464. std::string retryDelayString = this->GetOption("RetryDelay") == nullptr
  465. ? ""
  466. : this->GetOption("RetryDelay");
  467. std::string retryCountString = this->GetOption("RetryCount") == nullptr
  468. ? ""
  469. : this->GetOption("RetryCount");
  470. auto retryDelay = std::chrono::seconds(0);
  471. if (!retryDelayString.empty()) {
  472. unsigned long retryDelayValue = 0;
  473. if (!cmStrToULong(retryDelayString, &retryDelayValue)) {
  474. cmCTestLog(this->CTest, WARNING,
  475. "Invalid value for 'RETRY_DELAY' : " << retryDelayString
  476. << std::endl);
  477. } else {
  478. retryDelay = std::chrono::seconds(retryDelayValue);
  479. }
  480. }
  481. unsigned long retryCount = 0;
  482. if (!retryCountString.empty()) {
  483. if (!cmStrToULong(retryCountString, &retryCount)) {
  484. cmCTestLog(this->CTest, WARNING,
  485. "Invalid value for 'RETRY_DELAY' : " << retryCountString
  486. << std::endl);
  487. }
  488. }
  489. std::string md5sum =
  490. cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5);
  491. // 1. request the buildid and check to see if the file
  492. // has already been uploaded
  493. // TODO I added support for subproject. You would need to add
  494. // a "&subproject=subprojectname" to the first POST.
  495. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  496. cmake* cm = ch->GetCMake();
  497. cmProp subproject = cm->GetState()->GetGlobalProperty("SubProject");
  498. // TODO: Encode values for a URL instead of trusting caller.
  499. std::ostringstream str;
  500. if (subproject) {
  501. str << "subproject=" << curl.Escape(*subproject) << "&";
  502. }
  503. auto timeNow =
  504. std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  505. str << "stamp=" << curl.Escape(this->CTest->GetCurrentTag()) << "-"
  506. << curl.Escape(this->CTest->GetTestModelString()) << "&"
  507. << "model=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  508. << "build="
  509. << curl.Escape(this->CTest->GetCTestConfiguration("BuildName")) << "&"
  510. << "site=" << curl.Escape(this->CTest->GetCTestConfiguration("Site"))
  511. << "&"
  512. << "group=" << curl.Escape(this->CTest->GetTestModelString())
  513. << "&"
  514. // For now, we send both "track" and "group" to CDash in case we're
  515. // submitting to an older instance that still expects the prior
  516. // terminology.
  517. << "track=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  518. << "starttime=" << timeNow << "&"
  519. << "endtime=" << timeNow << "&"
  520. << "datafilesmd5[0]=" << md5sum << "&"
  521. << "type=" << curl.Escape(typeString);
  522. if (!fields.empty()) {
  523. fields += '&';
  524. }
  525. fields += str.str();
  526. cmCTestOptionalLog(this->CTest, DEBUG,
  527. "fields: " << fields << "\nurl:" << url
  528. << "\nfile: " << file << "\n",
  529. this->Quiet);
  530. std::string response;
  531. bool requestSucceeded = curl.HttpRequest(url, fields, response);
  532. if (!internalTest && !requestSucceeded) {
  533. // If request failed, wait and retry.
  534. for (unsigned long i = 0; i < retryCount; i++) {
  535. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  536. " Request failed, waiting " << retryDelay.count()
  537. << " seconds...\n",
  538. this->Quiet);
  539. auto stop = std::chrono::steady_clock::now() + retryDelay;
  540. while (std::chrono::steady_clock::now() < stop) {
  541. cmSystemTools::Delay(100);
  542. }
  543. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  544. " Retry request: Attempt "
  545. << (i + 1) << " of " << retryCount << std::endl,
  546. this->Quiet);
  547. requestSucceeded = curl.HttpRequest(url, fields, response);
  548. if (requestSucceeded) {
  549. break;
  550. }
  551. }
  552. }
  553. if (!internalTest && !requestSucceeded) {
  554. cmCTestLog(this->CTest, ERROR_MESSAGE,
  555. "Error in HttpRequest\n"
  556. << response);
  557. return -1;
  558. }
  559. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  560. "Request upload response: [" << response << "]\n",
  561. this->Quiet);
  562. Json::Value json;
  563. Json::Reader reader;
  564. if (!internalTest && !reader.parse(response, json)) {
  565. cmCTestLog(this->CTest, ERROR_MESSAGE,
  566. "error parsing json string ["
  567. << response << "]\n"
  568. << reader.getFormattedErrorMessages() << "\n");
  569. return -1;
  570. }
  571. if (!internalTest && json["status"].asInt() != 0) {
  572. cmCTestLog(this->CTest, ERROR_MESSAGE,
  573. "Bad status returned from CDash: " << json["status"].asInt());
  574. return -1;
  575. }
  576. if (!internalTest) {
  577. if (json["datafilesmd5"].isArray()) {
  578. int datares = json["datafilesmd5"][0].asInt();
  579. if (datares == 1) {
  580. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  581. "File already exists on CDash, skip upload "
  582. << file << "\n",
  583. this->Quiet);
  584. return 0;
  585. }
  586. } else {
  587. cmCTestLog(this->CTest, ERROR_MESSAGE,
  588. "bad datafilesmd5 value in response " << response << "\n");
  589. return -1;
  590. }
  591. }
  592. std::string upload_as = cmSystemTools::GetFilenameName(file);
  593. std::ostringstream fstr;
  594. fstr << "type=" << curl.Escape(typeString) << "&"
  595. << "md5=" << md5sum << "&"
  596. << "filename=" << curl.Escape(upload_as) << "&"
  597. << "buildid=" << json["buildid"].asString();
  598. bool uploadSucceeded = false;
  599. if (!internalTest) {
  600. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  601. }
  602. if (!uploadSucceeded) {
  603. // If upload failed, wait and retry.
  604. for (unsigned long i = 0; i < retryCount; i++) {
  605. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  606. " Upload failed, waiting " << retryDelay.count()
  607. << " seconds...\n",
  608. this->Quiet);
  609. auto stop = std::chrono::steady_clock::now() + retryDelay;
  610. while (std::chrono::steady_clock::now() < stop) {
  611. cmSystemTools::Delay(100);
  612. }
  613. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  614. " Retry upload: Attempt "
  615. << (i + 1) << " of " << retryCount << std::endl,
  616. this->Quiet);
  617. if (!internalTest) {
  618. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  619. }
  620. if (uploadSucceeded) {
  621. break;
  622. }
  623. }
  624. }
  625. if (!uploadSucceeded) {
  626. cmCTestLog(this->CTest, ERROR_MESSAGE,
  627. "error uploading to CDash. " << file << " " << url << " "
  628. << fstr.str());
  629. return -1;
  630. }
  631. if (!reader.parse(response, json)) {
  632. cmCTestLog(this->CTest, ERROR_MESSAGE,
  633. "error parsing json string ["
  634. << response << "]\n"
  635. << reader.getFormattedErrorMessages() << "\n");
  636. return -1;
  637. }
  638. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  639. "Upload file response: [" << response << "]\n",
  640. this->Quiet);
  641. return 0;
  642. }
  643. int cmCTestSubmitHandler::ProcessHandler()
  644. {
  645. const char* cdashUploadFile = this->GetOption("CDashUploadFile");
  646. const char* cdashUploadType = this->GetOption("CDashUploadType");
  647. if (cdashUploadFile && cdashUploadType) {
  648. return this->HandleCDashUploadFile(cdashUploadFile, cdashUploadType);
  649. }
  650. const std::string& buildDirectory =
  651. this->CTest->GetCTestConfiguration("BuildDirectory");
  652. if (buildDirectory.empty()) {
  653. cmCTestLog(this->CTest, ERROR_MESSAGE,
  654. "Cannot find BuildDirectory key in the DartConfiguration.tcl"
  655. << std::endl);
  656. return -1;
  657. }
  658. if (getenv("HTTP_PROXY")) {
  659. this->HTTPProxyType = 1;
  660. this->HTTPProxy = getenv("HTTP_PROXY");
  661. if (getenv("HTTP_PROXY_PORT")) {
  662. this->HTTPProxy += ":";
  663. this->HTTPProxy += getenv("HTTP_PROXY_PORT");
  664. }
  665. if (getenv("HTTP_PROXY_TYPE")) {
  666. std::string type = getenv("HTTP_PROXY_TYPE");
  667. // HTTP/SOCKS4/SOCKS5
  668. if (type == "HTTP") {
  669. this->HTTPProxyType = 1;
  670. } else if (type == "SOCKS4") {
  671. this->HTTPProxyType = 2;
  672. } else if (type == "SOCKS5") {
  673. this->HTTPProxyType = 3;
  674. }
  675. }
  676. if (getenv("HTTP_PROXY_USER")) {
  677. this->HTTPProxyAuth = getenv("HTTP_PROXY_USER");
  678. }
  679. if (getenv("HTTP_PROXY_PASSWD")) {
  680. this->HTTPProxyAuth += ":";
  681. this->HTTPProxyAuth += getenv("HTTP_PROXY_PASSWD");
  682. }
  683. }
  684. if (!this->HTTPProxy.empty()) {
  685. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  686. " Use HTTP Proxy: " << this->HTTPProxy << std::endl,
  687. this->Quiet);
  688. }
  689. cmGeneratedFileStream ofs;
  690. this->StartLogFile("Submit", ofs);
  691. std::vector<std::string> files;
  692. std::string prefix = this->GetSubmitResultsPrefix();
  693. if (!this->Files.empty()) {
  694. // Submit the explicitly selected files:
  695. cm::append(files, this->Files);
  696. }
  697. // Add to the list of files to submit from any selected, existing parts:
  698. //
  699. // TODO:
  700. // Check if test is enabled
  701. this->CTest->AddIfExists(cmCTest::PartUpdate, "Update.xml");
  702. this->CTest->AddIfExists(cmCTest::PartConfigure, "Configure.xml");
  703. this->CTest->AddIfExists(cmCTest::PartBuild, "Build.xml");
  704. this->CTest->AddIfExists(cmCTest::PartTest, "Test.xml");
  705. if (this->CTest->AddIfExists(cmCTest::PartCoverage, "Coverage.xml")) {
  706. std::vector<std::string> gfiles;
  707. std::string gpath =
  708. buildDirectory + "/Testing/" + this->CTest->GetCurrentTag();
  709. std::string::size_type glen = gpath.size() + 1;
  710. gpath = gpath + "/CoverageLog*";
  711. cmCTestOptionalLog(this->CTest, DEBUG,
  712. "Globbing for: " << gpath << std::endl, this->Quiet);
  713. if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) {
  714. for (std::string& gfile : gfiles) {
  715. gfile = gfile.substr(glen);
  716. cmCTestOptionalLog(this->CTest, DEBUG,
  717. "Glob file: " << gfile << std::endl, this->Quiet);
  718. this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile.c_str());
  719. }
  720. } else {
  721. cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl);
  722. }
  723. }
  724. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis.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 = 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 = cmCTest::Part(p + 1)) {
  807. this->SubmitPart[p] =
  808. (std::set<cmCTest::Part>::const_iterator(parts.find(p)) != parts.end());
  809. }
  810. }
  811. void cmCTestSubmitHandler::SelectFiles(std::set<std::string> const& files)
  812. {
  813. this->Files.insert(files.begin(), files.end());
  814. }