hdfs.cc 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999
  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 <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 implementations 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. const auto filename = XPlatform::Utils::Basename(stat_info.path);
  688. file_info->mName = new char[filename.size() + 1];
  689. strncpy(file_info->mName, filename.c_str(), filename.size() + 1);
  690. /* the last modification time for the file in seconds */
  691. file_info->mLastMod = (tTime) stat_info.modification_time;
  692. /* the size of the file in bytes */
  693. file_info->mSize = (tOffset) stat_info.length;
  694. /* the count of replicas */
  695. file_info->mReplication = (short) stat_info.block_replication;
  696. /* the block size for the file */
  697. file_info->mBlockSize = (tOffset) stat_info.blocksize;
  698. /* the owner of the file */
  699. file_info->mOwner = new char[stat_info.owner.size() + 1];
  700. strncpy(file_info->mOwner, stat_info.owner.c_str(), stat_info.owner.size() + 1);
  701. /* the group associated with the file */
  702. file_info->mGroup = new char[stat_info.group.size() + 1];
  703. strncpy(file_info->mGroup, stat_info.group.c_str(), stat_info.group.size() + 1);
  704. /* the permissions associated with the file encoded as an octal number (0777)*/
  705. file_info->mPermissions = (short) stat_info.permissions;
  706. /* the last access time for the file in seconds since the epoch*/
  707. file_info->mLastAccess = stat_info.access_time;
  708. }
  709. LIBHDFS_C_API
  710. int hdfsExists(hdfsFS fs, const char *path) {
  711. try {
  712. errno = 0;
  713. if (!CheckSystem(fs)) {
  714. return -1;
  715. }
  716. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  717. if(!abs_path) {
  718. return -1;
  719. }
  720. hdfs::StatInfo stat_info;
  721. Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
  722. if (!stat.ok()) {
  723. return Error(stat);
  724. }
  725. return 0;
  726. } catch (const std::exception & e) {
  727. return ReportException(e);
  728. } catch (...) {
  729. return ReportCaughtNonException();
  730. }
  731. }
  732. LIBHDFS_C_API
  733. hdfsFileInfo *hdfsGetPathInfo(hdfsFS fs, const char* path) {
  734. try {
  735. errno = 0;
  736. if (!CheckSystem(fs)) {
  737. return nullptr;
  738. }
  739. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  740. if(!abs_path) {
  741. return nullptr;
  742. }
  743. hdfs::StatInfo stat_info;
  744. Status stat = fs->get_impl()->GetFileInfo(*abs_path, stat_info);
  745. if (!stat.ok()) {
  746. Error(stat);
  747. return nullptr;
  748. }
  749. hdfsFileInfo *file_info = new hdfsFileInfo[1];
  750. StatInfoToHdfsFileInfo(file_info, stat_info);
  751. return file_info;
  752. } catch (const std::exception & e) {
  753. ReportException(e);
  754. return nullptr;
  755. } catch (...) {
  756. ReportCaughtNonException();
  757. return nullptr;
  758. }
  759. }
  760. LIBHDFS_C_API
  761. hdfsFileInfo *hdfsListDirectory(hdfsFS fs, const char* path, int *numEntries) {
  762. try {
  763. errno = 0;
  764. if (!CheckSystem(fs)) {
  765. *numEntries = 0;
  766. return nullptr;
  767. }
  768. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  769. if(!abs_path) {
  770. return nullptr;
  771. }
  772. std::vector<StatInfo> stat_infos;
  773. Status stat = fs->get_impl()->GetListing(*abs_path, &stat_infos);
  774. if (!stat.ok()) {
  775. Error(stat);
  776. *numEntries = 0;
  777. return nullptr;
  778. }
  779. if(stat_infos.empty()){
  780. *numEntries = 0;
  781. return nullptr;
  782. }
  783. *numEntries = stat_infos.size();
  784. hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
  785. for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
  786. StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
  787. }
  788. return file_infos;
  789. } catch (const std::exception & e) {
  790. ReportException(e);
  791. *numEntries = 0;
  792. return nullptr;
  793. } catch (...) {
  794. ReportCaughtNonException();
  795. *numEntries = 0;
  796. return nullptr;
  797. }
  798. }
  799. LIBHDFS_C_API
  800. void hdfsFreeFileInfo(hdfsFileInfo *hdfsFileInfo, int numEntries)
  801. {
  802. errno = 0;
  803. int i;
  804. for (i = 0; i < numEntries; ++i) {
  805. delete[] hdfsFileInfo[i].mName;
  806. delete[] hdfsFileInfo[i].mOwner;
  807. delete[] hdfsFileInfo[i].mGroup;
  808. }
  809. delete[] hdfsFileInfo;
  810. }
  811. LIBHDFS_C_API
  812. int hdfsCreateDirectory(hdfsFS fs, const char* path) {
  813. try {
  814. errno = 0;
  815. if (!CheckSystem(fs)) {
  816. return -1;
  817. }
  818. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  819. if(!abs_path) {
  820. return -1;
  821. }
  822. Status stat;
  823. //Use default permissions and set true for creating all non-existant parent directories
  824. stat = fs->get_impl()->Mkdirs(*abs_path, FileSystem::GetDefaultPermissionMask(), true);
  825. if (!stat.ok()) {
  826. return Error(stat);
  827. }
  828. return 0;
  829. } catch (const std::exception & e) {
  830. return ReportException(e);
  831. } catch (...) {
  832. return ReportCaughtNonException();
  833. }
  834. }
  835. LIBHDFS_C_API
  836. int hdfsDelete(hdfsFS fs, const char* path, int recursive) {
  837. try {
  838. errno = 0;
  839. if (!CheckSystem(fs)) {
  840. return -1;
  841. }
  842. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  843. if(!abs_path) {
  844. return -1;
  845. }
  846. Status stat;
  847. stat = fs->get_impl()->Delete(*abs_path, recursive);
  848. if (!stat.ok()) {
  849. return Error(stat);
  850. }
  851. return 0;
  852. } catch (const std::exception & e) {
  853. return ReportException(e);
  854. } catch (...) {
  855. return ReportCaughtNonException();
  856. }
  857. }
  858. LIBHDFS_C_API
  859. int hdfsRename(hdfsFS fs, const char* oldPath, const char* newPath) {
  860. try {
  861. errno = 0;
  862. if (!CheckSystem(fs)) {
  863. return -1;
  864. }
  865. const optional<std::string> old_abs_path = getAbsolutePath(fs, oldPath);
  866. const optional<std::string> new_abs_path = getAbsolutePath(fs, newPath);
  867. if(!old_abs_path || !new_abs_path) {
  868. return -1;
  869. }
  870. Status stat;
  871. stat = fs->get_impl()->Rename(*old_abs_path, *new_abs_path);
  872. if (!stat.ok()) {
  873. return Error(stat);
  874. }
  875. return 0;
  876. } catch (const std::exception & e) {
  877. return ReportException(e);
  878. } catch (...) {
  879. return ReportCaughtNonException();
  880. }
  881. }
  882. LIBHDFS_C_API
  883. int hdfsChmod(hdfsFS fs, const char* path, short mode){
  884. try {
  885. errno = 0;
  886. if (!CheckSystem(fs)) {
  887. return -1;
  888. }
  889. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  890. if(!abs_path) {
  891. return -1;
  892. }
  893. Status stat = FileSystem::CheckValidPermissionMask(mode);
  894. if (!stat.ok()) {
  895. return Error(stat);
  896. }
  897. stat = fs->get_impl()->SetPermission(*abs_path, mode);
  898. if (!stat.ok()) {
  899. return Error(stat);
  900. }
  901. return 0;
  902. } catch (const std::exception & e) {
  903. return ReportException(e);
  904. } catch (...) {
  905. return ReportCaughtNonException();
  906. }
  907. }
  908. LIBHDFS_C_API
  909. int hdfsChown(hdfsFS fs, const char* path, const char *owner, const char *group){
  910. try {
  911. errno = 0;
  912. if (!CheckSystem(fs)) {
  913. return -1;
  914. }
  915. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  916. if(!abs_path) {
  917. return -1;
  918. }
  919. std::string own = (owner) ? owner : "";
  920. std::string grp = (group) ? group : "";
  921. Status stat;
  922. stat = fs->get_impl()->SetOwner(*abs_path, own, grp);
  923. if (!stat.ok()) {
  924. return Error(stat);
  925. }
  926. return 0;
  927. } catch (const std::exception & e) {
  928. return ReportException(e);
  929. } catch (...) {
  930. return ReportCaughtNonException();
  931. }
  932. }
  933. LIBHDFSPP_EXT_API
  934. hdfsFileInfo * hdfsFind(hdfsFS fs, const char* path, const char* name, uint32_t * numEntries){
  935. try {
  936. errno = 0;
  937. if (!CheckSystem(fs)) {
  938. *numEntries = 0;
  939. return nullptr;
  940. }
  941. std::vector<StatInfo> stat_infos;
  942. Status stat = fs->get_impl()->Find(path, name, hdfs::FileSystem::GetDefaultFindMaxDepth(), &stat_infos);
  943. if (!stat.ok()) {
  944. Error(stat);
  945. *numEntries = 0;
  946. return nullptr;
  947. }
  948. //Existing API expects nullptr if size is 0
  949. if(stat_infos.empty()){
  950. *numEntries = 0;
  951. return nullptr;
  952. }
  953. *numEntries = stat_infos.size();
  954. hdfsFileInfo *file_infos = new hdfsFileInfo[stat_infos.size()];
  955. for(std::vector<StatInfo>::size_type i = 0; i < stat_infos.size(); i++) {
  956. StatInfoToHdfsFileInfo(&file_infos[i], stat_infos.at(i));
  957. }
  958. return file_infos;
  959. } catch (const std::exception & e) {
  960. ReportException(e);
  961. *numEntries = 0;
  962. return nullptr;
  963. } catch (...) {
  964. ReportCaughtNonException();
  965. *numEntries = 0;
  966. return nullptr;
  967. }
  968. }
  969. LIBHDFSPP_EXT_API
  970. int hdfsCreateSnapshot(hdfsFS fs, const char* path, const char* name) {
  971. try {
  972. errno = 0;
  973. if (!CheckSystem(fs)) {
  974. return -1;
  975. }
  976. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  977. if(!abs_path) {
  978. return -1;
  979. }
  980. Status stat;
  981. if(!name){
  982. stat = fs->get_impl()->CreateSnapshot(*abs_path, "");
  983. } else {
  984. stat = fs->get_impl()->CreateSnapshot(*abs_path, name);
  985. }
  986. if (!stat.ok()) {
  987. return Error(stat);
  988. }
  989. return 0;
  990. } catch (const std::exception & e) {
  991. return ReportException(e);
  992. } catch (...) {
  993. return ReportCaughtNonException();
  994. }
  995. }
  996. LIBHDFSPP_EXT_API
  997. int hdfsDeleteSnapshot(hdfsFS fs, const char* path, const char* name) {
  998. try {
  999. errno = 0;
  1000. if (!CheckSystem(fs)) {
  1001. return -1;
  1002. }
  1003. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1004. if(!abs_path) {
  1005. return -1;
  1006. }
  1007. if (!name) {
  1008. return Error(Status::InvalidArgument("hdfsDeleteSnapshot: argument 'name' cannot be NULL"));
  1009. }
  1010. Status stat;
  1011. stat = fs->get_impl()->DeleteSnapshot(*abs_path, name);
  1012. if (!stat.ok()) {
  1013. return Error(stat);
  1014. }
  1015. return 0;
  1016. } catch (const std::exception & e) {
  1017. return ReportException(e);
  1018. } catch (...) {
  1019. return ReportCaughtNonException();
  1020. }
  1021. }
  1022. int hdfsRenameSnapshot(hdfsFS fs, const char* path, const char* old_name, const char* new_name) {
  1023. try {
  1024. errno = 0;
  1025. if (!CheckSystem(fs)) {
  1026. return -1;
  1027. }
  1028. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1029. if(!abs_path) {
  1030. return -1;
  1031. }
  1032. if (!old_name) {
  1033. return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'old_name' cannot be NULL"));
  1034. }
  1035. if (!new_name) {
  1036. return Error(Status::InvalidArgument("hdfsRenameSnapshot: argument 'new_name' cannot be NULL"));
  1037. }
  1038. Status stat;
  1039. stat = fs->get_impl()->RenameSnapshot(*abs_path, old_name, new_name);
  1040. if (!stat.ok()) {
  1041. return Error(stat);
  1042. }
  1043. return 0;
  1044. } catch (const std::exception & e) {
  1045. return ReportException(e);
  1046. } catch (...) {
  1047. return ReportCaughtNonException();
  1048. }
  1049. }
  1050. LIBHDFSPP_EXT_API
  1051. int hdfsAllowSnapshot(hdfsFS fs, const char* path) {
  1052. try {
  1053. errno = 0;
  1054. if (!CheckSystem(fs)) {
  1055. return -1;
  1056. }
  1057. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1058. if(!abs_path) {
  1059. return -1;
  1060. }
  1061. Status stat;
  1062. stat = fs->get_impl()->AllowSnapshot(*abs_path);
  1063. if (!stat.ok()) {
  1064. return Error(stat);
  1065. }
  1066. return 0;
  1067. } catch (const std::exception & e) {
  1068. return ReportException(e);
  1069. } catch (...) {
  1070. return ReportCaughtNonException();
  1071. }
  1072. }
  1073. LIBHDFSPP_EXT_API
  1074. int hdfsDisallowSnapshot(hdfsFS fs, const char* path) {
  1075. try {
  1076. errno = 0;
  1077. if (!CheckSystem(fs)) {
  1078. return -1;
  1079. }
  1080. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1081. if(!abs_path) {
  1082. return -1;
  1083. }
  1084. Status stat;
  1085. stat = fs->get_impl()->DisallowSnapshot(*abs_path);
  1086. if (!stat.ok()) {
  1087. return Error(stat);
  1088. }
  1089. return 0;
  1090. } catch (const std::exception & e) {
  1091. return ReportException(e);
  1092. } catch (...) {
  1093. return ReportCaughtNonException();
  1094. }
  1095. }
  1096. LIBHDFS_C_API
  1097. tSize hdfsPread(hdfsFS fs, hdfsFile file, tOffset position, void *buffer,
  1098. tSize length) {
  1099. try
  1100. {
  1101. errno = 0;
  1102. if (!CheckSystemAndHandle(fs, file)) {
  1103. return -1;
  1104. }
  1105. size_t len = 0;
  1106. Status stat = file->get_impl()->PositionRead(buffer, length, position, &len);
  1107. if(!stat.ok()) {
  1108. return Error(stat);
  1109. }
  1110. return (tSize)len;
  1111. } catch (const std::exception & e) {
  1112. return ReportException(e);
  1113. } catch (...) {
  1114. return ReportCaughtNonException();
  1115. }
  1116. }
  1117. LIBHDFS_C_API
  1118. tSize hdfsRead(hdfsFS fs, hdfsFile file, void *buffer, tSize length) {
  1119. try
  1120. {
  1121. errno = 0;
  1122. if (!CheckSystemAndHandle(fs, file)) {
  1123. return -1;
  1124. }
  1125. size_t len = 0;
  1126. Status stat = file->get_impl()->Read(buffer, length, &len);
  1127. if (!stat.ok()) {
  1128. return Error(stat);
  1129. }
  1130. return (tSize)len;
  1131. } catch (const std::exception & e) {
  1132. return ReportException(e);
  1133. } catch (...) {
  1134. return ReportCaughtNonException();
  1135. }
  1136. }
  1137. LIBHDFS_C_API
  1138. int hdfsUnbufferFile(hdfsFile file) {
  1139. //Currently we are not doing any buffering
  1140. CheckHandle(file);
  1141. return -1;
  1142. }
  1143. LIBHDFS_C_API
  1144. int hdfsFileGetReadStatistics(hdfsFile file, struct hdfsReadStatistics **stats) {
  1145. try
  1146. {
  1147. errno = 0;
  1148. if (!CheckHandle(file)) {
  1149. return -1;
  1150. }
  1151. *stats = new hdfsReadStatistics;
  1152. memset(*stats, 0, sizeof(hdfsReadStatistics));
  1153. (*stats)->totalBytesRead = file->get_impl()->get_bytes_read();
  1154. return 0;
  1155. } catch (const std::exception & e) {
  1156. return ReportException(e);
  1157. } catch (...) {
  1158. return ReportCaughtNonException();
  1159. }
  1160. }
  1161. LIBHDFS_C_API
  1162. int hdfsFileClearReadStatistics(hdfsFile file) {
  1163. try
  1164. {
  1165. errno = 0;
  1166. if (!CheckHandle(file)) {
  1167. return -1;
  1168. }
  1169. file->get_impl()->clear_bytes_read();
  1170. return 0;
  1171. } catch (const std::exception & e) {
  1172. return ReportException(e);
  1173. } catch (...) {
  1174. return ReportCaughtNonException();
  1175. }
  1176. }
  1177. LIBHDFS_C_API
  1178. int64_t hdfsReadStatisticsGetRemoteBytesRead(const struct hdfsReadStatistics *stats) {
  1179. return stats->totalBytesRead - stats->totalLocalBytesRead;
  1180. }
  1181. LIBHDFS_C_API
  1182. void hdfsFileFreeReadStatistics(struct hdfsReadStatistics *stats) {
  1183. errno = 0;
  1184. delete stats;
  1185. }
  1186. /* 0 on success, -1 on error*/
  1187. LIBHDFS_C_API
  1188. int hdfsSeek(hdfsFS fs, hdfsFile file, tOffset desiredPos) {
  1189. try
  1190. {
  1191. errno = 0;
  1192. if (!CheckSystemAndHandle(fs, file)) {
  1193. return -1;
  1194. }
  1195. off_t desired = desiredPos;
  1196. Status stat = file->get_impl()->Seek(&desired, std::ios_base::beg);
  1197. if (!stat.ok()) {
  1198. return Error(stat);
  1199. }
  1200. return 0;
  1201. } catch (const std::exception & e) {
  1202. return ReportException(e);
  1203. } catch (...) {
  1204. return ReportCaughtNonException();
  1205. }
  1206. }
  1207. LIBHDFS_C_API
  1208. tOffset hdfsTell(hdfsFS fs, hdfsFile file) {
  1209. try
  1210. {
  1211. errno = 0;
  1212. if (!CheckSystemAndHandle(fs, file)) {
  1213. return -1;
  1214. }
  1215. off_t offset = 0;
  1216. Status stat = file->get_impl()->Seek(&offset, std::ios_base::cur);
  1217. if (!stat.ok()) {
  1218. return Error(stat);
  1219. }
  1220. return (tOffset)offset;
  1221. } catch (const std::exception & e) {
  1222. return ReportException(e);
  1223. } catch (...) {
  1224. return ReportCaughtNonException();
  1225. }
  1226. }
  1227. /* extended API */
  1228. int hdfsCancel(hdfsFS fs, hdfsFile file) {
  1229. try
  1230. {
  1231. errno = 0;
  1232. if (!CheckSystemAndHandle(fs, file)) {
  1233. return -1;
  1234. }
  1235. static_cast<FileHandleImpl*>(file->get_impl())->CancelOperations();
  1236. return 0;
  1237. } catch (const std::exception & e) {
  1238. return ReportException(e);
  1239. } catch (...) {
  1240. return ReportCaughtNonException();
  1241. }
  1242. }
  1243. LIBHDFSPP_EXT_API
  1244. int hdfsGetBlockLocations(hdfsFS fs, const char *path, struct hdfsBlockLocations ** locations_out)
  1245. {
  1246. try
  1247. {
  1248. errno = 0;
  1249. if (!CheckSystem(fs)) {
  1250. return -1;
  1251. }
  1252. if (locations_out == nullptr) {
  1253. ReportError(EINVAL, "Null pointer passed to hdfsGetBlockLocations");
  1254. return -1;
  1255. }
  1256. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1257. if(!abs_path) {
  1258. return -1;
  1259. }
  1260. std::shared_ptr<FileBlockLocation> ppLocations;
  1261. Status stat = fs->get_impl()->GetBlockLocations(*abs_path, 0, std::numeric_limits<int64_t>::max(), &ppLocations);
  1262. if (!stat.ok()) {
  1263. return Error(stat);
  1264. }
  1265. hdfsBlockLocations *locations = new struct hdfsBlockLocations();
  1266. (*locations_out) = locations;
  1267. explicit_bzero(locations, sizeof(*locations));
  1268. locations->fileLength = ppLocations->getFileLength();
  1269. locations->isLastBlockComplete = ppLocations->isLastBlockComplete();
  1270. locations->isUnderConstruction = ppLocations->isUnderConstruction();
  1271. const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
  1272. locations->num_blocks = ppBlockLocations.size();
  1273. locations->blocks = new struct hdfsBlockInfo[locations->num_blocks];
  1274. for (size_t i=0; i < ppBlockLocations.size(); i++) {
  1275. auto ppBlockLocation = ppBlockLocations[i];
  1276. auto block = &locations->blocks[i];
  1277. block->num_bytes = ppBlockLocation.getLength();
  1278. block->start_offset = ppBlockLocation.getOffset();
  1279. const std::vector<DNInfo> & ppDNInfos = ppBlockLocation.getDataNodes();
  1280. block->num_locations = ppDNInfos.size();
  1281. block->locations = new hdfsDNInfo[block->num_locations];
  1282. for (size_t j=0; j < block->num_locations; j++) {
  1283. auto ppDNInfo = ppDNInfos[j];
  1284. auto dn_info = &block->locations[j];
  1285. dn_info->xfer_port = ppDNInfo.getXferPort();
  1286. dn_info->info_port = ppDNInfo.getInfoPort();
  1287. dn_info->IPC_port = ppDNInfo.getIPCPort();
  1288. dn_info->info_secure_port = ppDNInfo.getInfoSecurePort();
  1289. char * buf;
  1290. buf = new char[ppDNInfo.getHostname().size() + 1];
  1291. strncpy(buf, ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
  1292. dn_info->hostname = buf;
  1293. buf = new char[ppDNInfo.getIPAddr().size() + 1];
  1294. strncpy(buf, ppDNInfo.getIPAddr().c_str(), ppDNInfo.getIPAddr().size() + 1);
  1295. dn_info->ip_address = buf;
  1296. buf = new char[ppDNInfo.getNetworkLocation().size() + 1];
  1297. strncpy(buf, ppDNInfo.getNetworkLocation().c_str(), ppDNInfo.getNetworkLocation().size() + 1);
  1298. dn_info->network_location = buf;
  1299. }
  1300. }
  1301. return 0;
  1302. } catch (const std::exception & e) {
  1303. return ReportException(e);
  1304. } catch (...) {
  1305. return ReportCaughtNonException();
  1306. }
  1307. }
  1308. LIBHDFSPP_EXT_API
  1309. int hdfsFreeBlockLocations(struct hdfsBlockLocations * blockLocations) {
  1310. errno = 0;
  1311. if (blockLocations == nullptr)
  1312. return 0;
  1313. for (size_t i=0; i < blockLocations->num_blocks; i++) {
  1314. auto block = &blockLocations->blocks[i];
  1315. for (size_t j=0; j < block->num_locations; j++) {
  1316. auto location = &block->locations[j];
  1317. delete[] location->hostname;
  1318. delete[] location->ip_address;
  1319. delete[] location->network_location;
  1320. }
  1321. }
  1322. delete[] blockLocations->blocks;
  1323. delete blockLocations;
  1324. return 0;
  1325. }
  1326. LIBHDFS_C_API
  1327. char*** hdfsGetHosts(hdfsFS fs, const char* path, tOffset start, tOffset length) {
  1328. try
  1329. {
  1330. errno = 0;
  1331. if (!CheckSystem(fs)) {
  1332. return nullptr;
  1333. }
  1334. const optional<std::string> abs_path = getAbsolutePath(fs, path);
  1335. if(!abs_path) {
  1336. return nullptr;
  1337. }
  1338. std::shared_ptr<FileBlockLocation> ppLocations;
  1339. Status stat = fs->get_impl()->GetBlockLocations(*abs_path, start, length, &ppLocations);
  1340. if (!stat.ok()) {
  1341. Error(stat);
  1342. return nullptr;
  1343. }
  1344. const std::vector<BlockLocation> & ppBlockLocations = ppLocations->getBlockLocations();
  1345. char ***hosts = new char**[ppBlockLocations.size() + 1];
  1346. for (size_t i=0; i < ppBlockLocations.size(); i++) {
  1347. const std::vector<DNInfo> & ppDNInfos = ppBlockLocations[i].getDataNodes();
  1348. hosts[i] = new char*[ppDNInfos.size() + 1];
  1349. for (size_t j=0; j < ppDNInfos.size(); j++) {
  1350. auto ppDNInfo = ppDNInfos[j];
  1351. hosts[i][j] = new char[ppDNInfo.getHostname().size() + 1];
  1352. strncpy(hosts[i][j], ppDNInfo.getHostname().c_str(), ppDNInfo.getHostname().size() + 1);
  1353. }
  1354. hosts[i][ppDNInfos.size()] = nullptr;
  1355. }
  1356. hosts[ppBlockLocations.size()] = nullptr;
  1357. return hosts;
  1358. } catch (const std::exception & e) {
  1359. ReportException(e);
  1360. return nullptr;
  1361. } catch (...) {
  1362. ReportCaughtNonException();
  1363. return nullptr;
  1364. }
  1365. }
  1366. LIBHDFS_C_API
  1367. void hdfsFreeHosts(char ***blockHosts) {
  1368. errno = 0;
  1369. if (blockHosts == nullptr)
  1370. return;
  1371. for (size_t i = 0; blockHosts[i]; i++) {
  1372. for (size_t j = 0; blockHosts[i][j]; j++) {
  1373. delete[] blockHosts[i][j];
  1374. }
  1375. delete[] blockHosts[i];
  1376. }
  1377. delete blockHosts;
  1378. }
  1379. /*******************************************************************
  1380. * EVENT CALLBACKS
  1381. *******************************************************************/
  1382. const char * FS_NN_CONNECT_EVENT = hdfs::FS_NN_CONNECT_EVENT;
  1383. const char * FS_NN_READ_EVENT = hdfs::FS_NN_READ_EVENT;
  1384. const char * FS_NN_WRITE_EVENT = hdfs::FS_NN_WRITE_EVENT;
  1385. const char * FILE_DN_CONNECT_EVENT = hdfs::FILE_DN_CONNECT_EVENT;
  1386. const char * FILE_DN_READ_EVENT = hdfs::FILE_DN_READ_EVENT;
  1387. const char * FILE_DN_WRITE_EVENT = hdfs::FILE_DN_WRITE_EVENT;
  1388. event_response fs_callback_glue(libhdfspp_fs_event_callback handler,
  1389. int64_t cookie,
  1390. const char * event,
  1391. const char * cluster,
  1392. int64_t value) {
  1393. int result = handler(event, cluster, value, cookie);
  1394. if (result == LIBHDFSPP_EVENT_OK) {
  1395. return event_response::make_ok();
  1396. }
  1397. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  1398. if (result == DEBUG_SIMULATE_ERROR) {
  1399. return event_response::test_err(Status::Error("Simulated error"));
  1400. }
  1401. #endif
  1402. return event_response::make_ok();
  1403. }
  1404. event_response file_callback_glue(libhdfspp_file_event_callback handler,
  1405. int64_t cookie,
  1406. const char * event,
  1407. const char * cluster,
  1408. const char * file,
  1409. int64_t value) {
  1410. int result = handler(event, cluster, file, value, cookie);
  1411. if (result == LIBHDFSPP_EVENT_OK) {
  1412. return event_response::make_ok();
  1413. }
  1414. #ifndef LIBHDFSPP_SIMULATE_ERROR_DISABLED
  1415. if (result == DEBUG_SIMULATE_ERROR) {
  1416. return event_response::test_err(Status::Error("Simulated error"));
  1417. }
  1418. #endif
  1419. return event_response::make_ok();
  1420. }
  1421. LIBHDFSPP_EXT_API
  1422. int hdfsPreAttachFSMonitor(libhdfspp_fs_event_callback handler, int64_t cookie)
  1423. {
  1424. fs_event_callback callback = std::bind(fs_callback_glue, handler, cookie, _1, _2, _3);
  1425. fsEventCallback = callback;
  1426. return 0;
  1427. }
  1428. LIBHDFSPP_EXT_API
  1429. int hdfsPreAttachFileMonitor(libhdfspp_file_event_callback handler, int64_t cookie)
  1430. {
  1431. file_event_callback callback = std::bind(file_callback_glue, handler, cookie, _1, _2, _3, _4);
  1432. fileEventCallback = callback;
  1433. return 0;
  1434. }
  1435. /*******************************************************************
  1436. * BUILDER INTERFACE
  1437. *******************************************************************/
  1438. HdfsConfiguration LoadDefault(ConfigurationLoader & loader)
  1439. {
  1440. optional<HdfsConfiguration> result = loader.LoadDefaultResources<HdfsConfiguration>();
  1441. if (result)
  1442. {
  1443. return result.value();
  1444. }
  1445. else
  1446. {
  1447. return loader.NewConfig<HdfsConfiguration>();
  1448. }
  1449. }
  1450. hdfsBuilder::hdfsBuilder() : config(loader.NewConfig<HdfsConfiguration>())
  1451. {
  1452. errno = 0;
  1453. config = LoadDefault(loader);
  1454. }
  1455. hdfsBuilder::hdfsBuilder(const char * directory) :
  1456. config(loader.NewConfig<HdfsConfiguration>())
  1457. {
  1458. errno = 0;
  1459. loader.SetSearchPath(directory);
  1460. config = LoadDefault(loader);
  1461. }
  1462. LIBHDFS_C_API
  1463. struct hdfsBuilder *hdfsNewBuilder(void)
  1464. {
  1465. try
  1466. {
  1467. errno = 0;
  1468. return new struct hdfsBuilder();
  1469. } catch (const std::exception & e) {
  1470. ReportException(e);
  1471. return nullptr;
  1472. } catch (...) {
  1473. ReportCaughtNonException();
  1474. return nullptr;
  1475. }
  1476. }
  1477. LIBHDFS_C_API
  1478. void hdfsBuilderSetNameNode(struct hdfsBuilder *bld, const char *nn)
  1479. {
  1480. errno = 0;
  1481. bld->overrideHost = std::string(nn);
  1482. }
  1483. LIBHDFS_C_API
  1484. void hdfsBuilderSetNameNodePort(struct hdfsBuilder *bld, tPort port)
  1485. {
  1486. errno = 0;
  1487. bld->overridePort = port;
  1488. }
  1489. LIBHDFS_C_API
  1490. void hdfsBuilderSetUserName(struct hdfsBuilder *bld, const char *userName)
  1491. {
  1492. errno = 0;
  1493. if (userName && *userName) {
  1494. bld->user = std::string(userName);
  1495. }
  1496. }
  1497. LIBHDFS_C_API
  1498. void hdfsBuilderSetForceNewInstance(struct hdfsBuilder *bld) {
  1499. //libhdfspp always returns a new instance, so nothing to do
  1500. (void)bld;
  1501. errno = 0;
  1502. }
  1503. LIBHDFS_C_API
  1504. void hdfsFreeBuilder(struct hdfsBuilder *bld)
  1505. {
  1506. try
  1507. {
  1508. errno = 0;
  1509. delete bld;
  1510. } catch (const std::exception & e) {
  1511. ReportException(e);
  1512. } catch (...) {
  1513. ReportCaughtNonException();
  1514. }
  1515. }
  1516. LIBHDFS_C_API
  1517. int hdfsBuilderConfSetStr(struct hdfsBuilder *bld, const char *key,
  1518. const char *val)
  1519. {
  1520. try
  1521. {
  1522. errno = 0;
  1523. optional<HdfsConfiguration> newConfig = bld->loader.OverlayValue(bld->config, key, val);
  1524. if (newConfig)
  1525. {
  1526. bld->config = newConfig.value();
  1527. return 0;
  1528. }
  1529. else
  1530. {
  1531. ReportError(EINVAL, "Could not change Builder value");
  1532. return -1;
  1533. }
  1534. } catch (const std::exception & e) {
  1535. return ReportException(e);
  1536. } catch (...) {
  1537. return ReportCaughtNonException();
  1538. }
  1539. }
  1540. LIBHDFS_C_API
  1541. void hdfsConfStrFree(char *val)
  1542. {
  1543. errno = 0;
  1544. free(val);
  1545. }
  1546. LIBHDFS_C_API
  1547. hdfsFS hdfsBuilderConnect(struct hdfsBuilder *bld) {
  1548. hdfsFS fs = doHdfsConnect(bld->overrideHost, bld->overridePort, bld->user, bld->config.GetOptions());
  1549. // Always free the builder
  1550. hdfsFreeBuilder(bld);
  1551. return fs;
  1552. }
  1553. LIBHDFS_C_API
  1554. int hdfsConfGetStr(const char *key, char **val)
  1555. {
  1556. try
  1557. {
  1558. errno = 0;
  1559. hdfsBuilder builder;
  1560. return hdfsBuilderConfGetStr(&builder, key, val);
  1561. } catch (const std::exception & e) {
  1562. return ReportException(e);
  1563. } catch (...) {
  1564. return ReportCaughtNonException();
  1565. }
  1566. }
  1567. LIBHDFS_C_API
  1568. int hdfsConfGetInt(const char *key, int32_t *val)
  1569. {
  1570. try
  1571. {
  1572. errno = 0;
  1573. hdfsBuilder builder;
  1574. return hdfsBuilderConfGetInt(&builder, key, val);
  1575. } catch (const std::exception & e) {
  1576. return ReportException(e);
  1577. } catch (...) {
  1578. return ReportCaughtNonException();
  1579. }
  1580. }
  1581. //
  1582. // Extended builder interface
  1583. //
  1584. struct hdfsBuilder *hdfsNewBuilderFromDirectory(const char * configDirectory)
  1585. {
  1586. try
  1587. {
  1588. errno = 0;
  1589. return new struct hdfsBuilder(configDirectory);
  1590. } catch (const std::exception & e) {
  1591. ReportException(e);
  1592. return nullptr;
  1593. } catch (...) {
  1594. ReportCaughtNonException();
  1595. return nullptr;
  1596. }
  1597. }
  1598. LIBHDFSPP_EXT_API
  1599. int hdfsBuilderConfGetStr(struct hdfsBuilder *bld, const char *key,
  1600. char **val)
  1601. {
  1602. try
  1603. {
  1604. errno = 0;
  1605. optional<std::string> value = bld->config.Get(key);
  1606. if (value)
  1607. {
  1608. size_t len = value->length() + 1;
  1609. *val = static_cast<char *>(malloc(len));
  1610. strncpy(*val, value->c_str(), len);
  1611. }
  1612. else
  1613. {
  1614. *val = nullptr;
  1615. }
  1616. return 0;
  1617. } catch (const std::exception & e) {
  1618. return ReportException(e);
  1619. } catch (...) {
  1620. return ReportCaughtNonException();
  1621. }
  1622. }
  1623. // If we're running on a 32-bit platform, we might get 64-bit values that
  1624. // don't fit in an int, and int is specified by the java hdfs.h interface
  1625. bool isValidInt(int64_t value)
  1626. {
  1627. return (value >= std::numeric_limits<int>::min() &&
  1628. value <= std::numeric_limits<int>::max());
  1629. }
  1630. LIBHDFSPP_EXT_API
  1631. int hdfsBuilderConfGetInt(struct hdfsBuilder *bld, const char *key, int32_t *val)
  1632. {
  1633. try
  1634. {
  1635. errno = 0;
  1636. // Pull from default configuration
  1637. optional<int64_t> value = bld->config.GetInt(key);
  1638. if (value)
  1639. {
  1640. if (!isValidInt(*value)){
  1641. ReportError(EINVAL, "Builder value is not valid");
  1642. return -1;
  1643. }
  1644. *val = *value;
  1645. return 0;
  1646. }
  1647. // If not found, don't change val
  1648. ReportError(EINVAL, "Could not get Builder value");
  1649. return 0;
  1650. } catch (const std::exception & e) {
  1651. return ReportException(e);
  1652. } catch (...) {
  1653. return ReportCaughtNonException();
  1654. }
  1655. }
  1656. LIBHDFSPP_EXT_API
  1657. int hdfsBuilderConfGetLong(struct hdfsBuilder *bld, const char *key, int64_t *val)
  1658. {
  1659. try
  1660. {
  1661. errno = 0;
  1662. // Pull from default configuration
  1663. optional<int64_t> value = bld->config.GetInt(key);
  1664. if (value)
  1665. {
  1666. *val = *value;
  1667. return 0;
  1668. }
  1669. // If not found, don't change val
  1670. ReportError(EINVAL, "Could not get Builder value");
  1671. return 0;
  1672. } catch (const std::exception & e) {
  1673. return ReportException(e);
  1674. } catch (...) {
  1675. return ReportCaughtNonException();
  1676. }
  1677. }
  1678. /**
  1679. * Logging functions
  1680. **/
  1681. class CForwardingLogger : public LoggerInterface {
  1682. public:
  1683. CForwardingLogger() : callback_(nullptr) {};
  1684. // Converts LogMessage into LogData, a POD type,
  1685. // and invokes callback_ if it's not null.
  1686. void Write(const LogMessage& msg);
  1687. // pass in NULL to clear the hook
  1688. void SetCallback(void (*callback)(LogData*));
  1689. //return a copy, or null on failure.
  1690. static LogData *CopyLogData(const LogData*);
  1691. //free LogData allocated with CopyLogData
  1692. static void FreeLogData(LogData*);
  1693. private:
  1694. void (*callback_)(LogData*);
  1695. };
  1696. /**
  1697. * Plugin to forward message to a C function pointer
  1698. **/
  1699. void CForwardingLogger::Write(const LogMessage& msg) {
  1700. if(!callback_)
  1701. return;
  1702. const std::string text = msg.MsgString();
  1703. LogData data;
  1704. data.level = msg.level();
  1705. data.component = msg.component();
  1706. data.msg = text.c_str();
  1707. data.file_name = msg.file_name();
  1708. data.file_line = msg.file_line();
  1709. callback_(&data);
  1710. }
  1711. void CForwardingLogger::SetCallback(void (*callback)(LogData*)) {
  1712. callback_ = callback;
  1713. }
  1714. LogData *CForwardingLogger::CopyLogData(const LogData *orig) {
  1715. if(!orig)
  1716. return nullptr;
  1717. LogData *copy = (LogData*)malloc(sizeof(LogData));
  1718. if(!copy)
  1719. return nullptr;
  1720. copy->level = orig->level;
  1721. copy->component = orig->component;
  1722. if(orig->msg)
  1723. copy->msg = strdup(orig->msg);
  1724. copy->file_name = orig->file_name;
  1725. copy->file_line = orig->file_line;
  1726. return copy;
  1727. }
  1728. void CForwardingLogger::FreeLogData(LogData *data) {
  1729. if(!data)
  1730. return;
  1731. if(data->msg)
  1732. free((void*)data->msg);
  1733. // Inexpensive way to help catch use-after-free
  1734. memset(data, 0, sizeof(LogData));
  1735. free(data);
  1736. }
  1737. LIBHDFSPP_EXT_API
  1738. LogData *hdfsCopyLogData(LogData *data) {
  1739. return CForwardingLogger::CopyLogData(data);
  1740. }
  1741. LIBHDFSPP_EXT_API
  1742. void hdfsFreeLogData(LogData *data) {
  1743. CForwardingLogger::FreeLogData(data);
  1744. }
  1745. LIBHDFSPP_EXT_API
  1746. void hdfsSetLogFunction(void (*callback)(LogData*)) {
  1747. CForwardingLogger *logger = new CForwardingLogger();
  1748. logger->SetCallback(callback);
  1749. LogManager::SetLoggerImplementation(std::unique_ptr<LoggerInterface>(logger));
  1750. }
  1751. static bool IsLevelValid(int component) {
  1752. if(component < HDFSPP_LOG_LEVEL_TRACE || component > HDFSPP_LOG_LEVEL_ERROR)
  1753. return false;
  1754. return true;
  1755. }
  1756. // should use __builtin_popcnt as optimization on some platforms
  1757. static int popcnt(int val) {
  1758. int bits = sizeof(val) * 8;
  1759. int count = 0;
  1760. for(int i=0; i<bits; i++) {
  1761. if((val >> i) & 0x1)
  1762. count++;
  1763. }
  1764. return count;
  1765. }
  1766. static bool IsComponentValid(int component) {
  1767. if(component < HDFSPP_LOG_COMPONENT_UNKNOWN || component > HDFSPP_LOG_COMPONENT_FILESYSTEM)
  1768. return false;
  1769. if(popcnt(component) != 1)
  1770. return false;
  1771. return true;
  1772. }
  1773. LIBHDFSPP_EXT_API
  1774. int hdfsEnableLoggingForComponent(int component) {
  1775. errno = 0;
  1776. if(!IsComponentValid(component))
  1777. return -1;
  1778. LogManager::EnableLogForComponent(static_cast<LogSourceComponent>(component));
  1779. return 0;
  1780. }
  1781. LIBHDFSPP_EXT_API
  1782. int hdfsDisableLoggingForComponent(int component) {
  1783. errno = 0;
  1784. if(!IsComponentValid(component))
  1785. return -1;
  1786. LogManager::DisableLogForComponent(static_cast<LogSourceComponent>(component));
  1787. return 0;
  1788. }
  1789. LIBHDFSPP_EXT_API
  1790. int hdfsSetLoggingLevel(int level) {
  1791. errno = 0;
  1792. if(!IsLevelValid(level))
  1793. return -1;
  1794. LogManager::SetLogLevel(static_cast<LogLevel>(level));
  1795. return 0;
  1796. }
  1797. #undef LIBHDFS_C_API
  1798. #undef LIBHDFSPP_EXT_API