cmCTestSubmitHandler.cxx 31 KB

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