hdfs.cc 49 KB

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