hdfs.cc 44 KB

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