cmCTestSubmitHandler.cxx 32 KB

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