hdfs.cc 50 KB

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