hdfs.cc 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. #include "hdfspp/hdfspp.h"
  19. #include "fs/filesystem.h"
  20. #include "common/hdfs_configuration.h"
  21. #include "common/configuration_loader.h"
  22. #include "common/logging.h"
  23. #include <hdfs/hdfs.h>
  24. #include <hdfspp/hdfs_ext.h>
  25. #include <libgen.h>
  26. #include "limits.h"
  27. #include <string>
  28. #include <cstring>
  29. #include <iostream>
  30. #include <algorithm>
  31. #include <functional>
  32. using namespace hdfs;
  33. using std::experimental::nullopt;
  34. using namespace std::placeholders;
  35. static constexpr tPort kDefaultPort = 8020;
  36. /* Separate the handles used by the C api from the C++ API*/
  37. struct hdfs_internal {
  38. hdfs_internal(FileSystem *p) : filesystem_(p), working_directory_("/") {}
  39. hdfs_internal(std::unique_ptr<FileSystem> p)
  40. : filesystem_(std::move(p)), working_directory_("/") {}
  41. virtual ~hdfs_internal(){};
  42. FileSystem *get_impl() { return filesystem_.get(); }
  43. const FileSystem *get_impl() const { return filesystem_.get(); }
  44. std::string get_working_directory() {
  45. std::lock_guard<std::mutex> read_guard(wd_lock_);
  46. return working_directory_;
  47. }
  48. void set_working_directory(std::string new_directory) {
  49. std::lock_guard<std::mutex> write_guard(wd_lock_);
  50. working_directory_ = new_directory;
  51. }
  52. private:
  53. std::unique_ptr<FileSystem> filesystem_;
  54. std::string working_directory_; //has to always start and end with '/'
  55. std::mutex wd_lock_; //synchronize access to the working directory
  56. };
  57. struct hdfsFile_internal {
  58. hdfsFile_internal(FileHandle *p) : file_(p) {}
  59. hdfsFile_internal(std::unique_ptr<FileHandle> p) : file_(std::move(p)) {}
  60. virtual ~hdfsFile_internal(){};
  61. FileHandle *get_impl() { return file_.get(); }
  62. const FileHandle *get_impl() const { return file_.get(); }
  63. private:
  64. std::unique_ptr<FileHandle> file_;
  65. };
  66. /* Keep thread local copy of last error string */
  67. thread_local std::string errstr;
  68. /* Fetch last error that happened in this thread */
  69. int hdfsGetLastError(char *buf, int len) {
  70. //No error message
  71. if(errstr.empty()){
  72. return -1;
  73. }
  74. //There is an error, but no room for the error message to be copied to
  75. if(nullptr == buf || len < 1) {
  76. return -1;
  77. }
  78. /* leave space for a trailing null */
  79. size_t copylen = std::min((size_t)errstr.size(), (size_t)len);
  80. if(copylen == (size_t)len) {
  81. copylen--;
  82. }
  83. strncpy(buf, errstr.c_str(), copylen);
  84. /* stick in null */
  85. buf[copylen] = 0;
  86. return 0;
  87. }
  88. /* Event callbacks for next open calls */
  89. thread_local std::experimental::optional<fs_event_callback> fsEventCallback;
  90. thread_local std::experimental::optional<file_event_callback> fileEventCallback;
  91. struct hdfsBuilder {
  92. hdfsBuilder();
  93. hdfsBuilder(const char * directory);
  94. virtual ~hdfsBuilder() {}
  95. ConfigurationLoader loader;
  96. HdfsConfiguration config;
  97. optional<std::string> overrideHost;
  98. optional<tPort> overridePort;
  99. optional<std::string> user;
  100. static constexpr tPort kUseDefaultPort = 0;
  101. };
  102. /* Error handling with optional debug to stderr */
  103. static void ReportError(int errnum, const std::string & msg) {
  104. errno = errnum;
  105. errstr = msg;
  106. #ifdef LIBHDFSPP_C_API_ENABLE_DEBUG
  107. std::cerr << "Error: errno=" << strerror(errnum) << " message=\"" << msg
  108. << "\"" << std::endl;
  109. #else
  110. (void)msg;
  111. #endif
  112. }
  113. /* Convert Status wrapped error into appropriate errno and return code */
  114. static int Error(const Status &stat) {
  115. const char * default_message;
  116. int errnum;
  117. int code = stat.code();
  118. switch (code) {
  119. case Status::Code::kOk:
  120. return 0;
  121. case Status::Code::kInvalidArgument:
  122. errnum = EINVAL;
  123. default_message = "Invalid argument";
  124. break;
  125. case Status::Code::kResourceUnavailable:
  126. errnum = EAGAIN;
  127. default_message = "Resource temporarily unavailable";
  128. break;
  129. case Status::Code::kUnimplemented:
  130. errnum = ENOSYS;
  131. default_message = "Function not implemented";
  132. break;
  133. case Status::Code::kException:
  134. errnum = EINTR;
  135. default_message = "Exception raised";
  136. break;
  137. case Status::Code::kOperationCanceled:
  138. errnum = EINTR;
  139. default_message = "Operation canceled";
  140. break;
  141. case Status::Code::kPermissionDenied:
  142. errnum = EACCES;
  143. default_message = "Permission denied";
  144. break;
  145. case Status::Code::kPathNotFound:
  146. errnum = ENOENT;
  147. default_message = "No such file or directory";
  148. break;
  149. case Status::Code::kNotADirectory:
  150. errnum = ENOTDIR;
  151. default_message = "Not a directory";
  152. break;
  153. case Status::Code::kFileAlreadyExists:
  154. errnum = EEXIST;
  155. default_message = "File already exists";
  156. break;
  157. case Status::Code::kPathIsNotEmptyDirectory:
  158. errnum = ENOTEMPTY;
  159. default_message = "Directory is not empty";
  160. break;
  161. case Status::Code::kInvalidOffset:
  162. errnum = Status::Code::kInvalidOffset;
  163. default_message = "Trying to begin a read past the EOF";
  164. break;
  165. default:
  166. errnum = ENOSYS;
  167. default_message = "Error: unrecognised code";
  168. }
  169. if (stat.ToString().empty())
  170. ReportError(errnum, default_message);
  171. else
  172. ReportError(errnum, stat.ToString());
  173. return -1;
  174. }
  175. static int ReportException(const std::exception & e)
  176. {
  177. return Error(Status::Exception("Uncaught exception", e.what()));
  178. }
  179. static int ReportCaughtNonException()
  180. {
  181. return Error(Status::Exception("Uncaught value not derived from std::exception", ""));
  182. }
  183. /* return false on failure */
  184. bool CheckSystem(hdfsFS fs) {
  185. if (!fs) {
  186. ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
  187. return false;
  188. }
  189. return true;
  190. }
  191. /* return false on failure */
  192. bool CheckHandle(hdfsFile file) {
  193. if (!file) {
  194. ReportError(EBADF, "Cannot perform FS operations with null File handle.");
  195. return false;
  196. }
  197. return true;
  198. }
  199. /* return false on failure */
  200. bool CheckSystemAndHandle(hdfsFS fs, hdfsFile file) {
  201. if (!CheckSystem(fs))
  202. return false;
  203. if (!CheckHandle(file))
  204. return false;
  205. return true;
  206. }
  207. optional<std::string> getAbsolutePath(hdfsFS fs, const char* path) {
  208. //Does not support . (dot) and .. (double dot) semantics
  209. if (!path || path[0] == '\0') {
  210. Error(Status::InvalidArgument("getAbsolutePath: argument 'path' cannot be NULL or empty"));
  211. return optional<std::string>();
  212. }
  213. if (path[0] != '/') {
  214. //we know that working directory always ends with '/'
  215. return fs->get_working_directory().append(path);
  216. }
  217. return optional<std::string>(path);
  218. }
  219. /**
  220. * C API implementations
  221. **/
  222. int hdfsFileIsOpenForRead(hdfsFile file) {
  223. /* files can only be open for reads at the moment, do a quick check */
  224. if (!CheckHandle(file)){
  225. return 0;
  226. }
  227. return 1; // Update implementation when we get file writing
  228. }
  229. int hdfsFileIsOpenForWrite(hdfsFile file) {
  230. /* files can only be open for reads at the moment, so return false */
  231. CheckHandle(file);
  232. return -1; // Update implementation when we get file writing
  233. }
  234. int hdfsConfGetLong(const char *key, int64_t *val)
  235. {
  236. try
  237. {
  238. errno = 0;
  239. hdfsBuilder builder;
  240. return hdfsBuilderConfGetLong(&builder, key, val);
  241. } catch (const std::exception & e) {
  242. return ReportException(e);
  243. } catch (...) {
  244. return ReportCaughtNonException();
  245. }
  246. }
  247. hdfsFS doHdfsConnect(optional<std::string> nn, optional<tPort> port, optional<std::string> user, const Options & options) {
  248. try
  249. {
  250. errno = 0;
  251. IoService * io_service = IoService::New();
  252. FileSystem *fs = FileSystem::New(io_service, user.value_or(""), options);
  253. if (!fs) {
  254. ReportError(ENODEV, "Could not create FileSystem object");
  255. return nullptr;
  256. }
  257. if (fsEventCallback) {
  258. fs->SetFsEventCallback(fsEventCallback.value());
  259. }
  260. Status status;
  261. if (nn || port) {
  262. if (!port) {
  263. port = kDefaultPort;
  264. }
  265. std::string port_as_string = std::to_string(*port);
  266. status = fs->Connect(nn.value_or(""), port_as_string);
  267. } else {
  268. status = fs->ConnectToDefaultFs();
  269. }
  270. if (!status.ok()) {
  271. Error(status);
  272. // FileSystem's ctor might take ownership of the io_service; if it does,
  273. // it will null out the pointer
  274. if (io_service)
  275. delete io_service;
  276. delete fs;
  277. return nullptr;
  278. }
  279. return new hdfs_internal(fs);
  280. } catch (const std::exception & e) {
  281. ReportException(e);
  282. return nullptr;
  283. } catch (...) {
  284. ReportCaughtNonException();
  285. return nullptr;
  286. }
  287. }
  288. hdfsFS hdfsAllocateFileSystem(struct hdfsBuilder *bld) {
  289. // Same idea as the first half of doHdfsConnect, but return the wrapped FS before
  290. // connecting.
  291. try {
  292. errno = 0;
  293. std::shared_ptr<IoService> io_service = IoService::MakeShared();
  294. int io_thread_count = bld->config.GetOptions().io_threads_;
  295. if(io_thread_count < 1) {
  296. io_service->InitDefaultWorkers();
  297. } else {
  298. io_service->InitWorkers(io_thread_count);
  299. }
  300. FileSystem *fs = FileSystem::New(io_service, bld->user.value_or(""), bld->config.GetOptions());
  301. if (!fs) {
  302. ReportError(ENODEV, "Could not create FileSystem object");
  303. return nullptr;
  304. }
  305. if (fsEventCallback) {
  306. fs->SetFsEventCallback(fsEventCallback.value());
  307. }
  308. return new hdfs_internal(fs);
  309. } catch (const std::exception &e) {
  310. ReportException(e);
  311. return nullptr;
  312. } catch (...) {
  313. ReportCaughtNonException();
  314. return nullptr;
  315. }
  316. return nullptr;
  317. }
  318. int hdfsConnectAllocated(hdfsFS fs, struct hdfsBuilder *bld) {
  319. if(!CheckSystem(fs)) {
  320. return ENODEV;
  321. }
  322. if(!bld) {
  323. ReportError(ENODEV, "No hdfsBuilder object supplied");
  324. return ENODEV;
  325. }
  326. // Get C++ FS to do connect
  327. FileSystem *fsImpl = fs->get_impl();
  328. if(!fsImpl) {
  329. ReportError(ENODEV, "Null FileSystem implementation");
  330. return ENODEV;
  331. }
  332. // Unpack the required bits of the hdfsBuilder
  333. optional<std::string> nn = bld->overrideHost;
  334. optional<tPort> port = bld->overridePort;
  335. optional<std::string> user = bld->user;
  336. // try-catch in case some of the third-party stuff throws
  337. try {
  338. Status status;
  339. if (nn || port) {
  340. if (!port) {
  341. port = kDefaultPort;
  342. }
  343. std::string port_as_string = std::to_string(*port);
  344. status = fsImpl->Connect(nn.value_or(""), port_as_string);
  345. } else {
  346. status = fsImpl->ConnectToDefaultFs();
  347. }
  348. if (!status.ok()) {
  349. Error(status);
  350. return ENODEV;
  351. }
  352. // 0 to indicate a good connection
  353. return 0;
  354. } catch (const std::exception & e) {
  355. ReportException(e);
  356. return ENODEV;
  357. } catch (...) {
  358. ReportCaughtNonException();
  359. return ENODEV;
  360. }
  361. return 0;
  362. }
  363. hdfsFS hdfsConnect(const char *nn, tPort port) {
  364. return hdfsConnectAsUser(nn, port, "");
  365. }
  366. hdfsFS hdfsConnectAsUser(const char* nn, tPort port, const char *user) {
  367. return doHdfsConnect(std::string(nn), port, std::string(user), Options());
  368. }
  369. hdfsFS hdfsConnectAsUserNewInstance(const char* nn, tPort port, const char *user ) {
  370. //libhdfspp always returns a new instance
  371. return doHdfsConnect(std::string(nn), port, std::string(user), Options());
  372. }
  373. hdfsFS hdfsConnectNewInstance(const char* nn, tPort port) {
  374. //libhdfspp always returns a new instance
  375. return hdfsConnectAsUser(nn, port, "");
  376. }
  377. int hdfsCancelPendingConnection(hdfsFS fs) {
  378. // todo: stick an enum in hdfs_internal to check the connect state
  379. if(!CheckSystem(fs)) {
  380. return ENODEV;
  381. }
  382. FileSystem *fsImpl = fs->get_impl();
  383. if(!fsImpl) {
  384. ReportError(ENODEV, "Null FileSystem implementation");
  385. return ENODEV;
  386. }
  387. bool canceled = fsImpl->CancelPendingConnect();
  388. if(canceled) {
  389. return 0;
  390. } else {
  391. return EINTR;
  392. }
  393. }
  394. int hdfsDisconnect(hdfsFS fs) {
  395. try
  396. {
  397. errno = 0;
  398. if (!fs) {
  399. ReportError(ENODEV, "Cannot disconnect null FS handle.");
  400. return -1;
  401. }
  402. delete fs;
  403. return 0;
  404. } catch (const std::exception & e) {
  405. return ReportException(e);
  406. } catch (...) {
  407. return ReportCaughtNonException();
  408. }
  409. }
  410. hdfsFile hdfsOpenFile(hdfsFS fs, const char *path, int flags, int bufferSize,
  411. short replication, tSize blocksize) {
  412. try
  413. {
  414. errno = 0;
  415. (void)flags;
  416. (void)bufferSize;
  417. (void)replication;
  418. (void)blocksize;
  419. if (!fs) {
  420. ReportError(ENODEV, "Cannot perform FS operations with null FS handle.");
  421. return nullptr;
  422. }
  423. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  424. if(!abs_path) {
  425. return nullptr;
  426. }
  427. FileHandle *f = nullptr;
  428. Status stat = fs->get_impl()->Open(*abs_path, &f);
  429. if (!stat.ok()) {
  430. Error(stat);
  431. return nullptr;
  432. }
  433. if (f && fileEventCallback) {
  434. f->SetFileEventCallback(fileEventCallback.value());
  435. }
  436. return new hdfsFile_internal(f);
  437. } catch (const std::exception & e) {
  438. ReportException(e);
  439. return nullptr;
  440. } catch (...) {
  441. ReportCaughtNonException();
  442. return nullptr;
  443. }
  444. }
  445. int hdfsCloseFile(hdfsFS fs, hdfsFile file) {
  446. try
  447. {
  448. errno = 0;
  449. if (!CheckSystemAndHandle(fs, file)) {
  450. return -1;
  451. }
  452. delete file;
  453. return 0;
  454. } catch (const std::exception & e) {
  455. return ReportException(e);
  456. } catch (...) {
  457. return ReportCaughtNonException();
  458. }
  459. }
  460. char* hdfsGetWorkingDirectory(hdfsFS fs, char *buffer, size_t bufferSize) {
  461. try
  462. {
  463. errno = 0;
  464. if (!CheckSystem(fs)) {
  465. return nullptr;
  466. }
  467. std::string wd = fs->get_working_directory();
  468. size_t size = wd.size();
  469. if (size + 1 > bufferSize) {
  470. std::stringstream ss;
  471. ss << "hdfsGetWorkingDirectory: bufferSize is " << bufferSize <<
  472. ", which is not enough to fit working directory of size " << (size + 1);
  473. Error(Status::InvalidArgument(ss.str().c_str()));
  474. return nullptr;
  475. }
  476. wd.copy(buffer, size);
  477. buffer[size] = '\0';
  478. return buffer;
  479. } catch (const std::exception & e) {
  480. ReportException(e);
  481. return nullptr;
  482. } catch (...) {
  483. ReportCaughtNonException();
  484. return nullptr;
  485. }
  486. }
  487. int hdfsSetWorkingDirectory(hdfsFS fs, const char* path) {
  488. try
  489. {
  490. errno = 0;
  491. if (!CheckSystem(fs)) {
  492. return -1;
  493. }
  494. optional<std::string> abs_path = getAbsolutePath(fs, path);
  495. if(!abs_path) {
  496. return -1;
  497. }
  498. //Enforce last character to be '/'
  499. std::string withSlash = *abs_path;
  500. char last = withSlash.back();
  501. if (last != '/'){
  502. withSlash += '/';
  503. }
  504. fs->set_working_directory(withSlash);
  505. return 0;
  506. } catch (const std::exception & e) {
  507. return ReportException(e);
  508. } catch (...) {
  509. return ReportCaughtNonException();
  510. }
  511. }
  512. int hdfsAvailable(hdfsFS fs, hdfsFile file) {
  513. //Since we do not have read ahead implemented, return 0 if fs and file are good;
  514. errno = 0;
  515. if (!CheckSystemAndHandle(fs, file)) {
  516. return -1;
  517. }
  518. return 0;
  519. }
  520. tOffset hdfsGetDefaultBlockSize(hdfsFS fs) {
  521. try {
  522. errno = 0;
  523. return fs->get_impl()->get_options().block_size;
  524. } catch (const std::exception & e) {
  525. ReportException(e);
  526. return -1;
  527. } catch (...) {
  528. ReportCaughtNonException();
  529. return -1;
  530. }
  531. }
  532. tOffset hdfsGetDefaultBlockSizeAtPath(hdfsFS fs, const char *path) {
  533. try {
  534. errno = 0;
  535. if (!CheckSystem(fs)) {
  536. return -1;
  537. }
  538. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  539. if(!abs_path) {
  540. return -1;
  541. }
  542. uint64_t block_size;
  543. Status stat = fs->get_impl()->GetPreferredBlockSize(*abs_path, block_size);
  544. if (!stat.ok()) {
  545. if (stat.pathNotFound()){
  546. return fs->get_impl()->get_options().block_size;
  547. } else {
  548. return Error(stat);
  549. }
  550. }
  551. return block_size;
  552. } catch (const std::exception & e) {
  553. ReportException(e);
  554. return -1;
  555. } catch (...) {
  556. ReportCaughtNonException();
  557. return -1;
  558. }
  559. }
  560. int hdfsSetReplication(hdfsFS fs, const char* path, int16_t replication) {
  561. try {
  562. errno = 0;
  563. if (!CheckSystem(fs)) {
  564. return -1;
  565. }
  566. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  567. if(!abs_path) {
  568. return -1;
  569. }
  570. if(replication < 1){
  571. return Error(Status::InvalidArgument("SetReplication: argument 'replication' cannot be less than 1"));
  572. }
  573. Status stat;
  574. stat = fs->get_impl()->SetReplication(*abs_path, replication);
  575. if (!stat.ok()) {
  576. return Error(stat);
  577. }
  578. return 0;
  579. } catch (const std::exception & e) {
  580. return ReportException(e);
  581. } catch (...) {
  582. return ReportCaughtNonException();
  583. }
  584. }
  585. int hdfsUtime(hdfsFS fs, const char* path, tTime mtime, tTime atime) {
  586. try {
  587. errno = 0;
  588. if (!CheckSystem(fs)) {
  589. return -1;
  590. }
  591. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  592. if(!abs_path) {
  593. return -1;
  594. }
  595. Status stat;
  596. stat = fs->get_impl()->SetTimes(*abs_path, mtime, atime);
  597. if (!stat.ok()) {
  598. return Error(stat);
  599. }
  600. return 0;
  601. } catch (const std::exception & e) {
  602. return ReportException(e);
  603. } catch (...) {
  604. return ReportCaughtNonException();
  605. }
  606. }
  607. tOffset hdfsGetCapacity(hdfsFS fs) {
  608. try {
  609. errno = 0;
  610. if (!CheckSystem(fs)) {
  611. return -1;
  612. }
  613. hdfs::FsInfo fs_info;
  614. Status stat = fs->get_impl()->GetFsStats(fs_info);
  615. if (!stat.ok()) {
  616. Error(stat);
  617. return -1;
  618. }
  619. return fs_info.capacity;
  620. } catch (const std::exception & e) {
  621. ReportException(e);
  622. return -1;
  623. } catch (...) {
  624. ReportCaughtNonException();
  625. return -1;
  626. }
  627. }
  628. tOffset hdfsGetUsed(hdfsFS fs) {
  629. try {
  630. errno = 0;
  631. if (!CheckSystem(fs)) {
  632. return -1;
  633. }
  634. hdfs::FsInfo fs_info;
  635. Status stat = fs->get_impl()->GetFsStats(fs_info);
  636. if (!stat.ok()) {
  637. Error(stat);
  638. return -1;
  639. }
  640. return fs_info.used;
  641. } catch (const std::exception & e) {
  642. ReportException(e);
  643. return -1;
  644. } catch (...) {
  645. ReportCaughtNonException();
  646. return -1;
  647. }
  648. }
  649. void StatInfoToHdfsFileInfo(hdfsFileInfo * file_info,
  650. const hdfs::StatInfo & stat_info) {
  651. /* file or directory */
  652. if (stat_info.file_type == StatInfo::IS_DIR) {
  653. file_info->mKind = kObjectKindDirectory;
  654. } else if (stat_info.file_type == StatInfo::IS_FILE) {
  655. file_info->mKind = kObjectKindFile;
  656. } else {
  657. file_info->mKind = kObjectKindFile;
  658. LOG_WARN(kFileSystem, << "Symlink is not supported! Reporting as a file: ");
  659. }
  660. /* the name of the file */
  661. char copyOfPath[PATH_MAX];
  662. strncpy(copyOfPath, stat_info.path.c_str(), PATH_MAX);
  663. copyOfPath[PATH_MAX - 1] = '\0'; // in case strncpy ran out of space
  664. char * mName = basename(copyOfPath);
  665. size_t mName_size = strlen(mName);
  666. file_info->mName = new char[mName_size+1];
  667. strncpy(file_info->mName, basename(copyOfPath), mName_size + 1);
  668. /* the last modification time for the file in seconds */
  669. file_info->mLastMod = (tTime) stat_info.modification_time;
  670. /* the size of the file in bytes */
  671. file_info->mSize = (tOffset) stat_info.length;
  672. /* the count of replicas */
  673. file_info->mReplication = (short) stat_info.block_replication;
  674. /* the block size for the file */
  675. file_info->mBlockSize = (tOffset) stat_info.blocksize;
  676. /* the owner of the file */
  677. file_info->mOwner = new char[stat_info.owner.size() + 1];
  678. strncpy(file_info->mOwner, stat_info.owner.c_str(), stat_info.owner.size() + 1);
  679. /* the group associated with the file */
  680. file_info->mGroup = new char[stat_info.group.size() + 1];
  681. strncpy(file_info->mGroup, stat_info.group.c_str(), stat_info.group.size() + 1);
  682. /* the permissions associated with the file encoded as an octal number (0777)*/
  683. file_info->mPermissions = (short) stat_info.permissions;
  684. /* the last access time for the file in seconds since the epoch*/
  685. file_info->mLastAccess = stat_info.access_time;
  686. }
  687. int hdfsExists(hdfsFS fs, const char *path) {
  688. try {
  689. errno = 0;
  690. if (!CheckSystem(fs)) {
  691. return -1;
  692. }
  693. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  694. if(!abs_path) {
  695. return -1;
  696. }
  697. hdfs::StatInfo stat_info;
  698. Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
  699. if (!stat.ok()) {
  700. return Error(stat);
  701. }
  702. return 0;
  703. } catch (const std::exception & e) {
  704. return ReportException(e);
  705. } catch (...) {
  706. return ReportCaughtNonException();
  707. }
  708. }
  709. hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path) {
  710. try {
  711. errno = 0;
  712. if (!CheckSystem(fs)) {
  713. return nullptr;
  714. }
  715. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  716. if(!abs_path) {
  717. return nullptr;
  718. }
  719. hdfs::StatInfo stat_info;
  720. Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
  721. if (!stat.ok()) {
  722. Error(stat);
  723. return nullptr;
  724. }
  725. hdfsFileInfo *file_info = new hdfsFileInfo[1];
  726. StatInfoToHdfsFileInfo(file_info, stat_info);
  727. return file_info;
  728. } catch (const std::exception & e) {
  729. ReportException(e);
  730. return nullptr;
  731. } catch (...) {
  732. ReportCaughtNonException();
  733. return nullptr;
  734. }
  735. }
  736. hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries) {
  737. try {
  738. errno = 0;
  739. if (!CheckSystem(fs)) {
  740. *numEntries = 0;
  741. return nullptr;
  742. }
  743. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  744. if(!abs_path) {
  745. return nullptr;
  746. }
  747. std::vector<StatInfo> stat_infos;
  748. Status stat = fs->get_impl()->GetListing(*abs_path, &stat_infos);
  749. if (!stat.ok()) {
  750. Error(stat);
  751. *numEntries = 0;
  752. return nullptr;
  753. }
  754. if(stat_infos.empty()){
  755. *numEntries = 0;
  756. return nullptr;
  757. }
  758. *numEntries = stat_infos.size();
  759. hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
  760. for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
  761. StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
  762. }
  763. return file_infos;
  764. } catch (const std::exception & e) {
  765. ReportException(e);
  766. *numEntries = 0;
  767. return nullptr;
  768. } catch (...) {
  769. ReportCaughtNonException();
  770. *numEntries = 0;
  771. return nullptr;
  772. }
  773. }
  774. void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
  775. {
  776. errno = 0;
  777. int i;
  778. for (i = 0; i < numEntries; ++i) {
  779. delete[] hdfsFileInfo[i].mName;
  780. delete[] hdfsFileInfo[i].mOwner;
  781. delete[] hdfsFileInfo[i].mGroup;
  782. }
  783. delete[] hdfsFileInfo;
  784. }
  785. int hdfsCreateDirectory(hdfsFS fs, const char* path) {
  786. try {
  787. errno = 0;
  788. if (!CheckSystem(fs)) {
  789. return -1;
  790. }
  791. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  792. if(!abs_path) {
  793. return -1;
  794. }
  795. Status stat;
  796. //Use default permissions and set true for creating all non-existant parent directories
  797. stat = fs->get_impl()->Mkdirs(*abs_path, FileSystem::GetDefaultPermissionMask(), true);
  798. if (!stat.ok()) {
  799. return Error(stat);
  800. }
  801. return 0;
  802. } catch (const std::exception & e) {
  803. return ReportException(e);
  804. } catch (...) {
  805. return ReportCaughtNonException();
  806. }
  807. }
  808. int hdfsDelete(hdfsFS fs, const char* path, int recursive) {
  809. try {
  810. errno = 0;
  811. if (!CheckSystem(fs)) {
  812. return -1;
  813. }
  814. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  815. if(!abs_path) {
  816. return -1;
  817. }
  818. Status stat;
  819. stat = fs->get_impl()->Delete(*abs_path, recursive);
  820. if (!stat.ok()) {
  821. return Error(stat);
  822. }
  823. return 0;
  824. } catch (const std::exception & e) {
  825. return ReportException(e);
  826. } catch (...) {
  827. return ReportCaughtNonException();
  828. }
  829. }
  830. int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath) {
  831. try {
  832. errno = 0;
  833. if (!CheckSystem(fs)) {
  834. return -1;
  835. }
  836. const optional<std::string> old_abs_path = getAbsolutePath(fs, oldPath);
  837. const optional<std::string> new_abs_path = getAbsolutePath(fs, newPath);
  838. if(!old_abs_path || !new_abs_path) {
  839. return -1;
  840. }
  841. Status stat;
  842. stat = fs->get_impl()->Rename(*old_abs_path, *new_abs_path);
  843. if (!stat.ok()) {
  844. return Error(stat);
  845. }
  846. return 0;
  847. } catch (const std::exception & e) {
  848. return ReportException(e);
  849. } catch (...) {
  850. return ReportCaughtNonException();
  851. }
  852. }
  853. int hdfsChmod(hdfsFS fs, const char* path, short mode){
  854. try {
  855. errno = 0;
  856. if (!CheckSystem(fs)) {
  857. return -1;
  858. }
  859. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  860. if(!abs_path) {
  861. return -1;
  862. }
  863. Status stat = FileSystem::CheckValidPermissionMask(mode);
  864. if (!stat.ok()) {
  865. return Error(stat);
  866. }
  867. stat = fs->get_impl()->SetPermission(*abs_path, mode);
  868. if (!stat.ok()) {
  869. return Error(stat);
  870. }
  871. return 0;
  872. } catch (const std::exception & e) {
  873. return ReportException(e);
  874. } catch (...) {
  875. return ReportCaughtNonException();
  876. }
  877. }
  878. int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group){
  879. try {
  880. errno = 0;
  881. if (!CheckSystem(fs)) {
  882. return -1;
  883. }
  884. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  885. if(!abs_path) {
  886. return -1;
  887. }
  888. std::string own = (owner) ? owner : "";
  889. std::string grp = (group) ? group : "";
  890. Status stat;
  891. stat = fs->get_impl()->SetOwner(*abs_path, own, grp);
  892. if (!stat.ok()) {
  893. return Error(stat);
  894. }
  895. return 0;
  896. } catch (const std::exception & e) {
  897. return ReportException(e);
  898. } catch (...) {
  899. return ReportCaughtNonException();
  900. }
  901. }
  902. hdfsFileInfo * hdfsFind(hdfsFS fs, const char* path, const char* name, uint32_t * numEntries){
  903. try {
  904. errno = 0;
  905. if (!CheckSystem(fs)) {
  906. *numEntries = 0;
  907. return nullptr;
  908. }
  909. std::vector<StatInfo> stat_infos;
  910. Status stat = fs->get_impl()->Find(path, name, hdfs::FileSystem::GetDefaultFindMaxDepth(), &stat_infos);
  911. if (!stat.ok()) {
  912. Error(stat);
  913. *numEntries = 0;
  914. return nullptr;
  915. }
  916. //Existing API expects nullptr if size is 0
  917. if(stat_infos.empty()){
  918. *numEntries = 0;
  919. return nullptr;
  920. }
  921. *numEntries = stat_infos.size();
  922. hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
  923. for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
  924. StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
  925. }
  926. return file_infos;
  927. } catch (const std::exception & e) {
  928. ReportException(e);
  929. *numEntries = 0;
  930. return nullptr;
  931. } catch (...) {
  932. ReportCaughtNonException();
  933. *numEntries = 0;
  934. return nullptr;
  935. }
  936. }
  937. int hdfsCreateSnapshot(hdfsFS fs, const char* path, const char* name) {
  938. try {
  939. errno = 0;
  940. if (!CheckSystem(fs)) {
  941. return -1;
  942. }
  943. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  944. if(!abs_path) {
  945. return -1;
  946. }
  947. Status stat;
  948. if(!name){
  949. stat = fs->get_impl()->CreateSnapshot(*abs_path, "");
  950. } else {
  951. stat = fs->get_impl()->CreateSnapshot(*abs_path, name);
  952. }
  953. if (!stat.ok()) {
  954. return Error(stat);
  955. }
  956. return 0;
  957. } catch (const std::exception & e) {
  958. return ReportException(e);
  959. } catch (...) {
  960. return ReportCaughtNonException();
  961. }
  962. }
  963. int hdfsDeleteSnapshot(hdfsFS fs, const char* path, const char* name) {
  964. try {
  965. errno = 0;
  966. if (!CheckSystem(fs)) {
  967. return -1;
  968. }
  969. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  970. if(!abs_path) {
  971. return -1;
  972. }
  973. if (!name) {
  974. return Error(Status::InvalidArgument("hdfsDeleteSnapshot: argument 'name' cannot be NULL"));
  975. }
  976. Status stat;
  977. stat = fs->get_impl()->DeleteSnapshot(*abs_path, name);
  978. if (!stat.ok()) {
  979. return Error(stat);
  980. }
  981. return 0;
  982. } catch (const std::exception & e) {
  983. return ReportException(e);
  984. } catch (...) {
  985. return ReportCaughtNonException();
  986. }
  987. }
  988. int hdfsRenameSnapshot(hdfsFS fs, const char* path, const char* old_name, const char* new_name) {
  989. try {
  990. errno = 0;
  991. if (!CheckSystem(fs)) {
  992. return -1;
  993. }
  994. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  995. if(!abs_path) {
  996. return -1;
  997. }
  998. if (!old_name) {
  999. return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'old_name' cannot be NULL"));
  1000. }
  1001. if (!new_name) {
  1002. return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'new_name' cannot be NULL"));
  1003. }
  1004. Status stat;
  1005. stat = fs->get_impl()->RenameSnapshot(*abs_path, old_name, new_name);
  1006. if (!stat.ok()) {
  1007. return Error(stat);
  1008. }
  1009. return 0;
  1010. } catch (const std::exception & e) {
  1011. return ReportException(e);
  1012. } catch (...) {
  1013. return ReportCaughtNonException();
  1014. }
  1015. }
  1016. int hdfsAllowSnapshot(hdfsFS fs, const char* path) {
  1017. try {
  1018. errno = 0;
  1019. if (!CheckSystem(fs)) {
  1020. return -1;
  1021. }
  1022. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1023. if(!abs_path) {
  1024. return -1;
  1025. }
  1026. Status stat;
  1027. stat = fs->get_impl()->AllowSnapshot(*abs_path);
  1028. if (!stat.ok()) {
  1029. return Error(stat);
  1030. }
  1031. return 0;
  1032. } catch (const std::exception & e) {
  1033. return ReportException(e);
  1034. } catch (...) {
  1035. return ReportCaughtNonException();
  1036. }
  1037. }
  1038. int hdfsDisallowSnapshot(hdfsFS fs, const char* path) {
  1039. try {
  1040. errno = 0;
  1041. if (!CheckSystem(fs)) {
  1042. return -1;
  1043. }
  1044. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1045. if(!abs_path) {
  1046. return -1;
  1047. }
  1048. Status stat;
  1049. stat = fs->get_impl()->DisallowSnapshot(*abs_path);
  1050. if (!stat.ok()) {
  1051. return Error(stat);
  1052. }
  1053. return 0;
  1054. } catch (const std::exception & e) {
  1055. return ReportException(e);
  1056. } catch (...) {
  1057. return ReportCaughtNonException();
  1058. }
  1059. }
  1060. tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position, void *buffer,
  1061. tSize length) {
  1062. try
  1063. {
  1064. errno = 0;
  1065. if (!CheckSystemAndHandle(fs, file)) {
  1066. return -1;
  1067. }
  1068. size_t len = 0;
  1069. Status stat = file->get_impl()->PositionRead(buffer, length, position, &len);
  1070. if(!stat.ok()) {
  1071. return Error(stat);
  1072. }
  1073. return (tSize)len;
  1074. } catch (const std::exception & e) {
  1075. return ReportException(e);
  1076. } catch (...) {
  1077. return ReportCaughtNonException();
  1078. }
  1079. }
  1080. tSize hdfsRead(hdfsFS fs, hdfsFile file, void *buffer, tSize length) {
  1081. try
  1082. {
  1083. errno = 0;
  1084. if (!CheckSystemAndHandle(fs, file)) {
  1085. return -1;
  1086. }
  1087. size_t len = 0;
  1088. Status stat = file->get_impl()->Read(buffer, length, &len);
  1089. if (!stat.ok()) {
  1090. return Error(stat);
  1091. }
  1092. return (tSize)len;
  1093. } catch (const std::exception & e) {
  1094. return ReportException(e);
  1095. } catch (...) {
  1096. return ReportCaughtNonException();
  1097. }
  1098. }
  1099. int hdfsUnbufferFile(hdfsFile file) {
  1100. //Currently we are not doing any buffering
  1101. CheckHandle(file);
  1102. return -1;
  1103. }
  1104. int hdfsFileGetReadStatistics(hdfsFile file, struct hdfsReadStatistics **stats) {
  1105. try
  1106. {
  1107. errno = 0;
  1108. if (!CheckHandle(file)) {
  1109. return -1;
  1110. }
  1111. *stats = new hdfsReadStatistics;
  1112. memset(*stats, 0, sizeof(hdfsReadStatistics));
  1113. (*stats)->totalBytesRead = file->get_impl()->get_bytes_read();
  1114. return 0;
  1115. } catch (const std::exception & e) {
  1116. return ReportException(e);
  1117. } catch (...) {
  1118. return ReportCaughtNonException();
  1119. }
  1120. }
  1121. int hdfsFileClearReadStatistics(hdfsFile file) {
  1122. try
  1123. {
  1124. errno = 0;
  1125. if (!CheckHandle(file)) {
  1126. return -1;
  1127. }
  1128. file->get_impl()->clear_bytes_read();
  1129. return 0;
  1130. } catch (const std::exception & e) {
  1131. return ReportException(e);
  1132. } catch (...) {
  1133. return ReportCaughtNonException();
  1134. }
  1135. }
  1136. int64_t hdfsReadStatisticsGetRemoteBytesRead(const struct hdfsReadStatistics *stats) {
  1137. return stats->totalBytesRead - stats->totalLocalBytesRead;
  1138. }
  1139. void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats) {
  1140. errno = 0;
  1141. delete stats;
  1142. }
  1143. /* 0 on success, -1 on error*/
  1144. int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos) {
  1145. try
  1146. {
  1147. errno = 0;
  1148. if (!CheckSystemAndHandle(fs, file)) {
  1149. return -1;
  1150. }
  1151. off_t desired = desiredPos;
  1152. Status stat = file->get_impl()->Seek(&desired, std::ios_base::beg);
  1153. if (!stat.ok()) {
  1154. return Error(stat);
  1155. }
  1156. return 0;
  1157. } catch (const std::exception & e) {
  1158. return ReportException(e);
  1159. } catch (...) {
  1160. return ReportCaughtNonException();
  1161. }
  1162. }
  1163. tOffset hdfsTell(hdfsFS fs, hdfsFile file) {
  1164. try
  1165. {
  1166. errno = 0;
  1167. if (!CheckSystemAndHandle(fs, file)) {
  1168. return -1;
  1169. }
  1170. ssize_t offset = 0;
  1171. Status stat = file->get_impl()->Seek(&offset, std::ios_base::cur);
  1172. if (!stat.ok()) {
  1173. return Error(stat);
  1174. }
  1175. return offset;
  1176. } catch (const std::exception & e) {
  1177. return ReportException(e);
  1178. } catch (...) {
  1179. return ReportCaughtNonException();
  1180. }
  1181. }
  1182. /* extended API */
  1183. int hdfsCancel(hdfsFS fs, hdfsFile file) {
  1184. try
  1185. {
  1186. errno = 0;
  1187. if (!CheckSystemAndHandle(fs, file)) {
  1188. return -1;
  1189. }
  1190. static_cast<FileHandleImpl*>(file->get_impl())->CancelOperations();
  1191. return 0;
  1192. } catch (const std::exception & e) {
  1193. return ReportException(e);
  1194. } catch (...) {
  1195. return ReportCaughtNonException();
  1196. }
  1197. }
  1198. int hdfsGetBlockLocations(hdfsFS fs, const char *path, struct hdfsBlockLocations ** locations_out)
  1199. {
  1200. try
  1201. {
  1202. errno = 0;
  1203. if (!CheckSystem(fs)) {
  1204. return -1;
  1205. }
  1206. if (locations_out == nullptr) {
  1207. ReportError(EINVAL, "Null pointer passed to hdfsGetBlockLocations");
  1208. return -1;
  1209. }
  1210. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1211. if(!abs_path) {
  1212. return -1;
  1213. }
  1214. std::shared_ptr<FileBlockLocation> ppLocations;
  1215. Status stat = fs->get_impl()->GetBlockLocations(*abs_path, 0, std::numeric_limits<int64_t>::max(), &ppLocations);
  1216. if (!stat.ok()) {
  1217. return Error(stat);
  1218. }
  1219. hdfsBlockLocations *locations = new struct hdfsBlockLocations();
  1220. (*locations_out) = locations;
  1221. bzero(locations, sizeof(*locations));
  1222. locations->fileLength = ppLocations->getFileLength();
  1223. locations->isLastBlockComplete = ppLocations->isLastBlockComplete();
  1224. locations->isUnderConstruction = ppLocations->isUnderConstruction();
  1225. const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
  1226. locations->num_blocks = ppBlockLocations.size();
  1227. locations->blocks = new struct hdfsBlockInfo[locations->num_blocks];
  1228. for (size_t i=0; i < ppBlockLocations.size(); i++) {
  1229. auto ppBlockLocation = ppBlockLocations[i];
  1230. auto block = &locations->blocks[i];
  1231. block->num_bytes = ppBlockLocation.getLength();
  1232. block->start_offset = ppBlockLocation.getOffset();
  1233. const std::vector<DNInfo> & ppDNInfos = ppBlockLocation.getDataNodes();
  1234. block->num_locations = ppDNInfos.size();
  1235. block->locations = new hdfsDNInfo[block->num_locations];
  1236. for (size_t j=0; j < block->num_locations; j++) {
  1237. auto ppDNInfo = ppDNInfos[j];
  1238. auto dn_info = &block->locations[j];
  1239. dn_info->xfer_port = ppDNInfo.getXferPort();
  1240. dn_info->info_port = ppDNInfo.getInfoPort();
  1241. dn_info->IPC_port = ppDNInfo.getIPCPort();
  1242. dn_info->info_secure_port = ppDNInfo.getInfoSecurePort();
  1243. char * buf;
  1244. buf = new char[ppDNInfo.getHostname().size() + 1];
  1245. strncpy(buf, ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
  1246. dn_info->hostname = buf;
  1247. buf = new char[ppDNInfo.getIPAddr().size() + 1];
  1248. strncpy(buf, ppDNInfo.getIPAddr().c_str(), ppDNInfo.getIPAddr().size() + 1);
  1249. dn_info->ip_address = buf;
  1250. buf = new char[ppDNInfo.getNetworkLocation().size() + 1];
  1251. strncpy(buf, ppDNInfo.getNetworkLocation().c_str(), ppDNInfo.getNetworkLocation().size() + 1);
  1252. dn_info->network_location = buf;
  1253. }
  1254. }
  1255. return 0;
  1256. } catch (const std::exception & e) {
  1257. return ReportException(e);
  1258. } catch (...) {
  1259. return ReportCaughtNonException();
  1260. }
  1261. }
  1262. int hdfsFreeBlockLocations(struct hdfsBlockLocations * blockLocations) {
  1263. errno = 0;
  1264. if (blockLocations == nullptr)
  1265. return 0;
  1266. for (size_t i=0; i < blockLocations->num_blocks; i++) {
  1267. auto block = &blockLocations->blocks[i];
  1268. for (size_t j=0; j < block->num_locations; j++) {
  1269. auto location = &block->locations[j];
  1270. delete[] location->hostname;
  1271. delete[] location->ip_address;
  1272. delete[] location->network_location;
  1273. }
  1274. }
  1275. delete[] blockLocations->blocks;
  1276. delete blockLocations;
  1277. return 0;
  1278. }
  1279. char*** hdfsGetHosts(hdfsFS fs, const char* path, tOffset start, tOffset length) {
  1280. try
  1281. {
  1282. errno = 0;
  1283. if (!CheckSystem(fs)) {
  1284. return nullptr;
  1285. }
  1286. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1287. if(!abs_path) {
  1288. return nullptr;
  1289. }
  1290. std::shared_ptr<FileBlockLocation> ppLocations;
  1291. Status stat = fs->get_impl()->GetBlockLocations(*abs_path, start, length, &ppLocations);
  1292. if (!stat.ok()) {
  1293. Error(stat);
  1294. return nullptr;
  1295. }
  1296. const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
  1297. char ***hosts = new char**[ppBlockLocations.size() + 1];
  1298. for (size_t i=0; i < ppBlockLocations.size(); i++) {
  1299. const std::vector<DNInfo> & ppDNInfos = ppBlockLocations[i].getDataNodes();
  1300. hosts[i] = new char*[ppDNInfos.size() + 1];
  1301. for (size_t j=0; j < ppDNInfos.size(); j++) {
  1302. auto ppDNInfo = ppDNInfos[j];
  1303. hosts[i][j] = new char[ppDNInfo.getHostname().size() + 1];
  1304. strncpy(hosts[i][j], ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
  1305. }
  1306. hosts[i][ppDNInfos.size()] = nullptr;
  1307. }
  1308. hosts[ppBlockLocations.size()] = nullptr;
  1309. return hosts;
  1310. } catch (const std::exception & e) {
  1311. ReportException(e);
  1312. return nullptr;
  1313. } catch (...) {
  1314. ReportCaughtNonException();
  1315. return nullptr;
  1316. }
  1317. }
  1318. void hdfsFreeHosts(char ***blockHosts) {
  1319. errno = 0;
  1320. if (blockHosts == nullptr)
  1321. return;
  1322. for (size_t i = 0; blockHosts[i]; i++) {
  1323. for (size_t j = 0; blockHosts[i][j]; j++) {
  1324. delete[] blockHosts[i][j];
  1325. }
  1326. delete[] blockHosts[i];
  1327. }
  1328. delete blockHosts;
  1329. }
  1330. /*******************************************************************
  1331. * EVENT CALLBACKS
  1332. *******************************************************************/
  1333. const char * FS_NN_CONNECT_EVENT = hdfs::FS_NN_CONNECT_EVENT;
  1334. const char * FS_NN_READ_EVENT = hdfs::FS_NN_READ_EVENT;
  1335. const char * FS_NN_WRITE_EVENT = hdfs::FS_NN_WRITE_EVENT;
  1336. const char * FILE_DN_CONNECT_EVENT = hdfs::FILE_DN_CONNECT_EVENT;
  1337. const char * FILE_DN_READ_EVENT = hdfs::FILE_DN_READ_EVENT;
  1338. const char * FILE_DN_WRITE_EVENT = hdfs::FILE_DN_WRITE_EVENT;
  1339. event_response fs_callback_glue(libhdfspp_fs_event_callback handler,
  1340. int64_t cookie,
  1341. const char * event,
  1342. const char * cluster,
  1343. int64_t value) {
  1344. int result = handler(event, cluster, value, cookie);
  1345. if (result == LIBHDFSPP_EVENT_OK) {
  1346. return event_response::make_ok();
  1347. }
  1348. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  1349. if (result == DEBUG_SIMULATE_ERROR) {
  1350. return event_response::test_err(Status::Error("Simulated error"));
  1351. }
  1352. #endif
  1353. return event_response::make_ok();
  1354. }
  1355. event_response file_callback_glue(libhdfspp_file_event_callback handler,
  1356. int64_t cookie,
  1357. const char * event,
  1358. const char * cluster,
  1359. const char * file,
  1360. int64_t value) {
  1361. int result = handler(event, cluster, file, value, cookie);
  1362. if (result == LIBHDFSPP_EVENT_OK) {
  1363. return event_response::make_ok();
  1364. }
  1365. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  1366. if (result == DEBUG_SIMULATE_ERROR) {
  1367. return event_response::test_err(Status::Error("Simulated error"));
  1368. }
  1369. #endif
  1370. return event_response::make_ok();
  1371. }
  1372. int hdfsPreAttachFSMonitor(libhdfspp_fs_event_callback handler, int64_t cookie)
  1373. {
  1374. fs_event_callback callback = std::bind(fs_callback_glue, handler, cookie, _1, _2, _3);
  1375. fsEventCallback = callback;
  1376. return 0;
  1377. }
  1378. int hdfsPreAttachFileMonitor(libhdfspp_file_event_callback handler, int64_t cookie)
  1379. {
  1380. file_event_callback callback = std::bind(file_callback_glue, handler, cookie, _1, _2, _3, _4);
  1381. fileEventCallback = callback;
  1382. return 0;
  1383. }
  1384. /*******************************************************************
  1385. * BUILDER INTERFACE
  1386. *******************************************************************/
  1387. HdfsConfiguration LoadDefault(ConfigurationLoader & loader)
  1388. {
  1389. optional<HdfsConfiguration> result = loader.LoadDefaultResources<HdfsConfiguration>();
  1390. if (result)
  1391. {
  1392. return result.value();
  1393. }
  1394. else
  1395. {
  1396. return loader.NewConfig<HdfsConfiguration>();
  1397. }
  1398. }
  1399. hdfsBuilder::hdfsBuilder() : config(loader.NewConfig<HdfsConfiguration>())
  1400. {
  1401. errno = 0;
  1402. config = LoadDefault(loader);
  1403. }
  1404. hdfsBuilder::hdfsBuilder(const char * directory) :
  1405. config(loader.NewConfig<HdfsConfiguration>())
  1406. {
  1407. errno = 0;
  1408. loader.SetSearchPath(directory);
  1409. config = LoadDefault(loader);
  1410. }
  1411. struct hdfsBuilder *hdfsNewBuilder(void)
  1412. {
  1413. try
  1414. {
  1415. errno = 0;
  1416. return new struct hdfsBuilder();
  1417. } catch (const std::exception & e) {
  1418. ReportException(e);
  1419. return nullptr;
  1420. } catch (...) {
  1421. ReportCaughtNonException();
  1422. return nullptr;
  1423. }
  1424. }
  1425. void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
  1426. {
  1427. errno = 0;
  1428. bld->overrideHost = std::string(nn);
  1429. }
  1430. void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
  1431. {
  1432. errno = 0;
  1433. bld->overridePort = port;
  1434. }
  1435. void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
  1436. {
  1437. errno = 0;
  1438. if (userName && *userName) {
  1439. bld->user = std::string(userName);
  1440. }
  1441. }
  1442. void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld) {
  1443. //libhdfspp always returns a new instance, so nothing to do
  1444. (void)bld;
  1445. errno = 0;
  1446. }
  1447. void hdfsFreeBuilder(struct hdfsBuilder *bld)
  1448. {
  1449. try
  1450. {
  1451. errno = 0;
  1452. delete bld;
  1453. } catch (const std::exception & e) {
  1454. ReportException(e);
  1455. } catch (...) {
  1456. ReportCaughtNonException();
  1457. }
  1458. }
  1459. int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
  1460. const char *val)
  1461. {
  1462. try
  1463. {
  1464. errno = 0;
  1465. optional<HdfsConfiguration> newConfig = bld->loader.OverlayValue(bld->config, key, val);
  1466. if (newConfig)
  1467. {
  1468. bld->config = newConfig.value();
  1469. return 0;
  1470. }
  1471. else
  1472. {
  1473. ReportError(EINVAL, "Could not change Builder value");
  1474. return -1;
  1475. }
  1476. } catch (const std::exception & e) {
  1477. return ReportException(e);
  1478. } catch (...) {
  1479. return ReportCaughtNonException();
  1480. }
  1481. }
  1482. void hdfsConfStrFree(char *val)
  1483. {
  1484. errno = 0;
  1485. free(val);
  1486. }
  1487. hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld) {
  1488. return doHdfsConnect(bld->overrideHost, bld->overridePort, bld->user, bld->config.GetOptions());
  1489. }
  1490. int hdfsConfGetStr(const char *key, char **val)
  1491. {
  1492. try
  1493. {
  1494. errno = 0;
  1495. hdfsBuilder builder;
  1496. return hdfsBuilderConfGetStr(&builder, key, val);
  1497. } catch (const std::exception & e) {
  1498. return ReportException(e);
  1499. } catch (...) {
  1500. return ReportCaughtNonException();
  1501. }
  1502. }
  1503. int hdfsConfGetInt(const char *key, int32_t *val)
  1504. {
  1505. try
  1506. {
  1507. errno = 0;
  1508. hdfsBuilder builder;
  1509. return hdfsBuilderConfGetInt(&builder, key, val);
  1510. } catch (const std::exception & e) {
  1511. return ReportException(e);
  1512. } catch (...) {
  1513. return ReportCaughtNonException();
  1514. }
  1515. }
  1516. //
  1517. // Extended builder interface
  1518. //
  1519. struct hdfsBuilder *hdfsNewBuilderFromDirectory(const char * configDirectory)
  1520. {
  1521. try
  1522. {
  1523. errno = 0;
  1524. return new struct hdfsBuilder(configDirectory);
  1525. } catch (const std::exception & e) {
  1526. ReportException(e);
  1527. return nullptr;
  1528. } catch (...) {
  1529. ReportCaughtNonException();
  1530. return nullptr;
  1531. }
  1532. }
  1533. int hdfsBuilderConfGetStr(struct hdfsBuilder *bld, const char *key,
  1534. char **val)
  1535. {
  1536. try
  1537. {
  1538. errno = 0;
  1539. optional<std::string> value = bld->config.Get(key);
  1540. if (value)
  1541. {
  1542. size_t len = value->length() + 1;
  1543. *val = static_cast<char *>(malloc(len));
  1544. strncpy(*val, value->c_str(), len);
  1545. }
  1546. else
  1547. {
  1548. *val = nullptr;
  1549. }
  1550. return 0;
  1551. } catch (const std::exception & e) {
  1552. return ReportException(e);
  1553. } catch (...) {
  1554. return ReportCaughtNonException();
  1555. }
  1556. }
  1557. // If we're running on a 32-bit platform, we might get 64-bit values that
  1558. // don't fit in an int, and int is specified by the java hdfs.h interface
  1559. bool isValidInt(int64_t value)
  1560. {
  1561. return (value >= std::numeric_limits<int>::min() &&
  1562. value <= std::numeric_limits<int>::max());
  1563. }
  1564. int hdfsBuilderConfGetInt(struct hdfsBuilder *bld, const char *key, int32_t *val)
  1565. {
  1566. try
  1567. {
  1568. errno = 0;
  1569. // Pull from default configuration
  1570. optional<int64_t> value = bld->config.GetInt(key);
  1571. if (value)
  1572. {
  1573. if (!isValidInt(*value)){
  1574. ReportError(EINVAL, "Builder value is not valid");
  1575. return -1;
  1576. }
  1577. *val = *value;
  1578. return 0;
  1579. }
  1580. // If not found, don't change val
  1581. ReportError(EINVAL, "Could not get Builder value");
  1582. return 0;
  1583. } catch (const std::exception & e) {
  1584. return ReportException(e);
  1585. } catch (...) {
  1586. return ReportCaughtNonException();
  1587. }
  1588. }
  1589. int hdfsBuilderConfGetLong(struct hdfsBuilder *bld, const char *key, int64_t *val)
  1590. {
  1591. try
  1592. {
  1593. errno = 0;
  1594. // Pull from default configuration
  1595. optional<int64_t> value = bld->config.GetInt(key);
  1596. if (value)
  1597. {
  1598. *val = *value;
  1599. return 0;
  1600. }
  1601. // If not found, don't change val
  1602. ReportError(EINVAL, "Could not get Builder value");
  1603. return 0;
  1604. } catch (const std::exception & e) {
  1605. return ReportException(e);
  1606. } catch (...) {
  1607. return ReportCaughtNonException();
  1608. }
  1609. }
  1610. /**
  1611. * Logging functions
  1612. **/
  1613. class CForwardingLogger : public LoggerInterface {
  1614. public:
  1615. CForwardingLogger() : callback_(nullptr) {};
  1616. // Converts LogMessage into LogData, a POD type,
  1617. // and invokes callback_ if it's not null.
  1618. void Write(const LogMessage& msg);
  1619. // pass in NULL to clear the hook
  1620. void SetCallback(void (*callback)(LogData*));
  1621. //return a copy, or null on failure.
  1622. static LogData *CopyLogData(const LogData*);
  1623. //free LogData allocated with CopyLogData
  1624. static void FreeLogData(LogData*);
  1625. private:
  1626. void (*callback_)(LogData*);
  1627. };
  1628. /**
  1629. * Plugin to forward message to a C function pointer
  1630. **/
  1631. void CForwardingLogger::Write(const LogMessage& msg) {
  1632. if(!callback_)
  1633. return;
  1634. const std::string text = msg.MsgString();
  1635. LogData data;
  1636. data.level = msg.level();
  1637. data.component = msg.component();
  1638. data.msg = text.c_str();
  1639. data.file_name = msg.file_name();
  1640. data.file_line = msg.file_line();
  1641. callback_(&data);
  1642. }
  1643. void CForwardingLogger::SetCallback(void (*callback)(LogData*)) {
  1644. callback_ = callback;
  1645. }
  1646. LogData *CForwardingLogger::CopyLogData(const LogData *orig) {
  1647. if(!orig)
  1648. return nullptr;
  1649. LogData *copy = (LogData*)malloc(sizeof(LogData));
  1650. if(!copy)
  1651. return nullptr;
  1652. copy->level = orig->level;
  1653. copy->component = orig->component;
  1654. if(orig->msg)
  1655. copy->msg = strdup(orig->msg);
  1656. copy->file_name = orig->file_name;
  1657. copy->file_line = orig->file_line;
  1658. return copy;
  1659. }
  1660. void CForwardingLogger::FreeLogData(LogData *data) {
  1661. if(!data)
  1662. return;
  1663. if(data->msg)
  1664. free((void*)data->msg);
  1665. // Inexpensive way to help catch use-after-free
  1666. memset(data, 0, sizeof(LogData));
  1667. free(data);
  1668. }
  1669. LogData *hdfsCopyLogData(LogData *data) {
  1670. return CForwardingLogger::CopyLogData(data);
  1671. }
  1672. void hdfsFreeLogData(LogData *data) {
  1673. CForwardingLogger::FreeLogData(data);
  1674. }
  1675. void hdfsSetLogFunction(void (*callback)(LogData*)) {
  1676. CForwardingLogger *logger = new CForwardingLogger();
  1677. logger->SetCallback(callback);
  1678. LogManager::SetLoggerImplementation(std::unique_ptr<LoggerInterface>(logger));
  1679. }
  1680. static bool IsLevelValid(int component) {
  1681. if(component < HDFSPP_LOG_LEVEL_TRACE || component > HDFSPP_LOG_LEVEL_ERROR)
  1682. return false;
  1683. return true;
  1684. }
  1685. // should use __builtin_popcnt as optimization on some platforms
  1686. static int popcnt(int val) {
  1687. int bits = sizeof(val) * 8;
  1688. int count = 0;
  1689. for(int i=0; i<bits; i++) {
  1690. if((val >> i) & 0x1)
  1691. count++;
  1692. }
  1693. return count;
  1694. }
  1695. static bool IsComponentValid(int component) {
  1696. if(component < HDFSPP_LOG_COMPONENT_UNKNOWN || component > HDFSPP_LOG_COMPONENT_FILESYSTEM)
  1697. return false;
  1698. if(popcnt(component) != 1)
  1699. return false;
  1700. return true;
  1701. }
  1702. int hdfsEnableLoggingForComponent(int component) {
  1703. errno = 0;
  1704. if(!IsComponentValid(component))
  1705. return -1;
  1706. LogManager::EnableLogForComponent(static_cast<LogSourceComponent>(component));
  1707. return 0;
  1708. }
  1709. int hdfsDisableLoggingForComponent(int component) {
  1710. errno = 0;
  1711. if(!IsComponentValid(component))
  1712. return -1;
  1713. LogManager::DisableLogForComponent(static_cast<LogSourceComponent>(component));
  1714. return 0;
  1715. }
  1716. int hdfsSetLoggingLevel(int level) {
  1717. errno = 0;
  1718. if(!IsLevelValid(level))
  1719. return -1;
  1720. LogManager::SetLogLevel(static_cast<LogLevel>(level));
  1721. return 0;
  1722. }