cmCTestSubmitHandler.cxx 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899
  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. enum StatusType
  29. {
  30. STATUS_OK,
  31. STATUS_WARNING,
  32. STATUS_ERROR
  33. };
  34. StatusType Status = STATUS_OK;
  35. std::string Filename;
  36. std::string MD5;
  37. std::string Message;
  38. std::string BuildID;
  39. private:
  40. std::vector<char> CurrentValue;
  41. std::string GetCurrentValue()
  42. {
  43. std::string val;
  44. if (!this->CurrentValue.empty()) {
  45. val.assign(&this->CurrentValue[0], this->CurrentValue.size());
  46. }
  47. return val;
  48. }
  49. void StartElement(const std::string& /*name*/,
  50. const char** /*atts*/) override
  51. {
  52. this->CurrentValue.clear();
  53. }
  54. void CharacterDataHandler(const char* data, int length) override
  55. {
  56. cmAppend(this->CurrentValue, data, data + length);
  57. }
  58. void EndElement(const std::string& name) override
  59. {
  60. if (name == "status") {
  61. std::string status = cmSystemTools::UpperCase(this->GetCurrentValue());
  62. if (status == "OK" || status == "SUCCESS") {
  63. this->Status = STATUS_OK;
  64. } else if (status == "WARNING") {
  65. this->Status = STATUS_WARNING;
  66. } else {
  67. this->Status = STATUS_ERROR;
  68. }
  69. } else if (name == "filename") {
  70. this->Filename = this->GetCurrentValue();
  71. } else if (name == "md5") {
  72. this->MD5 = this->GetCurrentValue();
  73. } else if (name == "message") {
  74. this->Message = this->GetCurrentValue();
  75. } else if (name == "buildId") {
  76. this->BuildID = this->GetCurrentValue();
  77. }
  78. }
  79. };
  80. static size_t cmCTestSubmitHandlerWriteMemoryCallback(void* ptr, size_t size,
  81. size_t nmemb, void* data)
  82. {
  83. int realsize = static_cast<int>(size * nmemb);
  84. const char* chPtr = static_cast<char*>(ptr);
  85. cmAppend(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  86. chPtr + realsize);
  87. return realsize;
  88. }
  89. static size_t cmCTestSubmitHandlerCurlDebugCallback(CURL* /*unused*/,
  90. curl_infotype /*unused*/,
  91. char* chPtr, size_t size,
  92. void* data)
  93. {
  94. cmAppend(*static_cast<cmCTestSubmitHandlerVectorOfChar*>(data), chPtr,
  95. chPtr + size);
  96. return size;
  97. }
  98. cmCTestSubmitHandler::cmCTestSubmitHandler()
  99. {
  100. this->Initialize();
  101. }
  102. void cmCTestSubmitHandler::Initialize()
  103. {
  104. // We submit all available parts by default.
  105. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  106. p = cmCTest::Part(p + 1)) {
  107. this->SubmitPart[p] = true;
  108. }
  109. this->HasWarnings = false;
  110. this->HasErrors = false;
  111. this->Superclass::Initialize();
  112. this->HTTPProxy.clear();
  113. this->HTTPProxyType = 0;
  114. this->HTTPProxyAuth.clear();
  115. this->LogFile = nullptr;
  116. this->Files.clear();
  117. }
  118. bool cmCTestSubmitHandler::SubmitUsingHTTP(
  119. const std::string& localprefix, const std::vector<std::string>& files,
  120. const std::string& remoteprefix, const std::string& url)
  121. {
  122. CURL* curl;
  123. CURLcode res;
  124. FILE* ftpfile;
  125. char error_buffer[1024];
  126. // Set Content-Type to satisfy fussy modsecurity rules.
  127. struct curl_slist* headers =
  128. ::curl_slist_append(nullptr, "Content-Type: text/xml");
  129. // Add any additional headers that the user specified.
  130. for (std::string const& h : this->HttpHeaders) {
  131. cmCTestOptionalLog(this->CTest, DEBUG,
  132. " Add HTTP Header: \"" << h << "\"" << std::endl,
  133. this->Quiet);
  134. headers = ::curl_slist_append(headers, h.c_str());
  135. }
  136. /* In windows, this will init the winsock stuff */
  137. ::curl_global_init(CURL_GLOBAL_ALL);
  138. std::string curlopt(this->CTest->GetCTestConfiguration("CurlOptions"));
  139. std::vector<std::string> args;
  140. cmSystemTools::ExpandListArgument(curlopt, args);
  141. bool verifyPeerOff = false;
  142. bool verifyHostOff = false;
  143. for (std::string const& arg : args) {
  144. if (arg == "CURLOPT_SSL_VERIFYPEER_OFF") {
  145. verifyPeerOff = true;
  146. }
  147. if (arg == "CURLOPT_SSL_VERIFYHOST_OFF") {
  148. verifyHostOff = true;
  149. }
  150. }
  151. for (std::string const& file : files) {
  152. /* get a curl handle */
  153. curl = curl_easy_init();
  154. if (curl) {
  155. cmCurlSetCAInfo(curl);
  156. if (verifyPeerOff) {
  157. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  158. " Set CURLOPT_SSL_VERIFYPEER to off\n",
  159. this->Quiet);
  160. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0);
  161. }
  162. if (verifyHostOff) {
  163. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  164. " Set CURLOPT_SSL_VERIFYHOST to off\n",
  165. this->Quiet);
  166. curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0);
  167. }
  168. // Using proxy
  169. if (this->HTTPProxyType > 0) {
  170. curl_easy_setopt(curl, CURLOPT_PROXY, this->HTTPProxy.c_str());
  171. switch (this->HTTPProxyType) {
  172. case 2:
  173. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS4);
  174. break;
  175. case 3:
  176. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  177. break;
  178. default:
  179. curl_easy_setopt(curl, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
  180. if (!this->HTTPProxyAuth.empty()) {
  181. curl_easy_setopt(curl, CURLOPT_PROXYUSERPWD,
  182. this->HTTPProxyAuth.c_str());
  183. }
  184. }
  185. }
  186. if (this->CTest->ShouldUseHTTP10()) {
  187. curl_easy_setopt(curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
  188. }
  189. // enable HTTP ERROR parsing
  190. curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);
  191. /* enable uploading */
  192. curl_easy_setopt(curl, CURLOPT_UPLOAD, 1);
  193. // if there is little to no activity for too long stop submitting
  194. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_LIMIT, 1);
  195. ::curl_easy_setopt(curl, CURLOPT_LOW_SPEED_TIME,
  196. SUBMIT_TIMEOUT_IN_SECONDS_DEFAULT);
  197. /* HTTP PUT please */
  198. ::curl_easy_setopt(curl, CURLOPT_PUT, 1);
  199. ::curl_easy_setopt(curl, CURLOPT_VERBOSE, 1);
  200. ::curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
  201. std::string local_file = file;
  202. bool initialize_cdash_buildid = false;
  203. if (!cmSystemTools::FileExists(local_file)) {
  204. local_file = localprefix + "/" + file;
  205. // If this file exists within the local Testing directory we assume
  206. // that it will be associated with the current build in CDash.
  207. initialize_cdash_buildid = true;
  208. }
  209. std::string remote_file =
  210. remoteprefix + cmSystemTools::GetFilenameName(file);
  211. *this->LogFile << "\tUpload file: " << local_file << " to "
  212. << remote_file << std::endl;
  213. std::string ofile = cmSystemTools::EncodeURL(remote_file);
  214. std::string upload_as = url +
  215. ((url.find('?') == std::string::npos) ? '?' : '&') +
  216. "FileName=" + ofile;
  217. if (initialize_cdash_buildid) {
  218. // Provide extra arguments to CDash so that it can initialize and
  219. // return a buildid.
  220. cmCTestCurl ctest_curl(this->CTest);
  221. upload_as += "&build=";
  222. upload_as +=
  223. ctest_curl.Escape(this->CTest->GetCTestConfiguration("BuildName"));
  224. upload_as += "&site=";
  225. upload_as +=
  226. ctest_curl.Escape(this->CTest->GetCTestConfiguration("Site"));
  227. upload_as += "&stamp=";
  228. upload_as += ctest_curl.Escape(this->CTest->GetCurrentTag());
  229. upload_as += "-";
  230. upload_as += ctest_curl.Escape(this->CTest->GetTestModelString());
  231. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  232. cmake* cm = ch->GetCMake();
  233. if (cm) {
  234. const char* subproject =
  235. 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 (cmSystemTools::IsOn(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;
  446. cmSystemTools::ExpandListArgument(curlopt, args);
  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. std::string fields;
  452. std::string::size_type pos = url.find('?');
  453. if (pos != std::string::npos) {
  454. fields = url.substr(pos + 1);
  455. url = url.substr(0, pos);
  456. }
  457. if (!cmHasLiteralPrefix(url, "http://") &&
  458. !cmHasLiteralPrefix(url, "https://")) {
  459. cmCTestLog(this->CTest, ERROR_MESSAGE,
  460. "Only http and https are supported for CDASH_UPLOAD\n");
  461. return -1;
  462. }
  463. bool internalTest = cmSystemTools::IsOn(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 (!cmSystemTools::StringToULong(retryDelayString.c_str(),
  475. &retryDelayValue)) {
  476. cmCTestLog(this->CTest, WARNING,
  477. "Invalid value for 'RETRY_DELAY' : " << retryDelayString
  478. << std::endl);
  479. } else {
  480. retryDelay = std::chrono::seconds(retryDelayValue);
  481. }
  482. }
  483. unsigned long retryCount = 0;
  484. if (!retryCountString.empty()) {
  485. if (!cmSystemTools::StringToULong(retryCountString.c_str(), &retryCount)) {
  486. cmCTestLog(this->CTest, WARNING,
  487. "Invalid value for 'RETRY_DELAY' : " << retryCountString
  488. << std::endl);
  489. }
  490. }
  491. std::string md5sum =
  492. cmSystemTools::ComputeFileHash(file, cmCryptoHash::AlgoMD5);
  493. // 1. request the buildid and check to see if the file
  494. // has already been uploaded
  495. // TODO I added support for subproject. You would need to add
  496. // a "&subproject=subprojectname" to the first POST.
  497. cmCTestScriptHandler* ch = this->CTest->GetScriptHandler();
  498. cmake* cm = ch->GetCMake();
  499. const char* subproject = cm->GetState()->GetGlobalProperty("SubProject");
  500. // TODO: Encode values for a URL instead of trusting caller.
  501. std::ostringstream str;
  502. if (subproject) {
  503. str << "subproject=" << curl.Escape(subproject) << "&";
  504. }
  505. auto timeNow =
  506. std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
  507. str << "stamp=" << curl.Escape(this->CTest->GetCurrentTag()) << "-"
  508. << curl.Escape(this->CTest->GetTestModelString()) << "&"
  509. << "model=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  510. << "build="
  511. << curl.Escape(this->CTest->GetCTestConfiguration("BuildName")) << "&"
  512. << "site=" << curl.Escape(this->CTest->GetCTestConfiguration("Site"))
  513. << "&"
  514. << "track=" << curl.Escape(this->CTest->GetTestModelString()) << "&"
  515. << "starttime=" << timeNow << "&"
  516. << "endtime=" << timeNow << "&"
  517. << "datafilesmd5[0]=" << md5sum << "&"
  518. << "type=" << curl.Escape(typeString);
  519. if (!fields.empty()) {
  520. fields += '&';
  521. }
  522. fields += str.str();
  523. cmCTestOptionalLog(this->CTest, DEBUG,
  524. "fields: " << fields << "\nurl:" << url
  525. << "\nfile: " << file << "\n",
  526. this->Quiet);
  527. std::string response;
  528. bool requestSucceeded = curl.HttpRequest(url, fields, response);
  529. if (!internalTest && !requestSucceeded) {
  530. // If request failed, wait and retry.
  531. for (unsigned long i = 0; i < retryCount; i++) {
  532. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  533. " Request failed, waiting " << retryDelay.count()
  534. << " seconds...\n",
  535. this->Quiet);
  536. auto stop = std::chrono::steady_clock::now() + retryDelay;
  537. while (std::chrono::steady_clock::now() < stop) {
  538. cmSystemTools::Delay(100);
  539. }
  540. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  541. " Retry request: Attempt "
  542. << (i + 1) << " of " << retryCount << std::endl,
  543. this->Quiet);
  544. requestSucceeded = curl.HttpRequest(url, fields, response);
  545. if (requestSucceeded) {
  546. break;
  547. }
  548. }
  549. }
  550. if (!internalTest && !requestSucceeded) {
  551. cmCTestLog(this->CTest, ERROR_MESSAGE,
  552. "Error in HttpRequest\n"
  553. << response);
  554. return -1;
  555. }
  556. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  557. "Request upload response: [" << response << "]\n",
  558. this->Quiet);
  559. Json::Value json;
  560. Json::Reader reader;
  561. if (!internalTest && !reader.parse(response, json)) {
  562. cmCTestLog(this->CTest, ERROR_MESSAGE,
  563. "error parsing json string ["
  564. << response << "]\n"
  565. << reader.getFormattedErrorMessages() << "\n");
  566. return -1;
  567. }
  568. if (!internalTest && json["status"].asInt() != 0) {
  569. cmCTestLog(this->CTest, ERROR_MESSAGE,
  570. "Bad status returned from CDash: " << json["status"].asInt());
  571. return -1;
  572. }
  573. if (!internalTest) {
  574. if (json["datafilesmd5"].isArray()) {
  575. int datares = json["datafilesmd5"][0].asInt();
  576. if (datares == 1) {
  577. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  578. "File already exists on CDash, skip upload "
  579. << file << "\n",
  580. this->Quiet);
  581. return 0;
  582. }
  583. } else {
  584. cmCTestLog(this->CTest, ERROR_MESSAGE,
  585. "bad datafilesmd5 value in response " << response << "\n");
  586. return -1;
  587. }
  588. }
  589. std::string upload_as = cmSystemTools::GetFilenameName(file);
  590. std::ostringstream fstr;
  591. fstr << "type=" << curl.Escape(typeString) << "&"
  592. << "md5=" << md5sum << "&"
  593. << "filename=" << curl.Escape(upload_as) << "&"
  594. << "buildid=" << json["buildid"].asString();
  595. bool uploadSucceeded = false;
  596. if (!internalTest) {
  597. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  598. }
  599. if (!uploadSucceeded) {
  600. // If upload failed, wait and retry.
  601. for (unsigned long i = 0; i < retryCount; i++) {
  602. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  603. " Upload failed, waiting " << retryDelay.count()
  604. << " seconds...\n",
  605. this->Quiet);
  606. auto stop = std::chrono::steady_clock::now() + retryDelay;
  607. while (std::chrono::steady_clock::now() < stop) {
  608. cmSystemTools::Delay(100);
  609. }
  610. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  611. " Retry upload: Attempt "
  612. << (i + 1) << " of " << retryCount << std::endl,
  613. this->Quiet);
  614. if (!internalTest) {
  615. uploadSucceeded = curl.UploadFile(file, url, fstr.str(), response);
  616. }
  617. if (uploadSucceeded) {
  618. break;
  619. }
  620. }
  621. }
  622. if (!uploadSucceeded) {
  623. cmCTestLog(this->CTest, ERROR_MESSAGE,
  624. "error uploading to CDash. " << file << " " << url << " "
  625. << fstr.str());
  626. return -1;
  627. }
  628. if (!reader.parse(response, json)) {
  629. cmCTestLog(this->CTest, ERROR_MESSAGE,
  630. "error parsing json string ["
  631. << response << "]\n"
  632. << reader.getFormattedErrorMessages() << "\n");
  633. return -1;
  634. }
  635. cmCTestOptionalLog(this->CTest, HANDLER_VERBOSE_OUTPUT,
  636. "Upload file response: [" << response << "]\n",
  637. this->Quiet);
  638. return 0;
  639. }
  640. int cmCTestSubmitHandler::ProcessHandler()
  641. {
  642. const char* cdashUploadFile = this->GetOption("CDashUploadFile");
  643. const char* cdashUploadType = this->GetOption("CDashUploadType");
  644. if (cdashUploadFile && cdashUploadType) {
  645. return this->HandleCDashUploadFile(cdashUploadFile, cdashUploadType);
  646. }
  647. const std::string& buildDirectory =
  648. this->CTest->GetCTestConfiguration("BuildDirectory");
  649. if (buildDirectory.empty()) {
  650. cmCTestLog(this->CTest, ERROR_MESSAGE,
  651. "Cannot find BuildDirectory key in the DartConfiguration.tcl"
  652. << std::endl);
  653. return -1;
  654. }
  655. if (getenv("HTTP_PROXY")) {
  656. this->HTTPProxyType = 1;
  657. this->HTTPProxy = getenv("HTTP_PROXY");
  658. if (getenv("HTTP_PROXY_PORT")) {
  659. this->HTTPProxy += ":";
  660. this->HTTPProxy += getenv("HTTP_PROXY_PORT");
  661. }
  662. if (getenv("HTTP_PROXY_TYPE")) {
  663. std::string type = getenv("HTTP_PROXY_TYPE");
  664. // HTTP/SOCKS4/SOCKS5
  665. if (type == "HTTP") {
  666. this->HTTPProxyType = 1;
  667. } else if (type == "SOCKS4") {
  668. this->HTTPProxyType = 2;
  669. } else if (type == "SOCKS5") {
  670. this->HTTPProxyType = 3;
  671. }
  672. }
  673. if (getenv("HTTP_PROXY_USER")) {
  674. this->HTTPProxyAuth = getenv("HTTP_PROXY_USER");
  675. }
  676. if (getenv("HTTP_PROXY_PASSWD")) {
  677. this->HTTPProxyAuth += ":";
  678. this->HTTPProxyAuth += getenv("HTTP_PROXY_PASSWD");
  679. }
  680. }
  681. if (!this->HTTPProxy.empty()) {
  682. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  683. " Use HTTP Proxy: " << this->HTTPProxy << std::endl,
  684. this->Quiet);
  685. }
  686. cmGeneratedFileStream ofs;
  687. this->StartLogFile("Submit", ofs);
  688. std::vector<std::string> files;
  689. std::string prefix = this->GetSubmitResultsPrefix();
  690. if (!this->Files.empty()) {
  691. // Submit the explicitly selected files:
  692. cmAppend(files, this->Files);
  693. }
  694. // Add to the list of files to submit from any selected, existing parts:
  695. //
  696. // TODO:
  697. // Check if test is enabled
  698. this->CTest->AddIfExists(cmCTest::PartUpdate, "Update.xml");
  699. this->CTest->AddIfExists(cmCTest::PartConfigure, "Configure.xml");
  700. this->CTest->AddIfExists(cmCTest::PartBuild, "Build.xml");
  701. this->CTest->AddIfExists(cmCTest::PartTest, "Test.xml");
  702. if (this->CTest->AddIfExists(cmCTest::PartCoverage, "Coverage.xml")) {
  703. std::vector<std::string> gfiles;
  704. std::string gpath =
  705. buildDirectory + "/Testing/" + this->CTest->GetCurrentTag();
  706. std::string::size_type glen = gpath.size() + 1;
  707. gpath = gpath + "/CoverageLog*";
  708. cmCTestOptionalLog(this->CTest, DEBUG,
  709. "Globbing for: " << gpath << std::endl, this->Quiet);
  710. if (cmSystemTools::SimpleGlob(gpath, gfiles, 1)) {
  711. for (std::string& gfile : gfiles) {
  712. gfile = gfile.substr(glen);
  713. cmCTestOptionalLog(this->CTest, DEBUG,
  714. "Glob file: " << gfile << std::endl, this->Quiet);
  715. this->CTest->AddSubmitFile(cmCTest::PartCoverage, gfile.c_str());
  716. }
  717. } else {
  718. cmCTestLog(this->CTest, ERROR_MESSAGE, "Problem globbing" << std::endl);
  719. }
  720. }
  721. this->CTest->AddIfExists(cmCTest::PartMemCheck, "DynamicAnalysis.xml");
  722. this->CTest->AddIfExists(cmCTest::PartMemCheck, "Purify.xml");
  723. this->CTest->AddIfExists(cmCTest::PartNotes, "Notes.xml");
  724. this->CTest->AddIfExists(cmCTest::PartUpload, "Upload.xml");
  725. // Query parts for files to submit.
  726. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  727. p = cmCTest::Part(p + 1)) {
  728. // Skip parts we are not submitting.
  729. if (!this->SubmitPart[p]) {
  730. continue;
  731. }
  732. // Submit files from this part.
  733. cmAppend(files, this->CTest->GetSubmitFiles(p));
  734. }
  735. // Make sure files are unique, but preserve order.
  736. {
  737. // This endPos intermediate is needed to work around non-conformant C++11
  738. // standard libraries that have erase(iterator,iterator) instead of
  739. // erase(const_iterator,const_iterator).
  740. size_t endPos = cmRemoveDuplicates(files) - files.cbegin();
  741. files.erase(files.begin() + endPos, files.end());
  742. }
  743. // Submit Done.xml last
  744. if (this->SubmitPart[cmCTest::PartDone]) {
  745. files.emplace_back("Done.xml");
  746. }
  747. if (ofs) {
  748. ofs << "Upload files:" << std::endl;
  749. int cnt = 0;
  750. for (std::string const& file : files) {
  751. ofs << cnt << "\t" << file << std::endl;
  752. cnt++;
  753. }
  754. }
  755. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT, "Submit files\n",
  756. this->Quiet);
  757. const char* specificTrack = this->CTest->GetSpecificTrack();
  758. if (specificTrack) {
  759. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  760. " Send to track: " << specificTrack << std::endl,
  761. this->Quiet);
  762. }
  763. this->SetLogFile(&ofs);
  764. std::string url = this->CTest->GetSubmitURL();
  765. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  766. " SubmitURL: " << url << '\n', this->Quiet);
  767. if (!this->SubmitUsingHTTP(buildDirectory + "/Testing/" +
  768. this->CTest->GetCurrentTag(),
  769. files, prefix, url)) {
  770. cmCTestLog(this->CTest, ERROR_MESSAGE,
  771. " Problems when submitting via HTTP\n");
  772. ofs << " Problems when submitting via HTTP\n";
  773. return -1;
  774. }
  775. if (this->HasErrors) {
  776. cmCTestLog(this->CTest, HANDLER_OUTPUT,
  777. " Errors occurred during submission.\n");
  778. ofs << " Errors occurred during submission.\n";
  779. } else {
  780. cmCTestOptionalLog(this->CTest, HANDLER_OUTPUT,
  781. " Submission successful"
  782. << (this->HasWarnings ? ", with warnings." : "")
  783. << std::endl,
  784. this->Quiet);
  785. ofs << " Submission successful"
  786. << (this->HasWarnings ? ", with warnings." : "") << std::endl;
  787. }
  788. return 0;
  789. }
  790. std::string cmCTestSubmitHandler::GetSubmitResultsPrefix()
  791. {
  792. std::string buildname =
  793. cmCTest::SafeBuildIdField(this->CTest->GetCTestConfiguration("BuildName"));
  794. std::string name = this->CTest->GetCTestConfiguration("Site") + "___" +
  795. buildname + "___" + this->CTest->GetCurrentTag() + "-" +
  796. this->CTest->GetTestModelString() + "___XML___";
  797. return name;
  798. }
  799. void cmCTestSubmitHandler::SelectParts(std::set<cmCTest::Part> const& parts)
  800. {
  801. // Check whether each part is selected.
  802. for (cmCTest::Part p = cmCTest::PartStart; p != cmCTest::PartCount;
  803. p = cmCTest::Part(p + 1)) {
  804. this->SubmitPart[p] =
  805. (std::set<cmCTest::Part>::const_iterator(parts.find(p)) != parts.end());
  806. }
  807. }
  808. void cmCTestSubmitHandler::SelectFiles(std::set<std::string> const& files)
  809. {
  810. this->Files.insert(files.begin(), files.end());
  811. }