cmCTestSubmitHandler.cxx 31 KB

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