1
0

hdfs.cc 50 KB

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